repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
mkitzan/atlas | test/atlas_math_solvers.cpp | #include <atlas/core/Float.hpp>
#include <atlas/math/Solvers.hpp>
#include <catch2/catch.hpp>
using namespace atlas::math;
using atlas::core::areEqual;
TEST_CASE("Testing quadratic solver", "[math]")
{
// x^2 - 1 = 0.
// Two roots: 1, -1.
{
std::vector<double> coefficients{1.0, 0.0, -1.0};
std::vector<double> roots;
auto numRoots = solveQuadratic(coefficients, roots);
REQUIRE(numRoots == 2);
REQUIRE(areEqual(roots[0], 1.0));
REQUIRE(areEqual(roots[1], -1.0));
}
// x^2 - 2x + 1.
// One root: 1.
{
std::vector<double> coefficients{1.0, -2.0, 1.0};
std::vector<double> roots;
auto numRoots = solveQuadratic(coefficients, roots);
REQUIRE(numRoots == 1);
REQUIRE(areEqual(roots[0], 1.0));
}
// x^2 + 1.
// No real roots.
{
std::vector<double> coefficients{1.0, 0.0, 1.0};
std::vector<double> roots;
auto numRoots = solveQuadratic(coefficients, roots);
REQUIRE(numRoots == 0);
}
}
TEST_CASE("Testing cubic solver", "[math]")
{
// -6 + 11x -6x^2 + x^3.
// 3 roots: 1, 2, 3.
{
std::vector<double> coefficients{-6.0, 11.0, -6.0, 1.0};
std::vector<double> roots;
auto numRoots = solveCubic(coefficients, roots);
REQUIRE(numRoots == 3);
REQUIRE(areEqual(roots[0], 3.0));
REQUIRE(areEqual(roots[1], 2.0));
REQUIRE(areEqual(roots[2], 1.0));
}
// -x^2 + x^3.
// 2 roots.
{
std::vector<double> coefficients{0.0, 0.0, -1.0, 1.0};
std::vector<double> roots;
auto numRoots = solveCubic(coefficients, roots);
REQUIRE(numRoots == 2);
REQUIRE(areEqual(roots[0], 1.0));
REQUIRE(areEqual(roots[1], 0.0));
}
// -1 + x^3
// 1 real root, two complex.
{
std::vector<double> coefficients{-1.0, 0.0, 0.0, 1.0};
std::vector<double> roots;
auto numRoots = solveCubic(coefficients, roots);
REQUIRE(numRoots == 1);
REQUIRE(areEqual(roots[0], 1.0));
}
// -1 + 3x - 3x^2 + x^3.
// 1 root.
{
std::vector<double> coefficients{-1.0, 3.0, -3.0, 1.0};
std::vector<double> roots;
auto numRoots = solveCubic(coefficients, roots);
REQUIRE(numRoots == 1);
REQUIRE(areEqual(roots[0], 1.0));
}
}
TEST_CASE("Testing quartic solver", "[math]")
{
// 24 + -50x + 35x^2 - 10x^3 + x^4
// 4 roots: 1, 2, 3, 4.
{
std::vector<double> coefficients{24.0, -50.0, 35.0, -10.0, 1.0};
std::vector<double> roots;
auto numRoots = solveQuartic(coefficients, roots);
REQUIRE(numRoots == 4);
REQUIRE(areEqual(roots[0], 2.0));
REQUIRE(areEqual(roots[1], 1.0));
REQUIRE(areEqual(roots[2], 4.0));
REQUIRE(areEqual(roots[3], 3.0));
}
// 2x^2 - 3x^3 + x^4.
// 3 roots: 0, 1, 2.
{
std::vector<double> coefficients{0.0, 0.0, 2.0, -3.0, 1.0};
std::vector<double> roots;
auto numRoots = solveQuartic(coefficients, roots);
REQUIRE(numRoots == 3);
REQUIRE(areEqual(roots[0], 2.0));
REQUIRE(areEqual(roots[1], 1.0));
REQUIRE(areEqual(roots[2], 0.0));
}
// 2 real roots, 2 complex.
// 2 -3x + 3x^2 - 3x^3 + x^4
{
std::vector<double> coefficients{2.0, -3.0, 3.0, -3.0, 1.0};
std::vector<double> roots;
auto numRoots = solveQuartic(coefficients, roots);
REQUIRE(numRoots == 2);
REQUIRE(areEqual(roots[0], 2.0));
REQUIRE(areEqual(roots[1], 1.0));
}
// 1 - 2x^2 + x^4.
// 2 real roots.
{
std::vector<double> coefficients{1.0, 0.0, -2.0, 0.0, 1.0};
std::vector<double> roots;
auto numRoots = solveQuartic(coefficients, roots);
REQUIRE(numRoots == 2);
REQUIRE(areEqual(roots[0], -1.0));
REQUIRE(areEqual(roots[1], 1.0));
}
// 1 - 4x + 6x^2 - 4x^3 + x^4.
// 1 root.
{
std::vector<double> coefficients{1.0, -4.0, 6.0, -4.0, 1.0};
std::vector<double> roots;
auto numRoots = solveQuartic(coefficients, roots);
// Due to epsilon values, roots may be reported more than once.
REQUIRE((numRoots == 1 || numRoots == 2));
if (numRoots == 1)
{
REQUIRE(areEqual(roots[0], 1.0));
}
else
{
REQUIRE(areEqual(roots[0], 1.0));
REQUIRE(areEqual(roots[1], 1.0));
}
}
}
|
anirban59/workcraft | workcraft/WorkcraftCore/src/org/workcraft/exceptions/LayoutException.java | <reponame>anirban59/workcraft
package org.workcraft.exceptions;
@SuppressWarnings("serial")
public class LayoutException extends RuntimeException {
public LayoutException(String message) {
super(message);
}
}
|
fenz-org/mlperf_inference_results_v0.7 | open/DellEMC/code/ssd-mobilenet/xilinx/math/include/vitis/ai/math.hpp | /*
* Copyright 2019 Xilinx Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
namespace vitis {
namespace ai {
/** @brief the softmax function.
* the input is fix-point, and the output is floating point
*/
void softmax(const int8_t *input, float scale, unsigned int cls,
unsigned int group, float *output);
/** @brief `yuv2bgr` converts a raw image from YUV422 to BGR, include
* cropping.
*/
void yuv2bgr(int left, int top, //
int width, int height, //
unsigned char *__restrict y, int stride_y, //
unsigned char *__restrict uv, int stride_uv, //
unsigned char *bgr);
/** @brief reshape a feature map
*
* input(iy, ix, c*tile_size + ty*tile_dim + tx) -> output(iy, ix, ty, tx, c)
*
* where tile_size = tile_dim * tile_dim;
*/
void tiling(const int8_t *input, unsigned int width, unsigned int height,
unsigned int tile_dim, unsigned int ch, int8_t *output);
} // namespace ai
} // namespace vitis
|
mldn/Mycat-openEP | mycat-ep-server/mycat-ep-icegrid/src/main/java/io/mycat/ep/ice/package-info.java | /**
* Created by Liwh on 2015/11/3.
*/
package io.mycat.ep.ice; |
AutomationConsultant/webpagetest | agent/browser/ie/pagetest/PageSpeed/include/pagespeed/core/string_util.h | // Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PAGESPEED_CORE_STRING_UTIL_H_
#define PAGESPEED_CORE_STRING_UTIL_H_
#include <map>
#include <string>
#include "base/string_piece.h"
namespace pagespeed {
namespace string_util {
class CaseInsensitiveStringComparator {
public:
bool operator()(const std::string& x, const std::string& y) const;
};
typedef std::map<std::string, std::string,
CaseInsensitiveStringComparator>
CaseInsensitiveStringStringMap;
// Return true iff the two strings are equal, ignoring case.
bool StringCaseEqual(const base::StringPiece& s1,
const base::StringPiece& s2);
// Return true iff str starts with prefix, ignoring case.
bool StringCaseStartsWith(const base::StringPiece& str,
const base::StringPiece& prefix);
// Return true iff str ends with suffix, ignoring case.
bool StringCaseEndsWith(const base::StringPiece& str,
const base::StringPiece& suffix);
} // namespace string_util
} // namespace pagespeed
#endif // PAGESPEED_CORE_STRING_UTIL_H_
|
a358003542/galaxy_blizzard_plugin | tasks.py | import os
import sys
import json
import tempfile
from shutil import rmtree
from distutils.dir_util import copy_tree
from invoke import task
from galaxy.tools import zip_folder_to_file
with open(os.path.join("src", "manifest.json"), "r") as f:
MANIFEST = json.load(f)
if sys.platform == 'win32':
DIST_DIR = os.environ['localappdata'] + '\\GOG.com\\Galaxy\\plugins\\installed'
PIP_PLATFORM = "win32"
elif sys.platform == 'darwin':
DIST_DIR = os.path.realpath("~/Library/Application Support/GOG.com/Galaxy/plugins/installed")
PIP_PLATFORM = "macosx_10_13_x86_64" # @see https://github.com/FriendsOfGalaxy/galaxy-integrations-updater/blob/master/scripts.py
@task
def build(c, output='build', ziparchive=None):
if os.path.exists(output):
print('--> Removing {} directory'.format(output))
rmtree(output)
# Firstly dependencies needs to be "flatten" with pip-compile as pip requires --no-deps if --platform is used
print('--> Flattening dependencies to temporary requirements file')
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp:
c.run(f'pip-compile requirements/app.txt --output-file=-', out_stream=tmp)
# Then install all stuff with pip to output folder
print('--> Installing with pip for specific version')
args = [
'pip', 'install',
'-r', tmp.name,
'--python-version', '37',
'--platform', PIP_PLATFORM,
'--target "{}"'.format(output),
'--no-compile',
'--no-deps'
]
c.run(" ".join(args), echo=True)
os.unlink(tmp.name)
print('--> Copying source files')
copy_tree("src", output)
if ziparchive is not None:
print('--> Compressing to {}'.format(ziparchive))
zip_folder_to_file(output, ziparchive)
@task
def test(c):
c.run('pytest')
@task
def install(c):
dist_path = os.path.join(DIST_DIR, "battlenet_" + MANIFEST['guid'])
build(c, output=dist_path)
@task
def pack(c):
output = "battlenet_" + MANIFEST['guid']
build(c, output=output, ziparchive='battlenet_v{}.zip'.format(MANIFEST['version']))
rmtree(output)
|
jbrandwood/kickc | src/main/java/dk/camelot64/kickc/passes/PassNAssertStructMembers.java | <gh_stars>1-10
package dk.camelot64.kickc.passes;
import dk.camelot64.kickc.model.CompileError;
import dk.camelot64.kickc.model.Program;
import dk.camelot64.kickc.model.iterator.ProgramValueIterator;
import dk.camelot64.kickc.model.symbols.StructDefinition;
import dk.camelot64.kickc.model.symbols.Variable;
import dk.camelot64.kickc.model.types.SymbolType;
import dk.camelot64.kickc.model.types.SymbolTypeInference;
import dk.camelot64.kickc.model.types.SymbolTypePointer;
import dk.camelot64.kickc.model.types.SymbolTypeStruct;
import dk.camelot64.kickc.model.values.StructMemberRef;
/**
* Asserts that all struct references point to members that exist
*/
public class PassNAssertStructMembers extends Pass2SsaOptimization {
public PassNAssertStructMembers(Program program) {
super(program);
}
@Override
public boolean step() {
ProgramValueIterator.execute(getGraph(), (programValue, currentStmt, stmtIt, currentBlock) -> {
if(programValue.get() instanceof StructMemberRef) {
StructMemberRef structMemberRef = (StructMemberRef) programValue.get();
SymbolType type = SymbolTypeInference.inferType(getScope(), structMemberRef.getStruct());
if(type instanceof SymbolTypeStruct) {
SymbolTypeStruct structType = (SymbolTypeStruct) type;
StructDefinition structDefinition = structType.getStructDefinition(getScope());
Variable member = structDefinition.getMember(structMemberRef.getMemberName());
if(member==null) {
throw new CompileError("Unknown struct member "+structMemberRef.getMemberName()+" in struct "+ structType.toCDecl(), currentStmt);
}
} else {
if(type instanceof SymbolTypePointer)
throw new CompileError("member '"+structMemberRef.getMemberName()+"' reference type '"+type.toCDecl()+"' is a pointer; did you mean to use '->'?", currentStmt);
else
throw new CompileError("member '"+structMemberRef.getMemberName()+"' reference operator '.'/'->' applied to a non-struct", currentStmt);
}
}
});
return false;
}
}
|
FranciscoKnebel/ufrgs-projects | neander/neanderImplementation/isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042.c | <reponame>FranciscoKnebel/ufrgs-projects
/**********************************************************************/
/* ____ ____ */
/* / /\/ / */
/* /___/ \ / */
/* \ \ \/ */
/* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */
/* / / All Right Reserved. */
/* /---/ /\ */
/* \ \ / \ */
/* \___\/\___\ */
/***********************************************************************/
/* This file is designed for use with ISim build 0x7708f090 */
#define XSI_HIDE_SYMBOL_SPEC true
#include "xsi.h"
#include <memory.h>
#ifdef __GNUC__
#include <stdlib.h>
#else
#include <malloc.h>
#define alloca _alloca
#endif
extern char *IEEE_P_2717149903;
extern char *IEEE_P_1367372525;
unsigned char ieee_p_1367372525_sub_1379054898_4070434989(char *, char *, char *, char *, char *, char *);
void ieee_p_2717149903_sub_2486506143_2101202839(char *, char *, char *, unsigned int , unsigned int , char *, char *, char *, char *, unsigned char , char *, char *, char *, unsigned char , unsigned char , unsigned char , unsigned char , unsigned char , unsigned char , unsigned char );
void ieee_p_2717149903_sub_539877840_2101202839(char *, char *, char *, unsigned int , unsigned int , char *, char *, unsigned int , unsigned int , char *);
static void simprim_a_3936907874_4055128042_p_0(char *t0)
{
char t7[16];
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
LAB0: t1 = (t0 + 4568);
t2 = (t0 + 1896U);
t3 = (t0 + 5968);
t4 = (t0 + 1416U);
t5 = (t0 + 2792U);
t6 = *((char **)t5);
memcpy(t7, t6, 16U);
ieee_p_2717149903_sub_539877840_2101202839(IEEE_P_2717149903, t1, t2, 0U, 0U, t3, t4, 0U, 0U, t7);
t5 = (t0 + 5824);
*((int *)t5) = 1;
LAB1: return;
}
static void simprim_a_3936907874_4055128042_p_1(char *t0)
{
char t7[16];
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
LAB0: t1 = (t0 + 4816);
t2 = (t0 + 2056U);
t3 = (t0 + 6032);
t4 = (t0 + 1576U);
t5 = (t0 + 2912U);
t6 = *((char **)t5);
memcpy(t7, t6, 16U);
ieee_p_2717149903_sub_539877840_2101202839(IEEE_P_2717149903, t1, t2, 0U, 0U, t3, t4, 0U, 0U, t7);
t5 = (t0 + 5840);
*((int *)t5) = 1;
LAB1: return;
}
static void simprim_a_3936907874_4055128042_p_2(char *t0)
{
char t7[16];
char *t1;
char *t2;
char *t3;
char *t4;
char *t5;
char *t6;
LAB0: t1 = (t0 + 5064);
t2 = (t0 + 2216U);
t3 = (t0 + 6096);
t4 = (t0 + 1736U);
t5 = (t0 + 3032U);
t6 = *((char **)t5);
memcpy(t7, t6, 16U);
ieee_p_2717149903_sub_539877840_2101202839(IEEE_P_2717149903, t1, t2, 0U, 0U, t3, t4, 0U, 0U, t7);
t5 = (t0 + 5856);
*((int *)t5) = 1;
LAB1: return;
}
static void simprim_a_3936907874_4055128042_p_3(char *t0)
{
char t8[16];
char t18[16];
char t53[16];
char *t1;
char *t2;
char *t3;
char *t4;
unsigned char t5;
char *t6;
unsigned char t7;
char *t9;
int t10;
unsigned int t11;
char *t12;
char *t13;
char *t14;
unsigned char t15;
int t16;
unsigned int t17;
char *t19;
char *t20;
int t21;
unsigned int t22;
char *t23;
unsigned char t24;
char *t25;
int64 t26;
char *t27;
char *t28;
char *t29;
unsigned int t30;
char *t31;
char *t32;
char *t33;
int64 t34;
char *t35;
char *t36;
char *t37;
int t38;
unsigned int t39;
unsigned int t40;
char *t41;
char *t42;
char *t43;
int64 t44;
char *t45;
char *t46;
char *t47;
char *t48;
char *t49;
int t50;
unsigned int t51;
char *t52;
char *t54;
char *t55;
LAB0: t1 = xsi_get_transient_memory(2U);
memset(t1, 0, 2U);
t2 = t1;
t3 = (t0 + 2096U);
t4 = *((char **)t3);
t5 = *((unsigned char *)t4);
*((unsigned char *)t2) = t5;
t2 = (t2 + 1U);
t3 = (t0 + 1936U);
t6 = *((char **)t3);
t7 = *((unsigned char *)t6);
*((unsigned char *)t2) = t7;
t3 = (t8 + 0U);
t9 = (t3 + 0U);
*((int *)t9) = 0;
t9 = (t3 + 4U);
*((int *)t9) = 1;
t9 = (t3 + 8U);
*((int *)t9) = 1;
t10 = (1 - 0);
t11 = (t10 * 1);
t11 = (t11 + 1);
t9 = (t3 + 12U);
*((unsigned int *)t9) = t11;
t9 = xsi_get_transient_memory(1U);
memset(t9, 0, 1U);
t12 = t9;
t13 = (t0 + 2256U);
t14 = *((char **)t13);
t15 = *((unsigned char *)t14);
t16 = (0 - 0);
t11 = (t16 * 1);
t17 = (1U * t11);
t13 = (t12 + t17);
*((unsigned char *)t13) = t15;
t19 = (t18 + 0U);
t20 = (t19 + 0U);
*((int *)t20) = 0;
t20 = (t19 + 4U);
*((int *)t20) = 0;
t20 = (t19 + 8U);
*((int *)t20) = 1;
t21 = (0 - 0);
t22 = (t21 * 1);
t22 = (t22 + 1);
t20 = (t19 + 12U);
*((unsigned int *)t20) = t22;
t20 = ((IEEE_P_2717149903) + 1768U);
t23 = *((char **)t20);
t24 = ieee_p_1367372525_sub_1379054898_4070434989(IEEE_P_1367372525, t1, t8, t9, t18, t23);
t20 = (t0 + 3512U);
t25 = *((char **)t20);
t20 = (t25 + 0);
*((unsigned char *)t20) = t24;
t1 = (t0 + 5312);
t2 = (t0 + 1256U);
t3 = (t0 + 6160);
t4 = (t0 + 3632U);
t6 = *((char **)t4);
t4 = (t0 + 9288);
t12 = (t8 + 0U);
t13 = (t12 + 0U);
*((int *)t13) = 1;
t13 = (t12 + 4U);
*((int *)t13) = 1;
t13 = (t12 + 8U);
*((int *)t13) = 1;
t10 = (1 - 1);
t11 = (t10 * 1);
t11 = (t11 + 1);
t13 = (t12 + 12U);
*((unsigned int *)t13) = t11;
t13 = (t0 + 3512U);
t14 = *((char **)t13);
t5 = *((unsigned char *)t14);
t13 = xsi_get_transient_memory(96U);
memset(t13, 0, 96U);
t19 = t13;
t16 = (0 - 0);
t11 = (t16 * 1);
t17 = (32U * t11);
t20 = (t19 + t17);
t23 = t20;
t25 = (t0 + 1896U);
t26 = xsi_signal_get_last_event(t25);
*((int64 *)t23) = t26;
t27 = (t20 + 8U);
t28 = (t0 + 3152U);
t29 = *((char **)t28);
memcpy(t27, t29, 16U);
t28 = (t20 + 24U);
*((unsigned char *)t28) = (unsigned char)1;
t21 = (1 - 0);
t22 = (t21 * 1);
t30 = (32U * t22);
t31 = (t19 + t30);
t32 = t31;
t33 = (t0 + 2056U);
t34 = xsi_signal_get_last_event(t33);
*((int64 *)t32) = t34;
t35 = (t31 + 8U);
t36 = (t0 + 3272U);
t37 = *((char **)t36);
memcpy(t35, t37, 16U);
t36 = (t31 + 24U);
*((unsigned char *)t36) = (unsigned char)1;
t38 = (2 - 0);
t39 = (t38 * 1);
t40 = (32U * t39);
t41 = (t19 + t40);
t42 = t41;
t43 = (t0 + 2216U);
t44 = xsi_signal_get_last_event(t43);
*((int64 *)t42) = t44;
t45 = (t41 + 8U);
t46 = (t0 + 3392U);
t47 = *((char **)t46);
memcpy(t45, t47, 16U);
t46 = (t41 + 24U);
*((unsigned char *)t46) = (unsigned char)1;
t48 = (t18 + 0U);
t49 = (t48 + 0U);
*((int *)t49) = 0;
t49 = (t48 + 4U);
*((int *)t49) = 2;
t49 = (t48 + 8U);
*((int *)t49) = 1;
t50 = (2 - 0);
t51 = (t50 * 1);
t51 = (t51 + 1);
t49 = (t48 + 12U);
*((unsigned int *)t49) = t51;
t49 = ((IEEE_P_2717149903) + 1288U);
t52 = *((char **)t49);
memcpy(t53, t52, 16U);
t49 = (t0 + 2552U);
t54 = *((char **)t49);
t7 = *((unsigned char *)t54);
t49 = (t0 + 2672U);
t55 = *((char **)t49);
t15 = *((unsigned char *)t55);
ieee_p_2717149903_sub_2486506143_2101202839(IEEE_P_2717149903, t1, t2, 0U, 0U, t3, t6, t4, t8, t5, t13, t18, t53, (unsigned char)3, t7, t15, (unsigned char)1, (unsigned char)0, (unsigned char)0, (unsigned char)0);
t1 = (t0 + 5872);
*((int *)t1) = 1;
LAB1: return;
}
extern void simprim_a_3936907874_4055128042_2085860681_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2085860681", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2085860681.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3409897891_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3409897891", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3409897891.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3405546388_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3405546388", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3405546388.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3367648717_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3367648717", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3367648717.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1157696741_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1157696741", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1157696741.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1153656530_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1153656530", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1153656530.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1504178867_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1504178867", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1504178867.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1483053188_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1483053188", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1483053188.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1512253149_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1512253149", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1512253149.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1541491946_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1541491946", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1541491946.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1588484719_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1588484719", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1588484719.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1600925784_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1600925784", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1600925784.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1563069953_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1563069953", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1563069953.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1558766646_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1558766646", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1558766646.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1471456011_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1471456011", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1471456011.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1450625340_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1450625340", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1450625340.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3776681430_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3776681430", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3776681430.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3772383201_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3772383201", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3772383201.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3802087864_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3802087864", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3802087864.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3814534031_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3814534031", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3814534031.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0590265260_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0590265260", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0590265260.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1045049293_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1045049293", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1045049293.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1065895418_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1065895418", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1065895418.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1036975011_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1036975011", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1036975011.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0342840248_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0342840248", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0342840248.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0363673999_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0363673999", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0363673999.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0401311702_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0401311702", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0401311702.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0371846625_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0371846625", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0371846625.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1997533812_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1997533812", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1997533812.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1993185347_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1993185347", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1993185347.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2264287400_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2264287400", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2264287400.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2268340895_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2268340895", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2268340895.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2238880966_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2238880966", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2238880966.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2226190065_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2226190065", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2226190065.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2882026595_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2882026595", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2882026595.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2852804180_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2852804180", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2852804180.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0518250192_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0518250192", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0518250192.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0522302695_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0522302695", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0522302695.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0493292222_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0493292222", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0493292222.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0480600201_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0480600201", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0480600201.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3426173311_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3426173311", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3426173311.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_3455396680_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_3455396680", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_3455396680.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0443458146_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0443458146", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0443458146.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_0464308309_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_0464308309", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_0464308309.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2851022563_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2851022563", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2851022563.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_1655960902_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_1655960902", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_1655960902.didat");
xsi_register_executes(pe);
}
extern void simprim_a_3936907874_4055128042_2859201165_init()
{
static char *pe[] = {(void *)simprim_a_3936907874_4055128042_p_0,(void *)simprim_a_3936907874_4055128042_p_1,(void *)simprim_a_3936907874_4055128042_p_2,(void *)simprim_a_3936907874_4055128042_p_3};
xsi_register_didat("simprim_a_3936907874_4055128042_2859201165", "isim/neandertb_isim_par.exe.sim/simprim/a_3936907874_4055128042_2859201165.didat");
xsi_register_executes(pe);
}
|
felixchr/leetcode | p0973_k_point_near_origin.py | from typing import List
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
result = sorted(points, key=lambda p: p[0]*p[0] + p[1]*p[1])[:K]
return result
def test_solution():
s = Solution()
test_cases = (([[1,3],[-2,2]], 1, [[-2, 2]]),
([[3,3],[5,-1],[-2,4]], 2, [[3,3],[-2,4]]))
for points, k, answer in test_cases:
result = s.kClosest(points, k)
if result != answer:
print('Failed')
print(points, answer, result)
break
else:
print('Passed!') |
neal-siekierski/seal-tk | sealtk/core/test/TestTrackModel.hpp | /* This file is part of SEAL-TK, and is distributed under the OSI-approved BSD
* 3-Clause License. See top-level LICENSE file or
* https://github.com/Kitware/seal-tk/blob/master/LICENSE for details. */
#ifndef sealtk_core_test_TestTrackModel_hpp
#define sealtk_core_test_TestTrackModel_hpp
#include <sealtk/core/test/TestTracks.hpp>
#include <sealtk/core/AbstractItemModel.hpp>
#include <sealtk/core/TimeMap.hpp>
namespace sealtk
{
namespace core
{
namespace test
{
// ============================================================================
class SimpleTrackModel : public core::AbstractItemModel
{
public:
SimpleTrackModel(QVector<TimeMap<TrackState>> data);
int rowCount(QModelIndex const& parent = {}) const override;
QVariant data(QModelIndex const& index, int role) const override;
QModelIndex parent(QModelIndex const& index) const override;
QModelIndex index(int row, int column,
QModelIndex const& parent) const override;
void setFirstId(qint64 id);
private:
QVector<TimeMap<TrackState>> const rowData;
qint64 firstId = 0;
};
} // namespace test
} // namespace core
} // namespace sealtk
#endif
|
Componolit/android_external_vixl | test/aarch32/traces/assembler-cond-rd-operand-imm16-t32-movt.h | // Copyright 2015, VIXL authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ARM Limited 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 CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---------------------------------------------------------------------
// This file is auto generated using tools/generate_simulator_traces.py.
//
// PLEASE DO NOT EDIT.
// ---------------------------------------------------------------------
#ifndef VIXL_ASSEMBLER_COND_RD_OPERAND_IMM16_T32_MOVT_H_
#define VIXL_ASSEMBLER_COND_RD_OPERAND_IMM16_T32_MOVT_H_
const byte kInstruction_movt_al_r0_0x0000[] = {
0xc0, 0xf2, 0x00, 0x00 // movt al r0 0x0000
};
const byte kInstruction_movt_al_r0_0x0001[] = {
0xc0, 0xf2, 0x01, 0x00 // movt al r0 0x0001
};
const byte kInstruction_movt_al_r0_0x0002[] = {
0xc0, 0xf2, 0x02, 0x00 // movt al r0 0x0002
};
const byte kInstruction_movt_al_r0_0x0020[] = {
0xc0, 0xf2, 0x20, 0x00 // movt al r0 0x0020
};
const byte kInstruction_movt_al_r0_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x00 // movt al r0 0x007d
};
const byte kInstruction_movt_al_r0_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x00 // movt al r0 0x007e
};
const byte kInstruction_movt_al_r0_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x00 // movt al r0 0x007f
};
const byte kInstruction_movt_al_r0_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x70 // movt al r0 0x7ffd
};
const byte kInstruction_movt_al_r0_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x70 // movt al r0 0x7ffe
};
const byte kInstruction_movt_al_r0_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x70 // movt al r0 0x7fff
};
const byte kInstruction_movt_al_r0_0x3333[] = {
0xc3, 0xf2, 0x33, 0x30 // movt al r0 0x3333
};
const byte kInstruction_movt_al_r0_0x5555[] = {
0xc5, 0xf2, 0x55, 0x50 // movt al r0 0x5555
};
const byte kInstruction_movt_al_r0_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x20 // movt al r0 0xaaaa
};
const byte kInstruction_movt_al_r0_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x40 // movt al r0 0xcccc
};
const byte kInstruction_movt_al_r0_0x8000[] = {
0xc8, 0xf2, 0x00, 0x00 // movt al r0 0x8000
};
const byte kInstruction_movt_al_r0_0x8001[] = {
0xc8, 0xf2, 0x01, 0x00 // movt al r0 0x8001
};
const byte kInstruction_movt_al_r0_0x8002[] = {
0xc8, 0xf2, 0x02, 0x00 // movt al r0 0x8002
};
const byte kInstruction_movt_al_r0_0x8003[] = {
0xc8, 0xf2, 0x03, 0x00 // movt al r0 0x8003
};
const byte kInstruction_movt_al_r0_0xff80[] = {
0xcf, 0xf6, 0x80, 0x70 // movt al r0 0xff80
};
const byte kInstruction_movt_al_r0_0xff81[] = {
0xcf, 0xf6, 0x81, 0x70 // movt al r0 0xff81
};
const byte kInstruction_movt_al_r0_0xff82[] = {
0xcf, 0xf6, 0x82, 0x70 // movt al r0 0xff82
};
const byte kInstruction_movt_al_r0_0xff83[] = {
0xcf, 0xf6, 0x83, 0x70 // movt al r0 0xff83
};
const byte kInstruction_movt_al_r0_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x70 // movt al r0 0xffe0
};
const byte kInstruction_movt_al_r0_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x70 // movt al r0 0xfffd
};
const byte kInstruction_movt_al_r0_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x70 // movt al r0 0xfffe
};
const byte kInstruction_movt_al_r0_0xffff[] = {
0xcf, 0xf6, 0xff, 0x70 // movt al r0 0xffff
};
const byte kInstruction_movt_al_r1_0x0000[] = {
0xc0, 0xf2, 0x00, 0x01 // movt al r1 0x0000
};
const byte kInstruction_movt_al_r1_0x0001[] = {
0xc0, 0xf2, 0x01, 0x01 // movt al r1 0x0001
};
const byte kInstruction_movt_al_r1_0x0002[] = {
0xc0, 0xf2, 0x02, 0x01 // movt al r1 0x0002
};
const byte kInstruction_movt_al_r1_0x0020[] = {
0xc0, 0xf2, 0x20, 0x01 // movt al r1 0x0020
};
const byte kInstruction_movt_al_r1_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x01 // movt al r1 0x007d
};
const byte kInstruction_movt_al_r1_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x01 // movt al r1 0x007e
};
const byte kInstruction_movt_al_r1_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x01 // movt al r1 0x007f
};
const byte kInstruction_movt_al_r1_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x71 // movt al r1 0x7ffd
};
const byte kInstruction_movt_al_r1_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x71 // movt al r1 0x7ffe
};
const byte kInstruction_movt_al_r1_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x71 // movt al r1 0x7fff
};
const byte kInstruction_movt_al_r1_0x3333[] = {
0xc3, 0xf2, 0x33, 0x31 // movt al r1 0x3333
};
const byte kInstruction_movt_al_r1_0x5555[] = {
0xc5, 0xf2, 0x55, 0x51 // movt al r1 0x5555
};
const byte kInstruction_movt_al_r1_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x21 // movt al r1 0xaaaa
};
const byte kInstruction_movt_al_r1_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x41 // movt al r1 0xcccc
};
const byte kInstruction_movt_al_r1_0x8000[] = {
0xc8, 0xf2, 0x00, 0x01 // movt al r1 0x8000
};
const byte kInstruction_movt_al_r1_0x8001[] = {
0xc8, 0xf2, 0x01, 0x01 // movt al r1 0x8001
};
const byte kInstruction_movt_al_r1_0x8002[] = {
0xc8, 0xf2, 0x02, 0x01 // movt al r1 0x8002
};
const byte kInstruction_movt_al_r1_0x8003[] = {
0xc8, 0xf2, 0x03, 0x01 // movt al r1 0x8003
};
const byte kInstruction_movt_al_r1_0xff80[] = {
0xcf, 0xf6, 0x80, 0x71 // movt al r1 0xff80
};
const byte kInstruction_movt_al_r1_0xff81[] = {
0xcf, 0xf6, 0x81, 0x71 // movt al r1 0xff81
};
const byte kInstruction_movt_al_r1_0xff82[] = {
0xcf, 0xf6, 0x82, 0x71 // movt al r1 0xff82
};
const byte kInstruction_movt_al_r1_0xff83[] = {
0xcf, 0xf6, 0x83, 0x71 // movt al r1 0xff83
};
const byte kInstruction_movt_al_r1_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x71 // movt al r1 0xffe0
};
const byte kInstruction_movt_al_r1_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x71 // movt al r1 0xfffd
};
const byte kInstruction_movt_al_r1_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x71 // movt al r1 0xfffe
};
const byte kInstruction_movt_al_r1_0xffff[] = {
0xcf, 0xf6, 0xff, 0x71 // movt al r1 0xffff
};
const byte kInstruction_movt_al_r2_0x0000[] = {
0xc0, 0xf2, 0x00, 0x02 // movt al r2 0x0000
};
const byte kInstruction_movt_al_r2_0x0001[] = {
0xc0, 0xf2, 0x01, 0x02 // movt al r2 0x0001
};
const byte kInstruction_movt_al_r2_0x0002[] = {
0xc0, 0xf2, 0x02, 0x02 // movt al r2 0x0002
};
const byte kInstruction_movt_al_r2_0x0020[] = {
0xc0, 0xf2, 0x20, 0x02 // movt al r2 0x0020
};
const byte kInstruction_movt_al_r2_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x02 // movt al r2 0x007d
};
const byte kInstruction_movt_al_r2_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x02 // movt al r2 0x007e
};
const byte kInstruction_movt_al_r2_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x02 // movt al r2 0x007f
};
const byte kInstruction_movt_al_r2_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x72 // movt al r2 0x7ffd
};
const byte kInstruction_movt_al_r2_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x72 // movt al r2 0x7ffe
};
const byte kInstruction_movt_al_r2_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x72 // movt al r2 0x7fff
};
const byte kInstruction_movt_al_r2_0x3333[] = {
0xc3, 0xf2, 0x33, 0x32 // movt al r2 0x3333
};
const byte kInstruction_movt_al_r2_0x5555[] = {
0xc5, 0xf2, 0x55, 0x52 // movt al r2 0x5555
};
const byte kInstruction_movt_al_r2_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x22 // movt al r2 0xaaaa
};
const byte kInstruction_movt_al_r2_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x42 // movt al r2 0xcccc
};
const byte kInstruction_movt_al_r2_0x8000[] = {
0xc8, 0xf2, 0x00, 0x02 // movt al r2 0x8000
};
const byte kInstruction_movt_al_r2_0x8001[] = {
0xc8, 0xf2, 0x01, 0x02 // movt al r2 0x8001
};
const byte kInstruction_movt_al_r2_0x8002[] = {
0xc8, 0xf2, 0x02, 0x02 // movt al r2 0x8002
};
const byte kInstruction_movt_al_r2_0x8003[] = {
0xc8, 0xf2, 0x03, 0x02 // movt al r2 0x8003
};
const byte kInstruction_movt_al_r2_0xff80[] = {
0xcf, 0xf6, 0x80, 0x72 // movt al r2 0xff80
};
const byte kInstruction_movt_al_r2_0xff81[] = {
0xcf, 0xf6, 0x81, 0x72 // movt al r2 0xff81
};
const byte kInstruction_movt_al_r2_0xff82[] = {
0xcf, 0xf6, 0x82, 0x72 // movt al r2 0xff82
};
const byte kInstruction_movt_al_r2_0xff83[] = {
0xcf, 0xf6, 0x83, 0x72 // movt al r2 0xff83
};
const byte kInstruction_movt_al_r2_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x72 // movt al r2 0xffe0
};
const byte kInstruction_movt_al_r2_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x72 // movt al r2 0xfffd
};
const byte kInstruction_movt_al_r2_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x72 // movt al r2 0xfffe
};
const byte kInstruction_movt_al_r2_0xffff[] = {
0xcf, 0xf6, 0xff, 0x72 // movt al r2 0xffff
};
const byte kInstruction_movt_al_r3_0x0000[] = {
0xc0, 0xf2, 0x00, 0x03 // movt al r3 0x0000
};
const byte kInstruction_movt_al_r3_0x0001[] = {
0xc0, 0xf2, 0x01, 0x03 // movt al r3 0x0001
};
const byte kInstruction_movt_al_r3_0x0002[] = {
0xc0, 0xf2, 0x02, 0x03 // movt al r3 0x0002
};
const byte kInstruction_movt_al_r3_0x0020[] = {
0xc0, 0xf2, 0x20, 0x03 // movt al r3 0x0020
};
const byte kInstruction_movt_al_r3_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x03 // movt al r3 0x007d
};
const byte kInstruction_movt_al_r3_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x03 // movt al r3 0x007e
};
const byte kInstruction_movt_al_r3_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x03 // movt al r3 0x007f
};
const byte kInstruction_movt_al_r3_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x73 // movt al r3 0x7ffd
};
const byte kInstruction_movt_al_r3_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x73 // movt al r3 0x7ffe
};
const byte kInstruction_movt_al_r3_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x73 // movt al r3 0x7fff
};
const byte kInstruction_movt_al_r3_0x3333[] = {
0xc3, 0xf2, 0x33, 0x33 // movt al r3 0x3333
};
const byte kInstruction_movt_al_r3_0x5555[] = {
0xc5, 0xf2, 0x55, 0x53 // movt al r3 0x5555
};
const byte kInstruction_movt_al_r3_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x23 // movt al r3 0xaaaa
};
const byte kInstruction_movt_al_r3_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x43 // movt al r3 0xcccc
};
const byte kInstruction_movt_al_r3_0x8000[] = {
0xc8, 0xf2, 0x00, 0x03 // movt al r3 0x8000
};
const byte kInstruction_movt_al_r3_0x8001[] = {
0xc8, 0xf2, 0x01, 0x03 // movt al r3 0x8001
};
const byte kInstruction_movt_al_r3_0x8002[] = {
0xc8, 0xf2, 0x02, 0x03 // movt al r3 0x8002
};
const byte kInstruction_movt_al_r3_0x8003[] = {
0xc8, 0xf2, 0x03, 0x03 // movt al r3 0x8003
};
const byte kInstruction_movt_al_r3_0xff80[] = {
0xcf, 0xf6, 0x80, 0x73 // movt al r3 0xff80
};
const byte kInstruction_movt_al_r3_0xff81[] = {
0xcf, 0xf6, 0x81, 0x73 // movt al r3 0xff81
};
const byte kInstruction_movt_al_r3_0xff82[] = {
0xcf, 0xf6, 0x82, 0x73 // movt al r3 0xff82
};
const byte kInstruction_movt_al_r3_0xff83[] = {
0xcf, 0xf6, 0x83, 0x73 // movt al r3 0xff83
};
const byte kInstruction_movt_al_r3_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x73 // movt al r3 0xffe0
};
const byte kInstruction_movt_al_r3_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x73 // movt al r3 0xfffd
};
const byte kInstruction_movt_al_r3_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x73 // movt al r3 0xfffe
};
const byte kInstruction_movt_al_r3_0xffff[] = {
0xcf, 0xf6, 0xff, 0x73 // movt al r3 0xffff
};
const byte kInstruction_movt_al_r4_0x0000[] = {
0xc0, 0xf2, 0x00, 0x04 // movt al r4 0x0000
};
const byte kInstruction_movt_al_r4_0x0001[] = {
0xc0, 0xf2, 0x01, 0x04 // movt al r4 0x0001
};
const byte kInstruction_movt_al_r4_0x0002[] = {
0xc0, 0xf2, 0x02, 0x04 // movt al r4 0x0002
};
const byte kInstruction_movt_al_r4_0x0020[] = {
0xc0, 0xf2, 0x20, 0x04 // movt al r4 0x0020
};
const byte kInstruction_movt_al_r4_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x04 // movt al r4 0x007d
};
const byte kInstruction_movt_al_r4_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x04 // movt al r4 0x007e
};
const byte kInstruction_movt_al_r4_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x04 // movt al r4 0x007f
};
const byte kInstruction_movt_al_r4_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x74 // movt al r4 0x7ffd
};
const byte kInstruction_movt_al_r4_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x74 // movt al r4 0x7ffe
};
const byte kInstruction_movt_al_r4_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x74 // movt al r4 0x7fff
};
const byte kInstruction_movt_al_r4_0x3333[] = {
0xc3, 0xf2, 0x33, 0x34 // movt al r4 0x3333
};
const byte kInstruction_movt_al_r4_0x5555[] = {
0xc5, 0xf2, 0x55, 0x54 // movt al r4 0x5555
};
const byte kInstruction_movt_al_r4_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x24 // movt al r4 0xaaaa
};
const byte kInstruction_movt_al_r4_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x44 // movt al r4 0xcccc
};
const byte kInstruction_movt_al_r4_0x8000[] = {
0xc8, 0xf2, 0x00, 0x04 // movt al r4 0x8000
};
const byte kInstruction_movt_al_r4_0x8001[] = {
0xc8, 0xf2, 0x01, 0x04 // movt al r4 0x8001
};
const byte kInstruction_movt_al_r4_0x8002[] = {
0xc8, 0xf2, 0x02, 0x04 // movt al r4 0x8002
};
const byte kInstruction_movt_al_r4_0x8003[] = {
0xc8, 0xf2, 0x03, 0x04 // movt al r4 0x8003
};
const byte kInstruction_movt_al_r4_0xff80[] = {
0xcf, 0xf6, 0x80, 0x74 // movt al r4 0xff80
};
const byte kInstruction_movt_al_r4_0xff81[] = {
0xcf, 0xf6, 0x81, 0x74 // movt al r4 0xff81
};
const byte kInstruction_movt_al_r4_0xff82[] = {
0xcf, 0xf6, 0x82, 0x74 // movt al r4 0xff82
};
const byte kInstruction_movt_al_r4_0xff83[] = {
0xcf, 0xf6, 0x83, 0x74 // movt al r4 0xff83
};
const byte kInstruction_movt_al_r4_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x74 // movt al r4 0xffe0
};
const byte kInstruction_movt_al_r4_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x74 // movt al r4 0xfffd
};
const byte kInstruction_movt_al_r4_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x74 // movt al r4 0xfffe
};
const byte kInstruction_movt_al_r4_0xffff[] = {
0xcf, 0xf6, 0xff, 0x74 // movt al r4 0xffff
};
const byte kInstruction_movt_al_r5_0x0000[] = {
0xc0, 0xf2, 0x00, 0x05 // movt al r5 0x0000
};
const byte kInstruction_movt_al_r5_0x0001[] = {
0xc0, 0xf2, 0x01, 0x05 // movt al r5 0x0001
};
const byte kInstruction_movt_al_r5_0x0002[] = {
0xc0, 0xf2, 0x02, 0x05 // movt al r5 0x0002
};
const byte kInstruction_movt_al_r5_0x0020[] = {
0xc0, 0xf2, 0x20, 0x05 // movt al r5 0x0020
};
const byte kInstruction_movt_al_r5_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x05 // movt al r5 0x007d
};
const byte kInstruction_movt_al_r5_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x05 // movt al r5 0x007e
};
const byte kInstruction_movt_al_r5_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x05 // movt al r5 0x007f
};
const byte kInstruction_movt_al_r5_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x75 // movt al r5 0x7ffd
};
const byte kInstruction_movt_al_r5_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x75 // movt al r5 0x7ffe
};
const byte kInstruction_movt_al_r5_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x75 // movt al r5 0x7fff
};
const byte kInstruction_movt_al_r5_0x3333[] = {
0xc3, 0xf2, 0x33, 0x35 // movt al r5 0x3333
};
const byte kInstruction_movt_al_r5_0x5555[] = {
0xc5, 0xf2, 0x55, 0x55 // movt al r5 0x5555
};
const byte kInstruction_movt_al_r5_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x25 // movt al r5 0xaaaa
};
const byte kInstruction_movt_al_r5_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x45 // movt al r5 0xcccc
};
const byte kInstruction_movt_al_r5_0x8000[] = {
0xc8, 0xf2, 0x00, 0x05 // movt al r5 0x8000
};
const byte kInstruction_movt_al_r5_0x8001[] = {
0xc8, 0xf2, 0x01, 0x05 // movt al r5 0x8001
};
const byte kInstruction_movt_al_r5_0x8002[] = {
0xc8, 0xf2, 0x02, 0x05 // movt al r5 0x8002
};
const byte kInstruction_movt_al_r5_0x8003[] = {
0xc8, 0xf2, 0x03, 0x05 // movt al r5 0x8003
};
const byte kInstruction_movt_al_r5_0xff80[] = {
0xcf, 0xf6, 0x80, 0x75 // movt al r5 0xff80
};
const byte kInstruction_movt_al_r5_0xff81[] = {
0xcf, 0xf6, 0x81, 0x75 // movt al r5 0xff81
};
const byte kInstruction_movt_al_r5_0xff82[] = {
0xcf, 0xf6, 0x82, 0x75 // movt al r5 0xff82
};
const byte kInstruction_movt_al_r5_0xff83[] = {
0xcf, 0xf6, 0x83, 0x75 // movt al r5 0xff83
};
const byte kInstruction_movt_al_r5_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x75 // movt al r5 0xffe0
};
const byte kInstruction_movt_al_r5_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x75 // movt al r5 0xfffd
};
const byte kInstruction_movt_al_r5_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x75 // movt al r5 0xfffe
};
const byte kInstruction_movt_al_r5_0xffff[] = {
0xcf, 0xf6, 0xff, 0x75 // movt al r5 0xffff
};
const byte kInstruction_movt_al_r6_0x0000[] = {
0xc0, 0xf2, 0x00, 0x06 // movt al r6 0x0000
};
const byte kInstruction_movt_al_r6_0x0001[] = {
0xc0, 0xf2, 0x01, 0x06 // movt al r6 0x0001
};
const byte kInstruction_movt_al_r6_0x0002[] = {
0xc0, 0xf2, 0x02, 0x06 // movt al r6 0x0002
};
const byte kInstruction_movt_al_r6_0x0020[] = {
0xc0, 0xf2, 0x20, 0x06 // movt al r6 0x0020
};
const byte kInstruction_movt_al_r6_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x06 // movt al r6 0x007d
};
const byte kInstruction_movt_al_r6_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x06 // movt al r6 0x007e
};
const byte kInstruction_movt_al_r6_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x06 // movt al r6 0x007f
};
const byte kInstruction_movt_al_r6_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x76 // movt al r6 0x7ffd
};
const byte kInstruction_movt_al_r6_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x76 // movt al r6 0x7ffe
};
const byte kInstruction_movt_al_r6_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x76 // movt al r6 0x7fff
};
const byte kInstruction_movt_al_r6_0x3333[] = {
0xc3, 0xf2, 0x33, 0x36 // movt al r6 0x3333
};
const byte kInstruction_movt_al_r6_0x5555[] = {
0xc5, 0xf2, 0x55, 0x56 // movt al r6 0x5555
};
const byte kInstruction_movt_al_r6_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x26 // movt al r6 0xaaaa
};
const byte kInstruction_movt_al_r6_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x46 // movt al r6 0xcccc
};
const byte kInstruction_movt_al_r6_0x8000[] = {
0xc8, 0xf2, 0x00, 0x06 // movt al r6 0x8000
};
const byte kInstruction_movt_al_r6_0x8001[] = {
0xc8, 0xf2, 0x01, 0x06 // movt al r6 0x8001
};
const byte kInstruction_movt_al_r6_0x8002[] = {
0xc8, 0xf2, 0x02, 0x06 // movt al r6 0x8002
};
const byte kInstruction_movt_al_r6_0x8003[] = {
0xc8, 0xf2, 0x03, 0x06 // movt al r6 0x8003
};
const byte kInstruction_movt_al_r6_0xff80[] = {
0xcf, 0xf6, 0x80, 0x76 // movt al r6 0xff80
};
const byte kInstruction_movt_al_r6_0xff81[] = {
0xcf, 0xf6, 0x81, 0x76 // movt al r6 0xff81
};
const byte kInstruction_movt_al_r6_0xff82[] = {
0xcf, 0xf6, 0x82, 0x76 // movt al r6 0xff82
};
const byte kInstruction_movt_al_r6_0xff83[] = {
0xcf, 0xf6, 0x83, 0x76 // movt al r6 0xff83
};
const byte kInstruction_movt_al_r6_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x76 // movt al r6 0xffe0
};
const byte kInstruction_movt_al_r6_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x76 // movt al r6 0xfffd
};
const byte kInstruction_movt_al_r6_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x76 // movt al r6 0xfffe
};
const byte kInstruction_movt_al_r6_0xffff[] = {
0xcf, 0xf6, 0xff, 0x76 // movt al r6 0xffff
};
const byte kInstruction_movt_al_r7_0x0000[] = {
0xc0, 0xf2, 0x00, 0x07 // movt al r7 0x0000
};
const byte kInstruction_movt_al_r7_0x0001[] = {
0xc0, 0xf2, 0x01, 0x07 // movt al r7 0x0001
};
const byte kInstruction_movt_al_r7_0x0002[] = {
0xc0, 0xf2, 0x02, 0x07 // movt al r7 0x0002
};
const byte kInstruction_movt_al_r7_0x0020[] = {
0xc0, 0xf2, 0x20, 0x07 // movt al r7 0x0020
};
const byte kInstruction_movt_al_r7_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x07 // movt al r7 0x007d
};
const byte kInstruction_movt_al_r7_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x07 // movt al r7 0x007e
};
const byte kInstruction_movt_al_r7_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x07 // movt al r7 0x007f
};
const byte kInstruction_movt_al_r7_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x77 // movt al r7 0x7ffd
};
const byte kInstruction_movt_al_r7_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x77 // movt al r7 0x7ffe
};
const byte kInstruction_movt_al_r7_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x77 // movt al r7 0x7fff
};
const byte kInstruction_movt_al_r7_0x3333[] = {
0xc3, 0xf2, 0x33, 0x37 // movt al r7 0x3333
};
const byte kInstruction_movt_al_r7_0x5555[] = {
0xc5, 0xf2, 0x55, 0x57 // movt al r7 0x5555
};
const byte kInstruction_movt_al_r7_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x27 // movt al r7 0xaaaa
};
const byte kInstruction_movt_al_r7_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x47 // movt al r7 0xcccc
};
const byte kInstruction_movt_al_r7_0x8000[] = {
0xc8, 0xf2, 0x00, 0x07 // movt al r7 0x8000
};
const byte kInstruction_movt_al_r7_0x8001[] = {
0xc8, 0xf2, 0x01, 0x07 // movt al r7 0x8001
};
const byte kInstruction_movt_al_r7_0x8002[] = {
0xc8, 0xf2, 0x02, 0x07 // movt al r7 0x8002
};
const byte kInstruction_movt_al_r7_0x8003[] = {
0xc8, 0xf2, 0x03, 0x07 // movt al r7 0x8003
};
const byte kInstruction_movt_al_r7_0xff80[] = {
0xcf, 0xf6, 0x80, 0x77 // movt al r7 0xff80
};
const byte kInstruction_movt_al_r7_0xff81[] = {
0xcf, 0xf6, 0x81, 0x77 // movt al r7 0xff81
};
const byte kInstruction_movt_al_r7_0xff82[] = {
0xcf, 0xf6, 0x82, 0x77 // movt al r7 0xff82
};
const byte kInstruction_movt_al_r7_0xff83[] = {
0xcf, 0xf6, 0x83, 0x77 // movt al r7 0xff83
};
const byte kInstruction_movt_al_r7_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x77 // movt al r7 0xffe0
};
const byte kInstruction_movt_al_r7_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x77 // movt al r7 0xfffd
};
const byte kInstruction_movt_al_r7_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x77 // movt al r7 0xfffe
};
const byte kInstruction_movt_al_r7_0xffff[] = {
0xcf, 0xf6, 0xff, 0x77 // movt al r7 0xffff
};
const byte kInstruction_movt_al_r8_0x0000[] = {
0xc0, 0xf2, 0x00, 0x08 // movt al r8 0x0000
};
const byte kInstruction_movt_al_r8_0x0001[] = {
0xc0, 0xf2, 0x01, 0x08 // movt al r8 0x0001
};
const byte kInstruction_movt_al_r8_0x0002[] = {
0xc0, 0xf2, 0x02, 0x08 // movt al r8 0x0002
};
const byte kInstruction_movt_al_r8_0x0020[] = {
0xc0, 0xf2, 0x20, 0x08 // movt al r8 0x0020
};
const byte kInstruction_movt_al_r8_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x08 // movt al r8 0x007d
};
const byte kInstruction_movt_al_r8_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x08 // movt al r8 0x007e
};
const byte kInstruction_movt_al_r8_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x08 // movt al r8 0x007f
};
const byte kInstruction_movt_al_r8_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x78 // movt al r8 0x7ffd
};
const byte kInstruction_movt_al_r8_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x78 // movt al r8 0x7ffe
};
const byte kInstruction_movt_al_r8_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x78 // movt al r8 0x7fff
};
const byte kInstruction_movt_al_r8_0x3333[] = {
0xc3, 0xf2, 0x33, 0x38 // movt al r8 0x3333
};
const byte kInstruction_movt_al_r8_0x5555[] = {
0xc5, 0xf2, 0x55, 0x58 // movt al r8 0x5555
};
const byte kInstruction_movt_al_r8_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x28 // movt al r8 0xaaaa
};
const byte kInstruction_movt_al_r8_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x48 // movt al r8 0xcccc
};
const byte kInstruction_movt_al_r8_0x8000[] = {
0xc8, 0xf2, 0x00, 0x08 // movt al r8 0x8000
};
const byte kInstruction_movt_al_r8_0x8001[] = {
0xc8, 0xf2, 0x01, 0x08 // movt al r8 0x8001
};
const byte kInstruction_movt_al_r8_0x8002[] = {
0xc8, 0xf2, 0x02, 0x08 // movt al r8 0x8002
};
const byte kInstruction_movt_al_r8_0x8003[] = {
0xc8, 0xf2, 0x03, 0x08 // movt al r8 0x8003
};
const byte kInstruction_movt_al_r8_0xff80[] = {
0xcf, 0xf6, 0x80, 0x78 // movt al r8 0xff80
};
const byte kInstruction_movt_al_r8_0xff81[] = {
0xcf, 0xf6, 0x81, 0x78 // movt al r8 0xff81
};
const byte kInstruction_movt_al_r8_0xff82[] = {
0xcf, 0xf6, 0x82, 0x78 // movt al r8 0xff82
};
const byte kInstruction_movt_al_r8_0xff83[] = {
0xcf, 0xf6, 0x83, 0x78 // movt al r8 0xff83
};
const byte kInstruction_movt_al_r8_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x78 // movt al r8 0xffe0
};
const byte kInstruction_movt_al_r8_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x78 // movt al r8 0xfffd
};
const byte kInstruction_movt_al_r8_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x78 // movt al r8 0xfffe
};
const byte kInstruction_movt_al_r8_0xffff[] = {
0xcf, 0xf6, 0xff, 0x78 // movt al r8 0xffff
};
const byte kInstruction_movt_al_r9_0x0000[] = {
0xc0, 0xf2, 0x00, 0x09 // movt al r9 0x0000
};
const byte kInstruction_movt_al_r9_0x0001[] = {
0xc0, 0xf2, 0x01, 0x09 // movt al r9 0x0001
};
const byte kInstruction_movt_al_r9_0x0002[] = {
0xc0, 0xf2, 0x02, 0x09 // movt al r9 0x0002
};
const byte kInstruction_movt_al_r9_0x0020[] = {
0xc0, 0xf2, 0x20, 0x09 // movt al r9 0x0020
};
const byte kInstruction_movt_al_r9_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x09 // movt al r9 0x007d
};
const byte kInstruction_movt_al_r9_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x09 // movt al r9 0x007e
};
const byte kInstruction_movt_al_r9_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x09 // movt al r9 0x007f
};
const byte kInstruction_movt_al_r9_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x79 // movt al r9 0x7ffd
};
const byte kInstruction_movt_al_r9_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x79 // movt al r9 0x7ffe
};
const byte kInstruction_movt_al_r9_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x79 // movt al r9 0x7fff
};
const byte kInstruction_movt_al_r9_0x3333[] = {
0xc3, 0xf2, 0x33, 0x39 // movt al r9 0x3333
};
const byte kInstruction_movt_al_r9_0x5555[] = {
0xc5, 0xf2, 0x55, 0x59 // movt al r9 0x5555
};
const byte kInstruction_movt_al_r9_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x29 // movt al r9 0xaaaa
};
const byte kInstruction_movt_al_r9_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x49 // movt al r9 0xcccc
};
const byte kInstruction_movt_al_r9_0x8000[] = {
0xc8, 0xf2, 0x00, 0x09 // movt al r9 0x8000
};
const byte kInstruction_movt_al_r9_0x8001[] = {
0xc8, 0xf2, 0x01, 0x09 // movt al r9 0x8001
};
const byte kInstruction_movt_al_r9_0x8002[] = {
0xc8, 0xf2, 0x02, 0x09 // movt al r9 0x8002
};
const byte kInstruction_movt_al_r9_0x8003[] = {
0xc8, 0xf2, 0x03, 0x09 // movt al r9 0x8003
};
const byte kInstruction_movt_al_r9_0xff80[] = {
0xcf, 0xf6, 0x80, 0x79 // movt al r9 0xff80
};
const byte kInstruction_movt_al_r9_0xff81[] = {
0xcf, 0xf6, 0x81, 0x79 // movt al r9 0xff81
};
const byte kInstruction_movt_al_r9_0xff82[] = {
0xcf, 0xf6, 0x82, 0x79 // movt al r9 0xff82
};
const byte kInstruction_movt_al_r9_0xff83[] = {
0xcf, 0xf6, 0x83, 0x79 // movt al r9 0xff83
};
const byte kInstruction_movt_al_r9_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x79 // movt al r9 0xffe0
};
const byte kInstruction_movt_al_r9_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x79 // movt al r9 0xfffd
};
const byte kInstruction_movt_al_r9_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x79 // movt al r9 0xfffe
};
const byte kInstruction_movt_al_r9_0xffff[] = {
0xcf, 0xf6, 0xff, 0x79 // movt al r9 0xffff
};
const byte kInstruction_movt_al_r10_0x0000[] = {
0xc0, 0xf2, 0x00, 0x0a // movt al r10 0x0000
};
const byte kInstruction_movt_al_r10_0x0001[] = {
0xc0, 0xf2, 0x01, 0x0a // movt al r10 0x0001
};
const byte kInstruction_movt_al_r10_0x0002[] = {
0xc0, 0xf2, 0x02, 0x0a // movt al r10 0x0002
};
const byte kInstruction_movt_al_r10_0x0020[] = {
0xc0, 0xf2, 0x20, 0x0a // movt al r10 0x0020
};
const byte kInstruction_movt_al_r10_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x0a // movt al r10 0x007d
};
const byte kInstruction_movt_al_r10_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x0a // movt al r10 0x007e
};
const byte kInstruction_movt_al_r10_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x0a // movt al r10 0x007f
};
const byte kInstruction_movt_al_r10_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x7a // movt al r10 0x7ffd
};
const byte kInstruction_movt_al_r10_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x7a // movt al r10 0x7ffe
};
const byte kInstruction_movt_al_r10_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x7a // movt al r10 0x7fff
};
const byte kInstruction_movt_al_r10_0x3333[] = {
0xc3, 0xf2, 0x33, 0x3a // movt al r10 0x3333
};
const byte kInstruction_movt_al_r10_0x5555[] = {
0xc5, 0xf2, 0x55, 0x5a // movt al r10 0x5555
};
const byte kInstruction_movt_al_r10_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x2a // movt al r10 0xaaaa
};
const byte kInstruction_movt_al_r10_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x4a // movt al r10 0xcccc
};
const byte kInstruction_movt_al_r10_0x8000[] = {
0xc8, 0xf2, 0x00, 0x0a // movt al r10 0x8000
};
const byte kInstruction_movt_al_r10_0x8001[] = {
0xc8, 0xf2, 0x01, 0x0a // movt al r10 0x8001
};
const byte kInstruction_movt_al_r10_0x8002[] = {
0xc8, 0xf2, 0x02, 0x0a // movt al r10 0x8002
};
const byte kInstruction_movt_al_r10_0x8003[] = {
0xc8, 0xf2, 0x03, 0x0a // movt al r10 0x8003
};
const byte kInstruction_movt_al_r10_0xff80[] = {
0xcf, 0xf6, 0x80, 0x7a // movt al r10 0xff80
};
const byte kInstruction_movt_al_r10_0xff81[] = {
0xcf, 0xf6, 0x81, 0x7a // movt al r10 0xff81
};
const byte kInstruction_movt_al_r10_0xff82[] = {
0xcf, 0xf6, 0x82, 0x7a // movt al r10 0xff82
};
const byte kInstruction_movt_al_r10_0xff83[] = {
0xcf, 0xf6, 0x83, 0x7a // movt al r10 0xff83
};
const byte kInstruction_movt_al_r10_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x7a // movt al r10 0xffe0
};
const byte kInstruction_movt_al_r10_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x7a // movt al r10 0xfffd
};
const byte kInstruction_movt_al_r10_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x7a // movt al r10 0xfffe
};
const byte kInstruction_movt_al_r10_0xffff[] = {
0xcf, 0xf6, 0xff, 0x7a // movt al r10 0xffff
};
const byte kInstruction_movt_al_r11_0x0000[] = {
0xc0, 0xf2, 0x00, 0x0b // movt al r11 0x0000
};
const byte kInstruction_movt_al_r11_0x0001[] = {
0xc0, 0xf2, 0x01, 0x0b // movt al r11 0x0001
};
const byte kInstruction_movt_al_r11_0x0002[] = {
0xc0, 0xf2, 0x02, 0x0b // movt al r11 0x0002
};
const byte kInstruction_movt_al_r11_0x0020[] = {
0xc0, 0xf2, 0x20, 0x0b // movt al r11 0x0020
};
const byte kInstruction_movt_al_r11_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x0b // movt al r11 0x007d
};
const byte kInstruction_movt_al_r11_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x0b // movt al r11 0x007e
};
const byte kInstruction_movt_al_r11_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x0b // movt al r11 0x007f
};
const byte kInstruction_movt_al_r11_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x7b // movt al r11 0x7ffd
};
const byte kInstruction_movt_al_r11_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x7b // movt al r11 0x7ffe
};
const byte kInstruction_movt_al_r11_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x7b // movt al r11 0x7fff
};
const byte kInstruction_movt_al_r11_0x3333[] = {
0xc3, 0xf2, 0x33, 0x3b // movt al r11 0x3333
};
const byte kInstruction_movt_al_r11_0x5555[] = {
0xc5, 0xf2, 0x55, 0x5b // movt al r11 0x5555
};
const byte kInstruction_movt_al_r11_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x2b // movt al r11 0xaaaa
};
const byte kInstruction_movt_al_r11_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x4b // movt al r11 0xcccc
};
const byte kInstruction_movt_al_r11_0x8000[] = {
0xc8, 0xf2, 0x00, 0x0b // movt al r11 0x8000
};
const byte kInstruction_movt_al_r11_0x8001[] = {
0xc8, 0xf2, 0x01, 0x0b // movt al r11 0x8001
};
const byte kInstruction_movt_al_r11_0x8002[] = {
0xc8, 0xf2, 0x02, 0x0b // movt al r11 0x8002
};
const byte kInstruction_movt_al_r11_0x8003[] = {
0xc8, 0xf2, 0x03, 0x0b // movt al r11 0x8003
};
const byte kInstruction_movt_al_r11_0xff80[] = {
0xcf, 0xf6, 0x80, 0x7b // movt al r11 0xff80
};
const byte kInstruction_movt_al_r11_0xff81[] = {
0xcf, 0xf6, 0x81, 0x7b // movt al r11 0xff81
};
const byte kInstruction_movt_al_r11_0xff82[] = {
0xcf, 0xf6, 0x82, 0x7b // movt al r11 0xff82
};
const byte kInstruction_movt_al_r11_0xff83[] = {
0xcf, 0xf6, 0x83, 0x7b // movt al r11 0xff83
};
const byte kInstruction_movt_al_r11_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x7b // movt al r11 0xffe0
};
const byte kInstruction_movt_al_r11_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x7b // movt al r11 0xfffd
};
const byte kInstruction_movt_al_r11_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x7b // movt al r11 0xfffe
};
const byte kInstruction_movt_al_r11_0xffff[] = {
0xcf, 0xf6, 0xff, 0x7b // movt al r11 0xffff
};
const byte kInstruction_movt_al_r12_0x0000[] = {
0xc0, 0xf2, 0x00, 0x0c // movt al r12 0x0000
};
const byte kInstruction_movt_al_r12_0x0001[] = {
0xc0, 0xf2, 0x01, 0x0c // movt al r12 0x0001
};
const byte kInstruction_movt_al_r12_0x0002[] = {
0xc0, 0xf2, 0x02, 0x0c // movt al r12 0x0002
};
const byte kInstruction_movt_al_r12_0x0020[] = {
0xc0, 0xf2, 0x20, 0x0c // movt al r12 0x0020
};
const byte kInstruction_movt_al_r12_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x0c // movt al r12 0x007d
};
const byte kInstruction_movt_al_r12_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x0c // movt al r12 0x007e
};
const byte kInstruction_movt_al_r12_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x0c // movt al r12 0x007f
};
const byte kInstruction_movt_al_r12_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x7c // movt al r12 0x7ffd
};
const byte kInstruction_movt_al_r12_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x7c // movt al r12 0x7ffe
};
const byte kInstruction_movt_al_r12_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x7c // movt al r12 0x7fff
};
const byte kInstruction_movt_al_r12_0x3333[] = {
0xc3, 0xf2, 0x33, 0x3c // movt al r12 0x3333
};
const byte kInstruction_movt_al_r12_0x5555[] = {
0xc5, 0xf2, 0x55, 0x5c // movt al r12 0x5555
};
const byte kInstruction_movt_al_r12_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x2c // movt al r12 0xaaaa
};
const byte kInstruction_movt_al_r12_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x4c // movt al r12 0xcccc
};
const byte kInstruction_movt_al_r12_0x8000[] = {
0xc8, 0xf2, 0x00, 0x0c // movt al r12 0x8000
};
const byte kInstruction_movt_al_r12_0x8001[] = {
0xc8, 0xf2, 0x01, 0x0c // movt al r12 0x8001
};
const byte kInstruction_movt_al_r12_0x8002[] = {
0xc8, 0xf2, 0x02, 0x0c // movt al r12 0x8002
};
const byte kInstruction_movt_al_r12_0x8003[] = {
0xc8, 0xf2, 0x03, 0x0c // movt al r12 0x8003
};
const byte kInstruction_movt_al_r12_0xff80[] = {
0xcf, 0xf6, 0x80, 0x7c // movt al r12 0xff80
};
const byte kInstruction_movt_al_r12_0xff81[] = {
0xcf, 0xf6, 0x81, 0x7c // movt al r12 0xff81
};
const byte kInstruction_movt_al_r12_0xff82[] = {
0xcf, 0xf6, 0x82, 0x7c // movt al r12 0xff82
};
const byte kInstruction_movt_al_r12_0xff83[] = {
0xcf, 0xf6, 0x83, 0x7c // movt al r12 0xff83
};
const byte kInstruction_movt_al_r12_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x7c // movt al r12 0xffe0
};
const byte kInstruction_movt_al_r12_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x7c // movt al r12 0xfffd
};
const byte kInstruction_movt_al_r12_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x7c // movt al r12 0xfffe
};
const byte kInstruction_movt_al_r12_0xffff[] = {
0xcf, 0xf6, 0xff, 0x7c // movt al r12 0xffff
};
const byte kInstruction_movt_al_r13_0x0000[] = {
0xc0, 0xf2, 0x00, 0x0d // movt al r13 0x0000
};
const byte kInstruction_movt_al_r13_0x0001[] = {
0xc0, 0xf2, 0x01, 0x0d // movt al r13 0x0001
};
const byte kInstruction_movt_al_r13_0x0002[] = {
0xc0, 0xf2, 0x02, 0x0d // movt al r13 0x0002
};
const byte kInstruction_movt_al_r13_0x0020[] = {
0xc0, 0xf2, 0x20, 0x0d // movt al r13 0x0020
};
const byte kInstruction_movt_al_r13_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x0d // movt al r13 0x007d
};
const byte kInstruction_movt_al_r13_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x0d // movt al r13 0x007e
};
const byte kInstruction_movt_al_r13_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x0d // movt al r13 0x007f
};
const byte kInstruction_movt_al_r13_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x7d // movt al r13 0x7ffd
};
const byte kInstruction_movt_al_r13_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x7d // movt al r13 0x7ffe
};
const byte kInstruction_movt_al_r13_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x7d // movt al r13 0x7fff
};
const byte kInstruction_movt_al_r13_0x3333[] = {
0xc3, 0xf2, 0x33, 0x3d // movt al r13 0x3333
};
const byte kInstruction_movt_al_r13_0x5555[] = {
0xc5, 0xf2, 0x55, 0x5d // movt al r13 0x5555
};
const byte kInstruction_movt_al_r13_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x2d // movt al r13 0xaaaa
};
const byte kInstruction_movt_al_r13_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x4d // movt al r13 0xcccc
};
const byte kInstruction_movt_al_r13_0x8000[] = {
0xc8, 0xf2, 0x00, 0x0d // movt al r13 0x8000
};
const byte kInstruction_movt_al_r13_0x8001[] = {
0xc8, 0xf2, 0x01, 0x0d // movt al r13 0x8001
};
const byte kInstruction_movt_al_r13_0x8002[] = {
0xc8, 0xf2, 0x02, 0x0d // movt al r13 0x8002
};
const byte kInstruction_movt_al_r13_0x8003[] = {
0xc8, 0xf2, 0x03, 0x0d // movt al r13 0x8003
};
const byte kInstruction_movt_al_r13_0xff80[] = {
0xcf, 0xf6, 0x80, 0x7d // movt al r13 0xff80
};
const byte kInstruction_movt_al_r13_0xff81[] = {
0xcf, 0xf6, 0x81, 0x7d // movt al r13 0xff81
};
const byte kInstruction_movt_al_r13_0xff82[] = {
0xcf, 0xf6, 0x82, 0x7d // movt al r13 0xff82
};
const byte kInstruction_movt_al_r13_0xff83[] = {
0xcf, 0xf6, 0x83, 0x7d // movt al r13 0xff83
};
const byte kInstruction_movt_al_r13_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x7d // movt al r13 0xffe0
};
const byte kInstruction_movt_al_r13_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x7d // movt al r13 0xfffd
};
const byte kInstruction_movt_al_r13_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x7d // movt al r13 0xfffe
};
const byte kInstruction_movt_al_r13_0xffff[] = {
0xcf, 0xf6, 0xff, 0x7d // movt al r13 0xffff
};
const byte kInstruction_movt_al_r14_0x0000[] = {
0xc0, 0xf2, 0x00, 0x0e // movt al r14 0x0000
};
const byte kInstruction_movt_al_r14_0x0001[] = {
0xc0, 0xf2, 0x01, 0x0e // movt al r14 0x0001
};
const byte kInstruction_movt_al_r14_0x0002[] = {
0xc0, 0xf2, 0x02, 0x0e // movt al r14 0x0002
};
const byte kInstruction_movt_al_r14_0x0020[] = {
0xc0, 0xf2, 0x20, 0x0e // movt al r14 0x0020
};
const byte kInstruction_movt_al_r14_0x007d[] = {
0xc0, 0xf2, 0x7d, 0x0e // movt al r14 0x007d
};
const byte kInstruction_movt_al_r14_0x007e[] = {
0xc0, 0xf2, 0x7e, 0x0e // movt al r14 0x007e
};
const byte kInstruction_movt_al_r14_0x007f[] = {
0xc0, 0xf2, 0x7f, 0x0e // movt al r14 0x007f
};
const byte kInstruction_movt_al_r14_0x7ffd[] = {
0xc7, 0xf6, 0xfd, 0x7e // movt al r14 0x7ffd
};
const byte kInstruction_movt_al_r14_0x7ffe[] = {
0xc7, 0xf6, 0xfe, 0x7e // movt al r14 0x7ffe
};
const byte kInstruction_movt_al_r14_0x7fff[] = {
0xc7, 0xf6, 0xff, 0x7e // movt al r14 0x7fff
};
const byte kInstruction_movt_al_r14_0x3333[] = {
0xc3, 0xf2, 0x33, 0x3e // movt al r14 0x3333
};
const byte kInstruction_movt_al_r14_0x5555[] = {
0xc5, 0xf2, 0x55, 0x5e // movt al r14 0x5555
};
const byte kInstruction_movt_al_r14_0xaaaa[] = {
0xca, 0xf6, 0xaa, 0x2e // movt al r14 0xaaaa
};
const byte kInstruction_movt_al_r14_0xcccc[] = {
0xcc, 0xf6, 0xcc, 0x4e // movt al r14 0xcccc
};
const byte kInstruction_movt_al_r14_0x8000[] = {
0xc8, 0xf2, 0x00, 0x0e // movt al r14 0x8000
};
const byte kInstruction_movt_al_r14_0x8001[] = {
0xc8, 0xf2, 0x01, 0x0e // movt al r14 0x8001
};
const byte kInstruction_movt_al_r14_0x8002[] = {
0xc8, 0xf2, 0x02, 0x0e // movt al r14 0x8002
};
const byte kInstruction_movt_al_r14_0x8003[] = {
0xc8, 0xf2, 0x03, 0x0e // movt al r14 0x8003
};
const byte kInstruction_movt_al_r14_0xff80[] = {
0xcf, 0xf6, 0x80, 0x7e // movt al r14 0xff80
};
const byte kInstruction_movt_al_r14_0xff81[] = {
0xcf, 0xf6, 0x81, 0x7e // movt al r14 0xff81
};
const byte kInstruction_movt_al_r14_0xff82[] = {
0xcf, 0xf6, 0x82, 0x7e // movt al r14 0xff82
};
const byte kInstruction_movt_al_r14_0xff83[] = {
0xcf, 0xf6, 0x83, 0x7e // movt al r14 0xff83
};
const byte kInstruction_movt_al_r14_0xffe0[] = {
0xcf, 0xf6, 0xe0, 0x7e // movt al r14 0xffe0
};
const byte kInstruction_movt_al_r14_0xfffd[] = {
0xcf, 0xf6, 0xfd, 0x7e // movt al r14 0xfffd
};
const byte kInstruction_movt_al_r14_0xfffe[] = {
0xcf, 0xf6, 0xfe, 0x7e // movt al r14 0xfffe
};
const byte kInstruction_movt_al_r14_0xffff[] = {
0xcf, 0xf6, 0xff, 0x7e // movt al r14 0xffff
};
const TestResult kReferencemovt[] = {
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x0000),
kInstruction_movt_al_r0_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x0001),
kInstruction_movt_al_r0_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x0002),
kInstruction_movt_al_r0_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x0020),
kInstruction_movt_al_r0_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x007d),
kInstruction_movt_al_r0_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x007e),
kInstruction_movt_al_r0_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x007f),
kInstruction_movt_al_r0_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x7ffd),
kInstruction_movt_al_r0_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x7ffe),
kInstruction_movt_al_r0_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x7fff),
kInstruction_movt_al_r0_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x3333),
kInstruction_movt_al_r0_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x5555),
kInstruction_movt_al_r0_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xaaaa),
kInstruction_movt_al_r0_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xcccc),
kInstruction_movt_al_r0_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x8000),
kInstruction_movt_al_r0_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x8001),
kInstruction_movt_al_r0_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x8002),
kInstruction_movt_al_r0_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0x8003),
kInstruction_movt_al_r0_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xff80),
kInstruction_movt_al_r0_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xff81),
kInstruction_movt_al_r0_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xff82),
kInstruction_movt_al_r0_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xff83),
kInstruction_movt_al_r0_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xffe0),
kInstruction_movt_al_r0_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xfffd),
kInstruction_movt_al_r0_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xfffe),
kInstruction_movt_al_r0_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r0_0xffff),
kInstruction_movt_al_r0_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x0000),
kInstruction_movt_al_r1_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x0001),
kInstruction_movt_al_r1_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x0002),
kInstruction_movt_al_r1_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x0020),
kInstruction_movt_al_r1_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x007d),
kInstruction_movt_al_r1_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x007e),
kInstruction_movt_al_r1_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x007f),
kInstruction_movt_al_r1_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x7ffd),
kInstruction_movt_al_r1_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x7ffe),
kInstruction_movt_al_r1_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x7fff),
kInstruction_movt_al_r1_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x3333),
kInstruction_movt_al_r1_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x5555),
kInstruction_movt_al_r1_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xaaaa),
kInstruction_movt_al_r1_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xcccc),
kInstruction_movt_al_r1_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x8000),
kInstruction_movt_al_r1_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x8001),
kInstruction_movt_al_r1_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x8002),
kInstruction_movt_al_r1_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0x8003),
kInstruction_movt_al_r1_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xff80),
kInstruction_movt_al_r1_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xff81),
kInstruction_movt_al_r1_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xff82),
kInstruction_movt_al_r1_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xff83),
kInstruction_movt_al_r1_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xffe0),
kInstruction_movt_al_r1_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xfffd),
kInstruction_movt_al_r1_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xfffe),
kInstruction_movt_al_r1_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r1_0xffff),
kInstruction_movt_al_r1_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x0000),
kInstruction_movt_al_r2_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x0001),
kInstruction_movt_al_r2_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x0002),
kInstruction_movt_al_r2_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x0020),
kInstruction_movt_al_r2_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x007d),
kInstruction_movt_al_r2_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x007e),
kInstruction_movt_al_r2_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x007f),
kInstruction_movt_al_r2_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x7ffd),
kInstruction_movt_al_r2_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x7ffe),
kInstruction_movt_al_r2_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x7fff),
kInstruction_movt_al_r2_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x3333),
kInstruction_movt_al_r2_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x5555),
kInstruction_movt_al_r2_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xaaaa),
kInstruction_movt_al_r2_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xcccc),
kInstruction_movt_al_r2_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x8000),
kInstruction_movt_al_r2_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x8001),
kInstruction_movt_al_r2_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x8002),
kInstruction_movt_al_r2_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0x8003),
kInstruction_movt_al_r2_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xff80),
kInstruction_movt_al_r2_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xff81),
kInstruction_movt_al_r2_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xff82),
kInstruction_movt_al_r2_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xff83),
kInstruction_movt_al_r2_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xffe0),
kInstruction_movt_al_r2_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xfffd),
kInstruction_movt_al_r2_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xfffe),
kInstruction_movt_al_r2_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r2_0xffff),
kInstruction_movt_al_r2_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x0000),
kInstruction_movt_al_r3_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x0001),
kInstruction_movt_al_r3_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x0002),
kInstruction_movt_al_r3_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x0020),
kInstruction_movt_al_r3_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x007d),
kInstruction_movt_al_r3_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x007e),
kInstruction_movt_al_r3_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x007f),
kInstruction_movt_al_r3_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x7ffd),
kInstruction_movt_al_r3_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x7ffe),
kInstruction_movt_al_r3_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x7fff),
kInstruction_movt_al_r3_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x3333),
kInstruction_movt_al_r3_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x5555),
kInstruction_movt_al_r3_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xaaaa),
kInstruction_movt_al_r3_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xcccc),
kInstruction_movt_al_r3_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x8000),
kInstruction_movt_al_r3_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x8001),
kInstruction_movt_al_r3_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x8002),
kInstruction_movt_al_r3_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0x8003),
kInstruction_movt_al_r3_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xff80),
kInstruction_movt_al_r3_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xff81),
kInstruction_movt_al_r3_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xff82),
kInstruction_movt_al_r3_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xff83),
kInstruction_movt_al_r3_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xffe0),
kInstruction_movt_al_r3_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xfffd),
kInstruction_movt_al_r3_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xfffe),
kInstruction_movt_al_r3_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r3_0xffff),
kInstruction_movt_al_r3_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x0000),
kInstruction_movt_al_r4_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x0001),
kInstruction_movt_al_r4_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x0002),
kInstruction_movt_al_r4_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x0020),
kInstruction_movt_al_r4_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x007d),
kInstruction_movt_al_r4_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x007e),
kInstruction_movt_al_r4_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x007f),
kInstruction_movt_al_r4_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x7ffd),
kInstruction_movt_al_r4_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x7ffe),
kInstruction_movt_al_r4_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x7fff),
kInstruction_movt_al_r4_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x3333),
kInstruction_movt_al_r4_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x5555),
kInstruction_movt_al_r4_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xaaaa),
kInstruction_movt_al_r4_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xcccc),
kInstruction_movt_al_r4_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x8000),
kInstruction_movt_al_r4_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x8001),
kInstruction_movt_al_r4_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x8002),
kInstruction_movt_al_r4_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0x8003),
kInstruction_movt_al_r4_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xff80),
kInstruction_movt_al_r4_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xff81),
kInstruction_movt_al_r4_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xff82),
kInstruction_movt_al_r4_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xff83),
kInstruction_movt_al_r4_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xffe0),
kInstruction_movt_al_r4_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xfffd),
kInstruction_movt_al_r4_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xfffe),
kInstruction_movt_al_r4_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r4_0xffff),
kInstruction_movt_al_r4_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x0000),
kInstruction_movt_al_r5_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x0001),
kInstruction_movt_al_r5_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x0002),
kInstruction_movt_al_r5_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x0020),
kInstruction_movt_al_r5_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x007d),
kInstruction_movt_al_r5_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x007e),
kInstruction_movt_al_r5_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x007f),
kInstruction_movt_al_r5_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x7ffd),
kInstruction_movt_al_r5_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x7ffe),
kInstruction_movt_al_r5_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x7fff),
kInstruction_movt_al_r5_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x3333),
kInstruction_movt_al_r5_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x5555),
kInstruction_movt_al_r5_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xaaaa),
kInstruction_movt_al_r5_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xcccc),
kInstruction_movt_al_r5_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x8000),
kInstruction_movt_al_r5_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x8001),
kInstruction_movt_al_r5_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x8002),
kInstruction_movt_al_r5_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0x8003),
kInstruction_movt_al_r5_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xff80),
kInstruction_movt_al_r5_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xff81),
kInstruction_movt_al_r5_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xff82),
kInstruction_movt_al_r5_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xff83),
kInstruction_movt_al_r5_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xffe0),
kInstruction_movt_al_r5_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xfffd),
kInstruction_movt_al_r5_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xfffe),
kInstruction_movt_al_r5_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r5_0xffff),
kInstruction_movt_al_r5_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x0000),
kInstruction_movt_al_r6_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x0001),
kInstruction_movt_al_r6_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x0002),
kInstruction_movt_al_r6_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x0020),
kInstruction_movt_al_r6_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x007d),
kInstruction_movt_al_r6_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x007e),
kInstruction_movt_al_r6_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x007f),
kInstruction_movt_al_r6_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x7ffd),
kInstruction_movt_al_r6_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x7ffe),
kInstruction_movt_al_r6_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x7fff),
kInstruction_movt_al_r6_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x3333),
kInstruction_movt_al_r6_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x5555),
kInstruction_movt_al_r6_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xaaaa),
kInstruction_movt_al_r6_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xcccc),
kInstruction_movt_al_r6_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x8000),
kInstruction_movt_al_r6_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x8001),
kInstruction_movt_al_r6_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x8002),
kInstruction_movt_al_r6_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0x8003),
kInstruction_movt_al_r6_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xff80),
kInstruction_movt_al_r6_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xff81),
kInstruction_movt_al_r6_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xff82),
kInstruction_movt_al_r6_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xff83),
kInstruction_movt_al_r6_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xffe0),
kInstruction_movt_al_r6_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xfffd),
kInstruction_movt_al_r6_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xfffe),
kInstruction_movt_al_r6_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r6_0xffff),
kInstruction_movt_al_r6_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x0000),
kInstruction_movt_al_r7_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x0001),
kInstruction_movt_al_r7_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x0002),
kInstruction_movt_al_r7_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x0020),
kInstruction_movt_al_r7_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x007d),
kInstruction_movt_al_r7_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x007e),
kInstruction_movt_al_r7_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x007f),
kInstruction_movt_al_r7_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x7ffd),
kInstruction_movt_al_r7_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x7ffe),
kInstruction_movt_al_r7_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x7fff),
kInstruction_movt_al_r7_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x3333),
kInstruction_movt_al_r7_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x5555),
kInstruction_movt_al_r7_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xaaaa),
kInstruction_movt_al_r7_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xcccc),
kInstruction_movt_al_r7_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x8000),
kInstruction_movt_al_r7_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x8001),
kInstruction_movt_al_r7_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x8002),
kInstruction_movt_al_r7_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0x8003),
kInstruction_movt_al_r7_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xff80),
kInstruction_movt_al_r7_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xff81),
kInstruction_movt_al_r7_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xff82),
kInstruction_movt_al_r7_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xff83),
kInstruction_movt_al_r7_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xffe0),
kInstruction_movt_al_r7_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xfffd),
kInstruction_movt_al_r7_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xfffe),
kInstruction_movt_al_r7_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r7_0xffff),
kInstruction_movt_al_r7_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x0000),
kInstruction_movt_al_r8_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x0001),
kInstruction_movt_al_r8_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x0002),
kInstruction_movt_al_r8_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x0020),
kInstruction_movt_al_r8_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x007d),
kInstruction_movt_al_r8_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x007e),
kInstruction_movt_al_r8_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x007f),
kInstruction_movt_al_r8_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x7ffd),
kInstruction_movt_al_r8_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x7ffe),
kInstruction_movt_al_r8_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x7fff),
kInstruction_movt_al_r8_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x3333),
kInstruction_movt_al_r8_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x5555),
kInstruction_movt_al_r8_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xaaaa),
kInstruction_movt_al_r8_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xcccc),
kInstruction_movt_al_r8_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x8000),
kInstruction_movt_al_r8_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x8001),
kInstruction_movt_al_r8_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x8002),
kInstruction_movt_al_r8_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0x8003),
kInstruction_movt_al_r8_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xff80),
kInstruction_movt_al_r8_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xff81),
kInstruction_movt_al_r8_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xff82),
kInstruction_movt_al_r8_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xff83),
kInstruction_movt_al_r8_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xffe0),
kInstruction_movt_al_r8_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xfffd),
kInstruction_movt_al_r8_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xfffe),
kInstruction_movt_al_r8_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r8_0xffff),
kInstruction_movt_al_r8_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x0000),
kInstruction_movt_al_r9_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x0001),
kInstruction_movt_al_r9_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x0002),
kInstruction_movt_al_r9_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x0020),
kInstruction_movt_al_r9_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x007d),
kInstruction_movt_al_r9_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x007e),
kInstruction_movt_al_r9_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x007f),
kInstruction_movt_al_r9_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x7ffd),
kInstruction_movt_al_r9_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x7ffe),
kInstruction_movt_al_r9_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x7fff),
kInstruction_movt_al_r9_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x3333),
kInstruction_movt_al_r9_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x5555),
kInstruction_movt_al_r9_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xaaaa),
kInstruction_movt_al_r9_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xcccc),
kInstruction_movt_al_r9_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x8000),
kInstruction_movt_al_r9_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x8001),
kInstruction_movt_al_r9_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x8002),
kInstruction_movt_al_r9_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0x8003),
kInstruction_movt_al_r9_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xff80),
kInstruction_movt_al_r9_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xff81),
kInstruction_movt_al_r9_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xff82),
kInstruction_movt_al_r9_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xff83),
kInstruction_movt_al_r9_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xffe0),
kInstruction_movt_al_r9_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xfffd),
kInstruction_movt_al_r9_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xfffe),
kInstruction_movt_al_r9_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r9_0xffff),
kInstruction_movt_al_r9_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x0000),
kInstruction_movt_al_r10_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x0001),
kInstruction_movt_al_r10_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x0002),
kInstruction_movt_al_r10_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x0020),
kInstruction_movt_al_r10_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x007d),
kInstruction_movt_al_r10_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x007e),
kInstruction_movt_al_r10_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x007f),
kInstruction_movt_al_r10_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x7ffd),
kInstruction_movt_al_r10_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x7ffe),
kInstruction_movt_al_r10_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x7fff),
kInstruction_movt_al_r10_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x3333),
kInstruction_movt_al_r10_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x5555),
kInstruction_movt_al_r10_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xaaaa),
kInstruction_movt_al_r10_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xcccc),
kInstruction_movt_al_r10_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x8000),
kInstruction_movt_al_r10_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x8001),
kInstruction_movt_al_r10_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x8002),
kInstruction_movt_al_r10_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0x8003),
kInstruction_movt_al_r10_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xff80),
kInstruction_movt_al_r10_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xff81),
kInstruction_movt_al_r10_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xff82),
kInstruction_movt_al_r10_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xff83),
kInstruction_movt_al_r10_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xffe0),
kInstruction_movt_al_r10_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xfffd),
kInstruction_movt_al_r10_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xfffe),
kInstruction_movt_al_r10_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r10_0xffff),
kInstruction_movt_al_r10_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x0000),
kInstruction_movt_al_r11_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x0001),
kInstruction_movt_al_r11_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x0002),
kInstruction_movt_al_r11_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x0020),
kInstruction_movt_al_r11_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x007d),
kInstruction_movt_al_r11_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x007e),
kInstruction_movt_al_r11_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x007f),
kInstruction_movt_al_r11_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x7ffd),
kInstruction_movt_al_r11_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x7ffe),
kInstruction_movt_al_r11_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x7fff),
kInstruction_movt_al_r11_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x3333),
kInstruction_movt_al_r11_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x5555),
kInstruction_movt_al_r11_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xaaaa),
kInstruction_movt_al_r11_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xcccc),
kInstruction_movt_al_r11_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x8000),
kInstruction_movt_al_r11_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x8001),
kInstruction_movt_al_r11_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x8002),
kInstruction_movt_al_r11_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0x8003),
kInstruction_movt_al_r11_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xff80),
kInstruction_movt_al_r11_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xff81),
kInstruction_movt_al_r11_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xff82),
kInstruction_movt_al_r11_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xff83),
kInstruction_movt_al_r11_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xffe0),
kInstruction_movt_al_r11_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xfffd),
kInstruction_movt_al_r11_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xfffe),
kInstruction_movt_al_r11_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r11_0xffff),
kInstruction_movt_al_r11_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x0000),
kInstruction_movt_al_r12_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x0001),
kInstruction_movt_al_r12_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x0002),
kInstruction_movt_al_r12_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x0020),
kInstruction_movt_al_r12_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x007d),
kInstruction_movt_al_r12_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x007e),
kInstruction_movt_al_r12_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x007f),
kInstruction_movt_al_r12_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x7ffd),
kInstruction_movt_al_r12_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x7ffe),
kInstruction_movt_al_r12_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x7fff),
kInstruction_movt_al_r12_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x3333),
kInstruction_movt_al_r12_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x5555),
kInstruction_movt_al_r12_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xaaaa),
kInstruction_movt_al_r12_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xcccc),
kInstruction_movt_al_r12_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x8000),
kInstruction_movt_al_r12_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x8001),
kInstruction_movt_al_r12_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x8002),
kInstruction_movt_al_r12_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0x8003),
kInstruction_movt_al_r12_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xff80),
kInstruction_movt_al_r12_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xff81),
kInstruction_movt_al_r12_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xff82),
kInstruction_movt_al_r12_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xff83),
kInstruction_movt_al_r12_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xffe0),
kInstruction_movt_al_r12_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xfffd),
kInstruction_movt_al_r12_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xfffe),
kInstruction_movt_al_r12_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r12_0xffff),
kInstruction_movt_al_r12_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x0000),
kInstruction_movt_al_r13_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x0001),
kInstruction_movt_al_r13_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x0002),
kInstruction_movt_al_r13_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x0020),
kInstruction_movt_al_r13_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x007d),
kInstruction_movt_al_r13_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x007e),
kInstruction_movt_al_r13_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x007f),
kInstruction_movt_al_r13_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x7ffd),
kInstruction_movt_al_r13_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x7ffe),
kInstruction_movt_al_r13_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x7fff),
kInstruction_movt_al_r13_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x3333),
kInstruction_movt_al_r13_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x5555),
kInstruction_movt_al_r13_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xaaaa),
kInstruction_movt_al_r13_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xcccc),
kInstruction_movt_al_r13_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x8000),
kInstruction_movt_al_r13_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x8001),
kInstruction_movt_al_r13_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x8002),
kInstruction_movt_al_r13_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0x8003),
kInstruction_movt_al_r13_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xff80),
kInstruction_movt_al_r13_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xff81),
kInstruction_movt_al_r13_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xff82),
kInstruction_movt_al_r13_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xff83),
kInstruction_movt_al_r13_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xffe0),
kInstruction_movt_al_r13_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xfffd),
kInstruction_movt_al_r13_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xfffe),
kInstruction_movt_al_r13_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r13_0xffff),
kInstruction_movt_al_r13_0xffff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x0000),
kInstruction_movt_al_r14_0x0000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x0001),
kInstruction_movt_al_r14_0x0001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x0002),
kInstruction_movt_al_r14_0x0002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x0020),
kInstruction_movt_al_r14_0x0020,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x007d),
kInstruction_movt_al_r14_0x007d,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x007e),
kInstruction_movt_al_r14_0x007e,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x007f),
kInstruction_movt_al_r14_0x007f,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x7ffd),
kInstruction_movt_al_r14_0x7ffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x7ffe),
kInstruction_movt_al_r14_0x7ffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x7fff),
kInstruction_movt_al_r14_0x7fff,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x3333),
kInstruction_movt_al_r14_0x3333,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x5555),
kInstruction_movt_al_r14_0x5555,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xaaaa),
kInstruction_movt_al_r14_0xaaaa,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xcccc),
kInstruction_movt_al_r14_0xcccc,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x8000),
kInstruction_movt_al_r14_0x8000,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x8001),
kInstruction_movt_al_r14_0x8001,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x8002),
kInstruction_movt_al_r14_0x8002,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0x8003),
kInstruction_movt_al_r14_0x8003,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xff80),
kInstruction_movt_al_r14_0xff80,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xff81),
kInstruction_movt_al_r14_0xff81,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xff82),
kInstruction_movt_al_r14_0xff82,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xff83),
kInstruction_movt_al_r14_0xff83,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xffe0),
kInstruction_movt_al_r14_0xffe0,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xfffd),
kInstruction_movt_al_r14_0xfffd,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xfffe),
kInstruction_movt_al_r14_0xfffe,
},
{
ARRAY_SIZE(kInstruction_movt_al_r14_0xffff),
kInstruction_movt_al_r14_0xffff,
},
};
#endif // VIXL_ASSEMBLER_COND_RD_OPERAND_IMM16_T32_MOVT_H_
|
thanhdinhit/source_Example_ReactJS | src/containers/Login/ChangePasswordContainer.js | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as authenticateActions from '../../actions/authenticateActions';
import ChangePasswordComponent from '../../components/pages/Login/ChangePassword';
import * as globalAction from '../../actions/globalAction';
export const ChangePasswordContainer = React.createClass({
render: function () {
return (
<ChangePasswordComponent {...this.props} />
);
}
});
function mapStateToProps(state) {
return {
curEmp: state.authReducer.curEmp,
payload: state.authReducer.payload,
isValidToken: state.authReducer.isValidToken,
afterChangePassword: state.authReducer.afterChangePassword
};
}
function mapDispatchToProps(dispatch) {
return {
checkValidToken: bindActionCreators(authenticateActions.checkValidToken, dispatch),
changeForgetPassword: bindActionCreators(authenticateActions.changeForgetPassword, dispatch),
resetError: bindActionCreators(globalAction.resetError, dispatch),
resetState: bindActionCreators(globalAction.resetState, dispatch),
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(ChangePasswordContainer);
|
mindspore-ai/models | research/cv/U-GAT-IT/postprocess.py | <gh_stars>10-100
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""
postprocess
"""
import os
import cv2
import numpy as np
from src.modelarts_utils.config import config
def save_image(img, img_path):
"""Save a numpy image to the disk
Parameters:
img (numpy array / Tensor): image to save.
image_path (str): the path of the image.
"""
img = decode_image(img)
img_pil = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite(img_path + '.jpg', img_pil * 255.0)
def decode_image(img):
"""Decode a [1, C, H, W] Tensor to image numpy array."""
mean = 0.5
std = 0.5
return (img * std + mean).transpose(1, 2, 0)
if __name__ == '__main__':
infer_output_img = config.eval_outputdir
object_imageSize = config.img_size
bifile_dir = config.bifile_outputdir
for file in os.listdir(bifile_dir):
file_name = os.path.join(bifile_dir, file)
output = np.fromfile(file_name, np.float32).reshape(3, object_imageSize, object_imageSize)
print(output.shape)
save_image(output, infer_output_img + "/" + file.split('.')[0])
print("=======image", file, "saved success=======")
print("Generate images success!")
|
AdamCyffka/cpp-pool-tek2 | cpp_rush2_2019/Toy.hpp | <gh_stars>0
/*
** EPITECH PROJECT, 2020
** Toy.hpp
** File description:
** Toy.hpp
*/
#ifndef TMP_RUSH_TOY_HPP
#define TMP_RUSH_TOY_HPP
#include "Object.hpp"
class Toy : public Object {
public:
// Constructor and destructor
Toy();
Toy(const Toy &other);
virtual ~Toy();
// Setters and getters
virtual std::string getTitle() {return "";};
// Members Functions
};
#endif //TMP_RUSH_TOY_HPP
|
Kline-/nzbhydra2 | tests/src/test/java/org/nzbhydra/tests/ScreenshotTakingTestExecutionListener.java | /*
* (C) Copyright 2017 TheOtherP (<EMAIL>)
*
* 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.nzbhydra.tests;
import org.apache.commons.codec.binary.Base64;
import org.openqa.selenium.remote.ScreenshotException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class ScreenshotTakingTestExecutionListener extends AbstractTestExecutionListener {
private static final Logger logger = LoggerFactory.getLogger(ScreenshotTakingTestExecutionListener.class);
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
super.afterTestMethod(testContext);
try {
if (testContext.getTestException() != null && testContext.getTestException().getCause() instanceof ScreenshotException) {
File screenshotFolderFile = new File("target", "screenshots");
screenshotFolderFile.mkdirs();
byte[] data = Base64.decodeBase64(((ScreenshotException) testContext.getTestException().getCause()).getBase64EncodedScreenshot());
String screenshotFileName = (testContext.getTestMethod().getDeclaringClass().getName() + "." + testContext.getTestMethod().getName() + ".png").replaceAll("[\\\\/:*?\"<>|]", "_");
File file = new File(screenshotFolderFile, screenshotFileName);
try (OutputStream stream = new FileOutputStream(file)) {
stream.write(data);
logger.info("Wrote screenshot to " + file.getAbsolutePath());
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
fkleedorfer/webofneeds | webofneeds/won-node/src/main/java/won/node/service/persistence/DataDerivationService.java | package won.node.service.persistence;
import java.util.Optional;
import org.apache.jena.query.Dataset;
import org.apache.jena.query.DatasetFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import won.node.service.linkeddata.lookup.SocketLookup;
import won.protocol.model.*;
import won.protocol.repository.AtomRepository;
import won.protocol.repository.ConnectionRepository;
import won.protocol.repository.DatasetHolderRepository;
import won.protocol.vocabulary.WON;
@Component
public class DataDerivationService {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired()
SocketLookup socketLookup;
@Autowired
DatasetHolderRepository datasetHolderRepository;
public DataDerivationService() {
}
/**
* Performs the data derivation for the specified atom. (Currently just deletes
* any derived data in the atom, if present)
*
* @param atom
*/
public void deriveDataIfNecessary(Atom atom) {
logger.debug("Checking data derivation for atom {}", atom.getAtomURI());
DatasetHolder datasetHolder = atom.getDatatsetHolder();
Dataset dataset = null;
if (datasetHolder == null) {
dataset = DatasetFactory.createGeneral();
datasetHolder = new DatasetHolder(atom.getAtomURI(), dataset);
atom.setDatatsetHolder(datasetHolder);
} else {
dataset = datasetHolder.getDataset();
}
Dataset atomDataset = atom.getDatatsetHolder().getDataset();
String derivedDataGraphUri = atom.getAtomURI() + "#derivedData";
if (atomDataset.containsNamedModel(derivedDataGraphUri)) {
atomDataset.removeNamedModel(derivedDataGraphUri);
atom.getDatatsetHolder().setDataset(atomDataset);
logger.debug("Derived data for atom {}", atom.getAtomURI());
}
datasetHolderRepository.save(datasetHolder);
}
/**
* Performs the data derivation for the specified connection.
*
* @param con
*/
public void deriveDataIfNecessary(Connection con) {
logger.debug("Checking data derivation for connection {} (state: {})", con.getConnectionURI(),
con.getState().getURI());
DatasetHolder datasetHolder = con.getDatasetHolder();
Dataset dataset = null;
if (datasetHolder == null) {
dataset = DatasetFactory.createGeneral();
datasetHolder = new DatasetHolder(con.getConnectionURI(), dataset);
con.setDatasetHolder(datasetHolder);
} else {
dataset = datasetHolder.getDataset();
}
String derivedDataGraphUri = con.getConnectionURI() + "#derivedData";
String derivedDataMetadataGraphUri = con.getConnectionURI() + "#derivedDataMetadata";
Model metadataModel = dataset.getNamedModel(derivedDataGraphUri);
if (derivedDataIsUpToDate(con, metadataModel)) {
logger.debug("Nothing to be done for connection {}", con.getConnectionURI());
return;
}
dataset.addNamedModel(derivedDataGraphUri, deriveData(con));
dataset.addNamedModel(derivedDataMetadataGraphUri, generateDerivationMetadata(con));
con.getDatasetHolder().setDataset(dataset);
datasetHolderRepository.save(datasetHolder);
logger.debug("Derived data for connection {}", con.getConnectionURI());
}
private boolean derivedDataIsUpToDate(Connection con, Model metadataModel) {
return metadataModel.contains(
metadataModel.getResource(con.getConnectionURI().toString() + "#derivedData"),
WON.derivedForConnectionState,
metadataModel.getResource(con.getState().getURI().toString()));
}
private Model generateDerivationMetadata(Connection con) {
Model model = ModelFactory.createDefaultModel();
model.add(
model.getResource(con.getConnectionURI().toString() + "#derivedData"),
WON.derivedForConnectionState,
model.getResource(con.getState().getURI().toString()));
return model;
}
private Model deriveData(Connection con) {
Model model = ModelFactory.createDefaultModel();
Optional<SocketDefinition> socketConfig = socketLookup.getSocketConfig(con.getSocketURI());
if (socketConfig.isPresent()) {
Resource atomRes = model.getResource(con.getAtomURI().toString());
Resource targetAtomRes = model.getResource(con.getTargetAtomURI().toString());
if (con.getState() == ConnectionState.CONNECTED) {
logger.debug("adding data for connection {}", con.getConnectionURI());
socketConfig.get().getDerivationProperties().stream()
.map(u -> model.createProperty(u.toString()))
.forEach(p -> model.add(atomRes, p, targetAtomRes));
socketConfig.get().getInverseDerivationProperties().stream()
.map(u -> model.createProperty(u.toString()))
.forEach(p -> model.add(targetAtomRes, p, atomRes));
}
}
return model;
}
}
|
swember/give-me-poc | app/cells/web/dashboard/base_status_button.rb | <gh_stars>10-100
# frozen_string_literal: true
module Web
module Dashboard
# This cell renders status user
class BaseStatusButton < BaseCell
def link_to_status(status: model.state, url: url_status, confirm: nil)
@status = status
options = { method: :put }.merge(class_button).merge(tabindex).merge(data_confirm(confirm))
link_to t("dashboard.cells.button.#{@status}"), url, options
end
private
def link_status
LINK_STATUS[@status.to_sym]
end
# Link functionality caveat
# The .disabled class uses pointer-events: none to try to disable the link functionality of <a>s,
# but that CSS property is not yet standardized. In addition, even in browsers that do support
# pointer-events: none, keyboard navigation remains unaffected, meaning that sighted keyboard
# users and users of assistive technologies will still be able to activate these links. So to be
# safe, add a tabindex="-1" attribute on these links (to prevent them from receiving keyboard focus)
# and use custom JavaScript to disable their functionality.
def tabindex
return {} unless LINK_STATUS[@status.<EMAIL>sym]
{ tabindex: '-1' }
end
def class_button
{ class: "btn btn-#{COLOR_STATUS[@status.to_sym]} btn-sm #{link_status}".rstrip }
end
def data_confirm(confirm)
return {} unless confirm
{ data: { confirm: t("dashboard.cells.links.confirm.#{CONFIRM_STATUS[confirm.to_sym]}") } }
end
def url_status
raise 'Implement in child class'
end
end
end
end
|
apache/incubator-taverna-server | taverna-server-unix-forker/src/main/java/org/apache/taverna/server/unixforker/Forker.java | <reponame>apache/incubator-taverna-server
/*
*/
package org.apache.taverna.server.unixforker;
/*
* 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 static java.lang.System.err;
import static java.lang.System.getProperty;
import static java.lang.System.in;
import static java.lang.System.out;
import static java.util.Arrays.asList;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import javax.annotation.Nonnull;
/**
* A simple class that forks off processes when asked to over its standard
* input. The one complication is that it forks them off as other users, through
* the use of the <tt>sudo</tt> utility. It is Unix-specific.
*
* @author <NAME>
*/
public class Forker extends Thread {
private static String password;
private static BufferedReader br;
/**
* Helper to make reading a password from a file clearer. The password must
* be the first line of the file.
*
* @param passwordFile
* The file to load from.
* @throws IOException
* If anything goes wrong.
*/
private static void loadPassword(@Nonnull File passwordFile)
throws IOException {
try {
err.println("attempting to load password from " + passwordFile);
try (FileReader fr = new FileReader(passwordFile)) {
password = new BufferedReader(fr).readLine();
}
} catch (IOException e) {
err.println("failed to read password from file " + passwordFile
+ "described in password.file property");
throw e;
}
}
/**
* Initialization code, which runs before the main loop starts processing.
*
* @param args
* The arguments to the program.
* @throws Exception
* If anything goes wrong.
*/
public static void init(String[] args) throws Exception {
if (args.length < 1)
throw new IllegalArgumentException(
"wrong # args: must be \"program ?argument ...?\"");
if (getProperty("password.file") != null)
loadPassword(new File(getProperty("password.file")));
if (password == null)
err.println("no password.file property or empty file; "
+ "assuming password-less sudo is configured");
else
err.println("password is of length " + password.length());
br = new BufferedReader(new InputStreamReader(in));
}
/**
* The body of the main loop of this program.
*
* @param args
* The arguments to use when running the other program.
* @return Whether to repeat the loop.
* @throws Exception
* If anything goes wrong. Note that the loop is repeated if an
* exception occurs in it.
*/
public static boolean mainLoopBody(String[] args) throws Exception {
String line = br.readLine();
if (line == null)
return false;
List<String> vals = asList(line.split("[ \t]+"));
if (vals.size() != 2) {
out.println("wrong # values: must be \"username UUID\"");
return true;
}
ProcessBuilder pb = new ProcessBuilder();
pb.command()
.addAll(asList("sudo", "-u", vals.get(0), "-S", "-H", "--"));
pb.command().addAll(asList(args));
pb.command().add(vals.get(1));
Forker f = new Forker(pb);
f.setDaemon(true);
f.start();
return true;
}
/**
* The main code for this class, which turns this into an executable
* program. Runs the initialisation and then the main loop, in both cases
* with appropriate error handling.
*
* @param args
* Arguments to this program.
*/
public static void main(String... args) {
try {
init(args);
while (true) {
try {
if (!mainLoopBody(args))
break;
} catch (Exception e) {
e.printStackTrace(err);
out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
System.exit(0);
} catch (Exception e) {
e.printStackTrace(err);
System.exit(1);
}
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public Forker(ProcessBuilder pb) throws IOException {
out.println("Starting subprocess: " + pb.command());
final Process p = pb.start();
abstract class ProcessAttachedDaemon extends Thread {
public ProcessAttachedDaemon() {
setDaemon(true);
start();
}
abstract void act() throws Exception;
@Override
public final void run() {
try {
act();
p.waitFor();
} catch (InterruptedException e) {
// Just drop
} catch (Exception e) {
p.destroy();
e.printStackTrace(err);
}
}
}
new ProcessAttachedDaemon() {
@Override
void act() throws Exception {
copyFromSudo("Subprocess(out):", p.getInputStream());
}
};
new ProcessAttachedDaemon() {
@Override
void act() throws Exception {
copyFromSudo("Subprocess(err):", p.getErrorStream());
}
};
new ProcessAttachedDaemon() {
@Override
void act() throws Exception {
interactWithSudo(p.getOutputStream());
}
};
}
protected void interactWithSudo(OutputStream os) throws Exception {
if (password != null) {
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(password + "\n");
osw.flush();
}
os.close();
}
protected void copyFromSudo(String header, InputStream sudoStream)
throws Exception {
int b = '\n';
while (true) {
if (b == '\n')
out.print(header);
b = sudoStream.read();
if (b == -1)
break;
out.write(b);
out.flush();
}
sudoStream.close();
}
}
|
ScalablyTyped/SlinkyTyped | w/wordpress__api-fetch/src/main/scala/typingsSlinky/wordpressApiFetch/mod/Schema/BaseType.scala | <filename>w/wordpress__api-fetch/src/main/scala/typingsSlinky/wordpressApiFetch/mod/Schema/BaseType.scala
package typingsSlinky.wordpressApiFetch.mod.Schema
import typingsSlinky.std.Record
import typingsSlinky.wordpressApiFetch.anon.Addnew
import typingsSlinky.wordpressApiFetch.anon.Author
import typingsSlinky.wordpressApiFetch.anon.Createposts
import typingsSlinky.wordpressApiFetch.anon.Dictk
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait BaseType[T /* <: Context */] extends BaseResponse {
var capabilities: Createposts = js.native
var description: String = js.native
var hierarchical: Boolean = js.native
var labels: Addnew = js.native
var name: String = js.native
var rest_base: String = js.native
var slug: String = js.native
var supports: Author = js.native
var taxonomies: js.Array[TaxonomyKind] = js.native
var viewable: Boolean = js.native
}
object BaseType {
@scala.inline
def apply[T /* <: Context */](
_links: Record[String, js.Array[Dictk]],
capabilities: Createposts,
description: String,
hierarchical: Boolean,
labels: Addnew,
name: String,
rest_base: String,
slug: String,
supports: Author,
taxonomies: js.Array[TaxonomyKind],
viewable: Boolean
): BaseType[T] = {
val __obj = js.Dynamic.literal(_links = _links.asInstanceOf[js.Any], capabilities = capabilities.asInstanceOf[js.Any], description = description.asInstanceOf[js.Any], hierarchical = hierarchical.asInstanceOf[js.Any], labels = labels.asInstanceOf[js.Any], name = name.asInstanceOf[js.Any], rest_base = rest_base.asInstanceOf[js.Any], slug = slug.asInstanceOf[js.Any], supports = supports.asInstanceOf[js.Any], taxonomies = taxonomies.asInstanceOf[js.Any], viewable = viewable.asInstanceOf[js.Any])
__obj.asInstanceOf[BaseType[T]]
}
@scala.inline
implicit class BaseTypeMutableBuilder[Self <: BaseType[_], T /* <: Context */] (val x: Self with BaseType[T]) extends AnyVal {
@scala.inline
def setCapabilities(value: Createposts): Self = StObject.set(x, "capabilities", value.asInstanceOf[js.Any])
@scala.inline
def setDescription(value: String): Self = StObject.set(x, "description", value.asInstanceOf[js.Any])
@scala.inline
def setHierarchical(value: Boolean): Self = StObject.set(x, "hierarchical", value.asInstanceOf[js.Any])
@scala.inline
def setLabels(value: Addnew): Self = StObject.set(x, "labels", value.asInstanceOf[js.Any])
@scala.inline
def setName(value: String): Self = StObject.set(x, "name", value.asInstanceOf[js.Any])
@scala.inline
def setRest_base(value: String): Self = StObject.set(x, "rest_base", value.asInstanceOf[js.Any])
@scala.inline
def setSlug(value: String): Self = StObject.set(x, "slug", value.asInstanceOf[js.Any])
@scala.inline
def setSupports(value: Author): Self = StObject.set(x, "supports", value.asInstanceOf[js.Any])
@scala.inline
def setTaxonomies(value: js.Array[TaxonomyKind]): Self = StObject.set(x, "taxonomies", value.asInstanceOf[js.Any])
@scala.inline
def setTaxonomiesVarargs(value: TaxonomyKind*): Self = StObject.set(x, "taxonomies", js.Array(value :_*))
@scala.inline
def setViewable(value: Boolean): Self = StObject.set(x, "viewable", value.asInstanceOf[js.Any])
}
}
|
k-czajka/fh | fhCoreLite/fhPersistenceLite/src/main/java/pl/fhframework/fhPersistence/snapshots/model/SnapshotEmObjectState.java | package pl.fhframework.fhPersistence.snapshots.model;
/**
* @author <NAME>
*/
public enum SnapshotEmObjectState {
NoChange,
Persisted,
Removed
}
|
tony-jang/mongosh | packages/java-shell/src/test/resources/literal/float.js | <reponame>tony-jang/mongosh<filename>packages/java-shell/src/test/resources/literal/float.js
// command checkResultClass
0.5 |
2011master/spreadDemo-common | spreadDemo-common/src/main/java/pattern/factory/simple/service/HistogramChart.java | <reponame>2011master/spreadDemo-common<filename>spreadDemo-common/src/main/java/pattern/factory/simple/service/HistogramChart.java
package pattern.factory.simple.service;
public class HistogramChart implements Chart {
@Override
public void display() {
System.out.println("this is HIstogramChart");
}
}
|
jonasdenis/project-board | backend/project-board/src/main/java/de/adesso/projectboard/base/exceptions/UserNotFoundException.java | <filename>backend/project-board/src/main/java/de/adesso/projectboard/base/exceptions/UserNotFoundException.java<gh_stars>1-10
package de.adesso.projectboard.base.exceptions;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "User not found!")
@NoArgsConstructor
public class UserNotFoundException extends NoSuchEntityException {
public UserNotFoundException(String userId) {
super("User", userId);
}
}
|
thanujalk/carbon-identity | components/openid/org.wso2.carbon.identity.provider/src/main/java/org/wso2/carbon/identity/provider/saml/SAML2TokenBuilder.java | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.provider.saml;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.RahasData;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.utils.Base64;
import org.joda.time.DateTime;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.AttributeValue;
import org.opensaml.saml2.core.Audience;
import org.opensaml.saml2.core.AudienceRestriction;
import org.opensaml.saml2.core.Conditions;
import org.opensaml.saml2.core.Issuer;
import org.opensaml.saml2.core.Subject;
import org.opensaml.saml2.core.SubjectConfirmation;
import org.opensaml.saml2.core.SubjectConfirmationData;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.XMLObjectBuilder;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.io.Marshaller;
import org.opensaml.xml.io.MarshallerFactory;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.schema.XSBase64Binary;
import org.opensaml.xml.schema.XSString;
import org.opensaml.xml.schema.impl.XSBase64BinaryBuilder;
import org.opensaml.xml.schema.impl.XSStringBuilder;
import org.opensaml.xml.security.x509.X509Credential;
import org.opensaml.xml.signature.KeyInfo;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.Signer;
import org.opensaml.xml.signature.X509Certificate;
import org.opensaml.xml.signature.X509Data;
import org.w3c.dom.Element;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.provider.GenericIdentityProviderData;
import org.wso2.carbon.identity.provider.IdentityProviderException;
import org.wso2.carbon.identity.provider.RequestedClaimData;
import javax.xml.namespace.QName;
import java.security.cert.CertificateEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class SAML2TokenBuilder implements SAMLTokenBuilder {
public static final String CONF_KEY = "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key";
private static final Log log = LogFactory.getLog(SAML2TokenBuilder.class);
protected Assertion assertion = null;
protected AttributeStatement attributeStmt = null;
protected List<Signature> signatureList = new ArrayList<Signature>();
protected Element signedAssertion = null;
protected String appilesTo = null;
protected static XMLObject buildXMLObject(QName objectQName) throws IdentityProviderException {
XMLObjectBuilder builder = Configuration.getBuilderFactory().getBuilder(objectQName);
if (builder == null) {
throw new IdentityProviderException("Unable to retrieve builder for object QName " + objectQName);
}
return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), objectQName.getPrefix());
}
@Override
public void createStatement(GenericIdentityProviderData ipData, RahasData rahasData)
throws IdentityProviderException {
if (log.isDebugEnabled()) {
log.debug("Begin SAML statement creation.");
}
attributeStmt = (AttributeStatement) buildXMLObject(AttributeStatement.DEFAULT_ELEMENT_NAME);
Map<String, RequestedClaimData> mapClaims = ipData.getRequestedClaims();
if (rahasData.getAppliesToAddress() != null) {
appilesTo = rahasData.getAppliesToAddress();
}
Iterator<RequestedClaimData> ite = mapClaims.values().iterator();
while (ite.hasNext()) {
RequestedClaimData claim = ite.next();
String uri = claim.getUri();
int index = uri.lastIndexOf("/");
String attrName = uri.substring(index + 1, uri.length());
String attrNamespace = uri.substring(0, index);
Attribute attribute = (Attribute) buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
attribute.setName(attrName);
attribute.setNameFormat(attrNamespace);
XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
// TODO remove this else if condition after WSO2 IS supports claim
// types properly
if (claim.getUri().equals(IdentityConstants.CLAIM_PPID)) {
XSBase64BinaryBuilder ppidValueBuilder = (XSBase64BinaryBuilder) builderFactory
.getBuilder(XSBase64Binary.TYPE_NAME);
XSBase64Binary ppidValue = ppidValueBuilder.buildObject(
AttributeValue.DEFAULT_ELEMENT_NAME, XSBase64Binary.TYPE_NAME);
ppidValue.setValue(claim.getValue());
attribute.getAttributeValues().add(ppidValue);
} else {
XSStringBuilder attributeValueBuilder = (XSStringBuilder) builderFactory
.getBuilder(XSString.TYPE_NAME);
XSString stringValue = attributeValueBuilder.buildObject(
AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
stringValue.setValue(claim.getValue());
attribute.getAttributeValues().add(stringValue);
}
attributeStmt.getAttributes().add(attribute);
}
}
@Override
public void createSAMLAssertion(DateTime notAfter, DateTime notBefore, String assertionId)
throws IdentityProviderException {
assertion = (Assertion) buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME);
Conditions conditions = (Conditions) buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
conditions.setNotBefore(notBefore);
conditions.setNotOnOrAfter(notAfter);
ServerConfiguration config = ServerConfiguration.getInstance();
String host = "http://" + config.getFirstProperty("HostName");
Issuer issuer = (Issuer) buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME);
issuer.setValue(host);
assertion.setIssuer(issuer);
assertion.setIssueInstant(new DateTime());
if (appilesTo != null) {
Audience audience = (Audience) buildXMLObject(Audience.DEFAULT_ELEMENT_NAME);
audience.setAudienceURI(appilesTo);
AudienceRestriction audienceRestrictions =
(AudienceRestriction) buildXMLObject(AudienceRestriction.DEFAULT_ELEMENT_NAME);
audienceRestrictions.getAudiences().add(audience);
conditions.getAudienceRestrictions().add(audienceRestrictions);
}
assertion.setConditions(conditions);
assertion.getAttributeStatements().add(this.attributeStmt);
assertion.setID(assertionId);
Subject subject = (Subject) buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
SubjectConfirmation subjectConf =
(SubjectConfirmation) buildXMLObject(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
SubjectConfirmationData confData =
(SubjectConfirmationData) buildXMLObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
confData.setAddress(CONF_KEY);
subjectConf.setSubjectConfirmationData(confData);
subject.getSubjectConfirmations().add(subjectConf);
assertion.setSubject(subject);
}
@Override
public void setSignature(String signatureAlgorithm, X509Credential cred) throws IdentityProviderException {
Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
signature.setSigningCredential(cred);
signature.setSignatureAlgorithm(signatureAlgorithm);
signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
try {
KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
String value = Base64.encode(cred.getEntityCertificate().getEncoded());
cert.setValue(value);
data.getX509Certificates().add(cert);
keyInfo.getX509Datas().add(data);
signature.setKeyInfo(keyInfo);
} catch (CertificateEncodingException e) {
log.error("Failed to get encoded certificate", e);
throw new IdentityProviderException("Error while getting encoded certificate");
}
assertion.setSignature(signature);
signatureList.add(signature);
}
@Override
public void marshellAndSign() throws IdentityProviderException {
try {
MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(assertion);
signedAssertion = marshaller.marshall(assertion);
Signer.signObjects(signatureList);
} catch (MarshallingException e) {
log.debug(e);
throw new IdentityProviderException("errorMarshellingOrSigning", e);
} catch (Exception e) {
log.debug(e);
throw new IdentityProviderException("errorMarshellingOrSigning", e);
}
}
@Override
public Element getSAMLasDOM() throws IdentityProviderException {
return signedAssertion;
}
}
|
ReyhanPatria/hibernate-reactive | hibernate-reactive-core/src/main/java/org/hibernate/reactive/id/impl/SequenceReactiveIdentifierGenerator.java | /* Hibernate, Relational Persistence for Idiomatic Java
*
* SPDX-License-Identifier: Apache-2.0
* Copyright: Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.reactive.id.impl;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.id.Configurable;
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.reactive.session.ReactiveConnectionSupplier;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
import java.util.Properties;
import java.util.concurrent.CompletionStage;
import static org.hibernate.internal.util.config.ConfigurationHelper.getInt;
import static org.hibernate.reactive.id.impl.IdentifierGeneration.determineSequenceName;
/**
* Support for JPA's {@link javax.persistence.SequenceGenerator}.
* <p>
* This implementation supports block allocation, but does not
* guarantee that generated identifiers are sequential.
*/
public class SequenceReactiveIdentifierGenerator
extends BlockingIdentifierGenerator implements Configurable {
public static final Object[] NO_PARAMS = new Object[0];
private String sql;
private int increment;
@Override
protected int getBlockSize() {
return increment;
}
@Override
protected CompletionStage<Long> nextHiValue(ReactiveConnectionSupplier session) {
return session.getReactiveConnection().selectIdentifier( sql, NO_PARAMS ).thenApply( this::next );
}
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) {
JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
Dialect dialect = jdbcEnvironment.getDialect();
QualifiedName qualifiedSequenceName = determineSequenceName( params, serviceRegistry );
// allow physical naming strategies a chance to kick in
String renderedSequenceName = jdbcEnvironment.getQualifiedObjectNameFormatter()
.format( qualifiedSequenceName, dialect );
increment = determineIncrementForSequenceEmulation( params );
sql = dialect.getSequenceNextValString( renderedSequenceName );
}
protected int determineIncrementForSequenceEmulation(Properties params) {
return getInt( SequenceStyleGenerator.INCREMENT_PARAM, params, SequenceStyleGenerator.DEFAULT_INCREMENT_SIZE );
}
}
|
metaborg/spoofax-intellij | src/main/java/org/metaborg/intellij/idea/parsing/annotations/MetaborgSourceAnnotationInfo.java | <filename>src/main/java/org/metaborg/intellij/idea/parsing/annotations/MetaborgSourceAnnotationInfo.java<gh_stars>1-10
/*
* Copyright © 2015-2016
*
* This file is part of Spoofax for IntelliJ.
*
* 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.metaborg.intellij.idea.parsing.annotations;
import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.context.*;
/**
* Contains the collected annotation info.
*/
public final class MetaborgSourceAnnotationInfo {
private final FileObject resource;
private final String text;
private final IContext context;
/**
* Initializes a new instance of the {@link MetaborgSourceAnnotationInfo} class.
*
* @param resource The annotated resource.
* @param text The annotated resource's content.
* @param context The context.
*/
public MetaborgSourceAnnotationInfo(final FileObject resource, final String text, final IContext context) {
this.resource = resource;
this.text = text;
this.context = context;
}
/**
* Gets the annotated resource.
*
* @return The resource.
*/
public FileObject resource() { return this.resource; }
/**
* Gets the annotated resource's content.
*
* @return The content.
*/
public String text() { return this.text; }
/**
* Gets the context.
*
* @return The context.
*/
public IContext context() { return this.context; }
}
|
Testiduk/gitlabhq | lib/gitlab/background_migration/update_vulnerabilities_to_dismissed.rb | # frozen_string_literal: true
module Gitlab
module BackgroundMigration
# rubocop: disable Style/Documentation
class UpdateVulnerabilitiesToDismissed
def perform(project_id)
end
end
end
end
Gitlab::BackgroundMigration::UpdateVulnerabilitiesToDismissed.prepend_mod_with('Gitlab::BackgroundMigration::UpdateVulnerabilitiesToDismissed')
|
LaudateCorpus1/ccs-pycalendar | src/pycalendar/icalendar/itipdefinitions.py | ##
# Copyright (c) 2007-2013 <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
# 2446 Section 3
cICalMethod_PUBLISH = "PUBLISH"
cICalMethod_REQUEST = "REQUEST"
cICalMethod_REFRESH = "REFRESH"
cICalMethod_CANCEL = "CANCEL"
cICalMethod_ADD = "ADD"
cICalMethod_REPLY = "REPLY"
cICalMethod_COUNTER = "COUNTER"
cICalMethod_DECLINECOUNTER = "DECLINECOUNTER"
# 2447 Section 2.4
cICalMIMEMethod_PUBLISH = "publish"
cICalMIMEMethod_REQUEST = "request"
cICalMIMEMethod_REFRESH = "refresh"
cICalMIMEMethod_CANCEL = "cancel"
cICalMIMEMethod_ADD = "add"
cICalMIMEMethod_REPLY = "reply"
cICalMIMEMethod_COUNTER = "counter"
cICalMIMEMethod_DECLINECOUNTER = "declinecounter"
cICalMIMEComponent_VEVENT = "vevent"
cICalMIMEComponent_VTODO = "vtodo"
cICalMIMEComponent_VJOURNAL = "vjournal"
cICalMIMEComponent_VFREEBUSY = "vfreebusy"
cICalMIMEComponent_VAVAILABILITY = "vavailability"
# VPOLL extensions draft-york-vpoll-00.txt
# Section 6.1
cICalMethod_POLLSTATUS = "POLLSTATUS"
cICalMIMEMethod_POLLSTATUS = "pollstatus"
cICalMIMEComponent_VPOLL = "vpoll"
|
cyberbibby/UnrealGDK | SpatialGDK/Source/SpatialGDK/Public/Interop/RPCs/RPCStore.h | <filename>SpatialGDK/Source/SpatialGDK/Public/Interop/RPCs/RPCStore.h
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#pragma once
#include "Interop/Connection/SpatialGDKSpanId.h"
#include "Schema/RPCPayload.h"
#include "SpatialConstants.h"
#include "SpatialView/EntityComponentId.h"
DECLARE_DELEGATE_RetVal_OneParam(bool, ActorCanExtractRPCDelegate, Worker_EntityId);
DECLARE_DELEGATE_FourParams(ExtractRPCDelegate, const FUnrealObjectRef&, const SpatialGDK::RPCSender&, SpatialGDK::RPCPayload,
TOptional<uint64>);
DECLARE_DELEGATE_RetVal_OneParam(bool, DoesEntityIdHaveValidObjectDelegate, Worker_EntityId);
namespace SpatialGDK
{
struct EntityRPCType
{
EntityRPCType(Worker_EntityId EntityId, ERPCType Type)
: EntityId(EntityId)
, Type(Type)
{
}
Worker_EntityId EntityId;
ERPCType Type;
friend bool operator==(const EntityRPCType& Lhs, const EntityRPCType& Rhs)
{
return Lhs.EntityId == Rhs.EntityId && Lhs.Type == Rhs.Type;
}
friend uint32 GetTypeHash(EntityRPCType Value)
{
return HashCombine(::GetTypeHash(static_cast<int64>(Value.EntityId)), ::GetTypeHash(static_cast<uint32>(Value.Type)));
}
};
enum class EPushRPCResult : uint8
{
Success,
QueueOverflowed,
DropOverflowed,
HasAckAuthority,
NoRingBufferAuthority,
EntityBeingCreated
};
struct PendingUpdate
{
PendingUpdate(Schema_ComponentUpdate* InUpdate)
: Update(InUpdate)
{
}
Schema_ComponentUpdate* Update;
TArray<FSpatialGDKSpanId> SpanIds;
};
struct PendingRPCPayload
{
PendingRPCPayload(const RPCPayload& InPayload, const FSpatialGDKSpanId& SpanId)
: Payload(InPayload)
, SpanId(SpanId)
{
}
RPCPayload Payload;
FSpatialGDKSpanId SpanId;
};
struct FRPCStore
{
Schema_ComponentUpdate* GetOrCreateComponentUpdate(EntityComponentId EntityComponentIdPair, const FSpatialGDKSpanId& SpanId = {});
Schema_ComponentData* GetOrCreateComponentData(EntityComponentId EntityComponentIdPair);
void AddSpanIdForComponentUpdate(EntityComponentId EntityComponentIdPair, const FSpatialGDKSpanId& SpanId);
TMap<EntityRPCType, uint64> LastSentRPCIds;
TMap<EntityComponentId, PendingUpdate> PendingComponentUpdatesToSend;
TMap<EntityComponentId, Schema_ComponentData*> PendingRPCsOnEntityCreation;
};
} // namespace SpatialGDK
|
matthiasdiener/radeon_compute_profiler | Src/HSAFdnCommon/HSAAgentIterateReplacer.cpp | <reponame>matthiasdiener/radeon_compute_profiler
//==============================================================================
// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief This file contains a class to replace a user-specified agent
/// iterator callback
//==============================================================================
#include "GlobalSettings.h"
#include "HSAAgentIterateReplacer.h"
#include "HSAAgentUtils.h"
unsigned int HSAAgentIterateReplacer::m_gpuAgentCount = 0;
HSAAgentIterateReplacer::HSAAgentIteratorCallback HSAAgentIterateReplacer::m_userSepcifiedIterateAgentsCallback = nullptr;
CoreApiTable* HSAAgentIterateReplacer::m_pRealCoreFunctions = nullptr;
std::unordered_map<uint64_t, unsigned int> HSAAgentIterateReplacer::m_agentHandleToGPUIndexMap;
HSAAgentIterateReplacer::HSAAgentIteratorCallback HSAAgentIterateReplacer::GetAgentIterator(HSAAgentIterateReplacer::HSAAgentIteratorCallback userCallback, CoreApiTable* pRealCoreFunctions)
{
m_gpuAgentCount = 0;
m_userSepcifiedIterateAgentsCallback = nullptr;
m_pRealCoreFunctions = pRealCoreFunctions;
m_userSepcifiedIterateAgentsCallback = userCallback;
return ReplacedIterateAgentsCallback;
}
hsa_status_t HSAAgentIterateReplacer::ReplacedIterateAgentsCallback(hsa_agent_t agent, void* data)
{
char agentName[512];
if (HSA_STATUS_SUCCESS == m_pRealCoreFunctions->hsa_agent_get_info_fn(agent, HSA_AGENT_INFO_NAME, agentName))
{
HSAAgentsContainer::Instance()->AddAgent(agent, agentName);
}
hsa_status_t retVal = HSA_STATUS_SUCCESS;
bool callUserSpecifiedCallback = true;
hsa_device_type_t deviceType;
if (nullptr != m_userSepcifiedIterateAgentsCallback)
{
// Query type of device
hsa_status_t status = m_pRealCoreFunctions->hsa_agent_get_info_fn(agent, HSA_AGENT_INFO_DEVICE, &deviceType);
if (HSA_STATUS_SUCCESS == status)
{
if (HSA_DEVICE_TYPE_GPU == deviceType)
{
if (GlobalSettings::GetInstance()->m_params.m_bForceSingleGPU && m_gpuAgentCount != GlobalSettings::GetInstance()->m_params.m_uiForcedGpuIndex)
{
callUserSpecifiedCallback = false;
}
else
{
m_agentHandleToGPUIndexMap[agent.handle] = m_gpuAgentCount;
}
m_gpuAgentCount++;
}
}
}
if (callUserSpecifiedCallback)
{
retVal = m_userSepcifiedIterateAgentsCallback(agent, data);
}
return retVal;
}
bool HSAAgentIterateReplacer::GetAgentGPUIndex(uint64_t agentHandle, unsigned int& gpuIndex)
{
bool retVal = false;
if (m_agentHandleToGPUIndexMap.find(agentHandle) != m_agentHandleToGPUIndexMap.end())
{
retVal = true;
gpuIndex = m_agentHandleToGPUIndexMap[agentHandle];
}
return retVal;
}
|
reddcoin-project/ReddConnect | src/players/admin.py | <reponame>reddcoin-project/ReddConnect<gh_stars>1-10
#
# This sets up how models are displayed
# in the web admin interface.
#
from django import forms
#from django.db import models
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
#from django.contrib.admin import widgets
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
#from django.contrib.auth.models import User
from src.players.models import PlayerDB
#from src.typeclasses.models import Attribute
from src.utils import create
# handle the custom User editor
class PlayerDBChangeForm(UserChangeForm):
class Meta:
model = PlayerDB
username = forms.RegexField(label="Username",
max_length=30,
regex=r'^[\w. @+-]+$',
widget=forms.TextInput(attrs={'size':'30'}),
error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")
def clean_username(self):
username = self.cleaned_data['username']
if username.upper() == self.instance.username.upper():
return username
elif PlayerDB.objects.filter(username__iexact=username):
raise forms.ValidationError('A player with that name already exists.')
return self.cleaned_data['username']
class PlayerDBCreationForm(UserCreationForm):
class Meta:
model = PlayerDB
username = forms.RegexField(label="Username",
max_length=30,
regex=r'^[\w. @+-]+$',
widget=forms.TextInput(attrs={'size':'30'}),
error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
help_text = "30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")
def clean_username(self):
username = self.cleaned_data['username']
if PlayerDB.objects.filter(username__iexact=username):
raise forms.ValidationError('A player with that name already exists.')
return username
# # The Player editor
# class AttributeForm(forms.ModelForm):
# "Defines how to display the atttributes"
# class Meta:
# model = Attribute
# db_key = forms.CharField(label="Key",
# widget=forms.TextInput(attrs={'size':'15'}))
# db_value = forms.CharField(label="Value",
# widget=forms.Textarea(attrs={'rows':'2'}))
# class AttributeInline(admin.TabularInline):
# "Inline creation of player attributes"
# model = Attribute
# extra = 0
# form = AttributeForm
# fieldsets = (
# (None, {'fields' : (('db_key', 'db_value'))}),)
class PlayerForm(forms.ModelForm):
"Defines how to display Players"
class Meta:
model = PlayerDB
db_key = forms.RegexField(label="Username",
initial="PlayerDummy",
max_length=30,
regex=r'^[\w. @+-]+$',
required=False,
widget=forms.TextInput(attrs={'size':'30'}),
error_messages = {'invalid': "This value may contain only letters, spaces, numbers and @/./+/-/_ characters."},
help_text = "This should be the same as the connected Player's key name. 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only.")
db_typeclass_path = forms.CharField(label="Typeclass",
initial=settings.BASE_PLAYER_TYPECLASS,
widget=forms.TextInput(attrs={'size':'78'}),
help_text="Required. Defines what 'type' of entity this is. This variable holds a Python path to a module with a valid Evennia Typeclass. Defaults to settings.BASE_PLAYER_TYPECLASS.")
#db_permissions = forms.CharField(label="Permissions",
# initial=settings.PERMISSION_PLAYER_DEFAULT,
# required=False,
# widget=forms.TextInput(attrs={'size':'78'}),
# help_text="In-game permissions. A comma-separated list of text strings checked by certain locks. They are often used for hierarchies, such as letting a Player have permission 'Wizards', 'Builders' etc. A Player permission can be overloaded by the permissions of a controlled Character. Normal players use 'Players' by default.")
db_lock_storage = forms.CharField(label="Locks",
widget=forms.Textarea(attrs={'cols':'100', 'rows':'2'}),
required=False,
help_text="In-game lock definition string. If not given, defaults will be used. This string should be on the form <i>type:lockfunction(args);type2:lockfunction2(args);...")
db_cmdset_storage = forms.CharField(label="cmdset",
initial=settings.CMDSET_PLAYER,
widget=forms.TextInput(attrs={'size':'78'}),
required=False,
help_text="python path to player cmdset class (set in settings.CMDSET_PLAYER by default)")
class PlayerInline(admin.StackedInline):
"Inline creation of Player"
model = PlayerDB
template = "admin/players/stacked.html"
form = PlayerForm
fieldsets = (
("In-game Permissions and Locks",
{'fields': ('db_lock_storage',),
#{'fields': ('db_permissions', 'db_lock_storage'),
'description':"<i>These are permissions/locks for in-game use. They are unrelated to website access rights.</i>"}),
("In-game Player data",
{'fields':('db_typeclass_path', 'db_cmdset_storage'),
'description':"<i>These fields define in-game-specific properties for the Player object in-game.</i>"}),
)
extra = 1
max_num = 1
class PlayerDBAdmin(BaseUserAdmin):
"This is the main creation screen for Users/players"
list_display = ('username', 'email', 'is_staff', 'is_superuser')
form = PlayerDBChangeForm
add_form = PlayerDBCreationForm
fieldsets = (
(None, {'fields': ('username', 'password', 'email')}),
('Website profile', {'fields': ('first_name', 'last_name'),
'description': "<i>These are not used in the default system.</i>"}),
('Website dates', {'fields': ('last_login', 'date_joined'),
'description': '<i>Relevant only to the website.</i>'}),
('Website Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',
'user_permissions', 'groups'),
'description': "<i>These are permissions/permission groups for accessing the admin site. They are unrelated to in-game access rights.</i>"}),
('Game Options', {'fields': ('db_typeclass_path', 'db_cmdset_storage', 'db_lock_storage'),
'description': '<i>These are attributes that are more relevant to gameplay.</i>'}))
#('Game Options', {'fields': ('db_typeclass_path', 'db_cmdset_storage', 'db_permissions', 'db_lock_storage'),
# 'description': '<i>These are attributes that are more relevant to gameplay.</i>'}))
add_fieldsets = (
(None,
{'fields': ('username', '<PASSWORD>', '<PASSWORD>', 'email'),
'description':"<i>These account details are shared by the admin system and the game.</i>"},),)
# TODO! Remove User reference!
def save_formset(self, request, form, formset, change):
"Run all hooks on the player object"
super(PlayerDBAdmin, self).save_formset(request, form, formset, change)
userobj = form.instance
userobj.name = userobj.username
if not change:
#uname, passwd, email = str(request.POST.get(u"username")), \
# str(request.POST.get(u"<PASSWORD>")), str(request.POST.get(u"email"))
typeclass = str(request.POST.get(u"playerdb_set-0-db_typeclass_path"))
create.create_player("", "", "",
user=userobj,
typeclass=typeclass,
player_dbobj=userobj)
admin.site.register(PlayerDB, PlayerDBAdmin)
|
delgadofarid/djl | api/src/main/java/ai/djl/training/initializer/ConstantInitializer.java | <filename>api/src/main/java/ai/djl/training/initializer/ConstantInitializer.java
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.training.initializer;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
/** Initializer that generates tensors with constant values. */
public class ConstantInitializer implements Initializer {
private float value;
/**
* Creates a Constant Initializer.
*
* @param value the value to fill
*/
public ConstantInitializer(float value) {
this.value = value;
}
/**
* Initializes a single {@link NDArray}.
*
* @param manager the {@link NDManager} to create the new {@link NDArray} in
* @param shape the {@link Shape} for the new NDArray
* @param dataType the {@link DataType} for the new NDArray
* @return the {@link NDArray} initialized with the manager and shape
*/
@Override
public NDArray initialize(NDManager manager, Shape shape, DataType dataType) {
return manager.full(shape, value, dataType);
}
}
|
npocmaka/Windows-Server-2003 | base/hals/halia64/ia64/xxstubs.c | <gh_stars>10-100
//
/*++
Copyright (c) 1991 Microsoft Corporation
Module Name:
stubs.c
Abstract:
This implements the HAL routines which don't do anything on IA64.
Author:
<NAME> (jvert) 11-Jul-1991
Revision History:
--*/
#include "halp.h"
VOID
HalSaveState(
VOID
)
/*++
Routine Description:
Saves the system state into the restart block. Currently does nothing.
Arguments:
None
Return Value:
Does not return
--*/
{
HalDebugPrint(( HAL_ERROR, "HAL: HalSaveState called - System stopped\n" ));
KeBugCheck(0);
}
BOOLEAN
HalDataBusError(
VOID
)
/*++
Routine Description:
Called when a data bus error occurs. There is no way to fix this on
IA64.
Arguments:
None
Return Value:
FALSE
--*/
{
HalDebugPrint(( HAL_ERROR, "HAL: HalDataBusError called - System stopped\n" ));
KeBugCheck(0);
return(FALSE);
}
BOOLEAN
HalInstructionBusError(
VOID
)
/*++
Routine Description:
Called when an instruction bus error occurs. There is no way to fix this
on IA64.
Arguments:
None
Return Value:
FALSE
--*/
{
HalDebugPrint(( HAL_ERROR, "HAL: HalInstructionBusError called - System stopped\n" ));
KeBugCheck(0);
return(FALSE);
}
//*******************************************************************
// Added by T. Kjos to temporarily stub out unused functions that
// are needed at link time. These should all be removed as the
// "real" versions are developed.
// Function called for by all stubbed functions. Can be used for
// breakpoints on unimplemented functions
VOID DbgNop() { return; }
// Macro for stubbed function. If function is called then BugCheck
#define STUBFUNC(Func) \
ULONG Func () \
{ \
HalDebugPrint(( HAL_FATAL_ERROR, "HAL: " # Func " - not yet implemented - System stopped\n" )); \
DbgNop(); \
KeBugCheck(0); \
}
// Macro for stubbed function. If function is called then print
// warning and continue
#define STUBFUNC_NOP(Func) \
ULONG Func () \
{ \
HalDebugPrint(( HAL_INFO, "HAL: " # Func " - not yet implemented\n" )); \
DbgNop(); \
return TRUE; \
}
// Macro for stubbed void function. If function is called then print
// warning and continue
#define STUBVOIDFUNC_NOP(Func) \
VOID Func ( VOID ) \
{ \
HalDebugPrint(( HAL_INFO, "HAL: " # Func " - not yet implemented\n" )); \
DbgNop(); \
return; \
}
// Macro for stubbed void function with 3 PVOID arguments.
// If function is called then print warning and continue
#define STUBVOIDFUNC3PVOID_NOP(Func) \
VOID Func ( PVOID pv0, PVOID pv1, PVOID pv2 ) \
{ \
HalDebugPrint(( HAL_INFO, "HAL: " # Func " - not yet implemented\n" )); \
DbgNop(); \
return; \
}
// Macro for stubbed ULONG values
#define STUBULONG(UlongVar) ULONG UlongVar = 0;
// Functions that are not yet implemented...
STUBVOIDFUNC_NOP(HalpResetAllProcessors)
STUBFUNC_NOP(HalpSetClockBeforeSleep)
STUBFUNC_NOP(HalpSetClockAfterSleep)
STUBFUNC_NOP(HalpSetWakeAlarm)
STUBFUNC(HalpRemapVirtualAddress)
STUBFUNC_NOP(HalaAcpiTimerInit)
STUBFUNC_NOP(Stub_LockNMILock)
STUBFUNC_NOP(HalAcpiTimerCarry)
STUBVOIDFUNC3PVOID_NOP(HalpPowerStateCallback)
|
wiechula/AliPhysics | PWGDQ/reducedTree/AliReducedVarCut.cxx | /*
***********************************************************
Implementation of AliReducedVarCut class.
Contact: <EMAIL>
2016/09/07
*********************************************************
*/
#include <iostream>
using std::cout;
using std::endl;
#ifndef ALIREDUCEDVARCUT_H
#include "AliReducedVarCut.h"
#endif
#include "AliReducedBaseTrack.h"
#include "AliReducedBaseEvent.h"
#include "AliReducedPairInfo.h"
#include "AliReducedVarManager.h"
ClassImp(AliReducedVarCut)
//____________________________________________________________________________
AliReducedVarCut::AliReducedVarCut() :
AliReducedInfoCut(),
fNCuts(0)
{
//
// default constructor
//
for(Int_t i=0; i<kNMaxCuts; ++i) {
fCutVariables[i] = AliReducedVarManager::kNothing;
fDependentVariable[i] = AliReducedVarManager::kNothing;
fCutLow[i] = 0.;
fCutHigh[i] = 0.;
fCutExclude[i] = kFALSE;
fCutHasDependentVariable[i] = kFALSE;
fDependentVariableCutLow[i] = 0.;
fDependentVariableCutHigh[i] = 0.;
fDependentVariableExclude[i] = kFALSE;
fFuncCutLow[i] = 0x0;
fFuncCutHigh[i] = 0x0;
}
}
//____________________________________________________________________________
AliReducedVarCut::AliReducedVarCut(const Char_t* name, const Char_t* title) :
AliReducedInfoCut(name, title),
fNCuts(0)
{
//
// named constructor
//
for(Int_t i=0; i<kNMaxCuts; ++i) {
fCutVariables[i] = AliReducedVarManager::kNothing;
fDependentVariable[i] = AliReducedVarManager::kNothing;
fCutLow[i] = 0.;
fCutHigh[i] = 0.;
fCutExclude[i] = kFALSE;
fCutHasDependentVariable[i] = kFALSE;
fDependentVariableCutLow[i] = 0.;
fDependentVariableCutHigh[i] = 0.;
fDependentVariableExclude[i] = kFALSE;
fFuncCutLow[i] = 0x0;
fFuncCutHigh[i] = 0x0;
}
}
//____________________________________________________________________________
AliReducedVarCut::~AliReducedVarCut() {
//
// destructor
//
}
//____________________________________________________________________________
void AliReducedVarCut::AddCut(AliReducedVarManager::Variables var, Float_t cutLow, Float_t cutHigh, Bool_t exclude /*= kFALSE*/,
AliReducedVarManager::Variables dependentVar /*=AliReducedVarManager::kNothing*/,
Float_t depCutLow /*=0.*/, Float_t depCutHigh /*=0.*/, Bool_t depCutExclude /*=kFALSE*/) {
//
// Add a cut
//
if(fNCuts==kNMaxCuts) {
cout << "AliReducedVarCut::AddCut() Too many cuts added! Reduce the number of cuts in your config macro or increase the maximum allowed limit!" << endl;
cout << " Cut not added !!" << endl;
return;
}
fCutVariables[fNCuts] = var; fCutLow[fNCuts] = cutLow; fCutHigh[fNCuts] = cutHigh; fCutExclude[fNCuts] = exclude;
AliReducedVarManager::SetUseVariable(var);
if(dependentVar != AliReducedVarManager::kNothing) {
fCutHasDependentVariable[fNCuts] = kTRUE;
fDependentVariable[fNCuts] = dependentVar;
fDependentVariableCutLow[fNCuts] = depCutLow; fDependentVariableCutHigh[fNCuts] = depCutHigh;
fDependentVariableExclude[fNCuts] = depCutExclude;
AliReducedVarManager::SetUseVariable(dependentVar);
}
fNCuts++;
}
//____________________________________________________________________________
void AliReducedVarCut::AddCut(AliReducedVarManager::Variables var, Float_t cutLow, TF1* funcCutHigh, Bool_t exclude /*= kFALSE*/,
AliReducedVarManager::Variables dependentVar /*=AliReducedVarManager::kNothing*/,
Float_t depCutLow /*=0.*/, Float_t depCutHigh /*=0.*/, Bool_t depCutExclude /*=kFALSE*/) {
//
// Add a cut with a function as a high cut
//
if(fNCuts==kNMaxCuts) {
cout << "AliReducedVarCut::AddCut() Too many cuts added! Reduce the number of cuts in your config macro or increase the maximum allowed limit!" << endl;
cout << " Cut not added !!" << endl;
return;
}
if(dependentVar == AliReducedVarManager::kNothing) {
cout << "AliReducedVarCut::AddCut() When adding a cut with a function as high limit, the dependentVar must be set otherwise this does not make sense!" << endl;
cout << " Cut not added !!" << endl;
return;
}
fCutVariables[fNCuts] = var; fCutLow[fNCuts] = cutLow; fFuncCutHigh[fNCuts] = funcCutHigh; fCutExclude[fNCuts] = exclude;
AliReducedVarManager::SetUseVariable(var);
fCutHasDependentVariable[fNCuts] = kTRUE;
fDependentVariable[fNCuts] = dependentVar;
fDependentVariableCutLow[fNCuts] = depCutLow; fDependentVariableCutHigh[fNCuts] = depCutHigh;
fDependentVariableExclude[fNCuts] = depCutExclude;
AliReducedVarManager::SetUseVariable(dependentVar);
fNCuts++;
}
//____________________________________________________________________________
void AliReducedVarCut::AddCut(AliReducedVarManager::Variables var, TF1* funcCutLow, Float_t cutHigh, Bool_t exclude /*= kFALSE*/,
AliReducedVarManager::Variables dependentVar /*=AliReducedVarManager::kNothing*/,
Float_t depCutLow /*=0.*/, Float_t depCutHigh /*=0.*/, Bool_t depCutExclude /*=kFALSE*/) {
//
// Add a cut with a function as a low cut
//
if(fNCuts==kNMaxCuts) {
cout << "AliReducedVarCut::AddCut() Too many cuts added! Reduce the number of cuts in your config macro or increase the maximum allowed limit!" << endl;
cout << " Cut not added !!" << endl;
return;
}
if(dependentVar == AliReducedVarManager::kNothing) {
cout << "AliReducedVarCut::AddCut() When adding a cut with a function as low limit, the dependentVar must be set otherwise this does not make sense!" << endl;
cout << " Cut not added !!" << endl;
return;
}
fCutVariables[fNCuts] = var; fFuncCutLow[fNCuts] = funcCutLow; fCutHigh[fNCuts] = cutHigh; fCutExclude[fNCuts] = exclude;
AliReducedVarManager::SetUseVariable(var);
fCutHasDependentVariable[fNCuts] = kTRUE;
fDependentVariable[fNCuts] = dependentVar;
fDependentVariableCutLow[fNCuts] = depCutLow; fDependentVariableCutHigh[fNCuts] = depCutHigh;
fDependentVariableExclude[fNCuts] = depCutExclude;
AliReducedVarManager::SetUseVariable(dependentVar);
fNCuts++;
}
//____________________________________________________________________________
void AliReducedVarCut::AddCut(AliReducedVarManager::Variables var, TF1* funcCutLow, TF1* funcCutHigh, Bool_t exclude /*= kFALSE*/,
AliReducedVarManager::Variables dependentVar /*=AliReducedVarManager::kNothing*/,
Float_t depCutLow /*=0.*/, Float_t depCutHigh /*=0.*/, Bool_t depCutExclude /*=kFALSE*/) {
//
// Add a cut with functions as low and high cuts
//
if(fNCuts==kNMaxCuts) {
cout << "AliReducedVarCut::AddCut() Too many cuts added! Reduce the number of cuts in your config macro or increase the maximum allowed limit!" << endl;
cout << " Cut not added !!" << endl;
return;
}
if(dependentVar == AliReducedVarManager::kNothing) {
cout << "AliReducedVarCut::AddCut() When adding a cut with functions as low and high limits, the dependentVar must be set otherwise this does not make sense!" << endl;
cout << " Cut not added !!" << endl;
return;
}
fCutVariables[fNCuts] = var; fFuncCutLow[fNCuts] = funcCutLow; fFuncCutHigh[fNCuts] = funcCutHigh; fCutExclude[fNCuts] = exclude;
AliReducedVarManager::SetUseVariable(var);
fCutHasDependentVariable[fNCuts] = kTRUE;
fDependentVariable[fNCuts] = dependentVar;
fDependentVariableCutLow[fNCuts] = depCutLow; fDependentVariableCutHigh[fNCuts] = depCutHigh;
fDependentVariableExclude[fNCuts] = depCutExclude;
AliReducedVarManager::SetUseVariable(dependentVar);
fNCuts++;
}
//____________________________________________________________________________
Bool_t AliReducedVarCut::IsSelected(TObject* obj, Float_t* values) {
//
// apply cuts
//
if(values) return IsSelected(values);
if(!values) return IsSelected(obj);
}
//____________________________________________________________________________
Bool_t AliReducedVarCut::IsSelected(TObject* obj) {
//
// apply cuts
//
if(!obj->InheritsFrom(AliReducedBaseTrack::Class())) return kFALSE;
//Fill values
Float_t values[AliReducedVarManager::kNVars];
if(obj->InheritsFrom(AliReducedBaseEvent::Class())) AliReducedVarManager::FillEventInfo((AliReducedBaseEvent*)obj, values);
if(obj->InheritsFrom(AliReducedBaseTrack::Class())) AliReducedVarManager::FillTrackInfo((AliReducedBaseTrack*)obj, values);
if(obj->InheritsFrom(AliReducedPairInfo::Class())) AliReducedVarManager::FillPairInfo((AliReducedPairInfo*)obj, values);
return IsSelected(values);
}
//____________________________________________________________________________
Bool_t AliReducedVarCut::IsSelected(Float_t* values) {
//
// apply cuts
//
for(Int_t i=0; i<fNCuts; ++i) {
//cout << "AliReducedVarCut::IsSelected() icut " << i << endl;
if(fCutHasDependentVariable[i]) {
//cout << "AliReducedVarCut::IsSelected() has dependent var " << endl;
Bool_t inRangeDep = (values[fDependentVariable[i]]>=fDependentVariableCutLow[i] && values[fDependentVariable[i]]<=fDependentVariableCutHigh[i]);
//cout << "AliReducedVarCut::IsSelected() inRangeDep/fDepVar/val/cutLow/cutHigh: " << inRangeDep
// << "/" << fDependentVariable[i] << "/" << values[fDependentVariable[i]] << "/"
// << fDependentVariableCutLow[i] << "/" << fDependentVariableCutHigh[i] << endl;
//cout << "AliReducedVarCut::IsSelected() fDependentVariableExclude: " << fDependentVariableExclude[i] << endl;
// do not apply this cut if outside of the applicability range
if(!inRangeDep && !fDependentVariableExclude[i]) continue;
if(inRangeDep && fDependentVariableExclude[i]) continue;
}
if(fFuncCutLow[i]) {
fCutLow[i] = fFuncCutLow[i]->Eval(values[fDependentVariable[i]]);
//cout << "Func low cut depVar/cutVal :: " << values[fDependentVariable[i]] << " / " << fCutLow[i] << endl;
}
if(fFuncCutHigh[i]) fCutHigh[i] = fFuncCutHigh[i]->Eval(values[fDependentVariable[i]]);
Bool_t inRange = (values[fCutVariables[i]]>=fCutLow[i] && values[fCutVariables[i]]<=fCutHigh[i]);
//cout << "AliReducedVarCut::IsSelected() inRange/fCutVariables/val/cutLow/cutHigh: " << inRange << "/" << fCutVariables[i]
// << "/" << values[fCutVariables[i]] << "/" << fCutLow[i] << "/" << fCutHigh[i] << "/" << fCutExclude[i] << endl;
if(!inRange && !fCutExclude[i]) return kFALSE;
if(inRange && fCutExclude[i]) return kFALSE;
}
return kTRUE;
}
|
redhatanalytics/oshinko-cli | rest/bkp/deploymentconfigs_test.go | <reponame>redhatanalytics/oshinko-cli
package unittest
import (
"gopkg.in/check.v1"
kapi "k8s.io/api/core/v1"
api "github.com/openshift/api/apps/v1"
"github.com/radanalyticsio/oshinko-cli/core/clusters/deploymentconfigs"
"github.com/radanalyticsio/oshinko-cli/core/clusters/podtemplates"
)
func (s *OshinkoUnitTestSuite) TestDeploymentConfig(c *check.C) {
expectedName, expectedNamespace := "testname", "testnamespace"
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig(expectedName, expectedNamespace)
c.Assert(newDeploymentConfig.Name, check.Equals, expectedName)
c.Assert(newDeploymentConfig.Namespace, check.Equals, expectedNamespace)
}
func (s *OshinkoUnitTestSuite) TestReplicas(c *check.C) {
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
expectedReplicas := 12345
newDeploymentConfig.Replicas(expectedReplicas)
c.Assert(newDeploymentConfig.Spec.Replicas, check.Equals, int32(expectedReplicas))
}
func (s *OshinkoUnitTestSuite) TestLabel(c *check.C) {
expectedName, expectedLabel := "testname", "testlabel"
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.Label(expectedName, expectedLabel)
c.Assert(newDeploymentConfig.Labels[expectedName], check.Equals, expectedLabel)
}
func (s *OshinkoUnitTestSuite) TestDeploymentPodSelector(c *check.C) {
expectedSelector, expectedValue := "testselector", "testvalue"
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.PodSelector(expectedSelector, expectedValue)
c.Assert(newDeploymentConfig.Spec.Selector[expectedSelector], check.Equals, expectedValue)
}
func (s *OshinkoUnitTestSuite) TestDeploymentPodSelectors(c *check.C) {
expectedSelectors := map[string]string{"selector1": "value1", "selector2": "value2"}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.PodSelectors(expectedSelectors)
c.Assert(newDeploymentConfig.Spec.Selector, check.DeepEquals, expectedSelectors)
}
func (s *OshinkoUnitTestSuite) TestGetPodSelectors(c *check.C) {
expectedSelectors := map[string]string{"selector1": "value1", "selector2": "value2"}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.PodSelectors(expectedSelectors)
c.Assert(newDeploymentConfig.GetPodSelectors(), check.DeepEquals, expectedSelectors)
}
func (s *OshinkoUnitTestSuite) TestRollingStrategy(c *check.C) {
expectedStrategy := api.DeploymentStrategy{Type: api.DeploymentStrategyTypeRolling}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.RollingStrategy()
c.Assert(newDeploymentConfig.Spec.Strategy, check.DeepEquals, expectedStrategy)
}
func (s *OshinkoUnitTestSuite) TestRollingStrategyParams(c *check.C) {
rp := api.RollingDeploymentStrategyParams{}
req := kapi.ResourceRequirements{}
lbls := map[string]string{"test": "value"}
anttns := map[string]string{"moretest": "morevalue"}
expectedStrategy := api.DeploymentStrategy{
Type: api.DeploymentStrategyTypeRolling,
RollingParams: &rp,
Resources: req,
Labels: lbls,
Annotations: anttns}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.RollingStrategyParams(&rp, req, lbls, anttns)
c.Assert(newDeploymentConfig.Spec.Strategy, check.DeepEquals, expectedStrategy)
}
func (s *OshinkoUnitTestSuite) TestRecreateStrategy(c *check.C) {
expectedStrategy := api.DeploymentStrategy{Type: api.DeploymentStrategyTypeRecreate}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.RecreateStrategy()
c.Assert(newDeploymentConfig.Spec.Strategy, check.DeepEquals, expectedStrategy)
}
func (s *OshinkoUnitTestSuite) TestRecreateStrategyParams(c *check.C) {
rp := api.RecreateDeploymentStrategyParams{}
req := kapi.ResourceRequirements{}
lbls := map[string]string{"test": "value"}
anttns := map[string]string{"moretest": "morevalue"}
expectedStrategy := api.DeploymentStrategy{
Type: api.DeploymentStrategyTypeRecreate,
RecreateParams: &rp,
Resources: req,
Labels: lbls,
Annotations: anttns}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.RecreateStrategyParams(&rp, req, lbls, anttns)
c.Assert(newDeploymentConfig.Spec.Strategy, check.DeepEquals, expectedStrategy)
}
func (s *OshinkoUnitTestSuite) TestCustomStrategyParams(c *check.C) {
rp := api.CustomDeploymentStrategyParams{}
req := kapi.ResourceRequirements{}
lbls := map[string]string{"test": "value"}
anttns := map[string]string{"moretest": "morevalue"}
expectedStrategy := api.DeploymentStrategy{
Type: api.DeploymentStrategyTypeCustom,
CustomParams: &rp,
Resources: req,
Labels: lbls,
Annotations: anttns}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.CustomStrategyParams(&rp, req, lbls, anttns)
c.Assert(newDeploymentConfig.Spec.Strategy, check.DeepEquals, expectedStrategy)
}
func (s *OshinkoUnitTestSuite) TestTriggerOnConfigChange(c *check.C) {
expectedTriggers := []api.DeploymentTriggerPolicy{
api.DeploymentTriggerPolicy{Type: api.DeploymentTriggerOnConfigChange}}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.TriggerOnConfigChange()
c.Assert(newDeploymentConfig.Spec.Triggers, check.DeepEquals, expectedTriggers)
}
func (s *OshinkoUnitTestSuite) TestTriggerOnImageChange(c *check.C) {
imageChangeParams1 := api.DeploymentTriggerImageChangeParams{
From: kapi.ObjectReference{
Name: "imagename1",
Namespace: "namespace1"}}
imageChangeParams1Copy := api.DeploymentTriggerImageChangeParams{
From: kapi.ObjectReference{
Name: "imagename1",
Namespace: "namespace1"}}
imageChangeParams2 := api.DeploymentTriggerImageChangeParams{
From: kapi.ObjectReference{
Name: "imagename2",
Namespace: "namespace2"}}
expectedTriggers := []api.DeploymentTriggerPolicy{
api.DeploymentTriggerPolicy{
Type: api.DeploymentTriggerOnImageChange,
ImageChangeParams: &imageChangeParams1}}
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
newDeploymentConfig.TriggerOnImageChange(&imageChangeParams1)
c.Assert(newDeploymentConfig.Spec.Triggers, check.DeepEquals, expectedTriggers)
newDeploymentConfig.TriggerOnImageChange(&imageChangeParams1Copy)
c.Assert(newDeploymentConfig.Spec.Triggers, check.DeepEquals, expectedTriggers)
newDeploymentConfig.TriggerOnImageChange(&imageChangeParams2)
expectedTriggers = append(expectedTriggers, api.DeploymentTriggerPolicy{
Type: api.DeploymentTriggerOnImageChange,
ImageChangeParams: &imageChangeParams2})
c.Assert(newDeploymentConfig.Spec.Triggers, check.DeepEquals, expectedTriggers)
}
func (s *OshinkoUnitTestSuite) TestPodTemplateSpec(c *check.C) {
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
expectedPodTemplateSpec := podtemplates.OPodTemplateSpec{}
newDeploymentConfig.PodTemplateSpec(&expectedPodTemplateSpec)
c.Assert(newDeploymentConfig.Spec.Template, check.Equals, &expectedPodTemplateSpec.PodTemplateSpec)
c.Assert(*newDeploymentConfig.Spec.Template, check.DeepEquals, expectedPodTemplateSpec.PodTemplateSpec)
}
func (s *OshinkoUnitTestSuite) TestGetPodTemplateSpecLabels(c *check.C) {
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
expectedLabels := map[string]string{}
c.Assert(newDeploymentConfig.GetPodTemplateSpecLabels(), check.DeepEquals, expectedLabels)
podTemplateSpec := podtemplates.OPodTemplateSpec{}
expectedLabels["test"] = "value"
podTemplateSpec.SetLabels(expectedLabels)
newDeploymentConfig.PodTemplateSpec(&podTemplateSpec)
c.Assert(newDeploymentConfig.GetPodTemplateSpecLabels(), check.DeepEquals, expectedLabels)
}
func (s *OshinkoUnitTestSuite) TestFindPort(c *check.C) {
newDeploymentConfig := deploymentconfigs.NewODeploymentConfig("name", "namespace")
c.Assert(newDeploymentConfig.FindPort("testport"), check.Equals, 0)
podTemplateSpec := podtemplates.OPodTemplateSpec{
kapi.PodTemplateSpec{
Spec: kapi.PodSpec{
Containers: []kapi.Container{
kapi.Container{
Ports: []kapi.ContainerPort{
kapi.ContainerPort{
Name: "testport",
ContainerPort: 12345}}}}}}}
newDeploymentConfig.PodTemplateSpec(&podTemplateSpec)
c.Assert(newDeploymentConfig.FindPort("testport"), check.Equals, 12345)
c.Assert(newDeploymentConfig.FindPort("badport"), check.Equals, 0)
}
|
xmakina/dscript | dist/Interpreter/Expr/VisitUnaryExpr.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Types_1 = require("../../Types");
const Utils_1 = require("../Utils");
exports.default = (interpreter) => async (expr) => {
const right = await interpreter.evaluate(expr.right);
switch (expr.operator.type) {
case Types_1.TokenType.BANG:
return !Utils_1.isTruthy(right);
case Types_1.TokenType.MINUS:
return -right;
}
return null;
};
|
glow/glow2 | test/speed/glow/NodeList/traversal/jquery142-tests.js | woosh.addTests('jq-142', {
'$preTest': function(prevTest, nextTest) {
if (!prevTest) {
}
},
'NodeList#ancestors': new woosh.TimeTest(1, function() {
return $('.tocline3').parents().length;
}),
'NodeList#parent': new woosh.TimeTest(1, function() {
return $('.tocline3').parent().length;
}),
'NodeList#get': new woosh.TimeTest(1, function() {
return $('.toc').find('li').length;
}),
'NodeList#prev': new woosh.TimeTest(1, function() {
return $('.tocline3').prev().length;
}),
'NodeList#next': new woosh.TimeTest(1, function() {
return $('.tocline3').next().length;
}),
'NodeList#children': new woosh.TimeTest(1, function() {
return $('.toc').children().length;
})
}); |
perfectrecall/aws-sdk-cpp | aws-cpp-sdk-iotsitewise/source/model/MetricProcessingConfig.cpp | <filename>aws-cpp-sdk-iotsitewise/source/model/MetricProcessingConfig.cpp
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iotsitewise/model/MetricProcessingConfig.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace IoTSiteWise
{
namespace Model
{
MetricProcessingConfig::MetricProcessingConfig() :
m_computeLocation(ComputeLocation::NOT_SET),
m_computeLocationHasBeenSet(false)
{
}
MetricProcessingConfig::MetricProcessingConfig(JsonView jsonValue) :
m_computeLocation(ComputeLocation::NOT_SET),
m_computeLocationHasBeenSet(false)
{
*this = jsonValue;
}
MetricProcessingConfig& MetricProcessingConfig::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("computeLocation"))
{
m_computeLocation = ComputeLocationMapper::GetComputeLocationForName(jsonValue.GetString("computeLocation"));
m_computeLocationHasBeenSet = true;
}
return *this;
}
JsonValue MetricProcessingConfig::Jsonize() const
{
JsonValue payload;
if(m_computeLocationHasBeenSet)
{
payload.WithString("computeLocation", ComputeLocationMapper::GetNameForComputeLocation(m_computeLocation));
}
return payload;
}
} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws
|
blackmoonfank/docker-rutorrent | plugins/throttle/lang/nl.js | <gh_stars>1-10
/*
* PLUGIN THROTTLE
*
* Dutch language file.
*
* Author: rascalli (<EMAIL>)
*/
theUILang.throttles = "Beperkingen";
theUILang.throttle = "Snelheidsbeperking";
theUILang.mnuThrottle = "Zet beperking";
theUILang.mnuUnlimited = "Geen Beperking";
theUILang.channelName = "Naam";
theUILang.channelDefault = "Default channel";
thePlugins.get("throttle").langLoaded(); |
aml-org/als | als-server/shared/src/main/scala/org/mulesoft/als/server/modules/workspace/TaskManagerState.scala | <filename>als-server/shared/src/main/scala/org/mulesoft/als/server/modules/workspace/TaskManagerState.scala
package org.mulesoft.als.server.modules.workspace
sealed abstract class TaskManagerState(state: String)
object Idle extends TaskManagerState("IDLE")
object ProcessingProject extends TaskManagerState("PROCESSING_PROJECT")
object ProcessingStaged extends TaskManagerState("PROCESSING_STAGED")
object NotAvailable extends TaskManagerState("UNAVAILABLE")
object ProcessingFile extends TaskManagerState("PROCESSING_FILE")
|
LDTorres/GASE-SUPERLOGOS | controllers/database.go | <filename>controllers/database.go
package controllers
import (
"GASE-SUPERLOGOS/models"
"fmt"
)
// DatabaseController operations for Countries
type DatabaseController struct {
BaseController
}
// URLMapping ...
func (c *DatabaseController) URLMapping() {
c.Mapping("GenerateDatabase", c.GenerateDatabase)
}
// Get Generate Database ...
// @Title Generate Database
// @Description Generate Database
// @router /generate [get]
func (c *DatabaseController) GenerateDatabase() {
// Add defaults to database
count, _ := models.AddDefaultDataCurrencies()
if count > 0 {
fmt.Println("Added Currencies : ", count)
}
count, _ = models.AddDefaultDataCountries()
if count > 0 {
fmt.Println("Added Countries : ", count)
}
count, _ = models.AddDefaultDataSectors()
if count > 0 {
fmt.Println("Added Sectors : ", count)
}
/* count, _ = models.AddDefaultDataActivities()
if count > 0 {
fmt.Println("Added Activities : ", count)
} */
models.AddDefaultDataGateways()
models.AddRelationsGatewaysCurrencies()
/*
count, _ = models.AddDefaultDataServices()
if count > 0 {
fmt.Println("Added Services : ", count)
}
*/
// models.AddDefaultDataPrices()
models.AddDefaultDataUsers()
c.Data["json"] = MessageResponse{
Message: "Generated Database",
PrettyMessage: "Datos Generados",
}
c.ServeJSON()
}
|
pgavlin/warp | wast/parser_script.go | package wast
import "strings"
func ParseScript(scanner *Scanner) (script *Script, err error) {
defer func() {
if v := recover(); v != nil {
e, ok := v.(error)
if !ok {
panic(v)
}
err = e
}
}()
p := parser{s: scanner}
p.start()
return p.parseScript(), nil
}
func (p *parser) parseScript() *Script {
var commands []Command
for p.tok.Kind != EOF {
commands = append(commands, p.parseCommand())
}
p.expect(EOF)
return &Script{Commands: commands}
}
func (p *parser) parseCommand() Command {
if p.tok.Kind == '(' {
switch p.peek() {
case TYPE, FUNC, IMPORT, EXPORT, TABLE, MEMORY, GLOBAL, ELEM, DATA, START:
return p.parseModuleBody("")
}
}
pos := p.tok.Pos
p.expect('(')
switch p.tok.Kind {
case MODULE:
return p.parseModule(pos, true)
case REGISTER:
return p.parseRegister(pos)
case INVOKE:
return p.parseInvoke(pos)
case GET:
return p.parseGet(pos)
case ASSERT_RETURN:
return p.parseAssertReturn(pos)
case ASSERT_TRAP:
return p.parseAssertTrap(pos)
case ASSERT_EXHAUSTION:
return p.parseAssertExhaustion(pos)
case ASSERT_MALFORMED, ASSERT_INVALID, ASSERT_UNLINKABLE:
return p.parseModuleAssertion(pos)
case SCRIPT:
return p.parseScriptCommand(pos)
case INPUT:
return p.parseInput(pos)
case OUTPUT:
return p.parseOutput(pos)
default:
panic(p.errorf("expected action, assertion, or meta command"))
}
}
func (p *parser) parseModuleLiteral(pos Pos, name string) *ModuleLiteral {
defer p.closeSExpr()
isBinary := false
switch p.tok.Kind {
case BINARY:
isBinary = true
case QUOTE:
// OK
default:
panic(p.errorf("expected BINARY or QUOTE"))
}
p.scan()
var data strings.Builder
for p.tok.Kind != ')' {
data.WriteString(p.expect(STRING).(string))
}
return &ModuleLiteral{
Pos: pos,
Name: name,
IsBinary: isBinary,
Data: data.String(),
}
}
func (p *parser) parseRegister(pos Pos) *Register {
p.expect(REGISTER)
defer p.closeSExpr()
export := p.expect(STRING).(string)
name, _ := p.maybe(VAR).(string)
return &Register{
Pos: pos,
Export: export,
Name: name,
}
}
func (p *parser) parseAction(pos Pos) Action {
p.expect('(')
switch p.tok.Kind {
case INVOKE:
return p.parseInvoke(pos)
case GET:
return p.parseGet(pos)
default:
panic(p.errorf("exected INVOKE or GET"))
}
}
func (p *parser) parseInvoke(pos Pos) *Invoke {
defer p.closeSExpr()
p.scan()
name, _ := p.maybe(VAR).(string)
export := p.expect(STRING).(string)
var args []interface{}
for p.tok.Kind != ')' {
p.expect('(')
switch p.tok.Kind {
case F32_CONST, F64_CONST, I32_CONST, I64_CONST:
args = append(args, p.parseOp().(*ConstOp).Value)
default:
panic(p.errorf("expected F32_CONST, F64_CONST, I32_CONST, or I64_CONST"))
}
p.closeSExpr()
}
return &Invoke{
Pos: pos,
Name: name,
Export: export,
Args: args,
}
}
func (p *parser) parseGet(pos Pos) *Get {
defer p.closeSExpr()
p.scan()
name, _ := p.maybe(VAR).(string)
return &Get{
Pos: pos,
Name: name,
Export: p.expect(STRING).(string),
}
}
func (p *parser) parseResult() interface{} {
p.expect('(')
defer p.closeSExpr()
switch p.tok.Kind {
case F32_CONST, F64_CONST:
if n := p.peek(); n == NAN_ARITHMETIC || n == NAN_CANONICAL {
p.scan()
p.scan()
return n
}
return p.parseOp().(*ConstOp).Value
case I32_CONST, I64_CONST:
return p.parseOp().(*ConstOp).Value
default:
panic(p.errorf("expected F32_CONST, F64_CONST, I32_CONST, or I64_CONST"))
}
}
func (p *parser) parseAssertReturn(pos Pos) *AssertReturn {
p.expect(ASSERT_RETURN)
defer p.closeSExpr()
action := p.parseAction(p.tok.Pos)
var results []interface{}
for p.tok.Kind != ')' {
results = append(results, p.parseResult())
}
return &AssertReturn{
Pos: pos,
Action: action,
Results: results,
}
}
func (p *parser) parseAssertTrap(pos Pos) *AssertTrap {
p.expect(ASSERT_TRAP)
defer p.closeSExpr()
return &AssertTrap{
Pos: pos,
Command: p.parseCommand(),
Failure: p.expect(STRING).(string),
}
}
func (p *parser) parseAssertExhaustion(pos Pos) *AssertExhaustion {
p.expect(ASSERT_EXHAUSTION)
defer p.closeSExpr()
return &AssertExhaustion{
Pos: pos,
Action: p.parseAction(p.tok.Pos),
Failure: p.expect(STRING).(string),
}
}
func (p *parser) parseModuleAssertion(pos Pos) *ModuleAssertion {
defer p.closeSExpr()
switch p.tok.Kind {
case ASSERT_MALFORMED, ASSERT_INVALID, ASSERT_UNLINKABLE:
// OK
default:
panic(p.errorf("expected ASSERT_MALFORMED, ASSERT_INVALID, or ASSERT_UNLINKABLE"))
}
kind := p.tok.Kind
p.scan()
modulePos := p.tok.Pos
p.expect('(')
module := p.parseModule(modulePos, true)
return &ModuleAssertion{
Pos: pos,
Kind: kind,
Module: module,
Failure: p.expect(STRING).(string),
}
}
func (p *parser) parseScriptCommand(pos Pos) *ScriptCommand {
p.expect(SCRIPT)
defer p.closeSExpr()
name, _ := p.maybe(VAR).(string)
return &ScriptCommand{
Pos: pos,
Name: name,
Script: p.parseScript(),
}
}
func (p *parser) parseInput(pos Pos) *Input {
p.expect(INPUT)
defer p.closeSExpr()
name, _ := p.maybe(VAR).(string)
return &Input{
Pos: pos,
Name: name,
Path: p.expect(STRING).(string),
}
}
func (p *parser) parseOutput(pos Pos) *Output {
p.expect(OUTPUT)
defer p.closeSExpr()
name, _ := p.maybe(VAR).(string)
return &Output{
Pos: pos,
Name: name,
Path: p.expect(STRING).(string),
}
}
|
Jianwei-Wang/python2.7_lib | dist-packages/ibus/object.py | # vim:set et sts=4 sw=4:
#
# ibus - The Input Bus
#
# Copyright (c) 2007-2010 <NAME> <<EMAIL>>
# Copyright (c) 2007-2010 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
__all__ = (
"Object",
)
import gobject
class Object(gobject.GObject):
__gtype_name__ = "PYIBusObject"
__gsignals__ = {
'destroy' : (
gobject.SIGNAL_RUN_LAST,
gobject.TYPE_NONE,
())
}
def __init__(self):
super(Object, self).__init__()
self.__destroyed = False
self.__handlers = []
def destroy(self):
if not self.__destroyed:
self.emit("destroy")
self.__destroyed = True
def do_destroy(self):
self.__disconnect_all()
def connect(self, signal_name, handler, *args):
id = super(Object, self).connect(signal_name, handler, *args)
self.__handlers.append(id)
def __disconnect_all(self):
map(self.disconnect, self.__handlers)
self.__handlers = []
|
crupest/cru | include/cru/parse/ParsingTreeNode.hpp | <gh_stars>1-10
#pragma once
#include "Grammar.hpp"
#include <vector>
namespace cru::parse {
class CRU_PARSE_API ParsingTreeNode {
public:
ParsingTreeNode(Symbol* symbol, Production* production);
CRU_DELETE_COPY(ParsingTreeNode)
CRU_DELETE_MOVE(ParsingTreeNode)
// In destructor, it will delete all children.
~ParsingTreeNode();
public:
Symbol* GetSymbol() const { return symbol_; }
Production* GetProduction() const { return production_; }
Grammar* GetGrammar() const;
const std::vector<ParsingTreeNode*>& GetChildren() const { return children_; }
void AddChild(ParsingTreeNode* child);
void AddChild(ParsingTreeNode* child, Index index);
void RemoveChild(Index index);
private:
Symbol* symbol_;
Production* production_;
std::vector<ParsingTreeNode*> children_;
};
} // namespace cru::parse
|
kmeeraj/openticket | src/test/java/com/example/openticket/controller/ScheduleMovieControllerTest.java | <reponame>kmeeraj/openticket
package com.example.openticket.controller;
import com.example.openticket.domain.Movie;
import com.example.openticket.domain.ScheduleMovie;
import com.example.openticket.domain.Theater;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ScheduleMovieControllerTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void getAllMovies() {
List<Movie> movies= this.restTemplate.getForObject("http://localhost:" + port + "/movies",
List.class);
assertEquals(movies.size(), 7);
}
@Test
void getAllScheduleMovies() {
List<ScheduleMovie> scheduleMovies= this.restTemplate.getForObject("http://localhost:" + port + "/schedules",
List.class);
assertEquals(scheduleMovies.size(), 73);
}
@Test
void getAllTheaters() {
List<Theater> theaters= this.restTemplate.getForObject("http://localhost:" + port + "/theaters",
List.class);
assertEquals(theaters.size(), 12);
}
} |
fengzhongye/LogiAM | agent-manager/agent-manager-extends/agent-manager-thirdpart/src/main/java/com/didichuxing/datachannel/agentmanager/thirdpart/service/extension/impl/ServiceHostManageServiceExtensionImpl.java | <filename>agent-manager/agent-manager-extends/agent-manager-thirdpart/src/main/java/com/didichuxing/datachannel/agentmanager/thirdpart/service/extension/impl/ServiceHostManageServiceExtensionImpl.java<gh_stars>100-1000
package com.didichuxing.datachannel.agentmanager.thirdpart.service.extension.impl;
import com.alibaba.fastjson.JSON;
import com.didichuxing.datachannel.agentmanager.common.bean.common.CheckResult;
import com.didichuxing.datachannel.agentmanager.common.bean.po.service.ServiceHostPO;
import com.didichuxing.datachannel.agentmanager.common.enumeration.ErrorCodeEnum;
import com.didichuxing.datachannel.agentmanager.thirdpart.service.extension.ServiceHostManageServiceExtension;
@org.springframework.stereotype.Service
public class ServiceHostManageServiceExtensionImpl implements ServiceHostManageServiceExtension {
@Override
public CheckResult checkCreateParameterServiceHost(ServiceHostPO serviceHostPO) {
if(null == serviceHostPO) {
return new CheckResult(
false,
ErrorCodeEnum.ILLEGAL_PARAMS.getCode(),
String.format(
"class=ServiceHostManageServiceExtensionImpl||method=checkCreateParameterServiceHost||errorMsg={%s}!",
"入参serviceHost对象为空"
)
);
}
if(null == serviceHostPO.getServiceId() || serviceHostPO.getServiceId() <= 0) {
return new CheckResult(
false,
ErrorCodeEnum.ILLEGAL_PARAMS.getCode(),
String.format(
"class=ServiceHostManageServiceExtensionImpl||method=checkCreateParameterServiceHost||errorMsg={%s}!",
String.format("入参serviceHost对象={%s}对应serviceId字段值非法", JSON.toJSONString( serviceHostPO ))
)
);
}
if(null == serviceHostPO.getHostId() || serviceHostPO.getHostId() <= 0) {
return new CheckResult(
false,
ErrorCodeEnum.ILLEGAL_PARAMS.getCode(),
String.format(
"class=ServiceHostManageServiceExtensionImpl||method=checkCreateParameterServiceHost||errorMsg={%s}!",
String.format("入参serviceHost对象={%s}对应hostId字段值非法", JSON.toJSONString( serviceHostPO ))
)
);
}
return new CheckResult(true);
}
}
|
wulfebw/retro | cores/n64/custom/GLideN64/mupenplus/Config_mupenplus.cpp | #include "GLideN64_mupenplus.h"
#include "GLideN64_libretro.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include "../Config.h"
#include "../GLideN64.h"
#include "../GBI.h"
#include "../RSP.h"
#include "../Log.h"
extern "C" {
#include "main/util.h"
#include "GLideN64.custom.ini.h"
}
Config config;
std::string replaceChars(std::string myString)
{
for (size_t pos = myString.find(' '); pos != std::string::npos; pos = myString.find(' ', pos))
{
myString.replace(pos, 1, "%20");
}
for (size_t pos = myString.find('\''); pos != std::string::npos; pos = myString.find('\'', pos))
{
myString.replace(pos, 1, "%27");
}
return myString;
}
void LoadCustomSettings(bool internal)
{
std::string myString = replaceChars(RSP.romname);
bool found = false;
char buffer[256];
char* line;
FILE* fPtr;
std::transform(myString.begin(), myString.end(), myString.begin(), ::toupper);
if (internal) {
line = strtok(customini, "\n");
} else {
const char *pathname = ConfigGetSharedDataFilepath("GLideN64.custom.ini");
if (pathname == NULL || (fPtr = fopen(pathname, "rb")) == NULL)
return;
}
while (true)
{
if (!internal) {
if (fgets(buffer, 255, fPtr) == NULL)
break;
else
line = buffer;
}
ini_line l = ini_parse_line(&line);
switch (l.type)
{
case INI_SECTION:
{
if (myString == replaceChars(l.name))
found = true;
else
found = false;
}
case INI_PROPERTY:
{
if (found) {
if (!strcmp(l.name, "video\\multisampling"))
config.video.multisampling = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\aspect"))
config.frameBufferEmulation.aspect = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\nativeResFactor"))
config.frameBufferEmulation.nativeResFactor = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\copyToRDRAM"))
config.frameBufferEmulation.copyToRDRAM = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\copyFromRDRAM"))
config.frameBufferEmulation.copyFromRDRAM = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\copyDepthToRDRAM"))
config.frameBufferEmulation.copyDepthToRDRAM = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\copyAuxToRDRAM"))
config.frameBufferEmulation.copyAuxToRDRAM = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\fbInfoDisabled"))
config.frameBufferEmulation.fbInfoDisabled = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\N64DepthCompare"))
config.frameBufferEmulation.N64DepthCompare = atoi(l.value);
else if (!strcmp(l.name, "frameBufferEmulation\\bufferSwapMode"))
config.frameBufferEmulation.bufferSwapMode = atoi(l.value);
else if (!strcmp(l.name, "texture\\bilinearMode"))
config.texture.bilinearMode = atoi(l.value);
else if (!strcmp(l.name, "texture\\maxAnisotropy"))
config.texture.maxAnisotropy = atoi(l.value);
else if (!strcmp(l.name, "generalEmulation\\enableNativeResTexrects"))
config.graphics2D.enableNativeResTexrects = atoi(l.value);
else if (!strcmp(l.name, "generalEmulation\\correctTexrectCoords"))
config.graphics2D.correctTexrectCoords = atoi(l.value);
else if (!strcmp(l.name, "generalEmulation\\enableLegacyBlending"))
config.generalEmulation.enableLegacyBlending = atoi(l.value);
else if (!strcmp(l.name, "generalEmulation\\enableFragmentDepthWrite"))
config.generalEmulation.enableFragmentDepthWrite = atoi(l.value);
}
}
}
if (internal) {
line = strtok(NULL, "\n");
if (line == NULL)
break;
}
}
}
extern "C" void Config_LoadConfig()
{
u32 hacks = config.generalEmulation.hacks;
config.resetToDefaults();
config.frameBufferEmulation.aspect = AspectRatio;
config.frameBufferEmulation.enable = EnableFBEmulation;
config.frameBufferEmulation.N64DepthCompare = EnableN64DepthCompare;
config.texture.bilinearMode = bilinearMode;
config.generalEmulation.enableHWLighting = EnableHWLighting;
config.generalEmulation.enableLegacyBlending = enableLegacyBlending;
config.generalEmulation.enableNoise = EnableNoiseEmulation;
config.generalEmulation.enableLOD = EnableLODEmulation;
config.frameBufferEmulation.copyDepthToRDRAM = EnableCopyDepthToRDRAM;
#if defined(GLES2) && !defined(ANDROID)
config.frameBufferEmulation.copyToRDRAM = Config::ctDisable;
#else
config.frameBufferEmulation.copyToRDRAM = EnableCopyColorToRDRAM;
#endif
#ifdef HAVE_OPENGLES
config.frameBufferEmulation.bufferSwapMode = Config::bsOnColorImageChange;
#endif
#ifdef HAVE_OPENGLES2
config.generalEmulation.enableFragmentDepthWrite = 0;
#else
config.generalEmulation.enableFragmentDepthWrite = EnableFragmentDepthWrite;
#endif
#ifdef VC
config.generalEmulation.enableShadersStorage = 0;
#else
config.generalEmulation.enableShadersStorage = EnableShadersStorage;
#endif
config.textureFilter.txSaveCache = EnableTextureCache;
config.textureFilter.txFilterMode = txFilterMode;
config.textureFilter.txEnhancementMode = txEnhancementMode;
config.textureFilter.txFilterIgnoreBG = txFilterIgnoreBG;
config.textureFilter.txHiresEnable = txHiresEnable;
config.textureFilter.txCacheCompression = EnableTxCacheCompression;
config.textureFilter.txHiresFullAlphaChannel = txHiresFullAlphaChannel;
config.video.fxaa = EnableFXAA;
config.video.multisampling = MultiSampling;
// Overscan
config.frameBufferEmulation.enableOverscan = EnableOverscan;
// NTSC
config.frameBufferEmulation.overscanNTSC.left = OverscanLeft;
config.frameBufferEmulation.overscanNTSC.right = OverscanRight;
config.frameBufferEmulation.overscanNTSC.top = OverscanTop;
config.frameBufferEmulation.overscanNTSC.bottom = OverscanBottom;
// PAL
config.frameBufferEmulation.overscanPAL.left = OverscanLeft;
config.frameBufferEmulation.overscanPAL.right = OverscanRight;
config.frameBufferEmulation.overscanPAL.top = OverscanTop;
config.frameBufferEmulation.overscanPAL.bottom = OverscanBottom;
config.graphics2D.correctTexrectCoords = CorrectTexrectCoords;
config.graphics2D.enableNativeResTexrects = enableNativeResTexrects;
config.graphics2D.bgMode = BackgroundMode;
config.textureFilter.txEnhancedTextureFileStorage = EnableEnhancedTextureStorage;
config.textureFilter.txHiresTextureFileStorage = EnableEnhancedHighResStorage;
config.frameBufferEmulation.nativeResFactor = EnableNativeResFactor;
config.generalEmulation.hacks = hacks;
LoadCustomSettings(true);
LoadCustomSettings(false);
}
|
himdel/manageiq-ui-classic | app/assets/javascripts/controllers/live_metrics/ad_hoc_metrics_controller.js | <filename>app/assets/javascripts/controllers/live_metrics/ad_hoc_metrics_controller.js
/* global miqHttpInject */
ManageIQ.angular.app.controller('adHocMetricsController', ['$http', '$window', '$timeout', 'miqService',
'metricsUtilsFactory', 'metricsHttpFactory', 'metricsConfigFactory', 'metricsParseUrlFactory',
function($http, $window, $timeout, miqService, metricsUtilsFactory, metricsHttpFactory, metricsConfigFactory, metricsParseUrlFactory) {
var dash = this;
var utils = metricsUtilsFactory(dash, $timeout);
var httpUtils = metricsHttpFactory(dash, $http, utils, miqService);
dash.getTenants = httpUtils.getTenants;
dash.refreshList = httpUtils.refreshList;
dash.refreshGraph = httpUtils.refreshGraph;
dash.setFilterOptions = utils.setFilterOptions;
dash.metricPrefix = utils.metricPrefix;
dash.calcDataDifferentials = utils.calcDataDifferentials;
dash.setPage = httpUtils.setPage;
var pageSetup = function() {
// try to parse config variables from page url
// and set page config variables
metricsParseUrlFactory(dash, $window);
metricsConfigFactory(dash);
}
var initialization = function() {
dash.tenantChanged = false;
dash.filterChanged = true;
dash.itemSelected = false;
dash.selectedItems = [];
dash.tagsLoaded = false;
dash.applied = false;
dash.showGraph = false;
dash.filtersText = '';
dash.definitions = [];
dash.items = [];
dash.tags = {};
dash.chartData = {};
dash.page = 1;
dash.pages = 1;
dash.pagesTitle = "";
dash.filterConfig = {
fields: [],
appliedFilters: [],
resultsCount: 0,
onFilterChange: filterChange
};
dash.toolbarConfig = {
filterConfig: dash.filterConfig,
actionsConfig: dash.actionsConfig
};
dash.graphToolbarConfig = {
actionsConfig: dash.actionsConfig
};
if (dash.tenant.value) {
// load filters
httpUtils.getMetricTags();
} else {
// load tenants and filters
httpUtils.getTenants();
}
setAppliedFilters();
}
var filterChange = function (filters, addOnly) {
dash.filterChanged = true;
dash.filtersText = "";
dash.tags = {};
// prevent listing all metrics point
if (dash.filterConfig.appliedFilters.length === 0) {
dash.applied = false;
dash.itemSelected = false;
dash.selectedItems = [];
dash.tagsLoaded = true;
dash.items = [];
dash.page = 1;
dash.pages = 1;
dash.pagesTitle = "";
dash.filterConfig.resultsCount = 0;
return;
}
dash.filterConfig.appliedFilters.forEach(function (filter) {
if (filter.title && filter.value) {
dash.filtersText += filter.title + " : " + filter.value + "\n";
dash.tags[filter.id] = filter.value;
}
});
// when change filter we automatically apply changes
if (!addOnly) {
dash.itemSelected = false;
dash.selectedItems = [];
dash.items = [];
dash.page = 1;
dash.pages = 1;
dash.pagesTitle = "";
dash.filterChanged = false;
dash.filterConfig.resultsCount = 0;
dash.applyFilters();
}
};
dash.doAddFilter = function() {
// if field is empty return
if ( !dash.filterConfig.currentValue ) return;
var filter = $('.filter-pf.filter-fields').scope().currentField;
dash.filterConfig.appliedFilters.push({
id: filter.id,
title: filter.title,
value: dash.filterConfig.currentValue}
);
dash.filterConfig.currentValue = "";
// add a filter but only add (do not apply)
filterChange(null, true);
};
var setAppliedFilters = function() {
// if user did not send any tags, just exit
if (!dash.params.tags) return;
// add the user defined tags as filters
var tags = JSON.parse(dash.params.tags);
angular.forEach(tags, function(value, key) {
dash.filterConfig.appliedFilters.push({
id: key,
title: key,
value: value,
});
});
// apply the new filters
filterChange();
}
dash.applyFilters = function() {
dash.applied = true;
dash.filterChanged = false;
httpUtils.refreshList();
};
dash.viewGraph = function() {
dash.showGraph = true;
dash.chartDataInit = false;
httpUtils.refreshGraph();
// enable the bootstrapSwitch to run chart refresh
angular.element('[name=rate-switch]').bootstrapSwitch({ onSwitchChange: utils.redrawGraph });
};
dash.viewMetrics = function() {
dash.showGraph = false;
};
dash.refreshTenant = function() {
initialization();
};
// one time initialization of page elemants
pageSetup();
// initialize page elemants
initialization();
}
]);
|
Manistein/behaviac | inc/behaviac/base/xml/xml.h | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause 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/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _CORE_XML_H_
#define _CORE_XML_H_
#include "behaviac/base/xml/ixml.h"
/**
******************************************************************************
* CXmlNode class
* Never use CXmlNode directly instead use reference counted XmlNodeRef.
******************************************************************************
*/
class IFile;
class CXmlNode : public IXmlNode
{
public:
BEHAVIAC_DECLARE_MEMORY_OPERATORS(CXmlNode)
//! Constructor.
CXmlNode(const char* tag);
//! Destructor.
~CXmlNode();
//////////////////////////////////////////////////////////////////////////
//! Reference counting.
void AddRef() const
{
m_refCount++;
};
//! When ref count reach zero XML node dies.
void Release() const
{
if (--m_refCount <= 0)
{
BEHAVIAC_DELETE(const_cast<CXmlNode*>(this));
}
};
//! Get XML node tag.
const char* getTag() const
{
return m_tag.c_str();
};
void setTag(const char* tag)
{
m_tag = tag;
}
//! Return true if given tag equal to node tag.
bool isTag(const char* tag) const;
//! Get XML Node attributes.
virtual void copyAttributes(XmlConstNodeRef fromNode);
//! Get the number of attribute
virtual int getAttrCount() const;
//! Get an attribute value with his index
virtual const char* getAttr(int index) const;
//! Get an attribute value with his index
virtual const char* getAttrTag(int index) const;
//! Get XML Node attribute for specified key.
const char* getAttr(const char* key) const;
//! Check if attributes with specified key exist.
bool haveAttr(const char* key) const;
//! Adds new child node.
void addChild(XmlNodeRef node);
//! Creates new xml node and add it to childs list.
XmlNodeRef newChild(const char* tagName);
//! Remove child node.
void removeChild(XmlNodeRef node);
//! Remove all child nodes.
void removeAllChilds();
//! Swap child nodes
void swapChilds(int child1, int child2);
//! Get number of child XML nodes.
int getChildCount() const
{
return (int)m_childs.size();
};
int getChildCount(const char* tag) const;
//! Get XML Node child nodes.
XmlNodeRef getChild(int i);
XmlConstNodeRef getChild(int i) const;
//! Find node with specified tag.
XmlNodeRef findChild(const char* tag);
XmlConstNodeRef findChild(const char* tag) const;
//! Find node with specified tag. Create the new one if not found.
XmlNodeRef findChildSafe(const char* tag);
//! Find node with specified tag. Return the Invalid node if not found.
XmlConstNodeRef findChildSafe(const char* tag) const;
//! Returns content of this node.
const char* getContent() const
{
return m_content.c_str();
};
void setContent(const char* str)
{
m_content = str;
};
void transferContent(behaviac::string& newContent)
{
m_content.swap(newContent);
}
XmlNodeRef clone() const;
#ifdef _DEBUG
//! Returns line number for XML tag.
int getLine() const
{
return m_line;
};
//! Set line number in xml.
void setLine(int line)
{
m_line = line;
};
#endif //_DEBUG
//! Returns XML of this node and sub nodes.
void getXML(behaviac::string& xml, int level = 0) const;
void getXML(behaviac::wstring& xml, int level = 0) const;
bool saveToFile(const char* fileName) const;
bool saveToFile(IFile* file) const;
void ReserveAttr(int nCount);
//! Set new XML Node attribute.
virtual void setAttrText(const char* key, const char* value);
virtual void setAttrText(const char* key, const wchar_t* text);
//! Delete attrbute.
void delAttr(const char* key);
//! Remove all node attributes.
void removeAllAttributes();
const XmlConstNodeRef& getInvalidNode() const
{
return m_invalidNode;
}
private:
static const XmlConstNodeRef m_invalidNode;
typedef behaviac::vector<XmlNodeRef> XmlNodes;
XmlNodes m_childs;
//! Xml node attributes.
XmlAttributes m_attributes;
//! Content of XML node.
behaviac::string m_content;
//! behaviac of XML node.
XmlString m_tag;
//! Ref count itself, its zeroed on node creation.
mutable int m_refCount; // mutable as ref-counting as nothing to do with data access
//! Line in XML file where this node firstly appeared (usefull for debuggin).
#ifdef _DEBUG
int m_line;
#endif //_DEBUG
};
/**
******************************************************************************
* CXmlNode class
* Never use CXmlNode directly instead use reference counted XmlNodeRef.
******************************************************************************
*/
#endif // #ifndef _CORE_XML_H_
|
AtlantisUnited/avrs-cabinet | src/app/pages/money/containers/ExternalTransfer.js | import React from 'react'
import { connect } from 'react-redux'
import { Column, Layout } from 'flex-layouts'
import { Block } from 'avrs-ui/src/content'
import { Steps, Step } from 'avrs-ui/src/steps'
import OutputMethods from './transfer/OutputMethods'
import CardMethod from './transfer/CardMethod'
import BitcoinMethod from './transfer/BitcoinMethod'
import PaymentSuccess from '../components/transfer/PaymentSuccess'
const renderMethod = (method) => {
if (method === 'bitcoin') {
return (
<BitcoinMethod />
)
}
return (
<CardMethod />
)
}
const External = ({ step, method, onChangeMethod }) => ( // eslint-disable-line no-unused-vars
<Column>
<Layout grow={1} />
<Layout basis='924px'>
<Block>
<Steps current={step}>
<Step title='Способ вывода'>
<OutputMethods />
</Step>
<Step title='Информация'>
{renderMethod(method)}
</Step>
<Step title='Подтверждение'>
<PaymentSuccess />
</Step>
</Steps>
</Block>
</Layout>
<Layout grow={1} />
</Column>
)
export default connect(
state => ({
step: state.money.transfer.external.step,
method: state.money.transfer.external.method,
}),
)(External)
|
npocmaka/Windows-Server-2003 | shell/ext/gina/userlist.cpp | // --------------------------------------------------------------------------
// Module Name: UserList.cpp
//
// Copyright (c) 1999-2000, Microsoft Corporation
//
// Class that implements the user list filtering algorithm shared by winlogon
// calling into msgina and shgina (the logonocx) calling into msgina.
//
// History: 1999-10-30 vtan created
// 1999-11-26 vtan moved from logonocx
// 2000-01-31 vtan moved from Neptune to Whistler
// --------------------------------------------------------------------------
#include "StandardHeader.h"
#include "UserList.h"
#include <shlwapi.h>
#include <shlwapip.h>
#include <winsta.h>
#include "RegistryResources.h"
#include "SpecialAccounts.h"
#include "SystemSettings.h"
// --------------------------------------------------------------------------
// CUserList::s_SIDAdministrator
// CUserList::s_SIDGuest
// CUserList::s_szAdministratorsGroupName
// CUserList::s_szPowerUsersGroupName
// CUserList::s_szUsersGroupName
// CUserList::s_szGuestsGroupName
//
// Purpose: Stores the localized name of the well known accounts
// "Administrator" and "Guest". These accounts are determined
// by SID. Also stores the localized name of the local
// "Administrators" group.
//
// History: 2000-02-15 vtan created
// 2000-03-06 vtan added Administrators group
// 2001-05-10 vtan changed user strings to SID
// --------------------------------------------------------------------------
unsigned char CUserList::s_SIDAdministrator[256] = { 0 };
unsigned char CUserList::s_SIDGuest[256] = { 0 };
WCHAR CUserList::s_szAdministratorsGroupName[GNLEN + sizeof('\0')] = { L'\0' };
WCHAR CUserList::s_szPowerUsersGroupName[GNLEN + sizeof('\0')] = { L'\0' };
WCHAR CUserList::s_szUsersGroupName[GNLEN + sizeof('\0')] = { L'\0' };
WCHAR CUserList::s_szGuestsGroupName[GNLEN + sizeof('\0')] = { L'\0' };
// --------------------------------------------------------------------------
// CUserList::Get
//
// Arguments: fRemoveGuest = Always remove the "Guest" account.
// pdwReturnEntryCount = Returned number of entries. This
// may be NULL.
// pUserList = Buffer containing user data. This
// may be NULL.
//
// Returns: LONG
//
// Purpose: Returns a filtered array of user entries from the given
// server SAM. Filtering is performed here so that a common
// algorithm can be applied to the list of users such that the
// logon UI host can display the correct user information and
// msgina can return the same number of users on the system.
//
// History: 1999-10-15 vtan created
// 1999-10-30 vtan uses CSpecialAccounts
// 1999-11-26 vtan moved from logonocx
// --------------------------------------------------------------------------
LONG CUserList::Get (bool fRemoveGuest, DWORD *pdwReturnedEntryCount, GINA_USER_INFORMATION* *pReturnedUserList)
{
LONG lError;
DWORD dwPreferredSize, dwEntryCount, dwEntriesRead;
GINA_USER_INFORMATION *pUserList;
NET_DISPLAY_USER *pNDU;
CSpecialAccounts SpecialAccounts;
pUserList = NULL;
dwEntryCount = 0;
// Determine the well known account names.
DetermineWellKnownAccountNames();
// Allow a buffer for 100 users including their name, comments and full name.
// This should be sufficient for home consumers. If the need to extend this
// arises make this dynamic!
dwPreferredSize = (sizeof(NET_DISPLAY_USER) + (3 * UNLEN) * s_iMaximumUserCount);
pNDU = NULL;
lError = NetQueryDisplayInformation(NULL, // NULL means LocalMachine
1, // query User information
0, // starting with the first user
s_iMaximumUserCount, // return a max of 100 users
dwPreferredSize, // preferred buffer size
&dwEntriesRead,
reinterpret_cast<void**>(&pNDU));
if ((ERROR_SUCCESS == lError) || (ERROR_MORE_DATA == lError))
{
bool fHasCreatedAccount, fFound;
DWORD dwUsernameSize;
int iIndex, iAdministratorIndex;
WCHAR wszUsername[UNLEN + sizeof('\0')];
// Get the current user name.
dwUsernameSize = ARRAYSIZE(wszUsername);
if (GetUserNameW(wszUsername, &dwUsernameSize) == FALSE)
{
wszUsername[0] = L'\0';
}
fHasCreatedAccount = false;
iAdministratorIndex = -1;
for (iIndex = static_cast<int>(dwEntriesRead - 1); iIndex >= 0; --iIndex)
{
PSID pSID;
pSID = ConvertNameToSID(pNDU[iIndex].usri1_name);
if (pSID != NULL)
{
// Never filter the current user.
if (lstrcmpiW(pNDU[iIndex].usri1_name, wszUsername) == 0)
{
// If this is executed in the current user context and
// that user isn't "Administrator", but is a member of
// the local administrators group, then a user created
// administrator account exists even though it isn't
// filtered. The "Administrator" account can be removed.
if ((EqualSid(pSID, s_SIDAdministrator) == FALSE) &&
IsUserMemberOfLocalAdministrators(pNDU[iIndex].usri1_name))
{
fHasCreatedAccount = true;
if (iAdministratorIndex >= 0)
{
DeleteEnumerateUsers(pNDU, dwEntriesRead, iAdministratorIndex);
iAdministratorIndex = -1;
}
}
}
else
{
// If the account is
// 1) disabled
// 2) locked out
// 3) a special account (see CSpecialAccounts)
// 4) "Guest" and fRemoveGuest is true
// 5) "Administrator" and has created another account
// and does not always include "Administrator" and
// "Administrator is not logged on
// Then filter the account out.
if (((pNDU[iIndex].usri1_flags & UF_ACCOUNTDISABLE) != 0) ||
((pNDU[iIndex].usri1_flags & UF_LOCKOUT) != 0) ||
SpecialAccounts.AlwaysExclude(pNDU[iIndex].usri1_name) ||
(fRemoveGuest && (EqualSid(pSID, s_SIDGuest) != FALSE)) ||
((EqualSid(pSID, s_SIDAdministrator) != FALSE) &&
fHasCreatedAccount &&
!SpecialAccounts.AlwaysInclude(pNDU[iIndex].usri1_name) &&
!IsUserLoggedOn(pNDU[iIndex].usri1_name, NULL)))
{
DeleteEnumerateUsers(pNDU, dwEntriesRead, iIndex);
// Account for indices being changed.
// If this index wasn't set previously it just goes more negative.
// If it was set we know it can never be below zero.
--iAdministratorIndex;
}
// If the account should always be included then do it.
// Guest is not a user created account so fHasCreatedAccount
// must not be set if this account is seen.
else if (!SpecialAccounts.AlwaysInclude(pNDU[iIndex].usri1_name))
{
// If safe mode then filter accounts that are not members of the
// local administrators group.
if (CSystemSettings::IsSafeMode())
{
if (!IsUserMemberOfLocalAdministrators(pNDU[iIndex].usri1_name))
{
DeleteEnumerateUsers(pNDU, dwEntriesRead, iIndex);
--iAdministratorIndex;
}
}
else if (EqualSid(pSID, s_SIDAdministrator) != FALSE)
{
if (!IsUserLoggedOn(pNDU[iIndex].usri1_name, NULL))
{
// Otherwise if the account name is "Administrator" and another
// account has been created then this account needs to be removed
// from the list. If another account has not been seen then
// remember this index so that if another account is seen this
// account can be removed.
if (fHasCreatedAccount)
{
DeleteEnumerateUsers(pNDU, dwEntriesRead, iIndex);
--iAdministratorIndex;
}
else
{
iAdministratorIndex = iIndex;
}
}
}
else if (EqualSid(pSID, s_SIDGuest) == FALSE)
{
// If the account name is NOT "Administrator" then check the
// account group membership. If the account is a member of the
// local administrators group then the "Administrator" account
// can be removed.
if (IsUserMemberOfLocalAdministrators(pNDU[iIndex].usri1_name))
{
fHasCreatedAccount = true;
if (iAdministratorIndex >= 0)
{
DeleteEnumerateUsers(pNDU, dwEntriesRead, iAdministratorIndex);
iAdministratorIndex = -1;
}
}
if (!IsUserMemberOfLocalKnownGroup(pNDU[iIndex].usri1_name))
{
DeleteEnumerateUsers(pNDU, dwEntriesRead, iIndex);
--iAdministratorIndex;
}
}
}
}
(HLOCAL)LocalFree(pSID);
}
}
if (!ParseDisplayInformation(pNDU, dwEntriesRead, pUserList, dwEntryCount))
{
lError = ERROR_OUTOFMEMORY;
pUserList = NULL;
dwEntryCount = 0;
}
(NET_API_STATUS)NetApiBufferFree(pNDU);
if (ERROR_SUCCESS == lError)
{
// Sort the user list. Typically this has come back alphabetized by the
// SAM. However, the SAM sorts by logon name and not by display name.
// This needs to be sorted by display name.
Sort(pUserList, dwEntryCount);
// The guest account should be put at the end of this list. This
// is a simple case of find the guest account (by localized name) and
// sliding all the entries down and inserting the guest at the end.
for (fFound = false, iIndex = 0; !fFound && (iIndex < static_cast<int>(dwEntryCount)); ++iIndex)
{
PSID pSID;
pSID = ConvertNameToSID(pUserList[iIndex].pszName);
if (pSID != NULL)
{
fFound = (EqualSid(pSID, s_SIDGuest) != FALSE);
if (fFound)
{
GINA_USER_INFORMATION gui;
MoveMemory(&gui, &pUserList[iIndex], sizeof(gui));
MoveMemory(&pUserList[iIndex], &pUserList[iIndex + 1], (dwEntryCount - iIndex - 1) * sizeof(pUserList[0]));
MoveMemory(&pUserList[dwEntryCount - 1], &gui, sizeof(gui));
}
(HLOCAL)LocalFree(pSID);
}
}
}
}
if (pReturnedUserList != NULL)
{
*pReturnedUserList = pUserList;
}
else
{
ReleaseMemory(pUserList);
}
if (pdwReturnedEntryCount != NULL)
{
*pdwReturnedEntryCount = dwEntryCount;
}
return(lError);
}
// --------------------------------------------------------------------------
// CLogonDialog::IsUserLoggedOn
//
// Arguments: pszUsername = User name.
// pszDomain = User domain.
//
// Returns: bool
//
// Purpose: Use WindowStation APIs in terminal services to determine if
// a given user is logged onto this machine. It will not query
// remote terminal servers.
//
// Windowstations must be in the active or disconnected state.
//
// History: 2000-02-28 vtan created
// 2000-05-30 vtan moved from CWLogonDialog.cpp
// --------------------------------------------------------------------------
bool CUserList::IsUserLoggedOn (const WCHAR *pszUsername, const WCHAR *pszDomain)
{
bool fResult;
WCHAR szDomain[DNLEN + sizeof('\0')];
fResult = false;
// If no domain is supplied then use the computer's name.
if ((pszDomain == NULL) || (pszDomain[0] == L'\0'))
{
DWORD dwDomainSize;
dwDomainSize = ARRAYSIZE(szDomain);
if (GetComputerNameW(szDomain, &dwDomainSize) != FALSE)
{
pszDomain = szDomain;
}
}
// If no domain is supplied and the computer's name cannot be determined
// then this API fails. A user name must also be supplied.
if ((pszUsername != NULL) && (pszDomain != NULL))
{
HANDLE hServer;
PLOGONID pLogonID, pLogonIDs;
ULONG ul, ulEntries;
// Open a connection to terminal services and get the number of sessions.
hServer = WinStationOpenServerW(reinterpret_cast<WCHAR*>(SERVERNAME_CURRENT));
if (hServer != NULL)
{
if (WinStationEnumerate(hServer, &pLogonIDs, &ulEntries) != FALSE)
{
// Iterate the sessions looking for active and disconnected sessions only.
// Then match the user name and domain (case INsensitive) for a result.
for (ul = 0, pLogonID = pLogonIDs; !fResult && (ul < ulEntries); ++ul, ++pLogonID)
{
if ((pLogonID->State == State_Active) || (pLogonID->State == State_Disconnected))
{
ULONG ulReturnLength;
WINSTATIONINFORMATIONW winStationInformation;
if (WinStationQueryInformationW(hServer,
pLogonID->LogonId,
WinStationInformation,
&winStationInformation,
sizeof(winStationInformation),
&ulReturnLength) != FALSE)
{
fResult = ((lstrcmpiW(pszUsername, winStationInformation.UserName) == 0) &&
(lstrcmpiW(pszDomain, winStationInformation.Domain) == 0));
}
}
}
// Free any resources used.
(BOOLEAN)WinStationFreeMemory(pLogonIDs);
}
(BOOLEAN)WinStationCloseServer(hServer);
}
}
return(fResult);
}
// --------------------------------------------------------------------------
// CUserList::IsInteractiveLogonAllowed
//
// Arguments: pszUsername = User name.
//
// Returns: int
//
// Purpose: Determines whether the SeDenyInteractiveLogonRight is
// assigned into the given user. Returns -1 if the state cannot
// be determined due to some error. Otherwise returns 0 if the
// the right is assigned and != 0 && != -1 if not.
//
// One final check is made on personal for a user name that
// matches DOMAIN_USER_RID_ADMIN.
//
// History: 2000-08-15 vtan created
// --------------------------------------------------------------------------
int CUserList::IsInteractiveLogonAllowed (const WCHAR *pszUsername)
{
int iResult;
LSA_HANDLE hLSA;
UNICODE_STRING strDenyInteractiveLogonRight;
OBJECT_ATTRIBUTES objectAttributes;
iResult = -1;
RtlInitUnicodeString(&strDenyInteractiveLogonRight, SE_DENY_INTERACTIVE_LOGON_NAME);
InitializeObjectAttributes(&objectAttributes,
NULL,
0,
NULL,
NULL);
if (NT_SUCCESS(LsaOpenPolicy(NULL,
&objectAttributes,
POLICY_LOOKUP_NAMES,
&hLSA)))
{
SID_NAME_USE eUse;
DWORD dwSIDSize, dwReferencedDomainSize;
PSID pSID;
WCHAR szReferencedDomain[CNLEN + sizeof('\0')];
dwSIDSize = 0;
dwReferencedDomainSize = ARRAYSIZE(szReferencedDomain);
(BOOL)LookupAccountNameW(NULL,
pszUsername,
NULL,
&dwSIDSize,
szReferencedDomain,
&dwReferencedDomainSize,
&eUse);
pSID = static_cast<PSID>(LocalAlloc(LMEM_FIXED, dwSIDSize));
if (pSID != NULL)
{
if (LookupAccountNameW(NULL,
pszUsername,
pSID,
&dwSIDSize,
szReferencedDomain,
&dwReferencedDomainSize,
&eUse) != FALSE)
{
NTSTATUS status;
ULONG ulIndex, ulCountOfRights;
PLSA_UNICODE_STRING pUserRights;
status = LsaEnumerateAccountRights(hLSA,
pSID,
&pUserRights,
&ulCountOfRights);
if (NT_SUCCESS(status))
{
bool fFound;
for (fFound = false, ulIndex = 0; !fFound && (ulIndex < ulCountOfRights); ++ulIndex)
{
fFound = (RtlEqualUnicodeString(&strDenyInteractiveLogonRight, pUserRights + ulIndex, TRUE) != FALSE);
}
iResult = fFound ? 0 : 1;
TSTATUS(LsaFreeMemory(pUserRights));
}
else if (STATUS_OBJECT_NAME_NOT_FOUND == status)
{
iResult = 1;
}
}
(HLOCAL)LocalFree(pSID);
}
TSTATUS(LsaClose(hLSA));
}
if (IsOS(OS_PERSONAL) && !CSystemSettings::IsSafeMode())
{
PSID pSID;
pSID = ConvertNameToSID(pszUsername);
if (pSID != NULL)
{
if (EqualSid(pSID, s_SIDAdministrator) != FALSE)
{
iResult = 0;
}
(HLOCAL)LocalFree(pSID);
}
}
return(iResult);
}
PSID CUserList::ConvertNameToSID (const WCHAR *pszUsername)
{
PSID pSID;
DWORD dwSIDSize, dwDomainSize;
SID_NAME_USE eUse;
pSID = NULL;
dwSIDSize = dwDomainSize = 0;
(BOOL)LookupAccountNameW(NULL,
pszUsername,
NULL,
&dwSIDSize,
NULL,
&dwDomainSize,
NULL);
if ((dwSIDSize != 0) && (dwDomainSize != 0))
{
WCHAR *pszDomain;
pszDomain = static_cast<WCHAR*>(LocalAlloc(LMEM_FIXED, dwDomainSize * sizeof(WCHAR)));
if (pszDomain != NULL)
{
pSID = static_cast<PSID>(LocalAlloc(LMEM_FIXED, dwSIDSize));
if (pSID != NULL)
{
if (LookupAccountName(NULL,
pszUsername,
pSID,
&dwSIDSize,
pszDomain,
&dwDomainSize,
&eUse) == FALSE)
{
(HLOCAL)LocalFree(pSID);
pSID = NULL;
}
}
(HLOCAL)LocalFree(pszDomain);
}
}
return(pSID);
}
// --------------------------------------------------------------------------
// CUserList::IsUserMemberOfLocalAdministrators
//
// Arguments: pszName = User name to test.
//
// Returns: bool
//
// Purpose: Returns whether the given user is a member of the local
// Administrators group.
//
// History: 2000-03-28 vtan created
// --------------------------------------------------------------------------
bool CUserList::IsUserMemberOfLocalAdministrators (const WCHAR *pszName)
{
bool fIsAnAdministrator;
DWORD dwGroupEntriesRead, dwGroupTotalEntries;
LOCALGROUP_USERS_INFO_0 *pLocalGroupUsersInfo;
fIsAnAdministrator = false;
pLocalGroupUsersInfo = NULL;
if (NetUserGetLocalGroups(NULL,
pszName,
0,
LG_INCLUDE_INDIRECT,
(LPBYTE*)&pLocalGroupUsersInfo,
MAX_PREFERRED_LENGTH,
&dwGroupEntriesRead,
&dwGroupTotalEntries) == NERR_Success)
{
int iIndexGroup;
LOCALGROUP_USERS_INFO_0 *pLGUI;
for (iIndexGroup = 0, pLGUI = pLocalGroupUsersInfo; !fIsAnAdministrator && (iIndexGroup < static_cast<int>(dwGroupEntriesRead)); ++iIndexGroup, ++pLGUI)
{
fIsAnAdministrator = (lstrcmpiW(pLGUI->lgrui0_name, s_szAdministratorsGroupName) == 0);
}
}
else
{
fIsAnAdministrator = true;
}
if (pLocalGroupUsersInfo != NULL)
{
TW32(NetApiBufferFree(pLocalGroupUsersInfo));
}
return(fIsAnAdministrator);
}
// --------------------------------------------------------------------------
// CUserList::IsUserMemberOfLocalKnownGroup
//
// Arguments: pszName = User name to test.
//
// Returns: bool
//
// Purpose: Returns whether the given user is a member of a local known
// group. Membership of a known group returns true. Membership
// of only groups that are not known returns false.
//
// History: 2000-06-29 vtan created
// --------------------------------------------------------------------------
bool CUserList::IsUserMemberOfLocalKnownGroup (const WCHAR *pszName)
{
bool fIsMember;
DWORD dwGroupEntriesRead, dwGroupTotalEntries;
LOCALGROUP_USERS_INFO_0 *pLocalGroupUsersInfo;
fIsMember = true;
pLocalGroupUsersInfo = NULL;
if (NetUserGetLocalGroups(NULL,
pszName,
0,
LG_INCLUDE_INDIRECT,
(LPBYTE*)&pLocalGroupUsersInfo,
MAX_PREFERRED_LENGTH,
&dwGroupEntriesRead,
&dwGroupTotalEntries) == NERR_Success)
{
int iIndexGroup;
LOCALGROUP_USERS_INFO_0 *pLGUI;
// Assume the worst. As soon as a known group is found this will terminate the loop.
fIsMember = false;
for (iIndexGroup = 0, pLGUI = pLocalGroupUsersInfo; !fIsMember && (iIndexGroup < static_cast<int>(dwGroupEntriesRead)); ++iIndexGroup, ++pLGUI)
{
fIsMember = ((lstrcmpiW(pLGUI->lgrui0_name, s_szAdministratorsGroupName) == 0) ||
(lstrcmpiW(pLGUI->lgrui0_name, s_szPowerUsersGroupName) == 0) ||
(lstrcmpiW(pLGUI->lgrui0_name, s_szUsersGroupName) == 0) ||
(lstrcmpiW(pLGUI->lgrui0_name, s_szGuestsGroupName) == 0));
}
}
if (pLocalGroupUsersInfo != NULL)
{
TW32(NetApiBufferFree(pLocalGroupUsersInfo));
}
return(fIsMember);
}
// --------------------------------------------------------------------------
// CUserList::DeleteEnumerateUsers
//
// Arguments: pNDU = NET_DISPLAY_USER array to delete from.
// dwEntriesRead = Number of entries in the array.
// iIndex = Index to delete.
//
// Returns: <none>
//
// Purpose: Deletes the given array index contents from the array by
// sliding down the elements and zeroing the last entry.
//
// History: 1999-10-16 vtan created
// 1999-11-26 vtan moved from logonocx
// --------------------------------------------------------------------------
void CUserList::DeleteEnumerateUsers (NET_DISPLAY_USER *pNDU, DWORD& dwEntriesRead, int iIndex)
{
int iIndiciesToMove;
iIndiciesToMove = static_cast<int>(dwEntriesRead - 1) - iIndex;
if (iIndiciesToMove != 0)
{
MoveMemory(&pNDU[iIndex], &pNDU[iIndex + 1], iIndiciesToMove * sizeof(*pNDU));
}
ZeroMemory(&pNDU[--dwEntriesRead], sizeof(*pNDU));
}
// --------------------------------------------------------------------------
// CUserList::DetermineWellKnownAccountNames
//
// Arguments: <none>
//
// Returns: <none>
//
// Purpose: Determines the string for the local Administrator and Guest
// accounts by getting the user list from the local SAM and
// looking up the SID corresponding with the iterated user names
// and checking the SID for the RID that is desired.
//
// The main loop structure mimics the filter function.
//
// History: 2000-02-15 vtan created
// --------------------------------------------------------------------------
void CUserList::DetermineWellKnownAccountNames (void)
{
static bool s_fCachedWellKnownAccountNames = false;
// If the well known account names haven't been determined yet
// then do this. But only do this once.
if (!s_fCachedWellKnownAccountNames)
{
USER_MODALS_INFO_2 *pUMI;
PSID pSID;
DWORD dwNameSize, dwDomainSize;
SID_NAME_USE eUse;
WCHAR szDomain[DNLEN + sizeof('\0')];
// Build the SID for the built-in local administrator
// and built-in local guest accounts.
if (NetUserModalsGet(NULL, 2, (LPBYTE*)&pUMI) == NERR_Success)
{
unsigned char ucSubAuthorityCount;
ucSubAuthorityCount = *GetSidSubAuthorityCount(pUMI->usrmod2_domain_id);
if (GetSidLengthRequired(ucSubAuthorityCount + 1) <= sizeof(s_SIDAdministrator))
{
if (CopySid(GetSidLengthRequired(ucSubAuthorityCount + 1), s_SIDAdministrator, pUMI->usrmod2_domain_id) != FALSE)
{
*GetSidSubAuthority(s_SIDAdministrator, ucSubAuthorityCount) = DOMAIN_USER_RID_ADMIN;
*GetSidSubAuthorityCount(s_SIDAdministrator) = ucSubAuthorityCount + 1;
}
}
else
{
ZeroMemory(s_SIDAdministrator, sizeof(s_SIDAdministrator));
}
if (GetSidLengthRequired(ucSubAuthorityCount + 1) <= sizeof(s_SIDGuest))
{
if (CopySid(GetSidLengthRequired(ucSubAuthorityCount + 1), s_SIDGuest, pUMI->usrmod2_domain_id) != FALSE)
{
*GetSidSubAuthority(s_SIDGuest, ucSubAuthorityCount) = DOMAIN_USER_RID_GUEST;
*GetSidSubAuthorityCount(s_SIDGuest) = ucSubAuthorityCount + 1;
}
}
else
{
ZeroMemory(s_SIDAdministrator, sizeof(s_SIDAdministrator));
}
(NET_API_STATUS)NetApiBufferFree(pUMI);
}
// Now determine the local administrators group name.
static SID_IDENTIFIER_AUTHORITY sSystemSidAuthority = SECURITY_NT_AUTHORITY;
if (NT_SUCCESS(RtlAllocateAndInitializeSid(&sSystemSidAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&pSID)))
{
dwNameSize = ARRAYSIZE(s_szAdministratorsGroupName);
dwDomainSize = ARRAYSIZE(szDomain);
TBOOL(LookupAccountSidW(NULL,
pSID,
s_szAdministratorsGroupName,
&dwNameSize,
szDomain,
&dwDomainSize,
&eUse));
(void*)RtlFreeSid(pSID);
}
// Power Users
if (NT_SUCCESS(RtlAllocateAndInitializeSid(&sSystemSidAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_POWER_USERS,
0, 0, 0, 0, 0, 0,
&pSID)))
{
dwNameSize = ARRAYSIZE(s_szPowerUsersGroupName);
dwDomainSize = ARRAYSIZE(szDomain);
(BOOL)LookupAccountSidW(NULL,
pSID,
s_szPowerUsersGroupName,
&dwNameSize,
szDomain,
&dwDomainSize,
&eUse);
(void*)RtlFreeSid(pSID);
}
// Users
if (NT_SUCCESS(RtlAllocateAndInitializeSid(&sSystemSidAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS,
0, 0, 0, 0, 0, 0,
&pSID)))
{
dwNameSize = ARRAYSIZE(s_szUsersGroupName);
dwDomainSize = ARRAYSIZE(szDomain);
TBOOL(LookupAccountSidW(NULL,
pSID,
s_szUsersGroupName,
&dwNameSize,
szDomain,
&dwDomainSize,
&eUse));
(void*)RtlFreeSid(pSID);
}
// Guests
if (NT_SUCCESS(RtlAllocateAndInitializeSid(&sSystemSidAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_GUESTS,
0, 0, 0, 0, 0, 0,
&pSID)))
{
dwNameSize = ARRAYSIZE(s_szGuestsGroupName);
dwDomainSize = ARRAYSIZE(szDomain);
TBOOL(LookupAccountSidW(NULL,
pSID,
s_szGuestsGroupName,
&dwNameSize,
szDomain,
&dwDomainSize,
&eUse));
(void*)RtlFreeSid(pSID);
}
// Don't do this again.
s_fCachedWellKnownAccountNames = true;
}
}
// --------------------------------------------------------------------------
// CUserList::ParseDisplayInformation
//
// Arguments: pNDU = NET_DISPLAY_USER list to parse.
// dwEntriesRead = Number of entries in NDU list.
// pUserList = GINA_USER_INFORMATION pointer returned.
// dwEntryCount = Number of entries in GUI list.
//
// Returns: bool
//
// Purpose: Converts NET_DISPLAY_USER array to GINA_USER_INFORMATION
// array so that information can be added or removed as desired
// from the final information returned to the caller.
//
// History: 2000-06-26 vtan created
// --------------------------------------------------------------------------
bool CUserList::ParseDisplayInformation (NET_DISPLAY_USER *pNDU, DWORD dwEntriesRead, GINA_USER_INFORMATION*& pUserList, DWORD& dwEntryCount)
{
bool fResult;
DWORD dwBufferSize, dwComputerNameSize;
int iIndex;
unsigned char *pBuffer;
WCHAR *pWC;
WCHAR szComputerName[CNLEN + sizeof('\0')];
// Get the local computer name. This is the local domain.
dwComputerNameSize = ARRAYSIZE(szComputerName);
if (GetComputerNameW(szComputerName, &dwComputerNameSize) == FALSE)
{
szComputerName[0] = L'\0';
}
// Calculate the total size of the buffer required based on the number of
// entries and the size of a struct and the length of the strings required.
// Append any additions to the below this loop.
dwBufferSize = 0;
for (iIndex = static_cast<int>(dwEntriesRead - 1); iIndex >= 0; --iIndex)
{
dwBufferSize += sizeof(GINA_USER_INFORMATION);
dwBufferSize += (lstrlenW(pNDU[iIndex].usri1_name) + sizeof('\0')) * sizeof(WCHAR);
dwBufferSize += (lstrlenW(szComputerName) + sizeof('\0')) * sizeof(WCHAR);
dwBufferSize += (lstrlenW(pNDU[iIndex].usri1_full_name) + sizeof('\0')) * sizeof(WCHAR);
}
// Allocate the buffer. Start allocating structs from the start of the
// buffer and allocate strings from the end of the buffer. Uses pUserList
// to allocate structs and pWC to allocate strings.
pBuffer = static_cast<unsigned char*>(LocalAlloc(LMEM_FIXED, dwBufferSize));
pUserList = reinterpret_cast<GINA_USER_INFORMATION*>(pBuffer);
pWC = reinterpret_cast<WCHAR*>(pBuffer + dwBufferSize);
if (pBuffer != NULL)
{
int iStringCount;
// Walk thru the NET_DISPLAY_USER array and convert/copy the
// struct and strings to GINA_USER_INFORMATION and allocate the
// space from the buffer we just allocated.
for (iIndex = 0; iIndex < static_cast<int>(dwEntriesRead); ++iIndex)
{
iStringCount = lstrlenW(pNDU[iIndex].usri1_name) + sizeof('\0');
pWC -= iStringCount;
CopyMemory(pWC, pNDU[iIndex].usri1_name, iStringCount * sizeof(WCHAR));
pUserList[iIndex].pszName = pWC;
iStringCount = lstrlenW(szComputerName) + sizeof('\0');
pWC -= iStringCount;
CopyMemory(pWC, szComputerName, iStringCount * sizeof(WCHAR));
pUserList[iIndex].pszDomain = pWC;
iStringCount = lstrlenW(pNDU[iIndex].usri1_full_name) + sizeof('\0');
pWC -= iStringCount;
CopyMemory(pWC, pNDU[iIndex].usri1_full_name, iStringCount * sizeof(WCHAR));
pUserList[iIndex].pszFullName = pWC;
pUserList[iIndex].dwFlags = pNDU[iIndex].usri1_flags;
}
// Return the count of entries.
dwEntryCount = dwEntriesRead;
// And a success.
fResult = true;
}
else
{
fResult = false;
}
return(fResult);
}
// --------------------------------------------------------------------------
// CUserList::Sort
//
// Arguments: pNDU = GINA_USER_INFORMATION list to sort.
// dwEntriesRead = Number of entries in the list.
//
// Returns: <none>
//
// Purpose: Sorts the GINA_USER_INFORMATION array by display name NOT
// logon name as the SAM returns the data. This is a lame n^2
// algorithm that won't scale well but it's for a very limited
// usage scenario. If need be this will be revised.
//
// History: 2000-06-08 vtan created
// 2000-06-26 vtan converted to GINA_USER_INFORMATION
// --------------------------------------------------------------------------
void CUserList::Sort (GINA_USER_INFORMATION *pUserList, DWORD dwEntryCount)
{
GINA_USER_INFORMATION *pSortedList;
pSortedList = static_cast<GINA_USER_INFORMATION*>(LocalAlloc(LMEM_FIXED, dwEntryCount * sizeof(GINA_USER_INFORMATION)));
if (pSortedList != NULL)
{
int iOuter;
for (iOuter = 0; iOuter < static_cast<int>(dwEntryCount); ++iOuter)
{
int iInner, iItem;
const WCHAR *pszItem;
for (iItem = -1, pszItem = NULL, iInner = 0; iInner < static_cast<int>(dwEntryCount); ++iInner)
{
const WCHAR *psz;
psz = pUserList[iInner].pszFullName;
if ((psz == NULL) || (psz[0] == L'\0'))
{
psz = pUserList[iInner].pszName;
}
if (psz != NULL)
{
if ((iItem == -1) || (lstrcmpiW(pszItem, psz) > 0))
{
iItem = iInner;
pszItem = psz;
}
}
}
pSortedList[iOuter] = pUserList[iItem];
pUserList[iItem].pszFullName = pUserList[iItem].pszName = NULL;
}
CopyMemory(pUserList, pSortedList, dwEntryCount * sizeof(GINA_USER_INFORMATION));
ReleaseMemory(pSortedList);
}
}
|
EventWiz/Frontend | src/App.js | import React, { useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { connect } from 'react-redux';
import Login from './components/Login';
import { GlobalStyle } from './styles/GlobalStyle';
import EventPage from './components/Events';
import Signup from './components/Signup';
import EventForm from './components/EventForm';
import Agenda from './components/Agenda';
import Event from './components/Event';
import { PrivateRoute } from './components/PrivateRoute';
import { loggedIn } from './actions/auth';
import { getToken } from './utils/localStorage';
import Logout from './components/Logout';
import { AuthRoute } from './components/AuthRoute';
const App = ({ loggedIn: logInUser }) => {
useEffect(() => {
const token = getToken();
if (token) {
logInUser();
}
}, [logInUser]);
return (
<Router>
<GlobalStyle />
<Switch>
<Route exact path="/" component={EventPage} />
<AuthRoute path="/login" component={Login} />
<AuthRoute path="/signup" component={Signup} />
<Route path="/events/:eventId" component={Event} />
<PrivateRoute path="/create-event" component={EventForm} />
<PrivateRoute path="/agenda" component={Agenda} />
<Route path="/logout" component={Logout} />
</Switch>
</Router>
);
};
export default connect(state => state.authReducer, { loggedIn })(App);
|
Dnmrk4/codewars-7kyu-part2 | Simple eviternity numbers.js | /*
Description:
An eviternity number is a number which contains only digits 8, 5 and 3, and the count of the digit 8 >= count of digit 5 >= count of digit 3. The first few eviternity numbers are as follows.
[8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
You will be given two integers, a and b, and your task is to return the number of eviternity numbers in the range >= a and < b.
For example:
solve(0,1000) = 14, because they are [8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
The upper bound will not exceed 500,000.
More examples in test cases. Good luck!
*/
const solve = (a,b) => {
const countCheck = n => {
let s = n+``
return s.replace(/[35]/g,'').length >= s.replace(/[38]/g,'').length &&
s.replace(/[38]/g,'').length >= s.replace(/[58]/g,'').length
}
let i = 0
while(a < b){
i += /^[358]+$/.test(a+``) && countCheck(a); a++
}
return i
}
|
KATO-Hiro/AtCoder | ARC/arc001-arc050/arc008/b.py | # -*- coding: utf-8 -*-
def main():
from collections import Counter
from math import ceil
n, m = map(int, input().split())
name = input()
kit = input()
ans = 0
for name_i in name:
if name_i not in kit:
print(-1)
exit()
kit_count = Counter(kit)
for key, value in Counter(name).items():
ans = max(ans, ceil(value / kit_count[key]))
print(ans)
if __name__ == '__main__':
main()
|
karensmolermiller/incubator-geode | gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/HealthMonitorImpl.java | /*
* 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 com.gemstone.gemfire.distributed.internal;
import org.apache.logging.log4j.Logger;
import com.gemstone.gemfire.admin.GemFireHealth;
import com.gemstone.gemfire.admin.GemFireHealthConfig;
import com.gemstone.gemfire.admin.internal.GemFireHealthEvaluator;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.internal.admin.remote.HealthListenerMessage;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.internal.logging.LoggingThreadGroup;
import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
/**
* Implements a thread that monitors the health of the vm it lives in.
* @author <NAME>
* @since 3.5
*/
public class HealthMonitorImpl implements HealthMonitor, Runnable {
private static final Logger logger = LogService.getLogger();
private final InternalDistributedMember owner;
private final int id;
private final DistributionManager dm;
private final GemFireHealthEvaluator eval;
/** The current health status
*
* @see GemFireHealth#OKAY_HEALTH */
private GemFireHealth.Health currentStatus;
private final Thread t;
private volatile boolean stopRequested = false;
private static int idCtr = 0;
/********** Constructors *********/
/**
* Creates a health monitor given its owner, configuration, and its dm
*/
public HealthMonitorImpl(InternalDistributedMember owner,
GemFireHealthConfig config,
DistributionManager dm) {
this.owner = owner;
this.id = getNewId();
this.dm = dm;
this.eval = new GemFireHealthEvaluator(config, dm);
this.currentStatus = GemFireHealth.GOOD_HEALTH;
ThreadGroup tg = LoggingThreadGroup.createThreadGroup("HealthMonitor Threads", logger);
this.t = new Thread(tg, this, LocalizedStrings.HealthMonitorImpl_HEALTH_MONITOR_OWNED_BY_0.toLocalizedString(owner));
this.t.setDaemon(true);
}
/************** HealthMonitor interface implementation ******************/
public int getId() {
return this.id;
}
public void resetStatus() {
this.currentStatus = GemFireHealth.GOOD_HEALTH;
this.eval.reset();
}
public String[] getDiagnosis(GemFireHealth.Health healthCode) {
return this.eval.getDiagnosis(healthCode);
}
public void stop() {
if (this.t.isAlive()) {
this.stopRequested = true;
this.t.interrupt();
}
}
/********** HealthMonitorImpl public methods **********/
/**
* Starts the monitor so that it will periodically do health checks.
*/
public void start() {
if (this.stopRequested) {
throw new RuntimeException(LocalizedStrings.HealthMonitorImpl_A_HEALTH_MONITOR_CAN_NOT_BE_STARTED_ONCE_IT_HAS_BEEN_STOPPED.toLocalizedString());
}
if (this.t.isAlive()) {
// it is already running
return;
}
this.t.start();
}
/********** Runnable interface implementation **********/
public void run() {
final int sleepTime = this.eval.getEvaluationInterval() * 1000;
if (logger.isDebugEnabled()) {
logger.debug("Starting health monitor. Health will be evaluated every {} seconds.", (sleepTime/1000));
}
try {
while (!this.stopRequested) {
// SystemFailure.checkFailure(); dm's stopper will do this
this.dm.getCancelCriterion().checkCancelInProgress(null);
Thread.sleep(sleepTime);
if (!this.stopRequested) {
GemFireHealth.Health newStatus = this.eval.evaluate();
if (newStatus != this.currentStatus) {
this.currentStatus = newStatus;
HealthListenerMessage msg = HealthListenerMessage.create(getId(), newStatus);
msg.setRecipient(this.owner);
this.dm.putOutgoing(msg);
}
}
}
} catch (InterruptedException ex) {
// No need to reset interrupt bit, we're exiting.
if (!this.stopRequested) {
logger.warn(LocalizedMessage.create(LocalizedStrings.HealthMonitorImpl_UNEXPECTED_STOP_OF_HEALTH_MONITOR), ex);
}
} finally {
this.eval.close();
this.stopRequested = true;
if (logger.isDebugEnabled()) {
logger.debug("Stopping health monitor");
}
}
}
/********** Internal implementation **********/
private static synchronized int getNewId() {
idCtr += 1;
return idCtr;
}
}
|
lamiaaMB/torN23 | src/test/test_circuitmux.c | /* Copyright (c) 2013-2016, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#define TOR_CHANNEL_INTERNAL_
#define CIRCUITMUX_PRIVATE
#define RELAY_PRIVATE
#include "or.h"
#include "channel.h"
#include "circuitmux.h"
#include "relay.h"
#include "scheduler.h"
#include "test.h"
/* XXXX duplicated function from test_circuitlist.c */
static channel_t *
new_fake_channel(void)
{
channel_t *chan = tor_malloc_zero(sizeof(channel_t));
channel_init(chan);
return chan;
}
static int
has_queued_writes(channel_t *c)
{
(void) c;
return 1;
}
/** Test destroy cell queue with no interference from other queues. */
static void
test_cmux_destroy_cell_queue(void *arg)
{
circuitmux_t *cmux = NULL;
channel_t *ch = NULL;
circuit_t *circ = NULL;
cell_queue_t *cq = NULL;
packed_cell_t *pc = NULL;
scheduler_init();
(void) arg;
cmux = circuitmux_alloc();
tt_assert(cmux);
ch = new_fake_channel();
ch->has_queued_writes = has_queued_writes;
ch->wide_circ_ids = 1;
circ = circuitmux_get_first_active_circuit(cmux, &cq);
tt_assert(!circ);
tt_assert(!cq);
circuitmux_append_destroy_cell(ch, cmux, 100, 10);
circuitmux_append_destroy_cell(ch, cmux, 190, 6);
circuitmux_append_destroy_cell(ch, cmux, 30, 1);
tt_int_op(circuitmux_num_cells(cmux), OP_EQ, 3);
circ = circuitmux_get_first_active_circuit(cmux, &cq);
tt_assert(!circ);
tt_assert(cq);
tt_int_op(cq->n, OP_EQ, 3);
pc = cell_queue_pop(cq);
tt_assert(pc);
tt_mem_op(pc->body, OP_EQ, "\x00\x00\x00\x64\x04\x0a\x00\x00\x00", 9);
packed_cell_free(pc);
pc = NULL;
tt_int_op(circuitmux_num_cells(cmux), OP_EQ, 2);
done:
circuitmux_free(cmux);
channel_free(ch);
packed_cell_free(pc);
}
struct testcase_t circuitmux_tests[] = {
{ "destroy_cell_queue", test_cmux_destroy_cell_queue, TT_FORK, NULL, NULL },
END_OF_TESTCASES
};
|
zhangkn/MachOExplorer | src/libmoex/node/LoadCommand.cpp | <reponame>zhangkn/MachOExplorer
//
// Created by qiwei on 2017/3/29.
//
#ifndef MACHOEXPLORER_LOADCOMMAND_FACTORY_H
#define MACHOEXPLORER_LOADCOMMAND_FACTORY_H
#include "LoadCommand.h"
#include "loadcmd/LoadCommand_SEGMENT.h"
#include "loadcmd/LoadCommand_DYLIB.h"
#include "loadcmd/LoadCommand_DYLD_INFO.h"
#include "loadcmd/LoadCommand_SYMTAB.h"
#include "loadcmd/LoadCommand_DYSYMTAB.h"
#include "loadcmd/LoadCommand_LOAD_DYLINKER.h"
#include "loadcmd/LoadCommand_UUID.h"
#include "loadcmd/LoadCommand_VERSION_MIN.h"
#include "loadcmd/LoadCommand_SOURCE_VERSION.h"
#include "loadcmd/LoadCommand_MAIN.h"
#include "loadcmd/LoadCommand_ENCRYPTION_INFO.h"
#include "loadcmd/LoadCommand_LINKEDIT_DATA.h"
#include "loadcmd/LoadCommand_TWOLEVEL_HINTS.h"
#include "MachHeader.h"
MOEX_NAMESPACE_BEGIN
bool LoadCommand::Is64() {
return header_->Is64();
}
std::string LoadCommand::GetLoadCommandTypeString(){
return util::GetLoadCommandType(offset()->cmd);
}
#define DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(commandtag,classtag) \
case commandtag: return std::make_shared<LoadCommand_##classtag>();
#define DECLARE_LOAD_COMMAND_CASE_STATEMENT(commandtag) \
case commandtag: return std::make_shared<LoadCommand_##commandtag>();
LoadCommandPtr LoadCommandFactory::NewCommand(uint32_t cmd) {
switch (cmd) {
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT_64)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_DYLIB, DYLIB)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_LOAD_WEAK_DYLIB, DYLIB)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_REEXPORT_DYLIB, DYLIB)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO, DYLD_INFO)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_DYLD_INFO_ONLY, DYLD_INFO)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SYMTAB)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_DYSYMTAB)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_LOAD_DYLINKER)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_UUID)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_IPHONEOS, VERSION_MIN)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_MACOSX, VERSION_MIN)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_TVOS, VERSION_MIN)
DECLARE_LOAD_COMMAND_CASE_STATEMENT_CLASS(LC_VERSION_MIN_WATCHOS, VERSION_MIN)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SOURCE_VERSION)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_MAIN)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_ENCRYPTION_INFO_64)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_CODE_SIGNATURE)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_SEGMENT_SPLIT_INFO)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_FUNCTION_STARTS)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_DATA_IN_CODE)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_DYLIB_CODE_SIGN_DRS)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_LINKER_OPTIMIZATION_HINT)
DECLARE_LOAD_COMMAND_CASE_STATEMENT(LC_TWOLEVEL_HINTS)
default:
return std::make_shared<LoadCommand>();
}
}
LoadCommandPtr LoadCommandFactory::Create(void * offset,NodeContextPtr & ctx,MachHeader *header){
load_command *lc = reinterpret_cast<load_command*>(offset);
LoadCommandPtr cmd = LoadCommandFactory::NewCommand(lc->cmd);
cmd->set_header(header);
cmd->Init(offset,ctx);
return cmd;
}
MOEX_NAMESPACE_END
#endif //MACHOEXPLORER_LOADCOMMAND_FACTORY_H
|
Sukikiroi/Noon-Clone | src/Components/Noon Clone/Checkout/CheckoutNoonClone.js | import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepLabel from "@material-ui/core/StepLabel";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import Checkoutcontainer from "./Checkoutcontainer";
import ArrowRightAltIcon from '@material-ui/icons/ArrowRightAlt';
const useStyles = makeStyles((theme) => ({
steps_root: {
width: "100%",
height:'120px',
position: 'fixed',
zIndex:'5',
top: '0',
backgroundColor:'whitesmoke',
display: "flex",
justifyContent: "center",
},
steps: {
width: "98%",
marginTop: "30px",
margin: "auto",
},
suivant_button_root: {
width: "100%",
display: "flex",
height:'100px',
justifyContent: "center",
zIndex:'5',
marginTop:'80px',
},
suivant_button: {
width: "80%",
display: "flex",
justifyContent: "flex-end",
marginTop: "30px",
'& Button':{
whiteSpace:'nowrap',
textTransform:'capitalize',
'& hover':{
border:'2px solid dodgerblue',
},
width:'90px'
}
},
}));
const Checkoutnoonclone = () => {
function getSteps() {
return ["Shipping Address", "Payment", "Order Placed"];
}
function getStepContent(step) {
switch (step) {
case 0:
return "Shipping Address";
case 1:
return "Payment";
case 2:
return "Order Placed";
default:
return "Unknown step";
}
}
const [activeStep, setActiveStep] = React.useState(0);
const [skipped, setSkipped] = React.useState(new Set());
const steps = getSteps();
const isStepOptional = (step) => {
return step === 1;
};
const isStepSkipped = (step) => {
return skipped.has(step);
};
const handleNext = () => {
let newSkipped = skipped;
if (isStepSkipped(activeStep)) {
newSkipped = new Set(newSkipped.values());
newSkipped.delete(activeStep);
}
setActiveStep((prevActiveStep) => prevActiveStep + 1);
setSkipped(newSkipped);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
const handleSkip = () => {
if (!isStepOptional(activeStep)) {
// You probably want to guard against something like this,
// it should never occur unless someone's actively trying to break something.
throw new Error("You can't skip a step that isn't optional.");
}
setActiveStep((prevActiveStep) => prevActiveStep + 1);
setSkipped((prevSkipped) => {
const newSkipped = new Set(prevSkipped.values());
newSkipped.add(activeStep);
return newSkipped;
});
};
const handleReset = () => {
setActiveStep(0);
};
const classes = useStyles();
return (
<div>
<div className={classes.steps_root}>
<div className={classes.steps}>
<Stepper
style={{ whiteSpace: "nowrap", backgroundColor: "yellow" }}
activeStep={activeStep}
>
{steps.map((label, index) => {
const stepProps = {};
const labelProps = {};
if (isStepSkipped(index)) {
stepProps.completed = false;
}
return (
<Step key={label} {...stepProps}>
<StepLabel {...labelProps}>{label}</StepLabel>
</Step>
);
})}
</Stepper>
</div>
</div>
<div className={classes.suivant_button_root}>
<div className={classes.suivant_button}>
<Button onClick={handleNext} endIcon={<ArrowRightAltIcon/>}>Suivant</Button>
</div>
</div>
<Checkoutcontainer steps_value={activeStep} />
</div>
);
};
export default Checkoutnoonclone;
|
skylark-integration/skylark-threejs-ex | src/loaders/TDSLoader.js | <filename>src/loaders/TDSLoader.js
define([
"skylark-threejs",
"../threex"
], function (
THREE,
threex
) {
'use strict';
var TDSLoader = function (manager) {
THREE.Loader.call(this, manager);
this.debug = false;
this.group = null;
this.position = 0;
this.materials = [];
this.meshes = [];
};
TDSLoader.prototype = Object.assign(Object.create(THREE.Loader.prototype), {
constructor: TDSLoader,
load: function (url, onLoad, onProgress, onError) {
var scope = this;
var path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase(url) : scope.path;
var loader = new THREE.FileLoader(this.manager);
loader.setPath(this.path);
loader.setResponseType('arraybuffer');
loader.load(url, function (data) {
onLoad(scope.parse(data, path));
}, onProgress, onError);
},
parse: function (arraybuffer, path) {
this.group = new THREE.Group();
this.position = 0;
this.materials = [];
this.meshes = [];
this.readFile(arraybuffer, path);
for (var i = 0; i < this.meshes.length; i++) {
this.group.add(this.meshes[i]);
}
return this.group;
},
readFile: function (arraybuffer, path) {
var data = new DataView(arraybuffer);
var chunk = this.readChunk(data);
if (chunk.id === MLIBMAGIC || chunk.id === CMAGIC || chunk.id === M3DMAGIC) {
var next = this.nextChunk(data, chunk);
while (next !== 0) {
if (next === M3D_VERSION) {
var version = this.readDWord(data);
this.debugMessage('3DS file version: ' + version);
} else if (next === MDATA) {
this.resetPosition(data);
this.readMeshData(data, path);
} else {
this.debugMessage('Unknown main chunk: ' + next.toString(16));
}
next = this.nextChunk(data, chunk);
}
}
this.debugMessage('Parsed ' + this.meshes.length + ' meshes');
},
readMeshData: function (data, path) {
var chunk = this.readChunk(data);
var next = this.nextChunk(data, chunk);
while (next !== 0) {
if (next === MESH_VERSION) {
var version = +this.readDWord(data);
this.debugMessage('Mesh Version: ' + version);
} else if (next === MASTER_SCALE) {
var scale = this.readFloat(data);
this.debugMessage('Master scale: ' + scale);
this.group.scale.set(scale, scale, scale);
} else if (next === NAMED_OBJECT) {
this.debugMessage('Named Object');
this.resetPosition(data);
this.readNamedObject(data);
} else if (next === MAT_ENTRY) {
this.debugMessage('Material');
this.resetPosition(data);
this.readMaterialEntry(data, path);
} else {
this.debugMessage('Unknown MDATA chunk: ' + next.toString(16));
}
next = this.nextChunk(data, chunk);
}
},
readNamedObject: function (data) {
var chunk = this.readChunk(data);
var name = this.readString(data, 64);
chunk.cur = this.position;
var next = this.nextChunk(data, chunk);
while (next !== 0) {
if (next === N_TRI_OBJECT) {
this.resetPosition(data);
var mesh = this.readMesh(data);
mesh.name = name;
this.meshes.push(mesh);
} else {
this.debugMessage('Unknown named object chunk: ' + next.toString(16));
}
next = this.nextChunk(data, chunk);
}
this.endChunk(chunk);
},
readMaterialEntry: function (data, path) {
var chunk = this.readChunk(data);
var next = this.nextChunk(data, chunk);
var material = new THREE.MeshPhongMaterial();
while (next !== 0) {
if (next === MAT_NAME) {
material.name = this.readString(data, 64);
this.debugMessage(' Name: ' + material.name);
} else if (next === MAT_WIRE) {
this.debugMessage(' Wireframe');
material.wireframe = true;
} else if (next === MAT_WIRE_SIZE) {
var value = this.readByte(data);
material.wireframeLinewidth = value;
this.debugMessage(' Wireframe Thickness: ' + value);
} else if (next === MAT_TWO_SIDE) {
material.side = THREE.DoubleSide;
this.debugMessage(' DoubleSided');
} else if (next === MAT_ADDITIVE) {
this.debugMessage(' Additive Blending');
material.blending = THREE.AdditiveBlending;
} else if (next === MAT_DIFFUSE) {
this.debugMessage(' Diffuse Color');
material.color = this.readColor(data);
} else if (next === MAT_SPECULAR) {
this.debugMessage(' Specular Color');
material.specular = this.readColor(data);
} else if (next === MAT_AMBIENT) {
this.debugMessage(' Ambient color');
material.color = this.readColor(data);
} else if (next === MAT_SHININESS) {
var shininess = this.readWord(data);
material.shininess = shininess;
this.debugMessage(' Shininess : ' + shininess);
} else if (next === MAT_TRANSPARENCY) {
var opacity = this.readWord(data);
material.opacity = opacity * 0.01;
this.debugMessage(' Opacity : ' + opacity);
material.transparent = opacity < 100 ? true : false;
} else if (next === MAT_TEXMAP) {
this.debugMessage(' ColorMap');
this.resetPosition(data);
material.map = this.readMap(data, path);
} else if (next === MAT_BUMPMAP) {
this.debugMessage(' BumpMap');
this.resetPosition(data);
material.bumpMap = this.readMap(data, path);
} else if (next === MAT_OPACMAP) {
this.debugMessage(' OpacityMap');
this.resetPosition(data);
material.alphaMap = this.readMap(data, path);
} else if (next === MAT_SPECMAP) {
this.debugMessage(' SpecularMap');
this.resetPosition(data);
material.specularMap = this.readMap(data, path);
} else {
this.debugMessage(' Unknown material chunk: ' + next.toString(16));
}
next = this.nextChunk(data, chunk);
}
this.endChunk(chunk);
this.materials[material.name] = material;
},
readMesh: function (data) {
var chunk = this.readChunk(data);
var next = this.nextChunk(data, chunk);
var geometry = new THREE.BufferGeometry();
var uvs = [];
var material = new THREE.MeshPhongMaterial();
var mesh = new THREE.Mesh(geometry, material);
mesh.name = 'mesh';
while (next !== 0) {
if (next === POINT_ARRAY) {
var points = this.readWord(data);
this.debugMessage(' Vertex: ' + points);
var vertices = [];
for (var i = 0; i < points; i++) {
vertices.push(this.readFloat(data));
vertices.push(this.readFloat(data));
vertices.push(this.readFloat(data));
}
geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
} else if (next === FACE_ARRAY) {
this.resetPosition(data);
this.readFaceArray(data, mesh);
} else if (next === TEX_VERTS) {
var texels = this.readWord(data);
this.debugMessage(' UV: ' + texels);
var uvs = [];
for (var i = 0; i < texels; i++) {
uvs.push(this.readFloat(data));
uvs.push(this.readFloat(data));
}
geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
} else if (next === MESH_MATRIX) {
this.debugMessage(' Tranformation Matrix (TODO)');
var values = [];
for (var i = 0; i < 12; i++) {
values[i] = this.readFloat(data);
}
var matrix = new THREE.Matrix4();
matrix.elements[0] = values[0];
matrix.elements[1] = values[6];
matrix.elements[2] = values[3];
matrix.elements[3] = values[9];
matrix.elements[4] = values[2];
matrix.elements[5] = values[8];
matrix.elements[6] = values[5];
matrix.elements[7] = values[11];
matrix.elements[8] = values[1];
matrix.elements[9] = values[7];
matrix.elements[10] = values[4];
matrix.elements[11] = values[10];
matrix.elements[12] = 0;
matrix.elements[13] = 0;
matrix.elements[14] = 0;
matrix.elements[15] = 1;
matrix.transpose();
var inverse = new THREE.Matrix4();
inverse.getInverse(matrix);
geometry.applyMatrix4(inverse);
matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);
} else {
this.debugMessage(' Unknown mesh chunk: ' + next.toString(16));
}
next = this.nextChunk(data, chunk);
}
this.endChunk(chunk);
geometry.computeVertexNormals();
return mesh;
},
readFaceArray: function (data, mesh) {
var chunk = this.readChunk(data);
var faces = this.readWord(data);
this.debugMessage(' Faces: ' + faces);
var index = [];
for (var i = 0; i < faces; ++i) {
index.push(this.readWord(data), this.readWord(data), this.readWord(data));
this.readWord(data);
}
mesh.geometry.setIndex(index);
while (this.position < chunk.end) {
var chunk = this.readChunk(data);
if (chunk.id === MSH_MAT_GROUP) {
this.debugMessage(' Material Group');
this.resetPosition(data);
var group = this.readMaterialGroup(data);
var material = this.materials[group.name];
if (material !== undefined) {
mesh.material = material;
if (material.name === '') {
material.name = mesh.name;
}
}
} else {
this.debugMessage(' Unknown face array chunk: ' + chunk.toString(16));
}
this.endChunk(chunk);
}
this.endChunk(chunk);
},
readMap: function (data, path) {
var chunk = this.readChunk(data);
var next = this.nextChunk(data, chunk);
var texture = {};
var loader = new THREE.TextureLoader(this.manager);
loader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
while (next !== 0) {
if (next === MAT_MAPNAME) {
var name = this.readString(data, 128);
texture = loader.load(name);
this.debugMessage(' File: ' + path + name);
} else if (next === MAT_MAP_UOFFSET) {
texture.offset.x = this.readFloat(data);
this.debugMessage(' OffsetX: ' + texture.offset.x);
} else if (next === MAT_MAP_VOFFSET) {
texture.offset.y = this.readFloat(data);
this.debugMessage(' OffsetY: ' + texture.offset.y);
} else if (next === MAT_MAP_USCALE) {
texture.repeat.x = this.readFloat(data);
this.debugMessage(' RepeatX: ' + texture.repeat.x);
} else if (next === MAT_MAP_VSCALE) {
texture.repeat.y = this.readFloat(data);
this.debugMessage(' RepeatY: ' + texture.repeat.y);
} else {
this.debugMessage(' Unknown map chunk: ' + next.toString(16));
}
next = this.nextChunk(data, chunk);
}
this.endChunk(chunk);
return texture;
},
readMaterialGroup: function (data) {
this.readChunk(data);
var name = this.readString(data, 64);
var numFaces = this.readWord(data);
this.debugMessage(' Name: ' + name);
this.debugMessage(' Faces: ' + numFaces);
var index = [];
for (var i = 0; i < numFaces; ++i) {
index.push(this.readWord(data));
}
return {
name: name,
index: index
};
},
readColor: function (data) {
var chunk = this.readChunk(data);
var color = new THREE.Color();
if (chunk.id === COLOR_24 || chunk.id === LIN_COLOR_24) {
var r = this.readByte(data);
var g = this.readByte(data);
var b = this.readByte(data);
color.setRGB(r / 255, g / 255, b / 255);
this.debugMessage(' Color: ' + color.r + ', ' + color.g + ', ' + color.b);
} else if (chunk.id === COLOR_F || chunk.id === LIN_COLOR_F) {
var r = this.readFloat(data);
var g = this.readFloat(data);
var b = this.readFloat(data);
color.setRGB(r, g, b);
this.debugMessage(' Color: ' + color.r + ', ' + color.g + ', ' + color.b);
} else {
this.debugMessage(' Unknown color chunk: ' + chunk.toString(16));
}
this.endChunk(chunk);
return color;
},
readChunk: function (data) {
var chunk = {};
chunk.cur = this.position;
chunk.id = this.readWord(data);
chunk.size = this.readDWord(data);
chunk.end = chunk.cur + chunk.size;
chunk.cur += 6;
return chunk;
},
endChunk: function (chunk) {
this.position = chunk.end;
},
nextChunk: function (data, chunk) {
if (chunk.cur >= chunk.end) {
return 0;
}
this.position = chunk.cur;
try {
var next = this.readChunk(data);
chunk.cur += next.size;
return next.id;
} catch (e) {
this.debugMessage('Unable to read chunk at ' + this.position);
return 0;
}
},
resetPosition: function () {
this.position -= 6;
},
readByte: function (data) {
var v = data.getUint8(this.position, true);
this.position += 1;
return v;
},
readFloat: function (data) {
try {
var v = data.getFloat32(this.position, true);
this.position += 4;
return v;
} catch (e) {
this.debugMessage(e + ' ' + this.position + ' ' + data.byteLength);
}
},
readInt: function (data) {
var v = data.getInt32(this.position, true);
this.position += 4;
return v;
},
readShort: function (data) {
var v = data.getInt16(this.position, true);
this.position += 2;
return v;
},
readDWord: function (data) {
var v = data.getUint32(this.position, true);
this.position += 4;
return v;
},
readWord: function (data) {
var v = data.getUint16(this.position, true);
this.position += 2;
return v;
},
readString: function (data, maxLength) {
var s = '';
for (var i = 0; i < maxLength; i++) {
var c = this.readByte(data);
if (!c) {
break;
}
s += String.fromCharCode(c);
}
return s;
},
debugMessage: function (message) {
if (this.debug) {
console.log(message);
}
}
});
var M3DMAGIC = 19789;
var MLIBMAGIC = 15786;
var CMAGIC = 49725;
var M3D_VERSION = 2;
var COLOR_F = 16;
var COLOR_24 = 17;
var LIN_COLOR_24 = 18;
var LIN_COLOR_F = 19;
var MDATA = 15677;
var MESH_VERSION = 15678;
var MASTER_SCALE = 256;
var MAT_ENTRY = 45055;
var MAT_NAME = 40960;
var MAT_AMBIENT = 40976;
var MAT_DIFFUSE = 40992;
var MAT_SPECULAR = 41008;
var MAT_SHININESS = 41024;
var MAT_TRANSPARENCY = 41040;
var MAT_TWO_SIDE = 41089;
var MAT_ADDITIVE = 41091;
var MAT_WIRE = 41093;
var MAT_WIRE_SIZE = 41095;
var MAT_TEXMAP = 41472;
var MAT_OPACMAP = 41488;
var MAT_BUMPMAP = 41520;
var MAT_SPECMAP = 41476;
var MAT_MAPNAME = 41728;
var MAT_MAP_USCALE = 41812;
var MAT_MAP_VSCALE = 41814;
var MAT_MAP_UOFFSET = 41816;
var MAT_MAP_VOFFSET = 41818;
var NAMED_OBJECT = 16384;
var N_TRI_OBJECT = 16640;
var POINT_ARRAY = 16656;
var FACE_ARRAY = 16672;
var MSH_MAT_GROUP = 16688;
var TEX_VERTS = 16704;
var MESH_MATRIX = 16736;
return threex.loaders.TDSLoader = TDSLoader;
}); |
chillpert/renderer | docs/html/matrix__int3x3_8hpp.js | var matrix__int3x3_8hpp =
[
[ "imat3", "matrix__int3x3_8hpp.html#ga0d26c46a0b5756bdaf8949154feaeb3f", null ],
[ "imat3x3", "matrix__int3x3_8hpp.html#gab222d4b3d8005a88b4dd9ce459a44eb8", null ]
]; |
Tsvetelin98/Solar | net.solarnetwork.node/src/net/solarnetwork/node/setup/PluginService.java | <filename>net.solarnetwork.node/src/net/solarnetwork/node/setup/PluginService.java
/* ==================================================================
* PluginService.java - Apr 21, 2014 2:12:15 PM
*
* Copyright 2007-2014 SolarNetwork.net Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
* ==================================================================
*/
package net.solarnetwork.node.setup;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
/**
* Service for managing dynamic "plugins" within the application.
*
* @author matt
* @version 1.0
*/
public interface PluginService {
/**
* Ask the PluginService to refresh its list of available plugins. This is
* designed for implementations where the available plugins might change
* over time.
*/
void refreshAvailablePlugins();
/**
* Get a list of all available plugins.
*
* @param query
* an optional query to apply to limit the returned results by. Pass
* <em>null</em> to request all available Plugin instances
* @param locale
* an optional locale to apply to PluginInfo
* @return list of available plugins, or an empty list if none available
*/
List<Plugin> availablePlugins(PluginQuery query, Locale locale);
/**
* Get a list of all installed plugins.
*
* @param locale
* an optional locale to apply to PluginInfo
* @return list of installed plugins, or an empty list if none installed
*/
List<Plugin> installedPlugins(Locale locale);
/**
* Remove one or more plugins based on their UIDs. This method might return
* immediately to allow the provisioning operation to complete
* asynchronously.
*
* @param uids
* the collection of plugins to remove
* @param locale
* an optional locale to apply to the returned PluginProvisionStatus
* @return a status object
*/
PluginProvisionStatus removePlugins(Collection<String> uids, Locale locale);
/**
* Get a "preview" status for installing a set of plugins based on their
* UIDs. This will return a status object synchronously that will contain
* details such as the list of plugins that will be installed and how many
* bytes must be downloaded. Note that the returned
* {@link PluginProvisionStatus#getProvisionID()} will not be valid for
* passing to {@link #statusForProvisioningOperation(String, Locale)}.
*
* @param uids
* the collection of plugins to remove
* @param locale
* an optional locale to apply to the returned PluginProvisionStatus
* @return a status object
*/
PluginProvisionStatus previewInstallPlugins(Collection<String> uids, Locale locale);
/**
* Install one or more plugins based on their UIDs. This method might return
* immediately to allow the provisioning operation to complete
* asynchronously.
*
* @param uids
* the collection of plugins to remove
* @param locale
* an optional locale to apply to the returned PluginProvisionStatus
* @return a status object
*/
PluginProvisionStatus installPlugins(Collection<String> uids, Locale locale);
/**
* Get a provisioning status based on a provisioning operation ID. The ID is
* one that would have been returned via a previous call to other methods
* like {@link #installedPlugins(Locale)}. The service will only maintain
* status information for a limited amount of time, and thus might return
* <em>null</em> even for an ID previously returned.
*
* @param provisionID
* the provisioning operation ID to find the status for
* @param locale
* an optional locale to apply to the returned PluginProvisionStatus
* @return the status, or <em>null</em> if the status is not available
*/
PluginProvisionStatus statusForProvisioningOperation(String provisionID, Locale locale);
}
|
Ale763/PSOPV_GROEP3_CALTOOL | Cal_tool/web/cal_tool/tests.py | <reponame>Ale763/PSOPV_GROEP3_CALTOOL
from django.test import TestCase
# Create your tests here.
print('herea') |
nsnikhil/go-datastructures | functions/consumer/bi_consumer.go | <filename>functions/consumer/bi_consumer.go
package consumer
type BiConsumer interface {
Accept(e, f interface{})
}
|
abserari/td | tg/tl_dialog_filter_gen.go | <reponame>abserari/td<filename>tg/tl_dialog_filter_gen.go
// Code generated by gotdgen, DO NOT EDIT.
package tg
import (
"context"
"fmt"
"strings"
"github.com/gotd/td/bin"
)
// No-op definition for keeping imports.
var _ = bin.Buffer{}
var _ = context.Background()
var _ = fmt.Stringer(nil)
var _ = strings.Builder{}
// DialogFilter represents TL type `dialogFilter#7438f7e8`.
// Dialog filter AKA folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
//
// See https://core.telegram.org/constructor/dialogFilter for reference.
type DialogFilter struct {
// Flags, see TL conditional fields¹
//
// Links:
// 1) https://core.telegram.org/mtproto/TL-combinators#conditional-fields
Flags bin.Fields
// Whether to include all contacts in this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
Contacts bool
// Whether to include all non-contacts in this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
NonContacts bool
// Whether to include all groups in this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
Groups bool
// Whether to include all channels in this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
Broadcasts bool
// Whether to include all bots in this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
Bots bool
// Whether to exclude muted chats from this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
ExcludeMuted bool
// Whether to exclude read chats from this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
ExcludeRead bool
// Whether to exclude archived chats from this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
ExcludeArchived bool
// Folder¹ ID
//
// Links:
// 1) https://core.telegram.org/api/folders
ID int
// Folder¹ name
//
// Links:
// 1) https://core.telegram.org/api/folders
Title string
// Folder¹ emoticon
//
// Links:
// 1) https://core.telegram.org/api/folders
//
// Use SetEmoticon and GetEmoticon helpers.
Emoticon string
// Pinned chats, folders¹ can have unlimited pinned chats
//
// Links:
// 1) https://core.telegram.org/api/folders
PinnedPeers []InputPeerClass
// Include the following chats in this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
IncludePeers []InputPeerClass
// Exclude the following chats from this folder¹
//
// Links:
// 1) https://core.telegram.org/api/folders
ExcludePeers []InputPeerClass
}
// DialogFilterTypeID is TL type id of DialogFilter.
const DialogFilterTypeID = 0x7438f7e8
// String implements fmt.Stringer.
func (d *DialogFilter) String() string {
if d == nil {
return "DialogFilter(nil)"
}
var sb strings.Builder
sb.WriteString("DialogFilter")
sb.WriteString("{\n")
sb.WriteString("\tFlags: ")
sb.WriteString(d.Flags.String())
sb.WriteString(",\n")
sb.WriteString("\tID: ")
sb.WriteString(fmt.Sprint(d.ID))
sb.WriteString(",\n")
sb.WriteString("\tTitle: ")
sb.WriteString(fmt.Sprint(d.Title))
sb.WriteString(",\n")
if d.Flags.Has(25) {
sb.WriteString("\tEmoticon: ")
sb.WriteString(fmt.Sprint(d.Emoticon))
sb.WriteString(",\n")
}
sb.WriteByte('[')
for _, v := range d.PinnedPeers {
sb.WriteString(fmt.Sprint(v))
}
sb.WriteByte(']')
sb.WriteByte('[')
for _, v := range d.IncludePeers {
sb.WriteString(fmt.Sprint(v))
}
sb.WriteByte(']')
sb.WriteByte('[')
for _, v := range d.ExcludePeers {
sb.WriteString(fmt.Sprint(v))
}
sb.WriteByte(']')
sb.WriteString("}")
return sb.String()
}
// Encode implements bin.Encoder.
func (d *DialogFilter) Encode(b *bin.Buffer) error {
if d == nil {
return fmt.Errorf("can't encode dialogFilter#7438f7e8 as nil")
}
b.PutID(DialogFilterTypeID)
if err := d.Flags.Encode(b); err != nil {
return fmt.Errorf("unable to encode dialogFilter#7438f7e8: field flags: %w", err)
}
b.PutInt(d.ID)
b.PutString(d.Title)
if d.Flags.Has(25) {
b.PutString(d.Emoticon)
}
b.PutVectorHeader(len(d.PinnedPeers))
for idx, v := range d.PinnedPeers {
if v == nil {
return fmt.Errorf("unable to encode dialogFilter#7438f7e8: field pinned_peers element with index %d is nil", idx)
}
if err := v.Encode(b); err != nil {
return fmt.Errorf("unable to encode dialogFilter#7438f7e8: field pinned_peers element with index %d: %w", idx, err)
}
}
b.PutVectorHeader(len(d.IncludePeers))
for idx, v := range d.IncludePeers {
if v == nil {
return fmt.Errorf("unable to encode dialogFilter#7438f7e8: field include_peers element with index %d is nil", idx)
}
if err := v.Encode(b); err != nil {
return fmt.Errorf("unable to encode dialogFilter#7438f7e8: field include_peers element with index %d: %w", idx, err)
}
}
b.PutVectorHeader(len(d.ExcludePeers))
for idx, v := range d.ExcludePeers {
if v == nil {
return fmt.Errorf("unable to encode dialogFilter#7438f7e8: field exclude_peers element with index %d is nil", idx)
}
if err := v.Encode(b); err != nil {
return fmt.Errorf("unable to encode dialogFilter#7438f7e8: field exclude_peers element with index %d: %w", idx, err)
}
}
return nil
}
// SetContacts sets value of Contacts conditional field.
func (d *DialogFilter) SetContacts(value bool) {
if value {
d.Flags.Set(0)
d.Contacts = true
} else {
d.Flags.Unset(0)
d.Contacts = false
}
}
// SetNonContacts sets value of NonContacts conditional field.
func (d *DialogFilter) SetNonContacts(value bool) {
if value {
d.Flags.Set(1)
d.NonContacts = true
} else {
d.Flags.Unset(1)
d.NonContacts = false
}
}
// SetGroups sets value of Groups conditional field.
func (d *DialogFilter) SetGroups(value bool) {
if value {
d.Flags.Set(2)
d.Groups = true
} else {
d.Flags.Unset(2)
d.Groups = false
}
}
// SetBroadcasts sets value of Broadcasts conditional field.
func (d *DialogFilter) SetBroadcasts(value bool) {
if value {
d.Flags.Set(3)
d.Broadcasts = true
} else {
d.Flags.Unset(3)
d.Broadcasts = false
}
}
// SetBots sets value of Bots conditional field.
func (d *DialogFilter) SetBots(value bool) {
if value {
d.Flags.Set(4)
d.Bots = true
} else {
d.Flags.Unset(4)
d.Bots = false
}
}
// SetExcludeMuted sets value of ExcludeMuted conditional field.
func (d *DialogFilter) SetExcludeMuted(value bool) {
if value {
d.Flags.Set(11)
d.ExcludeMuted = true
} else {
d.Flags.Unset(11)
d.ExcludeMuted = false
}
}
// SetExcludeRead sets value of ExcludeRead conditional field.
func (d *DialogFilter) SetExcludeRead(value bool) {
if value {
d.Flags.Set(12)
d.ExcludeRead = true
} else {
d.Flags.Unset(12)
d.ExcludeRead = false
}
}
// SetExcludeArchived sets value of ExcludeArchived conditional field.
func (d *DialogFilter) SetExcludeArchived(value bool) {
if value {
d.Flags.Set(13)
d.ExcludeArchived = true
} else {
d.Flags.Unset(13)
d.ExcludeArchived = false
}
}
// SetEmoticon sets value of Emoticon conditional field.
func (d *DialogFilter) SetEmoticon(value string) {
d.Flags.Set(25)
d.Emoticon = value
}
// GetEmoticon returns value of Emoticon conditional field and
// boolean which is true if field was set.
func (d *DialogFilter) GetEmoticon() (value string, ok bool) {
if !d.Flags.Has(25) {
return value, false
}
return d.Emoticon, true
}
// Decode implements bin.Decoder.
func (d *DialogFilter) Decode(b *bin.Buffer) error {
if d == nil {
return fmt.Errorf("can't decode dialogFilter#7438f7e8 to nil")
}
if err := b.ConsumeID(DialogFilterTypeID); err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: %w", err)
}
{
if err := d.Flags.Decode(b); err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field flags: %w", err)
}
}
d.Contacts = d.Flags.Has(0)
d.NonContacts = d.Flags.Has(1)
d.Groups = d.Flags.Has(2)
d.Broadcasts = d.Flags.Has(3)
d.Bots = d.Flags.Has(4)
d.ExcludeMuted = d.Flags.Has(11)
d.ExcludeRead = d.Flags.Has(12)
d.ExcludeArchived = d.Flags.Has(13)
{
value, err := b.Int()
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field id: %w", err)
}
d.ID = value
}
{
value, err := b.String()
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field title: %w", err)
}
d.Title = value
}
if d.Flags.Has(25) {
value, err := b.String()
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field emoticon: %w", err)
}
d.Emoticon = value
}
{
headerLen, err := b.VectorHeader()
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field pinned_peers: %w", err)
}
for idx := 0; idx < headerLen; idx++ {
value, err := DecodeInputPeer(b)
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field pinned_peers: %w", err)
}
d.PinnedPeers = append(d.PinnedPeers, value)
}
}
{
headerLen, err := b.VectorHeader()
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field include_peers: %w", err)
}
for idx := 0; idx < headerLen; idx++ {
value, err := DecodeInputPeer(b)
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field include_peers: %w", err)
}
d.IncludePeers = append(d.IncludePeers, value)
}
}
{
headerLen, err := b.VectorHeader()
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field exclude_peers: %w", err)
}
for idx := 0; idx < headerLen; idx++ {
value, err := DecodeInputPeer(b)
if err != nil {
return fmt.Errorf("unable to decode dialogFilter#7438f7e8: field exclude_peers: %w", err)
}
d.ExcludePeers = append(d.ExcludePeers, value)
}
}
return nil
}
// Ensuring interfaces in compile-time for DialogFilter.
var (
_ bin.Encoder = &DialogFilter{}
_ bin.Decoder = &DialogFilter{}
)
|
aQuaYi/Hands-On-Dependency-Injection-in-Go | ch02/02_open_closed_principle/07_handler_func.go | <reponame>aQuaYi/Hands-On-Dependency-Injection-in-Go<gh_stars>100-1000
package ocp
import (
"net/http"
)
// a HTTP health check handler in short form
func healthCheckShort(resp http.ResponseWriter, _ *http.Request) {
resp.WriteHeader(http.StatusNoContent)
}
func healthCheckShortUsage() {
http.Handle("/health", http.HandlerFunc(healthCheckShort))
}
|
paullewallencom/spring-978-1-7883-9242-6 | _src/ratings/src/main/java/com/packtpub/yummy/ratings/config/AmqpConfig.java | package com.packtpub.yummy.ratings.config;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.SubscribableChannel;
@Configuration
@EnableBinding(AmqpConfig.MessageSink.class)
public class AmqpConfig {
public interface MessageSink {
String BOOKMARK_DELETIONS = "bookmarkDeletions";
@Input
SubscribableChannel bookmarkDeletions();
}
}
|
trespasserw/MPS | core/project/source/jetbrains/mps/reloading/CompositeClassPathItem.java | /*
* Copyright 2003-2019 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.mps.reloading;
import jetbrains.mps.util.iterable.IterableEnumeration;
import org.jetbrains.annotations.Nullable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class CompositeClassPathItem extends AbstractClassPathItem {
private List<IClassPathItem> myChildren = new ArrayList<>();
public void add(IClassPathItem item) {
assert item != null;
myChildren.add(item);
}
@Override
public boolean hasClass(String name) {
for (IClassPathItem item : myChildren) {
if (item.hasClass(name)) {
return true;
}
}
return false;
}
@Nullable
@Override
public ClassBytes getClassBytes(String name) {
for (IClassPathItem item : myChildren) {
ClassBytes result = item.getClassBytes(name);
if (result != null) {
return result;
}
}
return null;
}
@Override
public URL getResource(String name) {
for (IClassPathItem item : myChildren) {
URL resource = item.getResource(name);
if (resource != null) {
return resource;
}
}
return null;
}
@Override
public Enumeration<URL> getResources(String name) {
List<URL> result = new ArrayList<>();
for (IClassPathItem item : myChildren) {
Enumeration<URL> resources = item.getResources(name);
while (resources.hasMoreElements()) {
result.add(resources.nextElement());
}
}
return new IterableEnumeration<>(result);
}
public List<IClassPathItem> getChildren() {
return new ArrayList<>(myChildren);
}
@Override
public List<RealClassPathItem> flatten() {
List<RealClassPathItem> result = new ArrayList<>();
for (IClassPathItem child : myChildren) {
result.addAll(child.flatten());
}
return result;
}
@Override
public CompositeClassPathItem optimize() {
List<RealClassPathItem> flattenedItems = flatten();
Iterator<RealClassPathItem> it = flattenedItems.iterator();
Set<String> alreadyVisited = new HashSet<>();
while (it.hasNext()) {
IClassPathItem item = it.next();
if (item instanceof FileClassPathItem) {
FileClassPathItem fcp = (FileClassPathItem) item;
if (alreadyVisited.contains(fcp.getPath())) {
it.remove();
} else {
alreadyVisited.add(fcp.getPath());
}
}
if (item instanceof JarFileClassPathItem) {
JarFileClassPathItem jfcp = (JarFileClassPathItem) item;
String path = jfcp.getFile().getAbsolutePath();
if (alreadyVisited.contains(path)) {
it.remove();
} else {
alreadyVisited.add(path);
}
}
}
CompositeClassPathItem result = new CompositeClassPathItem();
for (IClassPathItem item : flattenedItems) {
result.add(item);
}
return result;
}
public String toString() {
StringBuilder result = new StringBuilder("classpath {\n");
for (IClassPathItem child : myChildren) {
for (String s : child.toString().split("/[\n]/")) {
result.append('\t').append(s).append('\n');
}
}
result.append('}');
return result.toString();
}
}
|
RazZziel/wine-dplay | dlls/wined3d/swapchain.c | <reponame>RazZziel/wine-dplay
/*
*IDirect3DSwapChain9 implementation
*
*Copyright 2002-2003 <NAME>
*Copyright 2002-2003 <NAME>
*Copyright 2005 <NAME>
*Copyright 2007-2008 <NAME> for CodeWeavers
*
*This library is free software; you can redistribute it and/or
*modify it under the terms of the GNU Lesser General Public
*License as published by the Free Software Foundation; either
*version 2.1 of the License, or (at your option) any later version.
*
*This library is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
*Lesser General Public License for more details.
*
*You should have received a copy of the GNU Lesser General Public
*License along with this library; if not, write to the Free Software
*Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "config.h"
#include "wined3d_private.h"
/*TODO: some of the additional parameters may be required to
set the gamma ramp (for some weird reason microsoft have left swap gammaramp in device
but it operates on a swapchain, it may be a good idea to move it to IWineD3DSwapChain for IWineD3D)*/
WINE_DEFAULT_DEBUG_CHANNEL(d3d);
WINE_DECLARE_DEBUG_CHANNEL(fps);
#define GLINFO_LOCATION This->wineD3DDevice->adapter->gl_info
/*IWineD3DSwapChain parts follow: */
static void WINAPI IWineD3DSwapChainImpl_Destroy(IWineD3DSwapChain *iface, D3DCB_DESTROYSURFACEFN D3DCB_DestroyRenderTarget) {
IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
WINED3DDISPLAYMODE mode;
unsigned int i;
TRACE("Destroying swapchain %p\n", iface);
IWineD3DSwapChain_SetGammaRamp(iface, 0, &This->orig_gamma);
/* Release the swapchain's draw buffers. Make sure This->backBuffer[0] is
* the last buffer to be destroyed, FindContext() depends on that. */
if (This->frontBuffer)
{
IWineD3DSurface_SetContainer(This->frontBuffer, 0);
if (D3DCB_DestroyRenderTarget(This->frontBuffer))
{
FIXME("(%p) Something's still holding the front buffer (%p).\n",
This, This->frontBuffer);
}
This->frontBuffer = NULL;
}
if (This->backBuffer)
{
UINT i = This->presentParms.BackBufferCount;
while (i--)
{
IWineD3DSurface_SetContainer(This->backBuffer[i], 0);
if (D3DCB_DestroyRenderTarget(This->backBuffer[i]))
FIXME("(%p) Something's still holding back buffer %u (%p).\n",
This, i, This->backBuffer[i]);
}
HeapFree(GetProcessHeap(), 0, This->backBuffer);
This->backBuffer = NULL;
}
for (i = 0; i < This->num_contexts; ++i)
{
DestroyContext(This->wineD3DDevice, This->context[i]);
}
/* Restore the screen resolution if we rendered in fullscreen
* This will restore the screen resolution to what it was before creating the swapchain. In case of d3d8 and d3d9
* this will be the original desktop resolution. In case of d3d7 this will be a NOP because ddraw sets the resolution
* before starting up Direct3D, thus orig_width and orig_height will be equal to the modes in the presentation params
*/
if(This->presentParms.Windowed == FALSE && This->presentParms.AutoRestoreDisplayMode) {
mode.Width = This->orig_width;
mode.Height = This->orig_height;
mode.RefreshRate = 0;
mode.Format = This->orig_fmt;
IWineD3DDevice_SetDisplayMode((IWineD3DDevice *) This->wineD3DDevice, 0, &mode);
}
HeapFree(GetProcessHeap(), 0, This->context);
HeapFree(GetProcessHeap(), 0, This);
}
static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
unsigned int sync;
int retval;
ActivateContext(This->wineD3DDevice, This->backBuffer[0], CTXUSAGE_RESOURCELOAD);
/* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
if(This->wineD3DDevice->bCursorVisible && This->wineD3DDevice->cursorTexture) {
IWineD3DSurfaceImpl cursor;
RECT destRect = {This->wineD3DDevice->xScreenSpace - This->wineD3DDevice->xHotSpot,
This->wineD3DDevice->yScreenSpace - This->wineD3DDevice->yHotSpot,
This->wineD3DDevice->xScreenSpace + This->wineD3DDevice->cursorWidth - This->wineD3DDevice->xHotSpot,
This->wineD3DDevice->yScreenSpace + This->wineD3DDevice->cursorHeight - This->wineD3DDevice->yHotSpot};
TRACE("Rendering the cursor. Creating fake surface at %p\n", &cursor);
/* Build a fake surface to call the Blitting code. It is not possible to use the interface passed by
* the application because we are only supposed to copy the information out. Using a fake surface
* allows to use the Blitting engine and avoid copying the whole texture -> render target blitting code.
*/
memset(&cursor, 0, sizeof(cursor));
cursor.lpVtbl = &IWineD3DSurface_Vtbl;
cursor.resource.ref = 1;
cursor.resource.wineD3DDevice = This->wineD3DDevice;
cursor.resource.pool = WINED3DPOOL_SCRATCH;
cursor.resource.format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->wineD3DDevice->adapter->gl_info);
cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
cursor.texture_name = This->wineD3DDevice->cursorTexture;
cursor.texture_target = GL_TEXTURE_2D;
cursor.texture_level = 0;
cursor.currentDesc.Width = This->wineD3DDevice->cursorWidth;
cursor.currentDesc.Height = This->wineD3DDevice->cursorHeight;
cursor.glRect.left = 0;
cursor.glRect.top = 0;
cursor.glRect.right = cursor.currentDesc.Width;
cursor.glRect.bottom = cursor.currentDesc.Height;
/* The cursor must have pow2 sizes */
cursor.pow2Width = cursor.currentDesc.Width;
cursor.pow2Height = cursor.currentDesc.Height;
/* The surface is in the texture */
cursor.Flags |= SFLAG_INTEXTURE;
/* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
* which is exactly what we want :-)
*/
if (This->presentParms.Windowed) {
MapWindowPoints(NULL, This->win_handle, (LPPOINT)&destRect, 2);
}
IWineD3DSurface_Blt(This->backBuffer[0], &destRect, (IWineD3DSurface *)&cursor,
NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
}
if(This->wineD3DDevice->logo_surface) {
/* Blit the logo into the upper left corner of the drawable */
IWineD3DSurface_BltFast(This->backBuffer[0], 0, 0, This->wineD3DDevice->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
}
if (pSourceRect || pDestRect) FIXME("Unhandled present rects %s/%s\n", wine_dbgstr_rect(pSourceRect), wine_dbgstr_rect(pDestRect));
/* TODO: If only source rect or dest rect are supplied then clip the window to match */
TRACE("presetting HDC %p\n", This->context[0]->hdc);
/* Don't call checkGLcall, as glGetError is not applicable here */
if (hDestWindowOverride && This->win_handle != hDestWindowOverride) {
IWineD3DSwapChain_SetDestWindowOverride(iface, hDestWindowOverride);
}
SwapBuffers(This->context[0]->hdc); /* TODO: cycle through the swapchain buffers */
TRACE("SwapBuffers called, Starting new frame\n");
/* FPS support */
if (TRACE_ON(fps))
{
DWORD time = GetTickCount();
This->frames++;
/* every 1.5 seconds */
if (time - This->prev_time > 1500) {
TRACE_(fps)("%p @ approx %.2ffps\n", This, 1000.0*This->frames/(time - This->prev_time));
This->prev_time = time;
This->frames = 0;
}
}
#if defined(FRAME_DEBUGGING)
{
if (GetFileAttributesA("C:\\D3DTRACE") != INVALID_FILE_ATTRIBUTES) {
if (!isOn) {
isOn = TRUE;
FIXME("Enabling D3D Trace\n");
__WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 1);
#if defined(SHOW_FRAME_MAKEUP)
FIXME("Singe Frame snapshots Starting\n");
isDumpingFrames = TRUE;
ENTER_GL();
glClear(GL_COLOR_BUFFER_BIT);
LEAVE_GL();
#endif
#if defined(SINGLE_FRAME_DEBUGGING)
} else {
#if defined(SHOW_FRAME_MAKEUP)
FIXME("Singe Frame snapshots Finishing\n");
isDumpingFrames = FALSE;
#endif
FIXME("Singe Frame trace complete\n");
DeleteFileA("C:\\D3DTRACE");
__WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
#endif
}
} else {
if (isOn) {
isOn = FALSE;
#if defined(SHOW_FRAME_MAKEUP)
FIXME("Single Frame snapshots Finishing\n");
isDumpingFrames = FALSE;
#endif
FIXME("Disabling D3D Trace\n");
__WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
}
}
}
#endif
/* This is disabled, but the code left in for debug purposes.
*
* Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
* we can clear it with some ugly color to make bad drawing visible and ease debugging.
* The Debug runtime does the same on Windows. However, a few games do not redraw the
* screen properly, like Max Payne 2, which leaves a few pixels undefined.
*
* Tests show that the content of the back buffer after a discard flip is indeed not
* reliable, so no game can depend on the exact content. However, it resembles the
* old contents in some way, for example by showing fragments at other locations. In
* general, the color theme is still intact. So Max payne, which draws rather dark scenes
* gets a dark background image. If we clear it with a bright ugly color, the game's
* bug shows up much more than it does on Windows, and the players see single pixels
* with wrong colors.
* (The Max Payne bug has been confirmed on Windows with the debug runtime)
*/
if (FALSE && This->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD) {
TRACE("Clearing the color buffer with cyan color\n");
IWineD3DDevice_Clear((IWineD3DDevice*)This->wineD3DDevice, 0, NULL,
WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
}
if(((IWineD3DSurfaceImpl *) This->frontBuffer)->Flags & SFLAG_INSYSMEM ||
((IWineD3DSurfaceImpl *) This->backBuffer[0])->Flags & SFLAG_INSYSMEM ) {
/* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying */
IWineD3DSurfaceImpl *front = (IWineD3DSurfaceImpl *) This->frontBuffer;
IWineD3DSurfaceImpl *back = (IWineD3DSurfaceImpl *) This->backBuffer[0];
if(front->resource.size == back->resource.size) {
DWORD fbflags;
flip_surface(front, back);
/* Tell the front buffer surface that is has been modified. However,
* the other locations were preserved during that, so keep the flags.
* This serves to update the emulated overlay, if any
*/
fbflags = front->Flags;
IWineD3DSurface_ModifyLocation(This->frontBuffer, SFLAG_INDRAWABLE, TRUE);
front->Flags = fbflags;
} else {
IWineD3DSurface_ModifyLocation((IWineD3DSurface *) front, SFLAG_INDRAWABLE, TRUE);
IWineD3DSurface_ModifyLocation((IWineD3DSurface *) back, SFLAG_INDRAWABLE, TRUE);
}
} else {
IWineD3DSurface_ModifyLocation(This->frontBuffer, SFLAG_INDRAWABLE, TRUE);
/* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
* and INTEXTURE copies can keep their old content if they have any defined content.
* If the swapeffect is COPY, the content remains the same. If it is FLIP however,
* the texture / sysmem copy needs to be reloaded from the drawable
*/
if(This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP) {
IWineD3DSurface_ModifyLocation(This->backBuffer[0], SFLAG_INDRAWABLE, TRUE);
}
}
if (This->wineD3DDevice->stencilBufferTarget) {
if (This->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
|| ((IWineD3DSurfaceImpl *)This->wineD3DDevice->stencilBufferTarget)->Flags & SFLAG_DISCARD) {
surface_modify_ds_location(This->wineD3DDevice->stencilBufferTarget, SFLAG_DS_DISCARDED);
}
}
if(This->presentParms.PresentationInterval != WINED3DPRESENT_INTERVAL_IMMEDIATE && GL_SUPPORT(SGI_VIDEO_SYNC)) {
retval = GL_EXTCALL(glXGetVideoSyncSGI(&sync));
if(retval != 0) {
ERR("glXGetVideoSyncSGI failed(retval = %d\n", retval);
}
switch(This->presentParms.PresentationInterval) {
case WINED3DPRESENT_INTERVAL_DEFAULT:
case WINED3DPRESENT_INTERVAL_ONE:
if(sync <= This->vSyncCounter) {
retval = GL_EXTCALL(glXWaitVideoSyncSGI(1, 0, &This->vSyncCounter));
} else {
This->vSyncCounter = sync;
}
break;
case WINED3DPRESENT_INTERVAL_TWO:
if(sync <= This->vSyncCounter + 1) {
retval = GL_EXTCALL(glXWaitVideoSyncSGI(2, This->vSyncCounter & 0x1, &This->vSyncCounter));
} else {
This->vSyncCounter = sync;
}
break;
case WINED3DPRESENT_INTERVAL_THREE:
if(sync <= This->vSyncCounter + 2) {
retval = GL_EXTCALL(glXWaitVideoSyncSGI(3, This->vSyncCounter % 0x3, &This->vSyncCounter));
} else {
This->vSyncCounter = sync;
}
break;
case WINED3DPRESENT_INTERVAL_FOUR:
if(sync <= This->vSyncCounter + 3) {
retval = GL_EXTCALL(glXWaitVideoSyncSGI(4, This->vSyncCounter & 0x3, &This->vSyncCounter));
} else {
This->vSyncCounter = sync;
}
break;
default:
FIXME("Unknown presentation interval %08x\n", This->presentParms.PresentationInterval);
}
}
TRACE("returning\n");
return WINED3D_OK;
}
static HRESULT WINAPI IWineD3DSwapChainImpl_SetDestWindowOverride(IWineD3DSwapChain *iface, HWND window) {
IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
WINED3DLOCKED_RECT r;
BYTE *mem;
if(window == This->win_handle) return WINED3D_OK;
TRACE("Performing dest override of swapchain %p from window %p to %p\n", This, This->win_handle, window);
if(This->context[0] == This->wineD3DDevice->contexts[0]) {
/* The primary context 'owns' all the opengl resources. Destroying and recreating that context requires downloading
* all opengl resources, deleting the gl resources, destroying all other contexts, then recreating all other contexts
* and reload the resources
*/
delete_opengl_contexts((IWineD3DDevice *) This->wineD3DDevice, iface);
This->win_handle = window;
create_primary_opengl_context((IWineD3DDevice *) This->wineD3DDevice, iface);
} else {
This->win_handle = window;
/* The old back buffer has to be copied over to the new back buffer. A lockrect - switchcontext - unlockrect
* would suffice in theory, but it is rather nasty and may cause troubles with future changes of the locking code
* So lock read only, copy the surface out, then lock with the discard flag and write back
*/
IWineD3DSurface_LockRect(This->backBuffer[0], &r, NULL, WINED3DLOCK_READONLY);
mem = HeapAlloc(GetProcessHeap(), 0, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
memcpy(mem, r.pBits, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
IWineD3DSurface_UnlockRect(This->backBuffer[0]);
DestroyContext(This->wineD3DDevice, This->context[0]);
This->context[0] = CreateContext(This->wineD3DDevice, (IWineD3DSurfaceImpl *) This->frontBuffer, This->win_handle, FALSE /* pbuffer */, &This->presentParms);
IWineD3DSurface_LockRect(This->backBuffer[0], &r, NULL, WINED3DLOCK_DISCARD);
memcpy(r.pBits, mem, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
HeapFree(GetProcessHeap(), 0, mem);
IWineD3DSurface_UnlockRect(This->backBuffer[0]);
}
return WINED3D_OK;
}
const IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl =
{
/* IUnknown */
IWineD3DBaseSwapChainImpl_QueryInterface,
IWineD3DBaseSwapChainImpl_AddRef,
IWineD3DBaseSwapChainImpl_Release,
/* IWineD3DSwapChain */
IWineD3DBaseSwapChainImpl_GetParent,
IWineD3DSwapChainImpl_Destroy,
IWineD3DBaseSwapChainImpl_GetDevice,
IWineD3DSwapChainImpl_Present,
IWineD3DSwapChainImpl_SetDestWindowOverride,
IWineD3DBaseSwapChainImpl_GetFrontBufferData,
IWineD3DBaseSwapChainImpl_GetBackBuffer,
IWineD3DBaseSwapChainImpl_GetRasterStatus,
IWineD3DBaseSwapChainImpl_GetDisplayMode,
IWineD3DBaseSwapChainImpl_GetPresentParameters,
IWineD3DBaseSwapChainImpl_SetGammaRamp,
IWineD3DBaseSwapChainImpl_GetGammaRamp
};
struct wined3d_context *IWineD3DSwapChainImpl_CreateContextForThread(IWineD3DSwapChain *iface)
{
IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *) iface;
struct wined3d_context **newArray;
struct wined3d_context *ctx;
TRACE("Creating a new context for swapchain %p, thread %d\n", This, GetCurrentThreadId());
ctx = CreateContext(This->wineD3DDevice, (IWineD3DSurfaceImpl *) This->frontBuffer,
This->context[0]->win_handle, FALSE /* pbuffer */, &This->presentParms);
if(!ctx) {
ERR("Failed to create a new context for the swapchain\n");
return NULL;
}
newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * This->num_contexts + 1);
if(!newArray) {
ERR("Out of memory when trying to allocate a new context array\n");
DestroyContext(This->wineD3DDevice, ctx);
return NULL;
}
memcpy(newArray, This->context, sizeof(*newArray) * This->num_contexts);
HeapFree(GetProcessHeap(), 0, This->context);
newArray[This->num_contexts] = ctx;
This->context = newArray;
This->num_contexts++;
TRACE("Returning context %p\n", ctx);
return ctx;
}
void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height)
{
IWineD3DSurfaceImpl *surface = (IWineD3DSurfaceImpl *)context->current_rt;
/* The drawable size of an onscreen drawable is the surface size.
* (Actually: The window size, but the surface is created in window size) */
*width = surface->currentDesc.Width;
*height = surface->currentDesc.Height;
}
|
angry-tony/Portus-20170827 | config/initializers/swagger.rb | <reponame>angry-tony/Portus-20170827
unless Rails.env.production?
protocol = ENV["PORTUS_CHECK_SSL_USAGE_ENABLED"] ? "https://" : "http://"
GrapeSwaggerRails.options.url = "/api/swagger_doc.json"
GrapeSwaggerRails.options.app_url = "#{protocol}#{APP_CONFIG["machine_fqdn"]["value"]}"
end
|
wilebeast/FireFox-OS | B2G/gecko/browser/devtools/highlighter/test/browser_inspector_highlighter_autohide.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
let doc;
function createDocument() {
doc.body.innerHTML = '<h1>highlighter autohide test</h1>';
InspectorUI.openInspectorUI(doc.querySelector("h1"));
// Open the sidebar and wait for the default view (the rule view) to show.
InspectorUI.currentInspector.once("sidebaractivated-ruleview", inspectorRuleViewOpened);
InspectorUI.sidebar.show();
InspectorUI.sidebar.activatePanel("ruleview");
}
function inspectorRuleViewOpened() {
let deck = InspectorUI.sidebar._deck;
EventUtils.synthesizeMouse(InspectorUI.highlighter.highlighterContainer, 2, 2, {type: "mousemove"}, window);
executeSoon(function() {
ok(!InspectorUI.highlighter.hidden, "Outline visible (1)");
EventUtils.synthesizeMouse(deck, 10, 2, {type: "mousemove"}, window);
executeSoon(function() {
ok(InspectorUI.highlighter.hidden, "Outline not visible");
EventUtils.synthesizeMouse(deck, -10, 2, {type: "mousemove"}, window);
executeSoon(function() {
ok(!InspectorUI.highlighter.hidden, "Outline visible (2)");
finishTest();
});
});
});
}
function finishTest() {
InspectorUI.closeInspectorUI();
gBrowser.removeCurrentTab();
finish();
}
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab();
gBrowser.selectedBrowser.addEventListener("load", function() {
gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
doc = content.document;
waitForFocus(createDocument, content);
}, true);
content.location = "data:text/html,basic tests for highlighter";
}
|
xlf999/AdsDemo | MobGiAdSDK/AggregationAdThirdSDKs/Common/AdxAdsComponent.framework/Headers/MobGiReportDBLogicManager.h | <gh_stars>1-10
//
// AdxDataStoreManager.h
// AdxAdsComponent
//
// Created by star.liao on 2017/10/20.
// Copyright © 2017年 com.idreamsky. All rights reserved.
//
#import <Foundation/Foundation.h>
@class TReportRecordObject;
@interface MobGiReportDBLogicManager : NSObject
+ (void)createReportDataTable:(void (^)(BOOL result))block;
+(void) isLastExitRecordExist:(NSString*)sessionId
resultBlock:(void (^)(BOOL result))block;
+(void) updateLastExitRecord:(NSString*)sessionId
eventTime:(NSString*)eventTime
reportData:(NSString*)reportData
reportDate:(NSString*)reportDate
resultBlock:(void (^)(BOOL result))block;
+(void)addExitReportData:(NSString*)sessionId
eventTime:(NSString*)eventTime
recordInfo:(NSString*)recordInfo
clientTime:(NSString*)timeStamp
resultBlock:(void (^)(BOOL result))block;
//记录进程内(包括前后台切换),sessionid的记录
+(void)addSessionIdRecord:(NSString*)sessionId
clientTime:(NSString*)timeStamp
resultBlock:(void (^)(BOOL result))block;
//获取上一次进程最后使用的sessionid,这种情况一般会存在于切换到后台一分钟之后,会出现,否则是启动时候的sessionid
+(void) getLastProcessSessionIdRecord:(void (^)(NSMutableArray<NSString*>* results))block;
//判断上一次进程内保存的sessionid是否存在
+(void) isSessionIdRecordExist:(NSString*)sessionId
resultBlock:(void (^)(BOOL result))block;
+(void)deleteCurrentProcessLastSessionId:(NSString*)sessionId
resultBlock:(void (^)(BOOL result))block;
+(void)deleteExitRecordData:(NSString*)reportData
sessionId:(NSString*)sessionId
resultBlock:(void (^)(BOOL result))block;
+(void) getLastSessionExitRecords:(void (^)(NSMutableArray<TReportRecordObject*>* results))block;
@end
|
ItzzRitik/XtremePad | org/eclipse/swt/custom/StyledTextPrintOptions.java | <filename>org/eclipse/swt/custom/StyledTextPrintOptions.java
/*******************************************************************************
* Copyright (c) 2000, 2008 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
*******************************************************************************/
package org.eclipse.swt.custom;
/**
* Use StyledTextPrintOptions to specify printing options for the
* StyledText.print(Printer, StyledTextPrintOptions) API.
* <p>
* The following example prints a right aligned page number in the footer,
* sets the job name to "Example" and prints line background colors but no other
* formatting:
* </p>
* <pre>
* StyledTextPrintOptions options = new StyledTextPrintOptions();
* options.footer = "\t\t<page>";
* options.jobName = "Example";
* options.printLineBackground = true;
*
* Runnable runnable = styledText.print(new Printer(), options);
* runnable.run();
* </pre>
*
* @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a>
*
* @since 2.1
*/
public class StyledTextPrintOptions {
/**
* Page number placeholder constant for use in <code>header</code>
* and <code>footer</code>. Value is <code><page></code>
*/
public static final String PAGE_TAG = "<page>";
/**
* Separator constant for use in <code>header</code> and
* <code>footer</code>. Value is <code>\t</code>
*/
public static final String SEPARATOR = "\t";
/**
* Formatted text to print in the header of each page.
* <p>"left '\t' center '\t' right"</p>
* <p>left, center, right = <page> | #CDATA</p>
* <p>Header and footer are defined as three separate regions for arbitrary
* text or the page number placeholder <page>
* (<code>StyledTextPrintOptions.PAGE_TAG</code>). The three regions are
* left aligned, centered and right aligned. They are separated by a tab
* character (<code>StyledTextPrintOptions.SEPARATOR</code>).
*/
public String header = null;
/**
* Formatted text to print in the footer of each page.
* <p>"left '\t' center '\t' right"</p>
* <p>left, center, right = <page> | #CDATA</p>
* <p>Header and footer are defined as three separate regions for arbitrary
* text or the page number placeholder <page>
* (<code>StyledTextPrintOptions.PAGE_TAG</code>). The three regions are
* left aligned, centered and right aligned. They are separated by a tab
* character (<code>StyledTextPrintOptions.SEPARATOR</code>).
*/
public String footer = null;
/**
* Name of the print job.
*/
public String jobName = null;
/**
* Print the text foreground color. Default value is <code>false</code>.
*/
public boolean printTextForeground = false;
/**
* Print the text background color. Default value is <code>false</code>.
*/
public boolean printTextBackground = false;
/**
* Print the font styles. Default value is <code>false</code>.
*/
public boolean printTextFontStyle = false;
/**
* Print the line background color. Default value is <code>false</code>.
*/
public boolean printLineBackground = false;
/**
* Print line numbers. Default value is <code>false</code>.
*
* @since 3.3
*/
public boolean printLineNumbers = false;
/**
* Labels used for printing line numbers.
*
* @since 3.4
*/
public String[] lineLabels = null;
}
|
NewProggie/ecal | lib/Udpcap/src/udpcap_socket_private.h | /* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
#pragma once
#include <udpcap/host_address.h>
#include <vector>
#include <set>
#include <memory>
#include <chrono>
#include <deque>
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <pcap.h> // Pcap API
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable: 4800 4200)
#endif // _MSC_VER
#include <Packet.h> // Pcap++
#include <IPv4Layer.h> // Pcap++ IPv4
#include <UdpLayer.h> // Pcap++ UDP
#include <IPReassembly.h> // Pcap++ de-fragmentation of IP packets
#ifdef _MSC_VER
#pragma warning( pop )
#endif // _MSC_VER
namespace Udpcap
{
class UdpcapSocketPrivate
{
//////////////////////////////////////////
//// Helper Structs
//////////////////////////////////////////
private:
struct PcapDev
{
PcapDev(pcap_t* pcap_handle, bool is_loopback, const std::string& device_name)
: pcap_handle_(pcap_handle)
, is_loopback_ (is_loopback)
, device_name_(device_name)
{}
pcap_t* pcap_handle_;
bool is_loopback_;
std::string device_name_;
};
struct CallbackArgsVector
{
CallbackArgsVector(std::vector<char>* destination_vector, HostAddress* source_address, uint16_t* source_port, uint16_t bound_port, pcpp::LinkLayerType link_type, pcpp::IPReassembly* ip_reassembly)
: destination_vector_(destination_vector)
, source_address_ (source_address)
, source_port_ (source_port)
, success_ (false)
, link_type_ (link_type)
, bound_port_ (bound_port)
, ip_reassembly_ (ip_reassembly)
{}
std::vector<char>* const destination_vector_;
HostAddress* const source_address_;
uint16_t* const source_port_;
bool success_;
pcpp::LinkLayerType link_type_;
const uint16_t bound_port_;
pcpp::IPReassembly* const ip_reassembly_;
};
struct CallbackArgsRawPtr
{
CallbackArgsRawPtr(char* destination_buffer, size_t destination_buffer_size, HostAddress* source_address, uint16_t* source_port, uint16_t bound_port, pcpp::LinkLayerType link_type, pcpp::IPReassembly* ip_reassembly)
: destination_buffer_ (destination_buffer)
, destination_buffer_size_(destination_buffer_size)
, bytes_copied_ (0)
, source_address_ (source_address)
, source_port_ (source_port)
, success_ (false)
, link_type_ (link_type)
, bound_port_ (bound_port)
, ip_reassembly_ (ip_reassembly)
{}
char* const destination_buffer_;
const size_t destination_buffer_size_;
size_t bytes_copied_;
HostAddress* const source_address_;
uint16_t* const source_port_;
bool success_;
pcpp::LinkLayerType link_type_;
const uint16_t bound_port_;
pcpp::IPReassembly* const ip_reassembly_;
};
//////////////////////////////////////////
//// Socket API
//////////////////////////////////////////
public:
static const int MAX_PACKET_SIZE = 65536; // Npcap Doc: A snapshot length of 65535 should be sufficient, on most if not all networks, to capture all the data available from the packet.
UdpcapSocketPrivate();
~UdpcapSocketPrivate();
UdpcapSocketPrivate(UdpcapSocketPrivate const&) = delete;
UdpcapSocketPrivate& operator= (UdpcapSocketPrivate const&) = delete;
bool isValid() const;
bool bind(const HostAddress& local_address, uint16_t local_port);
bool isBound() const;
HostAddress localAddress() const;
uint16_t localPort() const;
bool setReceiveBufferSize(int buffer_size);
bool hasPendingDatagrams() const;
std::vector<char> receiveDatagram(HostAddress* source_address = nullptr, uint16_t* source_port = nullptr);
std::vector<char> receiveDatagram(unsigned long timeout_ms, HostAddress* source_address = nullptr, uint16_t* source_port = nullptr);
size_t receiveDatagram(char* data, size_t max_len, HostAddress* source_address = nullptr, uint16_t* source_port = nullptr);
size_t receiveDatagram(char* data, size_t max_len, unsigned long timeout_ms, HostAddress* source_address = nullptr, uint16_t* source_port = nullptr);
bool joinMulticastGroup(const HostAddress& group_address);
bool leaveMulticastGroup(const HostAddress& group_address);
void setMulticastLoopbackEnabled(bool enabled);
bool isMulticastLoopbackEnabled() const;
void close();
//////////////////////////////////////////
//// Internal
//////////////////////////////////////////
private:
// RAII for pcap_if_t*
typedef std::unique_ptr<pcap_if_t*, void(*)(pcap_if_t**)> pcap_if_t_uniqueptr;
static std::pair<std::string, std::string> getDeviceByIp(const HostAddress& ip);
static std::vector<std::pair<std::string, std::string>> getAllDevices();
static std::string getMac(pcap_t* const pcap_handle);
bool openPcapDevice(const std::string& device_name);
std::string createFilterString(PcapDev& pcap_dev) const;
void updateCaptureFilter(PcapDev& pcap_dev);
void updateAllCaptureFilters();
void kickstartLoopbackMulticast() const;
// Callbacks
static void PacketHandlerVector(unsigned char* param, const struct pcap_pkthdr* header, const unsigned char* pkt_data);
static void FillCallbackArgsVector(CallbackArgsVector* callback_args, pcpp::IPv4Layer* ip_layer, pcpp::UdpLayer* udp_layer);
static void PacketHandlerRawPtr(unsigned char* param, const struct pcap_pkthdr* header, const unsigned char* pkt_data);
static void FillCallbackArgsRawPtr(CallbackArgsRawPtr* callback_args, pcpp::IPv4Layer* ip_layer, pcpp::UdpLayer* udp_layer);
private:
bool is_valid_; /**< If the socket is valid and ready to use (e.g. npcap was initialized successfully) */
bool bound_state_; /**< Whether the socket is in bound state and ready to receive data */
HostAddress bound_address_; /**< Local interface address used to read data from */
uint16_t bound_port_; /**< Local port to read data from */
std::set<HostAddress> multicast_groups_;
bool multicast_loopback_enabled_; /**< Winsocks style IP_MULTICAST_LOOP: if enabled, the socket can receive loopback multicast packages */
std::vector<PcapDev> pcap_devices_;
std::vector<HANDLE> pcap_win32_handles_;
pcpp::IPReassembly ip_reassembly_;
int receive_buffer_;
};
}
|
henrikgruner/Programvareutvikling | backend/auction/reports/migrations/0002_auto_20190326_1421.py | # Generated by Django 2.1.5 on 2019-03-26 13:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("reports", "0001_initial")]
operations = [
migrations.RenameField(
model_name="report",
old_name="reportDescription",
new_name="report_description",
)
]
|
gangababu/rultor | rultor-web/src/main/java/com/rultor/web/StandRs.java | <gh_stars>0
/**
* Copyright (c) 2009-2013, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com 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 com.rultor.web;
import com.jcabi.aspects.Loggable;
import com.jcabi.aspects.Tv;
import com.jcabi.immutable.ArraySet;
import com.jcabi.urn.URN;
import com.rexsl.page.JaxbBundle;
import com.rexsl.page.Link;
import com.rexsl.page.PageBuilder;
import com.rultor.snapshot.Snapshot;
import com.rultor.snapshot.XSLT;
import com.rultor.spi.ACL;
import com.rultor.spi.Arguments;
import com.rultor.spi.Pulse;
import com.rultor.spi.Repo;
import com.rultor.spi.SpecException;
import com.rultor.spi.Stand;
import com.rultor.spi.Tag;
import com.rultor.spi.Wallet;
import com.rultor.spi.Work;
import com.rultor.tools.Exceptions;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.xml.transform.TransformerException;
import org.xembly.Directives;
import org.xembly.ImpossibleModificationException;
import org.xembly.XemblySyntaxException;
/**
* Stand front page.
*
* @author <NAME> (<EMAIL>)
* @version $Id$
* @since 1.0
* @checkstyle MultipleStringLiterals (500 lines)
* @checkstyle ClassDataAbstractionCoupling (500 lines)
* @checkstyle ClassFanOutComplexity (500 lines)
*/
@Path("/s/{stand:[\\w\\-]+}")
@Loggable(Loggable.DEBUG)
@SuppressWarnings({ "PMD.ExcessiveImports", "PMD.TooManyMethods" })
public final class StandRs extends BaseRs {
/**
* List of open pulses.
*/
private static final String QUERY_OPEN = "open";
/**
* ID of pulse.
*/
private static final String QUERY_ID = "id";
/**
* Stand name.
*/
private transient String name;
/**
* Names of pulses to show open.
*/
private final transient Set<String> open = new TreeSet<String>();
/**
* Inject it from query.
* @param stand Stand name
*/
@PathParam("stand")
public void setName(@NotNull(message = "stand name can't be NULL")
final String stand) {
this.name = stand;
}
/**
* Inject it from query.
* @param names Names of pulses
*/
@QueryParam(StandRs.QUERY_OPEN)
public void setPulses(final List<String> names) {
if (names != null) {
this.open.addAll(names);
}
}
/**
* Get entrance page JAX-RS response.
* @return The JAX-RS response
*/
@GET
@Path("/")
public Response index() {
return new PageBuilder()
.stylesheet("/xsl/stand.xsl")
.build(EmptyPage.class)
.init(this)
.link(
new Link(
"edit",
this.uriInfo().getBaseUriBuilder()
.clone()
.path(AclRs.class)
.build(this.name)
)
)
.link(new Link("collapse", this.self(new ArrayList<String>(0))))
.append(
new Breadcrumbs()
.with("stands")
.with("edit", this.name)
.with("collapse", "stand")
.bundle()
)
.append(new JaxbBundle("stand", this.name))
.append(this.pulses(this.stand().pulses().iterator(), Tv.TWENTY))
.render()
.build();
}
/**
* Get snapshot HTML for a pulse.
* @param uid Unique identifier of a pulse
* @return The JAX-RS response
*/
@GET
@Path("/fetch")
@Produces(MediaType.TEXT_HTML)
public Response fetch(@QueryParam(StandRs.QUERY_ID) final String uid) {
Response resp;
try {
resp = Response.ok().entity(
new XSLT(
this.render(
new JaxbBundle("div"),
this.stand().pulses().tail(uid).iterator().next()
).element(),
this.getClass().getResourceAsStream("fetch.xsl")
).xml()
).build();
} catch (TransformerException ex) {
resp = Response.serverError().entity(
Exceptions.stacktrace(ex)
).build();
} catch (IOException ex) {
resp = Response.serverError().entity(
Exceptions.stacktrace(ex)
).build();
}
return resp;
}
/**
* Get stand.
* @return The stand
*/
private Stand stand() {
final Stand stand;
try {
stand = this.users().stand(this.name);
} catch (NoSuchElementException ex) {
throw this.flash().redirect(this.uriInfo().getBaseUri(), ex);
}
if (!stand.owner().equals(this.user().urn())
&& !this.acl(stand).canView(this.user().urn())) {
throw this.flash().redirect(
this.uriInfo().getBaseUri(),
String.format("access denied to stand `%s`", this.name),
Level.SEVERE
);
}
return stand;
}
/**
* All pulses of the stand.
* @param pulses All pulses to show
* @param maximum Maximum to show
* @return Collection of JAXB stands
*/
private JaxbBundle pulses(final Iterator<Pulse> pulses, final int maximum) {
JaxbBundle bundle = new JaxbBundle("pulses");
int pos;
for (pos = 0; pos < maximum; ++pos) {
if (!pulses.hasNext()) {
break;
}
bundle = bundle.add(this.pulse(pulses.next()));
}
return bundle;
}
/**
* Convert pulse to JaxbBundle.
* @param pulse The pulse
* @return Bundle
*/
private JaxbBundle pulse(final Pulse pulse) {
final String uid = pulse.identifier();
JaxbBundle bundle = new JaxbBundle("pulse")
.add("identifier", uid)
.up();
final ArraySet<String> now = new ArraySet<String>(this.open);
if (this.open.contains(uid)) {
bundle = this
.render(bundle, pulse)
.link(new Link("close", this.self(now.without(uid))))
.link(
new Link(
"fetch",
this.uriInfo().getBaseUriBuilder()
.clone()
.path(StandRs.class)
.path(StandRs.class, "fetch")
.queryParam(StandRs.QUERY_ID, "{id}")
.build(this.name, uid)
)
);
} else {
bundle = bundle
.link(new Link("open", this.self(now.with(uid))))
.add("tags")
.add(
new JaxbBundle.Group<Tag>(pulse.tags()) {
@Override
public JaxbBundle bundle(final Tag tag) {
return new JaxbBundle("tag")
.add("label", tag.label()).up()
.add("level", tag.level().toString()).up();
}
}
)
.up();
}
return bundle;
}
/**
* Build URI to itself with new list of open pulses.
* @param names Names of pulses
* @return URI
*/
private URI self(final Collection<String> names) {
final UriBuilder builder = this.uriInfo().getBaseUriBuilder()
.clone()
.path(StandRs.class);
final Object[] args = new Object[names.size() + 1];
final Object[] labels = new String[names.size()];
args[0] = this.name;
int idx = 0;
for (String txt : names) {
labels[idx] = String.format("{arg%d}", idx);
args[idx + 1] = txt;
++idx;
}
return builder
.queryParam(StandRs.QUERY_OPEN, labels)
.build(args);
}
/**
* Render snapshot into bundle.
* @param bundle Bundle to render into
* @param pulse The pulse
* @return Bundle
*/
private JaxbBundle render(final JaxbBundle bundle, final Pulse pulse) {
JaxbBundle output = bundle;
try {
final Snapshot snapshot = this.snapshot(pulse.xembly());
try {
output = output.add(
new XSLT(
snapshot,
this.getClass().getResourceAsStream("post.xsl")
).dom().getDocumentElement()
);
} catch (ImpossibleModificationException ex) {
output = this.bug(output, ex);
} catch (TransformerException ex) {
output = this.bug(output, ex);
}
} catch (IOException ex) {
output = this.bug(output, ex);
} catch (XemblySyntaxException ex) {
output = this.bug(output, ex);
}
return output;
}
/**
* Get snapshot from xembly.
* @param xembly Xembly script
* @return Its snapshot
* @throws XemblySyntaxException If fails
* @checkstyle RedundantThrows (5 lines)
*/
private Snapshot snapshot(final String xembly)
throws XemblySyntaxException {
return new Snapshot(
new Directives(xembly)
.xpath("/snapshot/spec")
.remove()
);
}
/**
* Add bug to bundle.
* @param bundle Bundle to render into
* @param exc Exception
* @return Bundle
*/
private JaxbBundle bug(final JaxbBundle bundle, final Exception exc) {
return bundle.add("error", Exceptions.message(exc)).up();
}
/**
* Get ACL of the stand.
* @param stand The stand
* @return ACL
*/
private ACL acl(final Stand stand) {
ACL acl;
try {
acl = ACL.class.cast(
new Repo.Cached(this.repo(), this.user(), stand.acl())
.get()
.instantiate(
this.users(),
new Arguments(new Work.None(), new Wallet.Empty())
)
);
} catch (SpecException ex) {
Exceptions.warn(this, ex);
acl = new ACL() {
@Override
public boolean canView(final URN urn) {
return false;
}
@Override
public boolean canPost(final String key) {
return false;
}
};
}
return acl;
}
}
|
volkhin/nixie-timer | main/output.c | #include <stdint.h>
#include <stdio.h>
#include "stdatomic.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "output.h"
#define TAG "OUTPUT"
// blue
#define GPIO_CLOCK 12
// orange
#define GPIO_SERIAL 13
// brown
#define GPIO_LATCH 14
#define GPIO_BIT_SEL (BIT(GPIO_CLOCK) | BIT(GPIO_SERIAL) | BIT(GPIO_LATCH))
atomic_int state;
void set_output_value(int new_state) {
if (new_state < 0 || new_state >= 100) {
ESP_LOGE(TAG, "Invalid state: %d, ignorring", new_state);
return;
}
atomic_store_explicit(&state, new_state, memory_order_relaxed);
}
void output_task(void *pvParameter) {
ESP_LOGI(TAG, "output_task started");
gpio_config_t io_conf = {
.pin_bit_mask = GPIO_BIT_SEL, // bit mask of the pins that you want to set,e.g.GPIO18/19
.mode = GPIO_MODE_OUTPUT, // set as output mode
.pull_up_en = 0, // disable pull-down mode
.pull_down_en = 1, // enable pull-up mode
.intr_type = GPIO_INTR_DISABLE, // disable interrupt
};
gpio_config(&io_conf);
ESP_LOGI(TAG, "GPIO is configured");
for (;;) {
int value = atomic_load_explicit(&state, memory_order_relaxed);
int digit1 = value % 10;
int digit2 = (value / 10) % 10;
ESP_LOGI(TAG, "output: %d %d %d", value, digit1, digit2);
gpio_set_level(GPIO_LATCH, 0);
gpio_set_level(GPIO_CLOCK, 0);
for (int i = 0; i < 4; ++i) {
gpio_set_level(GPIO_SERIAL, digit1 & 1);
gpio_set_level(GPIO_CLOCK, 1);
digit1 >>= 1;
gpio_set_level(GPIO_CLOCK, 0);
}
for (int i = 0; i < 4; ++i) {
gpio_set_level(GPIO_SERIAL, digit2 & 1);
gpio_set_level(GPIO_CLOCK, 1);
digit2 >>= 1;
gpio_set_level(GPIO_CLOCK, 0);
}
gpio_set_level(GPIO_LATCH, 1);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
|
TimelyD/Timely-master | src/com/tg/tgt/ui/MomentsLogAct.java | <reponame>TimelyD/Timely-master
package com.tg.tgt.ui;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.hyphenate.easeui.GlideApp;
import com.tg.tgt.Constant;
import com.tg.tgt.R;
import com.tg.tgt.http.ApiManger2;
import com.tg.tgt.http.BaseObserver2;
import com.tg.tgt.http.HttpResult;
import com.tg.tgt.http.model2.MomentsLogModel;
import com.tg.tgt.moment.ui.activity.MomentAct;
import com.tg.tgt.utils.CodeUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
public class MomentsLogAct extends BaseActivity {
private RecyclerView mRecyclerView;
private MultipleStatusView mStatusView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private List<MomentsLogModel> mDatas = new ArrayList<>();
private static int pageSize = 10;
private BaseQuickAdapter<MomentsLogModel, BaseViewHolder> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_moments_log);
initView();
initEvent();
mSwipeRefreshLayout.measure(0,0);
mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
loadData(false);
}
private void initEvent() {
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadData(false);
}
});
mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
loadData(true);
}
}, mRecyclerView);
mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
/*Intent intent = new Intent(mContext,.class);
intent.putExtra("userId",mDatas.get(position).getId());intent.putExtra("username",mDatas.get(position).getNickname());
startActivity(intent);*/
if(mDatas.get(position).getRelationStatus().equals("1")){
try {
mActivity.startActivity(new Intent(mActivity, MomentAct.class)
.putExtra(Constant.USERNAME,mDatas.get(position).getFromName())
.putExtra(Constant.USER_ID,mDatas.get(position).getFromId())
.putExtra(Constant.IS_MINE_HOME_PAGE, true));
}catch (Exception e){
Log.i("异常",e.getMessage());
}
}else {
//CodeUtils.addContact(mActivity,mDatas.get(position).getFromId(),mDatas.get(position).getFromName());
}
/* mContext.startActivity(new Intent(mContext, MomentAct.class).putExtra(Constant.USERNAME,mDatas.get(position).getNickname()).putExtra
(Constant.USER_ID,mDatas.get(position).getFromId()).putExtra(Constant.IS_MINE_HOME_PAGE, true));*/
}
});
}
private void loadData(final boolean loadMore) {
ApiManger2.getApiService()
.showMomentsLog(!loadMore||mDatas.size()==0?null:mDatas.get(mDatas.size()-1).getId(), pageSize)
.compose(this.<HttpResult<List<MomentsLogModel>>>bindToLifeCyclerAndApplySchedulers(null))
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(@NonNull Disposable disposable) throws Exception {
if(!loadMore) {
mSwipeRefreshLayout.setRefreshing(true);
}
}
})
.subscribe(new BaseObserver2<List<MomentsLogModel>>() {
@Override
protected void onSuccess(List<MomentsLogModel> momentsLogModels) {
if(loadMore){
if(momentsLogModels == null){
mAdapter.loadMoreEnd();
return;
}else if(momentsLogModels.size()<10){
mAdapter.loadMoreEnd();
}else {
mAdapter.loadMoreComplete();
}
mDatas.addAll(momentsLogModels);
mAdapter.notifyDataSetChanged();
}else {
mSwipeRefreshLayout.setRefreshing(false);
mDatas.clear();
if(momentsLogModels != null) {
mDatas.addAll(momentsLogModels);
if(momentsLogModels.size()>=pageSize){
mAdapter.loadMoreComplete();
}else {
mAdapter.loadMoreEnd();
}
}else {
mStatusView.showEmpty();
}
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onFaild(int code, String message) {
super.onFaild(code, message);
if(loadMore) {
mAdapter.loadMoreFail();
}else {
mSwipeRefreshLayout.setRefreshing(false);
}
}
});
}
private int color1;
private int color;
private void initView() {
color1 = getResources().getColor(R.color.tx_black_3);
color = getResources().getColor(R.color.tx_black_1);
setTitleBarLeftBack();
mStatusView = (MultipleStatusView) findViewById(R.id.status_layout);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
// mRecyclerView.addItemDecoration(new SimpleDividerDecoration(mContext));
mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
mAdapter = new BaseQuickAdapter<MomentsLogModel, BaseViewHolder>(R.layout
.item_moments_log, mDatas) {
@Override
protected void convert(BaseViewHolder helper, final MomentsLogModel item) {
helper.setText(R.id.tv_time, item.getCreateTime());
helper.setText(R.id.tv_name, item.safeGetRemark());
ImageView view = (ImageView) helper.getView(R.id.iv_avatar);
GlideApp.with(mActivity).load(item.getPicture()).placeholder(R.drawable.default_avatar).into(view);
String relationStatus = item.getRelationStatus();
Button btn = (Button) helper.getView(R.id.add_btn);
if("0".equals(relationStatus)){
btn.setBackgroundResource(R.drawable.btn_agree_selector);
btn.setTextColor(color);
btn.setText(R.string.button_add);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CodeUtils.addContact(mActivity,item.getFromId(),item.getFromName());
}
});
}else if("1".equals(relationStatus)){
btn.setBackgroundDrawable(null);
btn.setTextColor(color1);
btn.setText(R.string.has_added);
}else {
btn.setBackgroundDrawable(null);
btn.setTextColor(color1);
btn.setText("unknown");
}
if(helper.getAdapterPosition()==mDatas.size()-1){
helper.setVisible(R.id.divider_long, true);
helper.setVisible(R.id.divider_short, false);
}else {
helper.setVisible(R.id.divider_long, false);
helper.setVisible(R.id.divider_short, true);
}
}
};
mAdapter.bindToRecyclerView(mRecyclerView);
mRecyclerView.setAdapter(mAdapter);
}
}
|
feiaxyt/CGACD | models/attention/attention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from config.config import cfg
class Attention(nn.Module):
def __init__(self):
super(Attention, self).__init__()
def forward(self, z_f, x_f):
raise NotImplementedError
class PixelAttention(Attention):
def __init__(self, feat_in=256):
super(PixelAttention, self).__init__()
self.feat_in = feat_in
self.spatial_pool_agl = nn.Sequential(
nn.Conv2d(25, 32, 3),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.Conv2d(32, 32, 3),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(32, 32, 3),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(32, 1, 3),
nn.Sigmoid(),
)
self.spatial_pool_agr = nn.Sequential(
nn.Conv2d(25, 32, 3),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.Conv2d(32, 32, 3),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(32, 32, 3),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(32, 1, 3),
nn.Sigmoid(),
)
self.channel_pool_ag = nn.Sequential(
nn.Linear(feat_in, feat_in//4),
nn.ReLU(inplace=True),
nn.Linear(feat_in//4, feat_in),
)
self.channel_maxpool = nn.MaxPool2d(cfg.train.search_pool_size - cfg.train.template_pool_size + 1)
self.channel_avgpool = nn.AvgPool2d(cfg.train.search_pool_size - cfg.train.template_pool_size + 1)
self.channel_activation = nn.Sigmoid()
for m in self.modules():
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.Linear)):
nn.init.kaiming_normal_(
m.weight.data, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1.0)
m.bias.data.zero_()
def forward(self, z_f, x_f):
b, c, h, w = z_f.shape
kernel = z_f.reshape(b,c,h*w).permute(0,2,1).reshape(-1, c, 1, 1)
b, c, h, w = x_f.shape
xf_reshape = x_f.reshape(1, -1, h, w)
pixel_corr = F.conv2d(xf_reshape, kernel, groups=b).reshape(b, -1, h, w)# / c
b, c, h, w = pixel_corr.shape
spatial_att_l = self.spatial_pool_agl(pixel_corr)
spatial_att_r = self.spatial_pool_agr(pixel_corr)
b, c, h, w = z_f.shape
kernel = z_f.reshape(b*c, 1, h, w)
b, c, h, w = x_f.shape
xf_reshape = x_f.reshape(1, b*c, h, w)
depth_corr = F.conv2d(xf_reshape, kernel, groups=b*c)
depth_corr = depth_corr.reshape(b, c, depth_corr.shape[-2], depth_corr.shape[-1])
channel_max_pool = self.channel_maxpool(depth_corr).squeeze()
channel_avg_pool = self.channel_avgpool(depth_corr).squeeze()
channel_att = self.channel_activation(self.channel_pool_ag(channel_max_pool) + self.channel_pool_ag(channel_avg_pool)).unsqueeze(-1).unsqueeze(-1)
x_f = x_f * channel_att
x_f_l = x_f * spatial_att_l
x_f_r = x_f * spatial_att_r
return x_f_l, x_f_r |
arpangreat/go | pkg/mod/github.com/golangci/golangci-lint@v1.38.1-0.20210309184618-2ebc9d7202f9/test/testdata/gofumpt.go | <gh_stars>1-10
// args: -Egofumpt
package testdata
import "fmt"
func GofumptNewLine() {
fmt.Println( "foo" ) // ERROR "File is not `gofumpt`-ed"
}
|
sDoka/tiis-library | liferay-plugins-sdk-6.2/portlets/tiis-library-portlet/docroot/WEB-INF/src/ru/tiis/srv/service/impl/BookLocalServiceImpl.java | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package ru.tiis.srv.service.impl;
import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang.StringUtils;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.Indexable;
import com.liferay.portal.kernel.search.IndexableType;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.kernel.util.ContentTypes;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portlet.asset.model.AssetEntry;
import com.liferay.portlet.asset.model.AssetLinkConstants;
import ru.tiis.srv.model.Book;
import ru.tiis.srv.service.base.BookLocalServiceBaseImpl;
/**
* The implementation of the book local service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link ru.tiis.srv.service.BookLocalService} interface.
*
* <p>
* This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
* </p>
*
* @author Michael
* @see ru.tiis.srv.service.base.BookLocalServiceBaseImpl
* @see ru.tiis.srv.service.BookLocalServiceUtil
*/
public class BookLocalServiceImpl extends BookLocalServiceBaseImpl {
/*
* NOTE FOR DEVELOPERS:
* Never reference this interface directly. Always use {@link ru.tiis.srv.service.BookLocalServiceUtil} to access the book local service.
*/
Log logger = LogFactoryUtil.getLog(this.getClass());
/**
* Adds the book to the database. Also notifies the appropriate model listeners.
*
* @param book the book
* @return the book that was added
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.REINDEX)
@Override
public Book addBook(Book book, ServiceContext serviceContext) throws SystemException {
if (null == book || null == serviceContext) {
throw new NullArgumentException("Arguments cannot be null.");
}
book.setCompanyId(serviceContext.getCompanyId());
book.setGroupId(serviceContext.getScopeGroupId());
book.setUserId(serviceContext.getUserId());
book.setUserName(String.valueOf(serviceContext.getUserId())); // actual userName not necessary
Book newBook = super.addBook(book);
try {
resourceLocalService.addResources(book.getCompanyId(), book.getGroupId(), book.getUserId(),
Book.class.getName(), book.getBookId(), false, true, true);
} catch (PortalException e) {
logger.error("Failed to add permissions resource for the book entry: " + book);
}
try {
AssetEntry assetEntry = assetEntryLocalService.updateEntry(
book.getUserId(), book.getGroupId(), book.getCreateDate(),
book.getModifiedDate(), Book.class.getName(),
book.getBookId(), book.getUuid(), 0,
serviceContext.getAssetCategoryIds(),
serviceContext.getAssetTagNames(), true,
null, null, null, ContentTypes.TEXT_HTML,
book.getTitle(), book.getDescription(), StringUtils.EMPTY,
null, null, 0, 0, null, false);
assetLinkLocalService.updateLinks(book.getUserId(),
assetEntry.getEntryId(), serviceContext.getAssetLinkEntryIds(),
AssetLinkConstants.TYPE_RELATED);
} catch (PortalException e) {
logger.error("Failed to add asset entry of the book entry: " + book);
}
try {
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
Book.class);
indexer.reindex(newBook);
} catch (PortalException e) {
logger.error("Failed to reindex Lucene document for the book entry: " + book);
}
return newBook;
}
/**
* Updates the book in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners.
*
* @param book the book
* @return the book that was updated
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.REINDEX)
@Override
public Book updateBook(Book book, ServiceContext serviceContext) throws SystemException {
if (null == book || null == serviceContext) {
throw new NullArgumentException("Arguments cannot be null.");
}
// temp (can be deleted after dev) fix to enable pre-asset-integration books as assets
// if companyId is not set, then book has not been made an asset
if (0 == book.getCompanyId()) {
book.setCompanyId(serviceContext.getCompanyId());
book.setGroupId(serviceContext.getScopeGroupId());
book.setUserId(serviceContext.getUserId());
book.setUserName(String.valueOf(serviceContext.getUserId()));
}
Book updatedBook = super.updateBook(book);
// unsure use case for updating permission resources, since currently there
// are no plans to change permissions via UI
try {
AssetEntry assetEntry = assetEntryLocalService.updateEntry(
book.getUserId(), book.getGroupId(), book.getCreateDate(),
book.getModifiedDate(), Book.class.getName(),
book.getBookId(), book.getUuid(), 0,
serviceContext.getAssetCategoryIds(),
serviceContext.getAssetTagNames(), true,
null, null, null, ContentTypes.TEXT_HTML,
book.getTitle(), book.getDescription(), StringUtils.EMPTY,
null, null, 0, 0, null, false);
assetLinkLocalService.updateLinks(book.getUserId(),
assetEntry.getEntryId(), serviceContext.getAssetLinkEntryIds(),
AssetLinkConstants.TYPE_RELATED);
} catch (PortalException e) {
logger.error("Failed to update asset entry of the book entry: " + book);
}
try {
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
Book.class);
indexer.reindex(updatedBook);
} catch (PortalException e) {
logger.error("Failed to reindex Lucene document for the book entry: " + book);
}
return updatedBook;
}
/**
* Deletes the book from the database. Also notifies the appropriate model listeners.
*
* @param book the book
* @return the book that was removed
* @throws SystemException if a system exception occurred
*/
@Indexable(type = IndexableType.DELETE)
@Override
public Book deleteBook(Book book) throws SystemException {
try {
resourceLocalService.deleteResource(book.getCompanyId(), Book.class.getName(),
ResourceConstants.SCOPE_INDIVIDUAL, book.getBookId());
} catch (PortalException e) {
logger.error("Failed to delete permissions resource for the book entry: " + book);
}
try {
AssetEntry assetEntry = assetEntryLocalService.fetchEntry(
Book.class.getName(), book.getBookId());
assetLinkLocalService.deleteLinks(assetEntry.getEntryId());
assetEntryLocalService.deleteEntry(assetEntry);
} catch (PortalException e) {
logger.error("Failed to delete asset entry of the book entry: " + book);
}
try {
Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
Book.class);
indexer.delete(book);
} catch (PortalException e) {
logger.error("Failed to delete Lucene document of the book entry: " + book);
}
Book deletedBook = super.deleteBook(book);
return deletedBook;
}
} |
lanpinguo/rootfs_build | kernel/drivers/media/platform/sunxi-tvd/tvd.c | /*
* Copyright (C) 2015 Allwinnertech, z.q <<EMAIL>>
*
* 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.
*
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <linux/mutex.h>
#include <linux/videodev2.h>
#include <linux/delay.h>
#include <linux/string.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 20)
#include <linux/freezer.h>
#endif
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/moduleparam.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-common.h>
#include <media/v4l2-mediabus.h>
#include <media/v4l2-subdev.h>
#include <media/videobuf2-dma-contig.h>
#include <media/videobuf2-core.h>
#include <linux/sys_config.h>
#include <linux/gpio.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pinctrl/pinconf-sunxi.h>
#include <linux/of_gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/switch.h>
#ifdef CONFIG_DEVFREQ_DRAM_FREQ_WITH_SOFT_NOTIFY
#include <linux/sunxi_dramfreq.h>
#endif
#include "tvd.h"
#define TVD_MODULE_NAME "sunxi_tvd"
#define MIN_WIDTH (32)
#define MIN_HEIGHT (32)
#define MAX_WIDTH (4096)
#define MAX_HEIGHT (4096)
#define MAX_BUFFER (32*1024*1024)
#define NUM_INPUTS 1
#define CVBS_INTERFACE 0
#define YPBPRI_INTERFACE 1
#define YPBPRP_INTERFACE 2
#define NTSC 0
#define PAL 1
#define NONE 2
#define TVD_MAX_POWER_NUM 2
#define TVD_MAX_GPIO_NUM 2
#define TVD_MAX 4
#define TVD_MAJOR_VERSION 1
#define TVD_MINOR_VERSION 0
#define TVD_RELEASE 0
#define TVD_VERSION \
KERNEL_VERSION(TVD_MAJOR_VERSION, TVD_MINOR_VERSION, TVD_RELEASE)
static unsigned int tvd_dbg_en;
static unsigned int tvd_dbg_sel;
#define TVD_DBG_DUMP_LEN 0x200000
#define TVD_NAME_LEN 32
static char tvd_dump_file_name[TVD_NAME_LEN];
static struct tvd_status tvd_status[4];
static struct tvd_dev *tvd[4];
static unsigned int tvd_hot_plug;
/* use for reversr special interfaces */
static int tvd_count;
static int fliter_count;
static struct mutex fliter_lock;
static struct mutex power_lock;
static char tvd_power[TVD_MAX_POWER_NUM][32];
static struct gpio_config tvd_gpio_config[TVD_MAX_GPIO_NUM];
static struct regulator *regu[TVD_MAX_POWER_NUM];
static atomic_t tvd_used_power_num = ATOMIC_INIT(0);
static atomic_t tvd_used_gpio_num = ATOMIC_INIT(0);
static atomic_t gpio_power_enable_count = ATOMIC_INIT(0);
static irqreturn_t tvd_isr(int irq, void *priv);
static irqreturn_t tvd_isr_special(int irq, void *priv);
static int __tvd_fetch_sysconfig(int sel, char *sub_name, int value[]);
static int __tvd_auto_plug_enable(struct tvd_dev *dev);
static int __tvd_auto_plug_disable(struct tvd_dev *dev);
static ssize_t tvd_dbg_en_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", tvd_dbg_en);
}
static ssize_t tvd_dbg_en_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int err;
unsigned long val;
err = strict_strtoul(buf, 10, &val);
if (err) {
pr_debug("Invalid size\n");
return err;
}
if(val < 0 || val > 1) {
pr_debug("Invalid value, 0~1 is expected!\n");
} else {
tvd_dbg_en = val;
pr_debug("tvd_dbg_en = %ld\n", val);
}
return count;
}
static ssize_t tvd_dbg_lv_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", tvd_dbg_sel);
}
static ssize_t tvd_dbg_lv_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int err;
unsigned long val;
err = strict_strtoul(buf, 10, &val);
if (err) {
pr_debug("Invalid size\n");
return err;
}
if(val < 0 || val > 4) {
pr_debug("Invalid value, 0~3 is expected!\n");
} else {
tvd_dbg_sel = val;
pr_debug("tvd_dbg_sel = %d\n", tvd_dbg_sel);
tvd_isr(46, tvd[tvd_dbg_sel]);
}
return count;
}
static ssize_t tvd_dbg_dump_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct tvd_dev *tvd_dev = (struct tvd_dev *)dev_get_drvdata(dev);
struct file *pfile;
mm_segment_t old_fs;
ssize_t bw;
dma_addr_t buf_dma_addr;
void *buf_addr;
buf_addr = dma_alloc_coherent(dev, TVD_DBG_DUMP_LEN,
(dma_addr_t *)&buf_dma_addr, GFP_KERNEL);
if (!buf_addr) {
pr_warn("%s(), dma_alloc_coherent fail, size=0x%x\n",
__func__, TVD_DBG_DUMP_LEN);
return 0;
}
/* start debug mode */
if (tvd_dbgmode_dump_data(tvd_dev->sel,
0, buf_dma_addr, TVD_DBG_DUMP_LEN / 2)) {
pr_warn("%s(), debug mode start fail\n", __func__);
goto exit;
}
pfile = filp_open(tvd_dump_file_name,
O_RDWR|O_CREAT|O_EXCL, 0755);
if (IS_ERR(pfile)) {
pr_warn("%s, open %s err\n",
__func__, tvd_dump_file_name);
goto exit;
}
pr_warn("%s, open %s ok\n",
__func__, tvd_dump_file_name);
old_fs = get_fs();
set_fs(KERNEL_DS);
bw = pfile->f_op->write(pfile,
(const char *)buf_addr, TVD_DBG_DUMP_LEN, &pfile->f_pos);
if (unlikely(bw != TVD_DBG_DUMP_LEN))
pr_warn("%s, write %s err at byte offset %llu\n",
__func__, tvd_dump_file_name, pfile->f_pos);
set_fs(old_fs);
filp_close(pfile, NULL);
pfile = NULL;
exit:
dma_free_coherent(dev, TVD_DBG_DUMP_LEN, buf_addr, buf_dma_addr);
return 0;
}
static ssize_t tvd_dbg_dump_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
memset(tvd_dump_file_name, '\0', TVD_NAME_LEN);
count = (count > TVD_NAME_LEN) ? TVD_NAME_LEN : count;
memcpy(tvd_dump_file_name, buf, count - 1);
pr_info("%s(), get dump file name %s\n",
__func__, tvd_dump_file_name);
return count;
}
static DEVICE_ATTR(tvd_dbg_en, S_IRUGO|S_IWUSR|S_IWGRP,
tvd_dbg_en_show, tvd_dbg_en_store);
static DEVICE_ATTR(tvd_dbg_lv, S_IRUGO|S_IWUSR|S_IWGRP,
tvd_dbg_lv_show, tvd_dbg_lv_store);
static DEVICE_ATTR(tvd_dump, S_IRUGO|S_IWUSR|S_IWGRP,
tvd_dbg_dump_show, tvd_dbg_dump_store);
static struct attribute *tvd0_attributes[] = {
&dev_attr_tvd_dbg_en.attr,
&dev_attr_tvd_dbg_lv.attr,
&dev_attr_tvd_dump.attr,
NULL
};
static struct attribute *tvd1_attributes[] = {
&dev_attr_tvd_dbg_en.attr,
&dev_attr_tvd_dbg_lv.attr,
&dev_attr_tvd_dump.attr,
NULL
};
static struct attribute *tvd2_attributes[] = {
&dev_attr_tvd_dbg_en.attr,
&dev_attr_tvd_dbg_lv.attr,
&dev_attr_tvd_dump.attr,
NULL
};
static struct attribute *tvd3_attributes[] = {
&dev_attr_tvd_dbg_en.attr,
&dev_attr_tvd_dbg_lv.attr,
&dev_attr_tvd_dump.attr,
NULL
};
static struct attribute_group tvd_attribute_group[] = {
{ .name = "tvd0_attr",
.attrs = tvd0_attributes
},
{ .name = "tvd1_attr",
.attrs = tvd1_attributes
},
{ .name = "tvd2_attr",
.attrs = tvd2_attributes
},
{ .name = "tvd3_attr",
.attrs = tvd3_attributes
},
};
static struct tvd_fmt formats[] = {
{
.name = "planar UVUV",
.fourcc = V4L2_PIX_FMT_NV12,
.output_fmt = TVD_PL_YUV420,
.depth = 12,
},
{
.name = "planar VUVU",
.fourcc = V4L2_PIX_FMT_NV21,
.output_fmt = TVD_PL_YUV420,
.depth = 12,
},
{
.name = "planar UVUV",
.fourcc = V4L2_PIX_FMT_NV16,
.output_fmt = TVD_PL_YUV422,
.depth = 16,
},
{
.name = "planar VUVU",
.fourcc = V4L2_PIX_FMT_NV61,
.output_fmt = TVD_PL_YUV422,
.depth = 16,
},
/* this format is not standard, just for allwinner. */
{
.name = "planar PACK",
.fourcc = 0,
.output_fmt = TVD_MB_YUV420,
.depth = 12,
},
};
static int inline tvd_is_generating(struct tvd_dev *dev)
{
int ret;
ret = test_bit(0, &dev->generating);
return ret;
}
static void inline tvd_start_generating(struct tvd_dev *dev)
{
set_bit(0, &dev->generating);
return;
}
static void inline tvd_stop_generating(struct tvd_dev *dev)
{
clear_bit(0, &dev->generating);
return;
}
static int tvd_is_opened(struct tvd_dev *dev)
{
int ret;
mutex_lock(&dev->opened_lock);
ret = test_bit(0, &dev->opened);
mutex_unlock(&dev->opened_lock);
return ret;
}
static void tvd_start_opened(struct tvd_dev *dev)
{
mutex_lock(&dev->opened_lock);
set_bit(0, &dev->opened);
mutex_unlock(&dev->opened_lock);
}
static void tvd_stop_opened(struct tvd_dev *dev)
{
mutex_lock(&dev->opened_lock);
clear_bit(0, &dev->opened);
mutex_unlock(&dev->opened_lock);
}
static int __tvd_clk_init(struct tvd_dev *dev)
{
int div = 0, ret = 0;
unsigned long p = 297000000;
pr_debug("%s: dev->interface = %d, dev->system = %d\n",
__func__, dev->interface, dev->system);
dev->parent = clk_get_parent(dev->clk);
if (IS_ERR_OR_NULL(dev->parent) || IS_ERR_OR_NULL(dev->clk))
return -EINVAL;
/* parent is 297M */
ret = clk_set_rate(dev->parent, p);
if (ret) {
ret = -EINVAL;
goto out;
}
if (dev->interface == CVBS_INTERFACE) {
/* cvbs interface */
if (PAL == dev->system)
div = 10;
else
div = 11;
} else if (dev->interface == YPBPRI_INTERFACE) {
/* ypbprI interface */
div = 11;
} else if (dev->interface == YPBPRP_INTERFACE) {
/* ypbprP interface */
ret = clk_set_rate(dev->parent, 594000000);
p = 594000000;
div = 11;
} else {
pr_err("%s: interface is err!\n", __func__);
return -EINVAL;
}
pr_debug("div = %d\n", div);
p /= div;
ret = clk_set_rate(dev->clk, p);
if (ret) {
ret = -EINVAL;
goto out;
}
pr_debug("%s: parent = %lu, clk = %lu\n",
__func__, clk_get_rate(dev->parent), clk_get_rate(dev->clk));
out:
return ret;
}
static int __tvd_clk_enable(struct tvd_dev *dev)
{
int ret = 0;
ret = clk_prepare_enable(dev->clk_top);
if (ret) {
pr_err("%s: tvd top clk enable err!", __func__);
clk_disable(dev->clk_top);
return ret;
}
ret = clk_prepare_enable(dev->clk);
if (ret) {
pr_err("%s: tvd clk enable err!", __func__);
clk_disable(dev->clk);
}
return ret;
}
static int __tvd_clk_disable(struct tvd_dev *dev)
{
int ret = 0;
clk_disable(dev->clk);
clk_disable(dev->clk_top);
return ret;
}
static int __tvd_init(struct tvd_dev *dev)
{
tvd_top_set_reg_base((unsigned long)dev->regs_top);
tvd_set_reg_base(dev->sel, (unsigned long)dev->regs_tvd);
return 0;
}
static int __tvd_config(struct tvd_dev *dev)
{
tvd_init(dev->sel, dev->interface);
tvd_config(dev->sel, dev->interface, dev->system);
tvd_set_wb_width(dev->sel, dev->width);
tvd_set_wb_width_jump(dev->sel, dev->width);
if (dev->interface == YPBPRP_INTERFACE)
tvd_set_wb_height(dev->sel, dev->height); /*P,no div*/
else
tvd_set_wb_height(dev->sel, dev->height/2);
/* pl_yuv420, mb_yuv420, pl_yuv422 */
tvd_set_wb_fmt(dev->sel, dev->fmt->output_fmt);
switch (dev->fmt->fourcc) {
case V4L2_PIX_FMT_NV12:
case V4L2_PIX_FMT_NV16:
tvd_set_wb_uv_swap(dev->sel, 0);
break;
case V4L2_PIX_FMT_NV21:
case V4L2_PIX_FMT_NV61:
tvd_set_wb_uv_swap(dev->sel, 1);
break;
}
return 0;
}
static int __tvd_3d_comp_mem_request(struct tvd_dev *dev, int size)
{
unsigned long phyaddr;
dev->fliter.size = PAGE_ALIGN(size);
dev->fliter.vir_address = dma_alloc_coherent(dev->v4l2_dev.dev, size,
(dma_addr_t *)&phyaddr, GFP_KERNEL);
dev->fliter.phy_address = (void *)phyaddr;
if (IS_ERR_OR_NULL(dev->fliter.vir_address)) {
pr_err("%s: 3d fliter buf_alloc failed!\n", __func__);
return -EINVAL;
}
return 0;
}
static void __tvd_3d_comp_mem_free(struct tvd_dev *dev)
{
u32 actual_bytes;
actual_bytes = PAGE_ALIGN(dev->fliter.size);
if (dev->fliter.phy_address && dev->fliter.vir_address)
dma_free_coherent(dev->v4l2_dev.dev, actual_bytes,
dev->fliter.vir_address,
(dma_addr_t)dev->fliter.phy_address);
}
/*
* set width,set height, set jump, set wb addr, set 3d_comb
*/
static void __tvd_set_addr(struct tvd_dev *dev, struct tvd_buffer *buffer)
{
struct tvd_buffer *buf = buffer;
dma_addr_t addr_org;
struct vb2_buffer *vb_buf = &buf->vb;
unsigned int c_offset = 0;
if(vb_buf == NULL || vb_buf->planes[0].mem_priv == NULL) {
pr_err("%s: vb_buf->priv is NULL!\n", __func__);
return;
}
addr_org = vb2_dma_contig_plane_dma_addr(vb_buf, 0);
switch (dev->fmt->output_fmt) {
case TVD_PL_YUV422:
case TVD_PL_YUV420:
c_offset = dev->width * dev->height;
break;
case TVD_MB_YUV420:
c_offset = 0;
break;
default:
break;
}
/* set y_addr,c_addr */
pr_debug("%s: format:%d, addr_org = 0x%x, addr_org + c_offset = 0x%x\n",
__func__, dev->format, addr_org, addr_org + c_offset);
tvd_set_wb_addr(dev->sel, addr_org, addr_org + c_offset);
}
/*
* the interrupt routine
*/
static irqreturn_t tvd_isr(int irq, void *priv)
{
struct tvd_buffer *buf;
unsigned long flags;
struct list_head *entry_tmp;
u32 irq_status = 0;
struct tvd_dev *dev = (struct tvd_dev *)priv;
struct tvd_dmaqueue *dma_q = &dev->vidq;
u32 value = (1 << TVD_IRQ_FIFO_C_O)|(1 << TVD_IRQ_FIFO_Y_O) \
|(1 << TVD_IRQ_FIFO_C_U)|(1 << TVD_IRQ_FIFO_Y_U) \
|(1 << TVD_IRQ_WB_ADDR_CHANGE_ERR);
if (dev->special_active == 1) {
return tvd_isr_special(irq, priv);
}
if(tvd_is_generating(dev) == 0) {
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
return IRQ_HANDLED;
}
tvd_dma_irq_status_get(dev->sel, &irq_status);
if ((irq_status & value) != 0)
tvd_dma_irq_status_clear_err_flag(dev->sel, value);
spin_lock_irqsave(&dev->slock, flags);
if (0 == dev->first_flag) {
/* if is first frame, flag set 1 */
dev->first_flag = 1;
goto set_next_addr;
}
if (list_empty(&dma_q->active) || dma_q->active.next->next == (&dma_q->active)) {
pr_debug("No active queue to serve\n");
goto unlock;
}
buf = list_entry(dma_q->active.next, struct tvd_buffer, list);
/* Nobody is waiting for this buffer*/
if (!waitqueue_active(&buf->vb.vb2_queue->done_wq)) {
pr_debug("%s: Nobody is waiting on this video buffer,buf = 0x%p\n",__func__, buf);
}
entry_tmp = &buf->list;
if ((entry_tmp == NULL) || (entry_tmp->prev == NULL) || (entry_tmp->next == NULL) \
|| (entry_tmp->prev == LIST_POISON2) || (entry_tmp->next == LIST_POISON1) \
|| (entry_tmp->prev->next == NULL) || (entry_tmp->next->prev == NULL)) {
if (entry_tmp == NULL)
pr_err("%s: buf NULL pointer error \n", __func__);
pr_err("%s: buf list error \n", __func__);
goto unlock;
}
list_del(&buf->list);
dev->ms += jiffies_to_msecs(jiffies - dev->jiffies);
dev->jiffies = jiffies;
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_DONE);
if (list_empty(&dma_q->active)) {
pr_debug("%s: No more free frame\n", __func__);
goto unlock;
}
/* hardware need one frame */
if ((&dma_q->active) == dma_q->active.next->next) {
pr_debug("No more free frame on next time\n");
goto unlock;
}
set_next_addr:
buf = list_entry(dma_q->active.next->next, struct tvd_buffer, list);
__tvd_set_addr(dev, buf);
unlock:
spin_unlock(&dev->slock);
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
return IRQ_HANDLED;
}
/*
* Videobuf operations
*/
static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
unsigned int *nbuffers, unsigned int *nplanes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct tvd_dev *dev = vb2_get_drv_priv(vq);
unsigned int size;
switch (dev->fmt->output_fmt) {
case TVD_MB_YUV420:
case TVD_PL_YUV420:
size = dev->width * dev->height * 3/2;
break;
case TVD_PL_YUV422:
default:
size = dev->width * dev->height * 2;
break;
}
if (size == 0)
return -EINVAL;
if (*nbuffers < 3) {
*nbuffers = 3;
pr_err("buffer conunt invalid, min is 3!\n");
} else if (*nbuffers > 10) {
*nbuffers = 10;
pr_err("buffer conunt invalid, max 10!\n");
}
dev->frame_size = size;
sizes[0] = size;
*nplanes = 1;
alloc_ctxs[0] = dev->alloc_ctx;
pr_debug("%s, buffer count=%d, size=%d\n", __func__, *nbuffers, size);
return 0;
}
static int buffer_prepare(struct vb2_buffer *vb)
{
struct tvd_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
struct tvd_buffer *buf = container_of(vb, struct tvd_buffer, vb);
unsigned long size;
pr_debug("%s: buffer_prepare\n", __func__);
if (dev->width < MIN_WIDTH || dev->width > MAX_WIDTH ||
dev->height < MIN_HEIGHT || dev->height > MAX_HEIGHT)
{
return -EINVAL;
}
size = dev->frame_size;
if (vb2_plane_size(vb, 0) < size) {
pr_err("%s data will not fit into plane (%lu < %lu)\n",
__func__, vb2_plane_size(vb, 0), size);
return -EINVAL;
}
vb2_set_plane_payload(&buf->vb, 0, size);
vb->v4l2_planes[0].m.mem_offset = vb2_dma_contig_plane_dma_addr(vb, 0);
return 0;
}
static void buffer_queue(struct vb2_buffer *vb)
{
struct tvd_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
struct tvd_buffer *buf = container_of(vb, struct tvd_buffer, vb);
struct tvd_dmaqueue *vidq = &dev->vidq;
unsigned long flags = 0;
pr_debug("%s: \n", __func__);
spin_lock_irqsave(&dev->slock, flags);
list_add_tail(&buf->list, &vidq->active);
spin_unlock_irqrestore(&dev->slock, flags);
}
static int start_streaming(struct vb2_queue *vq, unsigned int count)
{
struct tvd_dev *dev = vb2_get_drv_priv(vq);
pr_debug("%s:\n", __func__);
tvd_start_generating(dev);
return 0;
}
/* abort streaming and wait for last buffer */
static int stop_streaming(struct vb2_queue *vq)
{
struct tvd_dev *dev = vb2_get_drv_priv(vq);
struct tvd_dmaqueue *dma_q = &dev->vidq;
unsigned long flags = 0;
pr_debug("%s:\n", __func__);
tvd_stop_generating(dev);
spin_lock_irqsave(&dev->slock, flags);
/* Release all active buffers */
while (!list_empty(&dma_q->active)) {
struct tvd_buffer *buf;
buf = list_entry(dma_q->active.next, struct tvd_buffer, list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
pr_debug("[%p/%d] done\n", buf, buf->vb.v4l2_buf.index);
}
spin_unlock_irqrestore(&dev->slock, flags);
return 0;
}
static void tvd_lock(struct vb2_queue *vq)
{
struct tvd_dev *dev = vb2_get_drv_priv(vq);
mutex_lock(&dev->buf_lock);
}
static void tvd_unlock(struct vb2_queue *vq)
{
struct tvd_dev *dev = vb2_get_drv_priv(vq);
mutex_unlock(&dev->buf_lock);
}
static const struct vb2_ops tvd_video_qops = {
.queue_setup = queue_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.start_streaming = start_streaming,
.stop_streaming = stop_streaming,
.wait_prepare = tvd_unlock,
.wait_finish = tvd_lock,
};
/*
* IOCTL vidioc handling
*/
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct tvd_dev *dev = video_drvdata(file);
strcpy(cap->driver, "sunxi-tvd");
strcpy(cap->card, "sunxi-tvd");
strlcpy(cap->bus_info, dev->v4l2_dev.name, sizeof(cap->bus_info));
cap->version = TVD_VERSION;
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
| V4L2_CAP_STREAMING
| V4L2_CAP_READWRITE;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct tvd_fmt *fmt;
if (f->index > ARRAY_SIZE(formats)-1)
return -EINVAL;
fmt = &formats[f->index];
strlcpy(f->description, fmt->name, sizeof(f->description));
f->pixelformat = fmt->fourcc;
return 0;
}
static void __get_status(struct tvd_dev *dev, unsigned int *locked,
unsigned int *system)
{
int i = 0;
if (dev->interface > 0) {
/* ypbpr signal, search i/p */
dev->interface = 1;
for (i = 0; i < 2; i++) {
__tvd_clk_init(dev);
mdelay(200);
tvd_get_status(dev->sel, locked, system);
if (*locked)
break;
if (dev->interface < 2)
dev->interface++;
}
} else if (dev->interface == 0) {
/* cvbs signal */
mdelay(200);
tvd_get_status(dev->sel, locked, system);
}
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct tvd_dev *dev = video_drvdata(file);
u32 locked = 0, system = 2;
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
__get_status(dev, &locked, &system);
f->fmt.pix.priv = dev->interface;
if (!locked) {
pr_debug("%s: signal is not locked.\n", __func__);
return -EAGAIN;
} else {
/* system: 1->pal, 0->ntsc */
if (system == PAL) {
f->fmt.pix.width = 720;
f->fmt.pix.height = 576;
} else if (system == NTSC) {
f->fmt.pix.width = 720;
f->fmt.pix.height = 480;
} else {
pr_err("system is not sure.\n");
}
}
pr_debug("system = %d, w = %d, h = %d\n",
system, f->fmt.pix.width, f->fmt.pix.height);
return 0;
}
static struct tvd_fmt *__get_format(struct v4l2_format *f)
{
struct tvd_fmt *fmt;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(formats); i++) {
fmt = &formats[i];
/* user defined struct raw_data: 5->pixelformat */
if (fmt->fourcc == f->fmt.pix.pixelformat) {
pr_debug("fourcc = %d\n", fmt->fourcc);
break;
}
}
if (i == ARRAY_SIZE(formats))
return NULL;
return &formats[i];
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
return 0;
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct tvd_dev *dev = video_drvdata(file);
int ret = 0;
int used = 0;
int value = 0, mode = 0;
if (tvd_is_generating(dev)) {
pr_err("%s device busy\n", __func__);
return -EBUSY;
}
dev->fmt = __get_format(f);
if (!dev->fmt) {
pr_err("Fourcc format (0x%08x) invalid.\n",
f->fmt.pix.pixelformat);
return -EINVAL;
}
/* tvd ypbpr now only support 720*480 & 720*576 */
dev->width = f->fmt.pix.width;
dev->height = f->fmt.pix.height;
dev->fmt->field = V4L2_FIELD_NONE;
if (dev->height == 576) {
dev->system = PAL;
/* To solve the problem of PAL signal is not well.
* Accoding to the hardware designer, tvd need 29.7M
* clk input on PAL system, so here adjust clk again.
* Before this modify, PAL and NTSC have the same
* frequency which is 27M.
*/
__tvd_clk_init(dev);
} else {
dev->system = NTSC;
}
pr_debug("interface=%d\n",dev->interface);
pr_debug("system=%d\n",dev->system);
pr_debug("format=%d\n",dev->format);
pr_debug("width=%d\n",dev->width);
pr_debug("height=%d\n",dev->height);
__tvd_config(dev);
/* agc function */
ret = __tvd_fetch_sysconfig(dev->sel, (char *)"agc_auto_enable", &mode);
if (ret)
goto cagc;
if (mode == 0) {
/* manual mode */
ret = __tvd_fetch_sysconfig(dev->sel,
(char *)"agc_manual_value",
&value);
if (ret)
goto cagc;
tvd_agc_manual_config(dev->sel, (u32)value);
} else {
/* auto mode */
tvd_agc_auto_config(dev->sel);
}
cagc:
ret = __tvd_fetch_sysconfig(dev->sel, (char *)"cagc_enable", &value);
if (ret)
goto _3d_fliter;
tvd_cagc_config(dev->sel, (u32)value);
_3d_fliter:
/* 3d fliter */
__tvd_fetch_sysconfig(dev->sel, (char *)"fliter_used", &used);
dev->fliter.used = used;
if (dev->fliter.used) {
mutex_lock(&fliter_lock);
if (fliter_count < FLITER_NUM) {
if (__tvd_3d_comp_mem_request(dev,
(int)TVD_3D_COMP_BUFFER_SIZE)) {
/* no mem support for 3d fliter */
dev->fliter.used = 0;
mutex_unlock(&fliter_lock);
goto out;
}
fliter_count++;
}
tvd_3d_mode(dev->sel, 1, (u32)dev->fliter.phy_address);
mutex_unlock(&fliter_lock);
}
out:
return 0;
}
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct tvd_dev *dev = video_drvdata(file);
pr_debug("%s:\n", __func__);
return vb2_reqbufs(&dev->vb_vidq, p);
}
static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct tvd_dev *dev = video_drvdata(file);
return vb2_querybuf(&dev->vb_vidq, p);
}
static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct tvd_dev *dev = video_drvdata(file);
return vb2_qbuf(&dev->vb_vidq, p);
}
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
int ret = 0;
struct tvd_dev *dev = video_drvdata(file);
pr_debug("%s:\n", __func__);
ret = vb2_dqbuf(&dev->vb_vidq, p, file->f_flags & O_NONBLOCK);
return ret;
}
#ifdef CONFIG_VIDEO_V4L1_COMPAT
static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
{
struct tvd_dev *dev = video_drvdata(file);
return videobuf_cgmbuf(&dev->vb_vidq, mbuf, 8);
}
#endif
static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct tvd_dev *dev = video_drvdata(file);
struct tvd_dmaqueue *dma_q = &dev->vidq;
struct tvd_buffer *buf;
int ret = 0;
mutex_lock(&dev->stream_lock);
if (i != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
ret = -EINVAL;
goto streamon_unlock;
}
if (tvd_is_generating(dev)) {
pr_err("stream has been already on\n");
ret = -1;
goto streamon_unlock;
}
/* Resets frame counters */
dev->ms = 0;
dev->jiffies = jiffies;
dma_q->frame = 0;
dma_q->ini_jiffies = jiffies;
ret = vb2_streamon(&dev->vb_vidq, i);
if (ret)
goto streamon_unlock;
buf = list_entry(dma_q->active.next,struct tvd_buffer, list);
__tvd_set_addr(dev,buf);
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
tvd_irq_enable(dev->sel, TVD_IRQ_FRAME_END);
tvd_capture_on(dev->sel);
tvd_start_generating(dev);
streamon_unlock:
mutex_unlock(&dev->stream_lock);
return ret;
}
static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct tvd_dev *dev = video_drvdata(file);
struct tvd_dmaqueue *dma_q = &dev->vidq;
int ret = 0;
mutex_lock(&dev->stream_lock);
pr_debug("%s:\n", __func__);
if (!tvd_is_generating(dev)) {
pr_err("%s: stream has been already off\n", __func__);
ret = 0;
goto streamoff_unlock;
}
tvd_stop_generating(dev);
/* Resets frame counters */
dev->ms = 0;
dev->jiffies = jiffies;
dma_q->frame = 0;
dma_q->ini_jiffies = jiffies;
/* disable hardware */
tvd_irq_disable(dev->sel, TVD_IRQ_FRAME_END);
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
tvd_capture_off(dev->sel);
if (i != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
ret = -EINVAL;
goto streamoff_unlock;
}
ret = vb2_streamoff(&dev->vb_vidq, i);
if (ret!=0) {
pr_err("%s: videobu_streamoff error!\n", __func__);
goto streamoff_unlock;
}
streamoff_unlock:
mutex_unlock(&dev->stream_lock);
return ret;
}
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *inp)
{
if (inp->index > NUM_INPUTS-1) {
pr_err("%s: input index invalid!\n", __func__);
return -EINVAL;
}
inp->type = V4L2_INPUT_TYPE_CAMERA;
return 0;
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct tvd_dev *dev = video_drvdata(file);
pr_debug("%s:\n", __func__);
*i = dev->input;
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct tvd_dev *dev = video_drvdata(file);
pr_debug("%s: input_num = %d\n", __func__, i);
/* only one device */
if (i > 0) {
pr_err("%s: set input error!\n", __func__);
return -EINVAL;
}
dev->input = i;
return 0;
}
static int vidioc_g_parm(struct file *file, void *priv,
struct v4l2_streamparm *parms)
{
struct tvd_dev *dev = video_drvdata(file);
pr_debug("%s\n", __func__);
if(parms->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
parms->parm.capture.timeperframe.numerator=dev->fps.numerator;
parms->parm.capture.timeperframe.denominator=dev->fps.denominator;
}
return 0;
}
static int vidioc_s_parm(struct file *file, void *priv,
struct v4l2_streamparm *parms)
{
struct tvd_dev *dev = video_drvdata(file);
if (parms->parm.capture.capturemode != V4L2_MODE_VIDEO
&& parms->parm.capture.capturemode != V4L2_MODE_IMAGE
&& parms->parm.capture.capturemode != V4L2_MODE_PREVIEW)
parms->parm.capture.capturemode = V4L2_MODE_PREVIEW;
dev->capture_mode = parms->parm.capture.capturemode;
return 0;
}
static int vidioc_enum_framesizes(struct file *file, void *priv,
struct v4l2_frmsizeenum *fsize)
{
int i;
static const struct v4l2_frmsize_discrete sizes[] = {
{
.width = 720,
.height = 480,
},
{
.width = 720,
.height = 576,
},
};
/* there are two kinds of framesize*/
if (fsize->index > 1)
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(formats); i++)
if (formats[i].fourcc == fsize->pixel_format)
break;
if (i == ARRAY_SIZE(formats)) {
pr_err("format not found\n");
return -EINVAL;
}
fsize->discrete.width = sizes[fsize->index].width;
fsize->discrete.height = sizes[fsize->index].height;
return 0;
}
static ssize_t tvd_read(struct file *file, char __user *data, size_t count, loff_t *ppos)
{
struct tvd_dev *dev = video_drvdata(file);
if(tvd_is_generating(dev)) {
return vb2_read(&dev->vb_vidq, data, count, ppos,
file->f_flags & O_NONBLOCK);
} else {
pr_err("%s: tvd is not generating!\n", __func__);
return -EINVAL;
}
}
static unsigned int tvd_poll(struct file *file, struct poll_table_struct *wait)
{
struct tvd_dev *dev = video_drvdata(file);
struct vb2_queue *q = &dev->vb_vidq;
if(tvd_is_generating(dev)) {
return vb2_poll(q, file, wait);
} else {
pr_err("%s: tvd is not generating!\n", __func__);
return -EINVAL;
}
}
static int __tvd_power_enable(struct regulator *regu, bool is_true)
{
int ret = 0;
if (IS_ERR_OR_NULL(regu)) {
pr_err("regulator is err.\n");
return -EBUSY;
}
if (is_true)
ret = regulator_enable(regu);
else
ret = regulator_disable(regu);
return ret;
}
static int __tvd_gpio_request(struct gpio_config *pin_cfg)
{
int ret = 0;
char pin_name[32] = {0};
u32 config;
ret = gpio_request(pin_cfg->gpio, NULL);
if (ret) {
pr_err("tvd gpio(%d) request err!\n", pin_cfg->gpio);
return -EBUSY;
}
sunxi_gpio_to_name(pin_cfg->gpio, pin_name);
config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_FUNC, pin_cfg->mul_sel);
pin_config_set(SUNXI_PINCTRL, pin_name, config);
if (pin_cfg->pull != GPIO_PULL_DEFAULT) {
config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_PUD,
pin_cfg->pull);
pin_config_set(SUNXI_PINCTRL, pin_name, config);
}
if (pin_cfg->drv_level != GPIO_DRVLVL_DEFAULT) {
config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_DRV,
pin_cfg->drv_level);
pin_config_set(SUNXI_PINCTRL, pin_name, config);
}
if (pin_cfg->data != GPIO_DATA_DEFAULT) {
config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_DAT,
pin_cfg->data);
pin_config_set(SUNXI_PINCTRL, pin_name, config);
}
return 0;
}
static int tvd_open(struct file *file)
{
struct tvd_dev *dev = video_drvdata(file);
int ret = -1;
int i = 0;
pr_debug("%s:\n", __func__);
if (tvd_hot_plug)
__tvd_auto_plug_disable(dev);
if (tvd_is_opened(dev)) {
pr_err("%s: device open busy\n", __func__);
return -EBUSY;
}
dev->system = NTSC;
/* gpio power, open only once */
mutex_lock(&power_lock);
if (!atomic_read(&gpio_power_enable_count)) {
for (i = 0; i < atomic_read(&tvd_used_gpio_num); i++)
ret = __tvd_gpio_request(&tvd_gpio_config[i]);
}
atomic_inc(&gpio_power_enable_count);
/* pmu power */
for (i = 0; i < atomic_read(&tvd_used_power_num); i++) {
ret = __tvd_power_enable(regu[i], true);
if (ret)
pr_err("power(%s) enable failed.\n", &tvd_power[i][0]);
}
mutex_unlock(&power_lock);
if (__tvd_clk_init(dev)) {
pr_err("%s: clock init fail!\n", __func__);
}
ret = __tvd_clk_enable(dev);
__tvd_init(dev);
tvd_init(dev->sel, dev->interface);
dev->input = 0; /* default input null */
tvd_start_opened(dev);
return ret;
}
static int tvd_close(struct file *file)
{
struct tvd_dev *dev = video_drvdata(file);
int ret = 0;
int i = 0;
pr_debug("tvd_close\n");
tvd_stop_generating(dev);
__tvd_clk_disable(dev);
vb2_queue_release(&dev->vb_vidq);
tvd_stop_opened(dev);
mutex_lock(&fliter_lock);
if (fliter_count > 0 && dev->fliter.used) {
__tvd_3d_comp_mem_free(dev);
fliter_count--;
}
mutex_unlock(&fliter_lock);
/* close pmu power */
mutex_lock(&power_lock);
for (i = 0; i < atomic_read(&tvd_used_power_num); i++) {
ret = __tvd_power_enable(regu[i], false);
if (ret)
pr_err("power(%s) disable failed.\n", &tvd_power[i][0]);
}
if (atomic_dec_and_test(&gpio_power_enable_count)) {
for (i = 0; i < atomic_read(&tvd_used_gpio_num); i++)
gpio_free(tvd_gpio_config[i].gpio);
}
mutex_unlock(&power_lock);
if (tvd_hot_plug)
__tvd_auto_plug_enable(dev);
pr_debug("tvd_close end\n");
return ret;
}
static int tvd_mmap(struct file *file, struct vm_area_struct *vma)
{
struct tvd_dev *dev = video_drvdata(file);
int ret;
pr_debug("%s: mmap called, vma=0x%08lx\n",
__func__, (unsigned long)vma);
ret = vb2_mmap(&dev->vb_vidq, vma);
pr_debug("%s: vma start=0x%08lx, size=%ld, ret=%d\n",
__func__, (unsigned long)vma->vm_start,
(unsigned long)vma->vm_end - (unsigned long)vma->vm_start, ret);
return ret;
}
static int tvd_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
int ret = 0;
struct tvd_dev *dev = container_of(ctrl->handler, struct tvd_dev, ctrl_handler);
struct v4l2_control c;
memset((void*)&c, 0, sizeof(struct v4l2_control));
c.id = ctrl->id;
switch (c.id) {
case V4L2_CID_BRIGHTNESS:
c.value = tvd_get_luma(dev->sel);
break;
case V4L2_CID_CONTRAST:
c.value = tvd_get_contrast(dev->sel);
break;
case V4L2_CID_SATURATION:
c.value = tvd_get_saturation(dev->sel);
break;
}
ctrl->val = c.value;
return ret;
}
static int tvd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct tvd_dev *dev = container_of(ctrl->handler, struct tvd_dev, ctrl_handler);
int ret = 0;
struct v4l2_control c;
pr_debug("%s: %s set value: 0x%x\n", __func__, ctrl->name, ctrl->val);
c.id = ctrl->id;
c.value = ctrl->val;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
pr_debug("%s: V4L2_CID_BRIGHTNESS sel=%d, val=%d,\n",
__func__, dev->sel, ctrl->val);
tvd_set_luma(dev->sel, ctrl->val);
break;
case V4L2_CID_CONTRAST:
pr_debug("%s: V4L2_CID_CONTRAST sel=%d, val=%d,\n",
__func__, dev->sel, ctrl->val);
tvd_set_contrast(dev->sel, ctrl->val);
break;
case V4L2_CID_SATURATION:
pr_debug("%s: V4L2_CID_SATURATION sel=%d, val=%d,\n",
__func__, dev->sel, ctrl->val);
tvd_set_saturation(dev->sel, ctrl->val);
break;
}
return ret;
}
static void __tvd_set_addr_special(struct tvd_dev *dev,
struct tvd_buffer *buffer)
{
unsigned long addr_org;
unsigned int c_offset = 0;
if (buffer == NULL || buffer->paddr == NULL) {
pr_err("%s: vb_buf->priv is NULL!\n", __func__);
return;
}
addr_org = (unsigned long)buffer->paddr;
switch (dev->fmt->output_fmt) {
case TVD_PL_YUV422:
case TVD_PL_YUV420:
c_offset = dev->width * dev->height;
break;
case TVD_MB_YUV420:
c_offset = 0;
break;
default:
break;
}
tvd_set_wb_addr(dev->sel, addr_org, addr_org + c_offset);
pr_debug("%s: format:%d, addr_org = 0x%p, addr_org + c_offset = 0x%p\n",
__func__, dev->format, (void *)addr_org,
(void *)(addr_org + c_offset));
}
/* tvd device for special, 0 ~ tvd_count-1 */
int tvd_info_special(void)
{
return tvd_count;
}
EXPORT_SYMBOL(tvd_info_special);
int tvd_open_special(int tvd_fd)
{
struct tvd_dev *dev = tvd[tvd_fd];
int ret = -1;
int i = 0;
struct tvd_dmaqueue *active = &dev->vidq_special;
struct tvd_dmaqueue *done = &dev->done_special;
pr_debug("%s:\n", __func__);
if (tvd_is_opened(dev)) {
pr_err("%s: device open busy\n", __func__);
return -EBUSY;
}
dev->system = NTSC;
/* gpio power, open only once */
mutex_lock(&power_lock);
if (!atomic_read(&gpio_power_enable_count)) {
for (i = 0; i < atomic_read(&tvd_used_gpio_num); i++)
ret = __tvd_gpio_request(&tvd_gpio_config[i]);
}
atomic_inc(&gpio_power_enable_count);
/* pmu power */
for (i = 0; i < atomic_read(&tvd_used_power_num); i++) {
ret = __tvd_power_enable(regu[i], true);
if (ret)
pr_err("power(%s) enable failed.\n", &tvd_power[i][0]);
}
mutex_unlock(&power_lock);
INIT_LIST_HEAD(&active->active);
INIT_LIST_HEAD(&done->active);
if (__tvd_clk_init(dev))
pr_err("%s: clock init fail!\n", __func__);
ret = __tvd_clk_enable(dev);
__tvd_init(dev);
dev->input = 0;
dev->special_active = 1;
tvd_start_opened(dev);
return ret;
}
EXPORT_SYMBOL(tvd_open_special);
int tvd_close_special(int tvd_fd)
{
struct tvd_dev *dev = tvd[tvd_fd];
int ret = 0;
int i = 0;
struct tvd_dmaqueue *active = &dev->vidq_special;
struct tvd_dmaqueue *done = &dev->done_special;
pr_debug("%s:\n", __func__);
tvd_stop_generating(dev);
__tvd_clk_disable(dev);
tvd_stop_opened(dev);
INIT_LIST_HEAD(&active->active);
INIT_LIST_HEAD(&done->active);
dev->special_active = 0;
/* close pmu power */
mutex_lock(&power_lock);
for (i = 0; i < atomic_read(&tvd_used_power_num); i++) {
ret = __tvd_power_enable(regu[i], false);
if (ret)
pr_err("power(%s) disable failed.\n", &tvd_power[i][0]);
}
if (atomic_dec_and_test(&gpio_power_enable_count)) {
for (i = 0; i < atomic_read(&tvd_used_gpio_num); i++)
gpio_free(tvd_gpio_config[i].gpio);
}
mutex_unlock(&power_lock);
return ret;
}
EXPORT_SYMBOL(tvd_close_special);
int vidioc_s_fmt_vid_cap_special(int tvd_fd, struct v4l2_format *f)
{
struct tvd_dev *dev = tvd[tvd_fd];
int ret = 0;
pr_debug("%s:\n", __func__);
if (tvd_is_generating(dev)) {
pr_err("%s device busy\n", __func__);
return -EBUSY;
}
dev->fmt = __get_format(f);
if (!dev->fmt) {
pr_err("Fourcc format (0x%08x) invalid.\n",
f->fmt.pix.pixelformat);
return -EINVAL;
}
dev->width = f->fmt.pix.width;
dev->height = f->fmt.pix.height;
dev->fmt->field = V4L2_FIELD_NONE;
if (dev->height == 576) {
dev->system = PAL;
/* To solve the problem of PAL signal is not well.
* Accoding to the hardware designer, tvd need 29.7M
* clk input on PAL system, so here adjust clk again.
* Before this modify, PAL and NTSC have the same
* frequency which is 27M.
*/
__tvd_clk_init(dev);
} else {
dev->system = NTSC;
}
__tvd_config(dev);
pr_debug("interface=%d\n", dev->interface);
pr_debug("system=%d\n", dev->system);
pr_debug("format=%d\n", dev->format);
pr_debug("width=%d\n", dev->width);
pr_debug("height=%d\n", dev->height);
return ret;
}
EXPORT_SYMBOL(vidioc_s_fmt_vid_cap_special);
int vidioc_g_fmt_vid_cap_special(int tvd_fd, struct v4l2_format *f)
{
struct tvd_dev *dev = tvd[tvd_fd];
u32 locked = 0, system = 2;
f->fmt.pix.width = dev->width;
f->fmt.pix.height = dev->height;
__get_status(dev, &locked, &system);
if (!locked) {
pr_debug("%s: signal is not locked.\n", __func__);
return -EAGAIN;
} else {
/* system: 1->pal, 0->ntsc */
if (system == PAL) {
f->fmt.pix.width = 720;
f->fmt.pix.height = 576;
} else if (system == NTSC) {
f->fmt.pix.width = 720;
f->fmt.pix.height = 480;
} else {
pr_err("system is not sure.\n");
}
}
pr_debug("system = %d, w = %d, h = %d\n",
system, f->fmt.pix.width, f->fmt.pix.height);
return 0;
}
EXPORT_SYMBOL(vidioc_g_fmt_vid_cap_special);
int dqbuffer_special(int tvd_fd, struct tvd_buffer **buf)
{
int ret = 0;
unsigned long flags = 0;
struct tvd_dev *dev = tvd[tvd_fd];
struct tvd_dmaqueue *done = &dev->done_special;
spin_lock_irqsave(&dev->slock, flags);
if (!list_empty(&done->active)) {
*buf = list_first_entry(&done->active, struct tvd_buffer, list);
list_del(&((*buf)->list));
(*buf)->state = VB2_BUF_STATE_DEQUEUED;
} else {
ret = -1;
}
spin_unlock_irqrestore(&dev->slock, flags);
return ret;
}
EXPORT_SYMBOL(dqbuffer_special);
int qbuffer_special(int tvd_fd, struct tvd_buffer *buf)
{
struct tvd_dev *dev = tvd[tvd_fd];
struct tvd_dmaqueue *vidq = &dev->vidq_special;
unsigned long flags = 0;
int ret = 0;
spin_lock_irqsave(&dev->slock, flags);
list_add_tail(&buf->list, &vidq->active);
buf->state = VB2_BUF_STATE_QUEUED;
spin_unlock_irqrestore(&dev->slock, flags);
return ret;
}
EXPORT_SYMBOL(qbuffer_special);
int vidioc_streamon_special(int tvd_fd, enum v4l2_buf_type i)
{
struct tvd_dev *dev = tvd[tvd_fd];
struct tvd_dmaqueue *dma_q = &dev->vidq_special;
struct tvd_buffer *buf = NULL;
int ret = 0;
pr_debug("%s:\n", __func__);
mutex_lock(&dev->stream_lock);
if (i != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
ret = -EINVAL;
goto streamon_unlock;
}
if (tvd_is_generating(dev)) {
pr_err("stream has been already on\n");
ret = -1;
goto streamon_unlock;
}
dev->ms = 0;
dev->jiffies = jiffies;
dma_q->frame = 0;
dma_q->ini_jiffies = jiffies;
if (!list_empty(&dma_q->active)) {
buf = list_entry(dma_q->active.next, struct tvd_buffer, list);
} else {
pr_err("stream on, but no buffer now.\n");
goto streamon_unlock;
}
__tvd_set_addr_special(dev, buf);
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
tvd_irq_enable(dev->sel, TVD_IRQ_FRAME_END);
tvd_capture_on(dev->sel);
tvd_start_generating(dev);
streamon_unlock:
mutex_unlock(&dev->stream_lock);
return ret;
}
EXPORT_SYMBOL(vidioc_streamon_special);
int vidioc_streamoff_special(int tvd_fd, enum v4l2_buf_type i)
{
struct tvd_dev *dev = tvd[tvd_fd];
struct tvd_dmaqueue *dma_q = &dev->vidq_special;
struct tvd_dmaqueue *donelist = &dev->done_special;
struct tvd_buffer *buffer;
unsigned long flags = 0;
int ret = 0;
mutex_lock(&dev->stream_lock);
pr_debug("%s:\n", __func__);
if (!tvd_is_generating(dev)) {
pr_err("%s: stream has been already off\n", __func__);
ret = 0;
goto streamoff_unlock;
}
tvd_stop_generating(dev);
dev->ms = 0;
dev->jiffies = jiffies;
dma_q->frame = 0;
dma_q->ini_jiffies = jiffies;
tvd_irq_disable(dev->sel, TVD_IRQ_FRAME_END);
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
tvd_capture_off(dev->sel);
spin_lock_irqsave(&dev->slock, flags);
while (!list_empty(&dma_q->active)) {
buffer = list_first_entry(&dma_q->active,
struct tvd_buffer, list);
list_del(&buffer->list);
list_add(&buffer->list, &donelist->active);
}
spin_unlock_irqrestore(&dev->slock, flags);
if (i != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
ret = -EINVAL;
goto streamoff_unlock;
}
if (ret != 0) {
pr_err("%s: videobu_streamoff error!\n", __func__);
goto streamoff_unlock;
}
streamoff_unlock:
mutex_unlock(&dev->stream_lock);
return ret;
}
EXPORT_SYMBOL(vidioc_streamoff_special);
static void (*tvd_buffer_done)(int tvd_fd);
void tvd_register_buffer_done_callback(void *func)
{
pr_debug("%s\n", __func__);
tvd_buffer_done = func;
}
EXPORT_SYMBOL(tvd_register_buffer_done_callback);
static irqreturn_t tvd_isr_special(int irq, void *priv)
{
struct tvd_buffer *buf;
unsigned long flags;
struct tvd_dev *dev = (struct tvd_dev *)priv;
struct tvd_dmaqueue *dma_q = &dev->vidq_special;
struct tvd_dmaqueue *done = &dev->done_special;
int need_callback = 0;
if (tvd_is_generating(dev) == 0) {
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
return IRQ_HANDLED;
}
spin_lock_irqsave(&dev->slock, flags);
if (0 == dev->first_flag) {
dev->first_flag = 1;
goto set_next_addr;
}
if (list_empty(&dma_q->active)
|| dma_q->active.next->next == (&dma_q->active)) {
pr_debug("No active queue to serve\n");
goto unlock;
}
buf = list_entry(dma_q->active.next, struct tvd_buffer, list);
list_del(&buf->list);
dev->ms += jiffies_to_msecs(jiffies - dev->jiffies);
dev->jiffies = jiffies;
list_add_tail(&buf->list, &done->active);
need_callback = 1;
if (list_empty(&dma_q->active)) {
pr_debug("%s: No more free frame\n", __func__);
goto unlock;
}
if ((&dma_q->active) == dma_q->active.next->next) {
pr_debug("No more free frame on next time\n");
goto unlock;
}
set_next_addr:
buf = list_entry(dma_q->active.next->next, struct tvd_buffer, list);
__tvd_set_addr_special(dev, buf);
unlock:
spin_unlock(&dev->slock);
if (need_callback && tvd_buffer_done)
tvd_buffer_done(dev->id);
tvd_irq_status_clear(dev->sel, TVD_IRQ_FRAME_END);
return IRQ_HANDLED;
}
/* ------------------------------------------------------------------
File operations for the device
------------------------------------------------------------------*/
static const struct v4l2_ctrl_ops tvd_ctrl_ops = {
.g_volatile_ctrl = tvd_g_volatile_ctrl,
.s_ctrl = tvd_s_ctrl,
};
static const struct v4l2_file_operations tvd_fops = {
.owner = THIS_MODULE,
.open = tvd_open,
.release = tvd_close,
.read = tvd_read,
.poll = tvd_poll,
.ioctl = video_ioctl2,
#ifdef CONFIG_COMPAT
//.compat_ioctl32 = tvd_compat_ioctl32,
#endif
.mmap = tvd_mmap,
};
static const struct v4l2_ioctl_ops tvd_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_enum_framesizes = vidioc_enum_framesizes,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_parm = vidioc_g_parm,
.vidioc_s_parm = vidioc_s_parm,
#ifdef CONFIG_VIDEO_V4L1_COMPAT
.vidiocgmbuf = vidiocgmbuf,
#endif
};
static struct video_device tvd_template[] = {
[0] = {
.name = "tvd_0",
.fops = &tvd_fops,
.ioctl_ops = &tvd_ioctl_ops,
.release = video_device_release,
},
[1] = {
.name = "tvd_1",
.fops = &tvd_fops,
.ioctl_ops = &tvd_ioctl_ops,
.release = video_device_release,
},
[2] = {
.name = "tvd_2",
.fops = &tvd_fops,
.ioctl_ops = &tvd_ioctl_ops,
.release = video_device_release,
},
[3] = {
.name = "tvd_3",
.fops = &tvd_fops,
.ioctl_ops = &tvd_ioctl_ops,
.release = video_device_release,
},
};
static int __tvd_init_controls(struct v4l2_ctrl_handler *hdl)
{
unsigned int ret = 0;
v4l2_ctrl_handler_init(hdl, 4);
v4l2_ctrl_new_std(hdl, &tvd_ctrl_ops, V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
v4l2_ctrl_new_std(hdl, &tvd_ctrl_ops, V4L2_CID_CONTRAST, 0, 128, 1, 0);
v4l2_ctrl_new_std(hdl, &tvd_ctrl_ops, V4L2_CID_SATURATION, -4, 4, 1, 0);
if (hdl->error) {
pr_err("%s: hdl init err!\n", __func__);
ret = hdl->error;
v4l2_ctrl_handler_free(hdl);
}
return ret;
}
static int __tvd_fetch_sysconfig(int sel, char *sub_name, int value[])
{
char compat[32];
u32 len = 0;
struct device_node *node;
int ret = 0;
len = sprintf(compat, "allwinner,sunxi-tvd%d", sel);
if (len > 32)
pr_err("size of mian_name is out of range\n");
node = of_find_compatible_node(NULL, NULL, compat);
if (!node) {
pr_err("of_find_compatible_node %s fail\n", compat);
return -EINVAL;
}
if (of_property_read_u32_array(node, sub_name, value, 1)) {
pr_err("of_property_read_u32_array %s.%s fail\n", compat, sub_name);
return -EINVAL;
}
return ret;
}
static int __jude_config(struct tvd_dev *dev)
{
int ret = 0;
int id = dev->id;
if (id > 3 || id < 0) {
pr_err("%s: id is wrong!\n", __func__);
return -ENODEV;
}
/* first set sel as id */
dev->sel = id;
pr_debug("%s: sel = %d.\n", __func__, dev->sel);
ret = __tvd_fetch_sysconfig(id, (char *)"tvd_used", &tvd_status[id].tvd_used);
if (ret) {
pr_err("%s: fetch tvd_used%d err!", __func__, id);
return -EINVAL;
}
if (!tvd_status[id].tvd_used) {
pr_debug("%s: tvd_status[%d].used is null.\n", __func__, id);
return -ENODEV;
}
ret = __tvd_fetch_sysconfig(id, (char *)"tvd_if", &tvd_status[id].tvd_if);
if (ret) {
pr_err("%s: fetch tvd_if%d err!", __func__, id);
return -EINVAL;
}
dev->interface = tvd_status[id].tvd_if;
if (id > 0) {
if (tvd_status[0].tvd_used && tvd_status[0].tvd_if > 0 ) {
/* when tvd0 used and was configed as ypbpr,can not use tvd1,2 */
if (id == 1 || id == 2) {
return -ENODEV;
} else if (id == 3) {
/* reset id as 1, for video4 ypbpr,video5 cvbs*/
dev->id = 1;
return 0;
}
} else {
return 0;
}
}
return 0;
}
#if defined(CONFIG_SWITCH) || defined(CONFIG_ANDROID_SWITCH)
static char switch_lock_name[20];
static char switch_system_name[20];
static struct switch_dev switch_lock[TVD_MAX];
static struct switch_dev switch_system[TVD_MAX];
static struct task_struct *tvd_task;
static int __tvd_auto_plug_init(struct tvd_dev *dev)
{
int ret = 0;
snprintf(switch_lock_name, sizeof(switch_lock_name), "tvd_lock%d",
dev->sel);
switch_lock[dev->sel].name = switch_lock_name;
ret = switch_dev_register(&switch_lock[dev->sel]);
snprintf(switch_system_name, sizeof(switch_system_name), "tvd_system%d",
dev->sel);
switch_system[dev->sel].name = switch_system_name;
ret = switch_dev_register(&switch_system[dev->sel]);
return ret;
}
static void __tvd_auto_plug_exit(struct tvd_dev *dev)
{
switch_dev_unregister(&switch_lock[dev->sel]);
switch_dev_unregister(&switch_system[dev->sel]);
}
static int __tvd_detect_thread(void *parg)
{
s32 i = 0;
u32 locked = 0;
u32 system = 2;
static u32 systems[TVD_MAX];
static bool hpd[TVD_MAX];
for (i = 0; i < TVD_MAX; i++) {
systems[i] = NONE;
hpd[i] = false;
}
for (;;) {
if (kthread_should_stop())
break;
for (i = 0; i < tvd_count; i++) {
tvd_get_status(i, &locked, &system);
if (hpd[i] != locked) {
pr_debug("reverse hpd=%d, i = %d\n", locked, i);
hpd[i] = locked;
switch_set_state(&switch_lock[i], locked);
}
if (systems[i] != system) {
pr_debug("system = %d, i = %d\n", system, i);
systems[i] = system;
switch_set_state(&switch_system[i], system);
}
}
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(50);
}
return 0;
}
static int __tvd_auto_plug_enable(struct tvd_dev *dev)
{
int ret = 0;
int i = 0;
dev->system = NTSC;
/* gpio power, open only once */
mutex_lock(&power_lock);
if (!atomic_read(&gpio_power_enable_count)) {
for (i = 0; i < atomic_read(&tvd_used_gpio_num); i++)
ret = __tvd_gpio_request(&tvd_gpio_config[i]);
}
atomic_inc(&gpio_power_enable_count);
/* pmu power */
for (i = 0; i < atomic_read(&tvd_used_power_num); i++) {
ret = __tvd_power_enable(regu[i], true);
if (ret)
pr_err("power(%s) enable failed.\n", &tvd_power[i][0]);
}
mutex_unlock(&power_lock);
if (__tvd_clk_init(dev))
pr_err("%s: clock init fail!\n", __func__);
ret = __tvd_clk_enable(dev);
__tvd_init(dev);
tvd_init(dev->sel, dev->interface);
/* Set system as NTSC */
dev->width = 720;
dev->height = 480;
dev->fmt = &formats[0];
ret = __tvd_config(dev);
/* enable detect thread */
if (!tvd_task) {
tvd_task = kthread_create(__tvd_detect_thread, (void *)0,
"tvd detect");
if (IS_ERR(tvd_task)) {
s32 err = 0;
err = PTR_ERR(tvd_task);
tvd_task = NULL;
return err;
}
wake_up_process(tvd_task);
}
return ret;
}
static int __tvd_auto_plug_disable(struct tvd_dev *dev)
{
int ret = 0;
int i = 0;
__tvd_clk_disable(dev);
/* close pmu power */
mutex_lock(&power_lock);
for (i = 0; i < atomic_read(&tvd_used_power_num); i++) {
ret = __tvd_power_enable(regu[i], false);
if (ret)
pr_err("power(%s) disable failed.\n", &tvd_power[i][0]);
}
if (atomic_dec_and_test(&gpio_power_enable_count)) {
for (i = 0; i < atomic_read(&tvd_used_gpio_num); i++)
gpio_free(tvd_gpio_config[i].gpio);
}
mutex_unlock(&power_lock);
return ret;
}
#else
static int __tvd_auto_plug_init(struct tvd_dev *dev)
{
return 0;
}
static void __tvd_auto_plug_exit(struct tvd_dev *dev)
{
}
static int __tvd_auto_plug_enable(struct tvd_dev *dev)
{
pr_warn("there is no switch class for tvd\n");
return 0;
}
static int __tvd_auto_plug_disable(struct tvd_dev *dev)
{
return 0;
}
#endif
static void __iomem *tvd_top;
struct clk* tvd_clk_top;
static int __tvd_probe_init(int sel, struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct tvd_dev *dev;
int ret = 0;
struct video_device *vfd;
struct vb2_queue *q;
pr_debug("%s: \n", __func__);
/*request mem for dev*/
dev = kzalloc(sizeof(struct tvd_dev), GFP_KERNEL);
if (!dev) {
pr_err("request dev mem failed!\n");
return -ENOMEM;
}
pdev->id = sel;
if (pdev->id < 0) {
pr_err("TVD failed to get alias id\n");
ret = -EINVAL;
goto freedev;
}
dev->id = pdev->id;
dev->sel = sel;
dev->pdev = pdev;
dev->generating = 0;
dev->opened = 0;
spin_lock_init(&dev->slock);
/* fetch sysconfig,and judge support */
ret = __jude_config(dev);
if (ret) {
pr_err("%s:tvd%d is not used by sysconfig.\n", __func__, dev->id);
ret = -EINVAL;
goto freedev;
}
tvd[dev->id] = dev;
tvd_count++;
dev->irq = irq_of_parse_and_map(np, 0);
if (dev->irq <= 0) {
pr_err("failed to get IRQ resource\n");
ret = -ENXIO;
goto iomap_tvd_err;
}
dev->regs_tvd = of_iomap(pdev->dev.of_node, 0);
if (IS_ERR_OR_NULL(dev->regs_tvd)) {
dev_err(&pdev->dev, "unable to tvd registers\n");
ret = -EINVAL;
goto iomap_top_err;
}
dev->regs_top = tvd_top;
dev->clk_top = tvd_clk_top;
/* register irq */
ret = request_irq(dev->irq, tvd_isr, IRQF_DISABLED, pdev->name, dev);
/* get tvd clk ,name fix */
dev->clk = of_clk_get(np, 0);//fix
if (IS_ERR_OR_NULL(dev->clk)) {
pr_err("get tvd clk error!\n");
goto iomap_tvd_err;
}
/* register v4l2 device */
sprintf(dev->v4l2_dev.name, "tvd_v4l2_dev%d", dev->id);
ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev);
if (ret) {
pr_err("Error registering v4l2 device\n");
goto iomap_tvd_err;
}
ret = __tvd_init_controls(&dev->ctrl_handler);
if (ret) {
pr_err("Error v4l2 ctrls new!!\n");
goto v4l2_register_err;
}
dev->v4l2_dev.ctrl_handler = &dev->ctrl_handler;
dev_set_drvdata(&dev->pdev->dev, dev);
pr_info("%s: v4l2 subdev register.\n", __func__);
#ifdef CONFIG_PM_RUNTIME
pm_runtime_enable(&dev->pdev->dev);
#endif
vfd = video_device_alloc();
if (!vfd) {
pr_err("%s: Error video_device_alloc!\n", __func__);
goto v4l2_register_err;
}
*vfd = tvd_template[dev->id];
vfd->v4l2_dev = &dev->v4l2_dev;
ret = video_register_device(vfd, VFL_TYPE_GRABBER, dev->id + 4);
if (ret < 0) {
pr_err("Error video_register_device!!\n");
goto video_device_alloc_err;
}
video_set_drvdata(vfd, dev);
list_add_tail(&dev->devlist, &devlist); //use this for what?
dev->vfd = vfd;
pr_info("V4L2 tvd device registered as %s\n",video_device_node_name(vfd));
/* Initialize videobuf2 queue as per the buffer type */
dev->alloc_ctx = vb2_dma_contig_init_ctx(&dev->pdev->dev);
if (IS_ERR(dev->alloc_ctx)) {
pr_err("Failed to get the context\n");
goto video_device_register_err;
}
/* initialize queue */
q = &dev->vb_vidq;
q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct tvd_buffer);
q->ops = &tvd_video_qops;
q->mem_ops = &vb2_dma_contig_memops;
q->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
ret = vb2_queue_init(q);
if (ret) {
pr_err("vb2_queue_init failed\n");
vb2_dma_contig_cleanup_ctx(dev->alloc_ctx);
goto video_device_register_err;
}
INIT_LIST_HEAD(&dev->vidq.active);
ret = sysfs_create_group(&dev->pdev->dev.kobj, &tvd_attribute_group[dev->id]);
if (ret) {
pr_err("sysfs_create failed\n");
goto vb2_queue_err;
}
mutex_init(&dev->stream_lock);
mutex_init(&dev->opened_lock);
mutex_init(&dev->buf_lock);
if (tvd_hot_plug) {
__tvd_auto_plug_init(dev);
__tvd_auto_plug_enable(dev);
}
return 0;
vb2_queue_err:
vb2_queue_release(q);
video_device_register_err:
v4l2_device_unregister(&dev->v4l2_dev);
video_device_alloc_err:
video_device_release(vfd);
v4l2_register_err:
v4l2_device_unregister(&dev->v4l2_dev);
iomap_tvd_err:
iounmap((char __iomem *)dev->regs_tvd);
iomap_top_err:
iounmap((char __iomem *)dev->regs_top);
freedev:
kfree(dev);
return ret;
}
static int tvd_probe(struct platform_device *pdev)
{
int ret = 0, i = 0;
unsigned int tvd_num = 0;
struct device_node *sub_tvd = NULL;
struct platform_device *sub_pdev = NULL;
struct device_node *np = pdev->dev.of_node;
char sub_name[32] = {0};
const char *str;
mutex_init(&power_lock);
mutex_init(&fliter_lock);
tvd_top = of_iomap(pdev->dev.of_node, 0);
if (IS_ERR_OR_NULL(tvd_top)) {
dev_err(&pdev->dev, "unable to map tvd top registers\n");
ret = -EINVAL;
goto out;
}
tvd_clk_top = of_clk_get(np, 0);
if (IS_ERR_OR_NULL(tvd_clk_top)) {
pr_err("get tvd clk error!\n");
goto iomap_tvd_err;
}
of_property_read_u32(pdev->dev.of_node, "tvd_hot_plug", &tvd_hot_plug);
for (i = 0; i < TVD_MAX_POWER_NUM; i++) {
snprintf(sub_name, sizeof(sub_name), "tvd_power%d", i);
if (!of_property_read_string(pdev->dev.of_node, sub_name,
&str)) {
atomic_inc(&tvd_used_power_num);
memcpy(&tvd_power[i][0], str, strlen(str)+1);
regu[i] = regulator_get(NULL, &tvd_power[i][0]);
}
}
for (i = 0; i < TVD_MAX_GPIO_NUM; i++) {
int gpio;
snprintf(sub_name, sizeof(sub_name), "tvd_gpio%d", i);
gpio = of_get_named_gpio_flags(pdev->dev.of_node, sub_name, 0,
(enum of_gpio_flags *)&tvd_gpio_config[i]);
if (gpio_is_valid(gpio))
atomic_inc(&tvd_used_gpio_num);
}
if (of_property_read_u32(pdev->dev.of_node, "tvd-number", &tvd_num) < 0) {
dev_err(&pdev->dev, "unable to get tvd-number, force to one!\n");
tvd_num = 1;
}
for (i = 0; i < tvd_num; i++) {
sub_tvd = of_parse_phandle(pdev->dev.of_node, "tvds", i);
sub_pdev = of_find_device_by_node(sub_tvd);
if (!sub_pdev) {
dev_err(&pdev->dev, "fail to find device for tvd%d!\n", i);
continue;
}
if (sub_pdev) {
ret = __tvd_probe_init(i, sub_pdev);
if(ret!=0) {
/* one tvd may init fail because of the sysconfig */
pr_debug("tvd%d init is failed\n", i);
ret = 0;
}
}
}
iomap_tvd_err:
iounmap((char __iomem *)tvd_top);
out:
return ret;
}
static int tvd_release(void)/*fix*/
{
struct tvd_dev *dev;
struct list_head *list;
pr_debug("%s: \n", __func__);
while (!list_empty(&devlist)) {
list = devlist.next;
list_del(list);
dev = list_entry(list, struct tvd_dev, devlist);
kfree(dev);
}
pr_debug("tvd_release ok!\n");
return 0;
}
static int tvd_remove(struct platform_device *pdev)
{
struct tvd_dev *dev=(struct tvd_dev *)dev_get_drvdata(&(pdev)->dev);
int i = 0;
free_irq(dev->irq, dev);
__tvd_clk_disable(dev);
iounmap(dev->regs_top);
iounmap(dev->regs_tvd);
mutex_destroy(&dev->stream_lock);
mutex_destroy(&dev->opened_lock);
mutex_destroy(&dev->buf_lock);
sysfs_remove_group(&dev->pdev->dev.kobj, &tvd_attribute_group[dev->id]);
#ifdef CONFIG_PM_RUNTIME
pm_runtime_disable(&dev->pdev->dev);
#endif
video_unregister_device(dev->vfd);
v4l2_device_unregister(&dev->v4l2_dev);
v4l2_ctrl_handler_free(&dev->ctrl_handler);
vb2_dma_contig_cleanup_ctx(dev->alloc_ctx);
for (i = 0; i < atomic_read(&tvd_used_power_num); i++)
regulator_put(regu[i]);
return 0;
}
#ifdef CONFIG_PM_RUNTIME
static int tvd_runtime_suspend(struct device *d)
{
return 0;
}
static int tvd_runtime_resume(struct device *d)
{
return 0;
}
static int tvd_runtime_idle(struct device *d)
{
if(d) {
pm_runtime_mark_last_busy(d);
pm_request_autosuspend(d);
} else {
pr_err("%s, tvd device is null\n", __func__);
}
return 0;
}
#endif
static int tvd_suspend(struct device *d)
{
if (tvd_task) {
if (!kthread_stop(tvd_task))
tvd_task = NULL;
}
return 0;
}
static int tvd_resume(struct device *d)
{
if (!tvd_task) {
tvd_task = kthread_create(__tvd_detect_thread, (void *)0,
"tvd detect");
if (IS_ERR(tvd_task)) {
s32 err = 0;
err = PTR_ERR(tvd_task);
tvd_task = NULL;
return err;
}
wake_up_process(tvd_task);
}
return 0;
}
static void tvd_shutdown(struct platform_device *pdev)
{
}
static const struct dev_pm_ops tvd_runtime_pm_ops =
{
#ifdef CONFIG_PM_RUNTIME
.runtime_suspend = tvd_runtime_suspend,
.runtime_resume = tvd_runtime_resume,
.runtime_idle = tvd_runtime_idle,
#endif
.suspend = tvd_suspend,
.resume = tvd_resume,
};
static const struct of_device_id sunxi_tvd_match[] = {
{ .compatible = "allwinner,sunxi-tvd", },
{},
};
static struct platform_driver tvd_driver = {
.probe = tvd_probe,
.remove = tvd_remove,
.shutdown = tvd_shutdown,
.driver = {
.name = TVD_MODULE_NAME,
.owner = THIS_MODULE,
.of_match_table = sunxi_tvd_match,
.pm = &tvd_runtime_pm_ops,
}
};
static int __init tvd_module_init(void)
{
int ret;
pr_info("Welcome to tv decoder driver\n");
/*add sysconfig judge,if no use,return.*/
ret = platform_driver_register(&tvd_driver);
if (ret) {
pr_err("platform driver register failed\n");
return ret;
}
pr_info("tvd_init end\n");
return 0;
}
static void __exit tvd_module_exit(void)
{
int i = 0;
pr_info("tvd_exit\n");
if (tvd_hot_plug) {
for (i = 0; i < tvd_count; i++)
__tvd_auto_plug_exit(tvd[i]);
}
tvd_release();
platform_driver_unregister(&tvd_driver);
}
subsys_initcall_sync(tvd_module_init);
module_exit(tvd_module_exit);
MODULE_AUTHOR("zengqi");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("tvd driver for sunxi");
|
ldang264/leetcodes | src/main/java/Q00058s.java | /**
* 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
* 如果不存在最后一个单词,请返回 0 。
* 说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。
*
* 示例:
*
* 输入: "<NAME>"
* 输出: 5
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/length-of-last-word
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Q00058s {
public int lengthOfLastWord(String s) {
s = s.trim();
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) != ' ') {
i--;
}
return s.length() - 1 - i;
}
}
|
ScalablyTyped/SlinkyTyped | a/activex-word/src/main/scala/typingsSlinky/activexWord/Word/ProtectedViewWindow.scala | <reponame>ScalablyTyped/SlinkyTyped
package typingsSlinky.activexWord.Word
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ProtectedViewWindow extends StObject {
def Activate(): Unit = js.native
val Active: Boolean = js.native
val Application: typingsSlinky.activexWord.Word.Application = js.native
var Caption: String = js.native
def Close(): Unit = js.native
val Creator: Double = js.native
val Document: typingsSlinky.activexWord.Word.Document = js.native
def Edit(): typingsSlinky.activexWord.Word.Document = js.native
def Edit(
PasswordTemplate: js.UndefOr[scala.Nothing],
WritePasswordDocument: js.UndefOr[scala.Nothing],
WritePasswordTemplate: js.Any
): typingsSlinky.activexWord.Word.Document = js.native
def Edit(PasswordTemplate: js.UndefOr[scala.Nothing], WritePasswordDocument: js.Any): typingsSlinky.activexWord.Word.Document = js.native
def Edit(
PasswordTemplate: js.UndefOr[scala.Nothing],
WritePasswordDocument: js.Any,
WritePasswordTemplate: js.Any
): typingsSlinky.activexWord.Word.Document = js.native
def Edit(PasswordTemplate: js.Any): typingsSlinky.activexWord.Word.Document = js.native
def Edit(
PasswordTemplate: js.Any,
WritePasswordDocument: js.UndefOr[scala.Nothing],
WritePasswordTemplate: js.Any
): typingsSlinky.activexWord.Word.Document = js.native
def Edit(PasswordTemplate: js.Any, WritePasswordDocument: js.Any): typingsSlinky.activexWord.Word.Document = js.native
def Edit(PasswordTemplate: js.Any, WritePasswordDocument: js.Any, WritePasswordTemplate: js.Any): typingsSlinky.activexWord.Word.Document = js.native
var Height: Double = js.native
val Index: Double = js.native
var Left: Double = js.native
val Parent: js.Any = js.native
val SourceName: String = js.native
val SourcePath: String = js.native
def ToggleRibbon(): Unit = js.native
var Top: Double = js.native
var Visible: Boolean = js.native
var Width: Double = js.native
var WindowState: WdWindowState = js.native
@JSName("Word.ProtectedViewWindow_typekey")
var WordDotProtectedViewWindow_typekey: ProtectedViewWindow = js.native
}
|
jorenvo/minix2 | minix-2.0/fs/usr/src/lib/ip/gethnmadr.c | /*
* Copyright (c) 1985, 1988 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that: (1) source distributions retain this entire copyright
* notice and comment, and (2) distributions including binaries display
* the following acknowledgement: ``This product includes software
* developed by the University of California, Berkeley and its contributors''
* in the documentation or other materials provided with the distribution
* and in all advertising materials mentioning features or use of this
* software. Neither the name of the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)gethostnamadr.c 6.41 (Berkeley) 6/1/90";
#endif /* LIBC_SCCS and not lint */
#ifdef _MINIX
#include <sys/types.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <net/hton.h>
#include <net/gen/nameser.h>
#include <net/gen/netdb.h>
#include <net/gen/in.h>
#include <net/gen/inet.h>
#include <net/gen/resolv.h>
#include <net/gen/socket.h>
#else
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ctype.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>
#include <resolv.h>
#endif /* AMOEABA */
#define MAXALIASES 35
#define MAXADDRS 35
static char *h_addr_ptrs[MAXADDRS + 1];
#ifdef _MINIX
struct in_addr
{
ipaddr_t s_addr;
};
typedef u32_t u_long;
typedef u16_t u_short;
typedef u8_t u_char;
union querybuf;
extern int dn_skipname _ARGS(( const u_char *comp_dn, const u_char *eom ));
#define getshort _getshort
static struct hostent *getanswer _ARGS(( union querybuf *answer, int anslen,
int iquery ));
#define bcmp memcmp
#define bcopy(s, d, l) memcpy(d, s, l)
#endif /* _MINIX */
static struct hostent host;
static char *host_aliases[MAXALIASES];
static char hostbuf[BUFSIZ+1];
static struct in_addr host_addr;
#ifndef _MINIX
char *strpbrk();
#endif /* !_MINIX */
#if PACKETSZ > 1024
#define MAXPACKET PACKETSZ
#else
#define MAXPACKET 1024
#endif
typedef union querybuf
{
dns_hdr_t hdr;
u_char buf[MAXPACKET];
} querybuf_t;
typedef union align {
long al;
char ac;
} align_t;
static struct hostent *
getanswer(answer, anslen, iquery)
querybuf_t *answer;
int anslen;
int iquery;
{
register dns_hdr_t *hp;
register u_char *cp;
register int n;
u_char *eom;
char *bp, **ap;
int type, class, buflen, ancount, qdcount;
int haveanswer, getclass = C_ANY;
char **hap;
eom = answer->buf + anslen;
/*
* find first satisfactory answer
*/
hp = &answer->hdr;
ancount = ntohs(hp->dh_ancount);
qdcount = ntohs(hp->dh_qdcount);
bp = hostbuf;
buflen = sizeof(hostbuf);
cp = answer->buf + sizeof(dns_hdr_t);
if (qdcount) {
if (iquery) {
if ((n = dn_expand((u_char *)answer->buf, eom,
cp, (u_char *)bp, buflen)) < 0) {
h_errno = NO_RECOVERY;
return ((struct hostent *) NULL);
}
cp += n + QFIXEDSZ;
host.h_name = bp;
n = strlen(bp) + 1;
bp += n;
buflen -= n;
} else
cp += dn_skipname(cp, eom) + QFIXEDSZ;
while (--qdcount > 0)
cp += dn_skipname(cp, eom) + QFIXEDSZ;
} else if (iquery) {
if (hp->dh_flag1 & DHF_AA)
h_errno = HOST_NOT_FOUND;
else
h_errno = TRY_AGAIN;
return ((struct hostent *) NULL);
}
ap = host_aliases;
*ap = NULL;
host.h_aliases = host_aliases;
hap = h_addr_ptrs;
*hap = NULL;
#if BSD >= 43 || defined(h_addr) /* new-style hostent structure */
host.h_addr_list = h_addr_ptrs;
#endif
haveanswer = 0;
while (--ancount >= 0 && cp < eom) {
if ((n = dn_expand((u_char *)answer->buf, eom, cp, (u_char *)bp,
buflen)) < 0)
break;
cp += n;
type = getshort(cp);
cp += sizeof(u_short);
class = getshort(cp);
cp += sizeof(u_short) + sizeof(u_long);
n = getshort(cp);
cp += sizeof(u_short);
if (type == T_CNAME) {
cp += n;
if (ap >= &host_aliases[MAXALIASES-1])
continue;
*ap++ = bp;
n = strlen(bp) + 1;
bp += n;
buflen -= n;
continue;
}
if (iquery && type == T_PTR) {
if ((n = dn_expand((u8_t *)answer->buf, eom,
cp, (u8_t *)bp, buflen)) < 0) {
cp += n;
continue;
}
cp += n;
host.h_name = bp;
return(&host);
}
if (iquery || type != T_A) {
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("unexpected answer type %d, size %d\n",
type, n);
#endif
cp += n;
continue;
}
if (haveanswer) {
if (n != host.h_length) {
cp += n;
continue;
}
if (class != getclass) {
cp += n;
continue;
}
} else {
host.h_length = n;
getclass = class;
host.h_addrtype = (class == C_IN) ? AF_INET : AF_UNSPEC;
if (!iquery) {
host.h_name = bp;
bp += strlen(bp) + 1;
}
}
bp += (size_t)(sizeof(align_t) -
((u_long)bp % sizeof(align_t)));
if (bp + n >= &hostbuf[sizeof(hostbuf)]) {
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("size (%d) too big\n", n);
#endif
break;
}
bcopy(cp, *hap++ = bp, n);
bp +=n;
cp += n;
haveanswer++;
}
if (haveanswer) {
*ap = NULL;
#if BSD >= 43 || defined(h_addr) /* new-style hostent structure */
*hap = NULL;
#else
host.h_addr = h_addr_ptrs[0];
#endif
return (&host);
} else {
h_errno = TRY_AGAIN;
return ((struct hostent *) NULL);
}
}
struct hostent *
gethostbyname(name)
_CONST char *name;
{
querybuf_t buf;
register _CONST char *cp;
int n;
/*
* disallow names consisting only of digits/dots, unless
* they end in a dot.
*/
if (isdigit(name[0]))
for (cp = name;; ++cp) {
if (!*cp) {
if (*--cp == '.')
break;
/*
* All-numeric, no dot at the end.
* Fake up a hostent as if we'd actually
* done a lookup. What if someone types
* 255.255.255.255? The test below will
* succeed spuriously... ???
*/
if ((host_addr.s_addr = inet_addr(name)) == -1) {
h_errno = HOST_NOT_FOUND;
return((struct hostent *) NULL);
}
host.h_name = (char *) name;
host.h_aliases = host_aliases;
host_aliases[0] = NULL;
host.h_addrtype = AF_INET;
host.h_length = sizeof(u_long);
h_addr_ptrs[0] = (char *)&host_addr;
h_addr_ptrs[1] = (char *)0;
#if BSD >= 43 || defined(h_addr) /* new-style hostent structure */
host.h_addr_list = h_addr_ptrs;
#else
host.h_addr = h_addr_ptrs[0];
#endif
return (&host);
}
if (!isdigit(*cp) && *cp != '.')
break;
}
if ((n = res_search((char*)name, C_IN, T_A, buf.buf, sizeof(buf))) < 0) {
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("res_search failed\n");
#endif
return ((struct hostent *) NULL);
}
return (getanswer(&buf, n, 0));
}
struct hostent *
gethostbyaddr(addr, len, type)
const char *addr;
int len, type;
{
int n;
querybuf_t buf;
register struct hostent *hp;
char qbuf[MAXDNAME];
if (type != AF_INET)
return ((struct hostent *) NULL);
(void)sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa",
((unsigned)addr[3] & 0xff),
((unsigned)addr[2] & 0xff),
((unsigned)addr[1] & 0xff),
((unsigned)addr[0] & 0xff));
n = res_query(qbuf, C_IN, T_PTR, (u8_t *)&buf, sizeof(buf));
if (n < 0) {
#ifdef DEBUG
if (_res.options & RES_DEBUG)
printf("res_query failed\n");
#endif
return ((struct hostent *) NULL);
}
hp = getanswer(&buf, n, 1);
if (hp == NULL)
return ((struct hostent *) NULL);
hp->h_addrtype = type;
hp->h_length = len;
h_addr_ptrs[0] = (char *)&host_addr;
h_addr_ptrs[1] = (char *)0;
host_addr = *(struct in_addr *)addr;
#if BSD < 43 && !defined(h_addr) /* new-style hostent structure */
hp->h_addr = h_addr_ptrs[0];
#endif
return(hp);
}
|
swsachith/harp | contrib/src/main/java/edu/iu/lda/LdaMapCollective.java | package edu.iu.lda;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import edu.iu.fileformat.MultiFileInputFormat;
public class LdaMapCollective extends Configured
implements Tool {
Path inputDir;
Path outputDir;
Path metafile;
int numOfTerms;
int numOfTopics;
int numOfDocs;
int numOfMapTasks;
int numOfIterations;
int numOfThreads;
int mode;
public static void main(String[] args)
throws Exception {
int res = ToolRunner.run(new Configuration(),
new LdaMapCollective(), args);
System.exit(res);
}
@Override
public int run(String[] args) throws Exception {
if (args.length != 10) {
System.err
.println("Usage: LdaMapCollective "
+ "<input dir> " + "<metafile> "
+ "<output dir> " + "<number of terms> "
+ "<number of topics> "
+ "<number of docs> "
+ "<number of MapTasks> "
+ "<number of iterations> "
+ "<number of threads> "
+ "<mode, 1=multithreading> ");
ToolRunner
.printGenericCommandUsage(System.err);
return -1;
}
inputDir = new Path(args[0]);
metafile = new Path(args[1]);
outputDir = new Path(args[2]);
numOfTerms = Integer.parseInt(args[3]);
numOfTopics = Integer.parseInt(args[4]);
numOfDocs = Integer.parseInt(args[5]);
numOfMapTasks = Integer.parseInt(args[6]);
numOfIterations = Integer.parseInt(args[7]);
numOfThreads = Integer.parseInt(args[8]);
mode = Integer.parseInt(args[9]);
launch();
return 0;
}
void launch() {
Configuration configuration = getConf();
long beginTime = System.currentTimeMillis();
try {
Job job = configureJob(configuration);
job.waitForCompletion(true);
} catch (IOException |
ClassNotFoundException |
InterruptedException e) {
e.printStackTrace();
}
long endOfOneIteration =
System.currentTimeMillis();
System.out.println("total running time(ms): "
+ (endOfOneIteration - beginTime));
}
public Job
configureJob(Configuration configuration)
throws IOException {
Job job =
Job.getInstance(configuration, "lda_job");
FileSystem fs = FileSystem.get(configuration);
if (fs.exists(outputDir)) {
fs.delete(outputDir, true);
}
FileInputFormat.setInputPaths(job, inputDir);
FileOutputFormat.setOutputPath(job,
outputDir);
job.setInputFormatClass(
MultiFileInputFormat.class);
job.setJarByClass(LdaMapCollective.class);
if (mode == 1)
job.setMapperClass(LDAMapperDyn.class);
else {
job.setMapperClass(LDAMapper.class);
}
if (!fs.exists(metafile)) {
throw new IOException();
}
org.apache.hadoop.mapred.JobConf jobConf =
(JobConf) job.getConfiguration();
jobConf.setNumReduceTasks(0);
jobConf.set("mapreduce.framework.name",
"map-collective");
jobConf.setNumMapTasks(numOfMapTasks);
jobConf.setInt(Constants.NUM_OF_ITERATIONS,
numOfIterations);
jobConf.setInt(Constants.NUM_OF_TOPICS,
numOfTopics);
jobConf.setInt(Constants.NUM_OF_TERMS,
numOfTerms);
jobConf.setInt(Constants.NUM_OF_DOCS,
numOfDocs);
jobConf.setInt(Constants.NUM_OF_THREADS,
numOfThreads);
jobConf.setStrings(
Constants.META_DATA_FILE_NAME,
metafile.getName());
return job;
}
}
|
gza/beats | vendor/github.com/aws/aws-sdk-go-v2/service/rds/api_op_PromoteReadReplicaDBCluster.go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package rds
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/internal/awsutil"
)
// Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/PromoteReadReplicaDBClusterMessage
type PromoteReadReplicaDBClusterInput struct {
_ struct{} `type:"structure"`
// The identifier of the DB cluster Read Replica to promote. This parameter
// is not case-sensitive.
//
// Constraints:
//
// * Must match the identifier of an existing DBCluster Read Replica.
//
// Example: my-cluster-replica1
//
// DBClusterIdentifier is a required field
DBClusterIdentifier *string `type:"string" required:"true"`
}
// String returns the string representation
func (s PromoteReadReplicaDBClusterInput) String() string {
return awsutil.Prettify(s)
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *PromoteReadReplicaDBClusterInput) Validate() error {
invalidParams := aws.ErrInvalidParams{Context: "PromoteReadReplicaDBClusterInput"}
if s.DBClusterIdentifier == nil {
invalidParams.Add(aws.NewErrParamRequired("DBClusterIdentifier"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/PromoteReadReplicaDBClusterResult
type PromoteReadReplicaDBClusterOutput struct {
_ struct{} `type:"structure"`
// Contains the details of an Amazon Aurora DB cluster.
//
// This data type is used as a response element in the DescribeDBClusters, StopDBCluster,
// and StartDBCluster actions.
DBCluster *DBCluster `type:"structure"`
}
// String returns the string representation
func (s PromoteReadReplicaDBClusterOutput) String() string {
return awsutil.Prettify(s)
}
const opPromoteReadReplicaDBCluster = "PromoteReadReplicaDBCluster"
// PromoteReadReplicaDBClusterRequest returns a request value for making API operation for
// Amazon Relational Database Service.
//
// Promotes a Read Replica DB cluster to a standalone DB cluster.
//
// This action only applies to Aurora DB clusters.
//
// // Example sending a request using PromoteReadReplicaDBClusterRequest.
// req := client.PromoteReadReplicaDBClusterRequest(params)
// resp, err := req.Send(context.TODO())
// if err == nil {
// fmt.Println(resp)
// }
//
// Please also see https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/PromoteReadReplicaDBCluster
func (c *Client) PromoteReadReplicaDBClusterRequest(input *PromoteReadReplicaDBClusterInput) PromoteReadReplicaDBClusterRequest {
op := &aws.Operation{
Name: opPromoteReadReplicaDBCluster,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &PromoteReadReplicaDBClusterInput{}
}
req := c.newRequest(op, input, &PromoteReadReplicaDBClusterOutput{})
return PromoteReadReplicaDBClusterRequest{Request: req, Input: input, Copy: c.PromoteReadReplicaDBClusterRequest}
}
// PromoteReadReplicaDBClusterRequest is the request type for the
// PromoteReadReplicaDBCluster API operation.
type PromoteReadReplicaDBClusterRequest struct {
*aws.Request
Input *PromoteReadReplicaDBClusterInput
Copy func(*PromoteReadReplicaDBClusterInput) PromoteReadReplicaDBClusterRequest
}
// Send marshals and sends the PromoteReadReplicaDBCluster API request.
func (r PromoteReadReplicaDBClusterRequest) Send(ctx context.Context) (*PromoteReadReplicaDBClusterResponse, error) {
r.Request.SetContext(ctx)
err := r.Request.Send()
if err != nil {
return nil, err
}
resp := &PromoteReadReplicaDBClusterResponse{
PromoteReadReplicaDBClusterOutput: r.Request.Data.(*PromoteReadReplicaDBClusterOutput),
response: &aws.Response{Request: r.Request},
}
return resp, nil
}
// PromoteReadReplicaDBClusterResponse is the response type for the
// PromoteReadReplicaDBCluster API operation.
type PromoteReadReplicaDBClusterResponse struct {
*PromoteReadReplicaDBClusterOutput
response *aws.Response
}
// SDKResponseMetdata returns the response metadata for the
// PromoteReadReplicaDBCluster request.
func (r *PromoteReadReplicaDBClusterResponse) SDKResponseMetdata() *aws.Response {
return r.response
}
|
linapex/bitcoin-go-chinese | mining/mining.go |
//<developer>
// <name><NAME></name>
// <email><EMAIL></email>
// <wx>superexc</wx>
// <qqgroup>128148617</qqgroup>
// <url>https://jsq.ink</url>
// <role>pku engineer</role>
// <date>2019-03-16 20:02:54</date>
//</624461735822102528>
//版权所有(c)2014-2016 BTCSuite开发者
//此源代码的使用由ISC控制
//可以在许可文件中找到的许可证。
package mining
import (
"bytes"
"container/heap"
"fmt"
"time"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
)
const (
//MinHighPriority是允许
//交易应被视为高优先级。
MinHighPriority = btcutil.SatoshiPerBitcoin * 144.0 / 250
//BlockHeaderOverhead是序列化所需的最大字节数。
//块头和最大可能事务计数。
blockHeaderOverhead = wire.MaxBlockHeaderPayload + wire.MaxVarIntPayload
//CoinBaseFlags添加到生成的块的CoinBase脚本中
//用于监控bip16支持以及
//通过BTCD生成。
CoinbaseFlags = "/P2SH/btcd/"
)
//txtesc是关于事务源中事务的描述符,它与
//附加元数据。
type TxDesc struct {
//Tx是与条目关联的事务。
Tx *btcutil.Tx
//“添加”是将条目添加到源池中的时间。
Added time.Time
//Height是将项添加到源时的块高度。
//池。
Height int32
//费用是与条目关联的交易支付的总费用。
Fee int64
//feeperkb是以satoshi/1000字节为单位支付的费用。
FeePerKB int64
}
//TxSource表示要考虑包含在
//新街区。
//
//接口合同要求所有这些方法对于
//对源的并发访问。
type TxSource interface {
//LastUpdated返回上次向或添加事务的时间
//已从源池中删除。
LastUpdated() time.Time
//miningdescs返回所有
//源池中的事务。
MiningDescs() []*TxDesc
//HaveTransaction返回是否传递了事务哈希
//存在于源池中。
HaveTransaction(hash *chainhash.Hash) bool
}
//txPrioItem houses a transaction along with extra information that allows the
//要优先处理的事务并跟踪对其他事务的依赖性
//还没有开采成块。
type txPrioItem struct {
tx *btcutil.Tx
fee int64
priority float64
feePerKB int64
//Dependson持有此事务哈希所依赖的事务哈希的映射
//在。仅当事务引用其他
//源池中的事务,因此必须在
//一个街区
dependsOn map[chainhash.Hash]struct{}
}
//txPriorityQueuelessFunc描述了一个可以用作比较的函数
//事务优先级队列(TxPriorityQueue)的函数。
type txPriorityQueueLessFunc func(*txPriorityQueue, int, int) bool
//TxPriorityQueue实现TxPrioritem元素的优先级队列
//支持由txPriorityQueuelessFunc定义的任意比较函数。
type txPriorityQueue struct {
lessFunc txPriorityQueueLessFunc
items []*txPrioItem
}
//LeN返回优先级队列中的项数。它是
//堆。接口实现。
func (pq *txPriorityQueue) Len() int {
return len(pq.items)
}
//较少的返回优先级索引队列中的项目是否应该排序
//在带有索引j的项之前,通过延迟分配的less函数。它
//是堆。接口实现的一部分。
func (pq *txPriorityQueue) Less(i, j int) bool {
return pq.lessFunc(pq, i, j)
}
//交换在优先级队列中传递的索引处交换项目。它是
//堆的一部分。接口实现。
func (pq *txPriorityQueue) Swap(i, j int) {
pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
}
//push将传递的项推送到优先级队列中。它是
//堆。接口实现。
func (pq *txPriorityQueue) Push(x interface{}) {
pq.items = append(pq.items, x.(*txPrioItem))
}
//pop从优先级中删除最高优先级的项(按“更少”)。
//排队并返回。它是heap.interface实现的一部分。
func (pq *txPriorityQueue) Pop() interface{} {
n := len(pq.items)
item := pq.items[n-1]
pq.items[n-1] = nil
pq.items = pq.items[0 : n-1]
return item
}
//setlessfunc将优先级队列的比较函数设置为
//功能。它还使用新的
//函数,以便它可以立即与heap.push/pop一起使用。
func (pq *txPriorityQueue) SetLessFunc(lessFunc txPriorityQueueLessFunc) {
pq.lessFunc = lessFunc
heap.Init(pq)
}
//TxPqByPriority按事务优先级对TxPriorityQueue排序,然后按费用排序
//每千字节。
func txPQByPriority(pq *txPriorityQueue, i, j int) bool {
//在这里使用>以便pop提供最高优先级的项,而不是
//降到最低。先按优先级排序,然后按费用排序。
if pq.items[i].priority == pq.items[j].priority {
return pq.items[i].feePerKB > pq.items[j].feePerKB
}
return pq.items[i].priority > pq.items[j].priority
}
//TxPqByFee按每千字节的费用对TxPriorityQueue进行排序,然后进行事务处理。
//优先。
func txPQByFee(pq *txPriorityQueue, i, j int) bool {
//使用>这里,这样弹出窗口会给出与之相反的最高收费项目
//降到最低。先按费用排序,然后按优先级排序。
if pq.items[i].feePerKB == pq.items[j].feePerKB {
return pq.items[i].priority > pq.items[j].priority
}
return pq.items[i].feePerKB > pq.items[j].feePerKB
}
//newtxPriorityQueue返回保留
//为元素传递的空间量。新的优先级队列使用
//txpqbypriority或txpqbyfee比较功能取决于
//SortByFee参数,已初始化以用于heap.push/pop。
//优先级队列可能会比保留空间大,但会增加额外的副本
//可以通过保留一个健全的值来避免底层数组的错误。
func newTxPriorityQueue(reserve int, sortByFee bool) *txPriorityQueue {
pq := &txPriorityQueue{
items: make([]*txPrioItem, 0, reserve),
}
if sortByFee {
pq.SetLessFunc(txPQByFee)
} else {
pq.SetLessFunc(txPQByPriority)
}
return pq
}
//块模板包含一个尚未解决的块以及其他
//有关费用和每个签名操作的数量的详细信息
//块中的事务。
type BlockTemplate struct {
//区块是一个准备由矿工解决的区块。因此,它是
//除满足工作证明外,完全有效
//要求。
Block *wire.MsgBlock
//费用包含生成的每个交易中的费用金额
//模板以基本单位支付。因为第一个事务是
//coinbase, the first entry (offset 0) will contain the negative of the
//所有其他交易费用的总和。
Fees []int64
//SigOpCosts contains the number of signature operations each
//生成的模板中的事务将执行。
SigOpCosts []int64
//高度是块模板连接到主模板的高度
//链。
Height int32
//validpayaddress表示模板coinbase是否支付
//地址或任何人都可以赎回。请参阅上的文档
//newblocktemplate,用于生成有用的详细信息
//没有CoinBase付款地址的模板。
ValidPayAddress bool
//见证承诺是对见证数据(如有)的承诺。
//在街区内。This field will only be populted once segregated
//见证已激活,并且块包含一个事务
//有证人资料。
WitnessCommitment []byte
}
//
//VIEWA将包含所有原始条目和所有条目
//在VIEB中。它将替换VIEWB中也存在于VIEWA中的任何条目。
//如果VIEWA中的条目已用完。
func mergeUtxoView(viewA *blockchain.UtxoViewpoint, viewB *blockchain.UtxoViewpoint) {
viewAEntries := viewA.Entries()
for outpoint, entryB := range viewB.Entries() {
if entryA, exists := viewAEntries[outpoint]; !exists ||
entryA == nil || entryA.IsSpent() {
viewAEntries[outpoint] = entryB
}
}
}
//StandardCoinBaseScript返回适合用作
//新块的CoinBase事务的签名脚本。特别地,
//它以版本2所需的块高度开始,并添加
//额外的nonce和额外的coinbase标志。
func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) {
return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)).
AddInt64(int64(extraNonce)).AddData([]byte(CoinbaseFlags)).
Script()
}
//CreateCoinBaseTx返回支付适当补贴的CoinBase交易
//基于传递到所提供地址的块高度。当地址
//如果为零,则任何人都可以赎回CoinBase交易。
//
//有关nil的原因的详细信息,请参见newblocktemplate的注释。
//地址处理很有用。
func createCoinbaseTx(params *chaincfg.Params, coinbaseScript []byte, nextBlockHeight int32, addr btcutil.Address) (*btcutil.Tx, error) {
//创建脚本以支付到提供的支付地址(如果有)
//明确规定。否则,创建一个脚本,允许coinbase
//任何人都可以赎回。
var pkScript []byte
if addr != nil {
var err error
pkScript, err = txscript.PayToAddrScript(addr)
if err != nil {
return nil, err
}
} else {
var err error
scriptBuilder := txscript.NewScriptBuilder()
pkScript, err = scriptBuilder.AddOp(txscript.OP_TRUE).Script()
if err != nil {
return nil, err
}
}
tx := wire.NewMsgTx(wire.TxVersion)
tx.AddTxIn(&wire.TxIn{
//CoinBase事务没有输入,因此以前的输出点是
//零哈希和最大索引。
PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},
wire.MaxPrevOutIndex),
SignatureScript: coinbaseScript,
Sequence: wire.MaxTxInSequenceNum,
})
tx.AddTxOut(&wire.TxOut{
Value: blockchain.CalcBlockSubsidy(nextBlockHeight, params),
PkScript: pkScript,
})
return btcutil.NewTx(tx), nil
}
//SpendTransaction通过将输入标记为
//已用事务。它还添加了传递事务中的所有输出
//它们不能作为可用的未暂停事务输出被证明是不可暂停的。
func spendTransaction(utxoView *blockchain.UtxoViewpoint, tx *btcutil.Tx, height int32) error {
for _, txIn := range tx.MsgTx().TxIn {
entry := utxoView.LookupEntry(txIn.PreviousOutPoint)
if entry != nil {
entry.Spend()
}
}
utxoView.AddTxOuts(tx, height)
return nil
}
//logskippeddedps记录由于
//在跟踪级别生成块模板时跳过事务。
func logSkippedDeps(tx *btcutil.Tx, deps map[chainhash.Hash]*txPrioItem) {
if deps == nil {
return
}
for _, item := range deps {
log.Tracef("Skipping tx %s since it depends on %s\n",
item.tx.Hash(), tx.Hash())
}
}
//minimammediantime返回块构建允许的最小时间戳
//在提供的最佳链的末端。尤其是一秒钟之后
//每个链共识最后几个块的中间时间戳
//规则。
func MinimumMedianTime(chainState *blockchain.BestState) time.Time {
return chainState.MedianTime.Add(time.Second)
}
//medianadjustedtime返回调整后的当前时间,以确保至少
//在每个
//连锁共识规则。
func medianAdjustedTime(chainState *blockchain.BestState, timeSource blockchain.MedianTimeSource) time.Time {
//块的时间戳不能早于中间时间戳
//最后几个街区。因此,在
//当前时间和上一个中间时间后一秒。电流
//在比较之前,时间戳被截断为第二个边界,因为
//块时间戳不支持大于1的精度
//第二。
newTimestamp := timeSource.AdjustedTime()
minTimestamp := MinimumMedianTime(chainState)
if newTimestamp.Before(minTimestamp) {
newTimestamp = minTimestamp
}
return newTimestamp
}
//blktmplGenerator提供了一种类型,可用于生成块模板
//基于给定的挖掘策略和要从中选择的事务源。
//它还包含确保模板所需的其他状态
//是建立在当前最好的链条之上,并遵守共识规则。
type BlkTmplGenerator struct {
policy *Policy
chainParams *chaincfg.Params
txSource TxSource
chain *blockchain.BlockChain
timeSource blockchain.MedianTimeSource
sigCache *txscript.SigCache
hashCache *txscript.HashCache
}
//newblktmplgenerator返回给定的块模板生成器
//使用来自所提供事务源的事务的策略。
//
//为了确保
//模板构建在当前最佳链的顶部,并遵循
//共识规则。
func NewBlkTmplGenerator(policy *Policy, params *chaincfg.Params,
txSource TxSource, chain *blockchain.BlockChain,
timeSource blockchain.MedianTimeSource,
sigCache *txscript.SigCache,
hashCache *txscript.HashCache) *BlkTmplGenerator {
return &BlkTmplGenerator{
policy: policy,
chainParams: params,
txSource: txSource,
chain: chain,
timeSource: timeSource,
sigCache: sigCache,
hashCache: hashCache,
}
}
//new block template返回一个准备好解决的新块模板
//使用传递的事务源池和CoinBase中的事务
//如果不为零,则支付到传递的地址,或者
//如果传递的地址为零,任何人都可以赎回。零地址
//功能非常有用,因为存在诸如getBlockTemplate之类的情况
//rpc,其中外部挖掘软件负责创建自己的
//将替换为块模板生成的CoinBase。因此
//可以避免需要配置地址。
//
//所选和包含的事务根据以下几项进行优先级排序
//因素。首先,每个事务都有一个基于其
//值、输入时间和大小。包含较大交易的交易
//数量、旧输入和小尺寸具有最高优先级。第二,A
//每千字节的费用是为每个交易计算的。与
//每千字节的费用越高越好。最后,块生成相关
//策略设置都会考虑在内。
//
//仅花费已存在于
//块链立即添加到优先级队列
//根据优先级(然后是每千字节的费用)或
//千字节(然后是优先级)取决于blockPrioritySize
//策略设置为高优先级事务分配空间。交易
//将源池中其他事务的支出输出添加到
//依赖关系映射,以便在
//它们所依赖的事务已包括在内。
//
//一旦高优先级区域(如果配置)被填满
//交易,或者优先级低于被视为高优先级的事务,
//优先级队列将更新为按每千字节费用划分优先级(然后
//优先权)。
//
//当每千字节的费用低于txminfreefee策略设置时,
//除非BlockMinSize策略设置为
//非零,在这种情况下,块将填充低费用/免费
//直到块大小达到最小大小为止的事务。
//
//导致块超过blockMaxSize的任何事务
//策略设置,超过了每个块允许的最大签名操作数,或者
//否则将跳过块无效。
//
//鉴于上述情况,此函数生成的块的形式如下:
//
//————————————————————————————————
//CoinBase交易
//-----------------------------__
//----policy.blockPrioritySize
//高优先级事务
//_
//----------------------------------_
//| | |
//| | |
//---策略.blockMaxSize
//按费用排序的交易
//直到<=policy.txminfreefee
//| | |
//| | |
//| | |
//-----------------------------------
//低收费/非高优先级(免费)
//事务(而块大小
//<=policy.blockminize)
//—————————————————————————
func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress btcutil.Address) (*BlockTemplate, error) {
//扩展最近已知的最佳块。
best := g.chain.BestSnapshot()
nextBlockHeight := best.Height + 1
//创建向提供的
//地址。注意:CoinBase值将更新为包含
//所选交易的费用
//已选定。在这里创建它是为了尽早检测任何错误
//在下面做很多工作之前。额外的一段时间有助于
//确保交易不是重复的交易(支付
//相同的值到相同的公钥地址,否则将是
//块版本1的相同事务)。
extraNonce := uint64(0)
coinbaseScript, err := standardCoinbaseScript(nextBlockHeight, extraNonce)
if err != nil {
return nil, err
}
coinbaseTx, err := createCoinbaseTx(g.chainParams, coinbaseScript,
nextBlockHeight, payToAddress)
if err != nil {
return nil, err
}
coinbaseSigOpCost := int64(blockchain.CountSigOps(coinbaseTx)) * blockchain.WitnessScaleFactor
//获取当前源事务并创建优先级队列
//保留准备包含到块中的事务
//以及一些与优先级相关的和费用元数据。保留相同的
//可用于优先级队列的项目数。也,
//根据是否选择优先级队列的初始排序顺序
//或者不存在为高优先级事务分配的区域。
sourceTxns := g.txSource.MiningDescs()
sortedByFee := g.policy.BlockPrioritySize == 0
priorityQueue := newTxPriorityQueue(len(sourceTxns), sortedByFee)
//创建一个切片以保存要包含在
//已生成具有保留空间的块。同时创建一个utxo视图
//包含所有输入事务,以便可以进行多个查找
//避免。
blockTxns := make([]*btcutil.Tx, 0, len(sourceTxns))
blockTxns = append(blockTxns, coinbaseTx)
blockUtxos := blockchain.NewUtxoViewpoint()
//依赖项用于跟踪依赖于另一个
//源池中的事务。这与
//与每个相关事务一起保存的Dependson映射有助于快速
//确定哪些从属交易现在可以包含
//一旦每个事务都包含在块中。
dependers := make(map[chainhash.Hash]map[chainhash.Hash]*txPrioItem)
//创建切片以保存签名操作的费用和数量
//对于每个选定的事务,并为
//钴基。这允许下面的代码简单地附加有关
//选定要包含在最终块中的事务。
//但是,由于还不知道总费用,请使用虚拟值
//稍后将更新的CoinBase费用。
txFees := make([]int64, 0, len(sourceTxns))
txSigOpCosts := make([]int64, 0, len(sourceTxns))
txFees = append(txFees, -1) //已知时更新
txSigOpCosts = append(txSigOpCosts, coinbaseSigOpCost)
log.Debugf("Considering %d transactions for inclusion to new block",
len(sourceTxns))
mempoolLoop:
for _, txDesc := range sourceTxns {
//一个块不能有多个coinbase或包含
//未定案交易。
tx := txDesc.Tx
if blockchain.IsCoinBase(tx) {
log.Tracef("Skipping coinbase tx %s", tx.Hash())
continue
}
if !blockchain.IsFinalizedTransaction(tx, nextBlockHeight,
g.timeSource.AdjustedTime()) {
log.Tracef("Skipping non-finalized tx %s", tx.Hash())
continue
}
//获取此事务引用的所有utxos。
//注意:这不会从
//自依赖于其他
//mempool中的事务必须在这些事务之后
//最终生成的块中的依赖项。
utxos, err := g.chain.FetchUtxoView(tx)
if err != nil {
log.Warnf("Unable to fetch utxo view for tx %s: %v",
tx.Hash(), err)
continue
}
//为引用的任何事务设置依赖项
//内存池中的其他事务,以便
//以下命令。
prioItem := &txPrioItem{tx: tx}
for _, txIn := range tx.MsgTx().TxIn {
originHash := &txIn.PreviousOutPoint.Hash
entry := utxos.LookupEntry(txIn.PreviousOutPoint)
if entry == nil || entry.IsSpent() {
if !g.txSource.HaveTransaction(originHash) {
log.Tracef("Skipping tx %s because it "+
"references unspent output %s "+
"which is not available",
tx.Hash(), txIn.PreviousOutPoint)
continue mempoolLoop
}
//该事务正在引用另一个事务
//源池中的事务,因此设置
//排序依赖项。
deps, exists := dependers[*originHash]
if !exists {
deps = make(map[chainhash.Hash]*txPrioItem)
dependers[*originHash] = deps
}
deps[*prioItem.tx.Hash()] = prioItem
if prioItem.dependsOn == nil {
prioItem.dependsOn = make(
map[chainhash.Hash]struct{})
}
prioItem.dependsOn[*originHash] = struct{}{}
//跳过下面的检查。我们已经知道
//引用的事务可用。
continue
}
}
//使用输入计算最终事务优先级
//价值年限总和以及调整后的交易规模。这个
//公式为:SUM(输入值*输入值)/ADjustedTxsize
prioItem.priority = CalcPriority(tx.MsgTx(), utxos,
nextBlockHeight)
//计算Satoshi /KB的费用。
prioItem.feePerKB = txDesc.FeePerKB
prioItem.fee = txDesc.Fee
//将事务添加到优先级队列以将其标记为就绪
//用于包含在块中,除非它具有依赖项。
if prioItem.dependsOn == nil {
heap.Push(priorityQueue, prioItem)
}
//将输入事务中引用的输出合并到
//此事务进入块utxo视图。这允许
//下面的代码避免再次查找。
mergeUtxoView(blockUtxos, utxos)
}
log.Tracef("Priority queue len %d, dependers len %d",
priorityQueue.Len(), len(dependers))
//起始块大小是块头的大小加上最大值
//可能的事务计数大小,加上coinbase的大小
//交易。
blockWeight := uint32((blockHeaderOverhead * blockchain.WitnessScaleFactor) +
blockchain.GetTransactionWeight(coinbaseTx))
blockSigOpCost := coinbaseSigOpCost
totalFees := int64(0)
//查询版本位状态,查看segwit是否已激活,如果
//所以这意味着我们将包括与证人的任何交易
//在mempool中添加数据,并将证人承诺作为
//op_返回coinbase事务中的输出。
segwitState, err := g.chain.ThresholdState(chaincfg.DeploymentSegwit)
if err != nil {
return nil, err
}
segwitActive := segwitState == blockchain.ThresholdActive
witnessIncluded := false
//选择将其放入块中的事务。
for priorityQueue.Len() > 0 {
//获取最高优先级(或每千字节的最高费用)
//取决于排序顺序)事务。
prioItem := heap.Pop(priorityQueue).(*txPrioItem)
tx := prioItem.tx
switch {
//如果隔离证人还没有被激活,那么我们
//不应包括块中的任何见证事务。
case !segwitActive && tx.HasWitness():
continue
//否则,跟踪是否包括交易
//是否有证人资料。如果是,那么我们需要包括
//作为CoinBase中最后一个输出的见证承诺
//交易。
case segwitActive && !witnessIncluded && tx.HasWitness():
//如果我们要包括交易承担
//证人数据,那么我们还需要包括
//见证CoinBase交易中的承诺。
//因此,我们考虑了额外的重量
//在带有CoinBase TX模型的块内,
//见证承诺。
coinbaseCopy := btcutil.NewTx(coinbaseTx.MsgTx().Copy())
coinbaseCopy.MsgTx().TxIn[0].Witness = [][]byte{
bytes.Repeat([]byte("a"),
blockchain.CoinbaseWitnessDataLen),
}
coinbaseCopy.MsgTx().AddTxOut(&wire.TxOut{
PkScript: bytes.Repeat([]byte("a"),
blockchain.CoinbaseWitnessPkScriptLength),
})
//为了准确计算重量
//由于这个CoinBase交易,我们将添加
//交易前后的差额
//增加了对块重的承诺。
weightDiff := blockchain.GetTransactionWeight(coinbaseCopy) -
blockchain.GetTransactionWeight(coinbaseTx)
blockWeight += uint32(weightDiff)
witnessIncluded = true
}
//获取任何依赖于此事务的事务。
deps := dependers[*tx.Hash()]
//强制最大块大小。同时检查是否溢出。
txWeight := uint32(blockchain.GetTransactionWeight(tx))
blockPlusTxWeight := blockWeight + txWeight
if blockPlusTxWeight < blockWeight ||
blockPlusTxWeight >= g.policy.BlockMaxWeight {
log.Tracef("Skipping tx %s because it would exceed "+
"the max block weight", tx.Hash())
logSkippedDeps(tx, deps)
continue
}
//强制每个块的最大签名操作成本。阿尔索
//检查是否溢出。
sigOpCost, err := blockchain.GetSigOpCost(tx, false,
blockUtxos, true, segwitActive)
if err != nil {
log.Tracef("Skipping tx %s due to error in "+
"GetSigOpCost: %v", tx.Hash(), err)
logSkippedDeps(tx, deps)
continue
}
if blockSigOpCost+int64(sigOpCost) < blockSigOpCost ||
blockSigOpCost+int64(sigOpCost) > blockchain.MaxBlockSigOpsCost {
log.Tracef("Skipping tx %s because it would "+
"exceed the maximum sigops per block", tx.Hash())
logSkippedDeps(tx, deps)
continue
}
//一旦块大于
//最小块大小。
if sortedByFee &&
prioItem.feePerKB < int64(g.policy.TxMinFreeFee) &&
blockPlusTxWeight >= g.policy.BlockMinWeight {
log.Tracef("Skipping tx %s with feePerKB %d "+
"< TxMinFreeFee %d and block weight %d >= "+
"minBlockWeight %d", tx.Hash(), prioItem.feePerKB,
g.policy.TxMinFreeFee, blockPlusTxWeight,
g.policy.BlockMinWeight)
logSkippedDeps(tx, deps)
continue
}
//一旦块大于
//优先级大小或没有更高的优先级
//交易。
if !sortedByFee && (blockPlusTxWeight >= g.policy.BlockPrioritySize ||
prioItem.priority <= MinHighPriority) {
log.Tracef("Switching to sort by fees per "+
"kilobyte blockSize %d >= BlockPrioritySize "+
"%d || priority %.2f <= minHighPriority %.2f",
blockPlusTxWeight, g.policy.BlockPrioritySize,
prioItem.priority, MinHighPriority)
sortedByFee = true
priorityQueue.SetLessFunc(txPQByFee)
//将事务放回优先级队列,然后
//跳过它,如果不这样做的话,它将被费用重新优先考虑。
//适合高优先级部分或优先级
//太低了。否则,此事务将是
//在高优先级部分的最后一个,所以就下降吧
//但是下面的代码,所以现在添加了它。
if blockPlusTxWeight > g.policy.BlockPrioritySize ||
prioItem.priority < MinHighPriority {
heap.Push(priorityQueue, prioItem)
continue
}
}
//确保事务输入通过所有必要的
//允许将其添加到块之前的先决条件。
_, err = blockchain.CheckTransactionInputs(tx, nextBlockHeight,
blockUtxos, g.chainParams)
if err != nil {
log.Tracef("Skipping tx %s due to error in "+
"CheckTransactionInputs: %v", tx.Hash(), err)
logSkippedDeps(tx, deps)
continue
}
err = blockchain.ValidateTransactionScripts(tx, blockUtxos,
txscript.StandardVerifyFlags, g.sigCache,
g.hashCache)
if err != nil {
log.Tracef("Skipping tx %s due to error in "+
"ValidateTransactionScripts: %v", tx.Hash(), err)
logSkippedDeps(tx, deps)
continue
}
//使用块utxo视图中的事务输入并添加
//用于确保引用的任何交易的条目
//这一个将它作为输入提供,并可以确保它们
//不是双倍消费。
spendTransaction(blockUtxos, tx, nextBlockHeight)
//将事务添加到块、递增计数器和
//将费用和签名操作计数保存到块中
//模板。
blockTxns = append(blockTxns, tx)
blockWeight += txWeight
blockSigOpCost += int64(sigOpCost)
totalFees += prioItem.fee
txFees = append(txFees, prioItem.fee)
txSigOpCosts = append(txSigOpCosts, int64(sigOpCost))
log.Tracef("Adding tx %s (priority %.2f, feePerKB %.2f)",
prioItem.tx.Hash(), prioItem.priority, prioItem.feePerKB)
//添加依赖于此事务的事务(也不添加
//有任何其他未经授权的依赖项)
//排队。
for _, item := range deps {
//将事务添加到优先级队列(如果存在)
//在此之后不再依赖。
delete(item.dependsOn, *tx.Hash())
if len(item.dependsOn) == 0 {
heap.Push(priorityQueue, item)
}
}
}
//现在已选择实际交易记录,请更新
//实际交易计数和coinbase值的块权重
//相应的总费用。
blockWeight -= wire.MaxVarIntPayload -
(uint32(wire.VarIntSerializeSize(uint64(len(blockTxns)))) *
blockchain.WitnessScaleFactor)
coinbaseTx.MsgTx().TxOut[0].Value += totalFees
txFees[0] = -totalFees
//如果Segwit是活跃的,并且我们包括有见证数据的交易,
//然后我们需要在
//op_返回coinbase事务中的输出。
var witnessCommitment []byte
if witnessIncluded {
//CoinBase事务的见证必须正好为32个字节
//全零的
var witnessNonce [blockchain.CoinbaseWitnessDataLen]byte
coinbaseTx.MsgTx().TxIn[0].Witness = wire.TxWitness{witnessNonce[:]}
//接下来,获取由
//块中所有事务的wtxid。硬币库
//事务将具有所有零的特殊wtxid。
witnessMerkleTree := blockchain.BuildMerkleTreeStore(blockTxns,
true)
witnessMerkleRoot := witnessMerkleTree[len(witnessMerkleTree)-1]
//证人承诺的预兆是:
//目击证人
var witnessPreimage [64]byte
copy(witnessPreimage[:32], witnessMerkleRoot[:])
copy(witnessPreimage[32:], witnessNonce[:])
//证人承诺本身就是
//见证上图。带着承诺
//生成,输出的见证脚本为:op_-return
//操作数据0XA21A9ED见证承诺。领导
//前缀被称为“见证魔法字节”。
witnessCommitment = chainhash.DoubleHashB(witnessPreimage[:])
witnessScript := append(blockchain.WitnessMagicBytes, witnessCommitment...)
//最后,创建带证人承诺的Op_返回
//输出作为coinbase中的附加输出。
commitmentOutput := &wire.TxOut{
Value: 0,
PkScript: witnessScript,
}
coinbaseTx.MsgTx().TxOut = append(coinbaseTx.MsgTx().TxOut,
commitmentOutput)
}
//计算块所需的难度。时间戳
//可能会进行调整,以确保它在
//最后几个区块按照链共识规则。
ts := medianAdjustedTime(best, g.timeSource)
reqDifficulty, err := g.chain.CalcNextRequiredDifficulty(ts)
if err != nil {
return nil, err
}
//根据
//规则更改部署。
nextBlockVersion, err := g.chain.CalcNextBlockVersion()
if err != nil {
return nil, err
}
//创建一个准备解决的新块。
merkles := blockchain.BuildMerkleTreeStore(blockTxns, false)
var msgBlock wire.MsgBlock
msgBlock.Header = wire.BlockHeader{
Version: nextBlockVersion,
PrevBlock: best.Hash,
MerkleRoot: *merkles[len(merkles)-1],
Timestamp: ts,
Bits: reqDifficulty,
}
for _, tx := range blockTxns {
if err := msgBlock.AddTransaction(tx.MsgTx()); err != nil {
return nil, err
}
}
//最后,根据链对创建的块执行完全检查
//一致同意的规则,以确保它正确地连接到当前的最佳
//链没有问题。
block := btcutil.NewBlock(&msgBlock)
block.SetHeight(nextBlockHeight)
if err := g.chain.CheckConnectBlockTemplate(block); err != nil {
return nil, err
}
log.Debugf("Created new block template (%d transactions, %d in "+
"fees, %d signature operations cost, %d weight, target difficulty "+
"%064x)", len(msgBlock.Transactions), totalFees, blockSigOpCost,
blockWeight, blockchain.CompactToBig(msgBlock.Header.Bits))
return &BlockTemplate{
Block: &msgBlock,
Fees: txFees,
SigOpCosts: txSigOpCosts,
Height: nextBlockHeight,
ValidPayAddress: payToAddress != nil,
WitnessCommitment: witnessCommitment,
}, nil
}
//updateBlockTime将传递的块头中的时间戳更新为
//当前时间,同时考虑最后一个时间的中间值
//several blocks to ensure the new time is after that time per the chain
//共识规则。最后,如果需要,它将更新目标难度
//基于测试网络的新时间,因为它们的目标难度可以
//根据时间变化。
func (g *BlkTmplGenerator) UpdateBlockTime(msgBlock *wire.MsgBlock) error {
//新的时间戳可能会被调整,以确保它在
//每个链共识最后几个块的中间时间
//规则。
newTime := medianAdjustedTime(g.chain.BestSnapshot(), g.timeSource)
msgBlock.Header.Timestamp = newTime
//如果在需要的网络上运行,则重新计算难度。
if g.chainParams.ReduceMinDifficulty {
difficulty, err := g.chain.CalcNextRequiredDifficulty(newTime)
if err != nil {
return err
}
msgBlock.Header.Bits = difficulty
}
return nil
}
//updateExtrance更新传递的coinBase脚本中的额外nonce
//通过使用传递的值和块重新生成coinbase脚本来阻止
//高度。它还重新计算并更新产生的新merkle根目录
//更改coinbase脚本。
func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int32, extraNonce uint64) error {
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
if err != nil {
return err
}
if len(coinbaseScript) > blockchain.MaxCoinbaseScriptLen {
return fmt.Errorf("coinbase transaction script length "+
"of %d is out of range (min: %d, max: %d)",
len(coinbaseScript), blockchain.MinCoinbaseScriptLen,
blockchain.MaxCoinbaseScriptLen)
}
msgBlock.Transactions[0].TxIn[0].SignatureScript = coinbaseScript
//TODO(Davec):bcutil.block应使用保存在状态以避免
//重新计算所有其他事务哈希。
//块.事务[0].无效缓存()
//使用更新的额外nonce重新计算merkle根。
block := btcutil.NewBlock(msgBlock)
merkles := blockchain.BuildMerkleTreeStore(block.Transactions(), false)
msgBlock.Header.MerkleRoot = *merkles[len(merkles)-1]
return nil
}
//BestSnapshot返回有关当前最佳链块和
//使用链实例的当前时间点的相关状态
//与块模板生成器关联。返回的状态必须为
//被视为不可变的,因为它由所有调用方共享。
//
//此函数对于并发访问是安全的。
func (g *BlkTmplGenerator) BestSnapshot() *blockchain.BestState {
return g.chain.BestSnapshot()
}
//TxSource返回关联的事务源。
//
//此函数对于并发访问是安全的。
func (g *BlkTmplGenerator) TxSource() TxSource {
return g.txSource
}
|
kundajelab/kerasAC | kerasAC/architectures/functional_basset_classification_gc_corrected.py | import numpy as np ;
from kerasAC.metrics import *
from kerasAC.custom_losses import *
def getModelGivenModelOptionsAndWeightInits(args):
#get the arguments
seed=args.seed
w0=args.w0
w1=args.w1
ntasks=args.num_tasks
init_weights=args.init_weights
np.random.seed(seed)
import keras;
from keras.layers.core import Dropout, Reshape, Dense, Activation, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.optimizers import Adadelta, SGD, RMSprop;
import keras.losses;
from keras.constraints import maxnorm;
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l1, l2
from keras import backend as K
from keras.layers import Input, Concatenate
from keras.models import Model
K.set_image_data_format('channels_last')
print(K.image_data_format())
seq = Input(shape=(1,1000,4))
gc=Input(shape=(1,))
if (init_weights!=None):
#load the weight initializations
data=np.load(init_weights);
x = Conv2D(filters=300,kernel_size=(1,19),weights=[data['0.Conv/weights:0'],np.zeros(300,)],padding="same")(seq)
x = BatchNormalization(axis=-1,weights=[data['2.BatchNorm/gamma:0'],data['1.BatchNorm/beta:0'],np.zeros(300,),np.zeros(300,)])(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(1,3))(x)
x = Conv2D(filters=200,kernel_size=(1,11),weights=[data['3.Conv_1/weights:0'],np.zeros(200,)],padding="same")(x)
x = BatchNormalization(axis=-1,weights=[data['5.BatchNorm_1/gamma:0'],data['4.BatchNorm_1/beta:0'],np.zeros(200,),np.zeros(200,)])(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(1,4))(x)
x = Conv2D(filters=200,kernel_size=(1,7),weights=[data['6.Conv_2/weights:0'],np.zeros(200,)],padding="same")(x)
x = BatchNormalization(axis=-1,weights=[data['8.BatchNorm_2/gamma:0'],data['7.BatchNorm_2/beta:0'],np.zeros(200,),np.zeros(200,)])(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(1,4))(x)
x = Flatten()(x)
x = Dense(1000,weights=[data['9.fc0/fully_connected/weights:0'],np.zeros(1000,)])(x)
x = BatchNormalization(axis=1,weights=[data['11.fc0/BatchNorm/gamma:0'],data['10.fc0/BatchNorm/beta:0'],np.zeros(1000,),np.zeros(1000,)])(x)
x = Activation('relu')(x)
x = Dropout(0.3)(x)
x = Dense(1000,weights=[data['12.fc1/fully_connected/weights:0'],np.zeros(1000,)])(x)
x = BatchNormalization(axis=1,weights=[data['14.fc1/BatchNorm/gamma:0'],data['13.fc1/BatchNorm/beta:0'],np.zeros(1000,),np.zeros(1000,)])(x)
x = Activation('relu')(x)
x = Dropout(0.3)(x)
#add in the gc content
added=Concatenate(axis=-1)([x,gc])
y = Dense(ntasks)(added)
outputs = Activation("sigmoid")(y)
else:
x = Conv2D(filters=300,kernel_size=(1,19),input_shape=(1,1000,4))(seq)
x = BatchNormalization(axis=-1)(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(1,3))(x)
x = Conv2D(filters=200,kernel_size=(1,11))(x)
x = BatchNormalization(axis=-1)(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(1,4))(x)
x = Conv2D(filters=200,kernel_size=(1,7))(x)
x = BatchNormalization(axis=-1)(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(1,4))(x)
x = Flatten()(x)
x = Dense(1000)(x)
x = BatchNormalization(axis=-1)(x)
x = Activation('relu')(x)
x = Dropout(0.3)(x)
x = Dense(1000)(x)
x = BatchNormalization(axis=-1)(x)
x = Activation('relu')(x)
x = Dropout(0.3)(x)
#add in the gc content
added=Concatenate(axis=-1)([x,gc])
y = Dense(ntasks)(added)
outputs = Activation("sigmoid")(y)
adam = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
print("compiling!")
loss=ambig_binary_crossentropy
model = Model(inputs = [seq,gc], outputs = outputs)
model.compile(optimizer=adam,loss=loss)
return model
|
iridium-browser/iridium-browser | chrome/browser/ui/commander/open_url_command_source.cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/commander/open_url_command_source.h"
#include "base/i18n/case_conversion.h"
#include "base/strings/utf_string_conversions.h"
#include "build/branding_buildflags.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/commander/fuzzy_finder.h"
#include "chrome/grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"
namespace commander {
namespace {
std::vector<std::pair<std::u16string, GURL>> CreateTitleURLMap() {
return {
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
{u"Chrome Help",
GURL("https://support.google.com/chrome/?p=help&ctx=menu#topic=9796470")},
// GSuite
{u"New Google Doc", GURL("https://docs.new")},
{u"New Google Sheet", GURL("https://sheets.new")},
{u"New Google Slides", GURL("https://slides.new")},
{u"New Google Form", GURL("https://forms.new")},
{u"New Google Meet", GURL("https://meet.new")},
{u"Open Theme Store",
GURL(l10n_util::GetStringUTF8(IDS_THEMES_GALLERY_URL))},
{u"Open Extension Store",
GURL(l10n_util::GetStringUTF8(IDS_WEBSTORE_URL))},
#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
};
}
} // namespace
OpenURLCommandSource::OpenURLCommandSource()
: title_url_map_(CreateTitleURLMap()) {}
OpenURLCommandSource::~OpenURLCommandSource() = default;
CommandSource::CommandResults OpenURLCommandSource::GetCommands(
const std::u16string& input,
Browser* browser) const {
CommandSource::CommandResults results;
std::vector<gfx::Range> ranges;
FuzzyFinder finder(input);
for (const auto& command_spec : title_url_map_) {
std::u16string title = command_spec.first;
double score = finder.Find(title, &ranges);
if (score == 0)
continue;
auto item = std::make_unique<CommandItem>(title, score, ranges);
// base::Unretained is safe because commands are reset when a browser is
// closed.
item->command =
base::BindOnce(&chrome::AddTabAt, base::Unretained(browser),
command_spec.second, -1, true, base::nullopt);
results.push_back(std::move(item));
}
return results;
}
} // namespace commander
|
fakeNetflix/uber-repo-potter | cli/lib/default-print.js | <filename>cli/lib/default-print.js
module.exports = defaultPrint;
function defaultPrint(name) {
return function printCallback(err, result) {
if (err) {
console.log(name + ' failed to complete');
console.error(err.message);
return process.exit(1);
}
console.log(name + ' finished');
if (result) console.log(result);
process.exit(0);
};
}
|
Robbbert/messui | src/mame/drivers/pockstat.cpp | // license:BSD-3-Clause
// copyright-holders:<NAME>
/***************************************************************************
Sony PocketStation
PocketStation games were downloaded from PS1 games into flash RAM after
the unit had been inserted in the memory card slot, and so this should
be emulated alongside the PS1. However, as many flash dumps exist, it
is possible to emulate the PocketStation in the meantime.
CPU: ARM7T (32 bit RISC Processor)
Memory: 2Kbytes of SRAM, 128Kbytes of FlashROM
Graphics: 32x32 monochrome LCD
Sound: 1 12-bit PCM channel
Input: 5 input buttons, 1 reset button
Infrared communication: Bi-directional and uni-directional comms
Other: 1 LED indicator
Currently, a handful of games run, but some die due to odd hardware
issues.
To start a game:
- Wait for the set-date screen to appear
- Press Down
- Set date with directional controls (optional)
- Press Button 1, wait, press Button 1, press Right, game starts
If you do nothing for about 20 secs, it turns itself off (screen goes white).
****************************************************************************/
#include "emu.h"
#include "bus/generic/carts.h"
#include "bus/generic/slot.h"
#include "cpu/arm7/arm7.h"
#include "cpu/arm7/arm7core.h"
#include "sound/dac.h"
#include "emupal.h"
#include "screen.h"
#include "speaker.h"
#define LOG_UNKNOWN (1 << 0)
#define LOG_FTLB (1 << 1)
#define LOG_IRQS (1 << 2)
#define LOG_INTC (1 << 3)
#define LOG_TIMER (1 << 4)
#define LOG_CLOCK (1 << 5)
#define LOG_RTC (1 << 6)
#define LOG_LCD (1 << 7)
#define LOG_AUDIO (1 << 8)
#define LOG_ALL (LOG_UNKNOWN | LOG_FTLB | LOG_IRQS | LOG_INTC | LOG_TIMER | LOG_CLOCK | LOG_RTC | LOG_LCD | LOG_AUDIO)
#define LOG_DEFAULT LOG_ALL
#define VERBOSE (0)
#include "logmacro.h"
namespace {
class pockstat_state : public driver_device
{
public:
pockstat_state(const machine_config &mconfig, device_type type, const char *tag) :
driver_device(mconfig, type, tag),
m_lcd_buffer(*this, "lcd_buffer"),
m_maincpu(*this, "maincpu"),
m_cart(*this, "cartslot")
{ }
void pockstat(machine_config &config);
DECLARE_INPUT_CHANGED_MEMBER(input_update);
protected:
virtual void machine_start() override;
virtual void machine_reset() override;
private:
void mem_map(address_map &map);
uint32_t screen_update_pockstat(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);
void set_interrupt_line(uint32_t line, int state);
uint32_t get_interrupt_line(uint32_t line);
void timer_start(int index);
required_shared_ptr<uint32_t> m_lcd_buffer;
required_device<cpu_device> m_maincpu;
required_device<generic_slot_device> m_cart;
memory_region *m_cart_rom;
static constexpr uint32_t TIMER_COUNT = 3;
enum : uint32_t
{
CLOCK_STEADY = 0x10
};
enum
{
INT_BTN_ACTION = 0x00000001, // "Action button"
INT_BTN_RIGHT = 0x00000002, // "Right button"
INT_BTN_LEFT = 0x00000004, // "Left button"
INT_BTN_DOWN = 0x00000008, // "Down button"
INT_BTN_UP = 0x00000010, // "Up button"
INT_UNKNOWN = 0x00000020, // "Unknown"
INT_COM = 0x00000040, // "COM" ???
INT_TIMER0 = 0x00000080, // "Timer 0"
INT_TIMER1 = 0x00000100, // "Timer 1"
INT_RTC = 0x00000200, // "RTC"
INT_BATTERY = 0x00000400, // "Battery Monitor"
INT_IOP = 0x00000800, // "IOP"
INT_IRDA = 0x00001000, // "IrDA"
INT_TIMER2 = 0x00002000, // "Timer 2"
INT_IRQ_MASK = 0x00001fbf,
INT_FIQ_MASK = 0x00002040,
INT_STATUS_MASK = 0x0000021f
};
struct ftlb_regs_t
{
uint32_t control;
uint32_t stat;
uint32_t valid;
uint32_t wait1;
uint32_t wait2;
uint32_t entry[16];
uint32_t serial;
} m_ftlb_regs;
struct intc_regs_t
{
uint32_t hold;
uint32_t status;
uint32_t enable;
uint32_t mask;
} m_intc_regs;
struct timer_t
{
uint32_t period;
uint32_t count;
uint32_t control;
emu_timer *timer;
} m_timers[TIMER_COUNT];
struct clock_regs_t
{
uint32_t mode;
uint32_t control;
} m_clock_regs;
struct rtc_regs_t
{
uint32_t mode;
uint32_t control;
uint32_t time;
uint32_t date;
emu_timer *timer;
} m_rtc_regs;
uint32_t m_lcd_control;
int32_t m_flash_write_enable_count;
int32_t m_flash_write_count;
uint32_t ftlb_r(offs_t offset, uint32_t mem_mask = ~0);
void ftlb_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
uint32_t intc_r(offs_t offset, uint32_t mem_mask = ~0);
void intc_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
uint32_t timer_r(offs_t offset, uint32_t mem_mask = ~0);
void timer_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
uint32_t clock_r(offs_t offset, uint32_t mem_mask = ~0);
void clock_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
uint32_t rtc_r(offs_t offset, uint32_t mem_mask = ~0);
void rtc_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
uint32_t lcd_r(offs_t offset, uint32_t mem_mask = ~0);
void lcd_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
uint32_t rombank_r(offs_t offset, uint32_t mem_mask = ~0);
uint32_t flash_r(offs_t offset, uint32_t mem_mask = ~0);
void flash_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
uint32_t audio_r(offs_t offset, uint32_t mem_mask = ~0);
void audio_w(offs_t offset, uint32_t data, uint32_t mem_mask = ~0);
TIMER_CALLBACK_MEMBER(timer_tick);
TIMER_CALLBACK_MEMBER(rtc_tick);
DECLARE_DEVICE_IMAGE_LOAD_MEMBER(flash_load);
static const int CPU_FREQ[16];
};
const int pockstat_state::CPU_FREQ[16] =
{
0x00f800,
0x01f000,
0x03e000,
0x07c000,
0x0f8000,
0x1e8000,
0x3d0000,
0x7a0000,
0x7a0000,
0x7a0000,
0x7a0000,
0x7a0000,
0x7a0000,
0x7a0000,
0x7a0000,
0x7a0000
};
uint32_t pockstat_state::ftlb_r(offs_t offset, uint32_t mem_mask)
{
switch(offset)
{
case 0x0000/4:
LOGMASKED(LOG_FTLB, "%s: FlashROM TLB Control = %08x & %08x\n", machine().describe_context(), m_ftlb_regs.control, mem_mask);
return m_ftlb_regs.control | 1; // ???
case 0x0004/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_STAT) = %08x & %08x\n", machine().describe_context(), m_ftlb_regs.stat, mem_mask);
return m_ftlb_regs.stat;
case 0x0008/4:
LOGMASKED(LOG_FTLB, "%s: FlashROM TLB Valid Tag = %08x & %08x\n", machine().describe_context(), m_ftlb_regs.valid, mem_mask);
return m_ftlb_regs.valid;
case 0x000c/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_WAIT1) = %08x & %08x\n", machine().describe_context(), m_ftlb_regs.wait1, mem_mask);
return m_ftlb_regs.wait1;
case 0x0010/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_WAIT2) = %08x & %08x\n", machine().describe_context(), m_ftlb_regs.wait2 | 0x04, mem_mask);
return m_ftlb_regs.wait2 | 0x04;
case 0x0100/4:
case 0x0104/4:
case 0x0108/4:
case 0x010c/4:
case 0x0110/4:
case 0x0114/4:
case 0x0118/4:
case 0x011c/4:
case 0x0120/4:
case 0x0124/4:
case 0x0128/4:
case 0x012c/4:
case 0x0130/4:
case 0x0134/4:
case 0x0138/4:
case 0x013c/4:
LOGMASKED(LOG_FTLB, "%s: FlashROM TLB Entry %d = %08x & %08x\n", machine().describe_context(), offset - 0x100/4, m_ftlb_regs.entry[offset - 0x100/4],
mem_mask);
return m_ftlb_regs.entry[offset - 0x100/4];
case 0x0300/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_SN) = %08x & %08x\n", machine().describe_context(), m_ftlb_regs.serial, mem_mask);
return m_ftlb_regs.serial;
default:
LOGMASKED(LOG_FTLB | LOG_UNKNOWN, "%s: Unknown Register %08x & %08x\n", machine().describe_context(), 0x06000000 + (offset << 2), mem_mask);
break;
}
return 0;
}
void pockstat_state::ftlb_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
switch(offset)
{
case 0x0000/4:
LOGMASKED(LOG_FTLB, "%s: FlashROM TLB Control = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_ftlb_regs.control);
break;
case 0x0004/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_STAT) = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_ftlb_regs.stat);
break;
case 0x0008/4:
LOGMASKED(LOG_FTLB, "%s: FlashROM TLB Valid Tag = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_ftlb_regs.valid);
break;
case 0x000c/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_WAIT1) = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_ftlb_regs.wait1);
break;
case 0x0010/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_WAIT2) = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_ftlb_regs.wait2);
break;
case 0x0100/4:
case 0x0104/4:
case 0x0108/4:
case 0x010c/4:
case 0x0110/4:
case 0x0114/4:
case 0x0118/4:
case 0x011c/4:
case 0x0120/4:
case 0x0124/4:
case 0x0128/4:
case 0x012c/4:
case 0x0130/4:
case 0x0134/4:
case 0x0138/4:
case 0x013c/4:
LOGMASKED(LOG_FTLB, "%s: FlashROM TLB Entry %d = %08x & %08x\n", machine().describe_context(), offset - 0x100/4, data, mem_mask);
COMBINE_DATA(&m_ftlb_regs.entry[offset - 0x100/4]);
break;
case 0x0300/4:
LOGMASKED(LOG_FTLB, "%s: Unknown (F_SN) = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_ftlb_regs.serial);
break;
default:
LOGMASKED(LOG_FTLB | LOG_UNKNOWN, "%s: Unknown Register %08x = %08x & %08x\n", machine().describe_context(), 0x06000000 + (offset << 2), data, mem_mask);
break;
}
}
uint32_t pockstat_state::get_interrupt_line(uint32_t line)
{
return m_intc_regs.status & line;
}
void pockstat_state::set_interrupt_line(uint32_t line, int state)
{
if (line)
{
if (state)
{
m_intc_regs.status |= line & INT_STATUS_MASK;
m_intc_regs.hold |= line &~ INT_STATUS_MASK;
LOGMASKED(LOG_IRQS, "Setting IRQ line %08x, status = %08x, hold = %08x\n", line, m_intc_regs.status, m_intc_regs.hold);
}
else
{
m_intc_regs.status &= ~line;
m_intc_regs.hold &= ~line;
LOGMASKED(LOG_IRQS, "Clearing IRQ line %08x, status = %08x, hold = %08x\n", line, m_intc_regs.status, m_intc_regs.hold);
}
}
const uint32_t new_irq = m_intc_regs.hold & m_intc_regs.enable & INT_IRQ_MASK;
if (new_irq)
{
m_maincpu->set_input_line(ARM7_IRQ_LINE, ASSERT_LINE);
}
else
{
m_maincpu->set_input_line(ARM7_IRQ_LINE, CLEAR_LINE);
}
const uint32_t new_fiq = m_intc_regs.hold & m_intc_regs.enable & INT_FIQ_MASK;
if (new_fiq)
{
m_maincpu->set_input_line(ARM7_FIRQ_LINE, ASSERT_LINE);
}
else
{
m_maincpu->set_input_line(ARM7_FIRQ_LINE, CLEAR_LINE);
}
}
uint32_t pockstat_state::intc_r(offs_t offset, uint32_t mem_mask)
{
switch(offset)
{
case 0x0000/4:
LOGMASKED(LOG_INTC, "%s: Held Interrupt Read: %08x & %08x\n", machine().describe_context(), m_intc_regs.hold, mem_mask);
return m_intc_regs.hold;
case 0x0004/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Status Read: %08x & %08x\n", machine().describe_context(), m_intc_regs.status, mem_mask);
return m_intc_regs.status;
case 0x0008/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Enable Read: %08x & %08x\n", machine().describe_context(), m_intc_regs.enable, mem_mask);
return m_intc_regs.enable;
case 0x000c/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Mask Read (Invalid): %08x & %08x\n", machine().describe_context(), 0, mem_mask);
return 0;
case 0x0010/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Acknowledge Read (Invalid): %08x & %08x\n", machine().describe_context(), 0, mem_mask);
return 0;
default:
LOGMASKED(LOG_INTC | LOG_UNKNOWN, "%s: Unknown Register Read: %08x & %08x\n", machine().describe_context(), 0x0a000000 + (offset << 2), mem_mask);
break;
}
return 0;
}
void pockstat_state::intc_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
switch(offset)
{
case 0x0000/4:
LOGMASKED(LOG_INTC, "%s: Held Interrupt (Invalid Write) = %08x & %08x\n", machine().describe_context(), data, mem_mask);
break;
case 0x0004/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Status (Invalid Write) = %08x & %08x\n", machine().describe_context(), data, mem_mask);
break;
case 0x0008/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Enable = %08x & %08x\n", machine().describe_context(), data, mem_mask);
m_intc_regs.enable |= data;
//COMBINE_DATA(&m_intc_regs.enable);
//m_intc_regs.status &= m_intc_regs.enable;
//m_intc_regs.hold &= m_intc_regs.enable;
set_interrupt_line(0, 0);
break;
case 0x000c/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Mask = %08x & %08x\n", machine().describe_context(), data, mem_mask);
m_intc_regs.enable &= ~data;
COMBINE_DATA(&m_intc_regs.mask);
//m_intc_regs.status &= m_intc_regs.enable;
//m_intc_regs.hold &= m_intc_regs.enable;
set_interrupt_line(0, 0);
break;
case 0x0010/4:
LOGMASKED(LOG_INTC, "%s: Interrupt Acknowledge = %08x & %08x\n", machine().describe_context(), data, mem_mask);
m_intc_regs.hold &= ~data;
m_intc_regs.status &= ~data;
set_interrupt_line(0, 0);
//COMBINE_DATA(&m_intc_regs.acknowledge);
break;
default:
LOGMASKED(LOG_INTC | LOG_UNKNOWN, "%s: Unknown Register %08x = %08x & %08x\n", machine().describe_context(), 0x0a000000 + (offset << 2), data, mem_mask);
break;
}
}
TIMER_CALLBACK_MEMBER(pockstat_state::timer_tick)
{
set_interrupt_line(param == 2 ? INT_TIMER2 : (param == 1 ? INT_TIMER1 : INT_TIMER0), 1);
m_timers[param].count = m_timers[param].period;
timer_start(param);
}
void pockstat_state::timer_start(int index)
{
int divisor = 1;
attotime period;
switch (m_timers[index].control & 3)
{
case 0:
case 3:
divisor = 1;
break;
case 1:
divisor = 16;
break;
case 2:
divisor = 256;
break;
}
period = attotime::from_hz(CPU_FREQ[m_clock_regs.mode & 0x0f] / 2) * divisor * m_timers[index].count;
m_timers[index].timer->adjust(period, index);
}
uint32_t pockstat_state::timer_r(offs_t offset, uint32_t mem_mask)
{
switch (offset)
{
case 0x0000/4:
case 0x0010/4:
case 0x0020/4:
{
const uint32_t index = offset / (0x10/4);
LOGMASKED(LOG_TIMER, "%s: Timer %d Period Read: %08x & %08x\n", machine().describe_context(), index, m_timers[index].period, mem_mask);
return m_timers[index].period;
}
case 0x0004/4:
case 0x0014/4:
case 0x0024/4:
{
const uint32_t index = offset / (0x10/4);
LOGMASKED(LOG_TIMER, "%s: Timer %d Count Read: %08x & %08x\n", machine().describe_context(), index, m_timers[index].count, mem_mask);
if(m_timers[index].control & 4)
{
m_timers[index].count--;
if (m_timers[index].count > m_timers[index].period)
{
m_timers[index].count = m_timers[index].period;
}
return --m_timers[index].count;
}
return m_timers[index].count;
}
case 0x0008/4:
case 0x0018/4:
case 0x0028/4:
{
const uint32_t index = offset / (0x10/4);
LOGMASKED(LOG_TIMER, "%s: Timer %d Control = %08x & %08x\n", machine().describe_context(), index, m_timers[index].control, mem_mask);
return m_timers[index].control;
}
default:
LOGMASKED(LOG_TIMER | LOG_UNKNOWN, "%s: Unknown Register %08x & %08x\n", machine().describe_context(), 0x0a800000 + (offset << 2), mem_mask);
break;
}
return 0;
}
void pockstat_state::timer_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
switch (offset)
{
case 0x0000/4:
case 0x0010/4:
case 0x0020/4:
{
const uint32_t index = offset / (0x10/4);
LOGMASKED(LOG_TIMER, "%s: Timer %d Period = %08x & %08x\n", machine().describe_context(), index, data, mem_mask);
COMBINE_DATA(&m_timers[index].period);
break;
}
case 0x0004/4:
case 0x0014/4:
case 0x0024/4:
{
const uint32_t index = offset / (0x10/4);
LOGMASKED(LOG_TIMER, "%s: Timer %d Count = %08x & %08x\n", machine().describe_context(), index, data, mem_mask);
COMBINE_DATA(&m_timers[index].count);
break;
}
case 0x0008/4:
case 0x0018/4:
case 0x0028/4:
{
const uint32_t index = offset / (0x10/4);
LOGMASKED(LOG_TIMER, "%s: Timer %d Control = %08x & %08x\n", machine().describe_context(), index, data, mem_mask);
COMBINE_DATA(&m_timers[index].control);
if(m_timers[index].control & 4)
{
timer_start(index);
}
else
{
m_timers[index].timer->adjust(attotime::never, index);
}
break;
}
default:
LOGMASKED(LOG_TIMER | LOG_UNKNOWN, "%s: Unknown Register %08x = %08x & %08x\n", machine().describe_context(), 0x0a800000 + (offset << 2), data, mem_mask);
break;
}
}
uint32_t pockstat_state::clock_r(offs_t offset, uint32_t mem_mask)
{
switch(offset)
{
case 0x0000/4:
LOGMASKED(LOG_CLOCK, "%s: Clock Mode Read: %08x & %08x\n", machine().describe_context(), m_clock_regs.mode | 0x10, mem_mask);
return m_clock_regs.mode | CLOCK_STEADY;
case 0x0004/4:
LOGMASKED(LOG_CLOCK, "%s: Clock Control Read: %08x & %08x\n", machine().describe_context(), m_clock_regs.control, mem_mask);
return m_clock_regs.control;
default:
LOGMASKED(LOG_CLOCK | LOG_UNKNOWN, "%s: Unknown Register %08x & %08x\n", machine().describe_context(), 0x0b000000 + (offset << 2), mem_mask);
break;
}
return 0;
}
void pockstat_state::clock_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
switch(offset)
{
case 0x0000/4:
LOGMASKED(LOG_CLOCK, "%s: Clock Mode = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_clock_regs.mode);
m_maincpu->set_unscaled_clock(CPU_FREQ[m_clock_regs.mode & 0x0f]);
break;
case 0x0004/4:
LOGMASKED(LOG_CLOCK, "%s: Clock Control = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_clock_regs.control);
break;
default:
LOGMASKED(LOG_CLOCK | LOG_UNKNOWN, "%s: Unknown Register %08x = %08x & %08x\n", machine().describe_context(), 0x0b000000 + (offset << 2), data, mem_mask);
break;
}
}
TIMER_CALLBACK_MEMBER(pockstat_state::rtc_tick)
{
set_interrupt_line(INT_RTC, get_interrupt_line(INT_RTC) ? 0 : 1);
if (!(m_rtc_regs.mode & 1))
{
m_rtc_regs.time++;
if ((m_rtc_regs.time & 0x0000000f) == 0x0000000a)
{
m_rtc_regs.time &= 0xfffffff0;
m_rtc_regs.time += 0x00000010;
if ((m_rtc_regs.time & 0x000000ff) == 0x00000060)
{
m_rtc_regs.time &= 0xffffff00;
m_rtc_regs.time += 0x00000100;
if ((m_rtc_regs.time & 0x00000f00) == 0x00000a00)
{
m_rtc_regs.time &= 0xfffff0ff;
m_rtc_regs.time += 0x00001000;
if ((m_rtc_regs.time & 0x0000ff00) == 0x00006000)
{
m_rtc_regs.time &= 0xffff00ff;
m_rtc_regs.time += 0x00010000;
if ((m_rtc_regs.time & 0x00ff0000) == 0x00240000)
{
m_rtc_regs.time &= 0xff00ffff;
m_rtc_regs.time += 0x01000000;
if ((m_rtc_regs.time & 0x0f000000) == 0x08000000)
{
m_rtc_regs.time &= 0xf0ffffff;
m_rtc_regs.time |= 0x01000000;
}
}
else if ((m_rtc_regs.time & 0x000f0000) == 0x000a0000)
{
m_rtc_regs.time &= 0xfff0ffff;
m_rtc_regs.time += 0x00100000;
}
}
}
}
}
}
m_rtc_regs.timer->adjust(attotime::from_hz(1));
}
uint32_t pockstat_state::rtc_r(offs_t offset, uint32_t mem_mask)
{
switch(offset)
{
case 0x0000/4:
LOGMASKED(LOG_RTC, "%s: RTC Mode Read: %08x & %08x\n", machine().describe_context(), m_rtc_regs.mode, mem_mask);
return m_rtc_regs.mode;
case 0x0004/4:
LOGMASKED(LOG_RTC, "%s: RTC Control Read: %08x & %08x\n", machine().describe_context(), m_rtc_regs.control, mem_mask);
return m_rtc_regs.control;
case 0x0008/4:
LOGMASKED(LOG_RTC, "%s: RTC Time Read: %08x & %08x\n", machine().describe_context(), m_rtc_regs.time, mem_mask);
return m_rtc_regs.time;
case 0x000c/4:
LOGMASKED(LOG_RTC, "%s: RTC Date Read: %08x & %08x\n", machine().describe_context(), m_rtc_regs.date, mem_mask);
return m_rtc_regs.date;
default:
LOGMASKED(LOG_RTC | LOG_UNKNOWN, "%s: Unknown Register %08x & %08x\n", machine().describe_context(), 0x0b800000 + (offset << 2), mem_mask);
break;
}
return 0;
}
void pockstat_state::rtc_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
switch (offset)
{
case 0x0000/4:
LOGMASKED(LOG_RTC, "%s: RTC Mode = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_rtc_regs.mode);
break;
case 0x0004/4:
LOGMASKED(LOG_RTC, "%s: RTC Control = %08x & %08x\n", machine().describe_context(), data, mem_mask);
if (m_rtc_regs.control == 1 && data == 1)
{
switch (m_rtc_regs.mode >> 1)
{
case 0: // Seconds
m_rtc_regs.time += 0x00000001;
if ((m_rtc_regs.time & 0x0000000f) == 0x0000000a)
{
m_rtc_regs.time &= 0xfffffff0;
m_rtc_regs.time += 0x00000010;
if ((m_rtc_regs.time & 0x000000ff) == 0x00000060)
{
m_rtc_regs.time &= 0xffffff00;
}
}
break;
case 1: // Minutes
m_rtc_regs.time += 0x00000100;
if ((m_rtc_regs.time & 0x00000f00) == 0x00000a00)
{
m_rtc_regs.time &= 0xfffff0ff;
m_rtc_regs.time += 0x00001000;
if ((m_rtc_regs.time & 0x0000ff00) == 0x00006000)
{
m_rtc_regs.time &= 0xffff00ff;
}
}
break;
case 2: // Hours
m_rtc_regs.time += 0x00010000;
if ((m_rtc_regs.time & 0x00ff0000) == 0x00240000)
{
m_rtc_regs.time &= 0xff00ffff;
}
else if ((m_rtc_regs.time & 0x000f0000) == 0x000a0000)
{
m_rtc_regs.time &= 0xfff0ffff;
m_rtc_regs.time += 0x00100000;
}
break;
case 3: // Day of the week
m_rtc_regs.time += 0x01000000;
if ((m_rtc_regs.time & 0x0f000000) == 0x08000000)
{
m_rtc_regs.time &= 0xf0ffffff;
m_rtc_regs.time |= 0x01000000;
}
break;
case 4: // Day
m_rtc_regs.date += 0x00000001;
if ((m_rtc_regs.date & 0x000000ff) == 0x00000032)
{
m_rtc_regs.date &= 0xffffff00;
}
else if ((m_rtc_regs.date & 0x0000000f) == 0x0000000a)
{
m_rtc_regs.date &= 0xfffffff0;
m_rtc_regs.date += 0x00000010;
}
break;
case 5: // Month
m_rtc_regs.date += 0x00000100;
if ((m_rtc_regs.date & 0x0000ff00) == 0x00001300)
{
m_rtc_regs.date &= 0xffffff00;
m_rtc_regs.date |= 0x00000001;
}
else if ((m_rtc_regs.date & 0x00000f00) == 0x00000a00)
{
m_rtc_regs.date &= 0xfffff0ff;
m_rtc_regs.date += 0x00001000;
}
break;
case 6: // Year (LSB)
m_rtc_regs.date += 0x00010000;
if ((m_rtc_regs.date & 0x000f0000) == 0x000a0000)
{
m_rtc_regs.date &= 0xfff0ffff;
m_rtc_regs.date += 0x00100000;
if ((m_rtc_regs.date & 0x00f00000) == 0x00a00000)
{
m_rtc_regs.date &= 0xff00ffff;
}
}
break;
case 7: // Year (MSB)
break;
}
m_rtc_regs.control = 0;
}
else if(m_rtc_regs.control == 0)
{
COMBINE_DATA(&m_rtc_regs.control);
}
break;
default:
LOGMASKED(LOG_RTC | LOG_UNKNOWN, "%s: Unknown Register %08x = %08x & %08x\n", machine().describe_context(), 0x0b800000 + (offset << 2), data, mem_mask);
break;
}
}
uint32_t pockstat_state::lcd_r(offs_t offset, uint32_t mem_mask)
{
switch (offset)
{
case 0x0000/4:
LOGMASKED(LOG_LCD, "%s: LCD Control Read: %08x & %08x\n", machine().describe_context(), m_lcd_control | 0x100, mem_mask);
return m_lcd_control;
default:
LOGMASKED(LOG_LCD | LOG_UNKNOWN, "%s: Unknown Register %08x & %08x\n", machine().describe_context(), 0x0d000000 + (offset << 2), mem_mask);
break;
}
return 0;
}
void pockstat_state::lcd_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
switch (offset)
{
case 0x0000/4:
LOGMASKED(LOG_LCD, "%s: LCD Control = %08x & %08x\n", machine().describe_context(), data, mem_mask);
COMBINE_DATA(&m_lcd_control);
break;
default:
LOGMASKED(LOG_LCD | LOG_UNKNOWN, "%s: Unknown Register %08x = %08x & %08x\n", machine().describe_context(), 0x0d000000 + (offset << 2), data, mem_mask);
break;
}
}
INPUT_CHANGED_MEMBER(pockstat_state::input_update)
{
uint32_t buttons = ioport("BUTTONS")->read();
set_interrupt_line(INT_BTN_ACTION, (buttons & 1) ? 1 : 0);
set_interrupt_line(INT_BTN_RIGHT, (buttons & 2) ? 1 : 0);
set_interrupt_line(INT_BTN_LEFT, (buttons & 4) ? 1 : 0);
set_interrupt_line(INT_BTN_DOWN, (buttons & 8) ? 1 : 0);
set_interrupt_line(INT_BTN_UP, (buttons & 16) ? 1 : 0);
}
uint32_t pockstat_state::rombank_r(offs_t offset, uint32_t mem_mask)
{
int32_t bank = (offset >> 11) & 0x0f;
for (int index = 0; index < 32; index++)
{
if (m_ftlb_regs.valid & (1 << index))
{
if (m_ftlb_regs.entry[index] == bank)
{
return m_cart->read32_rom(index * (0x2000/4) + (offset & (0x1fff/4)), mem_mask);
}
}
}
return m_cart->read32_rom(offset & 0x7fff, mem_mask);
}
// Horrible hack, probably wrong
void pockstat_state::flash_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
if (offset == (0x55a8/4))
{
m_flash_write_enable_count++;
return;
}
if (offset == (0x2a54/4))
{
m_flash_write_enable_count++;
return;
}
if (m_flash_write_enable_count == 3)
{
m_flash_write_enable_count = 0;
m_flash_write_count = 0x40;
return;
}
if (m_flash_write_count)
{
m_flash_write_count--;
COMBINE_DATA(&((uint32_t*)(m_cart_rom->base()))[offset]);
}
}
uint32_t pockstat_state::flash_r(offs_t offset, uint32_t mem_mask)
{
return m_cart->read32_rom(offset, mem_mask);
}
uint32_t pockstat_state::audio_r(offs_t offset, uint32_t mem_mask)
{
LOGMASKED(LOG_AUDIO | LOG_UNKNOWN, "%s: Unknown Audio Read: %08x = %08x & %08x\n", machine().describe_context(), 0xd800000 + (offset << 2), 0x10, mem_mask);
return 0;
}
void pockstat_state::audio_w(offs_t offset, uint32_t data, uint32_t mem_mask)
{
LOGMASKED(LOG_AUDIO | LOG_UNKNOWN, "%s: Unknown Audio Write: %08x = %08x & %08x\n", machine().describe_context(), 0xd800000 + (offset << 2), data, mem_mask);
}
void pockstat_state::mem_map(address_map &map)
{
map(0x00000000, 0x000007ff).ram();
map(0x02000000, 0x02ffffff).r(FUNC(pockstat_state::rombank_r));
map(0x04000000, 0x04003fff).rom().region("maincpu", 0);
map(0x06000000, 0x06000307).rw(FUNC(pockstat_state::ftlb_r), FUNC(pockstat_state::ftlb_w));
map(0x08000000, 0x0801ffff).rw(FUNC(pockstat_state::flash_r), FUNC(pockstat_state::flash_w));
map(0x0a000000, 0x0a000013).rw(FUNC(pockstat_state::intc_r), FUNC(pockstat_state::intc_w));
map(0x0a800000, 0x0a80002b).rw(FUNC(pockstat_state::timer_r), FUNC(pockstat_state::timer_w));
map(0x0b000000, 0x0b000007).rw(FUNC(pockstat_state::clock_r), FUNC(pockstat_state::clock_w));
map(0x0b800000, 0x0b80000f).rw(FUNC(pockstat_state::rtc_r), FUNC(pockstat_state::rtc_w));
map(0x0d000000, 0x0d000003).rw(FUNC(pockstat_state::lcd_r), FUNC(pockstat_state::lcd_w));
map(0x0d000100, 0x0d00017f).ram().share("lcd_buffer");
map(0x0d80000c, 0x0d80000f).rw(FUNC(pockstat_state::audio_r), FUNC(pockstat_state::audio_w));
map(0x0d800014, 0x0d800015).w("dac", FUNC(dac_word_interface::data_w));
}
/* Input ports */
static INPUT_PORTS_START( pockstat )
PORT_START("BUTTONS")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_BUTTON1) PORT_NAME("Action Button") PORT_CHANGED_MEMBER(DEVICE_SELF, pockstat_state, input_update, 0)
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT) PORT_NAME("Right") PORT_CHANGED_MEMBER(DEVICE_SELF, pockstat_state, input_update, 0)
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT) PORT_NAME("Left") PORT_CHANGED_MEMBER(DEVICE_SELF, pockstat_state, input_update, 0)
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN) PORT_NAME("Down") PORT_CHANGED_MEMBER(DEVICE_SELF, pockstat_state, input_update, 0)
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP) PORT_NAME("Up") PORT_CHANGED_MEMBER(DEVICE_SELF, pockstat_state, input_update, 0)
PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED)
INPUT_PORTS_END
void pockstat_state::machine_start()
{
for (uint32_t index = 0; index < TIMER_COUNT; index++)
{
m_timers[index].timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(pockstat_state::timer_tick), this));
m_timers[index].timer->adjust(attotime::never, index);
m_timers[index].count = 0;
}
m_rtc_regs.time = 0x01000000;
m_rtc_regs.date = 0x19990101;
m_rtc_regs.timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(pockstat_state::rtc_tick),this));
m_rtc_regs.timer->adjust(attotime::from_hz(1), TIMER_COUNT);
std::string region_tag;
m_cart_rom = memregion(region_tag.assign(m_cart->tag()).append(GENERIC_ROM_REGION_TAG).c_str());
save_item(NAME(m_ftlb_regs.control));
save_item(NAME(m_ftlb_regs.stat));
save_item(NAME(m_ftlb_regs.valid));
save_item(NAME(m_ftlb_regs.wait1));
save_item(NAME(m_ftlb_regs.wait2));
save_item(NAME(m_ftlb_regs.entry));
save_item(NAME(m_intc_regs.hold));
save_item(NAME(m_intc_regs.status));
save_item(NAME(m_intc_regs.enable));
save_item(NAME(m_intc_regs.mask));
save_item(NAME(m_timers[0].period));
save_item(NAME(m_timers[0].count));
save_item(NAME(m_timers[0].control));
save_item(NAME(m_timers[1].period));
save_item(NAME(m_timers[1].count));
save_item(NAME(m_timers[1].control));
save_item(NAME(m_timers[2].period));
save_item(NAME(m_timers[2].count));
save_item(NAME(m_timers[2].control));
save_item(NAME(m_clock_regs.mode));
save_item(NAME(m_clock_regs.control));
save_item(NAME(m_rtc_regs.mode));
save_item(NAME(m_rtc_regs.control));
save_item(NAME(m_rtc_regs.time));
save_item(NAME(m_rtc_regs.date));
save_item(NAME(m_flash_write_enable_count));
save_item(NAME(m_flash_write_count));
save_item(NAME(m_lcd_control));
}
void pockstat_state::machine_reset()
{
m_maincpu->set_state_int(ARM7_R15, 0x4000000);
m_flash_write_enable_count = 0;
m_flash_write_count = 0;
}
uint32_t pockstat_state::screen_update_pockstat(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
for (int y = 0; y < 32; y++)
{
uint32_t *const scanline = &bitmap.pix(y);
for (int x = 0; x < 32; x++)
{
if (m_lcd_control != 0) // Hack
{
if (BIT(m_lcd_buffer[y], x))
scanline[x] = 0x00000000;
else
scanline[x] = 0x00ffffff;
}
else
scanline[x] = 0x00ffffff;
}
}
return 0;
}
DEVICE_IMAGE_LOAD_MEMBER(pockstat_state::flash_load)
{
static const char *gme_id = "123-456-STD";
char cart_id[0xf40];
uint32_t size = image.length();
if (size != 0x20f40)
return image_init_result::FAIL;
image.fread(cart_id, 0xf40);
for (int i = 0; i < strlen(gme_id); i++)
{
if (cart_id[i] != gme_id[i])
return image_init_result::FAIL;
}
m_cart->rom_alloc(0x20000, GENERIC_ROM32_WIDTH, ENDIANNESS_LITTLE);
image.fread(m_cart->get_rom_base(), 0x20000);
return image_init_result::PASS;
}
void pockstat_state::pockstat(machine_config &config)
{
static constexpr uint32_t DEFAULT_CLOCK = 2000000;
/* basic machine hardware */
ARM7(config, m_maincpu, DEFAULT_CLOCK);
m_maincpu->set_addrmap(AS_PROGRAM, &pockstat_state::mem_map);
/* video hardware */
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_LCD));
screen.set_refresh_hz(50);
screen.set_vblank_time(ATTOSECONDS_IN_USEC(2500)); /* not accurate */
screen.set_size(32, 32);
screen.set_visarea(0, 32-1, 0, 32-1);
screen.set_screen_update(FUNC(pockstat_state::screen_update_pockstat));
PALETTE(config, "palette", palette_device::MONOCHROME);
SPEAKER(config, "speaker").front_center();
DAC_16BIT_R2R_TWOS_COMPLEMENT(config, "dac", 0).add_route(ALL_OUTPUTS, "speaker", 0.5); // unknown DAC
/* cartridge */
GENERIC_CARTSLOT(config, m_cart, generic_plain_slot, "pockstat_cart", "gme");
m_cart->set_width(GENERIC_ROM32_WIDTH);
m_cart->set_endian(ENDIANNESS_LITTLE);
m_cart->set_device_load(FUNC(pockstat_state::flash_load));
}
/* ROM definition */
ROM_START( pockstat )
ROM_REGION( 0x4000, "maincpu", 0 )
ROM_LOAD( "kernel.bin", 0x0000, 0x4000, CRC(5fb47dd8) SHA1(6ae880493ddde880827d1e9f08e9cb2c38f9f2ec) )
ROM_END
} // Anonymous namespace
/* Driver */
// YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS
CONS( 1999, pockstat, 0, 0, pockstat, pockstat, pockstat_state, empty_init, "Sony Computer Entertainment Inc", "Sony PocketStation", MACHINE_SUPPORTS_SAVE )
|
reels-research/iOS-Private-Frameworks | SafariShared.framework/WBSHistoryConnectionProxy.h | <reponame>reels-research/iOS-Private-Frameworks<filename>SafariShared.framework/WBSHistoryConnectionProxy.h
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/SafariShared.framework/SafariShared
*/
@interface WBSHistoryConnectionProxy : NSObject <WBSHistoryConnectionProxy> {
NSXPCConnection * _connection;
NSObject<OS_dispatch_queue> * _connectionProxyQueue;
}
@property (nonatomic, readonly) NSObject<OS_dispatch_queue> *connectionProxyQueue;
- (void).cxx_destruct;
- (id /* block */)_defaultProxyErrorHandlerWithSimpleReplyCompletionHandler:(id /* block */)arg1;
- (void)beginHistoryAccessSession:(id /* block */)arg1;
- (void)beginURLCompletionSession:(id /* block */)arg1;
- (id)connectionProxyQueue;
- (void)dealloc;
- (void)debugGetDatabaseURLWithCompletionHandler:(id /* block */)arg1;
- (void)ensureConnected:(id /* block */)arg1;
- (void)getServiceInfo:(id /* block */)arg1;
- (void)getVisitedLinksWithCompletionHandler:(id /* block */)arg1;
- (void)groupVisitsIntoSessionsBetweenStartDate:(id)arg1 endDate:(id)arg2 completionHandler:(id /* block */)arg3;
- (id)init;
- (void)killService;
- (void)queryMemoryFootprint:(id /* block */)arg1;
- (id)queryMemoryFootprintWithError:(id*)arg1;
@end
|
Farfetch/maestro | web/frontend/src/lib/charts/datasets/metricsToResponseCodeLine.js | <gh_stars>10-100
import { colors, getNextColor } from "../../colors";
import { toLocalDate } from "../../date";
const colorsAlias = {
200: colors.green,
204: colors.lime,
201: colors.lime,
400: colors.orange,
404: colors.orange,
500: colors.red,
501: colors.red,
502: colors.red,
503: colors.red,
0: colors.red
};
const colorsList = [
colors.cyan,
colors.blue,
colors.geekblue,
colors.purple,
colors.magenta
];
const metricsToResponseCodeLinesDataset = (metrics) => {
let minDatetime = metrics[0] ? toLocalDate(metrics[0].minDatetime) : null;
let maxDatetime = null;
const responseCodes = new Set(
metrics.reduce((previous, current) => {
const newResponseCodes = current.responses.map(
({ responseCode }) => responseCode
);
return [...previous, ...newResponseCodes];
}, [])
);
const getDataByResponseCode = (responseCode) =>
metrics.map((metric) => {
const metricMinDatetime = toLocalDate(metric.minDatetime);
const metricMaxDatetime = toLocalDate(metric.maxDatetime);
const responseCodeMetrics = metric.responses.find(
(el) => el.responseCode === responseCode
);
if (metricMinDatetime < minDatetime) minDatetime = metricMinDatetime;
if (metricMaxDatetime > maxDatetime) maxDatetime = metricMaxDatetime;
return {
responseCode,
y: responseCodeMetrics ? responseCodeMetrics.totalCount : 0,
x: metricMinDatetime,
messages: responseCodeMetrics ? responseCodeMetrics.messages : [],
totalCount: responseCodeMetrics ? responseCodeMetrics.totalCount : 0,
successCount: responseCodeMetrics ? responseCodeMetrics.successCount : 0
};
});
let currentColorIndex = 0;
const getColor = (responseCode) => {
const { colorIndex, color } = getNextColor(currentColorIndex, colorsList);
if (!colorsAlias[responseCode]) currentColorIndex = colorIndex;
return colorsAlias[responseCode] ? colorsAlias[responseCode] : color;
};
const sortedResponeCodes = Array.from(responseCodes).sort((a, b) => a - b);
const datasets = sortedResponeCodes.map((responseCode) => {
const color = getColor(responseCode);
return {
label: responseCode,
data: getDataByResponseCode(responseCode),
fill: false,
backgroundColor: color[2],
borderColor: color[4],
tension: 0.2
};
});
return {
datasets,
minDatetime,
maxDatetime
};
};
export default metricsToResponseCodeLinesDataset;
|
katastreet/ice4jtest | src/main/java/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java | /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.ice4j.socket;
import java.io.*;
import java.net.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.message.*;
/**
* Represents an application-purposed (as opposed to an ICE-specific)
* <tt>DatagramSocket</tt> for a <tt>RelayedCandidate</tt> harvested by a
* <tt>TurnCandidateHarvest</tt> (and its associated
* <tt>TurnCandidateHarvester</tt>, of course).
* <tt>GoogleRelayedCandidateDatagramSocket</tt> is associated with a successful
* Allocation on a TURN server and implements sends and receives through it
* using TURN messages to and from that TURN server.
*
* @author <NAME>
* @author <NAME>
*/
public class GoogleRelayedCandidateDatagramSocket
extends DatagramSocket
{
/**
* The <tt>Logger</tt> used by the
* <tt>GoogleRelayedCandidateDatagramSocket</tt> class and its instances for
* logging output.
*/
private static final Logger logger
= Logger.getLogger(
GoogleRelayedCandidateDatagramSocket.class.getName());
/**
* The indicator which determines whether this instance has started
* executing or has executed its {@link #close()} method.
*/
private boolean closed = false;
/**
* The <tt>GoogleRelayedCandidate</tt> which uses this instance as the value
* of its <tt>socket</tt> property.
*/
private final GoogleRelayedCandidate relayedCandidate;
/**
* The <tt>GoogleTurnCandidateHarvest</tt> which has harvested
* {@link #relayedCandidate}.
*/
private final GoogleTurnCandidateHarvest turnCandidateHarvest;
/**
* The <tt>GoogleTurnCandidateDelegage</tt> which will handle send/receive
* operations.
*/
private final GoogleRelayedCandidateDelegate socketDelegate;
/**
* Initializes a new <tt>GoogleRelayedCandidateDatagramSocket</tt> instance
* which is to be the <tt>socket</tt> of a specific
* <tt>RelayedCandidate</tt> harvested by a specific
* <tt>TurnCandidateHarvest</tt>.
*
* @param relayedCandidate the <tt>RelayedCandidate</tt> which is to use the
* new instance as the value of its <tt>socket</tt> property
* @param turnCandidateHarvest the <tt>TurnCandidateHarvest</tt> which has
* harvested <tt>relayedCandidate</tt>
* @param username username
* @throws SocketException if anything goes wrong while initializing the new
* <tt>GoogleRelayedCandidateDatagramSocket</tt> instance
*/
public GoogleRelayedCandidateDatagramSocket(
GoogleRelayedCandidate relayedCandidate,
GoogleTurnCandidateHarvest turnCandidateHarvest,
String username)
throws SocketException
{
super(/* bindaddr */ (SocketAddress) null);
socketDelegate = new GoogleRelayedCandidateDelegate(
turnCandidateHarvest, username);
this.relayedCandidate = relayedCandidate;
this.turnCandidateHarvest = turnCandidateHarvest;
logger.finest("Create new GoogleRelayedCandidateDatagramSocket");
}
/**
* Closes this datagram socket.
*
* @see DatagramSocket#close()
*/
@Override
public void close()
{
synchronized (this)
{
if (this.closed)
return;
else
this.closed = true;
}
socketDelegate.close();
turnCandidateHarvest.close(this);
}
/**
* Gets the local address to which the socket is bound.
* <tt>GoogleRelayedCandidateDatagramSocket</tt> returns the
* <tt>address</tt> of its <tt>localSocketAddress</tt>.
* <p>
* If there is a security manager, its <tt>checkConnect</tt> method is first
* called with the host address and <tt>-1</tt> as its arguments to see if
* the operation is allowed.
* </p>
*
* @return the local address to which the socket is bound, or an
* <tt>InetAddress</tt> representing any local address if either the socket
* is not bound, or the security manager <tt>checkConnect</tt> method does
* not allow the operation
* @see #getLocalSocketAddress()
* @see DatagramSocket#getLocalAddress()
*/
@Override
public InetAddress getLocalAddress()
{
return getLocalSocketAddress().getAddress();
}
/**
* Returns the port number on the local host to which this socket is bound.
* <tt>GoogleRelayedCandidateDatagramSocket</tt> returns the <tt>port</tt>
* of its <tt>localSocketAddress</tt>.
*
* @return the port number on the local host to which this socket is bound
* @see #getLocalSocketAddress()
* @see DatagramSocket#getLocalPort()
*/
@Override
public int getLocalPort()
{
return getLocalSocketAddress().getPort();
}
/**
* Returns the address of the endpoint this socket is bound to, or
* <tt>null</tt> if it is not bound yet. Since
* <tt>GoogleRelayedCandidateDatagramSocket</tt> represents an
* application-purposed <tt>DatagramSocket</tt> relaying data to and from a
* TURN server, the <tt>localSocketAddress</tt> is the
* <tt>transportAddress</tt> of the respective <tt>RelayedCandidate</tt>.
*
* @return a <tt>SocketAddress</tt> representing the local endpoint of this
* socket, or <tt>null</tt> if it is not bound yet
* @see DatagramSocket#getLocalSocketAddress()
*/
@Override
public InetSocketAddress getLocalSocketAddress()
{
return getRelayedCandidate().getTransportAddress();
}
/**
* Gets the <tt>RelayedCandidate</tt> which uses this instance as the value
* of its <tt>socket</tt> property.
*
* @return the <tt>RelayedCandidate</tt> which uses this instance as the
* value of its <tt>socket</tt> property
*/
public final GoogleRelayedCandidate getRelayedCandidate()
{
return relayedCandidate;
}
/**
* Notifies this <tt>GoogleRelayedCandidateDatagramSocket</tt> that a
* specific <tt>Request</tt> it has sent has received a STUN success
* <tt>Response</tt>.
*
* @param response the <tt>Response</tt> which responds to <tt>request</tt>
* @param request the <tt>Request</tt> sent by this instance to which
* <tt>response</tt> responds
*/
public void processSuccess(Response response, Request request)
{
socketDelegate.processSuccess(response, request);
}
/**
* Dispatch the specified response.
*
* @param response the response to dispatch.
*/
public void processResponse(StunResponseEvent response)
{
socketDelegate.processResponse(response);
}
/**
* Receives a datagram packet from this socket. When this method returns,
* the <tt>DatagramPacket</tt>'s buffer is filled with the data received.
* The datagram packet also contains the sender's IP address, and the port
* number on the sender's machine.
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
* @see DatagramSocket#receive(DatagramPacket)
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
socketDelegate.receive(p);
}
/**
* Sends a datagram packet from this socket. The <tt>DatagramPacket</tt>
* includes information indicating the data to be sent, its length, the IP
* address of the remote host, and the port number on the remote host.
*
* @param p the <tt>DatagramPacket</tt> to be sent
* @throws IOException if an I/O error occurs
* @see DatagramSocket#send(DatagramPacket)
*/
@Override
public void send(DatagramPacket p)
throws IOException
{
socketDelegate.send(p);
}
}
|
fzdabc/SlideWiki | slidewiki/libraries/frontend/MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/Latin1Supplement.js | /*
* /MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/Latin1Supplement.js
*
* Copyright (c) 2010 Design Science, Inc.
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({MathJax_AMS:{160:[[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0],[1,1,0]],165:[[6,5,0],[7,6,0],[8,7,0],[9,8,0],[11,9,0],[13,11,0],[15,13,0],[18,16,0],[21,19,0],[25,22,0],[29,27,0],[35,32,0],[41,38,0],[49,45,0]],174:[[7,6,1],[8,8,2],[9,9,2],[11,10,2],[13,12,2],[16,15,3],[18,17,3],[22,20,4],[26,24,5],[31,29,6],[36,34,7],[43,41,8],[51,49,10],[61,59,12]],240:[[4,5,0],[5,6,0],[5,8,0],[6,9,0],[8,11,0],[9,13,0],[10,15,0],[12,18,0],[15,22,2],[17,25,1],[20,30,1],[24,36,1],[29,43,1],[34,51,1]]}});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/AMS/Regular"+MathJax.OutputJax["HTML-CSS"].imgPacked+"/Latin1Supplement.js");
|
Thomas-Ulrich/core | apf/apfElementOf.h | <gh_stars>100-1000
/*
* Copyright 2011 Scientific Computation Research Center
*
* This work is open source software, licensed under the terms of the
* BSD license as described in the LICENSE file in the top-level directory.
*/
#ifndef APFELEMENTOF_H
#define APFELEMENTOF_H
#include "apfElement.h"
#include "apfFieldOf.h"
#include "apfShape.h"
namespace apf {
template <class T, class S = T>
class ElementOf : public Element
{
public:
ElementOf(FieldOf<S>* f, MeshEntity* e):
Element(f,e)
{
}
ElementOf(FieldOf<S>* f, VectorElement* p):
Element(f,p)
{
}
virtual ~ElementOf() {}
S* getNodeValues()
{
return reinterpret_cast<S*>(&(this->nodeData[0]));
}
T getValue(Vector3 const& local)
{
T value[1];
getComponents(local, reinterpret_cast<double*>(value));
return value[0];
}
void getValues(NewArray<S>& values)
{
values.allocate(nen);
S* nodeValues = getNodeValues();
for (int i=0; i < nen; ++i)
values[i] = nodeValues[i];
}
};
}//namespace apf
#endif
|
tkrajcar/pennjson | src/json/json-private.h | #ifndef JSON_PRIVATE_H
#define JSON_PRIVATE_H
#include <yajl/yajl_gen.h>
#include <yajl/yajl_parse.h>
/* Internal declarations for the JSON server */
/* I/O buffer size. */
#define JSON_SERVER_BUFFER_SIZE 32768
/*
* Maximum parse parts. This value is sufficient to handle messages with up to
* 3 parts. Any useful value can be parsed with only this many parts.
*/
#define JSON_SERVER_MAX_PARSE_PARTS 3
/* Error code for method not found. */
#define JSON_SERVER_ERROR_METHOD -32601
/* Error code for invalid method parameters. */
#define JSON_SERVER_ERROR_PARAMS -32602
/* Error code for (non-fatal) internal error. */
#define JSON_SERVER_ERROR_INTERNAL -32603
/*
* Context parameter callback. Currently defined statically, but we may want to
* allow different implementations, or explicit context parameters at a future
* date. But not needed for now.
*
* No assumptions should be made about the lifetime of the parameters. An
* explicit copy should be made if the parameters need to be retained. The
* strings are not necessarily null-terminated.
*
* The value may be NULL, to indicate a special value. If the value length is
* -1, the parameter should be removed. If the value length is -2, the value
* type is not supported.
*
* The return value should normally be non-zero to indicate that the parameter
* was handled successfully. Zero should be returned if an internal error
* prevents the parameter from being handled.
*/
extern int json_server_context_callback(const char *key, int klen,
const char *value, int vlen);
/*
* Protocol state.
*/
typedef enum JSON_Server_State_tag {
/* Send states. */
JSON_SERVER_STATE_READY, /* ready to send */
JSON_SERVER_STATE_REQ, /* started request */
JSON_SERVER_STATE_REQ_ARGS, /* started request parameters */
JSON_SERVER_STATE_REQ_CTX, /* started request context */
/* Receive states. */
JSON_SERVER_STATE_WAITING, /* waiting to receive */
JSON_SERVER_STATE_COMPOSITE, /* parsing composite value */
JSON_SERVER_STATE_MESSAGE, /* parsing message object */
JSON_SERVER_STATE_PARAMS, /* parsing method parameters array */
JSON_SERVER_STATE_CONTEXT, /* parsing context object */
JSON_SERVER_STATE_ERROR /* parsing error object */
} JSON_Server_State;
/*
* Received message type.
*/
typedef enum JSON_Server_Message_Type_tag {
JSON_SERVER_MSG_NONE, /* unknown */
JSON_SERVER_MSG_REQUEST, /* request */
JSON_SERVER_MSG_RESULT, /* successful response */
JSON_SERVER_MSG_ERROR /* error response */
} JSON_Server_Message_Type;
/*
* Received message. This structure is meant to be preallocated by the caller,
* then filled in with the results of an incoming message.
*
* TODO: Consider making this data structure opaque. On the other hand, the
* PennJSON code is the only code that is ever going to see it.
*/
typedef struct JSON_Server_Message_tag {
JSON_Server_Message_Type type; /* message type */
/* Method descriptor/result/error message. */
char *message;
/* Additional request information. */
int param_nargs; /* number of parameters */
char **param_args; /* parameter strings; may contain embedded nulls */
int *param_arglens; /* parameter string lengths */
/* Additional error information. */
long int error_code; /* error code */
long int local_error; /* local error code; check if non-zero */
/* Internal bookkeeping information. */
void *internal;
size_t int_off;
} JSON_Server_Message;
/*
* Type for holding information about a JSON server instance. For the first
* connection attempt, fd should be set to -1. Subsequent requests should use
* the same JSON_Server object, until a disconnect. Check for failure by
* whether or not fd is still -1 after return.
*/
typedef struct JSON_Server_tag {
/* I/O state. */
int fd; /* file descriptor; initialize to -1 for first connect */
JSON_Server_State state; /* protocol state */
unsigned int in_off; /* offset to data in temporary read buffer */
unsigned int in_len; /* length of data in temporary read buffer */
unsigned char in_buf[JSON_SERVER_BUFFER_SIZE]; /* temporary read buffer */
yajl_gen encoder; /* JSON encoder */
yajl_handle decoder; /* JSON decoder */
/* Lexer state. */
unsigned int lex_off; /* lexer offset */
int lex_ctx; /* context character */
int lex_depth; /* brace depth */
/* Parser state. */
JSON_Server_Message *msg; /* current message */
int parts_seen[JSON_SERVER_MAX_PARSE_PARTS]; /* parts seen */
int key_idx; /* current key token index */
int key_len; /* temporary context key length */
char key_buf[JSON_SERVER_BUFFER_SIZE]; /* temporary context key buffer */
JSON_Server_State saved_state; /* saved state when parsing composite */
int nesting_depth; /* nesting depth when parsing composite; starts at 0 */
/* Internal bookkeeping information. */
void *internal;
} JSON_Server;
/* Simple logging facility. Use 0 or errno-style for code parameter. */
extern void json_server_log(JSON_Server *server, const char *message, int code);
/* Lazily starts a JSON server instance. */
extern void json_server_start(JSON_Server *server);
/* Stops a JSON server instance. */
extern void json_server_stop(JSON_Server *server);
/* Allocate JSON encoder/decoder. */
extern int json_server_json_alloc(JSON_Server *server);
/* Deallocate JSON encoder/decoder. */
extern void json_server_json_free(JSON_Server *server);
/* Starts a request message. */
extern int json_server_start_request(JSON_Server *server,
const char *method, int len);
/* Add parameter. Must come after json_server_start_request. */
extern int json_server_add_param(JSON_Server *server,
const char *value, int len);
/* Add context value. Must come after any parameters. */
extern int json_server_add_context(JSON_Server *server,
const char *key, int klen,
const char *value, int vlen);
/* Sends a request message started by json_server_start_request(). */
extern int json_server_send_request(JSON_Server *server);
/* Sends a result message. */
extern int json_server_send_result(JSON_Server *server,
const char *result, int len);
/* Sends an error message. */
extern int json_server_send_error(JSON_Server *server, long int code,
const char *error, int len);
/* Initializes a received message for first use. */
extern void json_server_message_init(JSON_Server_Message *msg);
/*
* Clears a received message, releasing any allocated memory.
*
* Note that this does not actually overwrite any memory. If for some terrible
* reason you're actually passing secure data over the RPC mechanism, you
* should make sure to explicitly zero out any sensitive data to minimize the
* chance of compromise. (There are still a lot of potential attack vectors,
* but it's better than nothing.)
*/
extern void json_server_message_clear(JSON_Server_Message *msg);
/* Receives a message. */
extern int json_server_receive(JSON_Server *server, JSON_Server_Message *msg);
#endif /* undef JSON_PRIVATE_H */
|
lipovsek/oslo | oslo/torch/nn/modules/dropout.py | <reponame>lipovsek/oslo
import torch
from torch.nn.modules.dropout import _DropoutNd
from oslo.torch.nn.modules.functional import (
fused_bias_dropout,
fused_bias_dropout_residual,
)
class FusedBiasDropout(_DropoutNd):
def forward(self, input: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
return fused_bias_dropout(input, bias, self.p, self.training, self.inplace)
class FusedBiasDropoutResidual(_DropoutNd):
def forward(
self, input: torch.Tensor, bias: torch.Tensor, residual: torch.Tensor
) -> torch.Tensor:
return fused_bias_dropout_residual(
input, bias, residual, self.p, self.training, self.inplace
)
|
xushiwei/goplus-play | lib/unicode/utf16/exports.go | <filename>lib/unicode/utf16/exports.go
package utf16
import (
"unicode/utf16"
"github.com/qiniu/goplus/gop"
)
// func utf16.Decode(s []uint16) []rune
func execDecode(_ int, p *gop.Context) {
args := p.GetArgs(1)
ret := utf16.Decode(args[0].([]uint16))
p.Ret(1, ret)
}
// func utf16.DecodeRune(r1 rune, r2 rune) rune
func execDecodeRune(_ int, p *gop.Context) {
args := p.GetArgs(2)
ret := utf16.DecodeRune(args[0].(rune), args[1].(rune))
p.Ret(2, ret)
}
// func utf16.Encode(s []rune) []uint16
func execEncode(_ int, p *gop.Context) {
args := p.GetArgs(1)
ret := utf16.Encode(args[0].([]rune))
p.Ret(1, ret)
}
// func utf16.EncodeRune(r rune) (r1 rune, r2 rune)
func execEncodeRune(_ int, p *gop.Context) {
args := p.GetArgs(1)
ret, ret1 := utf16.EncodeRune(args[0].(rune))
p.Ret(1, ret, ret1)
}
// func utf16.IsSurrogate(r rune) bool
func execIsSurrogate(_ int, p *gop.Context) {
args := p.GetArgs(1)
ret := utf16.IsSurrogate(args[0].(rune))
p.Ret(1, ret)
}
// I is a Go package instance.
var I = gop.NewGoPackage("unicode/utf16")
func init() {
I.RegisterFuncs(
I.Func("Decode", utf16.Decode, execDecode),
I.Func("DecodeRune", utf16.DecodeRune, execDecodeRune),
I.Func("Encode", utf16.Encode, execEncode),
I.Func("EncodeRune", utf16.EncodeRune, execEncodeRune),
I.Func("IsSurrogate", utf16.IsSurrogate, execIsSurrogate),
)
}
|
graphcore/poprithms | poprithms/tests/testutil/include/testutil/schedule/commandlineoptions.hpp | // Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#ifndef TESTUTIL_SCHEDULE_COMMANDLINEOPTIONS_HPP
#define TESTUTIL_SCHEDULE_COMMANDLINEOPTIONS_HPP
#include <map>
#include <string>
#include <vector>
namespace poprithms {
namespace schedule {
class CommandLineOptions {
public:
using StringMap = std::map<std::string, std::string>;
// parse argv, and verify that all keys in required appear once
StringMap
getCommandLineOptionsMap(int argc,
char **argv,
const std::vector<std::string> &required,
const std::vector<std::string> &requiredInfos);
// the specific keys to the algorithm being tested
virtual const std::vector<std::string> &
getAlgoCommandLineOptions() const = 0;
std::string
getInfoString(const std::vector<std::string> &required,
const std::vector<std::string> &requiredInfos) const;
// select all algorithm specific arguments from m
StringMap getAlgoCommandLineOptionsMap(const StringMap &m) const;
};
} // namespace schedule
} // namespace poprithms
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.