text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* 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 groovy.test;
import groovy.lang.Closure;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.GroovyShell;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.isAtLeast;
/**
* <p>{@code GroovyAssert} contains a set of static assertion and test helper methods and is supposed to be a Groovy
* extension of JUnit 4's {@link org.junit.Assert} class. In case JUnit 3 is the choice, the {@link groovy.test.GroovyTestCase}
* is meant to be used for writing tests based on {@link junit.framework.TestCase}.
* </p>
*
* <p>
* {@code GroovyAssert} methods can either be used by fully qualifying the static method like
*
* <pre>
* groovy.test.GroovyAssert.shouldFail { ... }
* </pre>
*
* or by importing the static methods with one ore more static imports
*
* <pre>
* import static groovy.test.GroovyAssert.shouldFail
* import static groovy.test.GroovyAssert.assertNotNull
* </pre>
* </p>
*
* @see groovy.test.GroovyTestCase
* @since 2.3
*/
public class GroovyAssert extends org.junit.Assert {
private static final Logger log = Logger.getLogger(GroovyAssert.class.getName());
private static final int MAX_NESTED_EXCEPTIONS = 10;
private static final AtomicInteger counter = new AtomicInteger(0);
public static final String TEST_SCRIPT_NAME_PREFIX = "TestScript";
/**
* @return a generic script name to be used by {@code GroovyShell#evaluate} calls.
*/
protected static String genericScriptName() {
return TEST_SCRIPT_NAME_PREFIX + (counter.getAndIncrement()) + ".groovy";
}
/**
* Asserts that the script runs without any exceptions
*
* @param script the script that should pass without any exception thrown
*/
public static void assertScript(final String script) throws Exception {
assertScript(new GroovyShell(), script);
}
/**
* Asserts that the script runs using the given shell without any exceptions
*
* @param shell the shell to use to evaluate the script
* @param script the script that should pass without any exception thrown
*/
public static void assertScript(final GroovyShell shell, final String script) {
shell.evaluate(script, genericScriptName());
}
/**
* Asserts that the given code closure fails when it is evaluated
*
* @param code the code expected to fail
* @return the caught exception
*/
public static Throwable shouldFail(Closure code) {
boolean failed = false;
Throwable th = null;
try {
code.call();
} catch (GroovyRuntimeException gre) {
failed = true;
th = ScriptBytecodeAdapter.unwrap(gre);
} catch (Throwable e) {
failed = true;
th = e;
}
assertTrue("Closure " + code + " should have failed", failed);
return th;
}
/**
* Asserts that the given code closure fails when it is evaluated
* and that a particular type of exception is thrown.
*
* @param clazz the class of the expected exception
* @param code the closure that should fail
* @return the caught exception
*/
public static Throwable shouldFail(Class clazz, Closure code) {
Throwable th = null;
try {
code.call();
} catch (GroovyRuntimeException gre) {
th = ScriptBytecodeAdapter.unwrap(gre);
} catch (Throwable e) {
th = e;
}
if (th == null) {
fail("Closure " + code + " should have failed with an exception of type " + clazz.getName());
} else if (!clazz.isInstance(th)) {
fail("Closure " + code + " should have failed with an exception of type " + clazz.getName() + ", instead got Exception " + th);
}
return th;
}
/**
* Asserts that the given code closure fails when it is evaluated
* and that a particular Exception type can be attributed to the cause.
* The expected exception class is compared recursively with any nested
* exceptions using getCause() until either a match is found or no more
* nested exceptions exist.
* <p>
* If a match is found, the matching exception is returned
* otherwise the method will fail.
*
* @param expectedCause the class of the expected exception
* @param code the closure that should fail
* @return the cause
*/
public static Throwable shouldFailWithCause(Class expectedCause, Closure code) {
if (expectedCause == null) {
fail("The expectedCause class cannot be null");
}
Throwable cause = null;
Throwable orig = null;
int level = 0;
try {
code.call();
} catch (GroovyRuntimeException gre) {
orig = ScriptBytecodeAdapter.unwrap(gre);
cause = orig.getCause();
} catch (Throwable e) {
orig = e;
cause = orig.getCause();
}
if (orig != null && cause == null) {
fail("Closure " + code + " was expected to fail due to a nested cause of type " + expectedCause.getName() +
" but instead got a direct exception of type " + orig.getClass().getName() + " with no nested cause(s). Code under test has a bug or perhaps you meant shouldFail?");
}
while (cause != null && !expectedCause.isInstance(cause) && cause != cause.getCause() && level < MAX_NESTED_EXCEPTIONS) {
cause = cause.getCause();
level++;
}
if (orig == null) {
fail("Closure " + code + " should have failed with an exception having a nested cause of type " + expectedCause.getName());
} else if (cause == null || !expectedCause.isInstance(cause)) {
fail("Closure " + code + " should have failed with an exception having a nested cause of type " + expectedCause.getName() + ", instead found these Exceptions:\n" + buildExceptionList(orig));
}
return cause;
}
/**
* Asserts that the given script fails when it is evaluated
* and that a particular type of exception is thrown.
*
* @param clazz the class of the expected exception
* @param script the script that should fail
* @return the caught exception
*/
public static Throwable shouldFail(Class clazz, String script) {
return shouldFail(new GroovyShell(), clazz, script);
}
/**
* Asserts that the given script fails when it is evaluated using the given shell
* and that a particular type of exception is thrown.
*
* @param shell the shell to use to evaluate the script
* @param clazz the class of the expected exception
* @param script the script that should fail
* @return the caught exception
*/
public static Throwable shouldFail(GroovyShell shell, Class clazz, String script) {
Throwable th = null;
try {
shell.evaluate(script, genericScriptName());
} catch (GroovyRuntimeException gre) {
th = ScriptBytecodeAdapter.unwrap(gre);
} catch (Throwable e) {
th = e;
}
if (th == null) {
fail("Script should have failed with an exception of type " + clazz.getName());
} else if (!clazz.isInstance(th)) {
fail("Script should have failed with an exception of type " + clazz.getName() + ", instead got Exception " + th);
}
return th;
}
/**
* Asserts that the given script fails when it is evaluated
*
* @param script the script expected to fail
* @return the caught exception
*/
public static Throwable shouldFail(String script) {
return shouldFail(new GroovyShell(), script);
}
/**
* Asserts that the given script fails when it is evaluated using the given shell
*
* @param shell the shell to use to evaluate the script
* @param script the script expected to fail
* @return the caught exception
*/
public static Throwable shouldFail(GroovyShell shell, String script) {
boolean failed = false;
Throwable th = null;
try {
shell.evaluate(script, genericScriptName());
} catch (GroovyRuntimeException gre) {
failed = true;
th = ScriptBytecodeAdapter.unwrap(gre);
} catch (Throwable e) {
failed = true;
th = e;
}
assertTrue("Script should have failed", failed);
return th;
}
/**
* NotYetImplemented Implementation
*/
private static final ThreadLocal<Boolean> notYetImplementedFlag = new ThreadLocal<>();
/**
* From JUnit. Finds from the call stack the active running JUnit test case
*
* @return the test case method
* @throws RuntimeException if no method could be found.
*/
private static Method findRunningJUnitTestMethod(Class caller) {
final Class[] args = new Class[]{};
// search the initial junit test
final Throwable t = new Exception();
for (int i = t.getStackTrace().length - 1; i >= 0; --i) {
final StackTraceElement element = t.getStackTrace()[i];
if (element.getClassName().equals(caller.getName())) {
try {
final Method m = caller.getMethod(element.getMethodName(), args);
if (isPublicTestMethod(m)) {
return m;
}
}
catch (final Exception e) {
// can't access, ignore it
}
}
}
throw new RuntimeException("No JUnit test case method found in call stack");
}
/**
* From Junit. Test if the method is a JUnit 3 or 4 test.
*
* @param method the method
* @return <code>true</code> if this is a junit test.
*/
private static boolean isPublicTestMethod(final Method method) {
final String name = method.getName();
final Class[] parameters = method.getParameterTypes();
final Class returnType = method.getReturnType();
return parameters.length == 0
&& (name.startsWith("test") || method.getAnnotation(Test.class) != null)
&& returnType.equals(Void.TYPE)
&& Modifier.isPublic(method.getModifiers());
}
/**
* <p>
* Runs the calling JUnit test again and fails only if it unexpectedly runs.<br>
* This is helpful for tests that don't currently work but should work one day,
* when the tested functionality has been implemented.<br>
* </p>
*
* <p>
* The right way to use it for JUnit 3 is:
*
* <pre>
* public void testXXX() {
* if (GroovyAssert.notYetImplemented(this)) return;
* ... the real (now failing) unit test
* }
* </pre>
*
* or for JUnit 4
*
* <pre>
* @Test
* public void XXX() {
* if (GroovyAssert.notYetImplemented(this)) return;
* ... the real (now failing) unit test
* }
* </pre>
* </p>
*
* <p>
* Idea copied from HtmlUnit (many thanks to Marc Guillemot).
* Future versions maybe available in the JUnit distribution.
* </p>
*
* @return {@code false} when not itself already in the call stack
*/
public static boolean notYetImplemented(Object caller) {
if (notYetImplementedFlag.get() != null) {
return false;
}
notYetImplementedFlag.set(Boolean.TRUE);
final Method testMethod = findRunningJUnitTestMethod(caller.getClass());
try {
log.info("Running " + testMethod.getName() + " as not yet implemented");
testMethod.invoke(caller, (Object[]) new Class[]{});
fail(testMethod.getName() + " is marked as not yet implemented but passes unexpectedly");
}
catch (final Exception e) {
log.info(testMethod.getName() + " fails which is expected as it is not yet implemented");
// method execution failed, it is really "not yet implemented"
}
finally {
notYetImplementedFlag.set(null);
}
return true;
}
/**
* @return true if the JDK version is at least the version given by specVersion (e.g. "1.8", "9.0")
* @since 2.5.7
*/
public static boolean isAtLeastJdk(String specVersion) {
boolean result = false;
try {
result = isAtLeast(new BigDecimal(System.getProperty("java.specification.version")), specVersion);
} catch (Exception ignore) {
}
return result;
}
private static String buildExceptionList(Throwable th) {
StringBuilder sb = new StringBuilder();
int level = 0;
while (th != null) {
if (level > 1) {
for (int i = 0; i < level - 1; i++) sb.append(" ");
}
if (level > 0) sb.append("-> ");
if (level > MAX_NESTED_EXCEPTIONS) {
sb.append("...");
break;
}
sb.append(th.getClass().getName()).append(": ").append(th.getMessage()).append("\n");
if (th == th.getCause()) {
break;
}
th = th.getCause();
level++;
}
return sb.toString();
}
}
| {
"pile_set_name": "Github"
} |
---
sidebar: home_sidebar
title: Build for gts210wifi
folder: build
permalink: /devices/gts210wifi/build
device: gts210wifi
---
{% include templates/device_build.md %}
| {
"pile_set_name": "Github"
} |
{{!Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.}}
{{!master(layout/_master.tmpl)}}
<div id="sidetoggle">
<div>
{{^_disableSideFilter}}
<div class="sidefilter">
<form class="toc-filter">
<span class="glyphicon glyphicon-filter filter-icon"></span>
<input type="text" id="toc_filter_input" placeholder="Enter here to filter..." onkeypress="if(event.keyCode==13) {return false;}">
</form>
</div>
{{/_disableSideFilter}}
<div class="sidetoc">
<div class="toc" id="toc">
{{^leaf}}
{{>partials/li}}
{{/leaf}}
</div>
</div>
</div>
</div> | {
"pile_set_name": "Github"
} |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_HAL_INTRIN_MSA_HPP
#define OPENCV_HAL_INTRIN_MSA_HPP
#include <algorithm>
#include "opencv2/core/utility.hpp"
namespace cv
{
//! @cond IGNORED
CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN
#define CV_SIMD128 1
//MSA implements 128-bit wide vector registers shared with the 64-bit wide floating-point unit registers.
//MSA and FPU can not be both present, unless the FPU has 64-bit floating-point registers.
#define CV_SIMD128_64F 1
struct v_uint8x16
{
typedef uchar lane_type;
enum { nlanes = 16 };
v_uint8x16() : val(msa_dupq_n_u8(0)) {}
explicit v_uint8x16(v16u8 v) : val(v) {}
v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7,
uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15)
{
uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = msa_ld1q_u8(v);
}
uchar get0() const
{
return msa_getq_lane_u8(val, 0);
}
v16u8 val;
};
struct v_int8x16
{
typedef schar lane_type;
enum { nlanes = 16 };
v_int8x16() : val(msa_dupq_n_s8(0)) {}
explicit v_int8x16(v16i8 v) : val(v) {}
v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7,
schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15)
{
schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = msa_ld1q_s8(v);
}
schar get0() const
{
return msa_getq_lane_s8(val, 0);
}
v16i8 val;
};
struct v_uint16x8
{
typedef ushort lane_type;
enum { nlanes = 8 };
v_uint16x8() : val(msa_dupq_n_u16(0)) {}
explicit v_uint16x8(v8u16 v) : val(v) {}
v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7)
{
ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = msa_ld1q_u16(v);
}
ushort get0() const
{
return msa_getq_lane_u16(val, 0);
}
v8u16 val;
};
struct v_int16x8
{
typedef short lane_type;
enum { nlanes = 8 };
v_int16x8() : val(msa_dupq_n_s16(0)) {}
explicit v_int16x8(v8i16 v) : val(v) {}
v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7)
{
short v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = msa_ld1q_s16(v);
}
short get0() const
{
return msa_getq_lane_s16(val, 0);
}
v8i16 val;
};
struct v_uint32x4
{
typedef unsigned int lane_type;
enum { nlanes = 4 };
v_uint32x4() : val(msa_dupq_n_u32(0)) {}
explicit v_uint32x4(v4u32 v) : val(v) {}
v_uint32x4(unsigned int v0, unsigned int v1, unsigned int v2, unsigned int v3)
{
unsigned int v[] = {v0, v1, v2, v3};
val = msa_ld1q_u32(v);
}
unsigned int get0() const
{
return msa_getq_lane_u32(val, 0);
}
v4u32 val;
};
struct v_int32x4
{
typedef int lane_type;
enum { nlanes = 4 };
v_int32x4() : val(msa_dupq_n_s32(0)) {}
explicit v_int32x4(v4i32 v) : val(v) {}
v_int32x4(int v0, int v1, int v2, int v3)
{
int v[] = {v0, v1, v2, v3};
val = msa_ld1q_s32(v);
}
int get0() const
{
return msa_getq_lane_s32(val, 0);
}
v4i32 val;
};
struct v_float32x4
{
typedef float lane_type;
enum { nlanes = 4 };
v_float32x4() : val(msa_dupq_n_f32(0.0f)) {}
explicit v_float32x4(v4f32 v) : val(v) {}
v_float32x4(float v0, float v1, float v2, float v3)
{
float v[] = {v0, v1, v2, v3};
val = msa_ld1q_f32(v);
}
float get0() const
{
return msa_getq_lane_f32(val, 0);
}
v4f32 val;
};
struct v_uint64x2
{
typedef uint64 lane_type;
enum { nlanes = 2 };
v_uint64x2() : val(msa_dupq_n_u64(0)) {}
explicit v_uint64x2(v2u64 v) : val(v) {}
v_uint64x2(uint64 v0, uint64 v1)
{
uint64 v[] = {v0, v1};
val = msa_ld1q_u64(v);
}
uint64 get0() const
{
return msa_getq_lane_u64(val, 0);
}
v2u64 val;
};
struct v_int64x2
{
typedef int64 lane_type;
enum { nlanes = 2 };
v_int64x2() : val(msa_dupq_n_s64(0)) {}
explicit v_int64x2(v2i64 v) : val(v) {}
v_int64x2(int64 v0, int64 v1)
{
int64 v[] = {v0, v1};
val = msa_ld1q_s64(v);
}
int64 get0() const
{
return msa_getq_lane_s64(val, 0);
}
v2i64 val;
};
struct v_float64x2
{
typedef double lane_type;
enum { nlanes = 2 };
v_float64x2() : val(msa_dupq_n_f64(0.0f)) {}
explicit v_float64x2(v2f64 v) : val(v) {}
v_float64x2(double v0, double v1)
{
double v[] = {v0, v1};
val = msa_ld1q_f64(v);
}
double get0() const
{
return msa_getq_lane_f64(val, 0);
}
v2f64 val;
};
#define OPENCV_HAL_IMPL_MSA_INIT(_Tpv, _Tp, suffix) \
inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(msa_dupq_n_##suffix((_Tp)0)); } \
inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(msa_dupq_n_##suffix(v)); } \
inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(MSA_TPV_REINTERPRET(v16u8, v.val)); } \
inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(MSA_TPV_REINTERPRET(v16i8, v.val)); } \
inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(MSA_TPV_REINTERPRET(v8u16, v.val)); } \
inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(MSA_TPV_REINTERPRET(v8i16, v.val)); } \
inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(MSA_TPV_REINTERPRET(v4u32, v.val)); } \
inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(MSA_TPV_REINTERPRET(v4i32, v.val)); } \
inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(MSA_TPV_REINTERPRET(v2u64, v.val)); } \
inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(MSA_TPV_REINTERPRET(v2i64, v.val)); } \
inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(MSA_TPV_REINTERPRET(v4f32, v.val)); } \
inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(MSA_TPV_REINTERPRET(v2f64, v.val)); }
OPENCV_HAL_IMPL_MSA_INIT(uint8x16, uchar, u8)
OPENCV_HAL_IMPL_MSA_INIT(int8x16, schar, s8)
OPENCV_HAL_IMPL_MSA_INIT(uint16x8, ushort, u16)
OPENCV_HAL_IMPL_MSA_INIT(int16x8, short, s16)
OPENCV_HAL_IMPL_MSA_INIT(uint32x4, unsigned int, u32)
OPENCV_HAL_IMPL_MSA_INIT(int32x4, int, s32)
OPENCV_HAL_IMPL_MSA_INIT(uint64x2, uint64, u64)
OPENCV_HAL_IMPL_MSA_INIT(int64x2, int64, s64)
OPENCV_HAL_IMPL_MSA_INIT(float32x4, float, f32)
OPENCV_HAL_IMPL_MSA_INIT(float64x2, double, f64)
#define OPENCV_HAL_IMPL_MSA_PACK(_Tpvec, _Tpwvec, pack, mov, rshr) \
inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \
{ \
return _Tpvec(mov(a.val, b.val)); \
} \
template<int n> inline \
_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \
{ \
return _Tpvec(rshr(a.val, b.val, n)); \
}
OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_uint16x8, pack, msa_qpack_u16, msa_qrpackr_u16)
OPENCV_HAL_IMPL_MSA_PACK(v_int8x16, v_int16x8, pack, msa_qpack_s16, msa_qrpackr_s16)
OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_uint32x4, pack, msa_qpack_u32, msa_qrpackr_u32)
OPENCV_HAL_IMPL_MSA_PACK(v_int16x8, v_int32x4, pack, msa_qpack_s32, msa_qrpackr_s32)
OPENCV_HAL_IMPL_MSA_PACK(v_uint32x4, v_uint64x2, pack, msa_pack_u64, msa_rpackr_u64)
OPENCV_HAL_IMPL_MSA_PACK(v_int32x4, v_int64x2, pack, msa_pack_s64, msa_rpackr_s64)
OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_int16x8, pack_u, msa_qpacku_s16, msa_qrpackru_s16)
OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_int32x4, pack_u, msa_qpacku_s32, msa_qrpackru_s32)
#define OPENCV_HAL_IMPL_MSA_PACK_STORE(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \
inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \
{ \
hreg a1 = mov(a.val); \
msa_st1_##suffix(ptr, a1); \
} \
template<int n> inline \
void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \
{ \
hreg a1 = rshr(a.val, n); \
msa_st1_##suffix(ptr, a1); \
}
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_uint16x8, pack, msa_qmovn_u16, msa_qrshrn_n_u16)
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int8x16, schar, v8i8, s8, v_int16x8, pack, msa_qmovn_s16, msa_qrshrn_n_s16)
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_uint32x4, pack, msa_qmovn_u32, msa_qrshrn_n_u32)
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int16x8, short, v4i16, s16, v_int32x4, pack, msa_qmovn_s32, msa_qrshrn_n_s32)
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint32x4, unsigned, v2u32, u32, v_uint64x2, pack, msa_movn_u64, msa_rshrn_n_u64)
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int32x4, int, v2i32, s32, v_int64x2, pack, msa_movn_s64, msa_rshrn_n_s64)
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_int16x8, pack_u, msa_qmovun_s16, msa_qrshrun_n_s16)
OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_int32x4, pack_u, msa_qmovun_s32, msa_qrshrun_n_s32)
// pack boolean
inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b)
{
return v_uint8x16(msa_pack_u16(a.val, b.val));
}
inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b,
const v_uint32x4& c, const v_uint32x4& d)
{
return v_uint8x16(msa_pack_u16(msa_pack_u32(a.val, b.val), msa_pack_u32(c.val, d.val)));
}
inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c,
const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f,
const v_uint64x2& g, const v_uint64x2& h)
{
v8u16 abcd = msa_pack_u32(msa_pack_u64(a.val, b.val), msa_pack_u64(c.val, d.val));
v8u16 efgh = msa_pack_u32(msa_pack_u64(e.val, f.val), msa_pack_u64(g.val, h.val));
return v_uint8x16(msa_pack_u16(abcd, efgh));
}
inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0,
const v_float32x4& m1, const v_float32x4& m2,
const v_float32x4& m3)
{
v4f32 v0 = v.val;
v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0);
res = msa_mlaq_lane_f32(res, m1.val, v0, 1);
res = msa_mlaq_lane_f32(res, m2.val, v0, 2);
res = msa_mlaq_lane_f32(res, m3.val, v0, 3);
return v_float32x4(res);
}
inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0,
const v_float32x4& m1, const v_float32x4& m2,
const v_float32x4& a)
{
v4f32 v0 = v.val;
v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0);
res = msa_mlaq_lane_f32(res, m1.val, v0, 1);
res = msa_mlaq_lane_f32(res, m2.val, v0, 2);
res = msa_addq_f32(res, a.val);
return v_float32x4(res);
}
#define OPENCV_HAL_IMPL_MSA_BIN_OP(bin_op, _Tpvec, intrin) \
inline _Tpvec operator bin_op (const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(intrin(a.val, b.val)); \
} \
inline _Tpvec& operator bin_op##= (_Tpvec& a, const _Tpvec& b) \
{ \
a.val = intrin(a.val, b.val); \
return a; \
}
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_uint8x16, msa_qaddq_u8)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_uint8x16, msa_qsubq_u8)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_int8x16, msa_qaddq_s8)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_int8x16, msa_qsubq_s8)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_uint16x8, msa_qaddq_u16)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_uint16x8, msa_qsubq_u16)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_int16x8, msa_qaddq_s16)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_int16x8, msa_qsubq_s16)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_int32x4, msa_addq_s32)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_int32x4, msa_subq_s32)
OPENCV_HAL_IMPL_MSA_BIN_OP(*, v_int32x4, msa_mulq_s32)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_uint32x4, msa_addq_u32)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_uint32x4, msa_subq_u32)
OPENCV_HAL_IMPL_MSA_BIN_OP(*, v_uint32x4, msa_mulq_u32)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_float32x4, msa_addq_f32)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_float32x4, msa_subq_f32)
OPENCV_HAL_IMPL_MSA_BIN_OP(*, v_float32x4, msa_mulq_f32)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_int64x2, msa_addq_s64)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_int64x2, msa_subq_s64)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_uint64x2, msa_addq_u64)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_uint64x2, msa_subq_u64)
OPENCV_HAL_IMPL_MSA_BIN_OP(/, v_float32x4, msa_divq_f32)
OPENCV_HAL_IMPL_MSA_BIN_OP(+, v_float64x2, msa_addq_f64)
OPENCV_HAL_IMPL_MSA_BIN_OP(-, v_float64x2, msa_subq_f64)
OPENCV_HAL_IMPL_MSA_BIN_OP(*, v_float64x2, msa_mulq_f64)
OPENCV_HAL_IMPL_MSA_BIN_OP(/, v_float64x2, msa_divq_f64)
// saturating multiply 8-bit, 16-bit
#define OPENCV_HAL_IMPL_MSA_MUL_SAT(_Tpvec, _Tpwvec) \
inline _Tpvec operator * (const _Tpvec& a, const _Tpvec& b) \
{ \
_Tpwvec c, d; \
v_mul_expand(a, b, c, d); \
return v_pack(c, d); \
} \
inline _Tpvec& operator *= (_Tpvec& a, const _Tpvec& b) \
{a = a * b; return a; }
OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int8x16, v_int16x8)
OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint8x16, v_uint16x8)
OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int16x8, v_int32x4)
OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint16x8, v_uint32x4)
// Multiply and expand
inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b,
v_int16x8& c, v_int16x8& d)
{
v16i8 a_lo, a_hi, b_lo, b_hi;
ILVRL_B2_SB(a.val, msa_dupq_n_s8(0), a_lo, a_hi);
ILVRL_B2_SB(b.val, msa_dupq_n_s8(0), b_lo, b_hi);
c.val = msa_mulq_s16(msa_paddlq_s8(a_lo), msa_paddlq_s8(b_lo));
d.val = msa_mulq_s16(msa_paddlq_s8(a_hi), msa_paddlq_s8(b_hi));
}
inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b,
v_uint16x8& c, v_uint16x8& d)
{
v16u8 a_lo, a_hi, b_lo, b_hi;
ILVRL_B2_UB(a.val, msa_dupq_n_u8(0), a_lo, a_hi);
ILVRL_B2_UB(b.val, msa_dupq_n_u8(0), b_lo, b_hi);
c.val = msa_mulq_u16(msa_paddlq_u8(a_lo), msa_paddlq_u8(b_lo));
d.val = msa_mulq_u16(msa_paddlq_u8(a_hi), msa_paddlq_u8(b_hi));
}
inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b,
v_int32x4& c, v_int32x4& d)
{
v8i16 a_lo, a_hi, b_lo, b_hi;
ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi);
ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi);
c.val = msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo));
d.val = msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi));
}
inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b,
v_uint32x4& c, v_uint32x4& d)
{
v8u16 a_lo, a_hi, b_lo, b_hi;
ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi);
ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi);
c.val = msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo));
d.val = msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi));
}
inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b,
v_uint64x2& c, v_uint64x2& d)
{
v4u32 a_lo, a_hi, b_lo, b_hi;
ILVRL_W2_UW(a.val, msa_dupq_n_u32(0), a_lo, a_hi);
ILVRL_W2_UW(b.val, msa_dupq_n_u32(0), b_lo, b_hi);
c.val = msa_mulq_u64(msa_paddlq_u32(a_lo), msa_paddlq_u32(b_lo));
d.val = msa_mulq_u64(msa_paddlq_u32(a_hi), msa_paddlq_u32(b_hi));
}
inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b)
{
v8i16 a_lo, a_hi, b_lo, b_hi;
ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi);
ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi);
return v_int16x8(msa_packr_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)),
msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)), 16));
}
inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b)
{
v8u16 a_lo, a_hi, b_lo, b_hi;
ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi);
ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi);
return v_uint16x8(msa_packr_u32(msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)),
msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)), 16));
}
//////// Dot Product ////////
// 16 >> 32
inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b)
{ return v_int32x4(msa_dotp_s_w(a.val, b.val)); }
inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c)
{ return v_int32x4(msa_dpadd_s_w(c.val , a.val, b.val)); }
// 32 >> 64
inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b)
{ return v_int64x2(msa_dotp_s_d(a.val, b.val)); }
inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c)
{ return v_int64x2(msa_dpadd_s_d(c.val , a.val, b.val)); }
// 8 >> 32
inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b)
{
v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8);
v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8);
v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8);
v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8);
v4u32 prod = msa_dotp_u_w(even_a, even_b);
return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b));
}
inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c)
{
v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8);
v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8);
v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8);
v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8);
v4u32 prod = msa_dpadd_u_w(c.val, even_a, even_b);
return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b));
}
inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b)
{
v8i16 prod = msa_dotp_s_h(a.val, b.val);
return v_int32x4(msa_hadd_s32(prod, prod));
}
inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b,
const v_int32x4& c)
{ return v_dotprod_expand(a, b) + c; }
// 16 >> 64
inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b)
{
v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16);
v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16);
v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16);
v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16);
v2u64 prod = msa_dotp_u_d(even_a, even_b);
return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b));
}
inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b,
const v_uint64x2& c)
{
v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16);
v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16);
v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16);
v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16);
v2u64 prod = msa_dpadd_u_d(c.val, even_a, even_b);
return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b));
}
inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b)
{
v4i32 prod = msa_dotp_s_w(a.val, b.val);
return v_int64x2(msa_hadd_s64(prod, prod));
}
inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c)
{ return v_dotprod_expand(a, b) + c; }
// 32 >> 64f
inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b)
{ return v_cvt_f64(v_dotprod(a, b)); }
inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c)
{ return v_dotprod_expand(a, b) + c; }
//////// Fast Dot Product ////////
// 16 >> 32
inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b)
{ return v_dotprod(a, b); }
inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c)
{ return v_dotprod(a, b, c); }
// 32 >> 64
inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b)
{ return v_dotprod(a, b); }
inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c)
{ return v_dotprod(a, b, c); }
// 8 >> 32
inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b)
{ return v_dotprod_expand(a, b); }
inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c)
{ return v_dotprod_expand(a, b, c); }
inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b)
{ return v_dotprod_expand(a, b); }
inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c)
{ return v_dotprod_expand(a, b, c); }
// 16 >> 64
inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b)
{ return v_dotprod_expand(a, b); }
inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c)
{ return v_dotprod_expand(a, b, c); }
inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b)
{ return v_dotprod_expand(a, b); }
inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c)
{ return v_dotprod_expand(a, b, c); }
// 32 >> 64f
inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b)
{ return v_dotprod_expand(a, b); }
inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c)
{ return v_dotprod_expand(a, b, c); }
#define OPENCV_HAL_IMPL_MSA_LOGIC_OP(_Tpvec, _Tpv, suffix) \
OPENCV_HAL_IMPL_MSA_BIN_OP(&, _Tpvec, msa_andq_##suffix) \
OPENCV_HAL_IMPL_MSA_BIN_OP(|, _Tpvec, msa_orrq_##suffix) \
OPENCV_HAL_IMPL_MSA_BIN_OP(^, _Tpvec, msa_eorq_##suffix) \
inline _Tpvec operator ~ (const _Tpvec& a) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_u8(MSA_TPV_REINTERPRET(v16u8, a.val)))); \
}
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint8x16, v16u8, u8)
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int8x16, v16i8, s8)
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint16x8, v8u16, u16)
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int16x8, v8i16, s16)
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint32x4, v4u32, u32)
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int32x4, v4i32, s32)
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint64x2, v2u64, u64)
OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int64x2, v2i64, s64)
#define OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(bin_op, intrin) \
inline v_float32x4 operator bin_op (const v_float32x4& a, const v_float32x4& b) \
{ \
return v_float32x4(MSA_TPV_REINTERPRET(v4f32, intrin(MSA_TPV_REINTERPRET(v4i32, a.val), MSA_TPV_REINTERPRET(v4i32, b.val)))); \
} \
inline v_float32x4& operator bin_op##= (v_float32x4& a, const v_float32x4& b) \
{ \
a.val = MSA_TPV_REINTERPRET(v4f32, intrin(MSA_TPV_REINTERPRET(v4i32, a.val), MSA_TPV_REINTERPRET(v4i32, b.val))); \
return a; \
}
OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(&, msa_andq_s32)
OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(|, msa_orrq_s32)
OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(^, msa_eorq_s32)
inline v_float32x4 operator ~ (const v_float32x4& a)
{
return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val))));
}
/* v_abs */
#define OPENCV_HAL_IMPL_MSA_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \
inline _Tpuvec v_abs(const _Tpsvec& a) \
{ \
return v_reinterpret_as_##usuffix(_Tpsvec(msa_absq_##ssuffix(a.val))); \
}
OPENCV_HAL_IMPL_MSA_ABS(v_uint8x16, v_int8x16, u8, s8)
OPENCV_HAL_IMPL_MSA_ABS(v_uint16x8, v_int16x8, u16, s16)
OPENCV_HAL_IMPL_MSA_ABS(v_uint32x4, v_int32x4, u32, s32)
/* v_abs(float), v_sqrt, v_invsqrt */
#define OPENCV_HAL_IMPL_MSA_BASIC_FUNC(_Tpvec, func, intrin) \
inline _Tpvec func(const _Tpvec& a) \
{ \
return _Tpvec(intrin(a.val)); \
}
OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_abs, msa_absq_f32)
OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_abs, msa_absq_f64)
OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_sqrt, msa_sqrtq_f32)
OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_invsqrt, msa_rsqrtq_f32)
OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_sqrt, msa_sqrtq_f64)
OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_invsqrt, msa_rsqrtq_f64)
#define OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(bin_op, intrin) \
inline v_float64x2 operator bin_op (const v_float64x2& a, const v_float64x2& b) \
{ \
return v_float64x2(MSA_TPV_REINTERPRET(v2f64, intrin(MSA_TPV_REINTERPRET(v2i64, a.val), MSA_TPV_REINTERPRET(v2i64, b.val)))); \
} \
inline v_float64x2& operator bin_op##= (v_float64x2& a, const v_float64x2& b) \
{ \
a.val = MSA_TPV_REINTERPRET(v2f64, intrin(MSA_TPV_REINTERPRET(v2i64, a.val), MSA_TPV_REINTERPRET(v2i64, b.val))); \
return a; \
}
OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(&, msa_andq_s64)
OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(|, msa_orrq_s64)
OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(^, msa_eorq_s64)
inline v_float64x2 operator ~ (const v_float64x2& a)
{
return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val))));
}
// TODO: exp, log, sin, cos
#define OPENCV_HAL_IMPL_MSA_BIN_FUNC(_Tpvec, func, intrin) \
inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(intrin(a.val, b.val)); \
}
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_min, msa_minq_u8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_max, msa_maxq_u8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_min, msa_minq_s8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_max, msa_maxq_s8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_min, msa_minq_u16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_max, msa_maxq_u16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_min, msa_minq_s16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_max, msa_maxq_s16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_min, msa_minq_u32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_max, msa_maxq_u32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_min, msa_minq_s32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_max, msa_maxq_s32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_min, msa_minq_f32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_max, msa_maxq_f32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_min, msa_minq_f64)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_max, msa_maxq_f64)
#define OPENCV_HAL_IMPL_MSA_INT_CMP_OP(_Tpvec, _Tpv, suffix, not_suffix) \
inline _Tpvec operator == (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ceqq_##suffix(a.val, b.val))); } \
inline _Tpvec operator != (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_##not_suffix(msa_ceqq_##suffix(a.val, b.val)))); } \
inline _Tpvec operator < (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cltq_##suffix(a.val, b.val))); } \
inline _Tpvec operator > (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgtq_##suffix(a.val, b.val))); } \
inline _Tpvec operator <= (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cleq_##suffix(a.val, b.val))); } \
inline _Tpvec operator >= (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgeq_##suffix(a.val, b.val))); }
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint8x16, v16u8, u8, u8)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int8x16, v16i8, s8, u8)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint16x8, v8u16, u16, u16)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int16x8, v8i16, s16, u16)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint32x4, v4u32, u32, u32)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int32x4, v4i32, s32, u32)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float32x4, v4f32, f32, u32)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint64x2, v2u64, u64, u64)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int64x2, v2i64, s64, u64)
OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float64x2, v2f64, f64, u64)
inline v_float32x4 v_not_nan(const v_float32x4& a)
{ return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ceqq_f32(a.val, a.val))); }
inline v_float64x2 v_not_nan(const v_float64x2& a)
{ return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ceqq_f64(a.val, a.val))); }
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_add_wrap, msa_addq_u8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_add_wrap, msa_addq_s8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_add_wrap, msa_addq_u16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_add_wrap, msa_addq_s16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_sub_wrap, msa_subq_u8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_sub_wrap, msa_subq_s8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_sub_wrap, msa_subq_u16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_sub_wrap, msa_subq_s16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_mul_wrap, msa_mulq_u8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_mul_wrap, msa_mulq_s8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_mul_wrap, msa_mulq_u16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_mul_wrap, msa_mulq_s16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_absdiff, msa_abdq_u8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_absdiff, msa_abdq_u16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_absdiff, msa_abdq_u32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_absdiff, msa_abdq_f32)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_absdiff, msa_abdq_f64)
/** Saturating absolute difference **/
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_absdiffs, msa_qabdq_s8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_absdiffs, msa_qabdq_s16)
#define OPENCV_HAL_IMPL_MSA_BIN_FUNC2(_Tpvec, _Tpvec2, _Tpv, func, intrin) \
inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec2(MSA_TPV_REINTERPRET(_Tpv, intrin(a.val, b.val))); \
}
OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int8x16, v_uint8x16, v16u8, v_absdiff, msa_abdq_s8)
OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int16x8, v_uint16x8, v8u16, v_absdiff, msa_abdq_s16)
OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int32x4, v_uint32x4, v4u32, v_absdiff, msa_abdq_s32)
/* v_magnitude, v_sqr_magnitude, v_fma, v_muladd */
inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b)
{
v_float32x4 x(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val));
return v_sqrt(x);
}
inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b)
{
return v_float32x4(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val));
}
inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c)
{
return v_float32x4(msa_mlaq_f32(c.val, a.val, b.val));
}
inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c)
{
return v_int32x4(msa_mlaq_s32(c.val, a.val, b.val));
}
inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c)
{
return v_fma(a, b, c);
}
inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c)
{
return v_fma(a, b, c);
}
inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b)
{
v_float64x2 x(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val));
return v_sqrt(x);
}
inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b)
{
return v_float64x2(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val));
}
inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c)
{
return v_float64x2(msa_mlaq_f64(c.val, a.val, b.val));
}
inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c)
{
return v_fma(a, b, c);
}
// trade efficiency for convenience
#define OPENCV_HAL_IMPL_MSA_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \
inline _Tpvec operator << (const _Tpvec& a, int n) \
{ return _Tpvec(msa_shlq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \
inline _Tpvec operator >> (const _Tpvec& a, int n) \
{ return _Tpvec(msa_shrq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \
template<int n> inline _Tpvec v_shl(const _Tpvec& a) \
{ return _Tpvec(msa_shlq_n_##suffix(a.val, n)); } \
template<int n> inline _Tpvec v_shr(const _Tpvec& a) \
{ return _Tpvec(msa_shrq_n_##suffix(a.val, n)); } \
template<int n> inline _Tpvec v_rshr(const _Tpvec& a) \
{ return _Tpvec(msa_rshrq_n_##suffix(a.val, n)); }
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint8x16, u8, schar, s8)
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int8x16, s8, schar, s8)
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint16x8, u16, short, s16)
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int16x8, s16, short, s16)
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint32x4, u32, int, s32)
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int32x4, s32, int, s32)
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint64x2, u64, int64, s64)
OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int64x2, s64, int64, s64)
/* v_rotate_right, v_rotate_left */
#define OPENCV_HAL_IMPL_MSA_ROTATE_OP(_Tpvec, _Tpv, _Tpvs, suffix) \
template<int n> inline _Tpvec v_rotate_right(const _Tpvec& a) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##suffix(0), n))); \
} \
template<int n> inline _Tpvec v_rotate_left(const _Tpvec& a) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(msa_dupq_n_##suffix(0), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \
} \
template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \
{ \
return a; \
} \
template<int n> inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), n))); \
} \
template<int n> inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, b.val), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \
} \
template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \
{ \
CV_UNUSED(b); \
return a; \
}
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint8x16, v16u8, v16i8, s8)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int8x16, v16i8, v16i8, s8)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint16x8, v8u16, v8i16, s16)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int16x8, v8i16, v8i16, s16)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint32x4, v4u32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int32x4, v4i32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float32x4, v4f32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint64x2, v2u64, v2i64, s64)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int64x2, v2i64, v2i64, s64)
OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float64x2, v2f64, v2i64, s64)
#define OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(_Tpvec, _Tp, suffix) \
inline _Tpvec v_load(const _Tp* ptr) \
{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \
inline _Tpvec v_load_aligned(const _Tp* ptr) \
{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \
inline _Tpvec v_load_low(const _Tp* ptr) \
{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr), msa_dup_n_##suffix((_Tp)0))); } \
inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \
{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr0), msa_ld1_##suffix(ptr1))); } \
inline void v_store(_Tp* ptr, const _Tpvec& a) \
{ msa_st1q_##suffix(ptr, a.val); } \
inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \
{ msa_st1q_##suffix(ptr, a.val); } \
inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \
{ msa_st1q_##suffix(ptr, a.val); } \
inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \
{ msa_st1q_##suffix(ptr, a.val); } \
inline void v_store_low(_Tp* ptr, const _Tpvec& a) \
{ \
int n = _Tpvec::nlanes; \
for( int i = 0; i < (n/2); i++ ) \
ptr[i] = a.val[i]; \
} \
inline void v_store_high(_Tp* ptr, const _Tpvec& a) \
{ \
int n = _Tpvec::nlanes; \
for( int i = 0; i < (n/2); i++ ) \
ptr[i] = a.val[i+(n/2)]; \
}
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint8x16, uchar, u8)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int8x16, schar, s8)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint16x8, ushort, u16)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int16x8, short, s16)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint32x4, unsigned, u32)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int32x4, int, s32)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint64x2, uint64, u64)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int64x2, int64, s64)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float32x4, float, f32)
OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float64x2, double, f64)
/** Reverse **/
inline v_uint8x16 v_reverse(const v_uint8x16 &a)
{
v_uint8x16 c = v_uint8x16((v16u8)__builtin_msa_vshf_b((v16i8)((v2i64){0x08090A0B0C0D0E0F, 0x0001020304050607}), msa_dupq_n_s8(0), (v16i8)a.val));
return c;
}
inline v_int8x16 v_reverse(const v_int8x16 &a)
{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); }
inline v_uint16x8 v_reverse(const v_uint16x8 &a)
{
v_uint16x8 c = v_uint16x8((v8u16)__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000500060007, 0x0000000100020003}), msa_dupq_n_s16(0), (v8i16)a.val));
return c;
}
inline v_int16x8 v_reverse(const v_int16x8 &a)
{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); }
inline v_uint32x4 v_reverse(const v_uint32x4 &a)
{
v_uint32x4 c;
c.val[0] = a.val[3];
c.val[1] = a.val[2];
c.val[2] = a.val[1];
c.val[3] = a.val[0];
return c;
}
inline v_int32x4 v_reverse(const v_int32x4 &a)
{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); }
inline v_float32x4 v_reverse(const v_float32x4 &a)
{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); }
inline v_uint64x2 v_reverse(const v_uint64x2 &a)
{
v_uint64x2 c;
c.val[0] = a.val[1];
c.val[1] = a.val[0];
return c;
}
inline v_int64x2 v_reverse(const v_int64x2 &a)
{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); }
inline v_float64x2 v_reverse(const v_float64x2 &a)
{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); }
#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(func, cfunc) \
inline unsigned short v_reduce_##func(const v_uint16x8& a) \
{ \
v8u16 a_lo, a_hi; \
ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); \
v4u32 b = msa_##func##q_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(a_hi)); \
v4u32 b_lo, b_hi; \
ILVRL_W2_UW(b, msa_dupq_n_u32(0), b_lo, b_hi); \
v2u64 c = msa_##func##q_u64(msa_paddlq_u32(b_lo), msa_paddlq_u32(b_hi)); \
return (unsigned short)cfunc(c[0], c[1]); \
}
OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(max, std::max)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(min, std::min)
#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(func, cfunc) \
inline short v_reduce_##func(const v_int16x8& a) \
{ \
v8i16 a_lo, a_hi; \
ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); \
v4i32 b = msa_##func##q_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(a_hi)); \
v4i32 b_lo, b_hi; \
ILVRL_W2_SW(b, msa_dupq_n_s32(0), b_lo, b_hi); \
v2i64 c = msa_##func##q_s64(msa_paddlq_s32(b_lo), msa_paddlq_s32(b_hi)); \
return (short)cfunc(c[0], c[1]); \
}
OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(max, std::max)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(min, std::min)
#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(_Tpvec, scalartype, func, cfunc) \
inline scalartype v_reduce_##func(const _Tpvec& a) \
{ \
return (scalartype)cfunc(cfunc(a.val[0], a.val[1]), cfunc(a.val[2], a.val[3])); \
}
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, max, std::max)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, min, std::min)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, max, std::max)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, min, std::min)
#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(_Tpvec, scalartype, _Tpvec2, func) \
inline scalartype v_reduce_##func(const _Tpvec& a) \
{ \
_Tpvec2 a1, a2; \
v_expand(a, a1, a2); \
return (scalartype)v_reduce_##func(v_##func(a1, a2)); \
}
OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, min)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, max)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, min)
OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, max)
#define OPENCV_HAL_IMPL_MSA_REDUCE_SUM(_Tpvec, scalartype, suffix) \
inline scalartype v_reduce_sum(const _Tpvec& a) \
{ \
return (scalartype)msa_sum_##suffix(a.val); \
}
OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint8x16, unsigned char, u8)
OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int8x16, char, s8)
OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint16x8, unsigned short, u16)
OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int16x8, short, s16)
OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint32x4, unsigned, u32)
OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int32x4, int, s32)
OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_float32x4, float, f32)
inline uint64 v_reduce_sum(const v_uint64x2& a)
{ return (uint64)(msa_getq_lane_u64(a.val, 0) + msa_getq_lane_u64(a.val, 1)); }
inline int64 v_reduce_sum(const v_int64x2& a)
{ return (int64)(msa_getq_lane_s64(a.val, 0) + msa_getq_lane_s64(a.val, 1)); }
inline double v_reduce_sum(const v_float64x2& a)
{
return msa_getq_lane_f64(a.val, 0) + msa_getq_lane_f64(a.val, 1);
}
/* v_reduce_sum4, v_reduce_sad */
inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b,
const v_float32x4& c, const v_float32x4& d)
{
v4f32 u0 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val))),
MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val)))); // a0+a1 b0+b1 a2+a3 b2+b3
v4f32 u1 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val))),
MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val)))); // c0+c1 d0+d1 c2+c3 d2+d3
return v_float32x4(msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))),
MSA_TPV_REINTERPRET(v4f32, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0)))));
}
inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b)
{
v16u8 t0 = msa_abdq_u8(a.val, b.val);
v8u16 t1 = msa_paddlq_u8(t0);
v4u32 t2 = msa_paddlq_u16(t1);
return msa_sum_u32(t2);
}
inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b)
{
v16u8 t0 = MSA_TPV_REINTERPRET(v16u8, msa_abdq_s8(a.val, b.val));
v8u16 t1 = msa_paddlq_u8(t0);
v4u32 t2 = msa_paddlq_u16(t1);
return msa_sum_u32(t2);
}
inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b)
{
v8u16 t0 = msa_abdq_u16(a.val, b.val);
v4u32 t1 = msa_paddlq_u16(t0);
return msa_sum_u32(t1);
}
inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b)
{
v8u16 t0 = MSA_TPV_REINTERPRET(v8u16, msa_abdq_s16(a.val, b.val));
v4u32 t1 = msa_paddlq_u16(t0);
return msa_sum_u32(t1);
}
inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b)
{
v4u32 t0 = msa_abdq_u32(a.val, b.val);
return msa_sum_u32(t0);
}
inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b)
{
v4u32 t0 = MSA_TPV_REINTERPRET(v4u32, msa_abdq_s32(a.val, b.val));
return msa_sum_u32(t0);
}
inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b)
{
v4f32 t0 = msa_abdq_f32(a.val, b.val);
return msa_sum_f32(t0);
}
/* v_popcount */
#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(_Tpvec) \
inline v_uint8x16 v_popcount(const _Tpvec& a) \
{ \
v16u8 t = MSA_TPV_REINTERPRET(v16u8, msa_cntq_s8(MSA_TPV_REINTERPRET(v16i8, a.val))); \
return v_uint8x16(t); \
}
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_uint8x16)
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_int8x16)
#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(_Tpvec) \
inline v_uint16x8 v_popcount(const _Tpvec& a) \
{ \
v8u16 t = MSA_TPV_REINTERPRET(v8u16, msa_cntq_s16(MSA_TPV_REINTERPRET(v8i16, a.val))); \
return v_uint16x8(t); \
}
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_uint16x8)
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_int16x8)
#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(_Tpvec) \
inline v_uint32x4 v_popcount(const _Tpvec& a) \
{ \
v4u32 t = MSA_TPV_REINTERPRET(v4u32, msa_cntq_s32(MSA_TPV_REINTERPRET(v4i32, a.val))); \
return v_uint32x4(t); \
}
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_uint32x4)
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_int32x4)
#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(_Tpvec) \
inline v_uint64x2 v_popcount(const _Tpvec& a) \
{ \
v2u64 t = MSA_TPV_REINTERPRET(v2u64, msa_cntq_s64(MSA_TPV_REINTERPRET(v2i64, a.val))); \
return v_uint64x2(t); \
}
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_uint64x2)
OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_int64x2)
inline int v_signmask(const v_uint8x16& a)
{
v8i8 m0 = msa_create_s8(CV_BIG_UINT(0x0706050403020100));
v16u8 v0 = msa_shlq_u8(msa_shrq_n_u8(a.val, 7), msa_combine_s8(m0, m0));
v8u16 v1 = msa_paddlq_u8(v0);
v4u32 v2 = msa_paddlq_u16(v1);
v2u64 v3 = msa_paddlq_u32(v2);
return (int)msa_getq_lane_u64(v3, 0) + ((int)msa_getq_lane_u64(v3, 1) << 8);
}
inline int v_signmask(const v_int8x16& a)
{ return v_signmask(v_reinterpret_as_u8(a)); }
inline int v_signmask(const v_uint16x8& a)
{
v4i16 m0 = msa_create_s16(CV_BIG_UINT(0x0003000200010000));
v8u16 v0 = msa_shlq_u16(msa_shrq_n_u16(a.val, 15), msa_combine_s16(m0, m0));
v4u32 v1 = msa_paddlq_u16(v0);
v2u64 v2 = msa_paddlq_u32(v1);
return (int)msa_getq_lane_u64(v2, 0) + ((int)msa_getq_lane_u64(v2, 1) << 4);
}
inline int v_signmask(const v_int16x8& a)
{ return v_signmask(v_reinterpret_as_u16(a)); }
inline int v_signmask(const v_uint32x4& a)
{
v2i32 m0 = msa_create_s32(CV_BIG_UINT(0x0000000100000000));
v4u32 v0 = msa_shlq_u32(msa_shrq_n_u32(a.val, 31), msa_combine_s32(m0, m0));
v2u64 v1 = msa_paddlq_u32(v0);
return (int)msa_getq_lane_u64(v1, 0) + ((int)msa_getq_lane_u64(v1, 1) << 2);
}
inline int v_signmask(const v_int32x4& a)
{ return v_signmask(v_reinterpret_as_u32(a)); }
inline int v_signmask(const v_float32x4& a)
{ return v_signmask(v_reinterpret_as_u32(a)); }
inline int v_signmask(const v_uint64x2& a)
{
v2u64 v0 = msa_shrq_n_u64(a.val, 63);
return (int)msa_getq_lane_u64(v0, 0) + ((int)msa_getq_lane_u64(v0, 1) << 1);
}
inline int v_signmask(const v_int64x2& a)
{ return v_signmask(v_reinterpret_as_u64(a)); }
inline int v_signmask(const v_float64x2& a)
{ return v_signmask(v_reinterpret_as_u64(a)); }
inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); }
inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); }
#define OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(_Tpvec, _Tpvec2, suffix, shift) \
inline bool v_check_all(const v_##_Tpvec& a) \
{ \
_Tpvec2 v0 = msa_shrq_n_##suffix(msa_mvnq_##suffix(a.val), shift); \
v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \
return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) == 0; \
} \
inline bool v_check_any(const v_##_Tpvec& a) \
{ \
_Tpvec2 v0 = msa_shrq_n_##suffix(a.val, shift); \
v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \
return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) != 0; \
}
OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint8x16, v16u8, u8, 7)
OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint16x8, v8u16, u16, 15)
OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint32x4, v4u32, u32, 31)
OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint64x2, v2u64, u64, 63)
inline bool v_check_all(const v_int8x16& a)
{ return v_check_all(v_reinterpret_as_u8(a)); }
inline bool v_check_all(const v_int16x8& a)
{ return v_check_all(v_reinterpret_as_u16(a)); }
inline bool v_check_all(const v_int32x4& a)
{ return v_check_all(v_reinterpret_as_u32(a)); }
inline bool v_check_all(const v_float32x4& a)
{ return v_check_all(v_reinterpret_as_u32(a)); }
inline bool v_check_any(const v_int8x16& a)
{ return v_check_any(v_reinterpret_as_u8(a)); }
inline bool v_check_any(const v_int16x8& a)
{ return v_check_any(v_reinterpret_as_u16(a)); }
inline bool v_check_any(const v_int32x4& a)
{ return v_check_any(v_reinterpret_as_u32(a)); }
inline bool v_check_any(const v_float32x4& a)
{ return v_check_any(v_reinterpret_as_u32(a)); }
inline bool v_check_all(const v_int64x2& a)
{ return v_check_all(v_reinterpret_as_u64(a)); }
inline bool v_check_all(const v_float64x2& a)
{ return v_check_all(v_reinterpret_as_u64(a)); }
inline bool v_check_any(const v_int64x2& a)
{ return v_check_any(v_reinterpret_as_u64(a)); }
inline bool v_check_any(const v_float64x2& a)
{ return v_check_any(v_reinterpret_as_u64(a)); }
/* v_select */
#define OPENCV_HAL_IMPL_MSA_SELECT(_Tpvec, _Tpv, _Tpvu) \
inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_bslq_u8(MSA_TPV_REINTERPRET(_Tpvu, mask.val), \
MSA_TPV_REINTERPRET(_Tpvu, b.val), MSA_TPV_REINTERPRET(_Tpvu, a.val)))); \
}
OPENCV_HAL_IMPL_MSA_SELECT(v_uint8x16, v16u8, v16u8)
OPENCV_HAL_IMPL_MSA_SELECT(v_int8x16, v16i8, v16u8)
OPENCV_HAL_IMPL_MSA_SELECT(v_uint16x8, v8u16, v16u8)
OPENCV_HAL_IMPL_MSA_SELECT(v_int16x8, v8i16, v16u8)
OPENCV_HAL_IMPL_MSA_SELECT(v_uint32x4, v4u32, v16u8)
OPENCV_HAL_IMPL_MSA_SELECT(v_int32x4, v4i32, v16u8)
OPENCV_HAL_IMPL_MSA_SELECT(v_float32x4, v4f32, v16u8)
OPENCV_HAL_IMPL_MSA_SELECT(v_float64x2, v2f64, v16u8)
#define OPENCV_HAL_IMPL_MSA_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix, ssuffix, _Tpv, _Tpvs) \
inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \
{ \
_Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \
_Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \
b0.val = msa_paddlq_##suffix(a_lo); \
b1.val = msa_paddlq_##suffix(a_hi); \
} \
inline _Tpwvec v_expand_low(const _Tpvec& a) \
{ \
_Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \
return _Tpwvec(msa_paddlq_##suffix(a_lo)); \
} \
inline _Tpwvec v_expand_high(const _Tpvec& a) \
{ \
_Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \
return _Tpwvec(msa_paddlq_##suffix(a_hi)); \
} \
inline _Tpwvec v_load_expand(const _Tp* ptr) \
{ \
return _Tpwvec(msa_movl_##suffix(msa_ld1_##suffix(ptr))); \
}
OPENCV_HAL_IMPL_MSA_EXPAND(v_uint8x16, v_uint16x8, uchar, u8, s8, v16u8, v16i8)
OPENCV_HAL_IMPL_MSA_EXPAND(v_int8x16, v_int16x8, schar, s8, s8, v16i8, v16i8)
OPENCV_HAL_IMPL_MSA_EXPAND(v_uint16x8, v_uint32x4, ushort, u16, s16, v8u16, v8i16)
OPENCV_HAL_IMPL_MSA_EXPAND(v_int16x8, v_int32x4, short, s16, s16, v8i16, v8i16)
OPENCV_HAL_IMPL_MSA_EXPAND(v_uint32x4, v_uint64x2, uint, u32, s32, v4u32, v4i32)
OPENCV_HAL_IMPL_MSA_EXPAND(v_int32x4, v_int64x2, int, s32, s32, v4i32, v4i32)
inline v_uint32x4 v_load_expand_q(const uchar* ptr)
{
return v_uint32x4((v4u32){ptr[0], ptr[1], ptr[2], ptr[3]});
}
inline v_int32x4 v_load_expand_q(const schar* ptr)
{
return v_int32x4((v4i32){ptr[0], ptr[1], ptr[2], ptr[3]});
}
/* v_zip, v_combine_low, v_combine_high, v_recombine */
#define OPENCV_HAL_IMPL_MSA_UNPACKS(_Tpvec, _Tpv, _Tpvs, ssuffix) \
inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \
{ \
b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \
b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \
} \
inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \
} \
inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \
} \
inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \
{ \
c.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \
d.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \
}
OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint8x16, v16u8, v16i8, s8)
OPENCV_HAL_IMPL_MSA_UNPACKS(v_int8x16, v16i8, v16i8, s8)
OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint16x8, v8u16, v8i16, s16)
OPENCV_HAL_IMPL_MSA_UNPACKS(v_int16x8, v8i16, v8i16, s16)
OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint32x4, v4u32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_UNPACKS(v_int32x4, v4i32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_UNPACKS(v_float32x4, v4f32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_UNPACKS(v_float64x2, v2f64, v2i64, s64)
/* v_extract */
#define OPENCV_HAL_IMPL_MSA_EXTRACT(_Tpvec, _Tpv, _Tpvs, suffix) \
template <int s> \
inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), s))); \
}
OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint8x16, v16u8, v16i8, s8)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_int8x16, v16i8, v16i8, s8)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint16x8, v8u16, v8i16, s16)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_int16x8, v8i16, v8i16, s16)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint32x4, v4u32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_int32x4, v4i32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint64x2, v2u64, v2i64, s64)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_int64x2, v2i64, v2i64, s64)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_float32x4, v4f32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_EXTRACT(v_float64x2, v2f64, v2i64, s64)
/* v_round, v_floor, v_ceil, v_trunc */
inline v_int32x4 v_round(const v_float32x4& a)
{
return v_int32x4(msa_cvttintq_s32_f32(a.val));
}
inline v_int32x4 v_floor(const v_float32x4& a)
{
v4i32 a1 = msa_cvttintq_s32_f32(a.val);
return v_int32x4(msa_addq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(msa_cvtfintq_f32_s32(a1), a.val))));
}
inline v_int32x4 v_ceil(const v_float32x4& a)
{
v4i32 a1 = msa_cvttintq_s32_f32(a.val);
return v_int32x4(msa_subq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(a.val, msa_cvtfintq_f32_s32(a1)))));
}
inline v_int32x4 v_trunc(const v_float32x4& a)
{
return v_int32x4(msa_cvttruncq_s32_f32(a.val));
}
inline v_int32x4 v_round(const v_float64x2& a)
{
return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_dupq_n_s64(0)));
}
inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b)
{
return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_cvttintq_s64_f64(b.val)));
}
inline v_int32x4 v_floor(const v_float64x2& a)
{
v2f64 a1 = msa_cvtrintq_f64(a.val);
return v_int32x4(msa_pack_s64(msa_addq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a1, a.val))), msa_dupq_n_s64(0)));
}
inline v_int32x4 v_ceil(const v_float64x2& a)
{
v2f64 a1 = msa_cvtrintq_f64(a.val);
return v_int32x4(msa_pack_s64(msa_subq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a.val, a1))), msa_dupq_n_s64(0)));
}
inline v_int32x4 v_trunc(const v_float64x2& a)
{
return v_int32x4(msa_pack_s64(msa_cvttruncq_s64_f64(a.val), msa_dupq_n_s64(0)));
}
#define OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(_Tpvec, _Tpv, _Tpvs, ssuffix) \
inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \
const _Tpvec& a2, const _Tpvec& a3, \
_Tpvec& b0, _Tpvec& b1, \
_Tpvec& b2, _Tpvec& b3) \
{ \
_Tpv t00 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \
_Tpv t01 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \
_Tpv t10 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \
_Tpv t11 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \
b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \
b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \
b2.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \
b3.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \
}
OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_uint32x4, v4u32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_int32x4, v4i32, v4i32, s32)
OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_float32x4, v4f32, v4i32, s32)
#define OPENCV_HAL_IMPL_MSA_INTERLEAVED(_Tpvec, _Tp, suffix) \
inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \
{ \
msa_ld2q_##suffix(ptr, &a.val, &b.val); \
} \
inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \
{ \
msa_ld3q_##suffix(ptr, &a.val, &b.val, &c.val); \
} \
inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \
v_##_Tpvec& c, v_##_Tpvec& d) \
{ \
msa_ld4q_##suffix(ptr, &a.val, &b.val, &c.val, &d.val); \
} \
inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \
{ \
msa_st2q_##suffix(ptr, a.val, b.val); \
} \
inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \
const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \
{ \
msa_st3q_##suffix(ptr, a.val, b.val, c.val); \
} \
inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \
const v_##_Tpvec& c, const v_##_Tpvec& d, \
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \
{ \
msa_st4q_##suffix(ptr, a.val, b.val, c.val, d.val); \
}
OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint8x16, uchar, u8)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(int8x16, schar, s8)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint16x8, ushort, u16)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(int16x8, short, s16)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint32x4, unsigned, u32)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(int32x4, int, s32)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(float32x4, float, f32)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint64x2, uint64, u64)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(int64x2, int64, s64)
OPENCV_HAL_IMPL_MSA_INTERLEAVED(float64x2, double, f64)
/* v_cvt_f32, v_cvt_f64, v_cvt_f64_high */
inline v_float32x4 v_cvt_f32(const v_int32x4& a)
{
return v_float32x4(msa_cvtfintq_f32_s32(a.val));
}
inline v_float32x4 v_cvt_f32(const v_float64x2& a)
{
return v_float32x4(msa_cvtfq_f32_f64(a.val, msa_dupq_n_f64(0.0f)));
}
inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b)
{
return v_float32x4(msa_cvtfq_f32_f64(a.val, b.val));
}
inline v_float64x2 v_cvt_f64(const v_int32x4& a)
{
return v_float64x2(msa_cvtflq_f64_f32(msa_cvtfintq_f32_s32(a.val)));
}
inline v_float64x2 v_cvt_f64_high(const v_int32x4& a)
{
return v_float64x2(msa_cvtfhq_f64_f32(msa_cvtfintq_f32_s32(a.val)));
}
inline v_float64x2 v_cvt_f64(const v_float32x4& a)
{
return v_float64x2(msa_cvtflq_f64_f32(a.val));
}
inline v_float64x2 v_cvt_f64_high(const v_float32x4& a)
{
return v_float64x2(msa_cvtfhq_f64_f32(a.val));
}
inline v_float64x2 v_cvt_f64(const v_int64x2& a)
{
return v_float64x2(msa_cvtfintq_f64_s64(a.val));
}
////////////// Lookup table access ////////////////////
inline v_int8x16 v_lut(const schar* tab, const int* idx)
{
schar CV_DECL_ALIGNED(32) elems[16] =
{
tab[idx[ 0]],
tab[idx[ 1]],
tab[idx[ 2]],
tab[idx[ 3]],
tab[idx[ 4]],
tab[idx[ 5]],
tab[idx[ 6]],
tab[idx[ 7]],
tab[idx[ 8]],
tab[idx[ 9]],
tab[idx[10]],
tab[idx[11]],
tab[idx[12]],
tab[idx[13]],
tab[idx[14]],
tab[idx[15]]
};
return v_int8x16(msa_ld1q_s8(elems));
}
inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx)
{
schar CV_DECL_ALIGNED(32) elems[16] =
{
tab[idx[0]],
tab[idx[0] + 1],
tab[idx[1]],
tab[idx[1] + 1],
tab[idx[2]],
tab[idx[2] + 1],
tab[idx[3]],
tab[idx[3] + 1],
tab[idx[4]],
tab[idx[4] + 1],
tab[idx[5]],
tab[idx[5] + 1],
tab[idx[6]],
tab[idx[6] + 1],
tab[idx[7]],
tab[idx[7] + 1]
};
return v_int8x16(msa_ld1q_s8(elems));
}
inline v_int8x16 v_lut_quads(const schar* tab, const int* idx)
{
schar CV_DECL_ALIGNED(32) elems[16] =
{
tab[idx[0]],
tab[idx[0] + 1],
tab[idx[0] + 2],
tab[idx[0] + 3],
tab[idx[1]],
tab[idx[1] + 1],
tab[idx[1] + 2],
tab[idx[1] + 3],
tab[idx[2]],
tab[idx[2] + 1],
tab[idx[2] + 2],
tab[idx[2] + 3],
tab[idx[3]],
tab[idx[3] + 1],
tab[idx[3] + 2],
tab[idx[3] + 3]
};
return v_int8x16(msa_ld1q_s8(elems));
}
inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); }
inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); }
inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); }
inline v_int16x8 v_lut(const short* tab, const int* idx)
{
short CV_DECL_ALIGNED(32) elems[8] =
{
tab[idx[0]],
tab[idx[1]],
tab[idx[2]],
tab[idx[3]],
tab[idx[4]],
tab[idx[5]],
tab[idx[6]],
tab[idx[7]]
};
return v_int16x8(msa_ld1q_s16(elems));
}
inline v_int16x8 v_lut_pairs(const short* tab, const int* idx)
{
short CV_DECL_ALIGNED(32) elems[8] =
{
tab[idx[0]],
tab[idx[0] + 1],
tab[idx[1]],
tab[idx[1] + 1],
tab[idx[2]],
tab[idx[2] + 1],
tab[idx[3]],
tab[idx[3] + 1]
};
return v_int16x8(msa_ld1q_s16(elems));
}
inline v_int16x8 v_lut_quads(const short* tab, const int* idx)
{
return v_int16x8(msa_combine_s16(msa_ld1_s16(tab + idx[0]), msa_ld1_s16(tab + idx[1])));
}
inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); }
inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); }
inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); }
inline v_int32x4 v_lut(const int* tab, const int* idx)
{
int CV_DECL_ALIGNED(32) elems[4] =
{
tab[idx[0]],
tab[idx[1]],
tab[idx[2]],
tab[idx[3]]
};
return v_int32x4(msa_ld1q_s32(elems));
}
inline v_int32x4 v_lut_pairs(const int* tab, const int* idx)
{
return v_int32x4(msa_combine_s32(msa_ld1_s32(tab + idx[0]), msa_ld1_s32(tab + idx[1])));
}
inline v_int32x4 v_lut_quads(const int* tab, const int* idx)
{
return v_int32x4(msa_ld1q_s32(tab + idx[0]));
}
inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); }
inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); }
inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); }
inline v_int64x2 v_lut(const int64_t* tab, const int* idx)
{
return v_int64x2(msa_combine_s64(msa_create_s64(tab[idx[0]]), msa_create_s64(tab[idx[1]])));
}
inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx)
{
return v_int64x2(msa_ld1q_s64(tab + idx[0]));
}
inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); }
inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); }
inline v_float32x4 v_lut(const float* tab, const int* idx)
{
float CV_DECL_ALIGNED(32) elems[4] =
{
tab[idx[0]],
tab[idx[1]],
tab[idx[2]],
tab[idx[3]]
};
return v_float32x4(msa_ld1q_f32(elems));
}
inline v_float32x4 v_lut_pairs(const float* tab, const int* idx)
{
uint64 CV_DECL_ALIGNED(32) elems[2] =
{
*(uint64*)(tab + idx[0]),
*(uint64*)(tab + idx[1])
};
return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ld1q_u64(elems)));
}
inline v_float32x4 v_lut_quads(const float* tab, const int* idx)
{
return v_float32x4(msa_ld1q_f32(tab + idx[0]));
}
inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec)
{
int CV_DECL_ALIGNED(32) idx[4];
v_store_aligned(idx, idxvec);
return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]);
}
inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec)
{
unsigned CV_DECL_ALIGNED(32) elems[4] =
{
tab[msa_getq_lane_s32(idxvec.val, 0)],
tab[msa_getq_lane_s32(idxvec.val, 1)],
tab[msa_getq_lane_s32(idxvec.val, 2)],
tab[msa_getq_lane_s32(idxvec.val, 3)]
};
return v_uint32x4(msa_ld1q_u32(elems));
}
inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec)
{
int CV_DECL_ALIGNED(32) idx[4];
v_store_aligned(idx, idxvec);
return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]);
}
inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y)
{
int CV_DECL_ALIGNED(32) idx[4];
v_store_aligned(idx, idxvec);
v4f32 xy02 = msa_combine_f32(msa_ld1_f32(tab + idx[0]), msa_ld1_f32(tab + idx[2]));
v4f32 xy13 = msa_combine_f32(msa_ld1_f32(tab + idx[1]), msa_ld1_f32(tab + idx[3]));
x = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02))));
y = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02))));
}
inline v_int8x16 v_interleave_pairs(const v_int8x16& vec)
{
v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0705060403010200, 0x0F0D0E0C0B090A08}), msa_dupq_n_s8(0), vec.val));
return c;
}
inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec)
{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); }
inline v_int8x16 v_interleave_quads(const v_int8x16& vec)
{
v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0703060205010400, 0x0F0B0E0A0D090C08}), msa_dupq_n_s8(0), vec.val));
return c;
}
inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); }
inline v_int16x8 v_interleave_pairs(const v_int16x8& vec)
{
v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0003000100020000, 0x0007000500060004}), msa_dupq_n_s16(0), vec.val));
return c;
}
inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); }
inline v_int16x8 v_interleave_quads(const v_int16x8& vec)
{
v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0005000100040000, 0x0007000300060002}), msa_dupq_n_s16(0), vec.val));
return c;
}
inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); }
inline v_int32x4 v_interleave_pairs(const v_int32x4& vec)
{
v_int32x4 c;
c.val[0] = vec.val[0];
c.val[1] = vec.val[2];
c.val[2] = vec.val[1];
c.val[3] = vec.val[3];
return c;
}
inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); }
inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); }
inline v_int8x16 v_pack_triplets(const v_int8x16& vec)
{
v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0908060504020100, 0x131211100E0D0C0A}), msa_dupq_n_s8(0), vec.val));
return c;
}
inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); }
inline v_int16x8 v_pack_triplets(const v_int16x8& vec)
{
v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000200010000, 0x0009000800060005}), msa_dupq_n_s16(0), vec.val));
return c;
}
inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); }
inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; }
inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; }
inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; }
inline v_float64x2 v_lut(const double* tab, const int* idx)
{
double CV_DECL_ALIGNED(32) elems[2] =
{
tab[idx[0]],
tab[idx[1]]
};
return v_float64x2(msa_ld1q_f64(elems));
}
inline v_float64x2 v_lut_pairs(const double* tab, const int* idx)
{
return v_float64x2(msa_ld1q_f64(tab + idx[0]));
}
inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec)
{
int CV_DECL_ALIGNED(32) idx[4];
v_store_aligned(idx, idxvec);
return v_float64x2(tab[idx[0]], tab[idx[1]]);
}
inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y)
{
int CV_DECL_ALIGNED(32) idx[4];
v_store_aligned(idx, idxvec);
v2f64 xy0 = msa_ld1q_f64(tab + idx[0]);
v2f64 xy1 = msa_ld1q_f64(tab + idx[1]);
x = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvevq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0))));
y = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvodq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0))));
}
template<int i, typename _Tp>
inline typename _Tp::lane_type v_extract_n(const _Tp& a)
{
return v_rotate_right<i>(a).get0();
}
template<int i>
inline v_uint32x4 v_broadcast_element(const v_uint32x4& a)
{
return v_setall_u32(v_extract_n<i>(a));
}
template<int i>
inline v_int32x4 v_broadcast_element(const v_int32x4& a)
{
return v_setall_s32(v_extract_n<i>(a));
}
template<int i>
inline v_float32x4 v_broadcast_element(const v_float32x4& a)
{
return v_setall_f32(v_extract_n<i>(a));
}
////// FP16 support ///////
#if CV_FP16
inline v_float32x4 v_load_expand(const float16_t* ptr)
{
#ifndef msa_ld1_f16
v4f16 v = (v4f16)msa_ld1_s16((const short*)ptr);
#else
v4f16 v = msa_ld1_f16((const __fp16*)ptr);
#endif
return v_float32x4(msa_cvt_f32_f16(v));
}
inline void v_pack_store(float16_t* ptr, const v_float32x4& v)
{
v4f16 hv = msa_cvt_f16_f32(v.val);
#ifndef msa_st1_f16
msa_st1_s16((short*)ptr, (int16x4_t)hv);
#else
msa_st1_f16((__fp16*)ptr, hv);
#endif
}
#else
inline v_float32x4 v_load_expand(const float16_t* ptr)
{
float buf[4];
for( int i = 0; i < 4; i++ )
buf[i] = (float)ptr[i];
return v_load(buf);
}
inline void v_pack_store(float16_t* ptr, const v_float32x4& v)
{
float buf[4];
v_store(buf, v);
for( int i = 0; i < 4; i++ )
ptr[i] = (float16_t)buf[i];
}
#endif
inline void v_cleanup() {}
CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END
//! @endcond
}
#endif
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2009-12-11 Bernard first version
*/
#ifndef __S3C24X0_H__
#define __S3C24X0_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <rtthread.h>
/**
* @addtogroup S3C24X0
*/
/*@{*/
// Memory control
#define BWSCON (*(volatile unsigned *)0x48000000) //Bus width & wait status
#define BANKCON0 (*(volatile unsigned *)0x48000004) //Boot ROM control
#define BANKCON1 (*(volatile unsigned *)0x48000008) //BANK1 control
#define BANKCON2 (*(volatile unsigned *)0x4800000c) //BANK2 cControl
#define BANKCON3 (*(volatile unsigned *)0x48000010) //BANK3 control
#define BANKCON4 (*(volatile unsigned *)0x48000014) //BANK4 control
#define BANKCON5 (*(volatile unsigned *)0x48000018) //BANK5 control
#define BANKCON6 (*(volatile unsigned *)0x4800001c) //BANK6 control
#define BANKCON7 (*(volatile unsigned *)0x48000020) //BANK7 control
#define REFRESH (*(volatile unsigned *)0x48000024) //DRAM/SDRAM efresh
#define BANKSIZE (*(volatile unsigned *)0x48000028) //Flexible Bank Size
#define MRSRB6 (*(volatile unsigned *)0x4800002c) //Mode egister set for SDRAM
#define MRSRB7 (*(volatile unsigned *)0x48000030) //Mode egister set for SDRAM
// USB Host
// INTERRUPT
#define SRCPND (*(volatile unsigned *)0x4a000000) //Interrupt request status
#define INTMOD (*(volatile unsigned *)0x4a000004) //Interrupt mode control
#define INTMSK (*(volatile unsigned *)0x4a000008) //Interrupt mask control
#define PRIORITY (*(volatile unsigned *)0x4a00000c) //IRQ priority control
#define INTPND (*(volatile unsigned *)0x4a000010) //Interrupt request status
#define INTOFFSET (*(volatile unsigned *)0x4a000014) //Interruot request source offset
#define SUBSRCPND (*(volatile unsigned *)0x4a000018) //Sub source pending
#define INTSUBMSK (*(volatile unsigned *)0x4a00001c) //Interrupt sub mask
// DMA
#define DISRC0 (*(volatile unsigned *)0x4b000000) //DMA 0 Initial source
#define DISRCC0 (*(volatile unsigned *)0x4b000004) //DMA 0 Initial source control
#define DIDST0 (*(volatile unsigned *)0x4b000008) //DMA 0 Initial Destination
#define DIDSTC0 (*(volatile unsigned *)0x4b00000c) //DMA 0 Initial Destination control
#define DCON0 (*(volatile unsigned *)0x4b000010) //DMA 0 Control
#define DSTAT0 (*(volatile unsigned *)0x4b000014) //DMA 0 Status
#define DCSRC0 (*(volatile unsigned *)0x4b000018) //DMA 0 Current source
#define DCDST0 (*(volatile unsigned *)0x4b00001c) //DMA 0 Current destination
#define DMASKTRIG0 (*(volatile unsigned *)0x4b000020) //DMA 0 Mask trigger
#define DISRC1 (*(volatile unsigned *)0x4b000040) //DMA 1 Initial source
#define DISRCC1 (*(volatile unsigned *)0x4b000044) //DMA 1 Initial source control
#define DIDST1 (*(volatile unsigned *)0x4b000048) //DMA 1 Initial Destination
#define DIDSTC1 (*(volatile unsigned *)0x4b00004c) //DMA 1 Initial Destination control
#define DCON1 (*(volatile unsigned *)0x4b000050) //DMA 1 Control
#define DSTAT1 (*(volatile unsigned *)0x4b000054) //DMA 1 Status
#define DCSRC1 (*(volatile unsigned *)0x4b000058) //DMA 1 Current source
#define DCDST1 (*(volatile unsigned *)0x4b00005c) //DMA 1 Current destination
#define DMASKTRIG1 (*(volatile unsigned *)0x4b000060) //DMA 1 Mask trigger
#define DISRC2 (*(volatile unsigned *)0x4b000080) //DMA 2 Initial source
#define DISRCC2 (*(volatile unsigned *)0x4b000084) //DMA 2 Initial source control
#define DIDST2 (*(volatile unsigned *)0x4b000088) //DMA 2 Initial Destination
#define DIDSTC2 (*(volatile unsigned *)0x4b00008c) //DMA 2 Initial Destination control
#define DCON2 (*(volatile unsigned *)0x4b000090) //DMA 2 Control
#define DSTAT2 (*(volatile unsigned *)0x4b000094) //DMA 2 Status
#define DCSRC2 (*(volatile unsigned *)0x4b000098) //DMA 2 Current source
#define DCDST2 (*(volatile unsigned *)0x4b00009c) //DMA 2 Current destination
#define DMASKTRIG2 (*(volatile unsigned *)0x4b0000a0) //DMA 2 Mask trigger
#define DISRC3 (*(volatile unsigned *)0x4b0000c0) //DMA 3 Initial source
#define DISRCC3 (*(volatile unsigned *)0x4b0000c4) //DMA 3 Initial source control
#define DIDST3 (*(volatile unsigned *)0x4b0000c8) //DMA 3 Initial Destination
#define DIDSTC3 (*(volatile unsigned *)0x4b0000cc) //DMA 3 Initial Destination control
#define DCON3 (*(volatile unsigned *)0x4b0000d0) //DMA 3 Control
#define DSTAT3 (*(volatile unsigned *)0x4b0000d4) //DMA 3 Status
#define DCSRC3 (*(volatile unsigned *)0x4b0000d8) //DMA 3 Current source
#define DCDST3 (*(volatile unsigned *)0x4b0000dc) //DMA 3 Current destination
#define DMASKTRIG3 (*(volatile unsigned *)0x4b0000e0) //DMA 3 Mask trigger
// CLOCK & POWER MANAGEMENT
#define LOCKTIME (*(volatile unsigned *)0x4c000000) //PLL lock time counter
#define MPLLCON (*(volatile unsigned *)0x4c000004) //MPLL Control
#define UPLLCON (*(volatile unsigned *)0x4c000008) //UPLL Control
#define CLKCON (*(volatile unsigned *)0x4c00000c) //Clock generator control
#define CLKSLOW (*(volatile unsigned *)0x4c000010) //Slow clock control
#define CLKDIVN (*(volatile unsigned *)0x4c000014) //Clock divider control
#define CAMDIVN (*(volatile unsigned *)0x4c000018) //USB, CAM Clock divider control
// LCD CONTROLLER
#define LCDCON1 (*(volatile unsigned *)0x4d000000) //LCD control 1
#define LCDCON2 (*(volatile unsigned *)0x4d000004) //LCD control 2
#define LCDCON3 (*(volatile unsigned *)0x4d000008) //LCD control 3
#define LCDCON4 (*(volatile unsigned *)0x4d00000c) //LCD control 4
#define LCDCON5 (*(volatile unsigned *)0x4d000010) //LCD control 5
#define LCDSADDR1 (*(volatile unsigned *)0x4d000014) //STN/TFT Frame buffer start address 1
#define LCDSADDR2 (*(volatile unsigned *)0x4d000018) //STN/TFT Frame buffer start address 2
#define LCDSADDR3 (*(volatile unsigned *)0x4d00001c) //STN/TFT Virtual screen address set
#define REDLUT (*(volatile unsigned *)0x4d000020) //STN Red lookup table
#define GREENLUT (*(volatile unsigned *)0x4d000024) //STN Green lookup table
#define BLUELUT (*(volatile unsigned *)0x4d000028) //STN Blue lookup table
#define DITHMODE (*(volatile unsigned *)0x4d00004c) //STN Dithering mode
#define TPAL (*(volatile unsigned *)0x4d000050) //TFT Temporary palette
#define LCDINTPND (*(volatile unsigned *)0x4d000054) //LCD Interrupt pending
#define LCDSRCPND (*(volatile unsigned *)0x4d000058) //LCD Interrupt source
#define LCDINTMSK (*(volatile unsigned *)0x4d00005c) //LCD Interrupt mask
#define LPCSEL (*(volatile unsigned *)0x4d000060) //LPC3600 Control
#define PALETTE 0x4d000400 //Palette start address
// NAND flash
#define NFCONF (*(volatile unsigned *)0x4e000000) //NAND Flash configuration
#define NFCMD (*(volatile unsigned *)0x4e000004) //NADD Flash command
#define NFADDR (*(volatile unsigned *)0x4e000008) //NAND Flash address
#define NFDATA (*(volatile unsigned *)0x4e00000c) //NAND Flash data
#define NFSTAT (*(volatile unsigned *)0x4e000010) //NAND Flash operation status
#define NFECC (*(volatile unsigned *)0x4e000014) //NAND Flash ECC
#define NFECC0 (*(volatile unsigned *)0x4e000014)
#define NFECC1 (*(volatile unsigned *)0x4e000015)
#define NFECC2 (*(volatile unsigned *)0x4e000016)
// UART
#define U0BASE (*(volatile unsigned *)0x50000000) //UART 0 Line control
#define ULCON0 (*(volatile unsigned *)0x50000000) //UART 0 Line control
#define UCON0 (*(volatile unsigned *)0x50000004) //UART 0 Control
#define UFCON0 (*(volatile unsigned *)0x50000008) //UART 0 FIFO control
#define UMCON0 (*(volatile unsigned *)0x5000000c) //UART 0 Modem control
#define USTAT0 (*(volatile unsigned *)0x50000010) //UART 0 Tx/Rx status
#define URXB0 (*(volatile unsigned *)0x50000014) //UART 0 Rx error status
#define UFSTAT0 (*(volatile unsigned *)0x50000018) //UART 0 FIFO status
#define UMSTAT0 (*(volatile unsigned *)0x5000001c) //UART 0 Modem status
#define UBRD0 (*(volatile unsigned *)0x50000028) //UART 0 Baud ate divisor
#define U1BASE (*(volatile unsigned *)0x50004000) //UART 1 Line control
#define ULCON1 (*(volatile unsigned *)0x50004000) //UART 1 Line control
#define UCON1 (*(volatile unsigned *)0x50004004) //UART 1 Control
#define UFCON1 (*(volatile unsigned *)0x50004008) //UART 1 FIFO control
#define UMCON1 (*(volatile unsigned *)0x5000400c) //UART 1 Modem control
#define USTAT1 (*(volatile unsigned *)0x50004010) //UART 1 Tx/Rx status
#define URXB1 (*(volatile unsigned *)0x50004014) //UART 1 Rx error status
#define UFSTAT1 (*(volatile unsigned *)0x50004018) //UART 1 FIFO status
#define UMSTAT1 (*(volatile unsigned *)0x5000401c) //UART 1 Modem status
#define UBRD1 (*(volatile unsigned *)0x50004028) //UART 1 Baud ate divisor
#define U2BASE *(volatile unsigned *)0x50008000 //UART 2 Line control
#define ULCON2 (*(volatile unsigned *)0x50008000) //UART 2 Line control
#define UCON2 (*(volatile unsigned *)0x50008004) //UART 2 Control
#define UFCON2 (*(volatile unsigned *)0x50008008) //UART 2 FIFO control
#define UMCON2 (*(volatile unsigned *)0x5000800c) //UART 2 Modem control
#define USTAT2 (*(volatile unsigned *)0x50008010) //UART 2 Tx/Rx status
#define URXB2 (*(volatile unsigned *)0x50008014) //UART 2 Rx error status
#define UFSTAT2 (*(volatile unsigned *)0x50008018) //UART 2 FIFO status
#define UMSTAT2 (*(volatile unsigned *)0x5000801c) //UART 2 Modem status
#define UBRD2 (*(volatile unsigned *)0x50008028) //UART 2 Baud ate divisor
#ifdef __BIG_ENDIAN
#define UTXH0 (*(volatile unsigned char *)0x50000023) //UART 0 Transmission Hold
#define URXH0 (*(volatile unsigned char *)0x50000027) //UART 0 Receive buffer
#define UTXH1 (*(volatile unsigned char *)0x50004023) //UART 1 Transmission Hold
#define URXH1 (*(volatile unsigned char *)0x50004027) //UART 1 Receive buffer
#define UTXH2 (*(volatile unsigned char *)0x50008023) //UART 2 Transmission Hold
#define URXH2 (*(volatile unsigned char *)0x50008027) //UART 2 Receive buffer
#define WrUTXH0(ch) (*(volatile unsigned char *)0x50000023)=(unsigned char)(ch)
#define RdURXH0() (*(volatile unsigned char *)0x50000027)
#define WrUTXH1(ch) (*(volatile unsigned char *)0x50004023)=(unsigned char)(ch)
#define RdURXH1() (*(volatile unsigned char *)0x50004027)
#define WrUTXH2(ch) (*(volatile unsigned char *)0x50008023)=(unsigned char)(ch)
#define RdURXH2() (*(volatile unsigned char *)0x50008027)
#else //Little Endian
#define UTXH0 (*(volatile unsigned char *)0x50000020) //UART 0 Transmission Hold
#define URXH0 (*(volatile unsigned char *)0x50000024) //UART 0 Receive buffer
#define UTXH1 (*(volatile unsigned char *)0x50004020) //UART 1 Transmission Hold
#define URXH1 (*(volatile unsigned char *)0x50004024) //UART 1 Receive buffer
#define UTXH2 (*(volatile unsigned char *)0x50008020) //UART 2 Transmission Hold
#define URXH2 (*(volatile unsigned char *)0x50008024) //UART 2 Receive buffer
#define WrUTXH0(ch) (*(volatile unsigned char *)0x50000020)=(unsigned char)(ch)
#define RdURXH0() (*(volatile unsigned char *)0x50000024)
#define WrUTXH1(ch) (*(volatile unsigned char *)0x50004020)=(unsigned char)(ch)
#define RdURXH1() (*(volatile unsigned char *)0x50004024)
#define WrUTXH2(ch) (*(volatile unsigned char *)0x50008020)=(unsigned char)(ch)
#define RdURXH2() (*(volatile unsigned char *)0x50008024)
#endif
// PWM TIMER
#define TCFG0 (*(volatile unsigned *)0x51000000) //Timer 0 configuration
#define TCFG1 (*(volatile unsigned *)0x51000004) //Timer 1 configuration
#define TCON (*(volatile unsigned *)0x51000008) //Timer control
#define TCNTB0 (*(volatile unsigned *)0x5100000c) //Timer count buffer 0
#define TCMPB0 (*(volatile unsigned *)0x51000010) //Timer compare buffer 0
#define TCNTO0 (*(volatile unsigned *)0x51000014) //Timer count observation 0
#define TCNTB1 (*(volatile unsigned *)0x51000018) //Timer count buffer 1
#define TCMPB1 (*(volatile unsigned *)0x5100001c) //Timer compare buffer 1
#define TCNTO1 (*(volatile unsigned *)0x51000020) //Timer count observation 1
#define TCNTB2 (*(volatile unsigned *)0x51000024) //Timer count buffer 2
#define TCMPB2 (*(volatile unsigned *)0x51000028) //Timer compare buffer 2
#define TCNTO2 (*(volatile unsigned *)0x5100002c) //Timer count observation 2
#define TCNTB3 (*(volatile unsigned *)0x51000030) //Timer count buffer 3
#define TCMPB3 (*(volatile unsigned *)0x51000034) //Timer compare buffer 3
#define TCNTO3 (*(volatile unsigned *)0x51000038) //Timer count observation 3
#define TCNTB4 (*(volatile unsigned *)0x5100003c) //Timer count buffer 4
#define TCNTO4 (*(volatile unsigned *)0x51000040) //Timer count observation 4
// Added for 2440
#define FLTOUT (*(volatile unsigned *)0x560000c0) // Filter output(Read only)
#define DSC0 (*(volatile unsigned *)0x560000c4) // Strength control register 0
#define DSC1 (*(volatile unsigned *)0x560000c8) // Strength control register 1
#define MSLCON (*(volatile unsigned *)0x560000cc) // Memory sleep control register
// USB DEVICE
#ifdef __BIG_ENDIAN
#define FUNC_ADDR_REG (*(volatile unsigned char *)0x52000143) //Function address
#define PWR_REG (*(volatile unsigned char *)0x52000147) //Power management
#define EP_INT_REG (*(volatile unsigned char *)0x5200014b) //EP Interrupt pending and clear
#define USB_INT_REG (*(volatile unsigned char *)0x5200015b) //USB Interrupt pending and clear
#define EP_INT_EN_REG (*(volatile unsigned char *)0x5200015f) //Interrupt enable
#define USB_INT_EN_REG (*(volatile unsigned char *)0x5200016f)
#define FRAME_NUM1_REG (*(volatile unsigned char *)0x52000173) //Frame number lower byte
#define FRAME_NUM2_REG (*(volatile unsigned char *)0x52000177) //Frame number higher byte
#define INDEX_REG (*(volatile unsigned char *)0x5200017b) //Register index
#define MAXP_REG (*(volatile unsigned char *)0x52000183) //Endpoint max packet
#define EP0_CSR (*(volatile unsigned char *)0x52000187) //Endpoint 0 status
#define IN_CSR1_REG (*(volatile unsigned char *)0x52000187) //In endpoint control status
#define IN_CSR2_REG (*(volatile unsigned char *)0x5200018b)
#define OUT_CSR1_REG (*(volatile unsigned char *)0x52000193) //Out endpoint control status
#define OUT_CSR2_REG (*(volatile unsigned char *)0x52000197)
#define OUT_FIFO_CNT1_REG (*(volatile unsigned char *)0x5200019b) //Endpoint out write count
#define OUT_FIFO_CNT2_REG (*(volatile unsigned char *)0x5200019f)
#define EP0_FIFO (*(volatile unsigned char *)0x520001c3) //Endpoint 0 FIFO
#define EP1_FIFO (*(volatile unsigned char *)0x520001c7) //Endpoint 1 FIFO
#define EP2_FIFO (*(volatile unsigned char *)0x520001cb) //Endpoint 2 FIFO
#define EP3_FIFO (*(volatile unsigned char *)0x520001cf) //Endpoint 3 FIFO
#define EP4_FIFO (*(volatile unsigned char *)0x520001d3) //Endpoint 4 FIFO
#define EP1_DMA_CON (*(volatile unsigned char *)0x52000203) //EP1 DMA interface control
#define EP1_DMA_UNIT (*(volatile unsigned char *)0x52000207) //EP1 DMA Tx unit counter
#define EP1_DMA_FIFO (*(volatile unsigned char *)0x5200020b) //EP1 DMA Tx FIFO counter
#define EP1_DMA_TTC_L (*(volatile unsigned char *)0x5200020f) //EP1 DMA total Tx counter
#define EP1_DMA_TTC_M (*(volatile unsigned char *)0x52000213)
#define EP1_DMA_TTC_H (*(volatile unsigned char *)0x52000217)
#define EP2_DMA_CON (*(volatile unsigned char *)0x5200021b) //EP2 DMA interface control
#define EP2_DMA_UNIT (*(volatile unsigned char *)0x5200021f) //EP2 DMA Tx unit counter
#define EP2_DMA_FIFO (*(volatile unsigned char *)0x52000223) //EP2 DMA Tx FIFO counter
#define EP2_DMA_TTC_L (*(volatile unsigned char *)0x52000227) //EP2 DMA total Tx counter
#define EP2_DMA_TTC_M (*(volatile unsigned char *)0x5200022b)
#define EP2_DMA_TTC_H (*(volatile unsigned char *)0x5200022f)
#define EP3_DMA_CON (*(volatile unsigned char *)0x52000243) //EP3 DMA interface control
#define EP3_DMA_UNIT (*(volatile unsigned char *)0x52000247) //EP3 DMA Tx unit counter
#define EP3_DMA_FIFO (*(volatile unsigned char *)0x5200024b) //EP3 DMA Tx FIFO counter
#define EP3_DMA_TTC_L (*(volatile unsigned char *)0x5200024f) //EP3 DMA total Tx counter
#define EP3_DMA_TTC_M (*(volatile unsigned char *)0x52000253)
#define EP3_DMA_TTC_H (*(volatile unsigned char *)0x52000257)
#define EP4_DMA_CON (*(volatile unsigned char *)0x5200025b) //EP4 DMA interface control
#define EP4_DMA_UNIT (*(volatile unsigned char *)0x5200025f) //EP4 DMA Tx unit counter
#define EP4_DMA_FIFO (*(volatile unsigned char *)0x52000263) //EP4 DMA Tx FIFO counter
#define EP4_DMA_TTC_L (*(volatile unsigned char *)0x52000267) //EP4 DMA total Tx counter
#define EP4_DMA_TTC_M (*(volatile unsigned char *)0x5200026b)
#define EP4_DMA_TTC_H (*(volatile unsigned char *)0x5200026f)
#else // Little Endian
#define FUNC_ADDR_REG (*(volatile unsigned char *)0x52000140) //Function address
#define PWR_REG (*(volatile unsigned char *)0x52000144) //Power management
#define EP_INT_REG (*(volatile unsigned char *)0x52000148) //EP Interrupt pending and clear
#define USB_INT_REG (*(volatile unsigned char *)0x52000158) //USB Interrupt pending and clear
#define EP_INT_EN_REG (*(volatile unsigned char *)0x5200015c) //Interrupt enable
#define USB_INT_EN_REG (*(volatile unsigned char *)0x5200016c)
#define FRAME_NUM1_REG (*(volatile unsigned char *)0x52000170) //Frame number lower byte
#define FRAME_NUM2_REG (*(volatile unsigned char *)0x52000174) //Frame number higher byte
#define INDEX_REG (*(volatile unsigned char *)0x52000178) //Register index
#define MAXP_REG (*(volatile unsigned char *)0x52000180) //Endpoint max packet
#define EP0_CSR (*(volatile unsigned char *)0x52000184) //Endpoint 0 status
#define IN_CSR1_REG (*(volatile unsigned char *)0x52000184) //In endpoint control status
#define IN_CSR2_REG (*(volatile unsigned char *)0x52000188)
#define OUT_CSR1_REG (*(volatile unsigned char *)0x52000190) //Out endpoint control status
#define OUT_CSR2_REG (*(volatile unsigned char *)0x52000194)
#define OUT_FIFO_CNT1_REG (*(volatile unsigned char *)0x52000198) //Endpoint out write count
#define OUT_FIFO_CNT2_REG (*(volatile unsigned char *)0x5200019c)
#define EP0_FIFO (*(volatile unsigned char *)0x520001c0) //Endpoint 0 FIFO
#define EP1_FIFO (*(volatile unsigned char *)0x520001c4) //Endpoint 1 FIFO
#define EP2_FIFO (*(volatile unsigned char *)0x520001c8) //Endpoint 2 FIFO
#define EP3_FIFO (*(volatile unsigned char *)0x520001cc) //Endpoint 3 FIFO
#define EP4_FIFO (*(volatile unsigned char *)0x520001d0) //Endpoint 4 FIFO
#define EP1_DMA_CON (*(volatile unsigned char *)0x52000200) //EP1 DMA interface control
#define EP1_DMA_UNIT (*(volatile unsigned char *)0x52000204) //EP1 DMA Tx unit counter
#define EP1_DMA_FIFO (*(volatile unsigned char *)0x52000208) //EP1 DMA Tx FIFO counter
#define EP1_DMA_TTC_L (*(volatile unsigned char *)0x5200020c) //EP1 DMA total Tx counter
#define EP1_DMA_TTC_M (*(volatile unsigned char *)0x52000210)
#define EP1_DMA_TTC_H (*(volatile unsigned char *)0x52000214)
#define EP2_DMA_CON (*(volatile unsigned char *)0x52000218) //EP2 DMA interface control
#define EP2_DMA_UNIT (*(volatile unsigned char *)0x5200021c) //EP2 DMA Tx unit counter
#define EP2_DMA_FIFO (*(volatile unsigned char *)0x52000220) //EP2 DMA Tx FIFO counter
#define EP2_DMA_TTC_L (*(volatile unsigned char *)0x52000224) //EP2 DMA total Tx counter
#define EP2_DMA_TTC_M (*(volatile unsigned char *)0x52000228)
#define EP2_DMA_TTC_H (*(volatile unsigned char *)0x5200022c)
#define EP3_DMA_CON (*(volatile unsigned char *)0x52000240) //EP3 DMA interface control
#define EP3_DMA_UNIT (*(volatile unsigned char *)0x52000244) //EP3 DMA Tx unit counter
#define EP3_DMA_FIFO (*(volatile unsigned char *)0x52000248) //EP3 DMA Tx FIFO counter
#define EP3_DMA_TTC_L (*(volatile unsigned char *)0x5200024c) //EP3 DMA total Tx counter
#define EP3_DMA_TTC_M (*(volatile unsigned char *)0x52000250)
#define EP3_DMA_TTC_H (*(volatile unsigned char *)0x52000254)
#define EP4_DMA_CON (*(volatile unsigned char *)0x52000258) //EP4 DMA interface control
#define EP4_DMA_UNIT (*(volatile unsigned char *)0x5200025c) //EP4 DMA Tx unit counter
#define EP4_DMA_FIFO (*(volatile unsigned char *)0x52000260) //EP4 DMA Tx FIFO counter
#define EP4_DMA_TTC_L (*(volatile unsigned char *)0x52000264) //EP4 DMA total Tx counter
#define EP4_DMA_TTC_M (*(volatile unsigned char *)0x52000268)
#define EP4_DMA_TTC_H (*(volatile unsigned char *)0x5200026c)
#endif // __BIG_ENDIAN
// WATCH DOG TIMER
#define WTCON (*(volatile unsigned *)0x53000000) //Watch-dog timer mode
#define WTDAT (*(volatile unsigned *)0x53000004) //Watch-dog timer data
#define WTCNT (*(volatile unsigned *)0x53000008) //Eatch-dog timer count
// IIC
#define IICCON (*(volatile unsigned *)0x54000000) //IIC control
#define IICSTAT (*(volatile unsigned *)0x54000004) //IIC status
#define IICADD (*(volatile unsigned *)0x54000008) //IIC address
#define IICDS (*(volatile unsigned *)0x5400000c) //IIC data shift
// IIS
#define IISCON (*(volatile unsigned *)0x55000000) //IIS Control
#define IISMOD (*(volatile unsigned *)0x55000004) //IIS Mode
#define IISPSR (*(volatile unsigned *)0x55000008) //IIS Prescaler
#define IISFCON (*(volatile unsigned *)0x5500000c) //IIS FIFO control
#ifdef __BIG_ENDIAN
#define IISFIFO ((volatile unsigned short *)0x55000012) //IIS FIFO entry
#else //Little Endian
#define IISFIFO ((volatile unsigned short *)0x55000010) //IIS FIFO entry
#endif
// I/O PORT
#define GPACON (*(volatile unsigned *)0x56000000) //Port A control
#define GPADAT (*(volatile unsigned *)0x56000004) //Port A data
#define GPBCON (*(volatile unsigned *)0x56000010) //Port B control
#define GPBDAT (*(volatile unsigned *)0x56000014) //Port B data
#define GPBUP (*(volatile unsigned *)0x56000018) //Pull-up control B
#define GPCCON (*(volatile unsigned *)0x56000020) //Port C control
#define GPCDAT (*(volatile unsigned *)0x56000024) //Port C data
#define GPCUP (*(volatile unsigned *)0x56000028) //Pull-up control C
#define GPDCON (*(volatile unsigned *)0x56000030) //Port D control
#define GPDDAT (*(volatile unsigned *)0x56000034) //Port D data
#define GPDUP (*(volatile unsigned *)0x56000038) //Pull-up control D
#define GPECON (*(volatile unsigned *)0x56000040) //Port E control
#define GPEDAT (*(volatile unsigned *)0x56000044) //Port E data
#define GPEUP (*(volatile unsigned *)0x56000048) //Pull-up control E
#define GPFCON (*(volatile unsigned *)0x56000050) //Port F control
#define GPFDAT (*(volatile unsigned *)0x56000054) //Port F data
#define GPFUP (*(volatile unsigned *)0x56000058) //Pull-up control F
#define GPGCON (*(volatile unsigned *)0x56000060) //Port G control
#define GPGDAT (*(volatile unsigned *)0x56000064) //Port G data
#define GPGUP (*(volatile unsigned *)0x56000068) //Pull-up control G
#define GPHCON (*(volatile unsigned *)0x56000070) //Port H control
#define GPHDAT (*(volatile unsigned *)0x56000074) //Port H data
#define GPHUP (*(volatile unsigned *)0x56000078) //Pull-up control H
#define GPJCON (*(volatile unsigned *)0x560000d0) //Port J control
#define GPJDAT (*(volatile unsigned *)0x560000d4) //Port J data
#define GPJUP (*(volatile unsigned *)0x560000d8) //Pull-up control J
#define MISCCR (*(volatile unsigned *)0x56000080) //Miscellaneous control
#define DCLKCON (*(volatile unsigned *)0x56000084) //DCLK0/1 control
#define EXTINT0 (*(volatile unsigned *)0x56000088) //External interrupt control egister 0
#define EXTINT1 (*(volatile unsigned *)0x5600008c) //External interrupt control egister 1
#define EXTINT2 (*(volatile unsigned *)0x56000090) //External interrupt control egister 2
#define EINTFLT0 (*(volatile unsigned *)0x56000094) //Reserved
#define EINTFLT1 (*(volatile unsigned *)0x56000098) //Reserved
#define EINTFLT2 (*(volatile unsigned *)0x5600009c) //External interrupt filter control egister 2
#define EINTFLT3 (*(volatile unsigned *)0x560000a0) //External interrupt filter control egister 3
#define EINTMASK (*(volatile unsigned *)0x560000a4) //External interrupt mask
#define EINTPEND (*(volatile unsigned *)0x560000a8) //External interrupt pending
#define GSTATUS0 (*(volatile unsigned *)0x560000ac) //External pin status
#define GSTATUS1 (*(volatile unsigned *)0x560000b0) //Chip ID(0x32410000)
#define GSTATUS2 (*(volatile unsigned *)0x560000b4) //Reset type
#define GSTATUS3 (*(volatile unsigned *)0x560000b8) //Saved data0(32-bit) before entering POWER_OFF mode
#define GSTATUS4 (*(volatile unsigned *)0x560000bc) //Saved data0(32-bit) before entering POWER_OFF mode
// RTC
#ifdef __BIG_ENDIAN
#define RTCCON (*(volatile unsigned char *)0x57000043) //RTC control
#define TICNT (*(volatile unsigned char *)0x57000047) //Tick time count
#define RTCALM (*(volatile unsigned char *)0x57000053) //RTC alarm control
#define ALMSEC (*(volatile unsigned char *)0x57000057) //Alarm second
#define ALMMIN (*(volatile unsigned char *)0x5700005b) //Alarm minute
#define ALMHOUR (*(volatile unsigned char *)0x5700005f) //Alarm Hour
#define ALMDATE (*(volatile unsigned char *)0x57000063) //Alarm day <-- May 06, 2002 SOP
#define ALMMON (*(volatile unsigned char *)0x57000067) //Alarm month
#define ALMYEAR (*(volatile unsigned char *)0x5700006b) //Alarm year
#define RTCRST (*(volatile unsigned char *)0x5700006f) //RTC ound eset
#define BCDSEC (*(volatile unsigned char *)0x57000073) //BCD second
#define BCDMIN (*(volatile unsigned char *)0x57000077) //BCD minute
#define BCDHOUR (*(volatile unsigned char *)0x5700007b) //BCD hour
#define BCDDATE (*(volatile unsigned char *)0x5700007f) //BCD day <-- May 06, 2002 SOP
#define BCDDAY (*(volatile unsigned char *)0x57000083) //BCD date <-- May 06, 2002 SOP
#define BCDMON (*(volatile unsigned char *)0x57000087) //BCD month
#define BCDYEAR (*(volatile unsigned char *)0x5700008b) //BCD year
#else //Little Endian
#define RTCCON (*(volatile unsigned char *)0x57000040) //RTC control
#define TICNT (*(volatile unsigned char *)0x57000044) //Tick time count
#define RTCALM (*(volatile unsigned char *)0x57000050) //RTC alarm control
#define ALMSEC (*(volatile unsigned char *)0x57000054) //Alarm second
#define ALMMIN (*(volatile unsigned char *)0x57000058) //Alarm minute
#define ALMHOUR (*(volatile unsigned char *)0x5700005c) //Alarm Hour
#define ALMDATE (*(volatile unsigned char *)0x57000060) //Alarm day <-- May 06, 2002 SOP
#define ALMMON (*(volatile unsigned char *)0x57000064) //Alarm month
#define ALMYEAR (*(volatile unsigned char *)0x57000068) //Alarm year
#define RTCRST (*(volatile unsigned char *)0x5700006c) //RTC ound eset
#define BCDSEC (*(volatile unsigned char *)0x57000070) //BCD second
#define BCDMIN (*(volatile unsigned char *)0x57000074) //BCD minute
#define BCDHOUR (*(volatile unsigned char *)0x57000078) //BCD hour
#define BCDDATE (*(volatile unsigned char *)0x5700007c) //BCD day <-- May 06, 2002 SOP
#define BCDDAY (*(volatile unsigned char *)0x57000080) //BCD date <-- May 06, 2002 SOP
#define BCDMON (*(volatile unsigned char *)0x57000084) //BCD month
#define BCDYEAR (*(volatile unsigned char *)0x57000088) //BCD year
#endif //RTC
// ADC
#define ADCCON (*(volatile unsigned *)0x58000000) //ADC control
#define ADCTSC (*(volatile unsigned *)0x58000004) //ADC touch screen control
#define ADCDLY (*(volatile unsigned *)0x58000008) //ADC start or Interval Delay
#define ADCDAT0 (*(volatile unsigned *)0x5800000c) //ADC conversion data 0
#define ADCDAT1 (*(volatile unsigned *)0x58000010) //ADC conversion data 1
// SPI
#define SPCON0 (*(volatile unsigned *)0x59000000) //SPI0 control
#define SPSTA0 (*(volatile unsigned *)0x59000004) //SPI0 status
#define SPPIN0 (*(volatile unsigned *)0x59000008) //SPI0 pin control
#define SPPRE0 (*(volatile unsigned *)0x5900000c) //SPI0 baud ate prescaler
#define SPTDAT0 (*(volatile unsigned *)0x59000010) //SPI0 Tx data
#define SPRDAT0 (*(volatile unsigned *)0x59000014) //SPI0 Rx data
#define SPCON1 (*(volatile unsigned *)0x59000020) //SPI1 control
#define SPSTA1 (*(volatile unsigned *)0x59000024) //SPI1 status
#define SPPIN1 (*(volatile unsigned *)0x59000028) //SPI1 pin control
#define SPPRE1 (*(volatile unsigned *)0x5900002c) //SPI1 baud ate prescaler
#define SPTDAT1 (*(volatile unsigned *)0x59000030) //SPI1 Tx data
#define SPRDAT1 (*(volatile unsigned *)0x59000034) //SPI1 Rx data
// SD Interface
#define SDICON (*(volatile unsigned *)0x5a000000) //SDI control
#define SDIPRE (*(volatile unsigned *)0x5a000004) //SDI baud ate prescaler
#define SDICARG (*(volatile unsigned *)0x5a000008) //SDI command argument
#define SDICCON (*(volatile unsigned *)0x5a00000c) //SDI command control
#define SDICSTA (*(volatile unsigned *)0x5a000010) //SDI command status
#define SDIRSP0 (*(volatile unsigned *)0x5a000014) //SDI esponse 0
#define SDIRSP1 (*(volatile unsigned *)0x5a000018) //SDI esponse 1
#define SDIRSP2 (*(volatile unsigned *)0x5a00001c) //SDI esponse 2
#define SDIRSP3 (*(volatile unsigned *)0x5a000020) //SDI esponse 3
#define SDIDTIMER (*(volatile unsigned *)0x5a000024) //SDI data/busy timer
#define SDIBSIZE (*(volatile unsigned *)0x5a000028) //SDI block size
#define SDIDCON (*(volatile unsigned *)0x5a00002c) //SDI data control
#define SDIDCNT (*(volatile unsigned *)0x5a000030) //SDI data emain counter
#define SDIDSTA (*(volatile unsigned *)0x5a000034) //SDI data status
#define SDIFSTA (*(volatile unsigned *)0x5a000038) //SDI FIFO status
#define SDIIMSK (*(volatile unsigned *)0x5a000040) //SDI interrupt mask
#ifdef __BIG_ENDIAN /* edited for 2440A */
#define SDIDAT (*(volatile unsigned *)0x5a00004c)
#else // Little Endian
#define SDIDAT (*(volatile unsigned *)0x5a000040)
#endif //SD Interface
// PENDING BIT
#define INTEINT0 (0)
#define INTEINT1 (1)
#define INTEINT2 (2)
#define INTEINT3 (3)
#define INTEINT4_7 (4)
#define INTEINT8_23 (5)
#define INTNOTUSED6 (6)
#define INTBAT_FLT (7)
#define INTTICK (8)
#define INTWDT (9)
#define INTTIMER0 (10)
#define INTTIMER1 (11)
#define INTTIMER2 (12)
#define INTTIMER3 (13)
#define INTTIMER4 (14)
#define INTUART2 (15)
#define INTLCD (16)
#define INTDMA0 (17)
#define INTDMA1 (18)
#define INTDMA2 (19)
#define INTDMA3 (20)
#define INTSDI (21)
#define INTSPI0 (22)
#define INTUART1 (23)
//#define INTNOTUSED24 (24)
#define INTNIC (24)
#define INTUSBD (25)
#define INTUSBH (26)
#define INTIIC (27)
#define INTUART0 (28)
#define INTSPI1 (29)
#define INTRTC (30)
#define INTADC (31)
#define BIT_ALLMSK (0xffffffff)
#define BIT_SUB_ALLMSK (0x7ff)
#define INTSUB_ADC (10)
#define INTSUB_TC (9)
#define INTSUB_ERR2 (8)
#define INTSUB_TXD2 (7)
#define INTSUB_RXD2 (6)
#define INTSUB_ERR1 (5)
#define INTSUB_TXD1 (4)
#define INTSUB_RXD1 (3)
#define INTSUB_ERR0 (2)
#define INTSUB_TXD0 (1)
#define INTSUB_RXD0 (0)
#define BIT_SUB_ADC (0x1<<10)
#define BIT_SUB_TC (0x1<<9)
#define BIT_SUB_ERR2 (0x1<<8)
#define BIT_SUB_TXD2 (0x1<<7)
#define BIT_SUB_RXD2 (0x1<<6)
#define BIT_SUB_ERR1 (0x1<<5)
#define BIT_SUB_TXD1 (0x1<<4)
#define BIT_SUB_RXD1 (0x1<<3)
#define BIT_SUB_ERR0 (0x1<<2)
#define BIT_SUB_TXD0 (0x1<<1)
#define BIT_SUB_RXD0 (0x1<<0)
#define ClearPending(bit) {SRCPND = bit;INTPND = bit;INTPND;}
//Wait until INTPND is changed for the case that the ISR is very short.
#define INTGLOBAL 32
/*****************************/
/* CPU Mode */
/*****************************/
#define USERMODE 0x10
#define FIQMODE 0x11
#define IRQMODE 0x12
#define SVCMODE 0x13
#define ABORTMODE 0x17
#define UNDEFMODE 0x1b
#define MODEMASK 0x1f
#define NOINT 0xc0
struct rt_hw_register
{
rt_uint32_t r0;
rt_uint32_t r1;
rt_uint32_t r2;
rt_uint32_t r3;
rt_uint32_t r4;
rt_uint32_t r5;
rt_uint32_t r6;
rt_uint32_t r7;
rt_uint32_t r8;
rt_uint32_t r9;
rt_uint32_t r10;
rt_uint32_t fp;
rt_uint32_t ip;
rt_uint32_t sp;
rt_uint32_t lr;
rt_uint32_t pc;
rt_uint32_t cpsr;
rt_uint32_t ORIG_r0;
};
#ifdef __cplusplus
}
#endif
/*@}*/
#endif
| {
"pile_set_name": "Github"
} |
/*
* $Id: l440gx.c,v 1.18 2005/11/07 11:14:27 gleixner Exp $
*
* BIOS Flash chip on Intel 440GX board.
*
* Bugs this currently does not work under linuxBIOS.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#define PIIXE_IOBASE_RESOURCE 11
#define WINDOW_ADDR 0xfff00000
#define WINDOW_SIZE 0x00100000
#define BUSWIDTH 1
static u32 iobase;
#define IOBASE iobase
#define TRIBUF_PORT (IOBASE+0x37)
#define VPP_PORT (IOBASE+0x28)
static struct mtd_info *mymtd;
/* Is this really the vpp port? */
static void l440gx_set_vpp(struct map_info *map, int vpp)
{
unsigned long l;
l = inl(VPP_PORT);
if (vpp) {
l |= 1;
} else {
l &= ~1;
}
outl(l, VPP_PORT);
}
static struct map_info l440gx_map = {
.name = "L440GX BIOS",
.size = WINDOW_SIZE,
.bankwidth = BUSWIDTH,
.phys = WINDOW_ADDR,
#if 0
/* FIXME verify that this is the
* appripriate code for vpp enable/disable
*/
.set_vpp = l440gx_set_vpp
#endif
};
static int __init init_l440gx(void)
{
struct pci_dev *dev, *pm_dev;
struct resource *pm_iobase;
__u16 word;
dev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_82371AB_0, NULL);
pm_dev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_82371AB_3, NULL);
pci_dev_put(dev);
if (!dev || !pm_dev) {
printk(KERN_NOTICE "L440GX flash mapping: failed to find PIIX4 ISA bridge, cannot continue\n");
pci_dev_put(pm_dev);
return -ENODEV;
}
l440gx_map.virt = ioremap_nocache(WINDOW_ADDR, WINDOW_SIZE);
if (!l440gx_map.virt) {
printk(KERN_WARNING "Failed to ioremap L440GX flash region\n");
pci_dev_put(pm_dev);
return -ENOMEM;
}
simple_map_init(&l440gx_map);
printk(KERN_NOTICE "window_addr = 0x%08lx\n", (unsigned long)l440gx_map.virt);
/* Setup the pm iobase resource
* This code should move into some kind of generic bridge
* driver but for the moment I'm content with getting the
* allocation correct.
*/
pm_iobase = &pm_dev->resource[PIIXE_IOBASE_RESOURCE];
if (!(pm_iobase->flags & IORESOURCE_IO)) {
pm_iobase->name = "pm iobase";
pm_iobase->start = 0;
pm_iobase->end = 63;
pm_iobase->flags = IORESOURCE_IO;
/* Put the current value in the resource */
pci_read_config_dword(pm_dev, 0x40, &iobase);
iobase &= ~1;
pm_iobase->start += iobase & ~1;
pm_iobase->end += iobase & ~1;
pci_dev_put(pm_dev);
/* Allocate the resource region */
if (pci_assign_resource(pm_dev, PIIXE_IOBASE_RESOURCE) != 0) {
pci_dev_put(dev);
pci_dev_put(pm_dev);
printk(KERN_WARNING "Could not allocate pm iobase resource\n");
iounmap(l440gx_map.virt);
return -ENXIO;
}
}
/* Set the iobase */
iobase = pm_iobase->start;
pci_write_config_dword(pm_dev, 0x40, iobase | 1);
/* Set XBCS# */
pci_read_config_word(dev, 0x4e, &word);
word |= 0x4;
pci_write_config_word(dev, 0x4e, word);
/* Supply write voltage to the chip */
l440gx_set_vpp(&l440gx_map, 1);
/* Enable the gate on the WE line */
outb(inb(TRIBUF_PORT) & ~1, TRIBUF_PORT);
printk(KERN_NOTICE "Enabled WE line to L440GX BIOS flash chip.\n");
mymtd = do_map_probe("jedec_probe", &l440gx_map);
if (!mymtd) {
printk(KERN_NOTICE "JEDEC probe on BIOS chip failed. Using ROM\n");
mymtd = do_map_probe("map_rom", &l440gx_map);
}
if (mymtd) {
mymtd->owner = THIS_MODULE;
add_mtd_device(mymtd);
return 0;
}
iounmap(l440gx_map.virt);
return -ENXIO;
}
static void __exit cleanup_l440gx(void)
{
del_mtd_device(mymtd);
map_destroy(mymtd);
iounmap(l440gx_map.virt);
}
module_init(init_l440gx);
module_exit(cleanup_l440gx);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <[email protected]>");
MODULE_DESCRIPTION("MTD map driver for BIOS chips on Intel L440GX motherboards");
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4936392
* @summary enum spec allows trailing comma on enum constant list
* @author gafter
*
* @compile TrailingComma.java
*/
class TrailingComma {
enum a { , };
enum b { x , };
enum c { , ; };
enum d { x , ; };
}
| {
"pile_set_name": "Github"
} |
---
name: Bug report
about: Create a report to help us improve cuML
title: "[BUG]"
labels: "? - Needs Triage, bug"
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**Steps/Code to reproduce bug**
Follow this guide http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports to craft a minimal bug report. This helps us reproduce the issue you're having and resolve the issue more quickly.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Environment details (please complete the following information):**
- Environment location: [Bare-metal, Docker, Cloud(specify cloud provider)]
- Linux Distro/Architecture: [Ubuntu 16.04 amd64]
- GPU Model/Driver: [V100 and driver 396.44]
- CUDA: [9.2]
- Method of cuDF & cuML install: [conda, Docker, or from source]
- If method of install is [conda], run `conda list` and include results here
- If method of install is [Docker], provide `docker pull` & `docker run` commands used
- If method of install is [from source], provide versions of `cmake` & `gcc/g++` and commit hash of build
**Additional context**
Add any other context about the problem here.
| {
"pile_set_name": "Github"
} |
# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Provide a function to report modification to broadcast settings."""
BAD_OPTIONS_FMT = "\n --%s=%s"
BAD_OPTIONS_TITLE = "No broadcast to cancel/clear for these options:"
BAD_OPTIONS_TITLE_SET = ("Rejected broadcast: settings are not"
" compatible with the suite")
CHANGE_FMT = "\n%(change)s [%(namespace)s.%(point)s] %(key)s=%(value)s"
CHANGE_PREFIX_CANCEL = "-"
CHANGE_PREFIX_SET = "+"
CHANGE_TITLE_CANCEL = "Broadcast cancelled:"
CHANGE_TITLE_SET = "Broadcast set:"
def get_broadcast_bad_options_report(bad_options, is_set=False):
"""Return a string to report bad options for broadcast cancel/clear."""
if not bad_options:
return None
if is_set:
msg = BAD_OPTIONS_TITLE_SET
else:
msg = BAD_OPTIONS_TITLE
for key, values in sorted(bad_options.items()):
for value in values:
if isinstance(value, tuple) or isinstance(value, list):
value_str = ""
values = list(value)
while values:
val = values.pop(0)
if values:
value_str += "[" + val + "]"
else:
value_str += val
else:
value_str = value
msg += BAD_OPTIONS_FMT % (key, value_str)
return msg
def get_broadcast_change_iter(modified_settings, is_cancel=False):
"""Return an iterator of broadcast changes.
Each broadcast change is a dict with keys:
change, point, namespace, key, value
"""
if not modified_settings:
return
if is_cancel:
change = CHANGE_PREFIX_CANCEL
else:
change = CHANGE_PREFIX_SET
for modified_setting in sorted(modified_settings,
key=lambda x: (x[0], x[1])):
# sorted by (point, namespace)
point, namespace, setting = modified_setting
value = setting
keys_str = ""
while isinstance(value, dict):
key, value = list(value.items())[0]
if isinstance(value, dict):
keys_str += "[" + key + "]"
else:
keys_str += key
yield {
"change": change,
"point": point,
"namespace": namespace,
"key": keys_str,
"value": str(value)}
def get_broadcast_change_report(modified_settings, is_cancel=False):
"""Return a string for reporting modification to broadcast settings."""
if not modified_settings:
return ""
if is_cancel:
msg = CHANGE_TITLE_CANCEL
else:
msg = CHANGE_TITLE_SET
for broadcast_change in get_broadcast_change_iter(
modified_settings, is_cancel):
msg += CHANGE_FMT % broadcast_change
return msg
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_21) on Thu Jun 20 21:49:57 EDT 2013 -->
<title>peasy.org.apache.commons.math (Javadocs: peasycam)</title>
<meta name="date" content="2013-06-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../peasy/org/apache/commons/math/package-summary.html" target="classFrame">peasy.org.apache.commons.math</a></h1>
<div class="indexContainer">
<h2 title="Exceptions">Exceptions</h2>
<ul title="Exceptions">
<li><a href="MathException.html" title="class in peasy.org.apache.commons.math" target="classFrame">MathException</a></li>
</ul>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
---
layout: middleware
title: Express serve-favicon middleware
menu: resources
lang: en
module: serve-favicon
---
| {
"pile_set_name": "Github"
} |
// 3rdparty libraries
import * as _ from 'lodash';
import XRegExp from 'xregexp';
import emojiRegex from 'emoji-regex';
import tlds from 'tlds';
import * as constants from '../constants';
import { permission } from '../helpers/permissions';
import { command, default_permission, parser, permission_settings, settings } from '../decorators';
import Message from '../message';
import System from './_interface';
import { getLocalizedName, isModerator, parserReply, prepare, timeout } from '../commons';
import { timeout as timeoutLog, warning as warningLog } from '../helpers/log';
import { clusteredClientDelete } from '../cluster';
import { adminEndpoint } from '../helpers/socket';
import { Alias } from '../database/entity/alias';
import { getRepository, LessThan } from 'typeorm';
import { ModerationMessageCooldown, ModerationPermit, ModerationWarning } from '../database/entity/moderation';
import permissions from '../permissions';
import { translate } from '../translate';
import spotify from '../integrations/spotify';
import songs from './songs';
import aliasSystem from './alias';
import users from '../users';
const urlRegex = [
new RegExp(`(www)? ??\\.? ?[a-zA-Z0-9]+([a-zA-Z0-9-]+) ??\\. ?(${tlds.join('|')})(?=\\P{L}|$)`, 'igu'),
new RegExp(`[a-zA-Z0-9]+([a-zA-Z0-9-]+)?\\.(${tlds.join('|')})(?=\\P{L}|$)`, 'igu'),
];
class Moderation extends System {
@settings('lists')
cListsWhitelist: string[] = [];
@settings('lists')
cListsBlacklist: string[] = [];
@permission_settings('lists', [ permission.CASTERS ])
cListsEnabled = true;
@permission_settings('lists', [ permission.CASTERS ])
cListsTimeout = 120;
@permission_settings('links', [ permission.CASTERS ])
cLinksEnabled = true;
@permission_settings('links', [ permission.CASTERS ])
cLinksIncludeSpaces = false;
@permission_settings('links', [ permission.CASTERS ])
cLinksIncludeClips = true;
@permission_settings('links', [ permission.CASTERS ])
cLinksTimeout = 120;
@permission_settings('symbols', [ permission.CASTERS ])
cSymbolsEnabled = true;
@permission_settings('symbols', [ permission.CASTERS ])
cSymbolsTriggerLength = 15;
@permission_settings('symbols', [ permission.CASTERS ])
cSymbolsMaxSymbolsConsecutively = 10;
@permission_settings('symbols', [ permission.CASTERS ])
cSymbolsMaxSymbolsPercent = 50;
@permission_settings('symbols', [ permission.CASTERS ])
cSymbolsTimeout = 120;
@permission_settings('longMessage', [ permission.CASTERS ])
cLongMessageEnabled = true;
@permission_settings('longMessage', [ permission.CASTERS ])
cLongMessageTriggerLength = 300;
@permission_settings('longMessage', [ permission.CASTERS ])
cLongMessageTimeout = 120;
@permission_settings('caps', [ permission.CASTERS ])
cCapsEnabled = true;
@permission_settings('caps', [ permission.CASTERS ])
cCapsTriggerLength = 15;
@permission_settings('caps', [ permission.CASTERS ])
cCapsMaxCapsPercent = 50;
@permission_settings('caps', [ permission.CASTERS ])
cCapsTimeout = 120;
@permission_settings('spam', [ permission.CASTERS ])
cSpamEnabled = true;
@permission_settings('spam', [ permission.CASTERS ])
cSpamTriggerLength = 15;
@permission_settings('spam', [ permission.CASTERS ])
cSpamMaxLength = 50;
@permission_settings('spam', [ permission.CASTERS ])
cSpamTimeout = 300;
@permission_settings('color', [ permission.CASTERS ])
cColorEnabled = true;
@permission_settings('color', [ permission.CASTERS ])
cColorTimeout = 300;
@permission_settings('emotes', [ permission.CASTERS ])
cEmotesEnabled = true;
@permission_settings('emotes', [ permission.CASTERS ])
cEmotesEmojisAreEmotes = true;
@permission_settings('emotes', [ permission.CASTERS ])
cEmotesMaxCount = 15;
@permission_settings('emotes', [ permission.CASTERS ])
cEmotesTimeout = 120;
@settings('warnings')
cWarningsAllowedCount = 3;
@settings('warnings')
cWarningsAnnounceTimeouts = true;
@settings('warnings')
cWarningsShouldClearChat = true;
sockets () {
adminEndpoint(this.nsp, 'lists.get', async (cb) => {
cb(null, {
blacklist: this.cListsBlacklist,
whitelist: this.cListsWhitelist,
});
});
adminEndpoint(this.nsp, 'lists.set', (data) => {
this.cListsBlacklist = data.blacklist.filter(entry => entry.trim() !== '');
this.cListsWhitelist = data.whitelist.filter(entry => entry.trim() !== '');
});
}
async timeoutUser (sender: CommandOptions['sender'], text: string, warning: string, msg: string, time: number, type: string) {
// cleanup warnings
await getRepository(ModerationWarning).delete({
timestamp: LessThan(Date.now() - 1000 * 60 * 60),
});
const warnings = await getRepository(ModerationWarning).find({ userId: Number(sender.userId) });
const silent = await this.isSilent(type);
text = text.trim();
if (this.cWarningsAllowedCount === 0) {
msg = await new Message(msg.replace(/\$count/g, String(-1))).parse();
timeoutLog(`${sender.username} [${type}] ${time}s timeout | ${text}`);
timeout(sender.username, msg, time, isModerator(sender));
return;
}
const isWarningCountAboveThreshold = warnings.length >= this.cWarningsAllowedCount;
if (isWarningCountAboveThreshold) {
msg = await new Message(warning.replace(/\$count/g, String(this.cWarningsAllowedCount - warnings.length))).parse();
timeoutLog(`${sender.username} [${type}] ${time}s timeout | ${text}`);
timeout(sender.username, msg, time, isModerator(sender));
await getRepository(ModerationWarning).delete({ userId: Number(sender.userId) });
} else {
await getRepository(ModerationWarning).insert({ userId: Number(sender.userId), timestamp: Date.now() });
const warningsLeft = this.cWarningsAllowedCount - warnings.length;
warning = await new Message(warning.replace(/\$count/g, String(warningsLeft < 0 ? 0 : warningsLeft))).parse();
if (this.cWarningsShouldClearChat) {
timeoutLog(`${sender.username} [${type}] 1s timeout, warnings left ${warningsLeft < 0 ? 0 : warningsLeft} | ${text}`);
timeout(sender.username, warning, 1, isModerator(sender));
}
if (this.cWarningsAnnounceTimeouts) {
clusteredClientDelete(sender.id);
if (!silent) {
parserReply('$sender, ' + warning, { sender });
} else {
warningLog(`Moderation announce was not sent (another ${type} warning already sent in 60s): ${sender.username}, ${warning}`);
}
}
}
}
async whitelist (text: string, permId: string | null) {
let ytRegex, clipsRegex, spotifyRegex;
// check if spotify -or- alias of spotify contain open.spotify.com link
if (spotify.enabled) {
// we can assume its first command in array (spotify have only one command)
const cmd = (await spotify.commands())[0].command;
const alias = await getRepository(Alias).findOne({ where: { command: cmd } });
if (alias && alias.enabled && aliasSystem.enabled) {
spotifyRegex = new RegExp('^(' + cmd + '|' + alias.alias + ') \\S+open\\.spotify\\.com\\/track\\/(\\w+)(.*)?', 'gi');
} else {
spotifyRegex = new RegExp('^(' + cmd + ') \\S+open\\.spotify\\.com\\/track\\/(\\w+)(.*)?', 'gi');
}
text = text.replace(spotifyRegex, '');
}
// check if songrequest -or- alias of songrequest contain youtube link
if (songs.enabled) {
const alias = await getRepository(Alias).findOne({ where: { command: '!songrequest' } });
const cmd = songs.getCommand('!songrequest');
if (alias && alias.enabled && aliasSystem.enabled) {
ytRegex = new RegExp('^(' + cmd + '|' + alias.alias + ') \\S+(?:youtu.be\\/|v\\/|e\\/|u\\/\\w+\\/|embed\\/|v=)([^#&?]*).*', 'gi');
} else {
ytRegex = new RegExp('^(' + cmd + ') \\S+(?:youtu.be\\/|v\\/|e\\/|u\\/\\w+\\/|embed\\/|v=)([^#&?]*).*', 'gi');
}
text = text.replace(ytRegex, '');
}
if (permId) {
const cLinksIncludeClips = (await this.getPermissionBasedSettingsValue('cLinksIncludeClips'))[permId];
if (!cLinksIncludeClips) {
clipsRegex = /.*(clips.twitch.tv\/)(\w+)/g;
text = text.replace(clipsRegex, '');
clipsRegex = /.*(www.twitch.tv\/\w+\/clip\/)(\w+)/g;
text = text.replace(clipsRegex, '');
}
}
text = ` ${text} `;
const whitelist = this.cListsWhitelist;
for (const value of whitelist.map(o => o.trim().replace(/\*/g, '[\\pL0-9\\S]*').replace(/\+/g, '[\\pL0-9\\S]+'))) {
if (value.length > 0) {
let regexp;
if (value.startsWith('domain:')) {
regexp = XRegExp(` [\\S]*${XRegExp.escape(value.replace('domain:', ''))}[\\S]* `, 'gi');
} else { // default regexp behavior
regexp = XRegExp(` [^\\s\\pL0-9\\w]?${value}[^\\s\\pL0-9\\w]? `, 'gi');
}
// we need to change 'text' to ' text ' for regexp to correctly work
text = XRegExp.replace(` ${text} `, regexp, '').trim();
}
}
return text.trim();
}
@command('!permit')
@default_permission(permission.CASTERS)
async permitLink (opts: CommandOptions): Promise<CommandResponse[]> {
try {
const parsed = opts.parameters.match(/^@?([\S]+) ?(\d+)?$/);
if (!parsed) {
throw new Error('!permit command not parsed');
}
let count = 1;
if (!_.isNil(parsed[2])) {
count = parseInt(parsed[2], 10);
}
const userId = await users.getIdByName(parsed[1].toLowerCase());
for (let i = 0; i < count; i++) {
await getRepository(ModerationPermit).insert({ userId });
}
const response = prepare('moderation.user-have-link-permit', { username: parsed[1].toLowerCase(), link: getLocalizedName(count, 'core.links'), count: count });
return [{ response, ...opts }];
} catch (e) {
return [{ response: translate('moderation.permit-parse-failed'), ...opts }];
}
}
@parser({ priority: constants.MODERATION })
async containsLink (opts: ParserOptions) {
const enabled = await this.getPermissionBasedSettingsValue('cLinksEnabled');
const cLinksIncludeSpaces = await this.getPermissionBasedSettingsValue('cLinksIncludeSpaces');
const timeoutValues = await this.getPermissionBasedSettingsValue('cLinksTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
const whitelisted = await this.whitelist(opts.message, permId);
if (whitelisted.search(urlRegex[cLinksIncludeSpaces[permId] ? 0 : 1]) >= 0) {
const permit = await getRepository(ModerationPermit).findOne({ userId: Number(opts.sender.userId) });
if (permit) {
await getRepository(ModerationPermit).remove(permit);
return true;
} else {
this.timeoutUser(opts.sender, whitelisted,
translate('moderation.user-is-warned-about-links'),
translate('moderation.user-have-timeout-for-links'),
timeoutValues[permId], 'links');
return false;
}
} else {
return true;
}
}
@parser({ priority: constants.MODERATION })
async symbols (opts: ParserOptions) {
const enabled = await this.getPermissionBasedSettingsValue('cSymbolsEnabled');
const cSymbolsTriggerLength = await this.getPermissionBasedSettingsValue('cSymbolsTriggerLength');
const cSymbolsMaxSymbolsConsecutively = await this.getPermissionBasedSettingsValue('cSymbolsMaxSymbolsConsecutively');
const cSymbolsMaxSymbolsPercent = await this.getPermissionBasedSettingsValue('cSymbolsMaxSymbolsPercent');
const timeoutValues = await this.getPermissionBasedSettingsValue('cSymbolsTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
const whitelisted = await this.whitelist(opts.message, permId);
const msgLength = whitelisted.trim().length;
let symbolsLength = 0;
if (msgLength < cSymbolsTriggerLength[permId]) {
return true;
}
const out = whitelisted.match(/([^\s\u0500-\u052F\u0400-\u04FF\w]+)/g);
for (const item in out) {
if (out.hasOwnProperty(item)) {
const symbols = out[Number(item)];
if (symbols.length >= cSymbolsMaxSymbolsConsecutively[permId]) {
this.timeoutUser(opts.sender, opts.message,
translate('moderation.user-is-warned-about-symbols'),
translate('moderation.user-have-timeout-for-symbols'),
timeoutValues[permId], 'symbols');
return false;
}
symbolsLength = symbolsLength + symbols.length;
}
}
if (Math.ceil(symbolsLength / (msgLength / 100)) >= cSymbolsMaxSymbolsPercent[permId]) {
this.timeoutUser(opts.sender, opts.message, translate('moderation.user-is-warned-about-symbols'), translate('moderation.symbols'), timeoutValues[permId], 'symbols');
return false;
}
return true;
}
@parser({ priority: constants.MODERATION })
async longMessage (opts: ParserOptions) {
const enabled = await this.getPermissionBasedSettingsValue('cLongMessageEnabled');
const cLongMessageTriggerLength = await this.getPermissionBasedSettingsValue('cLongMessageTriggerLength');
const timeoutValues = await this.getPermissionBasedSettingsValue('cLongMessageTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
const whitelisted = await this.whitelist(opts.message, permId);
const msgLength = whitelisted.trim().length;
if (msgLength < cLongMessageTriggerLength[permId]) {
return true;
} else {
this.timeoutUser(opts.sender, opts.message,
translate('moderation.user-is-warned-about-long-message'),
translate('moderation.user-have-timeout-for-long-message'),
timeoutValues[permId], 'longmessage');
return false;
}
}
@parser({ priority: constants.MODERATION })
async caps (opts: ParserOptions) {
const enabled = await this.getPermissionBasedSettingsValue('cCapsEnabled');
const cCapsTriggerLength = await this.getPermissionBasedSettingsValue('cCapsTriggerLength');
const cCapsMaxCapsPercent = await this.getPermissionBasedSettingsValue('cCapsMaxCapsPercent');
const timeoutValues = await this.getPermissionBasedSettingsValue('cCapsTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
let whitelisted = await this.whitelist(opts.message, permId);
const emotesCharList: number[] = [];
if (Symbol.iterator in Object(opts.sender.emotes)) {
for (const emote of opts.sender.emotes) {
for (const i of _.range(emote.start, emote.end + 1)) {
emotesCharList.push(i);
}
}
}
let msgLength = whitelisted.trim().length;
let capsLength = 0;
// exclude emotes from caps check
whitelisted = whitelisted.replace(emojiRegex(), '').trim();
const regexp = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~]/gi;
for (let i = 0; i < whitelisted.length; i++) {
// if is emote or symbol - continue
if (_.includes(emotesCharList, i) || !_.isNull(whitelisted.charAt(i).match(regexp))) {
msgLength--;
continue;
} else if (!_.isFinite(parseInt(whitelisted.charAt(i), 10)) && whitelisted.charAt(i).toUpperCase() === whitelisted.charAt(i) && whitelisted.charAt(i) !== ' ') {
capsLength += 1;
}
}
if (msgLength < cCapsTriggerLength[permId]) {
return true;
}
if (Math.ceil(capsLength / (msgLength / 100)) >= cCapsMaxCapsPercent[permId]) {
this.timeoutUser(opts.sender, opts.message,
translate('moderation.user-is-warned-about-caps'),
translate('moderation.user-have-timeout-for-caps'),
timeoutValues[permId], 'caps');
return false;
}
return true;
}
@parser({ priority: constants.MODERATION })
async spam (opts: ParserOptions) {
const enabled = await this.getPermissionBasedSettingsValue('cSpamEnabled');
const cSpamTriggerLength = await this.getPermissionBasedSettingsValue('cSpamTriggerLength');
const cSpamMaxLength = await this.getPermissionBasedSettingsValue('cSpamMaxLength');
const timeoutValues = await this.getPermissionBasedSettingsValue('cSpamTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
const whitelisted = await this.whitelist(opts.message,permId);
const msgLength = whitelisted.trim().length;
if (msgLength < cSpamTriggerLength[permId]) {
return true;
}
const out = whitelisted.match(/(.+)(\1+)/g);
for (const item in out) {
if (out.hasOwnProperty(item) && out[Number(item)].length >= cSpamMaxLength[permId]) {
this.timeoutUser(opts.sender, opts.message,
translate('moderation.user-have-timeout-for-spam'),
translate('moderation.user-is-warned-about-spam'),
timeoutValues[permId], 'spam');
return false;
}
}
return true;
}
@parser({ priority: constants.MODERATION })
async color (opts: ParserOptions) {
const enabled = await this.getPermissionBasedSettingsValue('cColorEnabled');
const timeoutValues = await this.getPermissionBasedSettingsValue('cColorTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
if (opts.sender['message-type'] === 'action') {
this.timeoutUser(opts.sender, opts.message,
translate('moderation.user-is-warned-about-color'),
translate('moderation.user-have-timeout-for-color'),
timeoutValues[permId], 'color');
return false;
} else {
return true;
}
}
@parser({ priority: constants.MODERATION })
async emotes (opts: ParserOptions) {
if (!(Symbol.iterator in Object(opts.sender.emotes))) {
return true;
}
const enabled = await this.getPermissionBasedSettingsValue('cEmotesEnabled');
const cEmotesEmojisAreEmotes = await this.getPermissionBasedSettingsValue('cEmotesEmojisAreEmotes');
const cEmotesMaxCount = await this.getPermissionBasedSettingsValue('cEmotesMaxCount');
const timeoutValues = await this.getPermissionBasedSettingsValue('cEmotesTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
let count = opts.sender.emotes.length;
if (cEmotesEmojisAreEmotes[permId]) {
const regex = emojiRegex();
while (regex.exec(opts.message)) {
count++;
}
}
if (count > cEmotesMaxCount[permId]) {
this.timeoutUser(opts.sender, opts.message,
translate('moderation.user-is-warned-about-emotes'),
translate('moderation.user-have-timeout-for-emotes'),
timeoutValues[permId], 'emotes');
return false;
} else {
return true;
}
}
@parser({ priority: constants.MODERATION })
async blacklist (opts: ParserOptions) {
const enabled = await this.getPermissionBasedSettingsValue('cListsEnabled');
const timeoutValues = await this.getPermissionBasedSettingsValue('cListsTimeout');
const permId = await permissions.getUserHighestPermission(opts.sender.userId);
if (permId === null || !enabled[permId] || permId === permission.CASTERS) {
return true;
}
let isOK = true;
for (const value of this.cListsBlacklist.map(o => o.trim().replace(/\*/g, '[\\pL0-9]*').replace(/\+/g, '[\\pL0-9]+'))) {
if (value.length > 0) {
const regexp = XRegExp(` [^\\s\\pL0-9\\w]?${value}[^\\s\\pL0-9\\w]? `, 'gi');
// we need to change 'text' to ' text ' for regexp to correctly work
if (XRegExp.exec(` ${opts.message} `, regexp)) {
isOK = false;
this.timeoutUser(opts.sender, opts.message,
translate('moderation.user-is-warned-about-blacklist'),
translate('moderation.user-have-timeout-for-blacklist'),
timeoutValues[permId], 'blacklist');
break;
}
}
}
return isOK;
}
async isSilent (name: string) {
const item = await getRepository(ModerationMessageCooldown).findOne({ name });
if (!item || (Date.now() - item.timestamp) >= 60000) {
await getRepository(ModerationMessageCooldown).save({
...item, name, timestamp: Date.now(),
});
return false;
}
return true;
}
}
export default new Moderation();
| {
"pile_set_name": "Github"
} |
"""This module runs a 5-Fold CV for all the algorithms (default parameters) on
the movielens datasets, and reports average RMSE, MAE, and total computation
time. It is used for making tables in the README.md file"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import time
import datetime
import random
import numpy as np
import six
from tabulate import tabulate
from surprise import Dataset
from surprise.model_selection import cross_validate
from surprise.model_selection import KFold
from surprise import NormalPredictor
from surprise import BaselineOnly
from surprise import KNNBasic
from surprise import KNNWithMeans
from surprise import KNNBaseline
from surprise import SVD
from surprise import SVDpp
from surprise import NMF
from surprise import SlopeOne
from surprise import CoClustering
# The algorithms to cross-validate
classes = (SVD, SVDpp, NMF, SlopeOne, KNNBasic, KNNWithMeans, KNNBaseline,
CoClustering, BaselineOnly, NormalPredictor)
# ugly dict to map algo names and datasets to their markdown links in the table
stable = 'http://surprise.readthedocs.io/en/stable/'
LINK = {'SVD': '[{}]({})'.format('SVD',
stable +
'matrix_factorization.html#surprise.prediction_algorithms.matrix_factorization.SVD'),
'SVDpp': '[{}]({})'.format('SVD++',
stable +
'matrix_factorization.html#surprise.prediction_algorithms.matrix_factorization.SVDpp'),
'NMF': '[{}]({})'.format('NMF',
stable +
'matrix_factorization.html#surprise.prediction_algorithms.matrix_factorization.NMF'),
'SlopeOne': '[{}]({})'.format('Slope One',
stable +
'slope_one.html#surprise.prediction_algorithms.slope_one.SlopeOne'),
'KNNBasic': '[{}]({})'.format('k-NN',
stable +
'knn_inspired.html#surprise.prediction_algorithms.knns.KNNBasic'),
'KNNWithMeans': '[{}]({})'.format('Centered k-NN',
stable +
'knn_inspired.html#surprise.prediction_algorithms.knns.KNNWithMeans'),
'KNNBaseline': '[{}]({})'.format('k-NN Baseline',
stable +
'knn_inspired.html#surprise.prediction_algorithms.knns.KNNBaseline'),
'CoClustering': '[{}]({})'.format('Co-Clustering',
stable +
'co_clustering.html#surprise.prediction_algorithms.co_clustering.CoClustering'),
'BaselineOnly': '[{}]({})'.format('Baseline',
stable +
'basic_algorithms.html#surprise.prediction_algorithms.baseline_only.BaselineOnly'),
'NormalPredictor': '[{}]({})'.format('Random',
stable +
'basic_algorithms.html#surprise.prediction_algorithms.random_pred.NormalPredictor'),
'ml-100k': '[{}]({})'.format('Movielens 100k',
'http://grouplens.org/datasets/movielens/100k'),
'ml-1m': '[{}]({})'.format('Movielens 1M',
'http://grouplens.org/datasets/movielens/1m'),
}
# set RNG
np.random.seed(0)
random.seed(0)
dataset = 'ml-1m'
data = Dataset.load_builtin(dataset)
kf = KFold(random_state=0) # folds will be the same for all algorithms.
table = []
for klass in classes:
start = time.time()
out = cross_validate(klass(), data, ['rmse', 'mae'], kf)
cv_time = str(datetime.timedelta(seconds=int(time.time() - start)))
link = LINK[klass.__name__]
mean_rmse = '{:.3f}'.format(np.mean(out['test_rmse']))
mean_mae = '{:.3f}'.format(np.mean(out['test_mae']))
new_line = [link, mean_rmse, mean_mae, cv_time]
print(tabulate([new_line], tablefmt="pipe")) # print current algo perf
table.append(new_line)
header = [LINK[dataset],
'RMSE',
'MAE',
'Time'
]
print(tabulate(table, header, tablefmt="pipe"))
| {
"pile_set_name": "Github"
} |
---
title: 'Delete a site or user policy for external user access'
ms.reviewer:
ms:assetid: 6d907507-825b-4354-9c03-337a459f72de
ms:mtpsurl: https://technet.microsoft.com/en-us/library/Gg521013(v=OCS.15)
ms:contentKeyID: 48184455
mtps_version: v=OCS.15
ms.author: v-lanac
author: lanachin
manager: serdars
audience: ITPro
ms.topic: article
ms.prod: skype-for-business-itpro
f1.keywords:
- NOCSH
localization_priority: Normal
description: "You can delete any site or user policy that is listed in the Skype for Business Server Control Panel on the External Access Policy page."
---
# Delete a site or user policy for external user access
If you have created or configured external user access policies that you no longer want to use, you can do the following:
- Delete any site or user policy that you created.
- Reset the global policy to the default settings. The default global policy settings deny any external user access. The global policy cannot be deleted.
You can delete any site or user policy that is listed in the Skype for Business Server Control Panel on the **External Access Policy** page. Deleting the global policy does not actually delete it, but only resets it to the default settings, which do not include support for any external user access options. For details about resetting the global policy, see [Reset the global policy for external user access](reset-the-global-policy-for-external-user-access.md).
## To delete a site or user policy for external user access
1. From a user account that is a member of the RTCUniversalServerAdmins group (or has equivalent user rights), or is assigned to the CsAdministrator role, log on to any computer in your internal deployment.
2. Open a browser window, and then enter the Admin URL to open the Skype for Business Server Control Panel.
3. Click **External User Access**, click **External Access Policy**.
4. On the **External Access Policy** tab, click the site or user policy you want to delete, click **Edit**, and then click **Delete**.
5. When prompted to confirm the deletion, click **OK**.
## Removing PIN Policies by Using Windows PowerShell Cmdlets
External access policies can be deleted by using Windows PowerShell and the Remove-CsExternalAccessPolicy cmdlet. This cmdlet can be run either from the Skype for Business Server Management Shell or from a remote session of Windows PowerShell.
## To remove a specific external access policy
- This command removes the external access policy applied to the Redmond site:
Remove-CsExternalAccessPolicy -Identity "site:Redmond"
## To remove all the external access policies applied to the per-user scope
- This command removes all the external access policies configured at the per-user scope:
Get-CsExternalAccessPolicy -Filter "tag:*" | Remove-CsExternalAccessPolicy
## To remove all the external access policies where outside user access is disabled
- This command deletes all the external access policies where outside user access has been disabled:
Get-CsExternalAccessPolicy | Where-Object {$_.EnableOutsideAccess -eq $False} | Remove-CsExternalAccessPolicy
For more information, see the help topic for the [Remove-CsExternalAccessPolicy](https://docs.microsoft.com/powershell/module/skype/Remove-CsExternalAccessPolicy) cmdlet.
| {
"pile_set_name": "Github"
} |
-----BEGIN CERTIFICATE-----
MIIEBTCCAu2gAwIBAgIUEswpqtzamsXdRz7ftfxmemuvHNswDQYJKoZIhvcNAQEL
BQAwgZExCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTERMA8GA1UEBwwIU29tZUNp
dHkxGDAWBgNVBAoMD1NvbWVDb21wYW55VGVzdDEQMA4GA1UECwwHVGVzdGluZzEW
MBQGA1UEAwwNQW5jaG9yZVRlc3RlcjEeMBwGCSqGSIb3DQEJARYPdGVzdGluZ0B0
ZXN0ZXJzMB4XDTE5MDUyNDA3MjIyN1oXDTIwMDUyMzA3MjIyN1owgZExCzAJBgNV
BAYTAlVTMQswCQYDVQQIDAJDQTERMA8GA1UEBwwIU29tZUNpdHkxGDAWBgNVBAoM
D1NvbWVDb21wYW55VGVzdDEQMA4GA1UECwwHVGVzdGluZzEWMBQGA1UEAwwNQW5j
aG9yZVRlc3RlcjEeMBwGCSqGSIb3DQEJARYPdGVzdGluZ0B0ZXN0ZXJzMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApUM9ljs+YQiTjweQ43Pd1AzmKi2U
fGOBy6yAahXlbbFXDI+8UkA8x0QIc+YESBHOtMSdLXcnkL2lYTcz2iu2I5rVD+Ph
N98BeyBc9rA3+utK9+Mvx/5o42gN9hj91FOfJ8gcuQ2G9m39fBxEwBqhAGesZ9K3
CzkQ15j8hX+NRT4p1qqdsiPKgBWVmfoRVqN7PlxuEWwPlSZihiWAegSpmtHT0UiS
Pg2vCv7zZrdKW15qFewP7nyPL/ggFCgrrMqKrsTsFFoB4crRD6xrE4VwNOAp3ad9
eBhAoFlPHXz8+mcVCBq+tZv7QvsYrqDc8UBscjBamWAFeohrsCpPZx0dJwIDAQAB
o1MwUTAdBgNVHQ4EFgQUA8phxndgXvxag5IzrAiPnYtB+lwwHwYDVR0jBBgwFoAU
A8phxndgXvxag5IzrAiPnYtB+lwwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B
AQsFAAOCAQEAkO3nIm2PlxM8u51gwO/MpVU4gOTfjXwtt904NWMPCRNhgbWYnDMh
n1RVnrVXkgjFgprk3M1NIIFeHRClxPF4pww/ZbH4mTU7Eh9CrY+ailAjnajnt+XK
ucG7Fzjg3sbai9PKTO7Rm61IL/y6yiqvu8ij3V6U5VRwXeBSeyfMthBGfimtcedk
BbeDDCUariGKZH/J+y5utDYlmpbQ3ojxYzdINymeadd4SwqJusG60MV7fDhu487l
oGUvQyghzzAPRF/O4GvM55Om9VyvDKu31sZ9tOFG4wEoGa5JQNjoMdLXSZi/eUh4
pnnqn/DuNfyfKBzTCqMcCdlrdogQD+cxug==
-----END CERTIFICATE-----
| {
"pile_set_name": "Github"
} |
/**
* Catalan translation for bootstrap-datepicker
* J. Garcia <[email protected]>
*/
;(function($){
$.fn.datepicker.dates['ca'] = {
days: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"],
daysShort: ["Diu", "Dil", "Dmt", "Dmc", "Dij", "Div", "Dis"],
daysMin: ["dg", "dl", "dt", "dc", "dj", "dv", "ds"],
months: ["Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"],
monthsShort: ["Gen", "Feb", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Des"],
today: "Avui",
monthsTitle: "Mesos",
clear: "Esborrar",
weekStart: 1,
format: "dd/mm/yyyy"
};
}(jQuery));
| {
"pile_set_name": "Github"
} |
// System-core includes
#include "tsystem.h" //Processors count
#include "timagecache.h"
#include "tw/stringtable.h"
// Toonz scene-stage structures
#include "toonz/toonzscene.h"
#include "toonz/tscenehandle.h"
#include "toonz/sceneproperties.h"
#include "toonz/tframehandle.h"
#include "toonz/tfxhandle.h"
#include "toonz/tpalettehandle.h"
#include "toonz/txshlevel.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/tcamera.h"
#include "toonz/palettecontroller.h"
#include "tapp.h" //Toonz current objects
// Images stuff
#include "trasterimage.h"
#include "trop.h"
// Fxs stuff
#include "toutputproperties.h"
#include "trasterfx.h"
#include "toonz/scenefx.h" //Fxs tree build-up
#include "toonz/tcolumnfx.h"
// Cache management
#include "tpassivecachemanager.h"
// Flipbook
#include "flipbook.h"
#include "toonzqt/flipconsole.h"
// Qt stuff
#include <QMetaType>
#include <QRegion>
#include "toonzqt/gutil.h" //For converions between TRects and QRects
// Preferences
#include "toonz/preferences.h"
#include "previewfxmanager.h"
//=======================================================================================================
// Resume: The 'Preview Fx' command shows a flipbook associated with given fx,
// containing the appearance
// of the fx under current rendering status (including current camera,
// preview settings, schematic tree).
//
// There are some considerations to be aware of:
// 1. A Preview Fx flipbook must hold the render of the whole Preview settings
// range. Plus, many Preview Fx
// could live altogether. It could be that more than one Preview Fx window
// is active for the same fx.
// 2. The flipbook associated with a 'Preview Fx' command should react to
// updates of the rendering status.
// This should happen as long as the fx actually has a meaning in the
// rendering context - that is, if
// the user enters sub- or super-xsheets, the flipbook should continue
// rendering with
// the old data. Possibly, if modifying a sub-xsheet, an 'upper' Preview Fx
// should react accordingly.
// 3. Fx Subtree aliases retrieved through TRasterFx::getAlias() may be used
// to decide if some frame has to
// be rebuilt.
//=======================================================================================================
// Forward declarations
class PreviewFxInstance;
//=======================================================================================================
//==============================
// Preliminary functions
//------------------------------
namespace {
bool suspendedRendering = false;
PreviewFxManager *previewerInstance = 0;
// Timer used to deliver scene changes notifications in an 'overridden' fashion.
// In practice, only the last (up to a fixed time granularity) of these
// notifications
// is actually received by the manager's associated slots.
QTimer levelChangedTimer, fxChangedTimer, xsheetChangedTimer,
objectChangedTimer;
const int notificationDelay = 300;
//----------------------------------------------------------------------------
inline std::string getCacheId(const TFxP &fx, int frame) {
return std::to_string(fx->getIdentifier()) + ".noext" + std::to_string(frame);
}
//----------------------------------------------------------------------------
// NOTE: This method will not currently trespass xsheet level boundaries. It
// will not
// recognize descendants in sub-xsheets....
bool areAncestorAndDescendant(const TFxP &ancestor, const TFxP &descendant) {
if (ancestor.getPointer() == descendant.getPointer()) return true;
int i;
for (i = 0; i < ancestor->getInputPortCount(); ++i)
if (areAncestorAndDescendant(ancestor->getInputPort(i)->getFx(),
descendant))
return true;
return false;
}
//----------------------------------------------------------------------------
// Qt's contains actually returns QRegion::intersected... I wonder why...
inline bool contains(const QRegion ®ion, const TRect &rect) {
return QRegion(toQRect(rect)).subtracted(region).isEmpty();
}
//----------------------------------------------------------------------------
inline void adaptView(FlipBook *flipbook, TDimension cameraSize) {
TRect imgRect(cameraSize);
flipbook->getImageViewer()->adaptView(imgRect, imgRect);
}
}; // namespace
//=======================================================================================================
//==================================
// PreviewFxRenderPort class
//----------------------------------
//! This class receives and handles notifications from a TRenderer executing the
//! preview fx
//! rendering job.
class PreviewFxRenderPort final : public QObject, public TRenderPort {
PreviewFxInstance *m_owner;
public:
PreviewFxRenderPort(PreviewFxInstance *owner);
~PreviewFxRenderPort();
void onRenderRasterStarted(
const TRenderPort::RenderData &renderData) override;
void onRenderRasterCompleted(const RenderData &renderData) override;
void onRenderFailure(const RenderData &renderData, TException &e) override;
void onRenderFinished(bool inCanceled = false) override;
};
//----------------------------------------------------------------------------------------
PreviewFxRenderPort::PreviewFxRenderPort(PreviewFxInstance *owner)
: m_owner(owner) {}
//----------------------------------------------------------------------------------------
PreviewFxRenderPort::~PreviewFxRenderPort() {}
//=======================================================================================================
//==========================
// PreviewFxInstance
//--------------------------
class PreviewFxInstance {
public:
struct FrameInfo {
std::string m_alias;
QRegion m_renderedRegion;
FrameInfo(const std::string &alias) : m_alias(alias) {}
};
public:
TXsheetP m_xsheet;
TRasterFxP m_fx;
TRenderer m_renderer;
PreviewFxRenderPort m_renderPort;
std::set<FlipBook *> m_flipbooks;
std::set<FlipBook *> m_frozenFlips; // Used externally by PreviewFxManager
int m_start, m_end, m_step, m_initFrame;
std::map<int, FrameInfo> m_frameInfos; // Used to resume fx tree structures
std::vector<UCHAR> m_pbStatus;
TRenderSettings m_renderSettings;
TDimension m_cameraRes;
TRectD m_renderArea;
TPointD m_cameraPos;
TPointD m_subcameraDisplacement;
bool m_subcamera;
QRegion m_overallRenderedRegion;
TRect m_rectUnderRender;
bool m_renderFailed;
TLevelP m_level;
TSoundTrackP m_snd;
public:
PreviewFxInstance(TFxP fx, TXsheet *xsh);
~PreviewFxInstance();
void addFlipbook(FlipBook *&flipbook);
void detachFlipbook(FlipBook *flipbook);
void updateFlipbooks();
void refreshViewRects(bool rebuild = false);
void reset();
void reset(int frame);
// Updater methods. These refresh the manager's status, but do not launch new
// renders
// on their own. The refreshViewRects method must be invoked to trigger it.
// Observe that there may exist dependencies among them - invoking in the
// following
// declaration order is safe.
void updateFrameRange();
void updateInitialFrame();
void updateRenderSettings();
void updateCamera();
void updateFlipbookTitles();
void updatePreviewRect();
void updateAliases();
void updateAliasKeyword(const std::string &keyword);
void updateProgressBarStatus();
void onRenderRasterStarted(const TRenderPort::RenderData &renderData);
void onRenderRasterCompleted(const TRenderPort::RenderData &renderData);
void onRenderFailure(const TRenderPort::RenderData &renderData,
TException &e);
void onRenderFinished(bool isCanceled = false);
void doOnRenderRasterCompleted(const TRenderPort::RenderData &renderData);
void doOnRenderRasterStarted(const TRenderPort::RenderData &renderData);
bool isSubCameraActive() { return m_subcamera; }
private:
void cropAndStep(int &frame);
bool isFullPreview();
TFxP buildSceneFx(int frame);
void addRenderData(std::vector<TRenderer::RenderData> &datas,
ToonzScene *scene, int frame, bool rebuild);
void startRender(bool rebuild = false);
};
//------------------------------------------------------------------
inline bool PreviewFxInstance::isFullPreview() {
return dynamic_cast<TOutputFx *>((TFx *)m_fx.getPointer());
}
//------------------------------------------------------------------
inline void PreviewFxInstance::cropAndStep(int &frame) {
frame = frame < m_start ? m_start : frame;
frame = (frame > m_end && m_end > -1) ? m_end : frame;
// If a step was specified, ensure that frame is on step multiples.
int framePos = (frame - m_start) / m_step;
frame = m_start + (framePos * m_step);
}
//------------------------------------------------------------------
inline TFxP PreviewFxInstance::buildSceneFx(int frame) {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
if (isFullPreview())
return ::buildSceneFx(scene, m_xsheet.getPointer(), frame,
m_renderSettings.m_shrinkX, true);
else
return ::buildPartialSceneFx(scene, m_xsheet.getPointer(), frame, m_fx,
m_renderSettings.m_shrinkX, true);
}
//------------------------------------------------------------------
void PreviewFxInstance::addRenderData(std::vector<TRenderer::RenderData> &datas,
ToonzScene *scene, int frame,
bool rebuild) {
// Seek the image associated to the render data in the cache.
std::map<int, FrameInfo>::iterator it;
it = m_frameInfos.find(frame);
TRasterFxP builtFx =
buildSceneFx(frame); // when stereoscopic, i use this only for the alias
TRasterFxP builtFxA, builtFxB;
if (m_renderSettings.m_stereoscopic) {
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
scene->shiftCameraX(-m_renderSettings.m_stereoscopicShift / 2);
builtFxA = buildSceneFx(frame);
scene->shiftCameraX(m_renderSettings.m_stereoscopicShift);
builtFxB = buildSceneFx(frame);
scene->shiftCameraX(-m_renderSettings.m_stereoscopicShift / 2);
} else
builtFxA = builtFx;
if (it == m_frameInfos.end()) {
// Should not be - however, in this case build an associated Frame info
it = m_frameInfos.insert(std::make_pair(frame, FrameInfo(std::string())))
.first;
it->second.m_alias =
builtFx ? builtFx->getAlias(frame, m_renderSettings) : "";
}
bool isCalculated =
(!builtFx) || ((!rebuild) && ::contains(it->second.m_renderedRegion,
m_rectUnderRender));
m_pbStatus[(frame - m_start) / m_step] = isCalculated
? FlipSlider::PBFrameFinished
: FlipSlider::PBFrameNotStarted;
// If it is already present, return
if (isCalculated) return;
datas.push_back(TRenderer::RenderData(frame, m_renderSettings,
TFxPair(builtFxA, builtFxB)));
}
//-----------------------------------------------------------------------------------------
PreviewFxInstance::PreviewFxInstance(TFxP fx, TXsheet *xsh)
: m_renderer(TSystem::getProcessorCount())
, m_renderPort(this)
, m_fx(fx)
, m_cameraRes(0, 0)
, m_start(0)
, m_end(-1)
, m_initFrame(0)
, m_xsheet(xsh) {
// Install the render port on the instance renderer
m_renderer.addPort(&m_renderPort);
updateRenderSettings();
updateCamera();
updateFrameRange();
updateAliases();
}
//----------------------------------------------------------------------------------------
PreviewFxInstance::~PreviewFxInstance() {
// Stop the render - there is no need to wait for a complete (and blocking)
// render stop.
m_renderer.removePort(
&m_renderPort); // No more images to be stored in the cache!
m_renderer.stopRendering();
// Release the user cache about this instance
std::string contextName("PFX");
contextName += std::to_string(m_fx->getIdentifier());
TPassiveCacheManager::instance()->releaseContextNamesWithPrefix(contextName);
// Clear the cached images
int i;
for (i = m_start; i <= m_end; i += m_step)
TImageCache::instance()->remove(getCacheId(m_fx, i));
}
//-----------------------------------------------------------------------------------------
//! Clears the preview instance informations about passed frame, including any
//! cached image.
//! Informations needed to preview again are NOT rebuilt.
void PreviewFxInstance::reset(int frame) {
TImageCache::instance()->remove(getCacheId(m_fx, frame));
std::map<int, FrameInfo>::iterator it = m_frameInfos.find(frame);
if (it != m_frameInfos.end()) {
TRasterFxP builtFx = buildSceneFx(frame);
it->second.m_alias =
builtFx ? builtFx->getAlias(frame, m_renderSettings) : "";
it->second.m_renderedRegion = QRegion();
m_overallRenderedRegion = QRegion();
}
}
//-----------------------------------------------------------------------------------------
//! Clears the preview instance informations, including cached images.
//! Informations needed
//! to preview again are rebuilt.
void PreviewFxInstance::reset() {
int i;
for (i = m_start; i <= m_end; i += m_step)
TImageCache::instance()->remove(getCacheId(m_fx, i));
m_frameInfos.clear();
updateFrameRange();
updateRenderSettings();
updateCamera();
updateFlipbookTitles();
updateAliases();
}
//-----------------------------------------------------------------------------------------
void PreviewFxInstance::addFlipbook(FlipBook *&flipbook) {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
TOutputProperties *properties =
scene->getProperties()->getPreviewProperties();
int currFrame = flipbook ? flipbook->getCurrentFrame() - 1
: app->getCurrentFrame()->getFrame();
cropAndStep(currFrame);
if (!flipbook) {
/*-- 使用可能なFlipbookを取り出す。Poolに無い場合は新たに作る --*/
flipbook = FlipBookPool::instance()->pop();
// In case this is a subcamera preview, fit the flipbook's view. This is
// done *before* associating
// m_fx to the flipbook (using Flipbook::setLevel) - so there is no
// duplicate view refresh.
/*-- Preview Settingsで"Use Sub Camera"
* がONのとき、サブカメラ枠の外は計算しないようになる --*/
if (m_subcamera) {
// result->adaptGeometry(TRect(previewInstance->m_cameraRes)); //This
// one fits the panel, too.
adaptView(flipbook, m_cameraRes); // This one adapts the view. If has
// associated fx, calls refresh...
} else {
// Retrieve the eventual sub-camera
TCamera *currCamera = TApp::instance()
->getCurrentScene()
->getScene()
->getCurrentPreviewCamera();
TRect subcameraRect(currCamera->getInterestRect());
/*-- Viewer上でサブカメラが指定されている状態でFxPreviewをした場合 --*/
if (subcameraRect.getLx() > 0 && subcameraRect.getLy() > 0) {
/*-- サブカメラ枠のShrink --*/
if (m_renderSettings.m_shrinkX > 1 || m_renderSettings.m_shrinkY > 1) {
subcameraRect.x0 /= m_renderSettings.m_shrinkX;
subcameraRect.y0 /= m_renderSettings.m_shrinkY;
subcameraRect.x1 =
(subcameraRect.x1 + 1) / m_renderSettings.m_shrinkX - 1;
subcameraRect.y1 =
(subcameraRect.y1 + 1) / m_renderSettings.m_shrinkY - 1;
}
// Fit & pan the panel to cover the sub-camera
flipbook->adaptGeometry(subcameraRect, TRect(TPoint(), m_cameraRes));
}
}
/*-- フリーズボタンの表示 --*/
flipbook->addFreezeButtonToTitleBar();
}
m_flipbooks.insert(flipbook);
/*-- タイトルの設定。Previewコマンドから呼ばれた場合はisFullPreviewがON --*/
// Build the fx string description - Should really be moved in a better
// function...
std::wstring fxId;
TLevelColumnFx *columnFx = dynamic_cast<TLevelColumnFx *>(m_fx.getPointer());
TZeraryColumnFx *sfx = dynamic_cast<TZeraryColumnFx *>(m_fx.getPointer());
if (columnFx)
fxId =
L"Col" + QString::number(columnFx->getColumnIndex() + 1).toStdWString();
else if (sfx)
fxId = sfx->getZeraryFx()->getFxId();
else {
fxId = m_fx->getFxId();
if (fxId.empty()) fxId = m_fx->getName();
}
// Adjust the flipbook appropriately
// Decorate the description for the flipbook
if (isFullPreview()) {
flipbook->setTitle(
/*"Rendered Frames :: From " + QString::number(m_start+1) +
" To " + QString::number(m_end+1) +
" :: Step " + QString::number(m_step)*/
QObject::tr("Rendered Frames :: From %1 To %2 :: Step %3")
.arg(QString::number(m_start + 1))
.arg(QString::number(m_end + 1))
.arg(QString::number(m_step)));
TXsheet::SoundProperties *prop = new TXsheet::SoundProperties();
prop->m_frameRate = properties->getFrameRate();
m_snd = m_xsheet->makeSound(prop);
if (Preferences::instance()->fitToFlipbookEnabled())
flipbook->getImageViewer()->adaptView(TRect(m_cameraRes),
TRect(m_cameraRes));
} else
flipbook->setTitle(
QObject::tr("Preview FX :: %1 ").arg(QString::fromStdWString(fxId)));
// In case the render is a full preview, add the soundtrack
// Associate the rendered level to flipbook
flipbook->setLevel(m_fx.getPointer(), m_xsheet.getPointer(),
m_level.getPointer(), 0, m_start + 1, m_end + 1, m_step,
currFrame + 1, m_snd.getPointer());
// Add the progress bar status pointer
flipbook->setProgressBarStatus(&m_pbStatus);
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::detachFlipbook(FlipBook *flipbook) {
// Just remove the flipbook from the flipbooks container
std::set<FlipBook *>::iterator it = m_flipbooks.find(flipbook);
if (it == m_flipbooks.end()) return;
m_flipbooks.erase(it);
// If the flipbook set associated with the render is now empty, stop the
// render
if (m_flipbooks.empty()) m_renderer.stopRendering();
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateFlipbooks() {
std::set<FlipBook *>::iterator it;
for (it = m_flipbooks.begin(); it != m_flipbooks.end(); ++it) (*it)->update();
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateFrameRange() {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
TOutputProperties *properties =
scene->getProperties()->getPreviewProperties();
int frameCount = m_xsheet->getFrameCount();
// Initialize the render starting from current frame. If not in the preview
// range,
// start from the closest range extreme.
properties->getRange(m_start, m_end, m_step);
if (m_end < 0) m_end = frameCount - 1;
// Intersect with the fx active frame range
TRasterFxP rasterFx(m_fx);
TFxTimeRegion timeRegion(rasterFx->getTimeRegion());
m_start = std::max(timeRegion.getFirstFrame(), m_start);
m_end = std::min(timeRegion.getLastFrame(), m_end);
// Release all images not in the new frame range
std::map<int, FrameInfo>::iterator it, jt;
for (it = m_frameInfos.begin(); it != m_frameInfos.end();) {
if (it->first < m_start || it->first > m_end ||
((it->first - m_start) % m_step)) {
TImageCache::instance()->remove(getCacheId(m_fx, it->first));
jt = it++;
m_frameInfos.erase(jt);
} else
++it;
}
// Build a level to associate the flipbook with the rendered output
m_level->setName(std::to_string(m_fx->getIdentifier()) + ".noext");
int i;
for (i = 0; i < frameCount; i++) m_level->setFrame(TFrameId(i), 0);
// Resize and update internal containers
if (m_start > m_end) {
m_frameInfos.clear();
m_pbStatus.clear();
} else {
// Build the new frame-alias range
for (i = m_start; i <= m_end; i += m_step)
if (m_frameInfos.find(i) == m_frameInfos.end()) {
// Clear the overall rendered region and build the frame info
m_overallRenderedRegion = QRegion();
m_frameInfos.insert(std::make_pair(i, std::string()));
}
// Resize the progress bar
m_pbStatus.resize((m_end - m_start) / m_step + 1);
}
// Reset the flipbooks' frame range
std::set<FlipBook *>::iterator kt;
int currFrame;
bool fullPreview = isFullPreview();
for (kt = m_flipbooks.begin(); kt != m_flipbooks.end(); ++kt) {
currFrame = (*kt)->getCurrentFrame() - 1;
cropAndStep(currFrame);
(*kt)->setLevel(m_fx.getPointer(), m_xsheet.getPointer(),
m_level.getPointer(), 0, m_start + 1, m_end + 1, m_step,
currFrame + 1, m_snd.getPointer());
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateInitialFrame() {
// Search all flipbooks and take the minimum of each's current
std::set<FlipBook *>::iterator kt;
m_initFrame = (std::numeric_limits<int>::max)();
for (kt = m_flipbooks.begin(); kt != m_flipbooks.end(); ++kt)
m_initFrame = std::min(m_initFrame, (*kt)->getCurrentFrame() - 1);
cropAndStep(m_initFrame);
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateFlipbookTitles() {
if (isFullPreview() && m_start <= m_end) {
int start = m_start + 1;
int end = m_end + 1;
std::set<FlipBook *>::iterator kt;
for (kt = m_flipbooks.begin(); kt != m_flipbooks.end(); ++kt) {
// In the full preview case, the title must display the frame range
// informations
(*kt)->setTitle(
/*"Rendered Frames :: From " + QString::number(start) +
" To " + QString::number(end) +
" :: Step " + QString::number(m_step)*/
QObject::tr("Rendered Frames :: From %1 To %2 :: Step %3")
.arg(QString::number(start))
.arg(QString::number(end))
.arg(QString::number(m_step)));
}
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateAliases() {
if (m_start > m_end) return;
std::string newAlias;
// Build and compare the new aliases with the stored ones
std::map<int, FrameInfo>::iterator it;
for (it = m_frameInfos.begin(); it != m_frameInfos.end(); ++it) {
TRasterFxP builtFx = buildSceneFx(it->first);
newAlias = builtFx ? builtFx->getAlias(it->first, m_renderSettings) : "";
if (newAlias != it->second.m_alias) {
// Clear the overall and frame-specific rendered regions
m_overallRenderedRegion = QRegion();
it->second.m_renderedRegion = QRegion();
it->second.m_alias = newAlias;
}
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateAliasKeyword(const std::string &keyword) {
if (m_start > m_end) return;
// Remove the rendered image whose alias contains keyword
std::map<int, FrameInfo>::iterator it;
for (it = m_frameInfos.begin(); it != m_frameInfos.end(); ++it) {
if (it->second.m_alias.find(keyword) != std::string::npos) {
// Clear the overall and frame-specific rendered regions
m_overallRenderedRegion = QRegion();
it->second.m_renderedRegion = QRegion();
// Clear the cached image
TRasterImageP ri =
TImageCache::instance()->get(getCacheId(m_fx, it->first), true);
if (ri) ri->getRaster()->clear();
}
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateProgressBarStatus() {
int i;
unsigned int j;
std::map<int, FrameInfo>::iterator it;
for (i = m_start, j = 0; i <= m_end; i += m_step, ++j) {
it = m_frameInfos.find(i);
m_pbStatus[j] = ::contains(it->second.m_renderedRegion, m_rectUnderRender)
? FlipSlider::PBFrameFinished
: FlipSlider::PBFrameNotStarted;
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateRenderSettings() {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
TOutputProperties *properties =
scene->getProperties()->getPreviewProperties();
m_subcamera = properties->isSubcameraPreview();
const TRenderSettings &renderSettings = properties->getRenderSettings();
if (m_renderSettings != renderSettings) {
m_renderSettings = renderSettings;
// Erase all previuosly previewed images
int i;
for (i = m_start; i <= m_end; i += m_step)
TImageCache::instance()->remove(getCacheId(m_fx, i));
// Clear all frame-specific rendered regions
std::map<int, FrameInfo>::iterator it;
for (it = m_frameInfos.begin(); it != m_frameInfos.end(); ++it)
it->second.m_renderedRegion = QRegion();
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updateCamera() {
// Clear the overall rendered region
m_overallRenderedRegion = QRegion();
// Retrieve the preview camera
TCamera *currCamera = TApp::instance()
->getCurrentScene()
->getScene()
->getCurrentPreviewCamera();
TRect subCameraRect = currCamera->getInterestRect();
TPointD cameraPos(-0.5 * currCamera->getRes().lx,
-0.5 * currCamera->getRes().ly);
// Update the camera region and camera stage area
TDimension cameraRes(0, 0);
TRectD renderArea;
if (m_subcamera && subCameraRect.getLx() > 0 && subCameraRect.getLy() > 0) {
cameraRes = TDimension(subCameraRect.getLx(), subCameraRect.getLy());
renderArea = TRectD(subCameraRect.x0, subCameraRect.y0,
subCameraRect.x1 + 1, subCameraRect.y1 + 1) +
cameraPos;
} else {
cameraRes = currCamera->getRes();
renderArea = TRectD(cameraPos, TDimensionD(cameraRes.lx, cameraRes.ly));
}
cameraRes.lx /= m_renderSettings.m_shrinkX;
cameraRes.ly /= m_renderSettings.m_shrinkY;
if (m_cameraRes != cameraRes || m_renderArea != renderArea) {
m_cameraRes = cameraRes;
m_renderArea = renderArea;
m_cameraPos = cameraPos;
// Build the displacement needed when extracting the flipbooks' views
m_subcameraDisplacement =
TPointD(0.5 * (m_renderArea.x0 + m_renderArea.x1),
0.5 * (m_renderArea.y0 + m_renderArea.y1));
// Erase all previuosly previewed images
int i;
for (i = m_start; i <= m_end; i += m_step)
TImageCache::instance()->remove(getCacheId(m_fx, i));
// Clear all frame-specific rendered regions
std::map<int, FrameInfo>::iterator it;
for (it = m_frameInfos.begin(); it != m_frameInfos.end(); ++it)
it->second.m_renderedRegion = QRegion();
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::updatePreviewRect() {
bool isFullRender = false;
if (!m_subcamera) {
// Retrieve the eventual sub-camera
TCamera *currCamera = TApp::instance()
->getCurrentScene()
->getScene()
->getCurrentPreviewCamera();
TRect subcameraRect(currCamera->getInterestRect());
/*-- Viewer上でサブカメラが指定されていない状態でFxPreviewをした場合 --*/
if (subcameraRect.getLx() == 0 || subcameraRect.getLy() == 0)
isFullRender = true;
}
// Build all the viewRects to be calculated. They will be computed on
// consecutive
// render operations.
// NOTE: For now, we'll perform a simplicistic solution - coalesce all the
// flipbooks'
// viewrects and launch just one render.
TRectD previewRectD;
m_rectUnderRender = TRect();
int shrinkX = m_renderSettings.m_shrinkX;
int shrinkY = m_renderSettings.m_shrinkY;
if (!isFullRender) {
// For each opened flipbook
/*-- 開いているFlipbookの表示範囲を足しこんでいく --*/
std::set<FlipBook *>::iterator it;
for (it = m_flipbooks.begin(); it != m_flipbooks.end(); ++it) {
// Only visible flipbooks are considered
if ((*it)->isVisible())
// Retrieve the flipbook's viewRect. Observe that this image geometry
// is intended in shrinked image reference, and assumes that the camera
// center
// lies at coords (0.0, 0.0).
previewRectD += (*it)->getPreviewedImageGeometry();
}
// Pass from shrinked to standard image geometry
/*-- いったんShrinkを元に戻す --*/
previewRectD.x0 *= shrinkX;
previewRectD.y0 *= shrinkY;
previewRectD.x1 *= shrinkX;
previewRectD.y1 *= shrinkY;
// Now, the viewer will center the subcamera's raster instead than camera's.
// So, we have
// to correct the previewRectD by the stored displacement.
previewRectD += m_subcameraDisplacement;
/*-- 表示範囲と計算範囲の共通部分を得る --*/
previewRectD *= m_renderArea;
} else
previewRectD = m_renderArea;
// Ensure that rect has the same pixel geometry as the preview camera
/*-- 再度Shrink --*/
previewRectD -= m_cameraPos;
previewRectD.x0 = previewRectD.x0 / shrinkX;
previewRectD.y0 = previewRectD.y0 / shrinkY;
previewRectD.x1 = previewRectD.x1 / shrinkX;
previewRectD.y1 = previewRectD.y1 / shrinkY;
// Now, pass to m_cameraRes-relative coordinates
/*-- 計算エリア基準の座標 → カメラ基準の座標 --*/
TPointD shrinkedRelPos((m_renderArea.x0 - m_cameraPos.x) / shrinkX,
(m_renderArea.y0 - m_cameraPos.y) / shrinkY);
previewRectD -= shrinkedRelPos;
previewRectD.x0 = tfloor(previewRectD.x0);
previewRectD.y0 = tfloor(previewRectD.y0);
previewRectD.x1 = tceil(previewRectD.x1);
previewRectD.y1 = tceil(previewRectD.y1);
/*-- 表示しなくてはいけないRect --*/
QRect qViewRect(previewRectD.x0, previewRectD.y0, previewRectD.getLx(),
previewRectD.getLy());
/*-- 表示しなくてはいけないRectから、既に計算済みの範囲を引く =
* 新たに計算が必要な領域 --*/
QRegion viewRectRegionToRender(
QRegion(qViewRect).subtracted(m_overallRenderedRegion));
// If the rect to render has already been calculated, continue.
/*-- 新たに計算が必要な領域が無ければReturn --*/
if (viewRectRegionToRender.isEmpty()) return;
// Retrieve the minimal box containing the region yet to be rendered
/*-- 新たに計算が必要な領域を含む最小のRectを得る --*/
QRect boxRectToRender(viewRectRegionToRender.boundingRect());
/*-- 計算中のRectに登録する --*/
m_rectUnderRender = toTRect(boxRectToRender);
/*-- カメラ基準の座標 → 計算エリア基準の座標 --*/
previewRectD = toTRectD(boxRectToRender) + m_cameraPos + shrinkedRelPos;
/*-- RenderAreaをセット --*/
m_renderPort.setRenderArea(previewRectD);
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::refreshViewRects(bool rebuild) {
if (suspendedRendering) return;
if (m_flipbooks.empty()) return;
// Stop any currently running render process. It *should not* be necessary to
// wait for complete stop.
// WARNING: This requires that different rendering instances are
// simultaneously
// supported in a single TRenderer...!! We're not currently supporting this...
{
// NOTE: stopRendering(true) LOOPS and may trigger events which delete this
// very
// render instance. So we have to watch inside the manager to see if this is
// still
// alive... The following should be removed using stopRendering(false)...
// NOTE: The same problem imposes that refreshViewRects() is not invoked
// directly
// when iterating the previewInstances map - we've used a signal-slot
// connection for this.
unsigned long fxId = m_fx->getIdentifier();
m_renderer.stopRendering(true); // Wait until we've finished
QMap<unsigned long, PreviewFxInstance *> &previewInstances =
PreviewFxManager::instance()->m_previewInstances;
if (previewInstances.find(fxId) == previewInstances.end()) return;
}
if (suspendedRendering) return;
updatePreviewRect();
updateProgressBarStatus();
updateFlipbooks();
startRender(rebuild);
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::startRender(bool rebuild) {
if (m_start > m_end) return;
// Build the rendering initial frame
/*-- m_initialFrameに最初に計算するフレーム番号を格納 --*/
updateInitialFrame();
m_renderFailed = false;
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
// Fill the production-specific infos (threads count and tile size)
TOutputProperties *properties =
scene->getProperties()->getPreviewProperties();
// Update the threads number
const int procCount = TSystem::getProcessorCount();
const int threadCounts[3] = {1, procCount / 2, procCount};
int index = properties->getThreadIndex();
m_renderer.setThreadsCount(threadCounts[index]);
// Build raster granularity size
index = properties->getMaxTileSizeIndex();
const int maxTileSizes[4] = {
(std::numeric_limits<int>::max)(), TOutputProperties::LargeVal,
TOutputProperties::MediumVal, TOutputProperties::SmallVal};
int oldMaxTileSize = m_renderSettings.m_maxTileSize;
m_renderSettings.m_maxTileSize = maxTileSizes[index];
// Initialize the vector of TRenderer::RenderData to be rendered. The 'frame'
// data
// should be inserted first.
RenderDataVector *renderDatas = new RenderDataVector;
int i;
for (i = m_initFrame; i <= m_end; i += m_step)
addRenderData(*renderDatas, scene, i, rebuild);
for (i = m_start; i < m_initFrame; i += m_step)
addRenderData(*renderDatas, scene, i, rebuild);
// Restore the original max tile size
m_renderSettings.m_maxTileSize = oldMaxTileSize;
// Retrieve the renderId
unsigned long renderId = m_renderer.nextRenderId();
std::string contextName("PFX");
contextName += std::to_string(m_fx->getIdentifier());
TPassiveCacheManager::instance()->setContextName(renderId, contextName);
// Finally, start rendering all frames which were not found in cache
m_renderer.startRendering(renderDatas);
}
//----------------------------------------------------------------------------------------
void PreviewFxRenderPort::onRenderRasterStarted(
const TRenderPort::RenderData &renderData) {
m_owner->onRenderRasterStarted(renderData);
}
//----------------------------------------------------------------------------------------
void PreviewFxRenderPort::onRenderRasterCompleted(
const RenderData &renderData) {
/*-- Do not show the result if canceled while rendering --*/
if (renderData.m_info.m_isCanceled && *renderData.m_info.m_isCanceled) {
// set m_renderFailed to true in order to prevent updating
// m_overallRenderedRegion at PreviewFxInstance::onRenderFinished().
m_owner->m_renderFailed = true;
return;
}
m_owner->onRenderRasterCompleted(renderData);
}
//----------------------------------------------------------------------------------------
void PreviewFxRenderPort::onRenderFailure(const RenderData &renderData,
TException &e) {
m_owner->onRenderFailure(renderData, e);
}
//----------------------------------------------------------------------------------------
void PreviewFxRenderPort::onRenderFinished(bool isCanceled) {
m_owner->onRenderFinished(isCanceled);
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::onRenderRasterStarted(
const TRenderPort::RenderData &renderData) {
PreviewFxManager::instance()->emitStartedFrame(m_fx->getIdentifier(),
renderData);
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::onRenderRasterCompleted(
const TRenderPort::RenderData &renderData) {
PreviewFxManager::instance()->emitRenderedFrame(m_fx->getIdentifier(),
renderData);
}
//----------------------------------------------------------------------------------------
// Update the progress bar status to show the frame has started
void PreviewFxInstance::doOnRenderRasterStarted(
const TRenderPort::RenderData &renderData) {
unsigned int i, size = renderData.m_frames.size();
for (i = 0; i < size; ++i)
// Update the pb status for each cluster's frame
m_pbStatus[(renderData.m_frames[i] - m_start) / m_step] =
FlipSlider::PBFrameStarted;
/*-- 計算中の赤枠を表示する --*/
std::set<FlipBook *>::iterator it;
for (it = m_flipbooks.begin(); it != m_flipbooks.end(); ++it)
(*it)->setIsRemakingPreviewFx(true);
updateFlipbooks();
}
//----------------------------------------------------------------------------------------
// Show the rendered frame if it is some flipbook's current
void PreviewFxInstance::doOnRenderRasterCompleted(
const TRenderPort::RenderData &renderData) {
std::string cacheId(getCacheId(m_fx, renderData.m_frames[0]));
TRasterImageP ri(TImageCache::instance()->get(cacheId, true));
TRasterP ras;
if (ri)
ras = ri->getRaster();
else
ras = 0;
/*-- 16bpcで計算された場合、結果をDitheringする --*/
TRasterP rasA = renderData.m_rasA;
TRasterP rasB = renderData.m_rasB;
if (rasA->getPixelSize() == 8) // render in 64 bits
{
TRaster32P auxA(rasA->getLx(), rasA->getLy());
TRop::convert(auxA, rasA); // dithering
rasA = auxA;
if (m_renderSettings.m_stereoscopic) {
assert(rasB);
TRaster32P auxB(rasB->getLx(), rasB->getLy());
TRop::convert(auxB, rasB); // dithering
rasB = auxB;
}
}
if (!ras || (ras->getSize() != m_cameraRes)) {
TImageCache::instance()->remove(cacheId);
// Create the raster at camera resolution
ras = rasA->create(m_cameraRes.lx, m_cameraRes.ly);
ras->clear();
ri = TRasterImageP(ras);
}
// Finally, copy the rendered raster over the cached one
TRect rectUnderRender(
m_rectUnderRender); // Extract may MODIFY IT! E.g. with shrinks..!
ras = ras->extract(rectUnderRender);
if (ras) {
if (m_renderSettings.m_stereoscopic) {
assert(rasB);
TRop::makeStereoRaster(rasA, rasB);
}
ras->copy(rasA);
}
// Submit the image to the cache, for all cluster's frames
unsigned int i, size = renderData.m_frames.size();
for (i = 0; i < size; ++i) {
int frame = renderData.m_frames[i];
TImageCache::instance()->add(getCacheId(m_fx, frame), ri);
// Update the pb status
int pbIndex = (frame - m_start) / m_step;
if (pbIndex >= 0 && pbIndex < (int)m_pbStatus.size())
m_pbStatus[pbIndex] = FlipSlider::PBFrameFinished;
// Update the frame-specific rendered region
std::map<int, FrameInfo>::iterator jt = m_frameInfos.find(frame);
assert(jt != m_frameInfos.end());
jt->second.m_renderedRegion += toQRect(m_rectUnderRender);
std::set<FlipBook *>::iterator it;
int renderedFrame = frame + 1;
for (it = m_flipbooks.begin(); it != m_flipbooks.end(); ++it)
if ((*it)->getCurrentFrame() == renderedFrame)
(*it)->showFrame(renderedFrame);
}
updateFlipbooks();
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::onRenderFailure(
const TRenderPort::RenderData &renderData, TException &e) {
m_renderFailed = true;
// Update each frame status
unsigned int i, size = renderData.m_frames.size();
for (i = 0; i < size; ++i) {
int frame = renderData.m_frames[i];
// Update the pb status
int pbIndex = (frame - m_start) / m_step;
if (pbIndex >= 0 && pbIndex < (int)m_pbStatus.size())
m_pbStatus[pbIndex] = FlipSlider::PBFrameNotStarted;
}
}
//----------------------------------------------------------------------------------------
void PreviewFxInstance::onRenderFinished(bool isCanceled) {
// Update the rendered region
if (!m_renderFailed && !isCanceled)
m_overallRenderedRegion += toQRect(m_rectUnderRender);
/*-- 計算中の赤枠の表示を消す --*/
std::set<FlipBook *>::iterator it;
for (it = m_flipbooks.begin(); it != m_flipbooks.end(); ++it)
(*it)->setIsRemakingPreviewFx(false);
}
//=======================================================================================================
//=========================
// PreviewFxManager
//-------------------------
PreviewFxManager::PreviewFxManager() : QObject() {
TApp *app = TApp::instance();
qRegisterMetaType<unsigned long>("unsigned long");
qRegisterMetaType<TRenderPort::RenderData>("TRenderPort::RenderData");
/*-- Rendering終了時、各RenderPortからEmit → Flipbookの更新を行う --*/
connect(this, SIGNAL(renderedFrame(unsigned long, TRenderPort::RenderData)),
this, SLOT(onRenderedFrame(unsigned long, TRenderPort::RenderData)));
/*-- Rendering開始時、各RenderPortからEmit →
* Flipbookのプログレスバーのステータスを「計算中」にする --*/
connect(this, SIGNAL(startedFrame(unsigned long, TRenderPort::RenderData)),
this, SLOT(onStartedFrame(unsigned long, TRenderPort::RenderData)));
// connect(app->getPaletteController()->getCurrentPalette(),
// SIGNAL(colorStyleChangedOnMouseRelease()),SLOT(onLevelChanged()));
// connect(app->getPaletteController()->getCurrentPalette(),
// SIGNAL(paletteChanged()), SLOT(onLevelChanged()));
connect(app->getPaletteController()->getCurrentLevelPalette(),
SIGNAL(colorStyleChangedOnMouseRelease()), SLOT(onLevelChanged()));
connect(app->getPaletteController()->getCurrentLevelPalette(),
SIGNAL(paletteChanged()), SLOT(onLevelChanged()));
connect(app->getCurrentLevel(), SIGNAL(xshLevelChanged()), this,
SLOT(onLevelChanged()));
connect(app->getCurrentFx(), SIGNAL(fxChanged()), this, SLOT(onFxChanged()));
connect(app->getCurrentXsheet(), SIGNAL(xsheetChanged()), this,
SLOT(onXsheetChanged()));
connect(app->getCurrentObject(), SIGNAL(objectChanged(bool)), this,
SLOT(onObjectChanged(bool)));
/*-- 上記の on○○Changed() は、全て refreshViewRects をEmitしている。
→ これまでの計算を止め、新たにstartRenderをする。
(Qt::QueuedConnection
は、イベントループの手が空いた時に初めてSLOTを呼ぶ、ということ)
--*/
// Due to current implementation of PreviewFxInstance::refreshViewRects().
connect(this, SIGNAL(refreshViewRects(unsigned long)), this,
SLOT(onRefreshViewRects(unsigned long)), Qt::QueuedConnection);
previewerInstance = this;
}
//-----------------------------------------------------------------------------
PreviewFxManager::~PreviewFxManager() {}
//-----------------------------------------------------------------------------
PreviewFxManager *PreviewFxManager::instance() {
static PreviewFxManager _instance;
return &_instance;
}
//-----------------------------------------------------------------------------
FlipBook *PreviewFxManager::showNewPreview(TFxP fx, bool forceFlipbook) {
if (!fx) return 0;
/*-- fxIdは、Fxの作成ごとに1つずつインクリメントして割り振られる数字 --*/
unsigned long fxId = fx->getIdentifier();
PreviewFxInstance *previewInstance = 0;
/*-- PreviewFxInstanceをFxごとに作成する --*/
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fxId);
if (it == m_previewInstances.end()) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
previewInstance = new PreviewFxInstance(fx, xsh);
m_previewInstances.insert(fxId, previewInstance);
} else {
previewInstance = it.value();
/*-- 以前PreviewしたことのあるFxを、再度Previewしたとき --*/
if (!forceFlipbook &&
!Preferences::instance()->previewAlwaysOpenNewFlipEnabled()) {
// Search the first visible flipbook to be raised. If not found, add a new
// one.
/*--
* そのFxに関連付けられたFlipbookがあり、かつVisibleな場合は、reset()で再計算
* --*/
std::set<FlipBook *> &flipbooks = previewInstance->m_flipbooks;
std::set<FlipBook *>::iterator jt;
for (jt = flipbooks.begin(); jt != flipbooks.end(); ++jt)
if ((*jt)->isVisible()) {
reset(fx); // Also recalculate the preview
(*jt)->parentWidget()->raise();
return 0;
}
}
}
FlipBook *result = 0;
/*-- resultに必要なFlipbookを格納し、setLevelをする --*/
previewInstance->addFlipbook(result);
/*-- Flipbookのクローン時以外は forceFlipbookがfalse --*/
if (!forceFlipbook) /*-- startRenderを実行 --*/
previewInstance->refreshViewRects();
return result;
}
//-----------------------------------------------------------------------------
/*! return true if the preview fx instance for specified fx is with sub-camera
* activated
*/
bool PreviewFxManager::isSubCameraActive(TFxP fx) {
if (!fx) return false;
unsigned long fxId = fx->getIdentifier();
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fxId);
if (it == m_previewInstances.end()) return false;
return it.value()->isSubCameraActive();
}
//-----------------------------------------------------------------------------
void PreviewFxManager::refreshView(TFxP fx) {
if (!fx) return;
unsigned long fxId = fx->getIdentifier();
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fxId);
if (it == m_previewInstances.end()) return;
it.value()->refreshViewRects();
}
//-----------------------------------------------------------------------------
//! This slot is necessary to prevent problems with current implementation of
//! the
//! event-looping PreviewFxInstance::refreshViewRects function.
void PreviewFxManager::onRefreshViewRects(unsigned long id) {
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(id);
if (it != m_previewInstances.end()) it.value()->refreshViewRects();
}
//-----------------------------------------------------------------------------
void PreviewFxManager::unfreeze(FlipBook *flipbook) {
TFxP fx(flipbook->getPreviewedFx());
if (!fx) return;
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fx->getIdentifier());
if (it == m_previewInstances.end()) return;
PreviewFxInstance *previewInstance = it.value();
std::set<FlipBook *> &frozenFlips = previewInstance->m_frozenFlips;
std::set<FlipBook *>::iterator jt = frozenFlips.find(flipbook);
if (jt == frozenFlips.end()) return;
// Re-attach to the preview instance
{
frozenFlips.erase(jt);
// Before attaching, remove any old flipbook level from the cache
flipbook->clearCache();
// Also any associated pb status
delete flipbook->getProgressBarStatus();
flipbook->setProgressBarStatus(NULL);
previewInstance->addFlipbook(flipbook);
// recompute frames, if necessary (call the same process as
// PreviewFxManager::onXsheetChanged())
previewInstance->updateRenderSettings();
previewInstance->updateCamera();
previewInstance->updateFrameRange();
previewInstance->updateFlipbookTitles();
previewInstance->updateAliases();
previewInstance->refreshViewRects();
}
}
//-----------------------------------------------------------------------------
//! Observe that detached flipbooks which maintain the previewed images also
//! maintain the internal reference
//! to the previewed fx returned by the FlipBook::getPreviewedFx() method, so
//! the flipbook may be re-attached
//! (ie un-freezed) to the same preview fx.
void PreviewFxManager::freeze(FlipBook *flipbook) {
// Retrieve its previewed fx
TFxP fx(flipbook->getPreviewedFx());
if (!fx) return;
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fx->getIdentifier());
if (it == m_previewInstances.end()) return;
PreviewFxInstance *previewInstance = it.value();
// First off, detach the flipbook from the preview instance and
// insert it among the instance's frozen ones
previewInstance->detachFlipbook(flipbook);
previewInstance->m_frozenFlips.insert(flipbook);
// Then, perform the level copy
{
std::string levelName("freezed" + std::to_string(flipbook->getPoolIndex()) +
".noext");
int i;
// Clone the preview images
for (i = previewInstance->m_start; i <= previewInstance->m_end;
i += previewInstance->m_step) {
TImageP cachedImage =
TImageCache::instance()->get(getCacheId(fx, i), false);
if (cachedImage)
TImageCache::instance()->add(levelName + std::to_string(i),
cachedImage->cloneImage());
}
// Associate a level with the cached images
TLevelP freezedLevel;
freezedLevel->setName(levelName);
for (i = 0; i < previewInstance->m_level->getFrameCount(); ++i)
freezedLevel->setFrame(TFrameId(i), 0);
flipbook->setLevel(fx.getPointer(), previewInstance->m_xsheet.getPointer(),
freezedLevel.getPointer(), 0,
previewInstance->m_start + 1, previewInstance->m_end + 1,
previewInstance->m_step, flipbook->getCurrentFrame(),
previewInstance->m_snd.getPointer());
// Also, the associated PB must be cloned
std::vector<UCHAR> *newPBStatuses = new std::vector<UCHAR>;
*newPBStatuses = previewInstance->m_pbStatus;
flipbook->setProgressBarStatus(newPBStatuses);
// Traverse the PB: frames under rendering must be signed as uncompleted
std::vector<UCHAR>::iterator it;
for (it = newPBStatuses->begin(); it != newPBStatuses->end(); ++it)
if (*it == FlipSlider::PBFrameStarted)
*it = FlipSlider::PBFrameNotStarted;
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::detach(FlipBook *flipbook) {
// Retrieve its previewed fx
TFxP fx(flipbook->getPreviewedFx());
if (!fx) return;
// Search the flip among attached ones
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fx->getIdentifier());
if (it == m_previewInstances.end()) return;
PreviewFxInstance *previewInstance = it.value();
// Detach the flipbook (does nothing if flipbook is frozen)
previewInstance->detachFlipbook(flipbook);
// Eventually, it could be in frozens; detach it from there too
std::set<FlipBook *> &frozenFlips = previewInstance->m_frozenFlips;
std::set<FlipBook *>::iterator jt = frozenFlips.find(flipbook);
if (jt != frozenFlips.end()) {
flipbook->clearCache();
delete flipbook->getProgressBarStatus();
frozenFlips.erase(jt);
}
// Finally, delete the preview instance if no flipbook (active or frozen)
// remain
if (previewInstance->m_flipbooks.empty() &&
previewInstance->m_frozenFlips.empty()) {
delete it.value();
m_previewInstances.erase(it);
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::onLevelChanged() {
if (m_previewInstances.size()) {
// Build the level name as an alias keyword. All cache images associated
// with an alias containing the level name will be updated.
TXshLevel *xl = TApp::instance()->getCurrentLevel()->getLevel();
std::string aliasKeyword;
TFilePath fp = xl->getPath();
aliasKeyword = ::to_string(fp.withType(""));
QMap<unsigned long, PreviewFxInstance *>::iterator it;
for (it = m_previewInstances.begin(); it != m_previewInstances.end();
++it) {
it.value()->updateAliasKeyword(aliasKeyword);
emit refreshViewRects(it.key());
// it.value()->refreshViewRects();
}
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::onFxChanged() {
// Examinate all RenderInstances for ancestors of current fx
if (m_previewInstances.size()) {
TFxP fx = TApp::instance()->getCurrentFx()->getFx();
QMap<unsigned long, PreviewFxInstance *>::iterator it;
for (it = m_previewInstances.begin(); it != m_previewInstances.end(); ++it)
// if(areAncestorAndDescendant(it.value()->m_fx, fx)) //Currently not
// trespassing sub-xsheet boundaries
{
// in case the flipbook is frozen
if (it.value()->m_flipbooks.empty()) continue;
it.value()->updateAliases();
emit refreshViewRects(it.key());
// it.value()->refreshViewRects();
}
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::onXsheetChanged() {
// Update all rendered frames, if necessary
if (m_previewInstances.size()) {
QMap<unsigned long, PreviewFxInstance *>::iterator it;
for (it = m_previewInstances.begin(); it != m_previewInstances.end();
++it) {
// in case the flipbook is frozen
if (it.value()->m_flipbooks.empty()) continue;
it.value()->updateRenderSettings();
it.value()->updateCamera();
it.value()->updateFrameRange();
it.value()->updateFlipbookTitles();
it.value()->updateAliases();
emit refreshViewRects(it.key());
// it.value()->refreshViewRects();
}
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::onObjectChanged(bool isDragging) {
if (isDragging) return;
// Update all rendered frames, if necessary
if (m_previewInstances.size()) {
QMap<unsigned long, PreviewFxInstance *>::iterator it;
for (it = m_previewInstances.begin(); it != m_previewInstances.end();
++it) {
// in case the flipbook is frozen
if (it.value()->m_flipbooks.empty()) continue;
it.value()->updateFrameRange();
it.value()->updateFlipbookTitles();
it.value()->updateAliases();
emit refreshViewRects(it.key());
// it.value()->refreshViewRects();
}
}
}
//-----------------------------------------------------------------------------
/*--
* 既にPreviewしたことがあり、Flipbookが開いているFxを再度Previewしたときに実行される
* --*/
void PreviewFxManager::reset(TFxP fx) {
if (!fx) return;
unsigned long fxId = fx->getIdentifier();
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fxId);
if (it == m_previewInstances.end()) return;
it.value()->m_renderer.stopRendering(true);
// stopRendering(true) LOOPS and may destroy the preview instance. Recheck for
// its presence
it = m_previewInstances.find(fxId);
if (it != m_previewInstances.end()) {
it.value()->reset();
it.value()->refreshViewRects();
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::reset(TFxP fx, int frame) {
if (!fx) return;
unsigned long fxId = fx->getIdentifier();
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fxId);
if (it == m_previewInstances.end()) return;
if (it.value()->m_start > it.value()->m_end) return;
it.value()->m_renderer.stopRendering(true);
// stopRendering(true) LOOPS and may destroy the preview instance. Recheck for
// its presence
it = m_previewInstances.find(fxId);
if (it != m_previewInstances.end()) {
it.value()->reset(frame);
it.value()->refreshViewRects();
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::reset(bool detachFlipbooks) {
// Hard copy the instances pointers
QMap<unsigned long, PreviewFxInstance *> previewInstances =
m_previewInstances;
QMap<unsigned long, PreviewFxInstance *>::iterator it;
for (it = previewInstances.begin(); it != previewInstances.end(); ++it) {
// Just like the above, stopRendering(true) event-LOOPS...
it.value()->m_renderer.stopRendering(true);
if (m_previewInstances.find(it.key()) == m_previewInstances.end()) continue;
if (detachFlipbooks) {
// Reset all associated flipbooks
PreviewFxInstance *previewInstance = it.value();
// Hard copy, since detach manipulates the original
std::set<FlipBook *> flipbooks = previewInstance->m_flipbooks;
std::set<FlipBook *>::iterator jt;
for (jt = flipbooks.begin(); jt != flipbooks.end(); ++jt) {
// Detach and reset the flipbook
(*jt)->reset(); // The detachment happens in here
}
/*- Frozen
* Flipがひとつも無い場合には、この時点でpreviewInstanceが除外されている
* -*/
if (m_previewInstances.find(it.key()) == m_previewInstances.end())
continue;
// Same for frozen ones
if (!previewInstance->m_frozenFlips.empty() &&
previewInstance->m_frozenFlips.size() < 20) {
std::set<FlipBook *> frozenFlips = previewInstance->m_frozenFlips;
for (jt = frozenFlips.begin(); jt != frozenFlips.end(); ++jt) {
// Detach and reset the flipbook
(*jt)->reset(); // The detachment happens in here
}
}
// The Preview instance should have been deleted at this point (due to
// flipbook detachments)
assert(m_previewInstances.find(it.key()) == m_previewInstances.end());
} else {
it.value()->reset();
it.value()->refreshViewRects();
}
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::emitStartedFrame(
unsigned long fxId, const TRenderPort::RenderData &renderData) {
emit startedFrame(fxId, renderData);
}
//-----------------------------------------------------------------------------
void PreviewFxManager::emitRenderedFrame(
unsigned long fxId, const TRenderPort::RenderData &renderData) {
emit renderedFrame(fxId, renderData);
}
//-----------------------------------------------------------------------------
void PreviewFxManager::onStartedFrame(unsigned long fxId,
TRenderPort::RenderData renderData) {
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fxId);
if (it != m_previewInstances.end()) {
// Invoke the corresponding function. This happens in the MAIN THREAD
it.value()->doOnRenderRasterStarted(renderData);
}
}
//-----------------------------------------------------------------------------
void PreviewFxManager::onRenderedFrame(unsigned long fxId,
TRenderPort::RenderData renderData) {
QMap<unsigned long, PreviewFxInstance *>::iterator it =
m_previewInstances.find(fxId);
if (it != m_previewInstances.end()) {
// Invoke the corresponding function. This happens in the MAIN THREAD
it.value()->doOnRenderRasterCompleted(renderData);
}
}
//-----------------------------------------------------------------------------
//! The suspendRendering method allows suspension of the previewer's rendering
//! activity for safety purposes, typically related to the fact that no
//! rendering
//! process should actually be performed as the underlying scene is about to
//! change
//! or being destroyed. Upon suspension, further rendering requests are silently
//! rejected - and currently active ones are canceled and waited until they are
//! no
//! longer active.
void PreviewFxManager::suspendRendering(bool suspend) {
suspendedRendering = suspend;
if (suspend && previewerInstance) {
QMap<unsigned long, PreviewFxInstance *>::iterator it;
for (it = previewerInstance->m_previewInstances.begin();
it != previewerInstance->m_previewInstances.end(); ++it) {
it.value()->m_renderer.stopRendering(true);
}
}
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <Foundation/NSUndoManager.h>
@interface TInfoWindowUndoManager : NSUndoManager
{
_Bool _finderCanUndo;
_Bool _finderCanRedo;
}
+ (id)infoWindowUndoManager;
- (void)redo;
- (BOOL)canRedo;
- (void)undo;
- (BOOL)canUndo;
@end
| {
"pile_set_name": "Github"
} |
# Ghiro - Copyright (C) 2013-2016 Ghiro Developers.
# This file is part of Ghiro.
# See the file 'docs/LICENSE.txt' for license terms.
from lib.analyzer.base import BaseProcessingModule
try:
import magic
IS_MAGIC = True
except ImportError:
IS_MAGIC = False
class MimeProcessing(BaseProcessingModule):
"""Extracts MIME information."""
name = "MIME Analysis"
description = "This plugin extracts MIME information."
order = 10
def check_deps(self):
return IS_MAGIC
def get_magic_filetype(self, file_data):
"""Get magic file type.
@param file_data: file data
@return: file type
"""
mime = magic.Magic(mime=True)
return mime.from_buffer(file_data)
def get_filetype(self, file_data):
"""Get extended file type.
@param file_data: file data
@return: file type
"""
return magic.from_buffer(file_data)
def run(self, task):
# Get simple MIME type, example: 'image/png'
self.results["mime_type"] = self.get_magic_filetype(task.get_file_data)
# Get extended file type, example: 'PNG image data, 651 x 147, 8-bit/color RGB, non-interlaced'
self.results["file_type"] = self.get_filetype(task.get_file_data)
return self.results
| {
"pile_set_name": "Github"
} |
package com.sixthsolution.easymvp.test;
import android.support.test.filters.MediumTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* @author Saeed Masoumi ([email protected])
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class AppCompatActivityViewTest {
@Rule
public ActivityTestRule<SimpleAppCompatActivity> activityRule = new ActivityTestRule<>(
SimpleAppCompatActivity.class);
@Test
public void layout_already_inflated_with_ActivityView_annotation() {
onView(withId(R.id.base_layout)).check(matches(isDisplayed()));
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { assert } from "chai";
import Lexer from "./lexer";
import { TokenType } from "./token";
describe("lexer", () => {
describe("skipped content", () => {
it("skips whitespace", () => {
let input = " \t\r\n\t \tOpKill\t\n\t \r ";
let l = new Lexer(input);
let t = l.next();
assert.equal(t.type, TokenType.kOp);
assert.equal(t.line, 2);
assert.equal(t.data.name, "OpKill");
t = l.next();
assert.equal(t.type, TokenType.kEOF);
assert.equal(t.line, 3);
});
it("skips ; comments", () => {
let input = `; start with comment
OpKill ; end of line comment
; another comment
%1`;
let l = new Lexer(input);
let t = l.next();
assert.equal(t.type, TokenType.kOp);
assert.equal(t.data.name, "OpKill");
assert.equal(t.line, 2);
t = l.next();
assert.equal(t.type, TokenType.kResultId);
assert.equal(t.data.name, "1");
assert.equal(t.data.val, 1);
assert.equal(t.line, 4);
});
});
describe("numerics", () => {
it("parses floats", () => {
let input = ["0.0", "0.", ".0", "5.7", "5.", ".7", "-0.0", "-.0",
"-0.", "-5.7", "-5.", "-.7"];
let results = [0.0, 0.0, 0.0, 5.7, 5.0, 0.7, 0.0, 0.0, 0.0, -5.7, -5.0,
-0.7];
input.forEach((val, idx) => {
let l = new Lexer(val);
let t = l.next();
assert.equal(t.type, TokenType.kFloatLiteral,
`expected ${val} to be a float got ${t.type}`);
assert.equal(t.data, results[idx],
`expected ${results[idx]} === ${t.data}`);
t = l.next();
assert.equal(t.type, TokenType.kEOF);
assert.equal(t.data, undefined);
});
});
it("handles invalid floats", () => {
let input = [".", "-."];
input.forEach((val) => {
let l = new Lexer(val);
let t = l.next();
assert.notEqual(t.type, TokenType.kFloatLiteral,
`expect ${val} to not match type float`);
});
});
it("parses integers", () => {
let input = ["0", "-0", "123", "-123", "2147483647", "-2147483648",
"4294967295", "0x00", "0x24"];
let results = [0, 0, 123, -123,2147483647, -2147483648, 4294967295,
0x0, 0x24];
input.forEach((val, idx) => {
let l = new Lexer(val);
let t = l.next();
assert.equal(t.type, TokenType.kIntegerLiteral,
`expected ${val} to be an integer got ${t.type}`);
assert.equal(t.data, results[idx],
`expected ${results[idx]} === ${t.data}`);
t = l.next();
assert.equal(t.type, TokenType.kEOF);
assert.equal(t.data, undefined);
});
});
});
it("matches result_ids", () => {
let input = `%123
%001
%main
%_a_b_c`;
let result = [
{name: "123", val: 123},
{name: "001", val: 1},
{name: "main", val: undefined},
{name: "_a_b_c", val: undefined}
];
let l = new Lexer(input);
for (let i = 0; i < result.length; ++i) {
let t = l.next();
assert.equal(t.type, TokenType.kResultId);
assert.equal(t.data.name, result[i].name);
assert.equal(t.data.val, result[i].val);
}
});
it("matches punctuation", () => {
let input = "=";
let results = [TokenType.kEqual];
let l = new Lexer(input);
for (let i = 0; i < results.length; ++i) {
let t = l.next();
assert.equal(t.type, results[i]);
assert.equal(t.line, i + 1);
}
let t = l.next();
assert.equal(t.type, TokenType.kEOF);
});
describe("strings", () => {
it("matches strings", () => {
let input = "\"GLSL.std.450\"";
let l = new Lexer(input);
let t = l.next();
assert.equal(t.type, TokenType.kStringLiteral);
assert.equal(t.data, "GLSL.std.450");
});
it("handles unfinished strings", () => {
let input = "\"GLSL.std.450";
let l = new Lexer(input);
let t = l.next();
assert.equal(t.type, TokenType.kError);
});
it("handles escapes", () => {
let input = `"embedded\\"quote"
"embedded\\\\slash"
"embedded\\nchar"`;
let results = [`embedded\"quote`, `embedded\\slash`, `embeddednchar`];
let l = new Lexer(input);
for (let i = 0; i < results.length; ++i) {
let t = l.next();
assert.equal(t.type, TokenType.kStringLiteral, results[i]);
assert.equal(t.data, results[i]);
}
});
});
it("matches keywords", () => {
let input = "GLSL Function";
let results = ["GLSL", "Function"];
let l = new Lexer(input);
for (let i = 0; i < results.length; ++i) {
let t = l.next();
assert.equal(t.type, TokenType.kIdentifier, results[i]);
assert.equal(t.data, results[i]);
}
});
});
| {
"pile_set_name": "Github"
} |
// RUN: %clang -target mips64el-unknown-linux -O3 -S -mabi=n64 -o - -emit-llvm %s | FileCheck %s
class B0 {
double d;
};
class D0 : public B0 {
float f;
};
class B1 {
};
class D1 : public B1 {
double d;
float f;
};
class D2 : public B0 {
double d2;
};
extern D0 gd0;
extern D1 gd1;
extern D2 gd2;
// CHECK: define { i64, i64 } @_Z4foo1v()
D0 foo1(void) {
return gd0;
}
// CHECK: define { double, float } @_Z4foo2v()
D1 foo2(void) {
return gd1;
}
// CHECK-LABEL: define void @_Z4foo32D2(i64 %a0.coerce0, double %a0.coerce1)
void foo3(D2 a0) {
gd2 = a0;
}
// CHECK-LABEL: define void @_Z4foo42D0(i64 %a0.coerce0, i64 %a0.coerce1)
void foo4(D0 a0) {
gd0 = a0;
}
| {
"pile_set_name": "Github"
} |
/**************************************************************************
*
* Copyright 2009 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
#ifndef STW_TLS_H
#define STW_TLS_H
#include <windows.h>
struct stw_tls_data
{
DWORD dwThreadId;
HHOOK hCallWndProcHook;
struct stw_tls_data *next;
};
boolean
stw_tls_init(void);
boolean
stw_tls_init_thread(void);
void
stw_tls_cleanup_thread(void);
void
stw_tls_cleanup(void);
struct stw_tls_data *
stw_tls_get_data(void);
LRESULT CALLBACK
stw_call_window_proc(
int nCode,
WPARAM wParam,
LPARAM lParam );
#endif /* STW_TLS_H */
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Stdlib;
class Request extends Message implements RequestInterface
{
// generic request implementation
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:orientation="vertical"
android:layout_height="match_parent" android:background="?BrushDeepBackground">
<TextView android:id="@+id/ForumsIndexSectionItemListHeader"
android:layout_width="wrap_content" android:layout_marginTop="10dp" android:layout_gravity="center_horizontal"
android:layout_height="wrap_content" android:text="MyAnimeList" android:textSize="@dimen/FontSizeHuge" android:fontFamily="@string/font_family_light" android:textColor="?AccentColour" />
<LinearLayout
android:layout_width="match_parent" android:id="@+id/ForumsIndexSectionItemList"
android:layout_height="wrap_content" android:orientation="vertical"/>
</LinearLayout> | {
"pile_set_name": "Github"
} |
drop view a restrict
| {
"pile_set_name": "Github"
} |
(ns engulf.database
(:require [engulf.formula :as forumla]
[engulf.settings :as settings]
[engulf.utils :as utils]
[cheshire.core :as json]
[clojure.java.jdbc :as jdbc]
[clojure.walk :as walk])
(:use korma.db korma.core)
(:import java.util.UUID))
(defn connect
"Connect to the db specified in settings"
[]
(defdb db (assoc (:jdbc settings/all)
:naming {:entity (partial jdbc/as-quoted-str \`)
:fields #(.replace ^String % "-" "_")
:keyword #(.replace ^String % "-" "_") })))
(defn- dash-keys
"Convert underscores in a record map's keys into dashes"
[records]
(letfn [(kdasherize [s] (keyword (.replaceAll (name s) "_" "-")))
(fmt-kv [[k v]] [(kdasherize k) v])
(remap [m] (into {} (map fmt-kv m)))]
(if (map? records)
(remap records)
(map remap records)) ))
(defn- serialize-record-params
[{:keys [params last-result] :as record}]
(reduce
(fn [m [k v]]
(condp = k
:params (assoc m k (json/generate-string v))
:last-result (assoc m k (json/generate-string v))
(assoc m k v)))
{}
record))
(defn- deserialize-record-params
[records]
(letfn [(deserialize [record]
(-> record
(update-in [:params] (comp walk/keywordize-keys json/parse-string))
(update-in [:last-result] json/parse-string)))]
(if (map? records)
(deserialize records)
(map deserialize records) )))
(defn- serialize-record-value
[record]
(update-in record [:value] json/generate-string))
(defn- deserialize-record-value
[record]
(update-in record [:value] json/parse-string))
(defentity results
(pk :uuid)
(prepare serialize-record-value)
(transform (comp deserialize-record-value dash-keys)))
(defentity jobs
(pk :uuid)
(prepare serialize-record-params)
(transform (comp deserialize-record-params dash-keys))
(has-many results {:fk :job_uuid})) | {
"pile_set_name": "Github"
} |
import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Card, Select, List, Tag, Icon, Row, Col, Button } from 'antd';
import { FormattedMessage } from 'umi';
import TagSelect from '@/components/TagSelect';
import StandardFormRow from '@/components/StandardFormRow';
import ArticleListContent from '@/components/ArticleListContent';
import styles from './Articles.less';
const { Option } = Select;
const FormItem = Form.Item;
const pageSize = 5;
@connect(({ list, loading }) => ({
list,
loading: loading.models.list,
}))
@Form.create({
onValuesChange({ dispatch }, changedValues, allValues) {
// 表单项变化时请求数据
// eslint-disable-next-line
console.log(changedValues, allValues);
// 模拟查询表单生效
dispatch({
type: 'list/fetch',
payload: {
count: 5,
},
});
},
})
class SearchList extends Component {
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'list/fetch',
payload: {
count: 5,
},
});
}
setOwner = () => {
const { form } = this.props;
form.setFieldsValue({
owner: ['wzj'],
});
};
fetchMore = () => {
const { dispatch } = this.props;
dispatch({
type: 'list/appendFetch',
payload: {
count: pageSize,
},
});
};
render() {
const {
form,
list: { list },
loading,
} = this.props;
const { getFieldDecorator } = form;
const owners = [
{
id: 'wzj',
name: '我自己',
},
{
id: 'wjh',
name: '吴家豪',
},
{
id: 'zxx',
name: '周星星',
},
{
id: 'zly',
name: '赵丽颖',
},
{
id: 'ym',
name: '姚明',
},
];
const IconText = ({ type, text }) => (
<span>
<Icon type={type} style={{ marginRight: 8 }} />
{text}
</span>
);
const formItemLayout = {
wrapperCol: {
xs: { span: 24 },
sm: { span: 24 },
md: { span: 12 },
},
};
const actionsTextMap = {
expandText: <FormattedMessage id="component.tagSelect.expand" defaultMessage="Expand" />,
collapseText: (
<FormattedMessage id="component.tagSelect.collapse" defaultMessage="Collapse" />
),
selectAllText: <FormattedMessage id="component.tagSelect.all" defaultMessage="All" />,
};
const loadMore =
list.length > 0 ? (
<div style={{ textAlign: 'center', marginTop: 16 }}>
<Button onClick={this.fetchMore} style={{ paddingLeft: 48, paddingRight: 48 }}>
{loading ? (
<span>
<Icon type="loading" /> 加载中...
</span>
) : (
'加载更多'
)}
</Button>
</div>
) : null;
return (
<Fragment>
<Card bordered={false}>
<Form layout="inline">
<StandardFormRow title="所属类目" block style={{ paddingBottom: 11 }}>
<FormItem>
{getFieldDecorator('category')(
<TagSelect expandable actionsText={actionsTextMap}>
<TagSelect.Option value="cat1">类目一</TagSelect.Option>
<TagSelect.Option value="cat2">类目二</TagSelect.Option>
<TagSelect.Option value="cat3">类目三</TagSelect.Option>
<TagSelect.Option value="cat4">类目四</TagSelect.Option>
<TagSelect.Option value="cat5">类目五</TagSelect.Option>
<TagSelect.Option value="cat6">类目六</TagSelect.Option>
<TagSelect.Option value="cat7">类目七</TagSelect.Option>
<TagSelect.Option value="cat8">类目八</TagSelect.Option>
<TagSelect.Option value="cat9">类目九</TagSelect.Option>
<TagSelect.Option value="cat10">类目十</TagSelect.Option>
<TagSelect.Option value="cat11">类目十一</TagSelect.Option>
<TagSelect.Option value="cat12">类目十二</TagSelect.Option>
</TagSelect>
)}
</FormItem>
</StandardFormRow>
<StandardFormRow title="owner" grid>
<Row>
<Col>
<FormItem {...formItemLayout}>
{getFieldDecorator('owner', {
initialValue: ['wjh', 'zxx'],
})(
<Select
mode="multiple"
style={{ maxWidth: 286, width: '100%' }}
placeholder="选择 owner"
>
{owners.map(owner => (
<Option key={owner.id} value={owner.id}>
{owner.name}
</Option>
))}
</Select>
)}
<a className={styles.selfTrigger} onClick={this.setOwner}>
只看自己的
</a>
</FormItem>
</Col>
</Row>
</StandardFormRow>
<StandardFormRow title="其它选项" grid last>
<Row gutter={16}>
<Col xl={8} lg={10} md={12} sm={24} xs={24}>
<FormItem {...formItemLayout} label="活跃用户">
{getFieldDecorator(
'user',
{}
)(
<Select placeholder="不限" style={{ maxWidth: 200, width: '100%' }}>
<Option value="lisa">李三</Option>
</Select>
)}
</FormItem>
</Col>
<Col xl={8} lg={10} md={12} sm={24} xs={24}>
<FormItem {...formItemLayout} label="好评度">
{getFieldDecorator(
'rate',
{}
)(
<Select placeholder="不限" style={{ maxWidth: 200, width: '100%' }}>
<Option value="good">优秀</Option>
</Select>
)}
</FormItem>
</Col>
</Row>
</StandardFormRow>
</Form>
</Card>
<Card
style={{ marginTop: 24 }}
bordered={false}
bodyStyle={{ padding: '8px 32px 32px 32px' }}
>
<List
size="large"
loading={list.length === 0 ? loading : false}
rowKey="id"
itemLayout="vertical"
loadMore={loadMore}
dataSource={list}
renderItem={item => (
<List.Item
key={item.id}
actions={[
<IconText type="star-o" text={item.star} />,
<IconText type="like-o" text={item.like} />,
<IconText type="message" text={item.message} />,
]}
extra={<div className={styles.listItemExtra} />}
>
<List.Item.Meta
title={
<a className={styles.listItemMetaTitle} href={item.href}>
{item.title}
</a>
}
description={
<span>
<Tag>Ant Design</Tag>
<Tag>设计语言</Tag>
<Tag>蚂蚁金服</Tag>
</span>
}
/>
<ArticleListContent data={item} />
</List.Item>
)}
/>
</Card>
</Fragment>
);
}
}
export default SearchList;
| {
"pile_set_name": "Github"
} |
<?php
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'index' => [
'title' => 'ビートマップディスカッション投稿',
],
'item' => [
'content' => '内容',
'modding_history_link' => 'Modding履歴を見る',
],
];
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The nats-operator Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kubernetes
import (
"context"
"io/ioutil"
"k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
executil "k8s.io/client-go/util/exec"
)
// ExecInContainer runs a command in the specified container, blocking until the command finishes execution or the specified context times out.
// It returns the command's exit code (if available), its output (stdout and stderr) and the associated error (if any).
func ExecInContainer(ctx context.Context, kubeClient kubernetes.Interface, kubeCfg *rest.Config, podNamespace, podName, containerName string, args ...string) (int, error) {
var (
err error
exitCode int
)
// Build the "exec" request targeting the specified pod.
request := kubeClient.CoreV1().RESTClient().Post().Resource("pods").Namespace(podNamespace).Name(podName).SubResource("exec")
// Target the specified container and capture stdout and stderr.
request.VersionedParams(&v1.PodExecOptions{
Container: containerName,
Command: args,
Stdin: false,
Stdout: true,
Stderr: true,
TTY: false,
}, scheme.ParameterCodec)
// The "exec" request require a connection upgrade, so we must use a custom executor.
executor, err := remotecommand.NewSPDYExecutor(kubeCfg, "POST", request.URL())
if err != nil {
return -1, err
}
// For the time being we can drop stdout/stderr.
// If later on we need to capture them, we'll have to replace "ioutil.Discard" with a proper buffer.
streamOptions := remotecommand.StreamOptions{
Stdin: nil,
Stdout: ioutil.Discard,
Stderr: ioutil.Discard,
Tty: false,
}
// Perform the request and attempt to extract the command's exit code so it can be returned.
doneCh := make(chan struct{})
go func() {
if err = executor.Stream(streamOptions); err != nil {
if ceErr, ok := err.(executil.CodeExitError); ok {
exitCode = ceErr.Code
} else {
exitCode = -1
}
}
// Signal that the call to "Stream()" has finished.
close(doneCh)
}()
// Wait for the call to "Stream()" to finish or until the specified timeout.
select {
case <-doneCh:
return exitCode, err
case <-ctx.Done():
return -1, ctx.Err()
}
}
| {
"pile_set_name": "Github"
} |
/***************************************************************************
*
* Copyright (C) 2007-2010 SMSC
*
* 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.
*
*****************************************************************************/
#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/crc32.h>
#include <linux/usb/usbnet.h>
#include <linux/slab.h>
#include "smsc75xx.h"
#define SMSC_CHIPNAME "smsc75xx"
#define SMSC_DRIVER_VERSION "1.0.0"
#define HS_USB_PKT_SIZE (512)
#define FS_USB_PKT_SIZE (64)
#define DEFAULT_HS_BURST_CAP_SIZE (16 * 1024 + 5 * HS_USB_PKT_SIZE)
#define DEFAULT_FS_BURST_CAP_SIZE (6 * 1024 + 33 * FS_USB_PKT_SIZE)
#define DEFAULT_BULK_IN_DELAY (0x00002000)
#define MAX_SINGLE_PACKET_SIZE (9000)
#define LAN75XX_EEPROM_MAGIC (0x7500)
#define EEPROM_MAC_OFFSET (0x01)
#define DEFAULT_TX_CSUM_ENABLE (true)
#define DEFAULT_RX_CSUM_ENABLE (true)
#define SMSC75XX_INTERNAL_PHY_ID (1)
#define SMSC75XX_TX_OVERHEAD (8)
#define MAX_RX_FIFO_SIZE (20 * 1024)
#define MAX_TX_FIFO_SIZE (12 * 1024)
#define USB_VENDOR_ID_SMSC (0x0424)
#define USB_PRODUCT_ID_LAN7500 (0x7500)
#define USB_PRODUCT_ID_LAN7505 (0x7505)
#define RXW_PADDING 2
#define check_warn(ret, fmt, args...) \
({ if (ret < 0) netdev_warn(dev->net, fmt, ##args); })
#define check_warn_return(ret, fmt, args...) \
({ if (ret < 0) { netdev_warn(dev->net, fmt, ##args); return ret; } })
#define check_warn_goto_done(ret, fmt, args...) \
({ if (ret < 0) { netdev_warn(dev->net, fmt, ##args); goto done; } })
struct smsc75xx_priv {
struct usbnet *dev;
u32 rfe_ctl;
u32 multicast_hash_table[DP_SEL_VHF_HASH_LEN];
struct mutex dataport_mutex;
spinlock_t rfe_ctl_lock;
struct work_struct set_multicast;
};
struct usb_context {
struct usb_ctrlrequest req;
struct usbnet *dev;
};
static bool turbo_mode = true;
module_param(turbo_mode, bool, 0644);
MODULE_PARM_DESC(turbo_mode, "Enable multiple frames per Rx transaction");
static int __must_check smsc75xx_read_reg(struct usbnet *dev, u32 index,
u32 *data)
{
u32 *buf = kmalloc(4, GFP_KERNEL);
int ret;
BUG_ON(!dev);
if (!buf)
return -ENOMEM;
ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
USB_VENDOR_REQUEST_READ_REGISTER,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
00, index, buf, 4, USB_CTRL_GET_TIMEOUT);
if (unlikely(ret < 0))
netdev_warn(dev->net,
"Failed to read reg index 0x%08x: %d", index, ret);
le32_to_cpus(buf);
*data = *buf;
kfree(buf);
return ret;
}
static int __must_check smsc75xx_write_reg(struct usbnet *dev, u32 index,
u32 data)
{
u32 *buf = kmalloc(4, GFP_KERNEL);
int ret;
BUG_ON(!dev);
if (!buf)
return -ENOMEM;
*buf = data;
cpu_to_le32s(buf);
ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
USB_VENDOR_REQUEST_WRITE_REGISTER,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
00, index, buf, 4, USB_CTRL_SET_TIMEOUT);
if (unlikely(ret < 0))
netdev_warn(dev->net,
"Failed to write reg index 0x%08x: %d", index, ret);
kfree(buf);
return ret;
}
/* Loop until the read is completed with timeout
* called with phy_mutex held */
static int smsc75xx_phy_wait_not_busy(struct usbnet *dev)
{
unsigned long start_time = jiffies;
u32 val;
int ret;
do {
ret = smsc75xx_read_reg(dev, MII_ACCESS, &val);
check_warn_return(ret, "Error reading MII_ACCESS");
if (!(val & MII_ACCESS_BUSY))
return 0;
} while (!time_after(jiffies, start_time + HZ));
return -EIO;
}
static int smsc75xx_mdio_read(struct net_device *netdev, int phy_id, int idx)
{
struct usbnet *dev = netdev_priv(netdev);
u32 val, addr;
int ret;
mutex_lock(&dev->phy_mutex);
/* confirm MII not busy */
ret = smsc75xx_phy_wait_not_busy(dev);
check_warn_goto_done(ret, "MII is busy in smsc75xx_mdio_read");
/* set the address, index & direction (read from PHY) */
phy_id &= dev->mii.phy_id_mask;
idx &= dev->mii.reg_num_mask;
addr = ((phy_id << MII_ACCESS_PHY_ADDR_SHIFT) & MII_ACCESS_PHY_ADDR)
| ((idx << MII_ACCESS_REG_ADDR_SHIFT) & MII_ACCESS_REG_ADDR)
| MII_ACCESS_READ | MII_ACCESS_BUSY;
ret = smsc75xx_write_reg(dev, MII_ACCESS, addr);
check_warn_goto_done(ret, "Error writing MII_ACCESS");
ret = smsc75xx_phy_wait_not_busy(dev);
check_warn_goto_done(ret, "Timed out reading MII reg %02X", idx);
ret = smsc75xx_read_reg(dev, MII_DATA, &val);
check_warn_goto_done(ret, "Error reading MII_DATA");
ret = (u16)(val & 0xFFFF);
done:
mutex_unlock(&dev->phy_mutex);
return ret;
}
static void smsc75xx_mdio_write(struct net_device *netdev, int phy_id, int idx,
int regval)
{
struct usbnet *dev = netdev_priv(netdev);
u32 val, addr;
int ret;
mutex_lock(&dev->phy_mutex);
/* confirm MII not busy */
ret = smsc75xx_phy_wait_not_busy(dev);
check_warn_goto_done(ret, "MII is busy in smsc75xx_mdio_write");
val = regval;
ret = smsc75xx_write_reg(dev, MII_DATA, val);
check_warn_goto_done(ret, "Error writing MII_DATA");
/* set the address, index & direction (write to PHY) */
phy_id &= dev->mii.phy_id_mask;
idx &= dev->mii.reg_num_mask;
addr = ((phy_id << MII_ACCESS_PHY_ADDR_SHIFT) & MII_ACCESS_PHY_ADDR)
| ((idx << MII_ACCESS_REG_ADDR_SHIFT) & MII_ACCESS_REG_ADDR)
| MII_ACCESS_WRITE | MII_ACCESS_BUSY;
ret = smsc75xx_write_reg(dev, MII_ACCESS, addr);
check_warn_goto_done(ret, "Error writing MII_ACCESS");
ret = smsc75xx_phy_wait_not_busy(dev);
check_warn_goto_done(ret, "Timed out writing MII reg %02X", idx);
done:
mutex_unlock(&dev->phy_mutex);
}
static int smsc75xx_wait_eeprom(struct usbnet *dev)
{
unsigned long start_time = jiffies;
u32 val;
int ret;
do {
ret = smsc75xx_read_reg(dev, E2P_CMD, &val);
check_warn_return(ret, "Error reading E2P_CMD");
if (!(val & E2P_CMD_BUSY) || (val & E2P_CMD_TIMEOUT))
break;
udelay(40);
} while (!time_after(jiffies, start_time + HZ));
if (val & (E2P_CMD_TIMEOUT | E2P_CMD_BUSY)) {
netdev_warn(dev->net, "EEPROM read operation timeout");
return -EIO;
}
return 0;
}
static int smsc75xx_eeprom_confirm_not_busy(struct usbnet *dev)
{
unsigned long start_time = jiffies;
u32 val;
int ret;
do {
ret = smsc75xx_read_reg(dev, E2P_CMD, &val);
check_warn_return(ret, "Error reading E2P_CMD");
if (!(val & E2P_CMD_BUSY))
return 0;
udelay(40);
} while (!time_after(jiffies, start_time + HZ));
netdev_warn(dev->net, "EEPROM is busy");
return -EIO;
}
static int smsc75xx_read_eeprom(struct usbnet *dev, u32 offset, u32 length,
u8 *data)
{
u32 val;
int i, ret;
BUG_ON(!dev);
BUG_ON(!data);
ret = smsc75xx_eeprom_confirm_not_busy(dev);
if (ret)
return ret;
for (i = 0; i < length; i++) {
val = E2P_CMD_BUSY | E2P_CMD_READ | (offset & E2P_CMD_ADDR);
ret = smsc75xx_write_reg(dev, E2P_CMD, val);
check_warn_return(ret, "Error writing E2P_CMD");
ret = smsc75xx_wait_eeprom(dev);
if (ret < 0)
return ret;
ret = smsc75xx_read_reg(dev, E2P_DATA, &val);
check_warn_return(ret, "Error reading E2P_DATA");
data[i] = val & 0xFF;
offset++;
}
return 0;
}
static int smsc75xx_write_eeprom(struct usbnet *dev, u32 offset, u32 length,
u8 *data)
{
u32 val;
int i, ret;
BUG_ON(!dev);
BUG_ON(!data);
ret = smsc75xx_eeprom_confirm_not_busy(dev);
if (ret)
return ret;
/* Issue write/erase enable command */
val = E2P_CMD_BUSY | E2P_CMD_EWEN;
ret = smsc75xx_write_reg(dev, E2P_CMD, val);
check_warn_return(ret, "Error writing E2P_CMD");
ret = smsc75xx_wait_eeprom(dev);
if (ret < 0)
return ret;
for (i = 0; i < length; i++) {
/* Fill data register */
val = data[i];
ret = smsc75xx_write_reg(dev, E2P_DATA, val);
check_warn_return(ret, "Error writing E2P_DATA");
/* Send "write" command */
val = E2P_CMD_BUSY | E2P_CMD_WRITE | (offset & E2P_CMD_ADDR);
ret = smsc75xx_write_reg(dev, E2P_CMD, val);
check_warn_return(ret, "Error writing E2P_CMD");
ret = smsc75xx_wait_eeprom(dev);
if (ret < 0)
return ret;
offset++;
}
return 0;
}
static int smsc75xx_dataport_wait_not_busy(struct usbnet *dev)
{
int i, ret;
for (i = 0; i < 100; i++) {
u32 dp_sel;
ret = smsc75xx_read_reg(dev, DP_SEL, &dp_sel);
check_warn_return(ret, "Error reading DP_SEL");
if (dp_sel & DP_SEL_DPRDY)
return 0;
udelay(40);
}
netdev_warn(dev->net, "smsc75xx_dataport_wait_not_busy timed out");
return -EIO;
}
static int smsc75xx_dataport_write(struct usbnet *dev, u32 ram_select, u32 addr,
u32 length, u32 *buf)
{
struct smsc75xx_priv *pdata = (struct smsc75xx_priv *)(dev->data[0]);
u32 dp_sel;
int i, ret;
mutex_lock(&pdata->dataport_mutex);
ret = smsc75xx_dataport_wait_not_busy(dev);
check_warn_goto_done(ret, "smsc75xx_dataport_write busy on entry");
ret = smsc75xx_read_reg(dev, DP_SEL, &dp_sel);
check_warn_goto_done(ret, "Error reading DP_SEL");
dp_sel &= ~DP_SEL_RSEL;
dp_sel |= ram_select;
ret = smsc75xx_write_reg(dev, DP_SEL, dp_sel);
check_warn_goto_done(ret, "Error writing DP_SEL");
for (i = 0; i < length; i++) {
ret = smsc75xx_write_reg(dev, DP_ADDR, addr + i);
check_warn_goto_done(ret, "Error writing DP_ADDR");
ret = smsc75xx_write_reg(dev, DP_DATA, buf[i]);
check_warn_goto_done(ret, "Error writing DP_DATA");
ret = smsc75xx_write_reg(dev, DP_CMD, DP_CMD_WRITE);
check_warn_goto_done(ret, "Error writing DP_CMD");
ret = smsc75xx_dataport_wait_not_busy(dev);
check_warn_goto_done(ret, "smsc75xx_dataport_write timeout");
}
done:
mutex_unlock(&pdata->dataport_mutex);
return ret;
}
/* returns hash bit number for given MAC address */
static u32 smsc75xx_hash(char addr[ETH_ALEN])
{
return (ether_crc(ETH_ALEN, addr) >> 23) & 0x1ff;
}
static void smsc75xx_deferred_multicast_write(struct work_struct *param)
{
struct smsc75xx_priv *pdata =
container_of(param, struct smsc75xx_priv, set_multicast);
struct usbnet *dev = pdata->dev;
int ret;
netif_dbg(dev, drv, dev->net, "deferred multicast write 0x%08x",
pdata->rfe_ctl);
smsc75xx_dataport_write(dev, DP_SEL_VHF, DP_SEL_VHF_VLAN_LEN,
DP_SEL_VHF_HASH_LEN, pdata->multicast_hash_table);
ret = smsc75xx_write_reg(dev, RFE_CTL, pdata->rfe_ctl);
check_warn(ret, "Error writing RFE_CRL");
}
static void smsc75xx_set_multicast(struct net_device *netdev)
{
struct usbnet *dev = netdev_priv(netdev);
struct smsc75xx_priv *pdata = (struct smsc75xx_priv *)(dev->data[0]);
unsigned long flags;
int i;
spin_lock_irqsave(&pdata->rfe_ctl_lock, flags);
pdata->rfe_ctl &=
~(RFE_CTL_AU | RFE_CTL_AM | RFE_CTL_DPF | RFE_CTL_MHF);
pdata->rfe_ctl |= RFE_CTL_AB;
for (i = 0; i < DP_SEL_VHF_HASH_LEN; i++)
pdata->multicast_hash_table[i] = 0;
if (dev->net->flags & IFF_PROMISC) {
netif_dbg(dev, drv, dev->net, "promiscuous mode enabled");
pdata->rfe_ctl |= RFE_CTL_AM | RFE_CTL_AU;
} else if (dev->net->flags & IFF_ALLMULTI) {
netif_dbg(dev, drv, dev->net, "receive all multicast enabled");
pdata->rfe_ctl |= RFE_CTL_AM | RFE_CTL_DPF;
} else if (!netdev_mc_empty(dev->net)) {
struct netdev_hw_addr *ha;
netif_dbg(dev, drv, dev->net, "receive multicast hash filter");
pdata->rfe_ctl |= RFE_CTL_MHF | RFE_CTL_DPF;
netdev_for_each_mc_addr(ha, netdev) {
u32 bitnum = smsc75xx_hash(ha->addr);
pdata->multicast_hash_table[bitnum / 32] |=
(1 << (bitnum % 32));
}
} else {
netif_dbg(dev, drv, dev->net, "receive own packets only");
pdata->rfe_ctl |= RFE_CTL_DPF;
}
spin_unlock_irqrestore(&pdata->rfe_ctl_lock, flags);
/* defer register writes to a sleepable context */
schedule_work(&pdata->set_multicast);
}
static int smsc75xx_update_flowcontrol(struct usbnet *dev, u8 duplex,
u16 lcladv, u16 rmtadv)
{
u32 flow = 0, fct_flow = 0;
int ret;
if (duplex == DUPLEX_FULL) {
u8 cap = mii_resolve_flowctrl_fdx(lcladv, rmtadv);
if (cap & FLOW_CTRL_TX) {
flow = (FLOW_TX_FCEN | 0xFFFF);
/* set fct_flow thresholds to 20% and 80% */
fct_flow = (8 << 8) | 32;
}
if (cap & FLOW_CTRL_RX)
flow |= FLOW_RX_FCEN;
netif_dbg(dev, link, dev->net, "rx pause %s, tx pause %s",
(cap & FLOW_CTRL_RX ? "enabled" : "disabled"),
(cap & FLOW_CTRL_TX ? "enabled" : "disabled"));
} else {
netif_dbg(dev, link, dev->net, "half duplex");
}
ret = smsc75xx_write_reg(dev, FLOW, flow);
check_warn_return(ret, "Error writing FLOW");
ret = smsc75xx_write_reg(dev, FCT_FLOW, fct_flow);
check_warn_return(ret, "Error writing FCT_FLOW");
return 0;
}
static int smsc75xx_link_reset(struct usbnet *dev)
{
struct mii_if_info *mii = &dev->mii;
struct ethtool_cmd ecmd = { .cmd = ETHTOOL_GSET };
u16 lcladv, rmtadv;
int ret;
/* read and write to clear phy interrupt status */
ret = smsc75xx_mdio_read(dev->net, mii->phy_id, PHY_INT_SRC);
check_warn_return(ret, "Error reading PHY_INT_SRC");
smsc75xx_mdio_write(dev->net, mii->phy_id, PHY_INT_SRC, 0xffff);
ret = smsc75xx_write_reg(dev, INT_STS, INT_STS_CLEAR_ALL);
check_warn_return(ret, "Error writing INT_STS");
mii_check_media(mii, 1, 1);
mii_ethtool_gset(&dev->mii, &ecmd);
lcladv = smsc75xx_mdio_read(dev->net, mii->phy_id, MII_ADVERTISE);
rmtadv = smsc75xx_mdio_read(dev->net, mii->phy_id, MII_LPA);
netif_dbg(dev, link, dev->net, "speed: %u duplex: %d lcladv: %04x"
" rmtadv: %04x", ethtool_cmd_speed(&ecmd),
ecmd.duplex, lcladv, rmtadv);
return smsc75xx_update_flowcontrol(dev, ecmd.duplex, lcladv, rmtadv);
}
static void smsc75xx_status(struct usbnet *dev, struct urb *urb)
{
u32 intdata;
if (urb->actual_length != 4) {
netdev_warn(dev->net,
"unexpected urb length %d", urb->actual_length);
return;
}
memcpy(&intdata, urb->transfer_buffer, 4);
le32_to_cpus(&intdata);
netif_dbg(dev, link, dev->net, "intdata: 0x%08X", intdata);
if (intdata & INT_ENP_PHY_INT)
usbnet_defer_kevent(dev, EVENT_LINK_RESET);
else
netdev_warn(dev->net,
"unexpected interrupt, intdata=0x%08X", intdata);
}
static int smsc75xx_ethtool_get_eeprom_len(struct net_device *net)
{
return MAX_EEPROM_SIZE;
}
static int smsc75xx_ethtool_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *ee, u8 *data)
{
struct usbnet *dev = netdev_priv(netdev);
ee->magic = LAN75XX_EEPROM_MAGIC;
return smsc75xx_read_eeprom(dev, ee->offset, ee->len, data);
}
static int smsc75xx_ethtool_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *ee, u8 *data)
{
struct usbnet *dev = netdev_priv(netdev);
if (ee->magic != LAN75XX_EEPROM_MAGIC) {
netdev_warn(dev->net,
"EEPROM: magic value mismatch: 0x%x", ee->magic);
return -EINVAL;
}
return smsc75xx_write_eeprom(dev, ee->offset, ee->len, data);
}
static const struct ethtool_ops smsc75xx_ethtool_ops = {
.get_link = usbnet_get_link,
.nway_reset = usbnet_nway_reset,
.get_drvinfo = usbnet_get_drvinfo,
.get_msglevel = usbnet_get_msglevel,
.set_msglevel = usbnet_set_msglevel,
.get_settings = usbnet_get_settings,
.set_settings = usbnet_set_settings,
.get_eeprom_len = smsc75xx_ethtool_get_eeprom_len,
.get_eeprom = smsc75xx_ethtool_get_eeprom,
.set_eeprom = smsc75xx_ethtool_set_eeprom,
};
static int smsc75xx_ioctl(struct net_device *netdev, struct ifreq *rq, int cmd)
{
struct usbnet *dev = netdev_priv(netdev);
if (!netif_running(netdev))
return -EINVAL;
return generic_mii_ioctl(&dev->mii, if_mii(rq), cmd, NULL);
}
static void smsc75xx_init_mac_address(struct usbnet *dev)
{
/* try reading mac address from EEPROM */
if (smsc75xx_read_eeprom(dev, EEPROM_MAC_OFFSET, ETH_ALEN,
dev->net->dev_addr) == 0) {
if (is_valid_ether_addr(dev->net->dev_addr)) {
/* eeprom values are valid so use them */
netif_dbg(dev, ifup, dev->net,
"MAC address read from EEPROM");
return;
}
}
/* no eeprom, or eeprom values are invalid. generate random MAC */
eth_hw_addr_random(dev->net);
netif_dbg(dev, ifup, dev->net, "MAC address set to random_ether_addr");
}
static int smsc75xx_set_mac_address(struct usbnet *dev)
{
u32 addr_lo = dev->net->dev_addr[0] | dev->net->dev_addr[1] << 8 |
dev->net->dev_addr[2] << 16 | dev->net->dev_addr[3] << 24;
u32 addr_hi = dev->net->dev_addr[4] | dev->net->dev_addr[5] << 8;
int ret = smsc75xx_write_reg(dev, RX_ADDRH, addr_hi);
check_warn_return(ret, "Failed to write RX_ADDRH: %d", ret);
ret = smsc75xx_write_reg(dev, RX_ADDRL, addr_lo);
check_warn_return(ret, "Failed to write RX_ADDRL: %d", ret);
addr_hi |= ADDR_FILTX_FB_VALID;
ret = smsc75xx_write_reg(dev, ADDR_FILTX, addr_hi);
check_warn_return(ret, "Failed to write ADDR_FILTX: %d", ret);
ret = smsc75xx_write_reg(dev, ADDR_FILTX + 4, addr_lo);
check_warn_return(ret, "Failed to write ADDR_FILTX+4: %d", ret);
return 0;
}
static int smsc75xx_phy_initialize(struct usbnet *dev)
{
int bmcr, ret, timeout = 0;
/* Initialize MII structure */
dev->mii.dev = dev->net;
dev->mii.mdio_read = smsc75xx_mdio_read;
dev->mii.mdio_write = smsc75xx_mdio_write;
dev->mii.phy_id_mask = 0x1f;
dev->mii.reg_num_mask = 0x1f;
dev->mii.supports_gmii = 1;
dev->mii.phy_id = SMSC75XX_INTERNAL_PHY_ID;
/* reset phy and wait for reset to complete */
smsc75xx_mdio_write(dev->net, dev->mii.phy_id, MII_BMCR, BMCR_RESET);
do {
msleep(10);
bmcr = smsc75xx_mdio_read(dev->net, dev->mii.phy_id, MII_BMCR);
check_warn_return(bmcr, "Error reading MII_BMCR");
timeout++;
} while ((bmcr & BMCR_RESET) && (timeout < 100));
if (timeout >= 100) {
netdev_warn(dev->net, "timeout on PHY Reset");
return -EIO;
}
smsc75xx_mdio_write(dev->net, dev->mii.phy_id, MII_ADVERTISE,
ADVERTISE_ALL | ADVERTISE_CSMA | ADVERTISE_PAUSE_CAP |
ADVERTISE_PAUSE_ASYM);
smsc75xx_mdio_write(dev->net, dev->mii.phy_id, MII_CTRL1000,
ADVERTISE_1000FULL);
/* read and write to clear phy interrupt status */
ret = smsc75xx_mdio_read(dev->net, dev->mii.phy_id, PHY_INT_SRC);
check_warn_return(ret, "Error reading PHY_INT_SRC");
smsc75xx_mdio_write(dev->net, dev->mii.phy_id, PHY_INT_SRC, 0xffff);
smsc75xx_mdio_write(dev->net, dev->mii.phy_id, PHY_INT_MASK,
PHY_INT_MASK_DEFAULT);
mii_nway_restart(&dev->mii);
netif_dbg(dev, ifup, dev->net, "phy initialised successfully");
return 0;
}
static int smsc75xx_set_rx_max_frame_length(struct usbnet *dev, int size)
{
int ret = 0;
u32 buf;
bool rxenabled;
ret = smsc75xx_read_reg(dev, MAC_RX, &buf);
check_warn_return(ret, "Failed to read MAC_RX: %d", ret);
rxenabled = ((buf & MAC_RX_RXEN) != 0);
if (rxenabled) {
buf &= ~MAC_RX_RXEN;
ret = smsc75xx_write_reg(dev, MAC_RX, buf);
check_warn_return(ret, "Failed to write MAC_RX: %d", ret);
}
/* add 4 to size for FCS */
buf &= ~MAC_RX_MAX_SIZE;
buf |= (((size + 4) << MAC_RX_MAX_SIZE_SHIFT) & MAC_RX_MAX_SIZE);
ret = smsc75xx_write_reg(dev, MAC_RX, buf);
check_warn_return(ret, "Failed to write MAC_RX: %d", ret);
if (rxenabled) {
buf |= MAC_RX_RXEN;
ret = smsc75xx_write_reg(dev, MAC_RX, buf);
check_warn_return(ret, "Failed to write MAC_RX: %d", ret);
}
return 0;
}
static int smsc75xx_change_mtu(struct net_device *netdev, int new_mtu)
{
struct usbnet *dev = netdev_priv(netdev);
int ret;
if (new_mtu > MAX_SINGLE_PACKET_SIZE)
return -EINVAL;
ret = smsc75xx_set_rx_max_frame_length(dev, new_mtu + ETH_HLEN);
check_warn_return(ret, "Failed to set mac rx frame length");
return usbnet_change_mtu(netdev, new_mtu);
}
/* Enable or disable Rx checksum offload engine */
static int smsc75xx_set_features(struct net_device *netdev,
netdev_features_t features)
{
struct usbnet *dev = netdev_priv(netdev);
struct smsc75xx_priv *pdata = (struct smsc75xx_priv *)(dev->data[0]);
unsigned long flags;
int ret;
spin_lock_irqsave(&pdata->rfe_ctl_lock, flags);
if (features & NETIF_F_RXCSUM)
pdata->rfe_ctl |= RFE_CTL_TCPUDP_CKM | RFE_CTL_IP_CKM;
else
pdata->rfe_ctl &= ~(RFE_CTL_TCPUDP_CKM | RFE_CTL_IP_CKM);
spin_unlock_irqrestore(&pdata->rfe_ctl_lock, flags);
/* it's racing here! */
ret = smsc75xx_write_reg(dev, RFE_CTL, pdata->rfe_ctl);
check_warn_return(ret, "Error writing RFE_CTL");
return 0;
}
static int smsc75xx_reset(struct usbnet *dev)
{
struct smsc75xx_priv *pdata = (struct smsc75xx_priv *)(dev->data[0]);
u32 buf;
int ret = 0, timeout;
netif_dbg(dev, ifup, dev->net, "entering smsc75xx_reset");
ret = smsc75xx_read_reg(dev, HW_CFG, &buf);
check_warn_return(ret, "Failed to read HW_CFG: %d", ret);
buf |= HW_CFG_LRST;
ret = smsc75xx_write_reg(dev, HW_CFG, buf);
check_warn_return(ret, "Failed to write HW_CFG: %d", ret);
timeout = 0;
do {
msleep(10);
ret = smsc75xx_read_reg(dev, HW_CFG, &buf);
check_warn_return(ret, "Failed to read HW_CFG: %d", ret);
timeout++;
} while ((buf & HW_CFG_LRST) && (timeout < 100));
if (timeout >= 100) {
netdev_warn(dev->net, "timeout on completion of Lite Reset");
return -EIO;
}
netif_dbg(dev, ifup, dev->net, "Lite reset complete, resetting PHY");
ret = smsc75xx_read_reg(dev, PMT_CTL, &buf);
check_warn_return(ret, "Failed to read PMT_CTL: %d", ret);
buf |= PMT_CTL_PHY_RST;
ret = smsc75xx_write_reg(dev, PMT_CTL, buf);
check_warn_return(ret, "Failed to write PMT_CTL: %d", ret);
timeout = 0;
do {
msleep(10);
ret = smsc75xx_read_reg(dev, PMT_CTL, &buf);
check_warn_return(ret, "Failed to read PMT_CTL: %d", ret);
timeout++;
} while ((buf & PMT_CTL_PHY_RST) && (timeout < 100));
if (timeout >= 100) {
netdev_warn(dev->net, "timeout waiting for PHY Reset");
return -EIO;
}
netif_dbg(dev, ifup, dev->net, "PHY reset complete");
smsc75xx_init_mac_address(dev);
ret = smsc75xx_set_mac_address(dev);
check_warn_return(ret, "Failed to set mac address");
netif_dbg(dev, ifup, dev->net, "MAC Address: %pM", dev->net->dev_addr);
ret = smsc75xx_read_reg(dev, HW_CFG, &buf);
check_warn_return(ret, "Failed to read HW_CFG: %d", ret);
netif_dbg(dev, ifup, dev->net, "Read Value from HW_CFG : 0x%08x", buf);
buf |= HW_CFG_BIR;
ret = smsc75xx_write_reg(dev, HW_CFG, buf);
check_warn_return(ret, "Failed to write HW_CFG: %d", ret);
ret = smsc75xx_read_reg(dev, HW_CFG, &buf);
check_warn_return(ret, "Failed to read HW_CFG: %d", ret);
netif_dbg(dev, ifup, dev->net, "Read Value from HW_CFG after "
"writing HW_CFG_BIR: 0x%08x", buf);
if (!turbo_mode) {
buf = 0;
dev->rx_urb_size = MAX_SINGLE_PACKET_SIZE;
} else if (dev->udev->speed == USB_SPEED_HIGH) {
buf = DEFAULT_HS_BURST_CAP_SIZE / HS_USB_PKT_SIZE;
dev->rx_urb_size = DEFAULT_HS_BURST_CAP_SIZE;
} else {
buf = DEFAULT_FS_BURST_CAP_SIZE / FS_USB_PKT_SIZE;
dev->rx_urb_size = DEFAULT_FS_BURST_CAP_SIZE;
}
netif_dbg(dev, ifup, dev->net, "rx_urb_size=%ld",
(ulong)dev->rx_urb_size);
ret = smsc75xx_write_reg(dev, BURST_CAP, buf);
check_warn_return(ret, "Failed to write BURST_CAP: %d", ret);
ret = smsc75xx_read_reg(dev, BURST_CAP, &buf);
check_warn_return(ret, "Failed to read BURST_CAP: %d", ret);
netif_dbg(dev, ifup, dev->net,
"Read Value from BURST_CAP after writing: 0x%08x", buf);
ret = smsc75xx_write_reg(dev, BULK_IN_DLY, DEFAULT_BULK_IN_DELAY);
check_warn_return(ret, "Failed to write BULK_IN_DLY: %d", ret);
ret = smsc75xx_read_reg(dev, BULK_IN_DLY, &buf);
check_warn_return(ret, "Failed to read BULK_IN_DLY: %d", ret);
netif_dbg(dev, ifup, dev->net,
"Read Value from BULK_IN_DLY after writing: 0x%08x", buf);
if (turbo_mode) {
ret = smsc75xx_read_reg(dev, HW_CFG, &buf);
check_warn_return(ret, "Failed to read HW_CFG: %d", ret);
netif_dbg(dev, ifup, dev->net, "HW_CFG: 0x%08x", buf);
buf |= (HW_CFG_MEF | HW_CFG_BCE);
ret = smsc75xx_write_reg(dev, HW_CFG, buf);
check_warn_return(ret, "Failed to write HW_CFG: %d", ret);
ret = smsc75xx_read_reg(dev, HW_CFG, &buf);
check_warn_return(ret, "Failed to read HW_CFG: %d", ret);
netif_dbg(dev, ifup, dev->net, "HW_CFG: 0x%08x", buf);
}
/* set FIFO sizes */
buf = (MAX_RX_FIFO_SIZE - 512) / 512;
ret = smsc75xx_write_reg(dev, FCT_RX_FIFO_END, buf);
check_warn_return(ret, "Failed to write FCT_RX_FIFO_END: %d", ret);
netif_dbg(dev, ifup, dev->net, "FCT_RX_FIFO_END set to 0x%08x", buf);
buf = (MAX_TX_FIFO_SIZE - 512) / 512;
ret = smsc75xx_write_reg(dev, FCT_TX_FIFO_END, buf);
check_warn_return(ret, "Failed to write FCT_TX_FIFO_END: %d", ret);
netif_dbg(dev, ifup, dev->net, "FCT_TX_FIFO_END set to 0x%08x", buf);
ret = smsc75xx_write_reg(dev, INT_STS, INT_STS_CLEAR_ALL);
check_warn_return(ret, "Failed to write INT_STS: %d", ret);
ret = smsc75xx_read_reg(dev, ID_REV, &buf);
check_warn_return(ret, "Failed to read ID_REV: %d", ret);
netif_dbg(dev, ifup, dev->net, "ID_REV = 0x%08x", buf);
/* Configure GPIO pins as LED outputs */
ret = smsc75xx_read_reg(dev, LED_GPIO_CFG, &buf);
check_warn_return(ret, "Failed to read LED_GPIO_CFG: %d", ret);
buf &= ~(LED_GPIO_CFG_LED2_FUN_SEL | LED_GPIO_CFG_LED10_FUN_SEL);
buf |= LED_GPIO_CFG_LEDGPIO_EN | LED_GPIO_CFG_LED2_FUN_SEL;
ret = smsc75xx_write_reg(dev, LED_GPIO_CFG, buf);
check_warn_return(ret, "Failed to write LED_GPIO_CFG: %d", ret);
ret = smsc75xx_write_reg(dev, FLOW, 0);
check_warn_return(ret, "Failed to write FLOW: %d", ret);
ret = smsc75xx_write_reg(dev, FCT_FLOW, 0);
check_warn_return(ret, "Failed to write FCT_FLOW: %d", ret);
/* Don't need rfe_ctl_lock during initialisation */
ret = smsc75xx_read_reg(dev, RFE_CTL, &pdata->rfe_ctl);
check_warn_return(ret, "Failed to read RFE_CTL: %d", ret);
pdata->rfe_ctl |= RFE_CTL_AB | RFE_CTL_DPF;
ret = smsc75xx_write_reg(dev, RFE_CTL, pdata->rfe_ctl);
check_warn_return(ret, "Failed to write RFE_CTL: %d", ret);
ret = smsc75xx_read_reg(dev, RFE_CTL, &pdata->rfe_ctl);
check_warn_return(ret, "Failed to read RFE_CTL: %d", ret);
netif_dbg(dev, ifup, dev->net, "RFE_CTL set to 0x%08x", pdata->rfe_ctl);
/* Enable or disable checksum offload engines */
smsc75xx_set_features(dev->net, dev->net->features);
smsc75xx_set_multicast(dev->net);
ret = smsc75xx_phy_initialize(dev);
check_warn_return(ret, "Failed to initialize PHY: %d", ret);
ret = smsc75xx_read_reg(dev, INT_EP_CTL, &buf);
check_warn_return(ret, "Failed to read INT_EP_CTL: %d", ret);
/* enable PHY interrupts */
buf |= INT_ENP_PHY_INT;
ret = smsc75xx_write_reg(dev, INT_EP_CTL, buf);
check_warn_return(ret, "Failed to write INT_EP_CTL: %d", ret);
/* allow mac to detect speed and duplex from phy */
ret = smsc75xx_read_reg(dev, MAC_CR, &buf);
check_warn_return(ret, "Failed to read MAC_CR: %d", ret);
buf |= (MAC_CR_ADD | MAC_CR_ASD);
ret = smsc75xx_write_reg(dev, MAC_CR, buf);
check_warn_return(ret, "Failed to write MAC_CR: %d", ret);
ret = smsc75xx_read_reg(dev, MAC_TX, &buf);
check_warn_return(ret, "Failed to read MAC_TX: %d", ret);
buf |= MAC_TX_TXEN;
ret = smsc75xx_write_reg(dev, MAC_TX, buf);
check_warn_return(ret, "Failed to write MAC_TX: %d", ret);
netif_dbg(dev, ifup, dev->net, "MAC_TX set to 0x%08x", buf);
ret = smsc75xx_read_reg(dev, FCT_TX_CTL, &buf);
check_warn_return(ret, "Failed to read FCT_TX_CTL: %d", ret);
buf |= FCT_TX_CTL_EN;
ret = smsc75xx_write_reg(dev, FCT_TX_CTL, buf);
check_warn_return(ret, "Failed to write FCT_TX_CTL: %d", ret);
netif_dbg(dev, ifup, dev->net, "FCT_TX_CTL set to 0x%08x", buf);
ret = smsc75xx_set_rx_max_frame_length(dev, dev->net->mtu + ETH_HLEN);
check_warn_return(ret, "Failed to set max rx frame length");
ret = smsc75xx_read_reg(dev, MAC_RX, &buf);
check_warn_return(ret, "Failed to read MAC_RX: %d", ret);
buf |= MAC_RX_RXEN;
ret = smsc75xx_write_reg(dev, MAC_RX, buf);
check_warn_return(ret, "Failed to write MAC_RX: %d", ret);
netif_dbg(dev, ifup, dev->net, "MAC_RX set to 0x%08x", buf);
ret = smsc75xx_read_reg(dev, FCT_RX_CTL, &buf);
check_warn_return(ret, "Failed to read FCT_RX_CTL: %d", ret);
buf |= FCT_RX_CTL_EN;
ret = smsc75xx_write_reg(dev, FCT_RX_CTL, buf);
check_warn_return(ret, "Failed to write FCT_RX_CTL: %d", ret);
netif_dbg(dev, ifup, dev->net, "FCT_RX_CTL set to 0x%08x", buf);
netif_dbg(dev, ifup, dev->net, "smsc75xx_reset, return 0");
return 0;
}
static const struct net_device_ops smsc75xx_netdev_ops = {
.ndo_open = usbnet_open,
.ndo_stop = usbnet_stop,
.ndo_start_xmit = usbnet_start_xmit,
.ndo_tx_timeout = usbnet_tx_timeout,
.ndo_change_mtu = smsc75xx_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_do_ioctl = smsc75xx_ioctl,
.ndo_set_rx_mode = smsc75xx_set_multicast,
.ndo_set_features = smsc75xx_set_features,
};
static int smsc75xx_bind(struct usbnet *dev, struct usb_interface *intf)
{
struct smsc75xx_priv *pdata = NULL;
int ret;
printk(KERN_INFO SMSC_CHIPNAME " v" SMSC_DRIVER_VERSION "\n");
ret = usbnet_get_endpoints(dev, intf);
check_warn_return(ret, "usbnet_get_endpoints failed: %d", ret);
dev->data[0] = (unsigned long)kzalloc(sizeof(struct smsc75xx_priv),
GFP_KERNEL);
pdata = (struct smsc75xx_priv *)(dev->data[0]);
if (!pdata) {
netdev_warn(dev->net, "Unable to allocate smsc75xx_priv");
return -ENOMEM;
}
pdata->dev = dev;
spin_lock_init(&pdata->rfe_ctl_lock);
mutex_init(&pdata->dataport_mutex);
INIT_WORK(&pdata->set_multicast, smsc75xx_deferred_multicast_write);
if (DEFAULT_TX_CSUM_ENABLE)
dev->net->features |= NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
if (DEFAULT_RX_CSUM_ENABLE)
dev->net->features |= NETIF_F_RXCSUM;
dev->net->hw_features = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM |
NETIF_F_RXCSUM;
/* Init all registers */
ret = smsc75xx_reset(dev);
dev->net->netdev_ops = &smsc75xx_netdev_ops;
dev->net->ethtool_ops = &smsc75xx_ethtool_ops;
dev->net->flags |= IFF_MULTICAST;
dev->net->hard_header_len += SMSC75XX_TX_OVERHEAD;
dev->hard_mtu = dev->net->mtu + dev->net->hard_header_len;
return 0;
}
static void smsc75xx_unbind(struct usbnet *dev, struct usb_interface *intf)
{
struct smsc75xx_priv *pdata = (struct smsc75xx_priv *)(dev->data[0]);
if (pdata) {
netif_dbg(dev, ifdown, dev->net, "free pdata");
kfree(pdata);
pdata = NULL;
dev->data[0] = 0;
}
}
static void smsc75xx_rx_csum_offload(struct usbnet *dev, struct sk_buff *skb,
u32 rx_cmd_a, u32 rx_cmd_b)
{
if (!(dev->net->features & NETIF_F_RXCSUM) ||
unlikely(rx_cmd_a & RX_CMD_A_LCSM)) {
skb->ip_summed = CHECKSUM_NONE;
} else {
skb->csum = ntohs((u16)(rx_cmd_b >> RX_CMD_B_CSUM_SHIFT));
skb->ip_summed = CHECKSUM_COMPLETE;
}
}
static int smsc75xx_rx_fixup(struct usbnet *dev, struct sk_buff *skb)
{
/* This check is no longer done by usbnet */
if (skb->len < dev->net->hard_header_len)
return 0;
while (skb->len > 0) {
u32 rx_cmd_a, rx_cmd_b, align_count, size;
struct sk_buff *ax_skb;
unsigned char *packet;
memcpy(&rx_cmd_a, skb->data, sizeof(rx_cmd_a));
le32_to_cpus(&rx_cmd_a);
skb_pull(skb, 4);
memcpy(&rx_cmd_b, skb->data, sizeof(rx_cmd_b));
le32_to_cpus(&rx_cmd_b);
skb_pull(skb, 4 + RXW_PADDING);
packet = skb->data;
/* get the packet length */
size = (rx_cmd_a & RX_CMD_A_LEN) - RXW_PADDING;
align_count = (4 - ((size + RXW_PADDING) % 4)) % 4;
if (unlikely(rx_cmd_a & RX_CMD_A_RED)) {
netif_dbg(dev, rx_err, dev->net,
"Error rx_cmd_a=0x%08x", rx_cmd_a);
dev->net->stats.rx_errors++;
dev->net->stats.rx_dropped++;
if (rx_cmd_a & RX_CMD_A_FCS)
dev->net->stats.rx_crc_errors++;
else if (rx_cmd_a & (RX_CMD_A_LONG | RX_CMD_A_RUNT))
dev->net->stats.rx_frame_errors++;
} else {
/* MAX_SINGLE_PACKET_SIZE + 4(CRC) + 2(COE) + 4(Vlan) */
if (unlikely(size > (MAX_SINGLE_PACKET_SIZE + ETH_HLEN + 12))) {
netif_dbg(dev, rx_err, dev->net,
"size err rx_cmd_a=0x%08x", rx_cmd_a);
return 0;
}
/* last frame in this batch */
if (skb->len == size) {
smsc75xx_rx_csum_offload(dev, skb, rx_cmd_a,
rx_cmd_b);
skb_trim(skb, skb->len - 4); /* remove fcs */
skb->truesize = size + sizeof(struct sk_buff);
return 1;
}
ax_skb = skb_clone(skb, GFP_ATOMIC);
if (unlikely(!ax_skb)) {
netdev_warn(dev->net, "Error allocating skb");
return 0;
}
ax_skb->len = size;
ax_skb->data = packet;
skb_set_tail_pointer(ax_skb, size);
smsc75xx_rx_csum_offload(dev, ax_skb, rx_cmd_a,
rx_cmd_b);
skb_trim(ax_skb, ax_skb->len - 4); /* remove fcs */
ax_skb->truesize = size + sizeof(struct sk_buff);
usbnet_skb_return(dev, ax_skb);
}
skb_pull(skb, size);
/* padding bytes before the next frame starts */
if (skb->len)
skb_pull(skb, align_count);
}
if (unlikely(skb->len < 0)) {
netdev_warn(dev->net, "invalid rx length<0 %d", skb->len);
return 0;
}
return 1;
}
static struct sk_buff *smsc75xx_tx_fixup(struct usbnet *dev,
struct sk_buff *skb, gfp_t flags)
{
u32 tx_cmd_a, tx_cmd_b;
if (skb_headroom(skb) < SMSC75XX_TX_OVERHEAD) {
struct sk_buff *skb2 =
skb_copy_expand(skb, SMSC75XX_TX_OVERHEAD, 0, flags);
dev_kfree_skb_any(skb);
skb = skb2;
if (!skb)
return NULL;
}
tx_cmd_a = (u32)(skb->len & TX_CMD_A_LEN) | TX_CMD_A_FCS;
if (skb->ip_summed == CHECKSUM_PARTIAL)
tx_cmd_a |= TX_CMD_A_IPE | TX_CMD_A_TPE;
if (skb_is_gso(skb)) {
u16 mss = max(skb_shinfo(skb)->gso_size, TX_MSS_MIN);
tx_cmd_b = (mss << TX_CMD_B_MSS_SHIFT) & TX_CMD_B_MSS;
tx_cmd_a |= TX_CMD_A_LSO;
} else {
tx_cmd_b = 0;
}
skb_push(skb, 4);
cpu_to_le32s(&tx_cmd_b);
memcpy(skb->data, &tx_cmd_b, 4);
skb_push(skb, 4);
cpu_to_le32s(&tx_cmd_a);
memcpy(skb->data, &tx_cmd_a, 4);
return skb;
}
static const struct driver_info smsc75xx_info = {
.description = "smsc75xx USB 2.0 Gigabit Ethernet",
.bind = smsc75xx_bind,
.unbind = smsc75xx_unbind,
.link_reset = smsc75xx_link_reset,
.reset = smsc75xx_reset,
.rx_fixup = smsc75xx_rx_fixup,
.tx_fixup = smsc75xx_tx_fixup,
.status = smsc75xx_status,
.flags = FLAG_ETHER | FLAG_SEND_ZLP | FLAG_LINK_INTR,
};
static const struct usb_device_id products[] = {
{
/* SMSC7500 USB Gigabit Ethernet Device */
USB_DEVICE(USB_VENDOR_ID_SMSC, USB_PRODUCT_ID_LAN7500),
.driver_info = (unsigned long) &smsc75xx_info,
},
{
/* SMSC7500 USB Gigabit Ethernet Device */
USB_DEVICE(USB_VENDOR_ID_SMSC, USB_PRODUCT_ID_LAN7505),
.driver_info = (unsigned long) &smsc75xx_info,
},
{ }, /* END */
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver smsc75xx_driver = {
.name = SMSC_CHIPNAME,
.id_table = products,
.probe = usbnet_probe,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
.disconnect = usbnet_disconnect,
};
module_usb_driver(smsc75xx_driver);
MODULE_AUTHOR("Nancy Lin");
MODULE_AUTHOR("Steve Glendinning <[email protected]>");
MODULE_DESCRIPTION("SMSC75XX USB 2.0 Gigabit Ethernet Devices");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 gradlebuild.binarycompatibility
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.UnexpectedBuildFailure
import org.hamcrest.CoreMatchers
import org.junit.Assert.assertFalse
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import java.io.File
import java.nio.file.Files
import org.gradle.kotlin.dsl.*
abstract class AbstractBinaryCompatibilityTest {
@get:Rule
val tmpDir = TemporaryFolder()
private
val rootDir: File
get() = tmpDir.root
internal
fun checkBinaryCompatibleKotlin(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult =
runKotlinBinaryCompatibilityCheck(v1, v2) {
assertBinaryCompatible()
block()
}
internal
fun checkNotBinaryCompatibleKotlin(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult =
runKotlinBinaryCompatibilityCheck(v1, v2) {
assertNotBinaryCompatible()
block()
}
internal
fun checkBinaryCompatibleJava(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult =
runJavaBinaryCompatibilityCheck(v1, v2) {
assertBinaryCompatible()
block()
}
internal
fun checkNotBinaryCompatibleJava(v1: String = "", v2: String, block: CheckResult.() -> Unit = {}): CheckResult =
runJavaBinaryCompatibilityCheck(v1, v2) {
assertNotBinaryCompatible()
block()
}
internal
fun checkBinaryCompatible(v1: File.() -> Unit = {}, v2: File.() -> Unit = {}, block: CheckResult.() -> Unit = {}): CheckResult =
runBinaryCompatibilityCheck(v1, v2) {
assertBinaryCompatible()
block()
}
internal
fun checkNotBinaryCompatible(v1: File.() -> Unit = {}, v2: File.() -> Unit = {}, block: CheckResult.() -> Unit = {}): CheckResult =
runBinaryCompatibilityCheck(v1, v2) {
assertNotBinaryCompatible()
block()
}
private
fun CheckResult.assertBinaryCompatible() {
assertTrue(richReport.toAssertionMessage("Expected to be compatible but the check failed"), isBinaryCompatible)
}
private
fun CheckResult.assertNotBinaryCompatible() {
assertFalse(richReport.toAssertionMessage("Expected to be breaking but the check passed"), isBinaryCompatible)
}
private
fun RichReport.toAssertionMessage(message: String) =
if (isEmpty) "$message with an empty report"
else "$message\n${toText().prependIndent(" ")}"
private
fun runKotlinBinaryCompatibilityCheck(v1: String, v2: String, block: CheckResult.() -> Unit = {}): CheckResult =
runBinaryCompatibilityCheck(
v1 = {
withFile("kotlin/com/example/Source.kt", """
package com.example
import org.gradle.api.Incubating
import javax.annotation.Nullable
$v1
""")
},
v2 = {
withFile("kotlin/com/example/Source.kt", """
package com.example
import org.gradle.api.Incubating
import javax.annotation.Nullable
$v2
""")
},
block = block
)
private
fun runJavaBinaryCompatibilityCheck(v1: String, v2: String, block: CheckResult.() -> Unit = {}): CheckResult =
runBinaryCompatibilityCheck(
v1 = {
withFile("java/com/example/Source.java", """
package com.example;
import org.gradle.api.Incubating;
import javax.annotation.Nullable;
$v1
""")
},
v2 = {
withFile("java/com/example/Source.java", """
package com.example;
import org.gradle.api.Incubating;
import javax.annotation.Nullable;
$v2
""")
},
block = block
)
/**
* Runs the binary compatibility check against two source trees.
*
* The fixture build supports both Java and Kotlin sources.
*
* @param v1 sources producer for V1, receiver is the `src/main` directory
* @param v2 sources producer for V2, receiver is the `src/main` directory
* @param block convenience block invoked on the result
* @return the check result
*/
private
fun runBinaryCompatibilityCheck(v1: File.() -> Unit, v2: File.() -> Unit, block: CheckResult.() -> Unit = {}): CheckResult {
val inputBuildDir = rootDir.withUniqueDirectory("input-build").apply {
withSettings("""include("v1", "v2", "binary-compatibility")""")
withBuildScript("""
import gradlebuild.identity.extension.ModuleIdentityExtension
plugins {
base
kotlin("jvm") version "$embeddedKotlinVersion" apply false
}
subprojects {
apply(plugin = "gradlebuild.module-identity")
apply(plugin = "kotlin")
the<ModuleIdentityExtension>().baseName.set("api-module")
repositories {
jcenter()
}
dependencies {
"implementation"(gradleApi())
"implementation"(kotlin("stdlib"))
}
}
project(":v1") {
version = "1.0"
}
project(":v2") {
version = "2.0"
}
""")
withDirectory("v1/src/main").v1()
withDirectory("v2/src/main").v2()
withDirectory("binary-compatibility").apply {
withBuildScript("""
import japicmp.model.JApiChangeStatus
import me.champeau.gradle.japicmp.JapicmpTask
import gradlebuild.binarycompatibility.*
import gradlebuild.binarycompatibility.filters.*
tasks.register<JapicmpTask>("checkBinaryCompatibility") {
dependsOn(":v1:jar", ":v2:jar")
val v1 = rootProject.project(":v1")
val v1Jar = v1.tasks.named("jar")
val v2 = rootProject.project(":v2")
val v2Jar = v2.tasks.named("jar")
oldArchives = files(v1Jar)
oldClasspath = files(v1.configurations.named("runtimeClasspath"), v1Jar)
newArchives = files(v2Jar)
newClasspath = files(v2.configurations.named("runtimeClasspath"), v2Jar)
isOnlyModified = false
isFailOnModification = false // we rely on the rich report to fail
txtOutputFile = file("build/japi-report.txt")
richReport {
title = "Gradle Binary Compatibility Check"
destinationDir = file("build/japi")
reportName = "japi.html"
includedClasses = listOf(".*")
excludedClasses = emptyList()
}
BinaryCompatibilityHelper.setupJApiCmpRichReportRules(
this,
AcceptedApiChanges.parse("{acceptedApiChanges:[]}"),
rootProject.files("v2/src/main/kotlin"),
"2.0"
)
}
""")
}
}
val runner = GradleRunner.create()
.withProjectDir(inputBuildDir)
.withPluginClasspath()
.withArguments(":binary-compatibility:checkBinaryCompatibility", "-s")
val (buildResult, failure) = try {
runner.build()!! to null
} catch (ex: UnexpectedBuildFailure) {
ex.buildResult!! to ex
}
println(buildResult.output)
val richReportFile = inputBuildDir.resolve("binary-compatibility/build/japi/japi.html").apply {
assertTrue("Rich report file exists", isFile)
}
return CheckResult(failure, scrapeRichReport(richReportFile), buildResult).apply {
println(richReport.toText())
block()
}
}
internal
data class CheckResult(
val checkFailure: UnexpectedBuildFailure?,
val richReport: RichReport,
val buildResult: BuildResult
) {
val isBinaryCompatible = checkFailure == null
fun assertEmptyReport() {
assertHasNoError()
assertHasNoWarning()
assertHasNoInformation()
}
fun assertHasNoError() {
assertTrue("Has no error (${richReport.errors})", richReport.errors.isEmpty())
}
fun assertHasNoWarning() {
assertTrue("Has no warning (${richReport.warnings})", richReport.warnings.isEmpty())
}
fun assertHasNoInformation() {
assertTrue("Has no information (${richReport.information})", richReport.information.isEmpty())
}
fun assertHasErrors(vararg errors: String) {
assertThat("Has errors", richReport.errors.map { it.message }, CoreMatchers.equalTo(errors.toList()))
}
fun assertHasWarnings(vararg warnings: String) {
assertThat("Has warnings", richReport.warnings.map { it.message }, CoreMatchers.equalTo(warnings.toList()))
}
fun assertHasInformation(vararg information: String) {
assertThat("Has information", richReport.information.map { it.message }, CoreMatchers.equalTo(information.toList()))
}
fun assertHasErrors(vararg errors: List<String>) {
assertHasErrors(*errors.toList().flatten().toTypedArray())
}
fun assertHasErrors(vararg errorWithDetail: Pair<String, List<String>>) {
assertThat("Has errors", richReport.errors, CoreMatchers.equalTo(errorWithDetail.map { ReportMessage(it.first, it.second) }))
}
fun newApi(thing: String, desc: String): String =
"$thing ${describe(thing, desc)}: New public API in 2.0 (@Incubating)"
fun added(thing: String, desc: String): List<String> =
listOf(
"$thing ${describe(thing, desc)}: Is not annotated with @Incubating.",
"$thing ${describe(thing, desc)}: Is not annotated with @since 2.0."
)
fun removed(thing: String, desc: String): Pair<String, List<String>> =
"$thing ${describe(thing, desc)}: Is not binary compatible." to listOf("$thing has been removed")
private
fun describe(thing: String, desc: String) =
if (thing == "Field") desc else "com.example.$desc"
}
protected
fun File.withFile(path: String, text: String = ""): File =
resolve(path).apply {
parentFile.mkdirs()
writeText(text.trimIndent())
}
private
fun File.withUniqueDirectory(prefixPath: String): File =
Files.createTempDirectory(
withDirectory(prefixPath.substringBeforeLast("/")).toPath(),
prefixPath.substringAfterLast("/")
).toFile()
private
fun File.withDirectory(path: String): File =
resolve(path).apply {
mkdirs()
}
private
fun File.withSettings(text: String = ""): File =
withFile("settings.gradle.kts", text)
private
fun File.withBuildScript(text: String = ""): File =
withFile("build.gradle.kts", text)
}
| {
"pile_set_name": "Github"
} |
/*
* Autopsy Forensic Browser
*
* Copyright 2018-2019 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.timeline.ui.filtering.datamodel;
/**
* A FilterState implementation for DescriptionFilters.
*/
public class DescriptionFilterState extends AbstractFilterState<DescriptionFilter> {
public DescriptionFilterState(DescriptionFilter filter) {
this(filter, false);
}
public DescriptionFilterState(DescriptionFilter filter, boolean selected) {
super(filter, selected);
}
@Override
public String getDisplayName() {
return getFilter().getDescription();
}
@Override
public DescriptionFilterState copyOf() {
DescriptionFilterState copy = new DescriptionFilterState(getFilter());
copy.setSelected(isSelected());
copy.setDisabled(isDisabled());
return copy;
}
@Override
public String toString() {
return "DescriptionFilterState{"
+ " filter=" + getFilter().toString()
+ ", selected=" + isSelected()
+ ", disabled=" + isDisabled()
+ ", activeProp=" + isActive() + '}'; //NON-NLS
}
}
| {
"pile_set_name": "Github"
} |
public class Class1
{
public Class1()
{
var t = new Module.T();
t.|Dispose|(0)();
((System.IDisposable) t).Dispose();
}
}
---------------------------------------------------------
(0): ReSharper Underlined Error Highlighting: Cannot access explicit implementation of 'IDisposable.Dispose'
M:Module.T.#ctor
M:Module.T.System#IDisposable#Dispose
M:Module.T.System#IDisposable#Dispose
| {
"pile_set_name": "Github"
} |
<robot name="blob328">
<link name="random_obj_328">
<contact>
<lateral_friction value="1.0"/>
<rolling_friction value="0.0"/>
<inertia_scaling value="3.0"/>
<contact_cfm value="0.0"/>
<contact_erp value="1.0"/>
</contact>
<inertial>
<origin rpy="0 0 0" xyz="0 0 0"/>
<mass value="0.0823"/>
<inertia ixx="1" ixy="0" ixz="0" iyy="1" iyz="0" izz="0"/>
</inertial>
<visual>
<origin rpy="0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="328.obj" scale="0.0086 0.0086 0.0086"/>
</geometry>
<material name="blockmat">
<color rgba="0.73 0.48 0.89 1"/>
</material>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="328_coll.obj" scale="0.0086 0.0086 0.0086"/>
</geometry>
</collision>
</link>
</robot>
| {
"pile_set_name": "Github"
} |
{% extends "../../layout.twig" %}
{% set page_title = 'Localization' %}
{% set page_slug = '/localization/' %}
{% block page %}
<h1 id="overwrite-dictionary">{{page_title}}</h1>
<p>How to overwrite dictionary when instantiating Conversational Form.</p>
<p data-height="465" data-theme-id="light" data-slug-hash="ZvWwbo" data-default-tab="js,result" data-user="space10" data-embed-version="2" data-pen-title="Conversational Form - Localization" class="codepen">See the Pen <a href="https://codepen.io/space10/pen/ZvWwbo/">Conversational Form - Localization</a> by SPACE10 (<a href="https://codepen.io/jenssog">@space10</a>) on <a href="https://codepen.io">CodePen</a>.</p>
{% endblock %} | {
"pile_set_name": "Github"
} |
package B::Showlex;
our $VERSION = '1.02';
use strict;
use B qw(svref_2object comppadlist class);
use B::Terse ();
use B::Concise ();
#
# Invoke as
# perl -MO=Showlex,foo bar.pl
# to see the names of lexical variables used by &foo
# or as
# perl -MO=Showlex bar.pl
# to see the names of file scope lexicals used by bar.pl
#
# borrowed from B::Concise
our $walkHandle = \*STDOUT;
sub walk_output { # updates $walkHandle
$walkHandle = B::Concise::walk_output(@_);
#print "got $walkHandle";
#print $walkHandle "using it";
$walkHandle;
}
sub shownamearray {
my ($name, $av) = @_;
my @els = $av->ARRAY;
my $count = @els;
my $i;
print $walkHandle "$name has $count entries\n";
for ($i = 0; $i < $count; $i++) {
my $sv = $els[$i];
if (class($sv) ne "SPECIAL") {
printf $walkHandle "$i: %s (0x%lx) %s\n", class($sv), $$sv, $sv->PVX;
} else {
printf $walkHandle "$i: %s\n", $sv->terse;
#printf $walkHandle "$i: %s\n", B::Concise::concise_sv($sv);
}
}
}
sub showvaluearray {
my ($name, $av) = @_;
my @els = $av->ARRAY;
my $count = @els;
my $i;
print $walkHandle "$name has $count entries\n";
for ($i = 0; $i < $count; $i++) {
printf $walkHandle "$i: %s\n", $els[$i]->terse;
#print $walkHandle "$i: %s\n", B::Concise::concise_sv($els[$i]);
}
}
sub showlex {
my ($objname, $namesav, $valsav) = @_;
shownamearray("Pad of lexical names for $objname", $namesav);
showvaluearray("Pad of lexical values for $objname", $valsav);
}
my ($newlex, $nosp1); # rendering state vars
sub newlex { # drop-in for showlex
my ($objname, $names, $vals) = @_;
my @names = $names->ARRAY;
my @vals = $vals->ARRAY;
my $count = @names;
print $walkHandle "$objname Pad has $count entries\n";
printf $walkHandle "0: %s\n", $names[0]->terse unless $nosp1;
for (my $i = 1; $i < $count; $i++) {
printf $walkHandle "$i: %s = %s\n", $names[$i]->terse, $vals[$i]->terse
unless $nosp1 and $names[$i]->terse =~ /SPECIAL/;
}
}
sub showlex_obj {
my ($objname, $obj) = @_;
$objname =~ s/^&main::/&/;
showlex($objname, svref_2object($obj)->PADLIST->ARRAY) if !$newlex;
newlex ($objname, svref_2object($obj)->PADLIST->ARRAY) if $newlex;
}
sub showlex_main {
showlex("comppadlist", comppadlist->ARRAY) if !$newlex;
newlex ("main", comppadlist->ARRAY) if $newlex;
}
sub compile {
my @options = grep(/^-/, @_);
my @args = grep(!/^-/, @_);
for my $o (@options) {
$newlex = 1 if $o eq "-newlex";
$nosp1 = 1 if $o eq "-nosp";
}
return \&showlex_main unless @args;
return sub {
my $objref;
foreach my $objname (@args) {
next unless $objname; # skip nulls w/o carping
if (ref $objname) {
print $walkHandle "B::Showlex::compile($objname)\n";
$objref = $objname;
} else {
$objname = "main::$objname" unless $objname =~ /::/;
print $walkHandle "$objname:\n";
no strict 'refs';
die "err: unknown function ($objname)\n"
unless *{$objname}{CODE};
$objref = \&$objname;
}
showlex_obj($objname, $objref);
}
}
}
1;
__END__
=head1 NAME
B::Showlex - Show lexical variables used in functions or files
=head1 SYNOPSIS
perl -MO=Showlex[,-OPTIONS][,SUBROUTINE] foo.pl
=head1 DESCRIPTION
When a comma-separated list of subroutine names is given as options, Showlex
prints the lexical variables used in those subroutines. Otherwise, it prints
the file-scope lexicals in the file.
=head1 EXAMPLES
Traditional form:
$ perl -MO=Showlex -e 'my ($i,$j,$k)=(1,"foo")'
Pad of lexical names for comppadlist has 4 entries
0: SPECIAL #1 &PL_sv_undef
1: PVNV (0x9db0fb0) $i
2: PVNV (0x9db0f38) $j
3: PVNV (0x9db0f50) $k
Pad of lexical values for comppadlist has 5 entries
0: SPECIAL #1 &PL_sv_undef
1: NULL (0x9da4234)
2: NULL (0x9db0f2c)
3: NULL (0x9db0f44)
4: NULL (0x9da4264)
-e syntax OK
New-style form:
$ perl -MO=Showlex,-newlex -e 'my ($i,$j,$k)=(1,"foo")'
main Pad has 4 entries
0: SPECIAL #1 &PL_sv_undef
1: PVNV (0xa0c4fb8) "$i" = NULL (0xa0b8234)
2: PVNV (0xa0c4f40) "$j" = NULL (0xa0c4f34)
3: PVNV (0xa0c4f58) "$k" = NULL (0xa0c4f4c)
-e syntax OK
New form, no specials, outside O framework:
$ perl -MB::Showlex -e \
'my ($i,$j,$k)=(1,"foo"); B::Showlex::compile(-newlex,-nosp)->()'
main Pad has 4 entries
1: PVNV (0x998ffb0) "$i" = IV (0x9983234) 1
2: PVNV (0x998ff68) "$j" = PV (0x998ff5c) "foo"
3: PVNV (0x998ff80) "$k" = NULL (0x998ff74)
Note that this example shows the values of the lexicals, whereas the other
examples did not (as they're compile-time only).
=head2 OPTIONS
The C<-newlex> option produces a more readable C<< name => value >> format,
and is shown in the second example above.
The C<-nosp> option eliminates reporting of SPECIALs, such as C<0: SPECIAL
#1 &PL_sv_undef> above. Reporting of SPECIALs can sometimes overwhelm
your declared lexicals.
=head1 SEE ALSO
C<B::Showlex> can also be used outside of the O framework, as in the third
example. See C<B::Concise> for a fuller explanation of reasons.
=head1 TODO
Some of the reported info, such as hex addresses, is not particularly
valuable. Other information would be more useful for the typical
programmer, such as line-numbers, pad-slot reuses, etc.. Given this,
-newlex isnt a particularly good flag-name.
=head1 AUTHOR
Malcolm Beattie, C<[email protected]>
=cut
| {
"pile_set_name": "Github"
} |
import URL from 'url';
import { logger } from '../../logger';
import * as packageCache from '../../util/cache/package';
import { Http } from '../../util/http';
import { GetReleasesConfig, ReleaseResult } from '../common';
import { getTerraformServiceDiscoveryResult } from '../terraform-module';
export const id = 'terraform-provider';
export const defaultRegistryUrls = [
'https://registry.terraform.io',
'https://releases.hashicorp.com',
];
export const registryStrategy = 'hunt';
const http = new Http(id);
interface TerraformProvider {
namespace: string;
name: string;
provider: string;
source?: string;
versions: string[];
}
interface TerraformProviderReleaseBackend {
[key: string]: {
name: string;
versions: VersionsReleaseBackend;
};
}
interface VersionsReleaseBackend {
[key: string]: Record<string, any>;
}
async function queryRegistry(
lookupName: string,
registryURL: string,
repository: string
): Promise<ReleaseResult> {
const serviceDiscovery = await getTerraformServiceDiscoveryResult(
registryURL
);
const backendURL = `${registryURL}${serviceDiscovery['providers.v1']}${repository}`;
const res = (await http.getJson<TerraformProvider>(backendURL)).body;
const dep: ReleaseResult = {
name: repository,
versions: {},
releases: null,
};
if (res.source) {
dep.sourceUrl = res.source;
}
dep.releases = res.versions.map((version) => ({
version,
}));
dep.homepage = `${registryURL}/providers/${repository}`;
logger.trace({ dep }, 'dep');
return dep;
}
// TODO: add long term cache
async function queryReleaseBackend(
lookupName: string,
registryURL: string,
repository: string
): Promise<ReleaseResult> {
const backendLookUpName = `terraform-provider-${lookupName}`;
const backendURL = registryURL + `/index.json`;
const res = (await http.getJson<TerraformProviderReleaseBackend>(backendURL))
.body;
const dep: ReleaseResult = {
name: repository,
versions: {},
releases: null,
sourceUrl: `https://github.com/terraform-providers/${backendLookUpName}`,
};
dep.releases = Object.keys(res[backendLookUpName].versions).map(
(version) => ({
version,
})
);
logger.trace({ dep }, 'dep');
return dep;
}
/**
* terraform-provider.getReleases
*
* This function will fetch a provider from the public Terraform registry and return all semver versions.
*/
export async function getReleases({
lookupName,
registryUrl,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
const repository = lookupName.includes('/')
? lookupName
: `hashicorp/${lookupName}`;
const cacheNamespace = 'terraform-provider';
const pkgUrl = `${registryUrl}/${repository}`;
const cachedResult = await packageCache.get<ReleaseResult>(
cacheNamespace,
pkgUrl
);
// istanbul ignore if
if (cachedResult) {
return cachedResult;
}
logger.debug({ lookupName }, 'terraform-provider.getDependencies()');
let dep: ReleaseResult = null;
const registryHost = URL.parse(registryUrl).host;
if (registryHost === 'releases.hashicorp.com') {
dep = await queryReleaseBackend(lookupName, registryUrl, repository);
} else {
dep = await queryRegistry(lookupName, registryUrl, repository);
}
const cacheMinutes = 30;
await packageCache.set(cacheNamespace, pkgUrl, dep, cacheMinutes);
return dep;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/scoped_file.h"
#include "base/logging.h"
#if defined(OS_POSIX)
#include <unistd.h>
#include "base/posix/eintr_wrapper.h"
#endif
namespace base {
namespace internal {
#if defined(OS_POSIX)
// static
void ScopedFDCloseTraits::Free(int fd) {
// It's important to crash here.
// There are security implications to not closing a file descriptor
// properly. As file descriptors are "capabilities", keeping them open
// would make the current process keep access to a resource. Much of
// Chrome relies on being able to "drop" such access.
// It's especially problematic on Linux with the setuid sandbox, where
// a single open directory would bypass the entire security model.
PCHECK(0 == IGNORE_EINTR(close(fd)));
}
#endif // OS_POSIX
} // namespace internal
} // namespace base
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.jgss.krb5;
import org.ietf.jgss.*;
import sun.security.jgss.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import sun.security.krb5.Confounder;
/**
* This class represents a token emitted by the GSSContext.wrap()
* call. It is a MessageToken except that it also contains plaintext
* or encrypted data at the end. A wrapToken has certain other rules
* that are peculiar to it and different from a MICToken, which is
* another type of MessageToken. All data in a WrapToken is prepended
* by a random counfounder of 8 bytes. All data in a WrapToken is
* also padded with one to eight bytes where all bytes are equal in
* value to the number of bytes being padded. Thus, all application
* data is replaced by (confounder || data || padding).
*
* @author Mayank Upadhyay
*/
class WrapToken extends MessageToken {
/**
* The size of the random confounder used in a WrapToken.
*/
static final int CONFOUNDER_SIZE = 8;
/*
* The padding used with a WrapToken. All data is padded to the
* next multiple of 8 bytes, even if its length is already
* multiple of 8.
* Use this table as a quick way to obtain padding bytes by
* indexing it with the number of padding bytes required.
*/
static final byte[][] pads = {
null, // No, no one escapes padding
{0x01},
{0x02, 0x02},
{0x03, 0x03, 0x03},
{0x04, 0x04, 0x04, 0x04},
{0x05, 0x05, 0x05, 0x05, 0x05},
{0x06, 0x06, 0x06, 0x06, 0x06, 0x06},
{0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07},
{0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08}
};
/*
* A token may come in either in an InputStream or as a
* byte[]. Store a reference to it in either case and process
* it's data only later when getData() is called and
* decryption/copying is needed to be done. Note that JCE can
* decrypt both from a byte[] and from an InputStream.
*/
private boolean readTokenFromInputStream = true;
private InputStream is = null;
private byte[] tokenBytes = null;
private int tokenOffset = 0;
private int tokenLen = 0;
/*
* Application data may come from an InputStream or from a
* byte[]. However, it will always be stored and processed as a
* byte[] since
* (a) the MessageDigest class only accepts a byte[] as input and
* (b) It allows writing to an OuputStream via a CipherOutputStream.
*/
private byte[] dataBytes = null;
private int dataOffset = 0;
private int dataLen = 0;
// the len of the token data: (confounder || data || padding)
private int dataSize = 0;
// Accessed by CipherHelper
byte[] confounder = null;
byte[] padding = null;
private boolean privacy = false;
/**
* Constructs a WrapToken from token bytes obtained from the
* peer.
* @param context the mechanism context associated with this
* token
* @param tokenBytes the bytes of the token
* @param tokenOffset the offset of the token
* @param tokenLen the length of the token
* @param prop the MessageProp into which characteristics of the
* parsed token will be stored.
* @throws GSSException if the token is defective
*/
public WrapToken(Krb5Context context,
byte[] tokenBytes, int tokenOffset, int tokenLen,
MessageProp prop) throws GSSException {
// Just parse the MessageToken part first
super(Krb5Token.WRAP_ID, context,
tokenBytes, tokenOffset, tokenLen, prop);
this.readTokenFromInputStream = false;
// Will need the token bytes again when extracting data
this.tokenBytes = tokenBytes;
this.tokenOffset = tokenOffset;
this.tokenLen = tokenLen;
this.privacy = prop.getPrivacy();
dataSize =
getGSSHeader().getMechTokenLength() - getKrb5TokenSize();
}
/**
* Constructs a WrapToken from token bytes read on the fly from
* an InputStream.
* @param context the mechanism context associated with this
* token
* @param is the InputStream containing the token bytes
* @param prop the MessageProp into which characteristics of the
* parsed token will be stored.
* @throws GSSException if the token is defective or if there is
* a problem reading from the InputStream
*/
public WrapToken(Krb5Context context,
InputStream is, MessageProp prop)
throws GSSException {
// Just parse the MessageToken part first
super(Krb5Token.WRAP_ID, context, is, prop);
// Will need the token bytes again when extracting data
this.is = is;
this.privacy = prop.getPrivacy();
/*
debug("WrapToken Cons: gssHeader.getMechTokenLength=" +
getGSSHeader().getMechTokenLength());
debug("\n token size="
+ getTokenSize());
*/
dataSize =
getGSSHeader().getMechTokenLength() - getTokenSize();
// debug("\n dataSize=" + dataSize);
// debug("\n");
}
/**
* Obtains the application data that was transmitted in this
* WrapToken.
* @return a byte array containing the application data
* @throws GSSException if an error occurs while decrypting any
* cipher text and checking for validity
*/
public byte[] getData() throws GSSException {
byte[] temp = new byte[dataSize];
getData(temp, 0);
// Remove the confounder and the padding
byte[] retVal = new byte[dataSize - confounder.length -
padding.length];
System.arraycopy(temp, 0, retVal, 0, retVal.length);
return retVal;
}
/**
* Obtains the application data that was transmitted in this
* WrapToken, writing it into an application provided output
* array.
* @param dataBuf the output buffer into which the data must be
* written
* @param dataBufOffset the offset at which to write the data
* @return the size of the data written
* @throws GSSException if an error occurs while decrypting any
* cipher text and checking for validity
*/
public int getData(byte[] dataBuf, int dataBufOffset)
throws GSSException {
if (readTokenFromInputStream)
getDataFromStream(dataBuf, dataBufOffset);
else
getDataFromBuffer(dataBuf, dataBufOffset);
return (dataSize - confounder.length - padding.length);
}
/**
* Helper routine to obtain the application data transmitted in
* this WrapToken. It is called if the WrapToken was constructed
* with a byte array as input.
* @param dataBuf the output buffer into which the data must be
* written
* @param dataBufOffset the offset at which to write the data
* @throws GSSException if an error occurs while decrypting any
* cipher text and checking for validity
*/
private void getDataFromBuffer(byte[] dataBuf, int dataBufOffset)
throws GSSException {
GSSHeader gssHeader = getGSSHeader();
int dataPos = tokenOffset +
gssHeader.getLength() + getTokenSize();
if (dataPos + dataSize > tokenOffset + tokenLen)
throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
"Insufficient data in "
+ getTokenName(getTokenId()));
// debug("WrapToken cons: data is token is [" +
// getHexBytes(tokenBytes, tokenOffset, tokenLen) + "]\n");
confounder = new byte[CONFOUNDER_SIZE];
// Do decryption if this token was privacy protected.
if (privacy) {
cipherHelper.decryptData(this,
tokenBytes, dataPos, dataSize, dataBuf, dataBufOffset);
/*
debug("\t\tDecrypted data is [" +
getHexBytes(confounder) + " " +
getHexBytes(dataBuf, dataBufOffset,
dataSize - CONFOUNDER_SIZE - padding.length) +
getHexBytes(padding) +
"]\n");
*/
} else {
// Token data is in cleartext
// debug("\t\tNo encryption was performed by peer.\n");
System.arraycopy(tokenBytes, dataPos,
confounder, 0, CONFOUNDER_SIZE);
int padSize = tokenBytes[dataPos + dataSize - 1];
if (padSize < 0)
padSize = 0;
if (padSize > 8)
padSize %= 8;
padding = pads[padSize];
// debug("\t\tPadding applied was: " + padSize + "\n");
System.arraycopy(tokenBytes, dataPos + CONFOUNDER_SIZE,
dataBuf, dataBufOffset, dataSize -
CONFOUNDER_SIZE - padSize);
// byte[] debugbuf = new byte[dataSize - CONFOUNDER_SIZE - padSize];
// System.arraycopy(tokenBytes, dataPos + CONFOUNDER_SIZE,
// debugbuf, 0, debugbuf.length);
// debug("\t\tData is: " + getHexBytes(debugbuf, debugbuf.length));
}
/*
* Make sure sign and sequence number are not corrupt
*/
if (!verifySignAndSeqNumber(confounder,
dataBuf, dataBufOffset,
dataSize - CONFOUNDER_SIZE
- padding.length,
padding))
throw new GSSException(GSSException.BAD_MIC, -1,
"Corrupt checksum or sequence number in Wrap token");
}
/**
* Helper routine to obtain the application data transmitted in
* this WrapToken. It is called if the WrapToken was constructed
* with an Inputstream.
* @param dataBuf the output buffer into which the data must be
* written
* @param dataBufOffset the offset at which to write the data
* @throws GSSException if an error occurs while decrypting any
* cipher text and checking for validity
*/
private void getDataFromStream(byte[] dataBuf, int dataBufOffset)
throws GSSException {
GSSHeader gssHeader = getGSSHeader();
// Don't check the token length. Data will be read on demand from
// the InputStream.
// debug("WrapToken cons: data will be read from InputStream.\n");
confounder = new byte[CONFOUNDER_SIZE];
try {
// Do decryption if this token was privacy protected.
if (privacy) {
cipherHelper.decryptData(this, is, dataSize,
dataBuf, dataBufOffset);
// debug("\t\tDecrypted data is [" +
// getHexBytes(confounder) + " " +
// getHexBytes(dataBuf, dataBufOffset,
// dataSize - CONFOUNDER_SIZE - padding.length) +
// getHexBytes(padding) +
// "]\n");
} else {
// Token data is in cleartext
// debug("\t\tNo encryption was performed by peer.\n");
readFully(is, confounder);
if (cipherHelper.isArcFour()) {
padding = pads[1];
readFully(is, dataBuf, dataBufOffset, dataSize-CONFOUNDER_SIZE-1);
} else {
// Data is always a multiple of 8 with this GSS Mech
// Copy all but last block as they are
int numBlocks = (dataSize - CONFOUNDER_SIZE)/8 - 1;
int offset = dataBufOffset;
for (int i = 0; i < numBlocks; i++) {
readFully(is, dataBuf, offset, 8);
offset += 8;
}
byte[] finalBlock = new byte[8];
readFully(is, finalBlock);
int padSize = finalBlock[7];
padding = pads[padSize];
// debug("\t\tPadding applied was: " + padSize + "\n");
System.arraycopy(finalBlock, 0, dataBuf, offset,
finalBlock.length - padSize);
}
}
} catch (IOException e) {
throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
getTokenName(getTokenId())
+ ": " + e.getMessage());
}
/*
* Make sure sign and sequence number are not corrupt
*/
if (!verifySignAndSeqNumber(confounder,
dataBuf, dataBufOffset,
dataSize - CONFOUNDER_SIZE
- padding.length,
padding))
throw new GSSException(GSSException.BAD_MIC, -1,
"Corrupt checksum or sequence number in Wrap token");
}
/**
* Helper routine to pick the right padding for a certain length
* of application data. Every application message has some
* padding between 1 and 8 bytes.
* @param len the length of the application data
* @return the padding to be applied
*/
private byte[] getPadding(int len) {
int padSize = 0;
// For RC4-HMAC, all padding is rounded up to 1 byte.
// One byte is needed to say that there is 1 byte of padding.
if (cipherHelper.isArcFour()) {
padSize = 1;
} else {
padSize = len % 8;
padSize = 8 - padSize;
}
return pads[padSize];
}
public WrapToken(Krb5Context context, MessageProp prop,
byte[] dataBytes, int dataOffset, int dataLen)
throws GSSException {
super(Krb5Token.WRAP_ID, context);
confounder = Confounder.bytes(CONFOUNDER_SIZE);
padding = getPadding(dataLen);
dataSize = confounder.length + dataLen + padding.length;
this.dataBytes = dataBytes;
this.dataOffset = dataOffset;
this.dataLen = dataLen;
/*
debug("\nWrapToken cons: data to wrap is [" +
getHexBytes(confounder) + " " +
getHexBytes(dataBytes, dataOffset, dataLen) + " " +
// padding is never null for Wrap
getHexBytes(padding) + "]\n");
*/
genSignAndSeqNumber(prop,
confounder,
dataBytes, dataOffset, dataLen,
padding);
/*
* If the application decides to ask for privacy when the context
* did not negotiate for it, do not provide it. The peer might not
* have support for it. The app will realize this with a call to
* pop.getPrivacy() after wrap().
*/
if (!context.getConfState())
prop.setPrivacy(false);
privacy = prop.getPrivacy();
}
public void encode(OutputStream os) throws IOException, GSSException {
super.encode(os);
// debug("Writing data: [");
if (!privacy) {
// debug(getHexBytes(confounder, confounder.length));
os.write(confounder);
// debug(" " + getHexBytes(dataBytes, dataOffset, dataLen));
os.write(dataBytes, dataOffset, dataLen);
// debug(" " + getHexBytes(padding, padding.length));
os.write(padding);
} else {
cipherHelper.encryptData(this, confounder,
dataBytes, dataOffset, dataLen, padding, os);
}
// debug("]\n");
}
public byte[] encode() throws IOException, GSSException {
// XXX Fine tune this initial size
ByteArrayOutputStream bos = new ByteArrayOutputStream(dataSize + 50);
encode(bos);
return bos.toByteArray();
}
public int encode(byte[] outToken, int offset)
throws IOException, GSSException {
// Token header is small
ByteArrayOutputStream bos = new ByteArrayOutputStream();
super.encode(bos);
byte[] header = bos.toByteArray();
System.arraycopy(header, 0, outToken, offset, header.length);
offset += header.length;
// debug("WrapToken.encode: Writing data: [");
if (!privacy) {
// debug(getHexBytes(confounder, confounder.length));
System.arraycopy(confounder, 0, outToken, offset,
confounder.length);
offset += confounder.length;
// debug(" " + getHexBytes(dataBytes, dataOffset, dataLen));
System.arraycopy(dataBytes, dataOffset, outToken, offset,
dataLen);
offset += dataLen;
// debug(" " + getHexBytes(padding, padding.length));
System.arraycopy(padding, 0, outToken, offset, padding.length);
} else {
cipherHelper.encryptData(this, confounder, dataBytes,
dataOffset, dataLen, padding, outToken, offset);
// debug(getHexBytes(outToken, offset, dataSize));
}
// debug("]\n");
// %%% assume that plaintext length == ciphertext len
return (header.length + confounder.length + dataLen + padding.length);
}
protected int getKrb5TokenSize() throws GSSException {
return (getTokenSize() + dataSize);
}
protected int getSealAlg(boolean conf, int qop) throws GSSException {
if (!conf) {
return SEAL_ALG_NONE;
}
// ignore QOP
return cipherHelper.getSealAlg();
}
// This implementation is way too conservative. And it certainly
// doesn't return the maximum limit.
static int getSizeLimit(int qop, boolean confReq, int maxTokenSize,
CipherHelper ch) throws GSSException {
return (GSSHeader.getMaxMechTokenSize(OID, maxTokenSize) -
(getTokenSize(ch) + CONFOUNDER_SIZE) - 8); /* safety */
}
}
| {
"pile_set_name": "Github"
} |
import styled from 'styled-components';
import styledTS from 'styled-components-ts';
import { colors, dimensions, typography } from '../../styles';
const TabContainer = styledTS<{ grayBorder?: boolean; full?: boolean }>(
styled.div
)`
border-bottom: 1px solid
${props => (props.grayBorder ? colors.borderDarker : colors.borderPrimary)};
margin-bottom: -1px;
position: relative;
z-index: 2;
display: flex;
justify-content: ${props => props.full && 'space-evenly'};
flex-shrink: 0;
height: ${dimensions.headerSpacing}px;
`;
const TabCaption = styled.span`
cursor: pointer;
display: inline-block;
color: ${colors.textSecondary};
font-weight: ${typography.fontWeightRegular};
padding: 15px ${dimensions.coreSpacing}px;
position: relative;
transition: all ease 0.3s;
&:hover {
color: ${colors.textPrimary};
}
i {
margin-right: 3px;
}
&.active {
color: ${colors.textPrimary};
font-weight: 500;
&:before {
border-bottom: 3px solid ${colors.colorSecondary};
content: '';
width: 100%;
position: absolute;
z-index: 1;
left: 0;
bottom: -1px;
}
}
`;
export { TabContainer, TabCaption };
| {
"pile_set_name": "Github"
} |
DO_API(void, il2cpp_init, (const char* domain_name));
DO_API(void, il2cpp_init_utf16, (const Il2CppChar * domain_name));
DO_API(void, il2cpp_shutdown, ());
DO_API(void, il2cpp_set_config_dir, (const char *config_path));
DO_API(void, il2cpp_set_data_dir, (const char *data_path));
DO_API(void, il2cpp_set_commandline_arguments, (int argc, const char* const argv[], const char* basedir));
DO_API(void, il2cpp_set_commandline_arguments_utf16, (int argc, const Il2CppChar * const argv[], const char* basedir));
DO_API(void, il2cpp_set_config_utf16, (const Il2CppChar * executablePath));
DO_API(void, il2cpp_set_config, (const char* executablePath));
DO_API(void, il2cpp_set_memory_callbacks, (Il2CppMemoryCallbacks * callbacks));
DO_API(const Il2CppImage*, il2cpp_get_corlib, ());
DO_API(void, il2cpp_add_internal_call, (const char* name, Il2CppMethodPointer method));
DO_API(Il2CppMethodPointer, il2cpp_resolve_icall, (const char* name));
DO_API(void*, il2cpp_alloc, (size_t size));
DO_API(void, il2cpp_free, (void* ptr));
// array
DO_API(Il2CppClass*, il2cpp_array_class_get, (Il2CppClass * element_class, uint32_t rank));
DO_API(uint32_t, il2cpp_array_length, (Il2CppArray * array));
DO_API(uint32_t, il2cpp_array_get_byte_length, (Il2CppArray * array));
DO_API(Il2CppArray*, il2cpp_array_new, (Il2CppClass * elementTypeInfo, il2cpp_array_size_t length));
DO_API(Il2CppArray*, il2cpp_array_new_specific, (Il2CppClass * arrayTypeInfo, il2cpp_array_size_t length));
DO_API(Il2CppArray*, il2cpp_array_new_full, (Il2CppClass * array_class, il2cpp_array_size_t * lengths, il2cpp_array_size_t * lower_bounds));
DO_API(Il2CppClass*, il2cpp_bounded_array_class_get, (Il2CppClass * element_class, uint32_t rank, bool bounded));
DO_API(int, il2cpp_array_element_size, (const Il2CppClass * array_class));
// assembly
DO_API(const Il2CppImage*, il2cpp_assembly_get_image, (const Il2CppAssembly * assembly));
// class
DO_API(const Il2CppType*, il2cpp_class_enum_basetype, (Il2CppClass * klass));
DO_API(bool, il2cpp_class_is_generic, (const Il2CppClass * klass));
DO_API(bool, il2cpp_class_is_inflated, (const Il2CppClass * klass));
DO_API(bool, il2cpp_class_is_assignable_from, (Il2CppClass * klass, Il2CppClass * oklass));
DO_API(bool, il2cpp_class_is_subclass_of, (Il2CppClass * klass, Il2CppClass * klassc, bool check_interfaces));
DO_API(bool, il2cpp_class_has_parent, (Il2CppClass * klass, Il2CppClass * klassc));
DO_API(Il2CppClass*, il2cpp_class_from_il2cpp_type, (const Il2CppType * type));
DO_API(Il2CppClass*, il2cpp_class_from_name, (const Il2CppImage * image, const char* namespaze, const char *name));
DO_API(Il2CppClass*, il2cpp_class_from_system_type, (Il2CppReflectionType * type));
DO_API(Il2CppClass*, il2cpp_class_get_element_class, (Il2CppClass * klass));
DO_API(const EventInfo*, il2cpp_class_get_events, (Il2CppClass * klass, void* *iter));
DO_API(FieldInfo*, il2cpp_class_get_fields, (Il2CppClass * klass, void* *iter));
DO_API(Il2CppClass*, il2cpp_class_get_nested_types, (Il2CppClass * klass, void* *iter));
DO_API(Il2CppClass*, il2cpp_class_get_interfaces, (Il2CppClass * klass, void* *iter));
DO_API(const PropertyInfo*, il2cpp_class_get_properties, (Il2CppClass * klass, void* *iter));
DO_API(const PropertyInfo*, il2cpp_class_get_property_from_name, (Il2CppClass * klass, const char *name));
DO_API(FieldInfo*, il2cpp_class_get_field_from_name, (Il2CppClass * klass, const char *name));
DO_API(const MethodInfo*, il2cpp_class_get_methods, (Il2CppClass * klass, void* *iter));
DO_API(const MethodInfo*, il2cpp_class_get_method_from_name, (Il2CppClass * klass, const char* name, int argsCount));
DO_API(const char*, il2cpp_class_get_name, (Il2CppClass * klass));
DO_API(const char*, il2cpp_class_get_namespace, (Il2CppClass * klass));
DO_API(Il2CppClass*, il2cpp_class_get_parent, (Il2CppClass * klass));
DO_API(Il2CppClass*, il2cpp_class_get_declaring_type, (Il2CppClass * klass));
DO_API(int32_t, il2cpp_class_instance_size, (Il2CppClass * klass));
DO_API(size_t, il2cpp_class_num_fields, (const Il2CppClass * enumKlass));
DO_API(bool, il2cpp_class_is_valuetype, (const Il2CppClass * klass));
DO_API(int32_t, il2cpp_class_value_size, (Il2CppClass * klass, uint32_t * align));
DO_API(int, il2cpp_class_get_flags, (const Il2CppClass * klass));
DO_API(bool, il2cpp_class_is_abstract, (const Il2CppClass * klass));
DO_API(bool, il2cpp_class_is_interface, (const Il2CppClass * klass));
DO_API(int, il2cpp_class_array_element_size, (const Il2CppClass * klass));
DO_API(Il2CppClass*, il2cpp_class_from_type, (const Il2CppType * type));
DO_API(const Il2CppType*, il2cpp_class_get_type, (Il2CppClass * klass));
DO_API(bool, il2cpp_class_has_attribute, (Il2CppClass * klass, Il2CppClass * attr_class));
DO_API(bool, il2cpp_class_has_references, (Il2CppClass * klass));
DO_API(bool, il2cpp_class_is_enum, (const Il2CppClass * klass));
DO_API(const Il2CppImage*, il2cpp_class_get_image, (Il2CppClass * klass));
DO_API(const char*, il2cpp_class_get_assemblyname, (const Il2CppClass * klass));
// testing only
DO_API(size_t, il2cpp_class_get_bitmap_size, (const Il2CppClass * klass));
DO_API(void, il2cpp_class_get_bitmap, (Il2CppClass * klass, size_t * bitmap));
// stats
DO_API(bool, il2cpp_stats_dump_to_file, (const char *path));
DO_API(uint64_t, il2cpp_stats_get_value, (Il2CppStat stat));
// domain
DO_API(Il2CppDomain*, il2cpp_domain_get, ());
DO_API(const Il2CppAssembly*, il2cpp_domain_assembly_open, (Il2CppDomain * domain, const char* name));
DO_API(const Il2CppAssembly**, il2cpp_domain_get_assemblies, (const Il2CppDomain * domain, size_t * size));
// exception
DO_API(void, il2cpp_raise_exception, (Il2CppException*));
DO_API(Il2CppException*, il2cpp_exception_from_name_msg, (const Il2CppImage * image, const char *name_space, const char *name, const char *msg));
DO_API(Il2CppException*, il2cpp_get_exception_argument_null, (const char *arg));
DO_API(void, il2cpp_format_exception, (const Il2CppException * ex, char* message, int message_size));
DO_API(void, il2cpp_format_stack_trace, (const Il2CppException * ex, char* output, int output_size));
DO_API(void, il2cpp_unhandled_exception, (Il2CppException*));
// field
DO_API(int, il2cpp_field_get_flags, (FieldInfo * field));
DO_API(const char*, il2cpp_field_get_name, (FieldInfo * field));
DO_API(Il2CppClass*, il2cpp_field_get_parent, (FieldInfo * field));
DO_API(size_t, il2cpp_field_get_offset, (FieldInfo * field));
DO_API(const Il2CppType*, il2cpp_field_get_type, (FieldInfo * field));
DO_API(void, il2cpp_field_get_value, (Il2CppObject * obj, FieldInfo * field, void *value));
DO_API(Il2CppObject*, il2cpp_field_get_value_object, (FieldInfo * field, Il2CppObject * obj));
DO_API(bool, il2cpp_field_has_attribute, (FieldInfo * field, Il2CppClass * attr_class));
DO_API(void, il2cpp_field_set_value, (Il2CppObject * obj, FieldInfo * field, void *value));
DO_API(void, il2cpp_field_static_get_value, (FieldInfo * field, void *value));
DO_API(void, il2cpp_field_static_set_value, (FieldInfo * field, void *value));
DO_API(void, il2cpp_field_set_value_object, (Il2CppObject * instance, FieldInfo * field, Il2CppObject * value));
// gc
DO_API(void, il2cpp_gc_collect, (int maxGenerations));
DO_API(int32_t, il2cpp_gc_collect_a_little, ());
DO_API(void, il2cpp_gc_disable, ());
DO_API(void, il2cpp_gc_enable, ());
DO_API(int64_t, il2cpp_gc_get_used_size, ());
DO_API(int64_t, il2cpp_gc_get_heap_size, ());
// gchandle
DO_API(uint32_t, il2cpp_gchandle_new, (Il2CppObject * obj, bool pinned));
DO_API(uint32_t, il2cpp_gchandle_new_weakref, (Il2CppObject * obj, bool track_resurrection));
DO_API(Il2CppObject*, il2cpp_gchandle_get_target , (uint32_t gchandle));
DO_API(void, il2cpp_gchandle_free, (uint32_t gchandle));
// liveness
DO_API(void*, il2cpp_unity_liveness_calculation_begin, (Il2CppClass * filter, int max_object_count, il2cpp_register_object_callback callback, void* userdata, il2cpp_WorldChangedCallback onWorldStarted, il2cpp_WorldChangedCallback onWorldStopped));
DO_API(void, il2cpp_unity_liveness_calculation_end, (void* state));
DO_API(void, il2cpp_unity_liveness_calculation_from_root, (Il2CppObject * root, void* state));
DO_API(void, il2cpp_unity_liveness_calculation_from_statics, (void* state));
// method
DO_API(const Il2CppType*, il2cpp_method_get_return_type, (const MethodInfo * method));
DO_API(Il2CppClass*, il2cpp_method_get_declaring_type, (const MethodInfo * method));
DO_API(const char*, il2cpp_method_get_name, (const MethodInfo * method));
DO_API(Il2CppReflectionMethod*, il2cpp_method_get_object, (const MethodInfo * method, Il2CppClass * refclass));
DO_API(bool, il2cpp_method_is_generic, (const MethodInfo * method));
DO_API(bool, il2cpp_method_is_inflated, (const MethodInfo * method));
DO_API(bool, il2cpp_method_is_instance, (const MethodInfo * method));
DO_API(uint32_t, il2cpp_method_get_param_count, (const MethodInfo * method));
DO_API(const Il2CppType*, il2cpp_method_get_param, (const MethodInfo * method, uint32_t index));
DO_API(Il2CppClass*, il2cpp_method_get_class, (const MethodInfo * method));
DO_API(bool, il2cpp_method_has_attribute, (const MethodInfo * method, Il2CppClass * attr_class));
DO_API(uint32_t, il2cpp_method_get_flags, (const MethodInfo * method, uint32_t * iflags));
DO_API(uint32_t, il2cpp_method_get_token, (const MethodInfo * method));
DO_API(const char*, il2cpp_method_get_param_name, (const MethodInfo * method, uint32_t index));
// profiler
#if IL2CPP_ENABLE_PROFILER
DO_API(void, il2cpp_profiler_install, (Il2CppProfiler * prof, Il2CppProfileFunc shutdown_callback));
DO_API(void, il2cpp_profiler_set_events, (Il2CppProfileFlags events));
DO_API(void, il2cpp_profiler_install_enter_leave, (Il2CppProfileMethodFunc enter, Il2CppProfileMethodFunc fleave));
DO_API(void, il2cpp_profiler_install_allocation, (Il2CppProfileAllocFunc callback));
DO_API(void, il2cpp_profiler_install_gc, (Il2CppProfileGCFunc callback, Il2CppProfileGCResizeFunc heap_resize_callback));
#endif
// property
DO_API(uint32_t, il2cpp_property_get_flags, (PropertyInfo * prop));
DO_API(const MethodInfo*, il2cpp_property_get_get_method, (PropertyInfo * prop));
DO_API(const MethodInfo*, il2cpp_property_get_set_method, (PropertyInfo * prop));
DO_API(const char*, il2cpp_property_get_name, (PropertyInfo * prop));
DO_API(Il2CppClass*, il2cpp_property_get_parent, (PropertyInfo * prop));
// object
DO_API(Il2CppClass*, il2cpp_object_get_class, (Il2CppObject * obj));
DO_API(uint32_t, il2cpp_object_get_size, (Il2CppObject * obj));
DO_API(const MethodInfo*, il2cpp_object_get_virtual_method, (Il2CppObject * obj, const MethodInfo * method));
DO_API(Il2CppObject*, il2cpp_object_new, (const Il2CppClass * klass));
DO_API(void*, il2cpp_object_unbox, (Il2CppObject * obj));
DO_API(Il2CppObject*, il2cpp_value_box, (Il2CppClass * klass, void* data));
// monitor
DO_API(void, il2cpp_monitor_enter, (Il2CppObject * obj));
DO_API(bool, il2cpp_monitor_try_enter, (Il2CppObject * obj, uint32_t timeout));
DO_API(void, il2cpp_monitor_exit, (Il2CppObject * obj));
DO_API(void, il2cpp_monitor_pulse, (Il2CppObject * obj));
DO_API(void, il2cpp_monitor_pulse_all, (Il2CppObject * obj));
DO_API(void, il2cpp_monitor_wait, (Il2CppObject * obj));
DO_API(bool, il2cpp_monitor_try_wait, (Il2CppObject * obj, uint32_t timeout));
// runtime
DO_API(Il2CppObject*, il2cpp_runtime_invoke, (const MethodInfo * method, void *obj, void **params, Il2CppException **exc));
DO_API(Il2CppObject*, il2cpp_runtime_invoke_convert_args, (const MethodInfo * method, void *obj, Il2CppObject **params, int paramCount, Il2CppException **exc));
DO_API(void, il2cpp_runtime_class_init, (Il2CppClass * klass));
DO_API(void, il2cpp_runtime_object_init, (Il2CppObject * obj));
DO_API(void, il2cpp_runtime_object_init_exception, (Il2CppObject * obj, Il2CppException** exc));
DO_API(void, il2cpp_runtime_unhandled_exception_policy_set, (Il2CppRuntimeUnhandledExceptionPolicy value));
// string
DO_API(int32_t, il2cpp_string_length, (Il2CppString * str));
DO_API(Il2CppChar*, il2cpp_string_chars, (Il2CppString * str));
DO_API(Il2CppString*, il2cpp_string_new, (const char* str));
DO_API(Il2CppString*, il2cpp_string_new_len, (const char* str, uint32_t length));
DO_API(Il2CppString*, il2cpp_string_new_utf16, (const Il2CppChar * text, int32_t len));
DO_API(Il2CppString*, il2cpp_string_new_wrapper, (const char* str));
DO_API(Il2CppString*, il2cpp_string_intern, (Il2CppString * str));
DO_API(Il2CppString*, il2cpp_string_is_interned, (Il2CppString * str));
// thread
DO_API(char*, il2cpp_thread_get_name, (Il2CppThread * thread, uint32_t * len));
DO_API(Il2CppThread*, il2cpp_thread_current, ());
DO_API(Il2CppThread*, il2cpp_thread_attach, (Il2CppDomain * domain));
DO_API(void, il2cpp_thread_detach, (Il2CppThread * thread));
DO_API(Il2CppThread**, il2cpp_thread_get_all_attached_threads, (size_t * size));
DO_API(bool, il2cpp_is_vm_thread, (Il2CppThread * thread));
// stacktrace
DO_API(void, il2cpp_current_thread_walk_frame_stack, (Il2CppFrameWalkFunc func, void* user_data));
DO_API(void, il2cpp_thread_walk_frame_stack, (Il2CppThread * thread, Il2CppFrameWalkFunc func, void* user_data));
DO_API(bool, il2cpp_current_thread_get_top_frame, (Il2CppStackFrameInfo & frame));
DO_API(bool, il2cpp_thread_get_top_frame, (Il2CppThread * thread, Il2CppStackFrameInfo & frame));
DO_API(bool, il2cpp_current_thread_get_frame_at, (int32_t offset, Il2CppStackFrameInfo & frame));
DO_API(bool, il2cpp_thread_get_frame_at, (Il2CppThread * thread, int32_t offset, Il2CppStackFrameInfo & frame));
DO_API(int32_t, il2cpp_current_thread_get_stack_depth, ());
DO_API(int32_t, il2cpp_thread_get_stack_depth, (Il2CppThread * thread));
// type
DO_API(Il2CppObject*, il2cpp_type_get_object, (const Il2CppType * type));
DO_API(int, il2cpp_type_get_type, (const Il2CppType * type));
DO_API(Il2CppClass*, il2cpp_type_get_class_or_element_class, (const Il2CppType * type));
DO_API(char*, il2cpp_type_get_name, (const Il2CppType * type));
// image
DO_API(const Il2CppAssembly*, il2cpp_image_get_assembly, (const Il2CppImage * image));
DO_API(const char*, il2cpp_image_get_name, (const Il2CppImage * image));
DO_API(const char*, il2cpp_image_get_filename, (const Il2CppImage * image));
DO_API(const MethodInfo*, il2cpp_image_get_entry_point, (const Il2CppImage * image));
// Memory information
DO_API(Il2CppManagedMemorySnapshot*, il2cpp_capture_memory_snapshot, ());
DO_API(void, il2cpp_free_captured_memory_snapshot, (Il2CppManagedMemorySnapshot * snapshot));
DO_API(void, il2cpp_set_find_plugin_callback, (Il2CppSetFindPlugInCallback method));
// Logging
DO_API(void, il2cpp_register_log_callback, (Il2CppLogCallback method));
#if IL2CPP_DEBUGGER_ENABLED
// debug
DO_API(const Il2CppDebugTypeInfo*, il2cpp_debug_get_class_info, (const Il2CppClass * klass));
DO_API(const Il2CppDebugDocument*, il2cpp_debug_class_get_document, (const Il2CppDebugTypeInfo * info));
DO_API(const char*, il2cpp_debug_document_get_filename, (const Il2CppDebugDocument * document));
DO_API(const char*, il2cpp_debug_document_get_directory, (const Il2CppDebugDocument * document));
DO_API(const Il2CppDebugMethodInfo*, il2cpp_debug_get_method_info, (const MethodInfo * method));
DO_API(const Il2CppDebugDocument*, il2cpp_debug_method_get_document, (const Il2CppDebugMethodInfo * info));
DO_API(const int32_t*, il2cpp_debug_method_get_offset_table, (const Il2CppDebugMethodInfo * info));
DO_API(size_t, il2cpp_debug_method_get_code_size, (const Il2CppDebugMethodInfo * info));
DO_API(void, il2cpp_debug_update_frame_il_offset, (int32_t il_offset));
DO_API(const Il2CppDebugLocalsInfo**, il2cpp_debug_method_get_locals_info, (const Il2CppDebugMethodInfo * info));
DO_API(const Il2CppClass*, il2cpp_debug_local_get_type, (const Il2CppDebugLocalsInfo * info));
DO_API(const char*, il2cpp_debug_local_get_name, (const Il2CppDebugLocalsInfo * info));
DO_API(uint32_t, il2cpp_debug_local_get_start_offset, (const Il2CppDebugLocalsInfo * info));
DO_API(uint32_t, il2cpp_debug_local_get_end_offset, (const Il2CppDebugLocalsInfo * info));
DO_API(Il2CppObject*, il2cpp_debug_method_get_param_value, (const Il2CppStackFrameInfo * info, uint32_t position));
DO_API(Il2CppObject*, il2cpp_debug_frame_get_local_value, (const Il2CppStackFrameInfo * info, uint32_t position));
DO_API(void*, il2cpp_debug_method_get_breakpoint_data_at, (const Il2CppDebugMethodInfo * info, int64_t uid, int32_t offset));
DO_API(void, il2cpp_debug_method_set_breakpoint_data_at, (const Il2CppDebugMethodInfo * info, uint64_t location, void *data));
DO_API(void, il2cpp_debug_method_clear_breakpoint_data, (const Il2CppDebugMethodInfo * info));
DO_API(void, il2cpp_debug_method_clear_breakpoint_data_at, (const Il2CppDebugMethodInfo * info, uint64_t location));
#endif
| {
"pile_set_name": "Github"
} |
/*!
* Bootstrap v3.1.1 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
.btn-default,
.btn-primary,
.btn-success,
.btn-info,
.btn-warning,
.btn-danger {
text-shadow: 0 -1px 0 rgba(0, 0, 0, .2);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075);
}
.btn-default:active,
.btn-primary:active,
.btn-success:active,
.btn-info:active,
.btn-warning:active,
.btn-danger:active,
.btn-default.active,
.btn-primary.active,
.btn-success.active,
.btn-info.active,
.btn-warning.active,
.btn-danger.active {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn:active,
.btn.active {
background-image: none;
}
.btn-default {
text-shadow: 0 1px 0 #fff;
background-image: -webkit-linear-gradient(top, #fff 0%, #e0e0e0 100%);
background-image: linear-gradient(to bottom, #fff 0%, #e0e0e0 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #dbdbdb;
border-color: #ccc;
}
.btn-default:hover,
.btn-default:focus {
background-color: #e0e0e0;
background-position: 0 -15px;
}
.btn-default:active,
.btn-default.active {
background-color: #e0e0e0;
border-color: #dbdbdb;
}
.btn-primary {
background-image: -webkit-linear-gradient(top, #428bca 0%, #2d6ca2 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #2d6ca2 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff2d6ca2', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #2b669a;
}
.btn-primary:hover,
.btn-primary:focus {
background-color: #2d6ca2;
background-position: 0 -15px;
}
.btn-primary:active,
.btn-primary.active {
background-color: #2d6ca2;
border-color: #2b669a;
}
.btn-success {
background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%);
background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #3e8f3e;
}
.btn-success:hover,
.btn-success:focus {
background-color: #419641;
background-position: 0 -15px;
}
.btn-success:active,
.btn-success.active {
background-color: #419641;
border-color: #3e8f3e;
}
.btn-info {
background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);
background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #28a4c9;
}
.btn-info:hover,
.btn-info:focus {
background-color: #2aabd2;
background-position: 0 -15px;
}
.btn-info:active,
.btn-info.active {
background-color: #2aabd2;
border-color: #28a4c9;
}
.btn-warning {
background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);
background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #e38d13;
}
.btn-warning:hover,
.btn-warning:focus {
background-color: #eb9316;
background-position: 0 -15px;
}
.btn-warning:active,
.btn-warning.active {
background-color: #eb9316;
border-color: #e38d13;
}
.btn-danger {
background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%);
background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-color: #b92c28;
}
.btn-danger:hover,
.btn-danger:focus {
background-color: #c12e2a;
background-position: 0 -15px;
}
.btn-danger:active,
.btn-danger.active {
background-color: #c12e2a;
border-color: #b92c28;
}
.thumbnail,
.img-thumbnail {
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
background-color: #e8e8e8;
background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
background-repeat: repeat-x;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
background-color: #357ebd;
background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0);
background-repeat: repeat-x;
}
.navbar-default {
background-image: -webkit-linear-gradient(top, #fff 0%, #f8f8f8 100%);
background-image: linear-gradient(to bottom, #fff 0%, #f8f8f8 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075);
}
.navbar-default .navbar-nav > .active > a {
background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f3f3f3 100%);
background-image: linear-gradient(to bottom, #ebebeb 0%, #f3f3f3 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff3f3f3', GradientType=0);
background-repeat: repeat-x;
-webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075);
box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075);
}
.navbar-brand,
.navbar-nav > li > a {
text-shadow: 0 1px 0 rgba(255, 255, 255, .25);
}
.navbar-inverse {
background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222 100%);
background-image: linear-gradient(to bottom, #3c3c3c 0%, #222 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
background-repeat: repeat-x;
}
.navbar-inverse .navbar-nav > .active > a {
background-image: -webkit-linear-gradient(top, #222 0%, #282828 100%);
background-image: linear-gradient(to bottom, #222 0%, #282828 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff282828', GradientType=0);
background-repeat: repeat-x;
-webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25);
box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25);
}
.navbar-inverse .navbar-brand,
.navbar-inverse .navbar-nav > li > a {
text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
}
.navbar-static-top,
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
.alert {
text-shadow: 0 1px 0 rgba(255, 255, 255, .2);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05);
}
.alert-success {
background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);
background-repeat: repeat-x;
border-color: #b2dba1;
}
.alert-info {
background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);
background-repeat: repeat-x;
border-color: #9acfea;
}
.alert-warning {
background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);
background-repeat: repeat-x;
border-color: #f5e79e;
}
.alert-danger {
background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);
background-repeat: repeat-x;
border-color: #dca7a7;
}
.progress {
background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar {
background-image: -webkit-linear-gradient(top, #428bca 0%, #3071a9 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #3071a9 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3071a9', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-success {
background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%);
background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-info {
background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-warning {
background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);
background-repeat: repeat-x;
}
.progress-bar-danger {
background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%);
background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);
background-repeat: repeat-x;
}
.list-group {
border-radius: 4px;
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
text-shadow: 0 -1px 0 #3071a9;
background-image: -webkit-linear-gradient(top, #428bca 0%, #3278b3 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #3278b3 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3278b3', GradientType=0);
background-repeat: repeat-x;
border-color: #3278b3;
}
.panel {
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
}
.panel-default > .panel-heading {
background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
background-repeat: repeat-x;
}
.panel-primary > .panel-heading {
background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0);
background-repeat: repeat-x;
}
.panel-success > .panel-heading {
background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);
background-repeat: repeat-x;
}
.panel-info > .panel-heading {
background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);
background-repeat: repeat-x;
}
.panel-warning > .panel-heading {
background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);
background-repeat: repeat-x;
}
.panel-danger > .panel-heading {
background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);
background-repeat: repeat-x;
}
.well {
background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);
background-repeat: repeat-x;
border-color: #dcdcdc;
-webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1);
}
/*# sourceMappingURL=bootstrap-theme.css.map */
| {
"pile_set_name": "Github"
} |
// This file was procedurally generated from the following sources:
// - src/dstr-assignment-for-await/array-rest-elision.case
// - src/dstr-assignment-for-await/default/async-gen-decl.template
/*---
description: ArrayAssignmentPattern may include elisions at any position preceding a AssignmentRestElement in a AssignmentElementList. (for-await-of statement in an async generator declaration)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( LeftHandSideExpression of AssignmentExpression ) Statement
1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« »,
AssignmentExpression, iterate).
2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement,
keyResult, assignment, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
5. If destructuring is true and if lhsKind is assignment, then
a. Assert: lhs is a LeftHandSideExpression.
b. Let assignmentPattern be the parse of the source text corresponding to
lhs using AssignmentPattern as the goal symbol.
[...]
---*/
let x, y;
let iterCount = 0;
async function * fn() {
for await ([, , x, , ...y] of [[1, 2, 3, 4, 5, 6]]) {
assert.sameValue(x, 3);
assert.sameValue(y.length, 2);
assert.sameValue(y[0], 5);
assert.sameValue(y[1], 6);
iterCount += 1;
}
}
let promise = fn().next();
promise
.then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE)
.then($DONE, $DONE);
| {
"pile_set_name": "Github"
} |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var PaModel = (function () {
function PaModel() {
this.direction = "None";
this.fieldValue = "";
this.update = new core_1.EventEmitter();
}
PaModel.prototype.ngOnChanges = function (changes) {
var change = changes["modelProperty"];
if (change.currentValue != this.fieldValue) {
this.fieldValue = changes["modelProperty"].currentValue || "";
this.direction = "Model";
}
};
PaModel.prototype.updateValue = function (newValue) {
this.fieldValue = newValue;
this.update.emit(newValue);
this.direction = "Element";
};
__decorate([
core_1.Input("paModel"),
__metadata('design:type', String)
], PaModel.prototype, "modelProperty", void 0);
__decorate([
core_1.HostBinding("value"),
__metadata('design:type', String)
], PaModel.prototype, "fieldValue", void 0);
__decorate([
core_1.Output("paModelChange"),
__metadata('design:type', Object)
], PaModel.prototype, "update", void 0);
__decorate([
core_1.HostListener("input", ["$event.target.value"]),
__metadata('design:type', Function),
__metadata('design:paramtypes', [String]),
__metadata('design:returntype', void 0)
], PaModel.prototype, "updateValue", null);
PaModel = __decorate([
core_1.Directive({
selector: "input[paModel]",
exportAs: "paModel"
}),
__metadata('design:paramtypes', [])
], PaModel);
return PaModel;
}());
exports.PaModel = PaModel;
| {
"pile_set_name": "Github"
} |
/***
*wcsrchr.c - find last occurrence of wchar_t character in wide string
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines wcsrchr() - find the last occurrence of a given character
* in a string (wide-characters).
*
*******************************************************************************/
#include <vcruntime_internal.h>
/***
*wchar_t *wcsrchr(string, ch) - find last occurrence of ch in wide string
*
*Purpose:
* Finds the last occurrence of ch in string. The terminating
* null character is used as part of the search (wide-characters).
*
*Entry:
* wchar_t *string - string to search in
* wchar_t ch - character to search for
*
*Exit:
* returns a pointer to the last occurrence of ch in the given
* string
* returns NULL if ch does not occurr in the string
*
*Exceptions:
*
*******************************************************************************/
#if defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64)
// ARM64 Neon Intrinsics variant
// For long strings, this is faster than the naive version.
// But for short strings there is overhead.
#include <arm64string.h>
// Traverse the string forwards, only once.
// Collect possible matches along the way.
wchar_t * __cdecl wcsrchr (
const wchar_t * string,
wchar_t ch
)
{
vector_t *src_a, characters, match;
vector_t chmatch, chmatchrev, zeromatch, zeromatchrev, orrmatches;
__n64 uaddlvq32;
unsigned __int64 ch_lword0, ch_lword1, ch_lword0_rev, ch_lword1_rev;
unsigned __int64 zero_lword0_rev, zero_lword1_rev, mask;
unsigned __int64 andmask;
unsigned long offset, ch_bitoffset, zero_bitoffset;
wchar_t *found = (wchar_t)0;
if (ch == 0) {
if (*string == 0) {
return (wchar_t *)string;
} else {
return wcschr_zero_internal(string);
}
}
// Start by getting the aligned XMMWORD containing the first
// characters of the string. This is done first to partially
// cover any memory access latency.
// Use 16 byte alignment throughout, to guarantee page-safe loads.
src_a = (vector_t*)N128_ALIGN(string);
// Now create patterns to check for a terminating zero or match.
// These characters are copied to every position of a XMMWORD.
match = neon_dupqr16(ch);
// prepare to mask off any bits before the beginning of the string.
offset = N128_OFFSET(string);
{
// Check initial full or partial XMMWORD
characters = *src_a;
// Compare against each pattern to get flags for each match
chmatch = neon_cmeqq16(characters, match);
zeromatch = neon_cmeqzq16(characters);
// reverse order of 16bit elements within each of 2 64-bit vectors:
// ABCD EFGH => DCBA HGFE
chmatchrev = neon_rev64q_16(chmatch);
zeromatchrev = neon_rev64q_16(zeromatch);
ch_lword1_rev = neon_umovq64(chmatchrev, 1);
zero_lword1_rev = neon_umovq64(zeromatchrev, 1);
// For the initial XMMWORD mask off any bits before the beginning
// of the string.
if ((offset & 0x8) == 0) {
zero_lword0_rev = neon_umovq64(zeromatchrev, 0);
ch_lword0_rev = neon_umovq64(chmatchrev, 0);
andmask = ~0ull >> (offset << 3);
ch_lword0_rev = ch_lword0_rev & andmask;
zero_lword0_rev = zero_lword0_rev & andmask;
} else {
andmask = ~0ull >> ((offset - 8) << 3);
ch_lword0_rev = 0;
ch_lword1_rev = ch_lword1_rev & andmask;
zero_lword0_rev = 0;
zero_lword1_rev = zero_lword1_rev & andmask;
}
if ((zero_lword0_rev != 0) || (ch_lword0_rev != 0) || (zero_lword1_rev != 0) || (ch_lword1_rev != 0)) {
// Scan the lword0, lword1 for the position of the FIRST zero match
zero_bitoffset = _CountLeadingZeros128(zero_lword0_rev, zero_lword1_rev);
// Scan the lword0, lword1 for the position of the FIRST character match
ch_bitoffset = _CountLeadingZeros128(ch_lword0_rev, ch_lword1_rev);
if (zero_bitoffset < ch_bitoffset) {
// The next match is the end of the string.
return found;
}
// Take the UNREVERSED match:
ch_lword0 = neon_umovq64(chmatch, 0);
ch_lword1 = neon_umovq64(chmatch, 1);
// zero_bitoffset is in range 0..128
// Replace test for ==128 with test for bit 1<<7
if ((zero_bitoffset & 128) != 0) {
// There is no zero match in this vector.
// Record the offset of the LAST character match,
// and advance to the next vector.
ch_bitoffset = (128 - 16) - _CountLeadingZeros128(ch_lword1, ch_lword0);
found = (wchar_t*)((ch_bitoffset >> 3) + (intptr_t)(src_a));
} else {
// We have zero match after 1 or more character matches in this vector.
// Mask off all character matches after the FIRST zero match,
// RETURN the bit position of the LAST character match
if (zero_lword0_rev != 0) {
ch_lword0 = ch_lword0 & (~0ull >> (64 - zero_bitoffset));
ch_bitoffset = (64 - 16) - _CountLeadingZeros64(ch_lword0);
} else {
ch_lword1 = ch_lword1 & (~0ull >> (128 - zero_bitoffset));
ch_bitoffset = (128 - 16) - _CountLeadingZeros128(ch_lword1, ch_lword0);
}
found = (wchar_t*)((ch_bitoffset >> 3) + (intptr_t)(src_a));
return found;
}
}
}
for (;;) {
// Check each XMMWORD until the end of the string is found.
characters = *(++src_a);
// Compare against each pattern to get flags for each match
chmatch = neon_cmeqq16(characters, match);
zeromatch = neon_cmeqzq16(characters);
orrmatches = neon_orrq(chmatch, zeromatch);
uaddlvq32 = neon_uaddlvq32(orrmatches);
mask = neon_umov64(uaddlvq32, 0);
if (mask != 0) {
chmatchrev = neon_rev64q_16(chmatch);
zeromatchrev = neon_rev64q_16(zeromatch);
ch_lword0_rev = neon_umovq64(chmatchrev, 0);
zero_lword0_rev = neon_umovq64(zeromatchrev, 0);
ch_lword1_rev = neon_umovq64(chmatchrev, 1);
zero_lword1_rev = neon_umovq64(zeromatchrev, 1);
// Scan the lword0, lword1 for the position of the FIRST zero match
zero_bitoffset = _CountLeadingZeros128(zero_lword0_rev, zero_lword1_rev);
// Scan the lword0, lword1 for the position of the FIRST character match
ch_bitoffset = _CountLeadingZeros128(ch_lword0_rev, ch_lword1_rev);
if (zero_bitoffset < ch_bitoffset) {
// The next match is the end of the string.
return found;
}
// Take the UNREVERSED match:
ch_lword0 = neon_umovq64(chmatch, 0);
ch_lword1 = neon_umovq64(chmatch, 1);
// zero_bitoffset is in range 0..128
// Replace test for ==128 with test for bit 1<<7
if ((zero_bitoffset & 128) != 0) {
// There is no zero match in this vector.
// Record the offset of the LAST character match,
// and advance to the next vector.
ch_bitoffset = (128 - 16) - _CountLeadingZeros128(ch_lword1, ch_lword0);
found = (wchar_t*)((ch_bitoffset >> 3) + (intptr_t)(src_a));
} else {
// We have zero match after 1 or more character matches in this vector.
// Mask off all character matches after the FIRST zero match,
// RETURN the bit position of the LAST character match
if (zero_lword0_rev != 0) {
ch_lword0 = ch_lword0 & (~0ull >> (64 - zero_bitoffset));
ch_bitoffset = (64 - 16) - _CountLeadingZeros64(ch_lword0);
} else {
ch_lword1 = ch_lword1 & (~0ull >> (128 - zero_bitoffset));
ch_bitoffset = (128 - 16) - _CountLeadingZeros128(ch_lword1, ch_lword0);
}
found = (wchar_t*)((ch_bitoffset >> 3) + (intptr_t)(src_a));
return found;
}
}
}
}
#else
wchar_t * __cdecl wcsrchr (
const wchar_t * string,
wchar_t ch
)
{
wchar_t *start = (wchar_t *)string;
while (*string++) /* find end of string */
;
/* search towards front */
while (--string != start && *string != (wchar_t)ch)
;
if (*string == (wchar_t)ch) /* wchar_t found ? */
return( (wchar_t *)string );
return(NULL);
}
#endif
| {
"pile_set_name": "Github"
} |
#include <stropts.h>
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl -w
# Author: William Lam
# Site: www.virtuallyghetto.com
# Description: Script leveraging the new API for VDS Backup/Export feature
# Reference: https://blogs.vmware.com/vsphere/2013/01/automate-backups-of-vds-distributed-portgroup-configurations-in-vsphere-5-1.html
use strict;
use warnings;
use VMware::VIRuntime;
use VMware::VILib;
use MIME::Base64;
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
use File::Path;
use XML::LibXML;
my %opts = (
vds => {
type => "=s",
help => "Name of VDS",
required => 0,
},
operation => {
type => "=s",
help => "[list-vds|backup-vds|backup-dvpg|view-backup]",
required => 1,
},
dvpg => {
type => "=s",
help => "Name of Distributed Port Group",
required => 0,
},
backupname => {
type => "=s",
help => "Name of backup file",
required => 0,
},
note => {
type => "=s",
help => "Custom note",
required => 0,
},
schema => {
type => "=s",
help => "XML schema file",
required => 0,
},
);
Opts::add_options(%opts);
Opts::parse();
Opts::validate();
my $vds = Opts::get_option('vds');
my $dvpg = Opts::get_option('dvpg');
my $operation = Opts::get_option('operation');
my $backupname = Opts::get_option('backupname');
my $note = Opts::get_option('note');
my $schema = Opts::get_option('schema');
my ($vdsMgr,$dvPortgroups);
if($operation ne "view-backup") {
Util::connect();
$vdsMgr = Vim::get_view(mo_ref => Vim::get_service_content()->dvSwitchManager);
}
if($operation eq "list-vds") {
my $dvSwitches = Vim::find_entity_views(view_type => 'DistributedVirtualSwitch', properties => ['name','summary.productInfo.vendor','capability.featuresSupported','portgroup']);
foreach my $dvSwitch(@$dvSwitches) {
if($dvSwitch->{'summary.productInfo.vendor'} eq "VMware" && defined($dvSwitch->{'capability.featuresSupported'}->backupRestoreCapability)) {
if($dvSwitch->{'capability.featuresSupported'}->backupRestoreCapability->backupRestoreSupported) {
print "VDS: " . $dvSwitch->{'name'} . "\n";
my $dvPortgroups = eval {$dvSwitch->{portgroup} || []};
foreach my $dvPortgroup(@$dvPortgroups) {
my $dvPortgroup_view = Vim::get_view(mo_ref => $dvPortgroup, properties => ['name','tag']);
if(!$dvPortgroup_view->{tag}) {
print $dvPortgroup_view->{'name'} . "\n";
}
}
print "\n";
}
}
}
} elsif($operation eq "backup-vds" || $operation eq "backup-dvpg") {
my %fileMapping =();
my $fileCount = 0;
if($operation eq "backup-vds") {
unless($backupname && $vds) {
print "\n\"backup-vds\" option requires \"backupname\" and \"vds\" parameter!\n";
Util::disconnect();
exit 1;
}
} else {
unless($backupname && $vds && $dvpg) {
print "\n\"backup-dvpg\" option requires \"backupname\", \"vds\" and \"dvpg\" parameter!\n";
Util::disconnect();
exit 1;
}
}
# get VDS
my $dvSwitch = &findVDS($vds);
# Map file0 to dvSwitch UUID
$fileMapping{$dvSwitch->{'uuid'}} = "file" . $fileCount;
# folders for backup
my $backupFolderName = "vds-backup-" . time;
my $zipFileName = $backupname . "-" . &giveMeDate("other") . ".zip";
my $dataFolderName = "$backupFolderName/data";
my $metaFolderName = "$backupFolderName/META-INF";
my $metaDataFileName = "$metaFolderName/data.xml";
mkdir $backupFolderName;
print "\nCreating temp folder " . $backupFolderName . "\n";
if(! -e $backupFolderName) {
print "\nUnable to create temp backup folder " . $backupFolderName . "!\n";
Util::disconnect();
exit 1;
} else {
mkdir $dataFolderName;
mkdir $metaFolderName;
}
# get DvPg
$dvPortgroups = $dvSwitch->portgroup;
# backup of individual dvportgroup
if($dvpg) {
$dvPortgroups = &findDvpg($dvpg);
}
# get DvPg keys
my @dvPgKeys = ();
foreach my $dvPg(@$dvPortgroups) {
my $dvPg_view = Vim::get_view(mo_ref => $dvPg);
$fileCount++;
$fileMapping{$dvPg_view->key} = "file" . $fileCount;
push @dvPgKeys,$dvPg_view->key;
}
my $VDSSelectionSet = DVSSelection->new(dvsUuid => $dvSwitch->{'uuid'});
my $DvPgSelectionSet = DVPortgroupSelection->new(dvsUuid => $dvSwitch->{'uuid'}, portgroupKey => \@dvPgKeys);
my ($task,$msg);
eval {
print "Backing up VDS " . $vds . " ...\n";
$msg = "Successfully backed up VDS configuration!";
$task = $vdsMgr->DVSManagerExportEntity_Task(selectionSet => [$VDSSelectionSet,$DvPgSelectionSet]);
my $results = &getStatus($task,$msg);
if(defined($results)) {
foreach my $result(@$results) {
if($result->entityType eq "distributedVirtualSwitch") {
my $decoded = decode_base64($result->configBlob);
open(BLOBFILE,">" . $dataFolderName . "/" . $dvSwitch->{'uuid'} . ".bak");
binmode(BLOBFILE);
print BLOBFILE $decoded;
close(BLOBFILE);
} elsif($result->entityType eq "distributedVirtualPortgroup") {
my $decoded = decode_base64($result->configBlob);
open(BLOBFILE,">" . $dataFolderName . "/" . $result->key . ".bak");
binmode(BLOBFILE);
print BLOBFILE $decoded;
close(BLOBFILE);
}
}
print "Building XML file ...\n";
&buildAndSaveXML($dvSwitch,$dvPortgroups,$metaDataFileName,%fileMapping);
} else {
print "No results from backup, something went wrong!\n";
exit 1;
}
};
if($@) {
print "ERROR: Unable to backup VDS " . $@ . "\n";
exit 1;
}
# zip backup files
my $zipObj = Archive::Zip->new();
$zipObj->addTree($dataFolderName,'data');
$zipObj->addTree($metaFolderName,'META-INF');
print "Creating " . $zipFileName . " ...\n";
unless ($zipObj->writeToFileNamed($zipFileName) == AZ_OK) {
print "Unable to write " . $zipFileName . "!\n";
Util::disconnect();
rmtree($backupFolderName);
exit 1;
}
print "Succesfully completed VDS backup!\n";
print "Removing temp folder " . $backupFolderName . "\n\n";
rmtree($backupFolderName);
} elsif($operation eq "backup-dvpg") {
my $dvSwitch = &findVDS($vds);
} elsif($operation eq "view-backup") {
unless($backupname) {
print "\n\"view-backup\" option requires \"backupname\" parameter!\n";
Util::disconnect();
exit 1;
}
my $file = IO::File->new($backupname,'r');
my $zip = Archive::Zip->new();
my $zip_err = $zip->readFromFileHandle($file);
unless ($zip_err == AZ_OK ) {
print "Unable to open " . $backupname . ": " . $zip_err . "\n";
Util::disconnect();
exit 1;
}
foreach my $member ($zip->members()) {
my $fileName = $member->fileName();
if($fileName eq "META-INF/data.xml") {
my $content = $member->contents();
print Dumper($content);
}
}
exit 0;
} else {
print "Invalid operation!\n";
}
Util::disconnect();
sub findVDS {
my ($vdsName) = @_;
my $dvSwitch = Vim::find_entity_view(view_type => 'DistributedVirtualSwitch', filter => {'name' => $vds});
unless($dvSwitch) {
print "Unable to locate VDS " . $vdsName . "\n";
Util::disconnect();
exit 1;
}
if(!$dvSwitch->capability->featuresSupported->backupRestoreCapability->backupRestoreSupported) {
print "VDS " . $vdsName . " does not support backup and restore capabilities!\n";
Util::disconnect();
exit 1;
}
return $dvSwitch;
}
sub findDvpg {
my ($dvportgroup) = @_;
my @tmp_arr = ();
foreach my $dv (@$dvPortgroups) {
my $dv_view = Vim::get_view(mo_ref => $dv, properties => ['name']);
if($dv_view->name eq $dvportgroup) {
push @tmp_arr, $dv;
last;
}
}
return \@tmp_arr;
}
sub buildAndSaveXML {
my ($vds,$dvpgs,$fileName,%fileMap) = @_;
my $createTime = &giveMeDate("zula");
my $vdsVersion = $vds->summary->productInfo->version;
my $numRPs = eval { scalar @{$vds->networkResourcePool} || 0};
my $numUplinks = eval { scalar @{$vds->config->uplinkPortgroup} || 0};
my $vdsConfigVersion = $vds->config->configVersion;
my $vdsName = $vds->name;
my $vdsUuid = $vds->{uuid};
my $vdsFileRef = $fileMap{$vdsUuid};
my $vdsMoRef = $vds->{'mo_ref'}->value;
my %pvlanMapping = ();
# map all PVLAN primary/secondary
if($vds->config->isa("VMwareDVSConfigInfo")) {
if(defined($vds->config->pvlanConfig)) {
my $pvlans = $vds->config->pvlanConfig;
foreach my $pvlan(@$pvlans) {
$pvlanMapping{$pvlan->secondaryVlanId} = $pvlan;
}
}
}
my $xml = <<XML_START;
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:Envelope xmlns:ns1="http://vmware.com/vds/envelope/1">
<ns1:References>
<ns1:File ns1:href="data/$vdsUuid.bak" ns1:id="$vdsFileRef"/>
XML_START
my ($vlanSection,$vlanTrunkSection,$pvlanSection,$dvpgSection) = ("","","","");
my (%uniqueVlanSection,%uniqueVlanTrunkSection) = ();
# References
foreach my $dvpg (@$dvpgs) {
my $dvpg_view = Vim::get_view(mo_ref => $dvpg);
my ($trunkPorts,$trunkRanges,$vlanRef,$type,$allocation) = ("","","","standard","elastic");
my %bindings = ('lateBinding','dynamic','earlyBinding','static','ephemeral','ephemeral');
if(!$dvpg_view->config->autoExpand) {
$allocation = "fixed";
}
my $binding = $bindings{$dvpg_view->config->type};
my $file = $fileMap{$dvpg_view->key};
my $dvpgConfigVersion = $dvpg_view->config->configVersion;
$xml .= " <ns1:File ns1:href=\"data/" . $dvpg_view->key . ".bak\" ns1:id=\"" . $fileMap{$dvpg_view->key} . "\"/>\n";
# handle uplinks
if(defined($dvpg_view->tag)) {
my $tags = $dvpg_view->tag;
foreach my $tag (@$tags) {
if($tag->key eq "SYSTEM/DVS.UPLINKPG") {
$type = "uplink";
$trunkPorts = "";
my $vlans = $dvpg_view->config->defaultPortConfig->vlan->vlanId;
foreach my $vlan (@$vlans) {
$trunkPorts .= $vlan->start . "-" . $vlan->end . "_";
$trunkRanges .= " <ns1:VlanTrunkRange ns1:end=\"". $vlan->end . "\" ns1:start=\"" . $vlan->start . "\"/>\n";
}
}
}
if($trunkPorts ne "") {
my $vlanTrunkSec = " <ns1:VlanTrunk ns1:id=\"trunk_" . $trunkPorts . "\">\n" . $trunkRanges . " </ns1:VlanTrunk>\n";;
if(!$uniqueVlanTrunkSection{$vlanTrunkSec}) {
$uniqueVlanTrunkSection{$vlanTrunkSec} = "yes";
$vlanTrunkSection .= $vlanTrunkSec;
}
$dvpgSection .= §ionNode("trunk_" . $trunkPorts,$allocation,$binding,$type,$file,$dvpgConfigVersion,$dvpg_view->name,$dvpg_view->{'mo_ref'}->value);
}
# dvpgs
} else {
$type = "standard";
# trunk
if($dvpg_view->config->defaultPortConfig->vlan->isa("VmwareDistributedVirtualSwitchTrunkVlanSpec")) {
my $vlans = $dvpg_view->config->defaultPortConfig->vlan->vlanId;
foreach my $vlan (@$vlans) {
$trunkPorts .= $vlan->start . "-" . $vlan->end . "_";
$trunkRanges .= " <ns1:VlanTrunkRange ns1:end=\"". $vlan->end . "\" ns1:start=\"" . $vlan->start . "\"/>\n";
}
if($trunkPorts ne "") {
my $vlanTrunkSec = " <ns1:VlanTrunk ns1:id=\"trunk_" . $trunkPorts . "\">\n" . $trunkRanges . " </ns1:VlanTrunk>\n";;
if(!$uniqueVlanTrunkSection{$vlanTrunkSec}) {
$uniqueVlanTrunkSection{$vlanTrunkSec} = "yes";
$vlanTrunkSection .= $vlanTrunkSec;
}
$dvpgSection .= §ionNode("trunk_" . $trunkPorts,$allocation,$binding,$type,$file,$dvpgConfigVersion,$dvpg_view->name,$dvpg_view->{'mo_ref'}->value);
}
# pvlan
} elsif($dvpg_view->config->defaultPortConfig->vlan->isa("VmwareDistributedVirtualSwitchPvlanSpec")) {
my $pvlan = $pvlanMapping{$dvpg_view->config->defaultPortConfig->vlan->pvlanId};
my $primaryVlanRef = $pvlan->primaryVlanId;
my $secondaryVlanRef = $pvlan->secondaryVlanId;
my $pvlanType = $pvlan->pvlanType;
my $pvlanId = "private_" . $primaryVlanRef . "_" . $secondaryVlanRef;
$pvlanSection .= " <ns1:PrivateVlan ns1:pvlanType=\"" . $pvlanType . "\" ns1:secondary=\"" . $secondaryVlanRef . "\" ns1:primary=\"" . $primaryVlanRef . "\" ns1:id=\"" . $pvlanId . "\"/>\n";
$dvpgSection .= §ionNode($pvlanId,$allocation,$binding,$type,$file,$dvpgConfigVersion,$dvpg_view->name,$dvpg_view->{'mo_ref'}->value);
# vlan
} elsif($dvpg_view->config->defaultPortConfig->vlan->isa("VmwareDistributedVirtualSwitchVlanIdSpec")) {
$vlanRef = $dvpg_view->config->defaultPortConfig->vlan->vlanId;
my $vlanSec = " <ns1:VlanAccess ns1:vlan=\"" . $vlanRef . "\" ns1:id=\"access_" . $vlanRef . "\"/>\n";
# capture only unique vlan section
if(!$uniqueVlanSection{$vlanSec}) {
$uniqueVlanSection{$vlanSec} = "yes";
$vlanSection .= $vlanSec;
}
$dvpgSection .= §ionNode("access_" . $vlanRef,$allocation,$binding,$type,$file,$dvpgConfigVersion,$dvpg_view->name,$dvpg_view->{'mo_ref'}->value);
}
}
}
$xml .= "</ns1:References>\n";
$xml .= " <ns1:AnnotationSection>\n";
if(!defined($note)) {
$note = "Backup created with vdsBackupMgr.pl on " . &giveMeDate("other");
}
$xml .= " <ns1:Annotation>" . $note . "</ns1:Annotation>\n";
$xml .= " <ns1:CreateTime>" . $createTime . "</ns1:CreateTime>\n";
$xml .= " </ns1:AnnotationSection>\n";
$xml .= " <ns1:DistributedSwitchSection>\n";
$xml .= " <ns1:DistributedSwitch ns1:version=\"" . $vdsVersion . "\" ns1:numberOfResourcePools=\"" . $numRPs . "\" ns1:numberOfUplinks=\"" . $numUplinks . "\" ns1:configVersion=\"" . $vdsConfigVersion . "\" ns1:uuid=\"" . $vdsUuid . "\" ns1:name=\"" . $vdsName . "\" ns1:fileRef=\"" . $vdsFileRef . "\" ns1:id=\"" . $vdsMoRef . "\" />\n";
$xml .= " </ns1:DistributedSwitchSection>\n";
$xml .= " <ns1:VlanSection>\n";
$xml .= $vlanSection;
$xml .= $vlanTrunkSection;
$xml .= $pvlanSection;
$xml .= " </ns1:VlanSection>\n";
$xml .= " <ns1:DistributedPortGroupSection>\n";
$xml .= $dvpgSection;
$xml .= " </ns1:DistributedPortGroupSection>\n";
$xml .= <<XML_END;
</ns1:Envelope>
XML_END
# create data.xml file
open(VDS_XML,">" . $fileName);
print VDS_XML $xml;
close(VDS_XML);
if(defined($schema)) {
print "Validating XML against " . $schema . " ...\n";
my $doc = XML::LibXML->new->parse_file($fileName);
my $xmlschema = XML::LibXML::Schema->new(location => $schema);
eval { $xmlschema->validate( $doc ); };
if($@) {
print "Error: XML validation failed " . $@ . "\n";
Util::disconnect();
exit 1;
}
}
}
sub sectionNode {
my ($arg1,$arg2,$arg3,$arg4,$arg5,$arg6,$arg7,$arg8,$arg9) = @_;
return " <ns1:DistributedPortGroup ns1:vlanRef=\"" . $arg1 . "\" ns1:allocation=\"" . $arg2 . "\" ns1:binding=\"" . $arg3 . "\" ns1:type=\"" . $arg4 . "\" ns1:fileRef=\"" . $arg5 . "\" ns1:configVersion=\"" . $arg6 . "\" ns1:name=\"" . $arg7 . "\" ns1:id=\"" . $arg8 . "\" />\n";
}
sub getStatus {
my ($taskRef,$message) = @_;
my $task_view = Vim::get_view(mo_ref => $taskRef);
my $taskinfo = $task_view->info->state->val;
my $continue = 1;
while ($continue) {
my $info = $task_view->info;
if ($info->state->val eq 'success') {
print $message,"\n";
return $info->result;
$continue = 0;
} elsif ($info->state->val eq 'error') {
my $soap_fault = SoapFault->new;
$soap_fault->name($info->error->fault);
$soap_fault->detail($info->error->fault);
$soap_fault->fault_string($info->error->localizedMessage);
die "$soap_fault\n";
}
sleep 5;
$task_view->ViewBase::update_view_data();
}
}
sub giveMeDate {
my ($format) = @_;
my %dttime = ();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
### begin_: initialize DateTime number formats
$dttime{year } = sprintf "%04d",($year + 1900); ## four digits to specify the year
$dttime{mon } = sprintf "%02d",($mon + 1); ## zeropad months
$dttime{mday } = sprintf "%02d",$mday; ## zeropad day of the month
$dttime{wday } = sprintf "%02d",$wday + 1; ## zeropad day of week; sunday = 1;
$dttime{yday } = sprintf "%02d",$yday; ## zeropad nth day of the year
$dttime{hour } = sprintf "%02d",$hour; ## zeropad hour
$dttime{min } = sprintf "%02d",$min; ## zeropad minutes
$dttime{sec } = sprintf "%02d",$sec; ## zeropad seconds
$dttime{isdst} = $isdst;
if($format eq "zula") {
return "$dttime{year}-$dttime{mon}-$dttime{mday}T$dttime{hour}:$dttime{min}:$dttime{sec}Z";
} else {
return "$dttime{year}-$dttime{mon}-$dttime{mday}_$dttime{hour}-$dttime{min}-$dttime{sec}";
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.crypto.spec;
import java.security.spec.AlgorithmParameterSpec;
/**
* This class specifies the parameters used with the
* <a href="http://tools.ietf.org/html/rfc2040"><i>RC5</i></a>
* algorithm.
*
* <p> The parameters consist of a version number, a rounds count, a word
* size, and optionally an initialization vector (IV) (only in feedback mode).
*
* <p> This class can be used to initialize a {@code Cipher} object that
* implements the <i>RC5</i> algorithm as supplied by
* <a href="http://www.rsa.com">RSA Security LLC</a>,
* or any parties authorized by RSA Security.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class RC5ParameterSpec implements AlgorithmParameterSpec {
private byte[] iv = null;
private int version;
private int rounds;
private int wordSize; // the word size in bits
/**
* Constructs a parameter set for RC5 from the given version, number of
* rounds and word size (in bits).
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
*/
public RC5ParameterSpec(int version, int rounds, int wordSize) {
this.version = version;
this.rounds = rounds;
this.wordSize = wordSize;
}
/**
* Constructs a parameter set for RC5 from the given version, number of
* rounds, word size (in bits), and IV.
*
* <p> Note that the size of the IV (block size) must be twice the word
* size. The bytes that constitute the IV are those between
* {@code iv[0]} and {@code iv[2*(wordSize/8)-1]} inclusive.
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
* @param iv the buffer with the IV. The first {@code 2*(wordSize/8)}
* bytes of the buffer are copied to protect against subsequent
* modification.
* @exception IllegalArgumentException if {@code iv} is
* {@code null} or {@code (iv.length < 2 * (wordSize / 8))}
*/
public RC5ParameterSpec(int version, int rounds, int wordSize, byte[] iv) {
this(version, rounds, wordSize, iv, 0);
}
/**
* Constructs a parameter set for RC5 from the given version, number of
* rounds, word size (in bits), and IV.
*
* <p> The IV is taken from {@code iv}, starting at
* {@code offset} inclusive.
* Note that the size of the IV (block size), starting at
* {@code offset} inclusive, must be twice the word size.
* The bytes that constitute the IV are those between
* {@code iv[offset]} and {@code iv[offset+2*(wordSize/8)-1]}
* inclusive.
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
* @param iv the buffer with the IV. The first {@code 2*(wordSize/8)}
* bytes of the buffer beginning at {@code offset}
* inclusive are copied to protect against subsequent modification.
* @param offset the offset in {@code iv} where the IV starts.
* @exception IllegalArgumentException if {@code iv} is
* {@code null} or
* {@code (iv.length - offset < 2 * (wordSize / 8))}
*/
public RC5ParameterSpec(int version, int rounds, int wordSize,
byte[] iv, int offset) {
this.version = version;
this.rounds = rounds;
this.wordSize = wordSize;
if (iv == null) throw new IllegalArgumentException("IV missing");
int blockSize = (wordSize / 8) * 2;
if (iv.length - offset < blockSize) {
throw new IllegalArgumentException("IV too short");
}
this.iv = new byte[blockSize];
System.arraycopy(iv, offset, this.iv, 0, blockSize);
}
/**
* Returns the version.
*
* @return the version.
*/
public int getVersion() {
return this.version;
}
/**
* Returns the number of rounds.
*
* @return the number of rounds.
*/
public int getRounds() {
return this.rounds;
}
/**
* Returns the word size in bits.
*
* @return the word size in bits.
*/
public int getWordSize() {
return this.wordSize;
}
/**
* Returns the IV or null if this parameter set does not contain an IV.
*
* @return the IV or null if this parameter set does not contain an IV.
* Returns a new array each time this method is called.
*/
public byte[] getIV() {
return (iv == null? null:iv.clone());
}
/**
* Tests for equality between the specified object and this
* object. Two RC5ParameterSpec objects are considered equal if their
* version numbers, number of rounds, word sizes, and IVs are equal.
* (Two IV references are considered equal if both are {@code null}.)
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false if
* {@code obj} is null or otherwise.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof RC5ParameterSpec)) {
return false;
}
RC5ParameterSpec other = (RC5ParameterSpec) obj;
return ((version == other.version) &&
(rounds == other.rounds) &&
(wordSize == other.wordSize) &&
java.util.Arrays.equals(iv, other.iv));
}
/**
* Calculates a hash code value for the object.
* Objects that are equal will also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
if (iv != null) {
for (int i = 1; i < iv.length; i++) {
retval += iv[i] * i;
}
}
retval += (version + rounds + wordSize);
return retval;
}
}
| {
"pile_set_name": "Github"
} |
package io.udash.i18n
object Utils {
def getTranslatedString(tr: TranslationKey0)(implicit lang: Lang, provider: TranslationProvider): String =
tr().value.get.get.string
}
| {
"pile_set_name": "Github"
} |
package insertionsort
import "testing"
func TestInsertSort(t *testing.T) {
tests := []struct {
name string
array []int
}{
{
name: "sort1",
array: []int{23, 0, 12, 56, 34},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Logf("排序前:%+v", tt.array)
InsertSort(tt.array)
t.Logf("排序后:%+v", tt.array)
})
}
}
| {
"pile_set_name": "Github"
} |
/* eslint-disable global-require */
const ApiGateway = require('@cubejs-backend/api-gateway');
const crypto = require('crypto');
const fs = require('fs-extra');
const path = require('path');
const LRUCache = require('lru-cache');
const SqlString = require('sqlstring');
const R = require('ramda');
const CompilerApi = require('./CompilerApi');
const OrchestratorApi = require('./OrchestratorApi');
const RefreshScheduler = require('./RefreshScheduler');
const FileRepository = require('./FileRepository');
const DevServer = require('./DevServer');
const track = require('./track');
const agentCollect = require('./agentCollect');
const { version } = require('../package.json');
const DriverDependencies = require('./DriverDependencies');
const optionsValidate = require('./optionsValidate');
const checkEnvForPlaceholders = () => {
const placeholderSubstr = '<YOUR_DB_';
const credentials = [
'CUBEJS_DB_HOST',
'CUBEJS_DB_NAME',
'CUBEJS_DB_USER',
'CUBEJS_DB_PASS'
];
if (
credentials.find((credential) => (
process.env[credential] && process.env[credential].indexOf(placeholderSubstr) === 0
))
) {
throw new Error('Your .env file contains placeholders in DB credentials. Please replace them with your DB credentials.');
}
};
const devLogger = (level) => (type, { error, warning, ...message }) => {
const colors = {
red: '31', // ERROR
green: '32', // INFO
yellow: '33', // WARNING
};
const withColor = (str, color = colors.green) => `\u001b[${color}m${str}\u001b[0m`;
const format = ({
requestId, duration, allSqlLines, query, values, showRestParams, ...json
}) => {
const restParams = JSON.stringify(json, null, 2);
const durationStr = duration ? `(${duration}ms)` : '';
const prefix = `${requestId} ${durationStr}`;
if (query && values) {
const queryMaxLines = 50;
query = query.replace(/\$(\d+)/g, '?');
let formatted = SqlString.format(query, values).split('\n');
if (formatted.length > queryMaxLines && !allSqlLines) {
formatted = R.take(queryMaxLines / 2, formatted)
.concat(['.....', '.....', '.....'])
.concat(R.takeLast(queryMaxLines / 2, formatted));
}
return `${prefix}\n--\n ${formatted.join('\n')}\n--${showRestParams ? `\n${restParams}` : ''}`;
} else if (query) {
return `${prefix}\n--\n${JSON.stringify(query, null, 2)}\n--${showRestParams ? `\n${restParams}` : ''}`;
}
return `${prefix}${showRestParams ? `\n${restParams}` : ''}`;
};
const logWarning = () => console.log(
`${withColor(type, colors.yellow)}: ${format({ ...message, allSqlLines: true, showRestParams: true })} \n${withColor(warning, colors.yellow)}`
);
const logError = () => console.log(`${withColor(type, colors.red)}: ${format({ ...message, allSqlLines: true, showRestParams: true })} \n${error}`);
const logDetails = (showRestParams) => console.log(`${withColor(type)}: ${format({ ...message, showRestParams })}`);
if (error) {
logError();
return;
}
// eslint-disable-next-line default-case
switch ((level || 'info').toLowerCase()) {
case "trace": {
if (!error && !warning) {
logDetails(true);
break;
}
}
// eslint-disable-next-line no-fallthrough
case "info": {
if (!error && !warning && [
'Executing SQL',
'Executing Load Pre Aggregation SQL',
'Load Request Success',
'Performing query',
'Performing query completed',
].includes(type)) {
logDetails();
break;
}
}
// eslint-disable-next-line no-fallthrough
case "warn": {
if (!error && warning) {
logWarning();
break;
}
}
// eslint-disable-next-line no-fallthrough
case "error": {
if (error) {
logError();
break;
}
}
}
};
const prodLogger = (level) => (msg, params) => {
const { error, warning } = params;
const logMessage = () => console.log(JSON.stringify({ message: msg, ...params }));
// eslint-disable-next-line default-case
switch ((level || 'warn').toLowerCase()) {
case "trace": {
if (!error && !warning) {
logMessage();
break;
}
}
// eslint-disable-next-line no-fallthrough
case "info":
if ([
'REST API Request',
].includes(msg)) {
logMessage();
break;
}
// eslint-disable-next-line no-fallthrough
case "warn": {
if (!error && warning) {
logMessage();
break;
}
}
// eslint-disable-next-line no-fallthrough
case "error": {
if (error) {
logMessage();
break;
}
}
}
};
class CubejsServerCore {
constructor(options) {
optionsValidate(options);
options = options || {};
options = {
driverFactory: () => typeof options.dbType === 'string' && CubejsServerCore.createDriver(options.dbType),
dialectFactory: () => typeof options.dbType === 'string' &&
CubejsServerCore.lookupDriverClass(options.dbType).dialectClass &&
CubejsServerCore.lookupDriverClass(options.dbType).dialectClass(),
externalDriverFactory: process.env.CUBEJS_EXT_DB_TYPE && (
() => new (CubejsServerCore.lookupDriverClass(process.env.CUBEJS_EXT_DB_TYPE))({
host: process.env.CUBEJS_EXT_DB_HOST,
database: process.env.CUBEJS_EXT_DB_NAME,
port: process.env.CUBEJS_EXT_DB_PORT,
user: process.env.CUBEJS_EXT_DB_USER,
password: process.env.CUBEJS_EXT_DB_PASS,
})
),
externalDbType: process.env.CUBEJS_EXT_DB_TYPE,
apiSecret: process.env.CUBEJS_API_SECRET,
dbType: process.env.CUBEJS_DB_TYPE,
devServer: process.env.NODE_ENV !== 'production',
telemetry: process.env.CUBEJS_TELEMETRY !== 'false',
scheduledRefreshTimer: process.env.CUBEJS_SCHEDULED_REFRESH_TIMER,
scheduledRefreshTimeZones: process.env.CUBEJS_SCHEDULED_REFRESH_TIMEZONES &&
process.env.CUBEJS_SCHEDULED_REFRESH_TIMEZONES.split(',').map(t => t.trim()),
scheduledRefreshContexts: async () => [null],
...options
};
if (
!options.driverFactory ||
!options.apiSecret ||
!options.dbType
) {
throw new Error('driverFactory, apiSecret, dbType are required options');
}
this.options = options;
this.driverFactory = options.driverFactory;
this.externalDriverFactory = options.externalDriverFactory;
this.dialectFactory = options.dialectFactory;
this.externalDialectFactory = options.externalDialectFactory;
this.apiSecret = options.apiSecret;
this.schemaPath = options.schemaPath || process.env.CUBEJS_SCHEMA_PATH || 'schema';
this.dbType = options.dbType;
this.logger = options.logger ||
(process.env.NODE_ENV !== 'production' ?
devLogger(process.env.CUBEJS_LOG_LEVEL) :
prodLogger(process.env.CUBEJS_LOG_LEVEL)
);
this.repository = new FileRepository(this.schemaPath);
this.repositoryFactory = options.repositoryFactory || (() => this.repository);
this.contextToDbType = typeof options.dbType === 'function' ? options.dbType : () => options.dbType;
this.contextToExternalDbType = typeof options.externalDbType === 'function' ?
options.externalDbType :
() => options.externalDbType;
this.preAggregationsSchema =
typeof options.preAggregationsSchema === 'function' ? options.preAggregationsSchema : () => options.preAggregationsSchema;
this.compilerCache = new LRUCache({
max: options.compilerCacheSize || 250,
maxAge: options.maxCompilerCacheKeepAlive,
updateAgeOnGet: options.updateCompilerCacheKeepAlive
});
this.dataSourceIdToOrchestratorApi = {};
this.contextToAppId = options.contextToAppId || (() => process.env.CUBEJS_APP || 'STANDALONE');
this.contextToDataSourceId = options.contextToDataSourceId || this.defaultContextToDataSourceId.bind(this);
this.orchestratorOptions =
typeof options.orchestratorOptions === 'function' ?
options.orchestratorOptions :
() => options.orchestratorOptions;
// proactively free up old cache values occassionally
if (options.maxCompilerCacheKeepAlive) {
setInterval(() => this.compilerCache.prune(), options.maxCompilerCacheKeepAlive);
}
this.scheduledRefreshTimer = options.scheduledRefreshTimer;
this.scheduledRefreshTimeZones = options.scheduledRefreshTimeZones;
this.scheduledRefreshContexts = options.scheduledRefreshContexts;
if (this.scheduledRefreshTimer) {
setInterval(
async () => {
const contexts = await this.scheduledRefreshContexts();
if (contexts.length < 1) {
this.logger('Refresh Scheduler Error', {
error: 'At least one context should be returned by scheduledRefreshContexts'
});
}
await Promise.all(contexts.map(async context => {
if (this.scheduledRefreshTimeZones) {
// eslint-disable-next-line no-restricted-syntax
for (const timezone of this.scheduledRefreshTimeZones) {
await this.runScheduledRefresh(context, { timezone });
}
} else {
await this.runScheduledRefresh(context);
}
}));
},
typeof this.scheduledRefreshTimer === 'number' ||
typeof this.scheduledRefreshTimer === 'string' && this.scheduledRefreshTimer.match(/^\d+$/) ?
(this.scheduledRefreshTimer * 1000) :
5000
);
}
const { machineIdSync } = require('node-machine-id');
let anonymousId = 'unknown';
try {
anonymousId = machineIdSync();
} catch (e) {
// console.error(e);
}
this.anonymousId = anonymousId;
this.event = async (name, props) => {
if (!options.telemetry) {
return;
}
try {
if (!this.projectFingerprint) {
try {
this.projectFingerprint =
crypto.createHash('md5').update(JSON.stringify(await fs.readJson('package.json'))).digest('hex');
const coreServerJson = await fs.readJson(path.join(__dirname, '..', 'package.json'));
this.coreServerVersion = coreServerJson.version;
} catch (e) {
// console.error(e);
}
}
await track({
event: name,
anonymousId,
projectFingerprint: this.projectFingerprint,
coreServerVersion: this.coreServerVersion,
nodeVersion: process.version,
...props
});
} catch (e) {
// console.error(e);
}
};
this.initAgent();
if (this.options.devServer) {
this.devServer = new DevServer(this);
const oldLogger = this.logger;
this.logger = ((msg, params) => {
if (
msg === 'Load Request' ||
msg === 'Load Request Success' ||
msg === 'Orchestrator error' ||
msg === 'Internal Server Error' ||
msg === 'User Error' ||
msg === 'Compiling schema' ||
msg === 'Recompiling schema' ||
msg === 'Slow Query Warning'
) {
this.event(msg, { error: params.error });
}
oldLogger(msg, params);
});
let causeErrorPromise;
process.on('uncaughtException', async (e) => {
console.error(e.stack || e);
if (e.message && e.message.indexOf('Redis connection to') !== -1) {
console.log('🛑 Cube.js Server requires locally running Redis instance to connect to');
if (process.platform.indexOf('win') === 0) {
console.log('💾 To install Redis on Windows please use https://github.com/MicrosoftArchive/redis/releases');
} else if (process.platform.indexOf('darwin') === 0) {
console.log('💾 To install Redis on Mac please use https://redis.io/topics/quickstart or `$ brew install redis`');
} else {
console.log('💾 To install Redis please use https://redis.io/topics/quickstart');
}
}
if (!causeErrorPromise) {
causeErrorPromise = this.event('Dev Server Fatal Error', {
error: (e.stack || e.message || e).toString()
});
}
await causeErrorPromise;
process.exit(1);
});
} else {
const oldLogger = this.logger;
let loadRequestCount = 0;
this.logger = ((msg, params) => {
if (msg === 'Load Request Success') {
loadRequestCount++;
}
oldLogger(msg, params);
});
setInterval(() => {
this.event('Load Request Success Aggregated', { loadRequestSuccessCount: loadRequestCount });
loadRequestCount = 0;
}, 60000);
this.event('Server Start');
}
}
initAgent() {
if (process.env.CUBEJS_AGENT_ENDPOINT_URL) {
const oldLogger = this.logger;
this.preAgentLogger = oldLogger;
this.logger = (msg, params) => {
oldLogger(msg, params);
agentCollect(
{
msg,
...params
},
process.env.CUBEJS_AGENT_ENDPOINT_URL,
oldLogger
);
};
}
}
async flushAgent() {
if (process.env.CUBEJS_AGENT_ENDPOINT_URL) {
await agentCollect(
{ msg: 'Flush Agent' },
process.env.CUBEJS_AGENT_ENDPOINT_URL,
this.preAgentLogger
);
}
}
static create(options) {
return new CubejsServerCore(options);
}
async initApp(app) {
checkEnvForPlaceholders();
const apiGateway = this.apiGateway();
apiGateway.initApp(app);
if (this.options.devServer) {
this.devServer.initDevEnv(app);
} else {
app.get('/', (req, res) => {
res.status(200)
.send(`<html><body>Cube.js server is running in production mode. <a href="https://cube.dev/docs/deployment#production-mode">Learn more about production mode</a>.</body></html>`);
});
}
}
initSubscriptionServer(sendMessage) {
checkEnvForPlaceholders();
const apiGateway = this.apiGateway();
return apiGateway.initSubscriptionServer(sendMessage);
}
apiGateway() {
if (!this.apiGatewayInstance) {
this.apiGatewayInstance = new ApiGateway(
this.apiSecret,
this.getCompilerApi.bind(this),
this.getOrchestratorApi.bind(this),
this.logger, {
basePath: this.options.basePath,
checkAuthMiddleware: this.options.checkAuthMiddleware,
checkAuth: this.options.checkAuth,
queryTransformer: this.options.queryTransformer,
extendContext: this.options.extendContext,
refreshScheduler: () => new RefreshScheduler(this)
}
);
}
return this.apiGatewayInstance;
}
getCompilerApi(context) {
const appId = this.contextToAppId(context);
let compilerApi = this.compilerCache.get(appId);
const currentSchemaVersion = this.options.schemaVersion && (() => this.options.schemaVersion(context));
if (!compilerApi) {
compilerApi = this.createCompilerApi(
this.repositoryFactory(context), {
dbType: (dataSourceContext) => this.contextToDbType({ ...context, ...dataSourceContext }),
externalDbType: this.contextToExternalDbType(context),
dialectClass: (dataSourceContext) => this.dialectFactory &&
this.dialectFactory({ ...context, ...dataSourceContext }),
externalDialectClass: this.externalDialectFactory && this.externalDialectFactory(context),
schemaVersion: currentSchemaVersion,
preAggregationsSchema: this.preAggregationsSchema(context),
context,
allowJsDuplicatePropsInSchema: this.options.allowJsDuplicatePropsInSchema
}
);
this.compilerCache.set(appId, compilerApi);
}
compilerApi.schemaVersion = currentSchemaVersion;
return compilerApi;
}
defaultContextToDataSourceId(context) {
return `${this.contextToAppId(context)}_${context.dataSource}`;
}
getOrchestratorApi(context) {
const dataSourceId = this.contextToDataSourceId(context);
if (!this.dataSourceIdToOrchestratorApi[dataSourceId]) {
let driverPromise;
let externalPreAggregationsDriverPromise;
this.dataSourceIdToOrchestratorApi[dataSourceId] = this.createOrchestratorApi({
getDriver: async () => {
if (!driverPromise) {
const driver = await this.driverFactory(context);
if (driver.setLogger) {
driver.setLogger(this.logger);
}
driverPromise = driver.testConnection().then(() => driver).catch(e => {
driverPromise = null;
throw e;
});
}
return driverPromise;
},
getExternalDriverFactory: this.externalDriverFactory && (async () => {
if (!externalPreAggregationsDriverPromise) {
const driver = await this.externalDriverFactory(context);
if (driver.setLogger) {
driver.setLogger(this.logger);
}
externalPreAggregationsDriverPromise = driver.testConnection().then(() => driver).catch(e => {
externalPreAggregationsDriverPromise = null;
throw e;
});
}
return externalPreAggregationsDriverPromise;
}),
redisPrefix: dataSourceId,
orchestratorOptions: this.orchestratorOptions(context)
});
}
return this.dataSourceIdToOrchestratorApi[dataSourceId];
}
createCompilerApi(repository, options) {
options = options || {};
return new CompilerApi(repository, options.dbType || this.dbType, {
schemaVersion: options.schemaVersion || this.options.schemaVersion,
devServer: this.options.devServer,
logger: this.logger,
externalDbType: options.externalDbType,
preAggregationsSchema: options.preAggregationsSchema,
allowUngroupedWithoutPrimaryKey: this.options.allowUngroupedWithoutPrimaryKey,
compileContext: options.context,
dialectClass: options.dialectClass,
externalDialectClass: options.externalDialectClass,
allowJsDuplicatePropsInSchema: options.allowJsDuplicatePropsInSchema
});
}
createOrchestratorApi(options) {
options = options || {};
return new OrchestratorApi(options.getDriver || this.getDriver.bind(this), this.logger, {
redisPrefix: options.redisPrefix || process.env.CUBEJS_APP,
externalDriverFactory: options.getExternalDriverFactory,
...(options.orchestratorOptions || this.options.orchestratorOptions)
});
}
async runScheduledRefresh(context, queryingOptions) {
const scheduler = new RefreshScheduler(this);
return scheduler.runScheduledRefresh(context, queryingOptions);
}
async getDriver() {
if (!this.driver) {
const driver = this.driverFactory({});
await driver.testConnection(); // TODO mutex
this.driver = driver;
}
return this.driver;
}
static createDriver(dbType) {
checkEnvForPlaceholders();
const module = CubejsServerCore.lookupDriverClass(dbType);
if (module.default) {
// eslint-disable-next-line new-cap
return new module.default();
}
// eslint-disable-next-line new-cap
return new module();
}
static lookupDriverClass(dbType) {
// eslint-disable-next-line global-require,import/no-dynamic-require
const module = require(CubejsServerCore.driverDependencies(dbType || process.env.CUBEJS_DB_TYPE));
if (module.default) {
return module.default;
}
return module;
}
static driverDependencies(dbType) {
if (DriverDependencies[dbType]) {
return DriverDependencies[dbType];
} else if (fs.existsSync(path.join('node_modules', `${dbType}-cubejs-driver`))) {
return `${dbType}-cubejs-driver`;
}
throw new Error(`Unsupported db type: ${dbType}`);
}
testConnections() {
const tests = [];
Object.keys(this.dataSourceIdToOrchestratorApi).forEach(dataSourceId => {
const orchestratorApi = this.dataSourceIdToOrchestratorApi[dataSourceId];
tests.push(orchestratorApi.testConnection());
});
return Promise.all(tests);
}
async releaseConnections() {
const releases = [];
Object.keys(this.dataSourceIdToOrchestratorApi).forEach(dataSourceId => {
const orchestratorApi = this.dataSourceIdToOrchestratorApi[dataSourceId];
releases.push(orchestratorApi.release());
});
await Promise.all(releases);
this.dataSourceIdToOrchestratorApi = {};
}
static version() {
return version;
}
}
module.exports = CubejsServerCore;
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2008-2016, XebiaLabs B.V., All rights reserved.
*
*
* Overthere is licensed under the terms of the GPLv2
* <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most XebiaLabs Libraries.
* There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
* this software, see the FLOSS License Exception
* <http://github.com/xebialabs/overthere/blob/master/LICENSE>.
*
* This program is free software; you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation; version 2
* of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
* Floor, Boston, MA 02110-1301 USA
*/
package com.xebialabs.overthere.itest;
import java.util.Arrays;
import org.testng.annotations.Test;
import com.xebialabs.overthere.OverthereFile;
import static com.xebialabs.overthere.local.LocalConnection.getLocalConnection;
import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public abstract class ItestsBase3Copy extends ItestsBase2Basics {
private static final String SOURCE_DIR_NAME = "dir-to-copy";
private static final String DESTINATION_DIR_ALTERNATIVE_NAME = "dir-to-copy-with-different-name";
private static byte[] SOURCE_FILE_CONTENTS = "This file should be copied".getBytes();
private static final String SOURCE_FILE_NAME = "file-to-copy.txt";
private static final String DESTINATION_FILE_ALTERNATIVE_NAME = "file-to-copy-with-different-name.txt";
private static byte[] EXISTENT_DEST_FILE_CONTENT = "This file should be overwritten".getBytes();
private static final String OTHER_DEST_FILE_NAME = "file-to-be-left-as-is.txt";
private static byte[] OTHER_DEST_FILE_CONTENT = "This should be left as-is".getBytes();
/**
* Test copies from a local file to a remote file.
*/
@Test
public void shouldCopyLocalFileToNonExistentRemoteFile() {
shouldCopyToNonExistentFile(getLocalSourceFile(), getRemoteDestinationFile());
}
@Test
public void shouldCopyLocalFileToExistentRemoteFile() {
shouldCopyToExistentFile(getLocalSourceFile(), getRemoteDestinationFile());
}
@Test
public void shouldCopyLocalFileToNonExistentRemoteFileWithDifferentName() {
shouldCopyToNonExistentFile(getLocalSourceFile(), getRemoteDestinationFileWithDifferentName());
}
@Test
public void shouldCopyLocalFileToExistentRemoteFileWithDifferentName() {
shouldCopyToExistentFile(getLocalSourceFile(), getRemoteDestinationFileWithDifferentName());
}
/**
* Test copies from a remote file to a remote file.
*/
@Test
public void shouldCopyRemoteFileToNonExistentRemoteFile() {
shouldCopyToNonExistentFile(getRemoteSourceFile(), getRemoteDestinationFile());
}
@Test
public void shouldCopyRemoteFileToExistentRemoteFile() {
shouldCopyToExistentFile(getRemoteSourceFile(), getRemoteDestinationFile());
}
@Test
public void shouldCopyRemoteFileToNonExistentRemoteFileWithDifferentName() {
shouldCopyToNonExistentFile(getRemoteSourceFile(), getRemoteDestinationFileWithDifferentName());
}
@Test
public void shouldCopyRemoteFileToExistentRemoteFileWithDifferentName() {
shouldCopyToExistentFile(getRemoteSourceFile(), getRemoteDestinationFileWithDifferentName());
}
/**
* Test copies from a remote (temporary) file to a remote (temporary) file.
*/
@Test
public void shouldCopyRemoteFileToNonExistentRemoteTempFile() {
shouldCopyToNonExistentFile(getRemoteSourceFile(), getRemoteTempDestinationFile());
}
@Test
public void shouldCopyRemoteFileToExistentRemoteTempFile() {
shouldCopyToExistentFile(getRemoteSourceFile(), getRemoteTempDestinationFile());
}
@Test
public void shouldCopyRemoteTempFileToNonExistentRemoteFile() {
shouldCopyToNonExistentFile(getRemoteTempSourceFile(), getRemoteDestinationFile());
}
@Test
public void shouldCopyRemoteTempFileToExistentRemoteFile() {
shouldCopyToExistentFile(getRemoteTempSourceFile(), getRemoteDestinationFile());
}
@Test
public void shouldCopyRemoteTempFileToNonExistentRemoteTempFile() {
shouldCopyToNonExistentFile(getRemoteTempSourceFile(), getRemoteTempDestinationFile());
}
@Test
public void shouldCopyRemoteTempFileToExistentRemoteTempFile() {
shouldCopyToExistentFile(getRemoteTempSourceFile(), getRemoteTempDestinationFile());
}
/**
* Test copies from a local directory to a remote directory.
*/
@Test
public void shouldCopyLocalDirectoryToNonExistentRemoteDirectory() {
shouldCopyToNonExistentDirectory(getLocalSourceDirectory(), getRemoteDestinationDirectory());
}
@Test
public void shouldCopyLocalDirectoryToExistentRemoteDirectory() {
shouldCopyToExistentDirectory(getLocalSourceDirectory(), getRemoteDestinationDirectory());
}
@Test
public void shouldCopyLocalDirectoryToNonExistentRemoteDirectoryWithDifferentName() {
shouldCopyToNonExistentDirectory(getLocalSourceDirectory(), getRemoteDestinationDirectoryWithDifferentName());
}
@Test
public void shouldCopyLocalDirectoryToExistentRemoteDirectoryWithDifferentName() {
shouldCopyToExistentDirectory(getLocalSourceDirectory(), getRemoteDestinationDirectoryWithDifferentName());
}
/**
* Test copies from a remote directory to a remote directory.
*/
@Test
public void shouldCopyRemoteDirectoryToNonExistentRemoteDirectory() {
shouldCopyToNonExistentDirectory(getRemoteSourceDirectory(), getRemoteDestinationDirectory());
}
@Test
public void shouldCopyRemoteDirectoryToExistentRemoteDirectory() {
shouldCopyToExistentDirectory(getRemoteSourceDirectory(), getRemoteDestinationDirectory());
}
@Test
public void shouldCopyRemoteDirectoryToNonExistentRemoteDirectoryWithDifferentName() {
shouldCopyToNonExistentDirectory(getRemoteSourceDirectory(), getRemoteDestinationDirectoryWithDifferentName());
}
@Test
public void shouldCopyRemoteDirectoryToExistentRemoteDirectoryWithDifferentName() {
shouldCopyToExistentDirectory(getRemoteSourceDirectory(), getRemoteDestinationDirectoryWithDifferentName());
}
/**
* Test copies from a remote directory to a remote directory with a trailing file separator.
*/
@Test
public void shouldCopyLocalDirectoryToNonExistentRemoteDirectoryWithTrailingFileSeparator() {
shouldCopyToNonExistentDirectory(getLocalSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectory()));
}
@Test
public void shouldCopyLocalDirectoryToExistentRemoteDirectoryWithTrailingFileSeparator() {
shouldCopyToExistentDirectory(getLocalSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectory()));
}
@Test
public void shouldCopyLocalDirectoryToNonExistentRemoteDirectoryWithDifferentNameAndTrailingFileSeparator() {
shouldCopyToNonExistentDirectory(getLocalSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectoryWithDifferentName()));
}
@Test
public void shouldCopyLocalDirectoryToExistentRemoteDirectoryWithDifferentNameAndTrailingFileSeparator() {
shouldCopyToExistentDirectory(getLocalSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectoryWithDifferentName()));
}
@Test
public void shouldCopyRemoteDirectoryToNonExistentRemoteDirectoryWithTrailingFileSeparator() {
shouldCopyToNonExistentDirectory(getRemoteSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectory()));
}
@Test
public void shouldCopyRemoteDirectoryToExistentRemoteDirectoryWithTrailingFileSeparator() {
shouldCopyToExistentDirectory(getRemoteSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectory()));
}
@Test
public void shouldCopyRemoteDirectoryToNonExistentRemoteDirectoryWithDifferentNameAndTrailingFileSeparator() {
shouldCopyToNonExistentDirectory(getRemoteSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectoryWithDifferentName()));
}
@Test
public void shouldCopyRemoteDirectoryToExistentRemoteDirectoryWithDifferentNameAndTrailingFileSeparator() {
shouldCopyToExistentDirectory(getRemoteSourceDirectory(), appendFileSeparator(getRemoteDestinationDirectoryWithDifferentName()));
}
/**
* Test copies from a remote (temporary) directory to a remote (temporary) directory.
*/
@Test
public void shouldCopyRemoteDirectoryToNonExistentRemoteTempDirectory() {
shouldCopyToNonExistentDirectory(getRemoteSourceDirectory(), getRemoteTempDestinationDirectory());
}
@Test
public void shouldCopyRemoteDirectoryToExistentRemoteTempDirectory() {
shouldCopyToExistentDirectory(getRemoteSourceDirectory(), getRemoteTempDestinationDirectory());
}
@Test
public void shouldCopyRemoteTempDirectoryToNonExistentRemoteDirectory() {
shouldCopyToNonExistentDirectory(getRemoteTempSourceDirectory(), getRemoteDestinationDirectory());
}
@Test
public void shouldCopyRemoteTempDirectoryToExistentRemoteDirectory() {
shouldCopyToExistentDirectory(getRemoteTempSourceDirectory(), getRemoteDestinationDirectory());
}
@Test
public void shouldCopyRemoteTempDirectoryToNonExistentRemoteTempDirectory() {
shouldCopyToNonExistentDirectory(getRemoteTempSourceDirectory(), getRemoteTempDestinationDirectory());
}
@Test
public void shouldCopyRemoteTempDirectoryToExistentRemoteTempDirectory() {
shouldCopyToExistentDirectory(getRemoteTempSourceDirectory(), getRemoteTempDestinationDirectory());
}
private OverthereFile getLocalSourceFile() {
return getLocalConnection().getTempFile(SOURCE_FILE_NAME);
}
private OverthereFile getRemoteSourceFile() {
return connection.getFile(connection.getTempFile(SOURCE_FILE_NAME).getPath());
}
private OverthereFile getRemoteDestinationFile() {
return connection.getFile(connection.getTempFile(SOURCE_FILE_NAME).getPath());
}
private OverthereFile getRemoteTempSourceFile() {
return connection.getTempFile(SOURCE_FILE_NAME);
}
private OverthereFile getRemoteTempDestinationFile() {
return connection.getTempFile(SOURCE_FILE_NAME);
}
private OverthereFile getRemoteDestinationFileWithDifferentName() {
return connection.getFile(connection.getTempFile(DESTINATION_FILE_ALTERNATIVE_NAME).getPath());
}
private void populateSourceFile(OverthereFile srcFile) {
writeData(srcFile, SOURCE_FILE_CONTENTS);
}
private void populateExistentDestinationFile(OverthereFile dstFile) {
writeData(dstFile, EXISTENT_DEST_FILE_CONTENT);
}
private void assertSourceFileWasCopiedToDestinationFile(OverthereFile dstFile) {
dstFile = connection.getFile(dstFile.getPath());
assertFile(dstFile, SOURCE_FILE_CONTENTS);
}
private OverthereFile getLocalSourceDirectory() {
return getLocalConnection().getTempFile(SOURCE_DIR_NAME);
}
private OverthereFile getRemoteSourceDirectory() {
return connection.getFile(connection.getTempFile(SOURCE_DIR_NAME).getPath());
}
private OverthereFile getRemoteDestinationDirectory() {
return connection.getFile(connection.getTempFile(SOURCE_DIR_NAME).getPath());
}
private OverthereFile getRemoteTempSourceDirectory() {
return connection.getTempFile(SOURCE_DIR_NAME);
}
private OverthereFile getRemoteTempDestinationDirectory() {
return connection.getTempFile(SOURCE_DIR_NAME);
}
private OverthereFile getRemoteDestinationDirectoryWithDifferentName() {
return connection.getFile(connection.getTempFile(DESTINATION_DIR_ALTERNATIVE_NAME).getPath());
}
private OverthereFile appendFileSeparator(OverthereFile dir) {
return connection.getFile(dir.getPath() + connection.getHostOperatingSystem().getFileSeparator());
}
private void shouldCopyToNonExistentFile(final OverthereFile srcFile, final OverthereFile dstFile) {
populateSourceFile(srcFile);
srcFile.copyTo(dstFile);
assertSourceFileWasCopiedToDestinationFile(dstFile);
}
private void shouldCopyToExistentFile(final OverthereFile srcFile, final OverthereFile dstFile) {
populateSourceFile(srcFile);
populateExistentDestinationFile(dstFile);
srcFile.copyTo(dstFile);
assertSourceFileWasCopiedToDestinationFile(dstFile);
}
private void shouldCopyToNonExistentDirectory(final OverthereFile srcDir, final OverthereFile dstDir) {
populateSourceDirectory(srcDir);
srcDir.copyTo(dstDir);
assertSourceDirectoryWasCopiedToNonExistentDestinationDirectory(dstDir);
}
private void shouldCopyToExistentDirectory(final OverthereFile srcDir, final OverthereFile dstDir) {
populateSourceDirectory(srcDir);
populateExistentDestinationDirectory(dstDir);
srcDir.copyTo(dstDir);
assertSourceDirectoryWasCopiedToExistentDestinationDirectory(dstDir);
}
private void populateSourceDirectory(OverthereFile srcDir) {
srcDir.mkdir();
OverthereFile fileInSrcDir = srcDir.getFile(SOURCE_FILE_NAME);
writeData(fileInSrcDir, SOURCE_FILE_CONTENTS);
}
private void populateExistentDestinationDirectory(OverthereFile dstDir) {
dstDir.mkdir();
OverthereFile otherFileInDestDir = dstDir.getFile(OTHER_DEST_FILE_NAME);
writeData(otherFileInDestDir, OTHER_DEST_FILE_CONTENT);
}
private void assertSourceDirectoryWasCopiedToNonExistentDestinationDirectory(OverthereFile dstDir) {
dstDir = connection.getFile(dstDir.getPath());
assertDir(dstDir);
assertFile(dstDir.getFile(SOURCE_FILE_NAME), SOURCE_FILE_CONTENTS);
assertThat(dstDir.getFile(OTHER_DEST_FILE_NAME).exists(), is(false));
}
private void assertSourceDirectoryWasCopiedToExistentDestinationDirectory(OverthereFile dstDir) {
dstDir = connection.getFile(dstDir.getPath());
assertDir(dstDir);
assertFile(dstDir.getFile(SOURCE_FILE_NAME), SOURCE_FILE_CONTENTS);
assertFile(dstDir.getFile(OTHER_DEST_FILE_NAME), OTHER_DEST_FILE_CONTENT);
}
private void assertDir(final OverthereFile dir) {
assertThat(format("Directory [%s] does not exist", dir), dir.exists(), is(true));
assertThat(format("Directory [%s] is not a directory", dir), dir.isDirectory(), is(true));
}
private void assertFile(final OverthereFile file, final byte[] expectedContents) {
assertThat(format("File [%s] does not exist", file), file.exists(), is(true));
assertThat(format("File [%s] is not a regular file", file), file.isFile(), is(true));
byte[] actualContents = readFile(file);
assertThat(format("File [%s] does not have the expected contents", file), Arrays.equals(actualContents, expectedContents), is(true));
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2009-2016 Weibo, 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.
*/
package com.weibo.api.motan.filter;
import com.weibo.api.motan.core.extension.Spi;
import com.weibo.api.motan.rpc.Caller;
import com.weibo.api.motan.rpc.Request;
import com.weibo.api.motan.rpc.Response;
/**
*
* filter before transport.
*
* @author fishermen
* @version V1.0 created at: 2013-5-16
*/
@Spi
public interface Filter {
Response filter(Caller<?> caller, Request request);
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2012-2013, Michael Yang 杨福海 (www.yangfuhai.com).
*
* 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 net.tsz.afinal.annotation.sqlite;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
public String column() default "";
public String defaultValue() default "";
}
| {
"pile_set_name": "Github"
} |
Pair Tag Highlighter
====================
About
-----
Finds and highlights matching opening/closing HTML tag by clicking or
moving cursor inside a tag.
Usage
-----
Just enable plugin through Geany's plugin manager.
Licence
-------
This plugin is distributed under the terms of the BSD 2-Clause License.
You should have received a copy of the the BSD 2-Clause License in the
file COPYING included with the source code of this plugin. If not, find
it at <http://opensource.org/licenses/BSD-2-Clause>.
Contact developer
-----------------
You may contact developer (Volodymyr Kononenko) via e-mail:
<vm(at)kononenko(dot)ws>. The complete up to date list of contacts
can be found at <http://kononenko.ws/en/contacts>.
| {
"pile_set_name": "Github"
} |
module Awspec::Generator
module Doc
module Type
class IamRole < Base
def initialize
super
@type_name = 'IamRole'
@type = Awspec::Type::IamRole.new('my-iam-role')
@ret = @type.resource_via_client
@matchers = %w(be_allowed_action)
@ignore_matchers = []
@describes = []
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/fourbytwo_app_widget"
android:minHeight="110dp"
android:minWidth="250dp"
android:updatePeriodMillis="0" />
| {
"pile_set_name": "Github"
} |
// This is core/vbl/io/vbl_io_array_2d.h
#ifndef vbl_io_array_2d_h
#define vbl_io_array_2d_h
//:
// \file
// \author K.Y.McGaul
// \date 22-Mar-2001
#include <iosfwd>
#include <vsl/vsl_fwd.h>
#include <vbl/vbl_array_2d.h>
#ifdef _MSC_VER
# include <vcl_msvc_warnings.h>
#endif
//: Binary save vbl_array_2d to stream.
template <class T>
void vsl_b_write(vsl_b_ostream & os, const vbl_array_2d<T> & v);
//: Binary load vbl_array_2d from stream.
template <class T>
void vsl_b_read(vsl_b_istream & is, vbl_array_2d<T> & v);
//: Print human readable summary of object to a stream
template <class T>
void vsl_print_summary(std::ostream & os,const vbl_array_2d<T> & b);
#endif // vbl_io_array_2d_h
| {
"pile_set_name": "Github"
} |
// Text overflow
// Requires inline-block or block for proper styling
.text-overflow() {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Allow freebl and softoken to be loaded without util or NSPR.
*
* These symbols are overridden once real NSPR, and libutil are attached.
*/
#define _GNU_SOURCE 1
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#include <dlfcn.h>
#include <prio.h>
#include <prlink.h>
#include <prlog.h>
#include <prthread.h>
#include <plstr.h>
#include <prinit.h>
#include <prlock.h>
#include <prmem.h>
#include <prerror.h>
#include <prmon.h>
#include <pratom.h>
#include <prsystem.h>
#include <prinrval.h>
#include <prtime.h>
#include <prcvar.h>
#include <secasn1.h>
#include <secdig.h>
#include <secport.h>
#include <secitem.h>
#include <blapi.h>
#include <assert.h>
#include <private/pprio.h>
/* Android API < 21 doesn't define RTLD_NOLOAD */
#ifndef RTLD_NOLOAD
#define RTLD_NOLOAD 0
#endif
#define FREEBL_NO_WEAK 1
#define WEAK __attribute__((weak))
#ifdef FREEBL_NO_WEAK
/*
* This uses function pointers.
*
* CONS: A separate function is needed to
* fill in the function pointers.
*
* PROS: it works on all platforms.
* it allows for dynamically finding nspr and libutil, even once
* softoken is loaded and running. (NOTE: this may be a problem if
* we switch between the stubs and real NSPR on the fly. NSPR will
* do bad things if passed an _FakeArena to free or allocate from).
*/
#define STUB_DECLARE(ret, fn, args) \
typedef ret(*type_##fn) args; \
static type_##fn ptr_##fn = NULL
#define STUB_SAFE_CALL0(fn) \
if (ptr_##fn) { \
return ptr_##fn(); \
}
#define STUB_SAFE_CALL1(fn, a1) \
if (ptr_##fn) { \
return ptr_##fn(a1); \
}
#define STUB_SAFE_CALL2(fn, a1, a2) \
if (ptr_##fn) { \
return ptr_##fn(a1, a2); \
}
#define STUB_SAFE_CALL3(fn, a1, a2, a3) \
if (ptr_##fn) { \
return ptr_##fn(a1, a2, a3); \
}
#define STUB_SAFE_CALL4(fn, a1, a2, a3, a4) \
if (ptr_##fn) { \
return ptr_##fn(a1, a2, a3, a4); \
}
#define STUB_SAFE_CALL6(fn, a1, a2, a3, a4, a5, a6) \
if (ptr_##fn) { \
return ptr_##fn(a1, a2, a3, a4, a5, a6); \
}
#define STUB_FETCH_FUNCTION(fn) \
ptr_##fn = (type_##fn)dlsym(lib, #fn); \
if (ptr_##fn == NULL) { \
return SECFailure; \
}
#else
/*
* this uses the loader weak attribute. it works automatically, but once
* freebl is loaded, the symbols are 'fixed' (later loading of NSPR or
* libutil will not resolve these symbols).
*/
#define STUB_DECLARE(ret, fn, args) \
WEAK extern ret fn args
#define STUB_SAFE_CALL0(fn) \
if (fn) { \
return fn(); \
}
#define STUB_SAFE_CALL1(fn, a1) \
if (fn) { \
return fn(a1); \
}
#define STUB_SAFE_CALL2(fn, a1, a2) \
if (fn) { \
return fn(a1, a2); \
}
#define STUB_SAFE_CALL3(fn, a1, a2, a3) \
if (fn) { \
return fn(a1, a2, a3); \
}
#define STUB_SAFE_CALL4(fn, a1, a2, a3, a4) \
if (fn) { \
return fn(a1, a2, a3, a4); \
}
#define STUB_SAFE_CALL6(fn, a1, a2, a3, a4, a5, a6) \
if (fn) { \
return fn(a1, a2, a3, a4, a5, a6); \
}
#endif
STUB_DECLARE(void *, PORT_Alloc_Util, (size_t len));
STUB_DECLARE(void *, PORT_ArenaAlloc_Util, (PLArenaPool * arena, size_t size));
STUB_DECLARE(void *, PORT_ArenaZAlloc_Util, (PLArenaPool * arena, size_t size));
STUB_DECLARE(void, PORT_Free_Util, (void *ptr));
STUB_DECLARE(void, PORT_FreeArena_Util, (PLArenaPool * arena, PRBool zero));
STUB_DECLARE(int, PORT_GetError_Util, (void));
STUB_DECLARE(PLArenaPool *, PORT_NewArena_Util, (unsigned long chunksize));
STUB_DECLARE(void, PORT_SetError_Util, (int value));
STUB_DECLARE(void *, PORT_ZAlloc_Util, (size_t len));
STUB_DECLARE(void *, PORT_ZAllocAligned_Util, (size_t bytes, size_t alignment,
void **mem));
STUB_DECLARE(void *, PORT_ZAllocAlignedOffset_Util, (size_t bytes,
size_t alignment,
size_t offset));
STUB_DECLARE(void, PORT_ZFree_Util, (void *ptr, size_t len));
STUB_DECLARE(void, PR_Assert, (const char *s, const char *file, PRIntn ln));
STUB_DECLARE(PRStatus, PR_Access, (const char *name, PRAccessHow how));
STUB_DECLARE(PRStatus, PR_CallOnce, (PRCallOnceType * once, PRCallOnceFN func));
STUB_DECLARE(PRStatus, PR_Close, (PRFileDesc * fd));
STUB_DECLARE(void, PR_DestroyLock, (PRLock * lock));
STUB_DECLARE(void, PR_DestroyCondVar, (PRCondVar * cvar));
STUB_DECLARE(void, PR_Free, (void *ptr));
STUB_DECLARE(char *, PR_GetLibraryFilePathname, (const char *name,
PRFuncPtr addr));
STUB_DECLARE(PRFileDesc *, PR_ImportPipe, (PROsfd osfd));
STUB_DECLARE(void, PR_Lock, (PRLock * lock));
STUB_DECLARE(PRCondVar *, PR_NewCondVar, (PRLock * lock));
STUB_DECLARE(PRLock *, PR_NewLock, (void));
STUB_DECLARE(PRStatus, PR_NotifyCondVar, (PRCondVar * cvar));
STUB_DECLARE(PRStatus, PR_NotifyAllCondVar, (PRCondVar * cvar));
STUB_DECLARE(PRFileDesc *, PR_Open, (const char *name, PRIntn flags,
PRIntn mode));
STUB_DECLARE(PRInt32, PR_Read, (PRFileDesc * fd, void *buf, PRInt32 amount));
STUB_DECLARE(PROffset32, PR_Seek, (PRFileDesc * fd, PROffset32 offset,
PRSeekWhence whence));
STUB_DECLARE(PRStatus, PR_Sleep, (PRIntervalTime ticks));
STUB_DECLARE(PRStatus, PR_Unlock, (PRLock * lock));
STUB_DECLARE(PRStatus, PR_WaitCondVar, (PRCondVar * cvar,
PRIntervalTime timeout));
STUB_DECLARE(char *, PR_GetEnvSecure, (const char *));
STUB_DECLARE(SECItem *, SECITEM_AllocItem_Util, (PLArenaPool * arena,
SECItem *item, unsigned int len));
STUB_DECLARE(SECComparison, SECITEM_CompareItem_Util, (const SECItem *a,
const SECItem *b));
STUB_DECLARE(SECStatus, SECITEM_CopyItem_Util, (PLArenaPool * arena,
SECItem *to, const SECItem *from));
STUB_DECLARE(void, SECITEM_FreeItem_Util, (SECItem * zap, PRBool freeit));
STUB_DECLARE(void, SECITEM_ZfreeItem_Util, (SECItem * zap, PRBool freeit));
STUB_DECLARE(SECOidTag, SECOID_FindOIDTag_Util, (const SECItem *oid));
STUB_DECLARE(int, NSS_SecureMemcmp, (const void *a, const void *b, size_t n));
STUB_DECLARE(unsigned int, NSS_SecureMemcmpZero, (const void *mem, size_t n));
#define PORT_ZNew_stub(type) (type *)PORT_ZAlloc_stub(sizeof(type))
#define PORT_New_stub(type) (type *)PORT_Alloc_stub(sizeof(type))
#define PORT_ZNewArray_stub(type, num) \
(type *)PORT_ZAlloc_stub(sizeof(type) * (num))
#define PORT_ZNewAligned_stub(type, alignment, mem) \
(type *)PORT_ZAllocAlignedOffset_stub(sizeof(type), alignment, offsetof(type, mem))
/*
* NOTE: in order to support hashing only the memory allocation stubs,
* the get library name stubs, and the file io stubs are needed (the latter
* two are for the library verification). The remaining stubs are simply to
* compile. Attempts to use the library for other operations without NSPR
* will most likely fail.
*/
/* memory */
extern void *
PORT_Alloc_stub(size_t len)
{
STUB_SAFE_CALL1(PORT_Alloc_Util, len);
return malloc(len);
}
extern void
PORT_Free_stub(void *ptr)
{
STUB_SAFE_CALL1(PORT_Free_Util, ptr);
return free(ptr);
}
extern void *
PORT_ZAlloc_stub(size_t len)
{
STUB_SAFE_CALL1(PORT_ZAlloc_Util, len);
void *ptr = malloc(len);
if (ptr) {
memset(ptr, 0, len);
}
return ptr;
}
/* aligned_alloc is C11. This is an alternative to get aligned memory. */
extern void *
PORT_ZAllocAligned_stub(size_t bytes, size_t alignment, void **mem)
{
STUB_SAFE_CALL3(PORT_ZAllocAligned_Util, bytes, alignment, mem);
/* This only works if alignement is a power of 2. */
if ((alignment == 0) || (alignment & (alignment - 1))) {
return NULL;
}
size_t x = alignment - 1;
size_t len = (bytes ? bytes : 1) + x;
if (!mem) {
return NULL;
}
/* Always allocate a non-zero amount of bytes */
*mem = malloc(len);
if (!*mem) {
return NULL;
}
memset(*mem, 0, len);
/* We're pretty sure this is non-zero, but let's assure scan-build too. */
void *ret = (void *)(((uintptr_t)*mem + x) & ~(uintptr_t)x);
assert(ret);
return ret;
}
extern void *
PORT_ZAllocAlignedOffset_stub(size_t size, size_t alignment, size_t offset)
{
STUB_SAFE_CALL3(PORT_ZAllocAlignedOffset_Util, size, alignment, offset);
if (offset > size) {
return NULL;
}
void *mem = NULL;
void *v = PORT_ZAllocAligned_stub(size, alignment, &mem);
if (!v) {
return NULL;
}
*((void **)((uintptr_t)v + offset)) = mem;
return v;
}
extern void
PORT_ZFree_stub(void *ptr, size_t len)
{
STUB_SAFE_CALL2(PORT_ZFree_Util, ptr, len);
memset(ptr, 0, len);
return free(ptr);
}
extern void
PR_Free_stub(void *ptr)
{
STUB_SAFE_CALL1(PR_Free, ptr);
return free(ptr);
}
/*
* arenas
*
*/
extern PLArenaPool *
PORT_NewArena_stub(unsigned long chunksize)
{
STUB_SAFE_CALL1(PORT_NewArena_Util, chunksize);
abort();
return NULL;
}
extern void *
PORT_ArenaAlloc_stub(PLArenaPool *arena, size_t size)
{
STUB_SAFE_CALL2(PORT_ArenaZAlloc_Util, arena, size);
abort();
return NULL;
}
extern void *
PORT_ArenaZAlloc_stub(PLArenaPool *arena, size_t size)
{
STUB_SAFE_CALL2(PORT_ArenaZAlloc_Util, arena, size);
abort();
return NULL;
}
extern void
PORT_FreeArena_stub(PLArenaPool *arena, PRBool zero)
{
STUB_SAFE_CALL2(PORT_FreeArena_Util, arena, zero);
abort();
}
/* io */
extern PRFileDesc *
PR_Open_stub(const char *name, PRIntn flags, PRIntn mode)
{
int *lfd = NULL;
int fd;
int lflags = 0;
STUB_SAFE_CALL3(PR_Open, name, flags, mode);
if (flags & PR_RDWR) {
lflags = O_RDWR;
} else if (flags & PR_WRONLY) {
lflags = O_WRONLY;
} else {
lflags = O_RDONLY;
}
if (flags & PR_EXCL)
lflags |= O_EXCL;
if (flags & PR_APPEND)
lflags |= O_APPEND;
if (flags & PR_TRUNCATE)
lflags |= O_TRUNC;
fd = open(name, lflags, mode);
if (fd >= 0) {
lfd = PORT_New_stub(int);
if (lfd != NULL) {
*lfd = fd;
} else {
close(fd);
}
}
return (PRFileDesc *)lfd;
}
extern PRFileDesc *
PR_ImportPipe_stub(PROsfd fd)
{
int *lfd = NULL;
STUB_SAFE_CALL1(PR_ImportPipe, fd);
lfd = PORT_New_stub(int);
if (lfd != NULL) {
*lfd = fd;
}
return (PRFileDesc *)lfd;
}
extern PRStatus
PR_Close_stub(PRFileDesc *fd)
{
int *lfd;
STUB_SAFE_CALL1(PR_Close, fd);
lfd = (int *)fd;
close(*lfd);
PORT_Free_stub(lfd);
return PR_SUCCESS;
}
extern PRInt32
PR_Read_stub(PRFileDesc *fd, void *buf, PRInt32 amount)
{
int *lfd;
STUB_SAFE_CALL3(PR_Read, fd, buf, amount);
lfd = (int *)fd;
return read(*lfd, buf, amount);
}
extern PROffset32
PR_Seek_stub(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence)
{
int *lfd;
int lwhence = SEEK_SET;
STUB_SAFE_CALL3(PR_Seek, fd, offset, whence);
lfd = (int *)fd;
switch (whence) {
case PR_SEEK_CUR:
lwhence = SEEK_CUR;
break;
case PR_SEEK_END:
lwhence = SEEK_END;
break;
case PR_SEEK_SET:
break;
}
return lseek(*lfd, offset, lwhence);
}
PRStatus
PR_Access_stub(const char *name, PRAccessHow how)
{
int mode = F_OK;
int rv;
STUB_SAFE_CALL2(PR_Access, name, how);
switch (how) {
case PR_ACCESS_WRITE_OK:
mode = W_OK;
break;
case PR_ACCESS_READ_OK:
mode = R_OK;
break;
/* assume F_OK for all others */
default:
break;
}
rv = access(name, mode);
if (rv == 0) {
return PR_SUCCESS;
}
return PR_FAILURE;
}
/*
* library
*/
extern char *
PR_GetLibraryFilePathname_stub(const char *name, PRFuncPtr addr)
{
Dl_info dli;
char *result;
STUB_SAFE_CALL2(PR_GetLibraryFilePathname, name, addr);
if (dladdr((void *)addr, &dli) == 0) {
return NULL;
}
result = PORT_Alloc_stub(strlen(dli.dli_fname) + 1);
if (result != NULL) {
strcpy(result, dli.dli_fname);
}
return result;
}
#include <errno.h>
/* errors */
extern int
PORT_GetError_stub(void)
{
STUB_SAFE_CALL0(PORT_GetError_Util);
return errno;
}
extern void
PORT_SetError_stub(int value)
{
STUB_SAFE_CALL1(PORT_SetError_Util, value);
errno = value;
}
/* misc */
extern void
PR_Assert_stub(const char *s, const char *file, PRIntn ln)
{
STUB_SAFE_CALL3(PR_Assert, s, file, ln);
fprintf(stderr, "%s line %d: %s\n", file, ln, s);
abort();
}
/* time */
extern PRStatus
PR_Sleep_stub(PRIntervalTime ticks)
{
STUB_SAFE_CALL1(PR_Sleep, ticks);
usleep(ticks * 1000);
return PR_SUCCESS;
}
/* locking */
extern PRLock *
PR_NewLock_stub(void)
{
STUB_SAFE_CALL0(PR_NewLock);
abort();
return NULL;
}
extern PRStatus
PR_Unlock_stub(PRLock *lock)
{
STUB_SAFE_CALL1(PR_Unlock, lock);
abort();
return PR_FAILURE;
}
extern void
PR_Lock_stub(PRLock *lock)
{
STUB_SAFE_CALL1(PR_Lock, lock);
abort();
return;
}
extern void
PR_DestroyLock_stub(PRLock *lock)
{
STUB_SAFE_CALL1(PR_DestroyLock, lock);
abort();
return;
}
extern PRCondVar *
PR_NewCondVar_stub(PRLock *lock)
{
STUB_SAFE_CALL1(PR_NewCondVar, lock);
abort();
return NULL;
}
extern PRStatus
PR_NotifyCondVar_stub(PRCondVar *cvar)
{
STUB_SAFE_CALL1(PR_NotifyCondVar, cvar);
abort();
return PR_FAILURE;
}
extern PRStatus
PR_NotifyAllCondVar_stub(PRCondVar *cvar)
{
STUB_SAFE_CALL1(PR_NotifyAllCondVar, cvar);
abort();
return PR_FAILURE;
}
extern PRStatus
PR_WaitCondVar_stub(PRCondVar *cvar, PRIntervalTime timeout)
{
STUB_SAFE_CALL2(PR_WaitCondVar, cvar, timeout);
abort();
return PR_FAILURE;
}
extern char *
PR_GetEnvSecure_stub(const char *var)
{
STUB_SAFE_CALL1(PR_GetEnvSecure, var);
abort();
return NULL;
}
extern void
PR_DestroyCondVar_stub(PRCondVar *cvar)
{
STUB_SAFE_CALL1(PR_DestroyCondVar, cvar);
abort();
return;
}
/*
* NOTE: this presupposes GCC 4.1
*/
extern PRStatus
PR_CallOnce_stub(PRCallOnceType *once, PRCallOnceFN func)
{
STUB_SAFE_CALL2(PR_CallOnce, once, func);
abort();
return PR_FAILURE;
}
/*
* SECITEMS implement Item Utilities
*/
extern void
SECITEM_FreeItem_stub(SECItem *zap, PRBool freeit)
{
STUB_SAFE_CALL2(SECITEM_FreeItem_Util, zap, freeit);
abort();
}
extern SECItem *
SECITEM_AllocItem_stub(PLArenaPool *arena, SECItem *item, unsigned int len)
{
STUB_SAFE_CALL3(SECITEM_AllocItem_Util, arena, item, len);
abort();
return NULL;
}
extern SECComparison
SECITEM_CompareItem_stub(const SECItem *a, const SECItem *b)
{
STUB_SAFE_CALL2(SECITEM_CompareItem_Util, a, b);
abort();
return SECEqual;
}
extern SECStatus
SECITEM_CopyItem_stub(PLArenaPool *arena, SECItem *to, const SECItem *from)
{
STUB_SAFE_CALL3(SECITEM_CopyItem_Util, arena, to, from);
abort();
return SECFailure;
}
extern SECOidTag
SECOID_FindOIDTag_stub(const SECItem *oid)
{
STUB_SAFE_CALL1(SECOID_FindOIDTag_Util, oid);
abort();
return SEC_OID_UNKNOWN;
}
extern void
SECITEM_ZfreeItem_stub(SECItem *zap, PRBool freeit)
{
STUB_SAFE_CALL2(SECITEM_ZfreeItem_Util, zap, freeit);
abort();
}
extern int
NSS_SecureMemcmp_stub(const void *a, const void *b, size_t n)
{
STUB_SAFE_CALL3(NSS_SecureMemcmp, a, b, n);
abort();
}
extern unsigned int
NSS_SecureMemcmpZero_stub(const void *mem, size_t n)
{
STUB_SAFE_CALL2(NSS_SecureMemcmpZero, mem, n);
abort();
}
#ifdef FREEBL_NO_WEAK
static const char *nsprLibName = SHLIB_PREFIX "nspr4." SHLIB_SUFFIX;
static const char *nssutilLibName = SHLIB_PREFIX "nssutil3." SHLIB_SUFFIX;
static SECStatus
freebl_InitNSPR(void *lib)
{
STUB_FETCH_FUNCTION(PR_Free);
STUB_FETCH_FUNCTION(PR_Open);
STUB_FETCH_FUNCTION(PR_ImportPipe);
STUB_FETCH_FUNCTION(PR_Close);
STUB_FETCH_FUNCTION(PR_Read);
STUB_FETCH_FUNCTION(PR_Seek);
STUB_FETCH_FUNCTION(PR_GetLibraryFilePathname);
STUB_FETCH_FUNCTION(PR_Assert);
STUB_FETCH_FUNCTION(PR_Access);
STUB_FETCH_FUNCTION(PR_Sleep);
STUB_FETCH_FUNCTION(PR_CallOnce);
STUB_FETCH_FUNCTION(PR_NewCondVar);
STUB_FETCH_FUNCTION(PR_NotifyCondVar);
STUB_FETCH_FUNCTION(PR_NotifyAllCondVar);
STUB_FETCH_FUNCTION(PR_WaitCondVar);
STUB_FETCH_FUNCTION(PR_DestroyCondVar);
STUB_FETCH_FUNCTION(PR_NewLock);
STUB_FETCH_FUNCTION(PR_Unlock);
STUB_FETCH_FUNCTION(PR_Lock);
STUB_FETCH_FUNCTION(PR_DestroyLock);
STUB_FETCH_FUNCTION(PR_GetEnvSecure);
return SECSuccess;
}
static SECStatus
freebl_InitNSSUtil(void *lib)
{
STUB_FETCH_FUNCTION(PORT_Alloc_Util);
STUB_FETCH_FUNCTION(PORT_Free_Util);
STUB_FETCH_FUNCTION(PORT_ZAlloc_Util);
STUB_FETCH_FUNCTION(PORT_ZFree_Util);
STUB_FETCH_FUNCTION(PORT_NewArena_Util);
STUB_FETCH_FUNCTION(PORT_ArenaAlloc_Util);
STUB_FETCH_FUNCTION(PORT_ArenaZAlloc_Util);
STUB_FETCH_FUNCTION(PORT_FreeArena_Util);
STUB_FETCH_FUNCTION(PORT_GetError_Util);
STUB_FETCH_FUNCTION(PORT_SetError_Util);
STUB_FETCH_FUNCTION(SECITEM_FreeItem_Util);
STUB_FETCH_FUNCTION(SECITEM_AllocItem_Util);
STUB_FETCH_FUNCTION(SECITEM_CompareItem_Util);
STUB_FETCH_FUNCTION(SECITEM_CopyItem_Util);
STUB_FETCH_FUNCTION(SECITEM_ZfreeItem_Util);
STUB_FETCH_FUNCTION(SECOID_FindOIDTag_Util);
STUB_FETCH_FUNCTION(NSS_SecureMemcmp);
STUB_FETCH_FUNCTION(NSS_SecureMemcmpZero);
return SECSuccess;
}
/*
* fetch the library if it's loaded. For NSS it should already be loaded
*/
#define freebl_getLibrary(libName) \
dlopen(libName, RTLD_LAZY | RTLD_NOLOAD)
#define freebl_releaseLibrary(lib) \
if (lib) \
dlclose(lib)
static void *FREEBLnsprGlobalLib = NULL;
static void *FREEBLnssutilGlobalLib = NULL;
void __attribute((destructor)) FREEBL_unload()
{
freebl_releaseLibrary(FREEBLnsprGlobalLib);
freebl_releaseLibrary(FREEBLnssutilGlobalLib);
}
#endif
/*
* load the symbols from the real libraries if available.
*
* if force is set, explicitly load the libraries if they are not already
* loaded. If we could not use the real libraries, return failure.
*/
extern SECStatus
FREEBL_InitStubs()
{
SECStatus rv = SECSuccess;
#ifdef FREEBL_NO_WEAK
void *nspr = NULL;
void *nssutil = NULL;
/* NSPR should be first */
if (!FREEBLnsprGlobalLib) {
nspr = freebl_getLibrary(nsprLibName);
if (!nspr) {
return SECFailure;
}
rv = freebl_InitNSPR(nspr);
if (rv != SECSuccess) {
freebl_releaseLibrary(nspr);
return rv;
}
FREEBLnsprGlobalLib = nspr; /* adopt */
}
/* now load NSSUTIL */
if (!FREEBLnssutilGlobalLib) {
nssutil = freebl_getLibrary(nssutilLibName);
if (!nssutil) {
return SECFailure;
}
rv = freebl_InitNSSUtil(nssutil);
if (rv != SECSuccess) {
freebl_releaseLibrary(nssutil);
return rv;
}
FREEBLnssutilGlobalLib = nssutil; /* adopt */
}
#endif
return rv;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package expfmt
import (
"fmt"
"io"
"math"
"strings"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
)
// MetricFamilyToText converts a MetricFamily proto message into text format and
// writes the resulting lines to 'out'. It returns the number of bytes written
// and any error encountered. The output will have the same order as the input,
// no further sorting is performed. Furthermore, this function assumes the input
// is already sanitized and does not perform any sanity checks. If the input
// contains duplicate metrics or invalid metric or label names, the conversion
// will result in invalid text format output.
//
// This method fulfills the type 'prometheus.encoder'.
func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
var written int
// Fail-fast checks.
if len(in.Metric) == 0 {
return written, fmt.Errorf("MetricFamily has no metrics: %s", in)
}
name := in.GetName()
if name == "" {
return written, fmt.Errorf("MetricFamily has no name: %s", in)
}
// Comments, first HELP, then TYPE.
if in.Help != nil {
n, err := fmt.Fprintf(
out, "# HELP %s %s\n",
name, escapeString(*in.Help, false),
)
written += n
if err != nil {
return written, err
}
}
metricType := in.GetType()
n, err := fmt.Fprintf(
out, "# TYPE %s %s\n",
name, strings.ToLower(metricType.String()),
)
written += n
if err != nil {
return written, err
}
// Finally the samples, one line for each.
for _, metric := range in.Metric {
switch metricType {
case dto.MetricType_COUNTER:
if metric.Counter == nil {
return written, fmt.Errorf(
"expected counter in metric %s %s", name, metric,
)
}
n, err = writeSample(
name, metric, "", "",
metric.Counter.GetValue(),
out,
)
case dto.MetricType_GAUGE:
if metric.Gauge == nil {
return written, fmt.Errorf(
"expected gauge in metric %s %s", name, metric,
)
}
n, err = writeSample(
name, metric, "", "",
metric.Gauge.GetValue(),
out,
)
case dto.MetricType_UNTYPED:
if metric.Untyped == nil {
return written, fmt.Errorf(
"expected untyped in metric %s %s", name, metric,
)
}
n, err = writeSample(
name, metric, "", "",
metric.Untyped.GetValue(),
out,
)
case dto.MetricType_SUMMARY:
if metric.Summary == nil {
return written, fmt.Errorf(
"expected summary in metric %s %s", name, metric,
)
}
for _, q := range metric.Summary.Quantile {
n, err = writeSample(
name, metric,
model.QuantileLabel, fmt.Sprint(q.GetQuantile()),
q.GetValue(),
out,
)
written += n
if err != nil {
return written, err
}
}
n, err = writeSample(
name+"_sum", metric, "", "",
metric.Summary.GetSampleSum(),
out,
)
if err != nil {
return written, err
}
written += n
n, err = writeSample(
name+"_count", metric, "", "",
float64(metric.Summary.GetSampleCount()),
out,
)
case dto.MetricType_HISTOGRAM:
if metric.Histogram == nil {
return written, fmt.Errorf(
"expected histogram in metric %s %s", name, metric,
)
}
infSeen := false
for _, q := range metric.Histogram.Bucket {
n, err = writeSample(
name+"_bucket", metric,
model.BucketLabel, fmt.Sprint(q.GetUpperBound()),
float64(q.GetCumulativeCount()),
out,
)
written += n
if err != nil {
return written, err
}
if math.IsInf(q.GetUpperBound(), +1) {
infSeen = true
}
}
if !infSeen {
n, err = writeSample(
name+"_bucket", metric,
model.BucketLabel, "+Inf",
float64(metric.Histogram.GetSampleCount()),
out,
)
if err != nil {
return written, err
}
written += n
}
n, err = writeSample(
name+"_sum", metric, "", "",
metric.Histogram.GetSampleSum(),
out,
)
if err != nil {
return written, err
}
written += n
n, err = writeSample(
name+"_count", metric, "", "",
float64(metric.Histogram.GetSampleCount()),
out,
)
default:
return written, fmt.Errorf(
"unexpected type in metric %s %s", name, metric,
)
}
written += n
if err != nil {
return written, err
}
}
return written, nil
}
// writeSample writes a single sample in text format to out, given the metric
// name, the metric proto message itself, optionally an additional label name
// and value (use empty strings if not required), and the value. The function
// returns the number of bytes written and any error encountered.
func writeSample(
name string,
metric *dto.Metric,
additionalLabelName, additionalLabelValue string,
value float64,
out io.Writer,
) (int, error) {
var written int
n, err := fmt.Fprint(out, name)
written += n
if err != nil {
return written, err
}
n, err = labelPairsToText(
metric.Label,
additionalLabelName, additionalLabelValue,
out,
)
written += n
if err != nil {
return written, err
}
n, err = fmt.Fprintf(out, " %v", value)
written += n
if err != nil {
return written, err
}
if metric.TimestampMs != nil {
n, err = fmt.Fprintf(out, " %v", *metric.TimestampMs)
written += n
if err != nil {
return written, err
}
}
n, err = out.Write([]byte{'\n'})
written += n
if err != nil {
return written, err
}
return written, nil
}
// labelPairsToText converts a slice of LabelPair proto messages plus the
// explicitly given additional label pair into text formatted as required by the
// text format and writes it to 'out'. An empty slice in combination with an
// empty string 'additionalLabelName' results in nothing being
// written. Otherwise, the label pairs are written, escaped as required by the
// text format, and enclosed in '{...}'. The function returns the number of
// bytes written and any error encountered.
func labelPairsToText(
in []*dto.LabelPair,
additionalLabelName, additionalLabelValue string,
out io.Writer,
) (int, error) {
if len(in) == 0 && additionalLabelName == "" {
return 0, nil
}
var written int
separator := '{'
for _, lp := range in {
n, err := fmt.Fprintf(
out, `%c%s="%s"`,
separator, lp.GetName(), escapeString(lp.GetValue(), true),
)
written += n
if err != nil {
return written, err
}
separator = ','
}
if additionalLabelName != "" {
n, err := fmt.Fprintf(
out, `%c%s="%s"`,
separator, additionalLabelName,
escapeString(additionalLabelValue, true),
)
written += n
if err != nil {
return written, err
}
}
n, err := out.Write([]byte{'}'})
written += n
if err != nil {
return written, err
}
return written, nil
}
var (
escape = strings.NewReplacer("\\", `\\`, "\n", `\n`)
escapeWithDoubleQuote = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
)
// escapeString replaces '\' by '\\', new line character by '\n', and - if
// includeDoubleQuote is true - '"' by '\"'.
func escapeString(v string, includeDoubleQuote bool) string {
if includeDoubleQuote {
return escapeWithDoubleQuote.Replace(v)
}
return escape.Replace(v)
}
| {
"pile_set_name": "Github"
} |
/**
* \file psa_util.h
*
* \brief Utility functions for the use of the PSA Crypto library.
*
* \warning This function is not part of the public API and may
* change at any time.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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 MBEDTLS_PSA_UTIL_H
#define MBEDTLS_PSA_UTIL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#include "psa/crypto.h"
#include "mbedtls/ecp.h"
#include "mbedtls/md.h"
#include "mbedtls/pk.h"
#include "mbedtls/oid.h"
#include <string.h>
/* Translations for symmetric crypto. */
static inline psa_key_type_t mbedtls_psa_translate_cipher_type(
mbedtls_cipher_type_t cipher )
{
switch( cipher )
{
case MBEDTLS_CIPHER_AES_128_CCM:
case MBEDTLS_CIPHER_AES_192_CCM:
case MBEDTLS_CIPHER_AES_256_CCM:
case MBEDTLS_CIPHER_AES_128_GCM:
case MBEDTLS_CIPHER_AES_192_GCM:
case MBEDTLS_CIPHER_AES_256_GCM:
case MBEDTLS_CIPHER_AES_128_CBC:
case MBEDTLS_CIPHER_AES_192_CBC:
case MBEDTLS_CIPHER_AES_256_CBC:
return( PSA_KEY_TYPE_AES );
/* ARIA not yet supported in PSA. */
/* case MBEDTLS_CIPHER_ARIA_128_CCM:
case MBEDTLS_CIPHER_ARIA_192_CCM:
case MBEDTLS_CIPHER_ARIA_256_CCM:
case MBEDTLS_CIPHER_ARIA_128_GCM:
case MBEDTLS_CIPHER_ARIA_192_GCM:
case MBEDTLS_CIPHER_ARIA_256_GCM:
case MBEDTLS_CIPHER_ARIA_128_CBC:
case MBEDTLS_CIPHER_ARIA_192_CBC:
case MBEDTLS_CIPHER_ARIA_256_CBC:
return( PSA_KEY_TYPE_ARIA ); */
default:
return( 0 );
}
}
static inline psa_algorithm_t mbedtls_psa_translate_cipher_mode(
mbedtls_cipher_mode_t mode, size_t taglen )
{
switch( mode )
{
case MBEDTLS_MODE_GCM:
return( PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, taglen ) );
case MBEDTLS_MODE_CCM:
return( PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, taglen ) );
case MBEDTLS_MODE_CBC:
if( taglen == 0 )
return( PSA_ALG_CBC_NO_PADDING );
/* Intentional fallthrough for taglen != 0 */
/* fallthrough */
default:
return( 0 );
}
}
static inline psa_key_usage_t mbedtls_psa_translate_cipher_operation(
mbedtls_operation_t op )
{
switch( op )
{
case MBEDTLS_ENCRYPT:
return( PSA_KEY_USAGE_ENCRYPT );
case MBEDTLS_DECRYPT:
return( PSA_KEY_USAGE_DECRYPT );
default:
return( 0 );
}
}
/* Translations for hashing. */
static inline psa_algorithm_t mbedtls_psa_translate_md( mbedtls_md_type_t md_alg )
{
switch( md_alg )
{
#if defined(MBEDTLS_MD2_C)
case MBEDTLS_MD_MD2:
return( PSA_ALG_MD2 );
#endif
#if defined(MBEDTLS_MD4_C)
case MBEDTLS_MD_MD4:
return( PSA_ALG_MD4 );
#endif
#if defined(MBEDTLS_MD5_C)
case MBEDTLS_MD_MD5:
return( PSA_ALG_MD5 );
#endif
#if defined(MBEDTLS_SHA1_C)
case MBEDTLS_MD_SHA1:
return( PSA_ALG_SHA_1 );
#endif
#if defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_SHA224:
return( PSA_ALG_SHA_224 );
case MBEDTLS_MD_SHA256:
return( PSA_ALG_SHA_256 );
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA384:
return( PSA_ALG_SHA_384 );
case MBEDTLS_MD_SHA512:
return( PSA_ALG_SHA_512 );
#endif
#if defined(MBEDTLS_RIPEMD160_C)
case MBEDTLS_MD_RIPEMD160:
return( PSA_ALG_RIPEMD160 );
#endif
case MBEDTLS_MD_NONE: /* Intentional fallthrough */
default:
return( 0 );
}
}
/* Translations for ECC. */
static inline int mbedtls_psa_get_ecc_oid_from_id(
psa_ecc_family_t curve, size_t bits,
char const **oid, size_t *oid_len )
{
switch( curve )
{
case PSA_ECC_FAMILY_SECP_R1:
switch( bits )
{
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
case 192:
*oid = MBEDTLS_OID_EC_GRP_SECP192R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP192R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
case 224:
*oid = MBEDTLS_OID_EC_GRP_SECP224R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP224R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
case 256:
*oid = MBEDTLS_OID_EC_GRP_SECP256R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP256R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
case 384:
*oid = MBEDTLS_OID_EC_GRP_SECP384R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP384R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
case 521:
*oid = MBEDTLS_OID_EC_GRP_SECP521R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP521R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */
}
break;
case PSA_ECC_FAMILY_SECP_K1:
switch( bits )
{
#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
case 192:
*oid = MBEDTLS_OID_EC_GRP_SECP192K1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP192K1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
case 224:
*oid = MBEDTLS_OID_EC_GRP_SECP224K1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP224K1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
case 256:
*oid = MBEDTLS_OID_EC_GRP_SECP256K1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP256K1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */
}
break;
case PSA_ECC_FAMILY_BRAINPOOL_P_R1:
switch( bits )
{
#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
case 256:
*oid = MBEDTLS_OID_EC_GRP_BP256R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP256R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
case 384:
*oid = MBEDTLS_OID_EC_GRP_BP384R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP384R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
case 512:
*oid = MBEDTLS_OID_EC_GRP_BP512R1;
*oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP512R1 );
return( 0 );
#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */
}
break;
}
(void) oid;
(void) oid_len;
return( -1 );
}
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH 1
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 192 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 192 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 224 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 224 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 256 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 256 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 384 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 384 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 521 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 521 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 192 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 192 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 224 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 224 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 256 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 256 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 256 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 256 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 384 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 384 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */
#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
#if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 512 + 7 ) / 8 ) + 1 )
#undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH
#define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 512 + 7 ) / 8 ) + 1 )
#endif
#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */
/* Translations for PK layer */
static inline int mbedtls_psa_err_translate_pk( psa_status_t status )
{
switch( status )
{
case PSA_SUCCESS:
return( 0 );
case PSA_ERROR_NOT_SUPPORTED:
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
case PSA_ERROR_INSUFFICIENT_MEMORY:
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
case PSA_ERROR_INSUFFICIENT_ENTROPY:
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
case PSA_ERROR_BAD_STATE:
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
/* All other failures */
case PSA_ERROR_COMMUNICATION_FAILURE:
case PSA_ERROR_HARDWARE_FAILURE:
case PSA_ERROR_CORRUPTION_DETECTED:
return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
default: /* We return the same as for the 'other failures',
* but list them separately nonetheless to indicate
* which failure conditions we have considered. */
return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
}
}
/* Translations for ECC */
/* This function transforms an ECC group identifier from
* https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8
* into a PSA ECC group identifier. */
#if defined(MBEDTLS_ECP_C)
static inline psa_key_type_t mbedtls_psa_parse_tls_ecc_group(
uint16_t tls_ecc_grp_reg_id, size_t *bits )
{
const mbedtls_ecp_curve_info *curve_info =
mbedtls_ecp_curve_info_from_tls_id( tls_ecc_grp_reg_id );
if( curve_info == NULL )
return( 0 );
return( PSA_KEY_TYPE_ECC_KEY_PAIR(
mbedtls_ecc_group_to_psa( curve_info->grp_id, bits ) ) );
}
#endif /* MBEDTLS_ECP_C */
/* This function takes a buffer holding an EC public key
* exported through psa_export_public_key(), and converts
* it into an ECPoint structure to be put into a ClientKeyExchange
* message in an ECDHE exchange.
*
* Both the present and the foreseeable future format of EC public keys
* used by PSA have the ECPoint structure contained in the exported key
* as a subbuffer, and the function merely selects this subbuffer instead
* of making a copy.
*/
static inline int mbedtls_psa_tls_psa_ec_to_ecpoint( unsigned char *src,
size_t srclen,
unsigned char **dst,
size_t *dstlen )
{
*dst = src;
*dstlen = srclen;
return( 0 );
}
/* This function takes a buffer holding an ECPoint structure
* (as contained in a TLS ServerKeyExchange message for ECDHE
* exchanges) and converts it into a format that the PSA key
* agreement API understands.
*/
static inline int mbedtls_psa_tls_ecpoint_to_psa_ec( unsigned char const *src,
size_t srclen,
unsigned char *dst,
size_t dstlen,
size_t *olen )
{
if( srclen > dstlen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
memcpy( dst, src, srclen );
*olen = srclen;
return( 0 );
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#endif /* MBEDTLS_PSA_UTIL_H */
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_search_white_24dp"
android:title="@string/search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="always" />
</menu> | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <Automator/_AMSystemEventsUIElement.h>
@interface _AMSystemEventsTable : _AMSystemEventsUIElement
{
}
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="debug_shared|x64">
<Configuration>debug_shared</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="debug_static_md|x64">
<Configuration>debug_static_md</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="debug_static_mt|x64">
<Configuration>debug_static_mt</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_shared|x64">
<Configuration>release_shared</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_static_md|x64">
<Configuration>release_static_md</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_static_mt|x64">
<Configuration>release_static_mt</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>base64decode</ProjectName>
<ProjectGuid>{A1623462-1A5C-3CC2-8DCB-7E85D4EA56E8}</ProjectGuid>
<RootNamespace>base64decode</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props"/>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props"/>
<ImportGroup Label="ExtensionSettings"/>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<PropertyGroup Label="UserMacros"/>
<PropertyGroup>
<_ProjectFileVersion>14.0.23107.0</_ProjectFileVersion>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'">base64decoded</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'">base64decoded</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'">base64decoded</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'">base64decode</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'">base64decode</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'">base64decode</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'">
<OutDir>bin64\</OutDir>
<IntDir>obj64\base64decode\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'">
<OutDir>bin64\</OutDir>
<IntDir>obj64\base64decode\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'">
<OutDir>bin64\static_mt\</OutDir>
<IntDir>obj64\base64decode\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'">
<OutDir>bin64\static_mt\</OutDir>
<IntDir>obj64\base64decode\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'">
<OutDir>bin64\static_md\</OutDir>
<IntDir>obj64\base64decode\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'">
<OutDir>bin64\static_md\</OutDir>
<IntDir>obj64\base64decode\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\base64decoded.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin64\base64decoded.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\base64decode.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_mt\base64decoded.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin64\static_mt\base64decoded.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_mt\base64decode.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_md\base64decoded.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin64\static_md\base64decoded.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;ws2_32.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_md\base64decode.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\base64decode.cpp"/>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets"/>
<ImportGroup Label="ExtensionTargets"/>
</Project>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/jael.iml" filepath="$PROJECT_DIR$/jael.iml" />
</modules>
</component>
</project> | {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/admissionregistration/v1beta1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
type AdmissionregistrationV1beta1Interface interface {
RESTClient() rest.Interface
MutatingWebhookConfigurationsGetter
ValidatingWebhookConfigurationsGetter
}
// AdmissionregistrationV1beta1Client is used to interact with features provided by the admissionregistration.k8s.io group.
type AdmissionregistrationV1beta1Client struct {
restClient rest.Interface
}
func (c *AdmissionregistrationV1beta1Client) MutatingWebhookConfigurations() MutatingWebhookConfigurationInterface {
return newMutatingWebhookConfigurations(c)
}
func (c *AdmissionregistrationV1beta1Client) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInterface {
return newValidatingWebhookConfigurations(c)
}
// NewForConfig creates a new AdmissionregistrationV1beta1Client for the given config.
func NewForConfig(c *rest.Config) (*AdmissionregistrationV1beta1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &AdmissionregistrationV1beta1Client{client}, nil
}
// NewForConfigOrDie creates a new AdmissionregistrationV1beta1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *AdmissionregistrationV1beta1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new AdmissionregistrationV1beta1Client for the given RESTClient.
func New(c rest.Interface) *AdmissionregistrationV1beta1Client {
return &AdmissionregistrationV1beta1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1beta1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *AdmissionregistrationV1beta1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
| {
"pile_set_name": "Github"
} |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-358.js
* @description ES5 Attributes - success to update [[Enumerable]] attribute of data property ([[Writable]] is false, [[Enumerable]] is true, [[Configurable]] is true) to different value
*/
function testcase() {
var obj = {};
Object.defineProperty(obj, "prop", {
value: 2010,
writable: false,
enumerable: true,
configurable: true
});
var propertyDefineCorrect = obj.hasOwnProperty("prop");
var desc1 = Object.getOwnPropertyDescriptor(obj, "prop");
Object.defineProperty(obj, "prop", {
enumerable: false
});
var desc2 = Object.getOwnPropertyDescriptor(obj, "prop");
return propertyDefineCorrect && desc1.enumerable === true && obj.prop === 2010 && desc2.enumerable === false;
}
runTestCase(testcase);
| {
"pile_set_name": "Github"
} |
#if wxOSX_USE_CARBON
#include "wx/osx/carbon/uma.h"
#endif
| {
"pile_set_name": "Github"
} |
int bad_guy(int * i)
{
*i = 9;
return *i;
}
void bad_guy_test()
{
int * ptr = 0;
bad_guy(ptr);
}
| {
"pile_set_name": "Github"
} |
raise NotImplementedError("symtable is not yet implemented in Skulpt")
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
abstract class AbstractBinary extends AbstractExpression
{
public function __construct(\Twig_NodeInterface $left, \Twig_NodeInterface $right, $lineno)
{
parent::__construct(['left' => $left, 'right' => $right], [], $lineno);
}
public function compile(Compiler $compiler)
{
$compiler
->raw('(')
->subcompile($this->getNode('left'))
->raw(' ')
;
$this->operator($compiler);
$compiler
->raw(' ')
->subcompile($this->getNode('right'))
->raw(')')
;
}
abstract public function operator(Compiler $compiler);
}
class_alias('Twig\Node\Expression\Binary\AbstractBinary', 'Twig_Node_Expression_Binary');
| {
"pile_set_name": "Github"
} |
Transaction pool primitives types & Runtime API.
License: Apache-2.0 | {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
"""Caliopen User tag parameters classes."""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import types
import uuid
from caliopen_main.user.parameters.settings import Settings as SettingsParam
from caliopen_main.user.store import Settings as ModelSettings
from caliopen_main.common.objects.base import ObjectUser
log = logging.getLogger(__name__)
class Settings(ObjectUser):
"""Settings related to an user."""
_attrs = {
'user_id': uuid.UUID,
'default_locale': types.StringType,
'message_display_format': types.StringType,
'contact_display_order': types.StringType,
'contact_display_format': types.StringType,
'notification_enabled': types.BooleanType,
'notification_message_preview': types.StringType,
'notification_sound_enabled': types.BooleanType,
'notification_delay_disappear': types.IntType,
}
_model_class = ModelSettings
_pkey_name = None
_json_model = SettingsParam
| {
"pile_set_name": "Github"
} |
//-----------------------------------------------------------------------
// <copyright file="EventBusSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Akka.Actor;
using Akka.Event;
using Akka.TestKit;
using Xunit;
namespace Akka.Tests.Event
{
/// <summary>
/// I used <see cref="TestActorEventBus"/> for both specs, since ActorEventBus and EventBus
/// are even to each other at the time, spec is written.
/// </summary>
internal class TestActorEventBus : ActorEventBus<object, Type>
{
protected override bool IsSubClassification(Type parent, Type child)
{
return child.IsAssignableFrom(parent);
}
protected override void Publish(object evt, IActorRef subscriber)
{
subscriber.Tell(evt);
}
protected override bool Classify(object evt, Type classifier)
{
return evt.GetType().IsAssignableFrom(classifier);
}
protected override Type GetClassifier(object @event)
{
return @event.GetType();
}
}
internal class TestActorWrapperActor : ActorBase
{
private readonly IActorRef _ref;
public TestActorWrapperActor(IActorRef actorRef)
{
_ref = actorRef;
}
protected override bool Receive(object message)
{
_ref.Forward(message);
return true;
}
}
internal struct Notification
{
public Notification(IActorRef @ref, int payload) : this()
{
Ref = @ref;
Payload = payload;
}
public IActorRef Ref { get; set; }
public int Payload { get; set; }
}
public class EventBusSpec : AkkaSpec
{
internal ActorEventBus<object, Type> _bus;
protected object _evt;
protected Type _classifier;
protected IActorRef _subscriber;
public EventBusSpec()
{
_bus = new TestActorEventBus();
_evt = new Notification(TestActor, 1);
_classifier = typeof (Notification);
_subscriber = TestActor;
}
[Fact]
public void EventBus_allow_subscribers()
{
_bus.Subscribe(_subscriber, _classifier).ShouldBe(true);
}
[Fact]
public void EventBus_allow_to_unsubscribe_already_existing_subscribers()
{
_bus.Subscribe(_subscriber, _classifier).ShouldBe(true);
_bus.Unsubscribe(_subscriber, _classifier).ShouldBe(true);
}
[Fact]
public void EventBus_not_allow_to_unsubscribe_not_existing_subscribers()
{
_bus.Unsubscribe(_subscriber, _classifier).ShouldBe(false);
}
[Fact]
public void EventBus_not_allow_to_subscribe_same_subscriber_to_same_channel_twice()
{
_bus.Subscribe(_subscriber, _classifier).ShouldBe(true);
_bus.Subscribe(_subscriber, _classifier).ShouldBe(false);
_bus.Unsubscribe(_subscriber, _classifier).ShouldBe(true);
}
[Fact]
public void EventBus_not_allow_to_unsubscribe_same_subscriber_from_the_same_channel_twice()
{
_bus.Subscribe(_subscriber, _classifier).ShouldBe(true);
_bus.Unsubscribe(_subscriber, _classifier).ShouldBe(true);
_bus.Unsubscribe(_subscriber, _classifier).ShouldBe(false);
}
[Fact]
public void EventBus_allow_to_add_multiple_subscribers()
{
const int max = 10;
IEnumerable<IActorRef> subscribers = Enumerable.Range(0, max).Select(_ => CreateSubscriber(TestActor)).ToList();
foreach (var subscriber in subscribers)
{
_bus.Subscribe(subscriber, _classifier).ShouldBe(true);
}
foreach (var subscriber in subscribers)
{
_bus.Unsubscribe(subscriber, _classifier).ShouldBe(true);
DisposeSubscriber(subscriber);
}
}
[Fact]
public void EventBus_allow_publishing_with_empty_subscribers_list()
{
_bus.Publish(new object());
}
[Fact]
public void EventBus_publish_to_the_only_subscriber()
{
_bus.Subscribe(_subscriber, _classifier);
_bus.Publish(_evt);
ExpectMsg(_evt);
ExpectNoMsg(TimeSpan.FromSeconds(1));
_bus.Unsubscribe(_subscriber);
}
[Fact]
public void EventBus_publish_to_the_only_subscriber_multiple_times()
{
_bus.Subscribe(_subscriber, _classifier);
_bus.Publish(_evt);
_bus.Publish(_evt);
_bus.Publish(_evt);
ExpectMsg(_evt);
ExpectMsg(_evt);
ExpectMsg(_evt);
ExpectNoMsg(TimeSpan.FromSeconds(1));
_bus.Unsubscribe(_subscriber, _classifier);
}
[Fact]
public void EventBus_not_publish_event_to_unindented_subscribers()
{
var otherSubscriber = CreateSubscriber(TestActor);
var otherClassifier = typeof (int);
_bus.Subscribe(_subscriber, _classifier);
_bus.Subscribe(otherSubscriber, otherClassifier);
_bus.Publish(_evt);
ExpectMsg(_evt);
_bus.Unsubscribe(_subscriber, _classifier);
_bus.Unsubscribe(otherSubscriber, otherClassifier);
ExpectNoMsg(TimeSpan.FromSeconds(1));
}
[Fact]
public void EventBus_not_publish_event_to_former_subscriber()
{
_bus.Subscribe(_subscriber, _classifier);
_bus.Unsubscribe(_subscriber, _classifier);
_bus.Publish(_evt);
ExpectNoMsg(TimeSpan.FromSeconds(1));
}
[Fact]
public void EventBus_cleanup_subscribers()
{
DisposeSubscriber(_subscriber);
}
protected IActorRef CreateSubscriber(IActorRef actor)
{
return Sys.ActorOf(Props.Create(() => new TestActorWrapperActor(actor)));
}
protected void DisposeSubscriber(IActorRef subscriber)
{
Sys.Stop(subscriber);
}
}
}
| {
"pile_set_name": "Github"
} |
exec_program
------------
.. deprecated:: 3.0
Use the :command:`execute_process` command instead.
Run an executable program during the processing of the CMakeList.txt
file.
::
exec_program(Executable [directory in which to run]
[ARGS <arguments to executable>]
[OUTPUT_VARIABLE <var>]
[RETURN_VALUE <var>])
The executable is run in the optionally specified directory. The
executable can include arguments if it is double quoted, but it is
better to use the optional ``ARGS`` argument to specify arguments to the
program. This is because cmake will then be able to escape spaces in
the executable path. An optional argument ``OUTPUT_VARIABLE`` specifies a
variable in which to store the output. To capture the return value of
the execution, provide a ``RETURN_VALUE``. If ``OUTPUT_VARIABLE`` is
specified, then no output will go to the stdout/stderr of the console
running cmake.
| {
"pile_set_name": "Github"
} |
import * as React from 'react';
import {StatefulSlider} from 'baseui/slider';
export default () => <StatefulSlider />;
| {
"pile_set_name": "Github"
} |
/*
FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
This file is part of the FreeRTOS distribution.
FreeRTOS 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 >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
***************************************************************************
>>! NOTE: The modification to the GPL is included to allow you to !<<
>>! distribute a combined work that includes FreeRTOS without being !<<
>>! obliged to provide the source code for proprietary components !<<
>>! outside of the FreeRTOS kernel. !<<
***************************************************************************
FreeRTOS 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. Full license text is available on the following
link: http://www.freertos.org/a00114.html
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that is more than just the market leader, it *
* is the industry's de facto standard. *
* *
* Help yourself get started quickly while simultaneously helping *
* to support the FreeRTOS project by purchasing a FreeRTOS *
* tutorial book, reference manual, or both: *
* http://www.FreeRTOS.org/Documentation *
* *
***************************************************************************
http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
the FAQ page "My application does not run, what could be wrong?". Have you
defined configASSERT()?
http://www.FreeRTOS.org/support - In return for receiving this top quality
embedded software for free we request you assist our global community by
participating in the support forum.
http://www.FreeRTOS.org/training - Investing in training allows your team to
be as productive as possible as early as possible. Now you can receive
FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
Ltd, and the world's leading authority on the world's leading RTOS.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and commercial middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
#ifndef CO_ROUTINE_H
#define CO_ROUTINE_H
#ifndef INC_FREERTOS_H
#error "include FreeRTOS.h must appear in source files before include croutine.h"
#endif
#include "list.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Used to hide the implementation of the co-routine control block. The
control block structure however has to be included in the header due to
the macro implementation of the co-routine functionality. */
typedef void * CoRoutineHandle_t;
/* Defines the prototype to which co-routine functions must conform. */
typedef void (*crCOROUTINE_CODE)( CoRoutineHandle_t, UBaseType_t );
typedef struct corCoRoutineControlBlock
{
crCOROUTINE_CODE pxCoRoutineFunction;
ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */
ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */
UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */
UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */
uint16_t uxState; /*< Used internally by the co-routine implementation. */
} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */
/**
* croutine. h
*<pre>
BaseType_t xCoRoutineCreate(
crCOROUTINE_CODE pxCoRoutineCode,
UBaseType_t uxPriority,
UBaseType_t uxIndex
);</pre>
*
* Create a new co-routine and add it to the list of co-routines that are
* ready to run.
*
* @param pxCoRoutineCode Pointer to the co-routine function. Co-routine
* functions require special syntax - see the co-routine section of the WEB
* documentation for more information.
*
* @param uxPriority The priority with respect to other co-routines at which
* the co-routine will run.
*
* @param uxIndex Used to distinguish between different co-routines that
* execute the same function. See the example below and the co-routine section
* of the WEB documentation for further information.
*
* @return pdPASS if the co-routine was successfully created and added to a ready
* list, otherwise an error code defined with ProjDefs.h.
*
* Example usage:
<pre>
// Co-routine to be created.
void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
// Variables in co-routines must be declared static if they must maintain value across a blocking call.
// This may not be necessary for const variables.
static const char cLedToFlash[ 2 ] = { 5, 6 };
static const TickType_t uxFlashRates[ 2 ] = { 200, 400 };
// Must start every co-routine with a call to crSTART();
crSTART( xHandle );
for( ;; )
{
// This co-routine just delays for a fixed period, then toggles
// an LED. Two co-routines are created using this function, so
// the uxIndex parameter is used to tell the co-routine which
// LED to flash and how int32_t to delay. This assumes xQueue has
// already been created.
vParTestToggleLED( cLedToFlash[ uxIndex ] );
crDELAY( xHandle, uxFlashRates[ uxIndex ] );
}
// Must end every co-routine with a call to crEND();
crEND();
}
// Function that creates two co-routines.
void vOtherFunction( void )
{
uint8_t ucParameterToPass;
TaskHandle_t xHandle;
// Create two co-routines at priority 0. The first is given index 0
// so (from the code above) toggles LED 5 every 200 ticks. The second
// is given index 1 so toggles LED 6 every 400 ticks.
for( uxIndex = 0; uxIndex < 2; uxIndex++ )
{
xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );
}
}
</pre>
* \defgroup xCoRoutineCreate xCoRoutineCreate
* \ingroup Tasks
*/
BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex );
/**
* croutine. h
*<pre>
void vCoRoutineSchedule( void );</pre>
*
* Run a co-routine.
*
* vCoRoutineSchedule() executes the highest priority co-routine that is able
* to run. The co-routine will execute until it either blocks, yields or is
* preempted by a task. Co-routines execute cooperatively so one
* co-routine cannot be preempted by another, but can be preempted by a task.
*
* If an application comprises of both tasks and co-routines then
* vCoRoutineSchedule should be called from the idle task (in an idle task
* hook).
*
* Example usage:
<pre>
// This idle task hook will schedule a co-routine each time it is called.
// The rest of the idle task will execute between co-routine calls.
void vApplicationIdleHook( void )
{
vCoRoutineSchedule();
}
// Alternatively, if you do not require any other part of the idle task to
// execute, the idle task hook can call vCoRoutineScheduler() within an
// infinite loop.
void vApplicationIdleHook( void )
{
for( ;; )
{
vCoRoutineSchedule();
}
}
</pre>
* \defgroup vCoRoutineSchedule vCoRoutineSchedule
* \ingroup Tasks
*/
void vCoRoutineSchedule( void );
/**
* croutine. h
* <pre>
crSTART( CoRoutineHandle_t xHandle );</pre>
*
* This macro MUST always be called at the start of a co-routine function.
*
* Example usage:
<pre>
// Co-routine to be created.
void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
// Variables in co-routines must be declared static if they must maintain value across a blocking call.
static int32_t ulAVariable;
// Must start every co-routine with a call to crSTART();
crSTART( xHandle );
for( ;; )
{
// Co-routine functionality goes here.
}
// Must end every co-routine with a call to crEND();
crEND();
}</pre>
* \defgroup crSTART crSTART
* \ingroup Tasks
*/
#define crSTART( pxCRCB ) switch( ( ( CRCB_t * )( pxCRCB ) )->uxState ) { case 0:
/**
* croutine. h
* <pre>
crEND();</pre>
*
* This macro MUST always be called at the end of a co-routine function.
*
* Example usage:
<pre>
// Co-routine to be created.
void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
// Variables in co-routines must be declared static if they must maintain value across a blocking call.
static int32_t ulAVariable;
// Must start every co-routine with a call to crSTART();
crSTART( xHandle );
for( ;; )
{
// Co-routine functionality goes here.
}
// Must end every co-routine with a call to crEND();
crEND();
}</pre>
* \defgroup crSTART crSTART
* \ingroup Tasks
*/
#define crEND() }
/*
* These macros are intended for internal use by the co-routine implementation
* only. The macros should not be used directly by application writers.
*/
#define crSET_STATE0( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = (__LINE__ * 2); return; case (__LINE__ * 2):
#define crSET_STATE1( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = ((__LINE__ * 2)+1); return; case ((__LINE__ * 2)+1):
/**
* croutine. h
*<pre>
crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );</pre>
*
* Delay a co-routine for a fixed period of time.
*
* crDELAY can only be called from the co-routine function itself - not
* from within a function called by the co-routine function. This is because
* co-routines do not maintain their own stack.
*
* @param xHandle The handle of the co-routine to delay. This is the xHandle
* parameter of the co-routine function.
*
* @param xTickToDelay The number of ticks that the co-routine should delay
* for. The actual amount of time this equates to is defined by
* configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS
* can be used to convert ticks to milliseconds.
*
* Example usage:
<pre>
// Co-routine to be created.
void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
// Variables in co-routines must be declared static if they must maintain value across a blocking call.
// This may not be necessary for const variables.
// We are to delay for 200ms.
static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS;
// Must start every co-routine with a call to crSTART();
crSTART( xHandle );
for( ;; )
{
// Delay for 200ms.
crDELAY( xHandle, xDelayTime );
// Do something here.
}
// Must end every co-routine with a call to crEND();
crEND();
}</pre>
* \defgroup crDELAY crDELAY
* \ingroup Tasks
*/
#define crDELAY( xHandle, xTicksToDelay ) \
if( ( xTicksToDelay ) > 0 ) \
{ \
vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \
} \
crSET_STATE0( ( xHandle ) );
/**
* <pre>
crQUEUE_SEND(
CoRoutineHandle_t xHandle,
QueueHandle_t pxQueue,
void *pvItemToQueue,
TickType_t xTicksToWait,
BaseType_t *pxResult
)</pre>
*
* The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine
* equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.
*
* crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas
* xQueueSend() and xQueueReceive() can only be used from tasks.
*
* crQUEUE_SEND can only be called from the co-routine function itself - not
* from within a function called by the co-routine function. This is because
* co-routines do not maintain their own stack.
*
* See the co-routine section of the WEB documentation for information on
* passing data between tasks and co-routines and between ISR's and
* co-routines.
*
* @param xHandle The handle of the calling co-routine. This is the xHandle
* parameter of the co-routine function.
*
* @param pxQueue The handle of the queue on which the data will be posted.
* The handle is obtained as the return value when the queue is created using
* the xQueueCreate() API function.
*
* @param pvItemToQueue A pointer to the data being posted onto the queue.
* The number of bytes of each queued item is specified when the queue is
* created. This number of bytes is copied from pvItemToQueue into the queue
* itself.
*
* @param xTickToDelay The number of ticks that the co-routine should block
* to wait for space to become available on the queue, should space not be
* available immediately. The actual amount of time this equates to is defined
* by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant
* portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example
* below).
*
* @param pxResult The variable pointed to by pxResult will be set to pdPASS if
* data was successfully posted onto the queue, otherwise it will be set to an
* error defined within ProjDefs.h.
*
* Example usage:
<pre>
// Co-routine function that blocks for a fixed period then posts a number onto
// a queue.
static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
// Variables in co-routines must be declared static if they must maintain value across a blocking call.
static BaseType_t xNumberToPost = 0;
static BaseType_t xResult;
// Co-routines must begin with a call to crSTART().
crSTART( xHandle );
for( ;; )
{
// This assumes the queue has already been created.
crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );
if( xResult != pdPASS )
{
// The message was not posted!
}
// Increment the number to be posted onto the queue.
xNumberToPost++;
// Delay for 100 ticks.
crDELAY( xHandle, 100 );
}
// Co-routines must end with a call to crEND().
crEND();
}</pre>
* \defgroup crQUEUE_SEND crQUEUE_SEND
* \ingroup Tasks
*/
#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \
{ \
*( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) ); \
if( *( pxResult ) == errQUEUE_BLOCKED ) \
{ \
crSET_STATE0( ( xHandle ) ); \
*pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \
} \
if( *pxResult == errQUEUE_YIELD ) \
{ \
crSET_STATE1( ( xHandle ) ); \
*pxResult = pdPASS; \
} \
}
/**
* croutine. h
* <pre>
crQUEUE_RECEIVE(
CoRoutineHandle_t xHandle,
QueueHandle_t pxQueue,
void *pvBuffer,
TickType_t xTicksToWait,
BaseType_t *pxResult
)</pre>
*
* The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine
* equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.
*
* crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas
* xQueueSend() and xQueueReceive() can only be used from tasks.
*
* crQUEUE_RECEIVE can only be called from the co-routine function itself - not
* from within a function called by the co-routine function. This is because
* co-routines do not maintain their own stack.
*
* See the co-routine section of the WEB documentation for information on
* passing data between tasks and co-routines and between ISR's and
* co-routines.
*
* @param xHandle The handle of the calling co-routine. This is the xHandle
* parameter of the co-routine function.
*
* @param pxQueue The handle of the queue from which the data will be received.
* The handle is obtained as the return value when the queue is created using
* the xQueueCreate() API function.
*
* @param pvBuffer The buffer into which the received item is to be copied.
* The number of bytes of each queued item is specified when the queue is
* created. This number of bytes is copied into pvBuffer.
*
* @param xTickToDelay The number of ticks that the co-routine should block
* to wait for data to become available from the queue, should data not be
* available immediately. The actual amount of time this equates to is defined
* by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant
* portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the
* crQUEUE_SEND example).
*
* @param pxResult The variable pointed to by pxResult will be set to pdPASS if
* data was successfully retrieved from the queue, otherwise it will be set to
* an error code as defined within ProjDefs.h.
*
* Example usage:
<pre>
// A co-routine receives the number of an LED to flash from a queue. It
// blocks on the queue until the number is received.
static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
// Variables in co-routines must be declared static if they must maintain value across a blocking call.
static BaseType_t xResult;
static UBaseType_t uxLEDToFlash;
// All co-routines must start with a call to crSTART().
crSTART( xHandle );
for( ;; )
{
// Wait for data to become available on the queue.
crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
if( xResult == pdPASS )
{
// We received the LED to flash - flash it!
vParTestToggleLED( uxLEDToFlash );
}
}
crEND();
}</pre>
* \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE
* \ingroup Tasks
*/
#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \
{ \
*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) ); \
if( *( pxResult ) == errQUEUE_BLOCKED ) \
{ \
crSET_STATE0( ( xHandle ) ); \
*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 ); \
} \
if( *( pxResult ) == errQUEUE_YIELD ) \
{ \
crSET_STATE1( ( xHandle ) ); \
*( pxResult ) = pdPASS; \
} \
}
/**
* croutine. h
* <pre>
crQUEUE_SEND_FROM_ISR(
QueueHandle_t pxQueue,
void *pvItemToQueue,
BaseType_t xCoRoutinePreviouslyWoken
)</pre>
*
* The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the
* co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()
* functions used by tasks.
*
* crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to
* pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and
* xQueueReceiveFromISR() can only be used to pass data between a task and and
* ISR.
*
* crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue
* that is being used from within a co-routine.
*
* See the co-routine section of the WEB documentation for information on
* passing data between tasks and co-routines and between ISR's and
* co-routines.
*
* @param xQueue The handle to the queue on which the item is to be posted.
*
* @param pvItemToQueue A pointer to the item that is to be placed on the
* queue. The size of the items the queue will hold was defined when the
* queue was created, so this many bytes will be copied from pvItemToQueue
* into the queue storage area.
*
* @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto
* the same queue multiple times from a single interrupt. The first call
* should always pass in pdFALSE. Subsequent calls should pass in
* the value returned from the previous call.
*
* @return pdTRUE if a co-routine was woken by posting onto the queue. This is
* used by the ISR to determine if a context switch may be required following
* the ISR.
*
* Example usage:
<pre>
// A co-routine that blocks on a queue waiting for characters to be received.
static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
char cRxedChar;
BaseType_t xResult;
// All co-routines must start with a call to crSTART().
crSTART( xHandle );
for( ;; )
{
// Wait for data to become available on the queue. This assumes the
// queue xCommsRxQueue has already been created!
crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
// Was a character received?
if( xResult == pdPASS )
{
// Process the character here.
}
}
// All co-routines must end with a call to crEND().
crEND();
}
// An ISR that uses a queue to send characters received on a serial port to
// a co-routine.
void vUART_ISR( void )
{
char cRxedChar;
BaseType_t xCRWokenByPost = pdFALSE;
// We loop around reading characters until there are none left in the UART.
while( UART_RX_REG_NOT_EMPTY() )
{
// Obtain the character from the UART.
cRxedChar = UART_RX_REG;
// Post the character onto a queue. xCRWokenByPost will be pdFALSE
// the first time around the loop. If the post causes a co-routine
// to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.
// In this manner we can ensure that if more than one co-routine is
// blocked on the queue only one is woken by this ISR no matter how
// many characters are posted to the queue.
xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );
}
}</pre>
* \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR
* \ingroup Tasks
*/
#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) )
/**
* croutine. h
* <pre>
crQUEUE_SEND_FROM_ISR(
QueueHandle_t pxQueue,
void *pvBuffer,
BaseType_t * pxCoRoutineWoken
)</pre>
*
* The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the
* co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()
* functions used by tasks.
*
* crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to
* pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and
* xQueueReceiveFromISR() can only be used to pass data between a task and and
* ISR.
*
* crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data
* from a queue that is being used from within a co-routine (a co-routine
* posted to the queue).
*
* See the co-routine section of the WEB documentation for information on
* passing data between tasks and co-routines and between ISR's and
* co-routines.
*
* @param xQueue The handle to the queue on which the item is to be posted.
*
* @param pvBuffer A pointer to a buffer into which the received item will be
* placed. The size of the items the queue will hold was defined when the
* queue was created, so this many bytes will be copied from the queue into
* pvBuffer.
*
* @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become
* available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a
* co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise
* *pxCoRoutineWoken will remain unchanged.
*
* @return pdTRUE an item was successfully received from the queue, otherwise
* pdFALSE.
*
* Example usage:
<pre>
// A co-routine that posts a character to a queue then blocks for a fixed
// period. The character is incremented each time.
static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
{
// cChar holds its value while this co-routine is blocked and must therefore
// be declared static.
static char cCharToTx = 'a';
BaseType_t xResult;
// All co-routines must start with a call to crSTART().
crSTART( xHandle );
for( ;; )
{
// Send the next character to the queue.
crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );
if( xResult == pdPASS )
{
// The character was successfully posted to the queue.
}
else
{
// Could not post the character to the queue.
}
// Enable the UART Tx interrupt to cause an interrupt in this
// hypothetical UART. The interrupt will obtain the character
// from the queue and send it.
ENABLE_RX_INTERRUPT();
// Increment to the next character then block for a fixed period.
// cCharToTx will maintain its value across the delay as it is
// declared static.
cCharToTx++;
if( cCharToTx > 'x' )
{
cCharToTx = 'a';
}
crDELAY( 100 );
}
// All co-routines must end with a call to crEND().
crEND();
}
// An ISR that uses a queue to receive characters to send on a UART.
void vUART_ISR( void )
{
char cCharToTx;
BaseType_t xCRWokenByPost = pdFALSE;
while( UART_TX_REG_EMPTY() )
{
// Are there any characters in the queue waiting to be sent?
// xCRWokenByPost will automatically be set to pdTRUE if a co-routine
// is woken by the post - ensuring that only a single co-routine is
// woken no matter how many times we go around this loop.
if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
{
SEND_CHARACTER( cCharToTx );
}
}
}</pre>
* \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR
* \ingroup Tasks
*/
#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) )
/*
* This function is intended for internal use by the co-routine macros only.
* The macro nature of the co-routine implementation requires that the
* prototype appears here. The function should not be used by application
* writers.
*
* Removes the current co-routine from its ready list and places it in the
* appropriate delayed list.
*/
void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList );
/*
* This function is intended for internal use by the queue implementation only.
* The function should not be used by application writers.
*
* Removes the highest priority co-routine from the event list and places it in
* the pending ready list.
*/
BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList );
#ifdef __cplusplus
}
#endif
#endif /* CO_ROUTINE_H */
| {
"pile_set_name": "Github"
} |
define({
"button.dismiss.label": "Ausblenden",
"button.bold.label": "Fett",
"button.italic.label": "Kursiv",
"button.strikethrough.label": "Durchgestrichen",
"button.subscript.label": "Tiefgestellt",
"button.superscript.label": "Hochgestellt",
"button.underline.label": "Unterstrichen",
"button.yes.label": "Ja",
"button.no.label": "Nein",
"button.p.label": "Absatz",
"button.h1.label": "Überschrift 1",
"button.h2.label": "Überschrift 2",
"button.h3.label": "Überschrift 3",
"button.h4.label": "Überschrift 4",
"button.h5.label": "Überschrift 5",
"button.h6.label": "Überschrift 6",
"button.pre.label": "Vorformatierter Text",
"button.removeFormatting.label": "Format entfernen",
"button.ol.label": "Sortierte Liste einfügen",
"button.ul.label": "Unsortierte Liste einfügen",
"button.indent.label": "Liste einrücken",
"button.outdent.label": "Liste ausrücken",
"button.createLink.label": "Verweis einfügen",
"button.removeLink.label": "Verweis löschen",
"button.createAbbr.label": "Abkürzung einfügen",
"button.characterPicker.label": "Sonderzeichen einfügen",
"button.justifyLeft.label": "Linksbündig ausrichten",
"button.justifyRight.label": "Rechtsbündig ausrichten",
"button.justifyCenter.label": "Zentriert ausrichten",
"button.justifyFull.label": "Als Blocksatz formatieren",
"button.horizontalRule.label": "Horizontale Linie einfügen",
"button.createLanguageAnnotation.label": "Sprachauszeichnung hinzufügen",
"button.metaview.label": "Meta-Ansicht ein-/ausblenden",
"button.quote.label": "Zitat einfügen",
"button.blockquote.label": "Zitat einfügen",
"tab.format.label": "Formatierung",
"tab.insert.label": "Einfügen",
"tab.abbr.label": "Abkürzung",
"tab.img.label": "Bild",
"tab.link.label": "Verweis",
"tab.list.label": "Liste",
"tab.table.label": "Tabelle",
"tab.col.label": "Tabellenspalte",
"tab.row.label": "Tabellenzeile",
"tab.cell.label": "Tabellenzelle",
"tab.wai-lang.label": "Sprachauszeichnung"
});
| {
"pile_set_name": "Github"
} |
//
// DesktopEntity.m
// Lesson 53
//
// Created by Lucas Derraugh on 8/2/13.
// Copyright (c) 2013 Lucas Derraugh. All rights reserved.
//
#import "DesktopEntity.h"
@implementation DesktopEntity
- (instancetype)initWithFileURL:(NSURL *)fileURL {
if (self = [super init]) {
_fileURL = fileURL;
}
return self;
}
+ (DesktopEntity *)entityForURL:(NSURL *)url {
NSString *typeIdentifier;
if ([url getResourceValue:&typeIdentifier forKey:NSURLTypeIdentifierKey error:NULL]) {
NSArray *imgTypes = [NSImage imageTypes];
if ([imgTypes containsObject:typeIdentifier]) {
return [[DesktopImageEntity alloc] initWithFileURL:url];
} else if ([typeIdentifier isEqualToString:(NSString *)kUTTypeFolder]) {
return [[DesktopFolderEntity alloc] initWithFileURL:url];
}
}
return nil;
}
- (NSString *)name {
NSString *name;
if ([self.fileURL getResourceValue:&name forKey:NSURLLocalizedNameKey error:NULL]) {
return name;
}
return nil;
}
#pragma mark NSPasteboardWriting
- (NSPasteboardWritingOptions)writingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard {
return [self.fileURL writingOptionsForType:type pasteboard:pasteboard];
}
- (NSArray *)writableTypesForPasteboard:(NSPasteboard *)pasteboard {
return [self.fileURL writableTypesForPasteboard:pasteboard];
}
- (id)pasteboardPropertyListForType:(NSString *)type {
return [self.fileURL pasteboardPropertyListForType:type];
}
#pragma mark NSPasteboardReading
+ (NSArray *)readableTypesForPasteboard:(NSPasteboard *)pasteboard {
return @[(id)kUTTypeFolder, (id)kUTTypeFileURL];
}
+ (NSPasteboardReadingOptions)readingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard {
return NSPasteboardReadingAsString;
}
- (id)initWithPasteboardPropertyList:(id)propertyList ofType:(NSString *)type {
NSURL *url = [[NSURL alloc] initWithPasteboardPropertyList:propertyList ofType:type];
self = [DesktopEntity entityForURL:url];
return self;
}
@end
@implementation DesktopImageEntity
- (NSImage *)image {
if (!_image) {
_image = [[NSImage alloc] initByReferencingURL:self.fileURL];
}
return _image;
}
@end
@implementation DesktopFolderEntity
@end
| {
"pile_set_name": "Github"
} |
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
/*
* Copyright (C) 2000, 2001,
*
* Arjuna Solutions Limited,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: ORBBase.java 2342 2006-03-30 13:06:17Z $
*/
package com.arjuna.orbportability.internal.orbspecific.orb.implementations;
import java.applet.Applet;
import java.util.Properties;
import com.arjuna.common.internal.util.propertyservice.BeanPopulator;
import com.arjuna.orbportability.common.OrbPortabilityEnvironmentBean;
import org.omg.CORBA.SystemException;
import com.arjuna.orbportability.orb.core.ORBImple;
/**
* The base class from which all ORB implementations are derived. Each such
* implementation may be responsible for ensuring that the right ORB specific
* properties (such as org.omg.CORBA.ORBClass) are set.
*/
public class ORBBase implements ORBImple
{
public synchronized boolean initialised ()
{
return _init;
}
public synchronized void init () throws SystemException
{
if (!_init)
{
_orb = org.omg.CORBA.ORB.init();
_init = true;
}
}
public synchronized void init (Applet a, Properties p)
throws SystemException
{
if (!_init)
{
_orb = org.omg.CORBA.ORB.init(a, p);
_init = true;
}
}
public synchronized void init (String[] s, Properties p)
throws SystemException
{
if (!_init)
{
_orb = org.omg.CORBA.ORB.init(s, p);
_init = true;
}
}
public synchronized void shutdown () throws SystemException
{
shutdown(false);
}
public synchronized void shutdown (boolean waitForCompletion) throws SystemException
{
if (_init)
{
OrbPortabilityEnvironmentBean env = BeanPopulator.getDefaultInstance(OrbPortabilityEnvironmentBean.class);
if (env.isShutdownWrappedOrb()) {
_orb.shutdown(waitForCompletion);
_init = false;
}
}
}
public synchronized void destroy () throws SystemException
{
shutdown();
}
public synchronized org.omg.CORBA.ORB orb () throws SystemException
{
return _orb;
}
public synchronized void orb (org.omg.CORBA.ORB o) throws SystemException
{
_orb = o;
_init = true;
}
protected ORBBase()
{
}
protected org.omg.CORBA.ORB _orb = null;
protected boolean _init = false;
}
| {
"pile_set_name": "Github"
} |
{
"_args": [
[
{
"raw": "vinyl-bufferstream@^1.0.1",
"scope": null,
"escapedName": "vinyl-bufferstream",
"name": "vinyl-bufferstream",
"rawSpec": "^1.0.1",
"spec": ">=1.0.1 <2.0.0",
"type": "range"
},
"/var/www/html/star/node_modules/gulp-minify-css"
]
],
"_from": "vinyl-bufferstream@>=1.0.1 <2.0.0",
"_id": "[email protected]",
"_inCache": true,
"_location": "/vinyl-bufferstream",
"_nodeVersion": "1.1.0",
"_npmUser": {
"name": "shinnn",
"email": "[email protected]"
},
"_npmVersion": "2.5.0",
"_phantomChildren": {},
"_requested": {
"raw": "vinyl-bufferstream@^1.0.1",
"scope": null,
"escapedName": "vinyl-bufferstream",
"name": "vinyl-bufferstream",
"rawSpec": "^1.0.1",
"spec": ">=1.0.1 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/gulp-minify-css"
],
"_resolved": "https://registry.npmjs.org/vinyl-bufferstream/-/vinyl-bufferstream-1.0.1.tgz",
"_shasum": "0537869f580effa4ca45acb47579e4b9fe63081a",
"_shrinkwrap": null,
"_spec": "vinyl-bufferstream@^1.0.1",
"_where": "/var/www/html/star/node_modules/gulp-minify-css",
"author": {
"name": "Shinnosuke Watanabe",
"url": "https://github.com/shinnn"
},
"bugs": {
"url": "https://github.com/shinnn/vinyl-bufferstream/issues"
},
"dependencies": {
"bufferstreams": "1.0.1"
},
"description": "Deal with vinyl file contents, regardless of whether it is Buffer/Stream",
"devDependencies": {
"eslint": "^0.14.1",
"istanbul": "^0.3.5",
"istanbul-coveralls": "^1.0.1",
"jscs": "^1.11.2",
"simple-bufferstream": "0.0.4",
"tap-spec": "^2.2.1",
"tape": "^3.5.0",
"vinyl": "^0.4.6"
},
"directories": {},
"dist": {
"shasum": "0537869f580effa4ca45acb47579e4b9fe63081a",
"tarball": "https://registry.npmjs.org/vinyl-bufferstream/-/vinyl-bufferstream-1.0.1.tgz"
},
"files": [
"index.js"
],
"gitHead": "baaf30c5e6291c5838461902bab9098b1dcb4a30",
"homepage": "https://github.com/shinnn/vinyl-bufferstream",
"jscsConfig": {
"preset": "google",
"maximumLineLength": 98,
"requireBlocksOnNewline": true,
"validateLineBreaks": "LF"
},
"keywords": [
"gulpfriendly",
"gulp",
"vinyl",
"buffer",
"stream",
"compatibility",
"interchangeability",
"internal",
"helper"
],
"licenses": [
{
"type": "MIT",
"url": "https://github.com/shinnn/vinyl-bufferstream/blob/master/LICENSE"
}
],
"maintainers": [
{
"name": "shinnn",
"email": "[email protected]"
}
],
"name": "vinyl-bufferstream",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/shinnn/vinyl-bufferstream.git"
},
"scripts": {
"coverage": "istanbul cover test.js",
"coveralls": "${npm_package_scripts_coverage} && istanbul-coveralls",
"pretest": "jscs *.js && eslint *.js",
"test": "node test.js | tap-spec"
},
"version": "1.0.1"
}
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Options for rendering matches.
*
*/
goog.provide('goog.ui.ac.RenderOptions');
/**
* A simple class that contains options for rendering a set of autocomplete
* matches. Used as an optional argument in the callback from the matcher.
* @constructor
*/
goog.ui.ac.RenderOptions = function() {
};
/**
* Whether the current highlighting is to be preserved when displaying the new
* set of matches.
* @type {boolean}
* @private
*/
goog.ui.ac.RenderOptions.prototype.preserveHilited_ = false;
/**
* Whether the first match is to be highlighted. When undefined the autoHilite
* flag of the autocomplete is used.
* @type {boolean|undefined}
* @private
*/
goog.ui.ac.RenderOptions.prototype.autoHilite_;
/**
* @param {boolean} flag The new value for the preserveHilited_ flag.
*/
goog.ui.ac.RenderOptions.prototype.setPreserveHilited = function(flag) {
this.preserveHilited_ = flag;
};
/**
* @return {boolean} The value of the preserveHilited_ flag.
*/
goog.ui.ac.RenderOptions.prototype.getPreserveHilited = function() {
return this.preserveHilited_;
};
/**
* @param {boolean} flag The new value for the autoHilite_ flag.
*/
goog.ui.ac.RenderOptions.prototype.setAutoHilite = function(flag) {
this.autoHilite_ = flag;
};
/**
* @return {boolean|undefined} The value of the autoHilite_ flag.
*/
goog.ui.ac.RenderOptions.prototype.getAutoHilite = function() {
return this.autoHilite_;
};
| {
"pile_set_name": "Github"
} |
// Reverse Bits
// Time Complexity: O(logn), Space Complexity: O(1)
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int left = 0;
int right = 31;
while (left < right) {
// swap bit
int x = (n >> left) & 1;
int y = (n >> right) & 1;
if (x != y) {
n ^= (1 << left) | (1 << right);
}
++left;
--right;
}
return n;
}
} | {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/aux_/advance_forward.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl { namespace aux {
template< long N > struct advance_forward;
template<>
struct advance_forward<0>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef iter0 type;
};
};
template<>
struct advance_forward<1>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename next<iter0>::type iter1;
typedef iter1 type;
};
};
template<>
struct advance_forward<2>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename next<iter0>::type iter1;
typedef typename next<iter1>::type iter2;
typedef iter2 type;
};
};
template<>
struct advance_forward<3>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename next<iter0>::type iter1;
typedef typename next<iter1>::type iter2;
typedef typename next<iter2>::type iter3;
typedef iter3 type;
};
};
template<>
struct advance_forward<4>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename next<iter0>::type iter1;
typedef typename next<iter1>::type iter2;
typedef typename next<iter2>::type iter3;
typedef typename next<iter3>::type iter4;
typedef iter4 type;
};
};
template< long N >
struct advance_forward
{
template< typename Iterator > struct apply
{
typedef typename apply_wrap1<
advance_forward<4>
, Iterator
>::type chunk_result_;
typedef typename apply_wrap1<
advance_forward<(
(N - 4) < 0
? 0
: N - 4
)>
, chunk_result_
>::type type;
};
};
}}}
| {
"pile_set_name": "Github"
} |
<template>
<div id="map"></div>
</template>
<script>
import mapboxgl from "mapbox-gl";
export default {
data() {
return {
map: null
}
},
mounted() {
this.map = new mapboxgl.Map({
container: 'map',
zoom: 1,
});
this.map.addSource('osm', {
type: 'raster',
tiles: ['https://a.tile.openstreetmap.org/{z}/{x}/{y}.png', 'https://b.tile.openstreetmap.org/{z}/{x}/{y}.png', 'https://c.tile.openstreetmap.org/{z}/{x}/{y}.png'],
tileSize: 256 });
this.map.addLayer({
id: 'osm',
type: 'raster',
source: 'osm'
});
let url = 'http://localhost:8000/buildings_china_taiwan.geojson';
this.map.addSource('buildings', { type: 'geojson', data: url });
this.map.addLayer({
'id': 'buildings',
'type': 'fill-extrusion',
'source': 'buildings',
'paint': {
'fill-extrusion-color': 'Crimson',
'fill-extrusion-height': 100,
'fill-extrusion-opacity': 0.9,
}
});
this.map.addControl(new mapboxgl.NavigationControl());
}
}
</script>
<style scoped>
#map {
height: 100%;
}
</style> | {
"pile_set_name": "Github"
} |
.\" Copyright (c) 1980, 1990, 1993
.\" The Regents of the University of California. 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 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 BY THE REGENTS 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 REGENTS 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.
.\"
.\" @(#)script.1 8.1 (Berkeley) 6/6/93
.\" $FreeBSD: head/usr.bin/script/script.1 314436 2017-02-28 23:42:47Z imp $
.\"
.Dd November 25, 2018
.Dt SCRIPT 1
.Os
.Sh NAME
.Nm script
.Nd make typescript of terminal session
.Sh SYNOPSIS
.Nm
.Op Fl adkpqr
.Op Fl F Ar pipe
.Op Fl t Ar time
.Op Ar file Op Ar command ...
.Sh DESCRIPTION
The
.Nm
utility makes a typescript of everything printed on your terminal.
It is useful for students who need a hardcopy record of an interactive
session as proof of an assignment, as the typescript file
can be printed out later with
.Xr lpr 1 .
.Pp
If the argument
.Ar file
is given,
.Nm
saves all dialogue in
.Ar file .
If no file name is given, the typescript is saved in the file
.Pa typescript .
.Pp
If the argument
.Ar command
is given,
.Nm
will run the specified command with an optional argument vector
instead of an interactive shell.
.Pp
The following options are available:
.Bl -tag -width indent
.It Fl a
Append the output to
.Ar file
or
.Pa typescript ,
retaining the prior contents.
.It Fl d
When playing back a session with the
.Fl p
flag, do not sleep between records when playing back a timestamped session.
.It Fl F Ar pipe
Immediately flush output after each write.
This will allow a user to create a named pipe using
.Xr mkfifo 1
and another user may watch the live session using a utility like
.Xr cat 1 .
.It Fl k
Log keys sent to the program as well as output.
.It Fl p
Play back a session recorded with the
.Fl r
flag in real time.
.It Fl q
Run in quiet mode, omit the start, stop and command status messages.
.It Fl r
Record a session with input, output, and timestamping.
.It Fl t Ar time
Specify the interval at which the script output file will be flushed
to disk, in seconds.
A value of 0
causes
.Nm
to flush after every character I/O event.
The default interval is
30 seconds.
.El
.Pp
The script ends when the forked shell (or command) exits (a
.Em control-D
to exit
the Bourne shell
.Pf ( Xr sh 1 ) ,
and
.Em exit ,
.Em logout
or
.Em control-D
(if
.Em ignoreeof
is not set) for the
C-shell,
.Xr csh 1 ) .
.Pp
Certain interactive commands, such as
.Xr vi 1 ,
create garbage in the typescript file.
The
.Nm
utility works best with commands that do not manipulate the screen.
The results are meant to emulate a hardcopy terminal, not an addressable one.
.Sh ENVIRONMENT
The following environment variables are utilized by
.Nm :
.Bl -tag -width SHELL
.It Ev SCRIPT
The
.Ev SCRIPT
environment variable is added to the sub-shell.
If
.Ev SCRIPT
already existed in the users environment,
its value is overwritten within the sub-shell.
The value of
.Ev SCRIPT
is the name of the
.Ar typescript
file.
.It Ev SHELL
If the variable
.Ev SHELL
exists, the shell forked by
.Nm
will be that shell.
If
.Ev SHELL
is not set, the Bourne shell
is assumed.
.Pq Most shells set this variable automatically .
.El
.Sh SEE ALSO
.Xr csh 1
.Po
for the
.Em history
mechanism
.Pc
.Sh HISTORY
The
.Nm
command appeared in
.Bx 3.0 .
.Pp
The
.Fl d ,
.Fl p
and
.Fl r
options first appeared in
.Nx 2.0
and were ported to
.Fx 9.2 .
.Sh BUGS
The
.Nm
utility places
.Sy everything
in the log file, including linefeeds and backspaces.
This is not what the naive user expects.
.Pp
It is not possible to specify a command without also naming the script file
because of argument parsing compatibility issues.
.Pp
When running in
.Fl k
mode, echo cancelling is far from ideal.
The slave terminal mode is checked
for ECHO mode to check when to avoid manual echo logging.
This does not
work when the terminal is in a raw mode where
the program being run is doing manual echo.
.Pp
If
.Nm
reads zero bytes from the terminal, it switches to a mode when it
only attempts to read
once a second until there is data to read.
This prevents
.Nm
from spinning on zero-byte reads, but might cause a 1-second delay in
processing of user input.
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TableDependency.SqlClient.Base.Enums;
using TableDependency.SqlClient.Base.EventArgs;
namespace TableDependency.SqlClient.Test
{
[TestClass]
public class MultiDmlOperationsOrderTest : Base.SqlTableDependencyBaseTest
{
private class MultiDmlOperationsOrderTestModel
{
public int Id { get; set; }
public DateTime When { get; set; }
public string Letter { get; set; }
[NotMapped]
public ChangeType ChangeType { get; set; }
}
private static readonly string TableName = typeof(MultiDmlOperationsOrderTestModel).Name;
private static IList<MultiDmlOperationsOrderTestModel> _checkValues;
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
{
sqlConnection.Open();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = $"IF OBJECT_ID('{TableName}', 'U') IS NOT NULL DROP TABLE [{TableName}];";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = $"CREATE TABLE [{TableName}]([Id] [int] NULL, [Letter] NVARCHAR(50), [When] DATETIME NOT NULL)";
sqlCommand.ExecuteNonQuery();
}
}
}
[TestInitialize]
public void TestInitialize()
{
_checkValues = new List<MultiDmlOperationsOrderTestModel>();
using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
{
sqlConnection.Open();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = $"DELETE FROM [{TableName}]";
sqlCommand.ExecuteNonQuery();
}
}
}
[ClassCleanup]
public static void ClassCleanup()
{
using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
{
sqlConnection.Open();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = $"IF OBJECT_ID('{TableName}', 'U') IS NOT NULL DROP TABLE [{TableName}];";
sqlCommand.ExecuteNonQuery();
}
}
}
[TestCategory("SqlServer")]
[TestMethod]
public void MultiInsertTest1()
{
SqlTableDependency<MultiDmlOperationsOrderTestModel> tableDependency = null;
try
{
tableDependency = new SqlTableDependency<MultiDmlOperationsOrderTestModel>(ConnectionStringForTestUser, tableName: TableName);
tableDependency.OnChanged += this.TableDependency_Changed;
tableDependency.OnError += this.TableDependency_OnError;
tableDependency.Start();
var t = new Task(MultiInsertOperation1);
t.Start();
Thread.Sleep(1000 * 15 * 1);
}
finally
{
tableDependency?.Dispose();
}
Assert.AreEqual(3, _checkValues.Count);
Assert.IsTrue(_checkValues[0].Id == 100);
Assert.IsTrue(_checkValues[1].Id == 200);
Assert.IsTrue(_checkValues[2].Id == 300);
}
[TestCategory("SqlServer")]
[TestMethod]
public void MultiInsertTest2()
{
SqlTableDependency<MultiDmlOperationsOrderTestModel> tableDependency = null;
try
{
tableDependency = new SqlTableDependency<MultiDmlOperationsOrderTestModel>(ConnectionStringForTestUser, tableName: TableName);
tableDependency.OnChanged += this.TableDependency_Changed;
tableDependency.OnError += this.TableDependency_OnError;
tableDependency.Start();
var t = new Task(MultiInsertOperation2);
t.Start();
Thread.Sleep(1000 * 15 * 1);
}
finally
{
tableDependency?.Dispose();
}
Assert.AreEqual(3, _checkValues.Count);
Assert.IsTrue(_checkValues[0].Letter == "a");
Assert.IsTrue(_checkValues[1].Letter == "b");
Assert.IsTrue(_checkValues[2].Letter == "c");
}
private void TableDependency_OnError(object sender, ErrorEventArgs e)
{
throw e.Error;
}
private void TableDependency_Changed(object sender, RecordChangedEventArgs<MultiDmlOperationsOrderTestModel> e)
{
switch (e.ChangeType)
{
case ChangeType.Insert:
_checkValues.Add(new MultiDmlOperationsOrderTestModel { Id = e.Entity.Id, When = e.Entity.When, Letter = e.Entity.Letter });
break;
case ChangeType.Update:
throw new Exception("Update non expected");
case ChangeType.Delete:
throw new Exception("Delete non expected");
}
}
private static void MultiInsertOperation1()
{
using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
{
var sql = $"INSERT INTO [{TableName}] ([Id], [When]) VALUES" +
"(100, GETDATE())," +
"(200, GETDATE())," +
"(300, GETDATE())";
sqlConnection.Open();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = sql;
sqlCommand.ExecuteNonQuery();
}
}
Thread.Sleep(500);
}
private static void MultiInsertOperation2()
{
using (var sqlConnection = new SqlConnection(ConnectionStringForTestUser))
{
var sql = $"INSERT INTO [{TableName}] ([When], [Letter]) VALUES" +
"(GETDATE(), 'a')," +
"(GETDATE(), 'b')," +
"(GETDATE(), 'c')";
sqlConnection.Open();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = sql;
sqlCommand.ExecuteNonQuery();
}
}
Thread.Sleep(500);
}
}
} | {
"pile_set_name": "Github"
} |
#include <common.h>
#include <asm/arch/dram.h>
static struct dram_para dram_para = {
.clock = CONFIG_DRAM_CLK,
.type = 3,
.rank_num = 1,
.density = 0,
.io_width = 0,
.bus_width = 0,
.zq = CONFIG_DRAM_ZQ,
.odt_en = IS_ENABLED(CONFIG_DRAM_ODT_EN),
.size = 0,
#ifdef CONFIG_DRAM_TIMINGS_VENDOR_MAGIC
.cas = 6,
.tpr0 = 0x30926692,
.tpr1 = 0x1090,
.tpr2 = 0x1a0c8,
.emr2 = 0,
#else
# include "dram_timings_sun4i.h"
.active_windowing = 1,
#endif
.tpr3 = CONFIG_DRAM_TPR3,
.tpr4 = 0,
.tpr5 = 0,
.emr1 = CONFIG_DRAM_EMR1,
.emr3 = 0,
.dqs_gating_delay = CONFIG_DRAM_DQS_GATING_DELAY,
};
unsigned long sunxi_dram_init(void)
{
return dramc_init(&dram_para);
}
| {
"pile_set_name": "Github"
} |
/* Test mpn_dc_divappr_q.
Copyright 2002 Free Software Foundation, Inc.
Copyright 2009 William Hart
This file is part of the MPIR Library.
The MPIR 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.
The MPIR 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 the MPIR Library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
#include <stdio.h>
#include <stdlib.h>
#include "mpir.h"
#include "gmp-impl.h"
#include "longlong.h"
#include "tests.h"
#if defined(_MSC_VER) || defined(__MINGW32__)
#define random rand
#endif
#define MAX_LIMBS 400
#define ITERS 10000
/* Check divide and conquer division routine. */
void
check_dc_divappr_q (void)
{
mp_limb_t np[2*MAX_LIMBS];
mp_limb_t np2[2*MAX_LIMBS];
mp_limb_t rp[2*MAX_LIMBS];
mp_limb_t dp[MAX_LIMBS];
mp_limb_t qp[2*MAX_LIMBS];
mp_limb_t dip;
mp_size_t nn, rn, dn, qn;
gmp_randstate_t rands;
int i, j, s;
gmp_randinit_default(rands);
for (i = 0; i < ITERS; i++)
{
dn = (random() % (MAX_LIMBS - 5)) + 6;
nn = (random() % (MAX_LIMBS - 3)) + dn + 3;
mpn_rrandom (np, rands, nn);
mpn_rrandom (dp, rands, dn);
dp[dn-1] |= GMP_LIMB_HIGHBIT;
MPN_COPY(np2, np, nn);
mpir_invert_pi1(dip, dp[dn - 1], dp[dn - 2]);
qn = nn - dn + 1;
qp[qn - 1] = mpn_dc_divappr_q(qp, np, nn, dp, dn, dip);
MPN_NORMALIZE(qp, qn);
if (qn)
{
if (qn >= dn) mpn_mul(rp, qp, qn, dp, dn);
else mpn_mul(rp, dp, dn, qp, qn);
rn = dn + qn;
MPN_NORMALIZE(rp, rn);
s = (rn < nn) ? -1 : (rn > nn) ? 1 : mpn_cmp(rp, np2, nn);
if (s <= 0)
{
mpn_sub(rp, np2, nn, rp, rn);
rn = nn;
MPN_NORMALIZE(rp, rn);
} else
{
mpn_sub(rp, rp, rn, np2, nn);
MPN_NORMALIZE(rp, rn);
}
} else
{
rn = nn;
MPN_COPY(rp, np, nn);
}
s = (rn < dn) ? -1 : (rn > dn) ? 1 : mpn_cmp(rp, dp, dn);
if (s >= 0)
{
printf ("failed:\n");
printf ("nn = %lu, dn = %lu, qn = %lu, rn = %lu\n\n", nn, dn, qn, rn);
gmp_printf (" np: %Nx\n\n", np2, nn);
gmp_printf (" dp: %Nx\n\n", dp, dn);
gmp_printf (" qp: %Nx\n\n", qp, qn);
gmp_printf (" rp: %Nx\n\n", rp, rn);
abort ();
}
}
gmp_randclear(rands);
}
int
main (void)
{
tests_start ();
check_dc_divappr_q ();
tests_end ();
exit (0);
}
| {
"pile_set_name": "Github"
} |
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"adminUsername": {
"type": "string",
"metadata": {
"description": "User name for the Virtual Machine."
}
},
"adminPassword": {
"type": "securestring",
"metadata": {
"description": "Password for the Virtual Machine."
}
},
"ubuntuOSVersion": {
"type": "string",
"defaultValue": "16.04.0-LTS",
"allowedValues": [
"12.04.5-LTS",
"14.04.5-LTS",
"15.10",
"16.04.0-LTS"
],
"metadata": {
"description": "The Ubuntu version for the VM. This will pick a fully patched image of this given Ubuntu version."
}
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
}
},
"variables": {
"imagePublisher": "Canonical",
"imageOffer": "UbuntuServer",
"nicName": "az3000901-nic",
"addressPrefix": "10.0.0.0/16",
"subnetName": "subnet0",
"subnetPrefix": "10.0.0.0/24",
"publicIPAddressName": "az3000901-pip",
"publicIPAddressType": "Dynamic",
"vmName": "az3000901-vm",
"vmSize": "Standard_D2s_v3",
"virtualNetworkName": "az3000901-vnet",
"subnetRef": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('subnetName'))]"
},
"resources": [
{
"apiVersion": "2018-08-01",
"type": "Microsoft.Network/publicIPAddresses",
"name": "[variables('publicIPAddressName')]",
"location": "[parameters('location')]",
"properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]"
}
},
{
"apiVersion": "2018-08-01",
"type": "Microsoft.Network/virtualNetworks",
"name": "[variables('virtualNetworkName')]",
"location": "[parameters('location')]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[variables('addressPrefix')]"
]
},
"subnets": [
{
"name": "[variables('subnetName')]",
"properties": {
"addressPrefix": "[variables('subnetPrefix')]"
}
}
]
}
},
{
"apiVersion": "2018-08-01",
"type": "Microsoft.Network/networkInterfaces",
"name": "[variables('nicName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
"[resourceId('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Dynamic",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
}
},
{
"apiVersion": "2018-06-01",
"type": "Microsoft.Compute/virtualMachines",
"name": "[variables('vmName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "[variables('vmSize')]"
},
"osProfile": {
"computerName": "[variables('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"storageProfile": {
"imageReference": {
"publisher": "[variables('imagePublisher')]",
"offer": "[variables('imageOffer')]",
"sku": "[parameters('ubuntuOSVersion')]",
"version": "latest"
},
"osDisk": {
"createOption": "FromImage"
},
"dataDisks": []
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
}
]
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": false
}
}
}
}
],
"outputs": {
}
}
| {
"pile_set_name": "Github"
} |
extends :
imports:
installer:
data.ec2.elastic.ip:
----------------------------------------------------
[
["property", "extends"], ["punctuation", ":"],
["property", "imports"], ["punctuation", ":"],
["property", "installer"], ["punctuation", ":"],
["property", "data.ec2.elastic.ip"], ["punctuation", ":"]
]
----------------------------------------------------
Checks for properties. | {
"pile_set_name": "Github"
} |
#!/bin/bash
# Copyright 2015 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.
set -ev
# If we're on Travis, we need to set up the environment.
if [[ "${TRAVIS}" == "true" ]]; then
# If secure variables are available, run system test.
if [[ "${TRAVIS_SECURE_ENV_VARS}" ]]; then
echo "Running in Travis, decrypting stored key file."
# Convert encrypted JSON key file into decrypted file to be used.
openssl aes-256-cbc -K ${OAUTH2CLIENT_KEY} \
-iv ${OAUTH2CLIENT_IV} \
-in tests/data/key.json.enc \
-out ${OAUTH2CLIENT_TEST_JSON_KEY_PATH} -d
# Convert encrypted P12 key file into decrypted file to be used.
openssl aes-256-cbc -K ${OAUTH2CLIENT_KEY} \
-iv ${OAUTH2CLIENT_IV} \
-in tests/data/key.p12.enc \
-out ${OAUTH2CLIENT_TEST_P12_KEY_PATH} -d
# Convert encrypted User JSON key file into decrypted file to be used.
openssl aes-256-cbc -K ${encrypted_1ee98544e5ca_key} \
-iv ${encrypted_1ee98544e5ca_iv} \
-in tests/data/user-key.json.enc \
-out ${OAUTH2CLIENT_TEST_USER_KEY_PATH} -d
else
echo "Running in Travis during non-merge to master, doing nothing."
exit
fi
fi
# Run the system tests for each tested package.
python scripts/run_system_tests.py
| {
"pile_set_name": "Github"
} |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiMerchantOperatorRoleCreateModel Data Structure.
/// </summary>
public class KoubeiMerchantOperatorRoleCreateModel : AlipayObject
{
/// <summary>
/// 操作员ID
/// </summary>
[JsonPropertyName("auth_code")]
public string AuthCode { get; set; }
/// <summary>
/// 角色ID
/// </summary>
[JsonPropertyName("role_id")]
public string RoleId { get; set; }
/// <summary>
/// 角色名称,修改时必填
/// </summary>
[JsonPropertyName("role_name")]
public string RoleName { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
//===-- StopInfo.h ----------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_StopInfo_h_
#define liblldb_StopInfo_h_
#include <string>
#include "lldb/Target/Process.h"
#include "lldb/Utility/StructuredData.h"
#include "lldb/lldb-public.h"
namespace lldb_private {
class StopInfo {
friend class Process::ProcessEventData;
friend class ThreadPlanBase;
public:
// Constructors and Destructors
StopInfo(Thread &thread, uint64_t value);
virtual ~StopInfo() {}
bool IsValid() const;
void SetThread(const lldb::ThreadSP &thread_sp) { m_thread_wp = thread_sp; }
lldb::ThreadSP GetThread() const { return m_thread_wp.lock(); }
// The value of the StopInfo depends on the StopReason. StopReason
// Meaning ----------------------------------------------
// eStopReasonBreakpoint BreakpointSiteID eStopReasonSignal
// Signal number eStopReasonWatchpoint WatchpointLocationID
// eStopReasonPlanComplete No significance
uint64_t GetValue() const { return m_value; }
virtual lldb::StopReason GetStopReason() const = 0;
// ShouldStopSynchronous will get called before any thread plans are
// consulted, and if it says we should resume the target, then we will just
// immediately resume. This should not run any code in or resume the target.
virtual bool ShouldStopSynchronous(Event *event_ptr) { return true; }
void OverrideShouldNotify(bool override_value) {
m_override_should_notify = override_value ? eLazyBoolYes : eLazyBoolNo;
}
// If should stop returns false, check if we should notify of this event
virtual bool ShouldNotify(Event *event_ptr) {
if (m_override_should_notify == eLazyBoolCalculate)
return DoShouldNotify(event_ptr);
else
return m_override_should_notify == eLazyBoolYes;
}
virtual void WillResume(lldb::StateType resume_state) {
// By default, don't do anything
}
virtual const char *GetDescription() { return m_description.c_str(); }
virtual void SetDescription(const char *desc_cstr) {
if (desc_cstr && desc_cstr[0])
m_description.assign(desc_cstr);
else
m_description.clear();
}
virtual bool IsValidForOperatingSystemThread(Thread &thread) { return true; }
// Sometimes the thread plan logic will know that it wants a given stop to
// stop or not, regardless of what the ordinary logic for that StopInfo would
// dictate. The main example of this is the ThreadPlanCallFunction, which
// for instance knows - based on how that particular expression was executed
// - whether it wants all breakpoints to auto-continue or not. Use
// OverrideShouldStop on the StopInfo to implement this.
void OverrideShouldStop(bool override_value) {
m_override_should_stop = override_value ? eLazyBoolYes : eLazyBoolNo;
}
bool GetOverrideShouldStop() {
return m_override_should_stop != eLazyBoolCalculate;
}
bool GetOverriddenShouldStopValue() {
return m_override_should_stop == eLazyBoolYes;
}
StructuredData::ObjectSP GetExtendedInfo() { return m_extended_info; }
static lldb::StopInfoSP
CreateStopReasonWithBreakpointSiteID(Thread &thread,
lldb::break_id_t break_id);
// This creates a StopInfo for the thread where the should_stop is already
// set, and won't be recalculated.
static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID(
Thread &thread, lldb::break_id_t break_id, bool should_stop);
static lldb::StopInfoSP CreateStopReasonWithWatchpointID(
Thread &thread, lldb::break_id_t watch_id,
lldb::addr_t watch_hit_addr = LLDB_INVALID_ADDRESS);
static lldb::StopInfoSP
CreateStopReasonWithSignal(Thread &thread, int signo,
const char *description = nullptr);
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread);
static lldb::StopInfoSP
CreateStopReasonWithPlan(lldb::ThreadPlanSP &plan,
lldb::ValueObjectSP return_valobj_sp,
lldb::ExpressionVariableSP expression_variable_sp);
static lldb::StopInfoSP
CreateStopReasonWithException(Thread &thread, const char *description);
static lldb::StopInfoSP CreateStopReasonWithExec(Thread &thread);
static lldb::ValueObjectSP
GetReturnValueObject(lldb::StopInfoSP &stop_info_sp);
static lldb::ExpressionVariableSP
GetExpressionVariable(lldb::StopInfoSP &stop_info_sp);
static lldb::ValueObjectSP
GetCrashingDereference(lldb::StopInfoSP &stop_info_sp,
lldb::addr_t *crashing_address = nullptr);
protected:
// Perform any action that is associated with this stop. This is done as the
// Event is removed from the event queue. ProcessEventData::DoOnRemoval does
// the job.
virtual void PerformAction(Event *event_ptr) {}
virtual bool DoShouldNotify(Event *event_ptr) { return false; }
// Stop the thread by default. Subclasses can override this to allow the
// thread to continue if desired. The ShouldStop method should not do
// anything that might run code. If you need to run code when deciding
// whether to stop at this StopInfo, that must be done in the PerformAction.
// The PerformAction will always get called before the ShouldStop. This is
// done by the ProcessEventData::DoOnRemoval, though the ThreadPlanBase needs
// to consult this later on.
virtual bool ShouldStop(Event *event_ptr) { return true; }
// Classes that inherit from StackID can see and modify these
lldb::ThreadWP m_thread_wp; // The thread corresponding to the stop reason.
uint32_t m_stop_id; // The process stop ID for which this stop info is valid
uint32_t m_resume_id; // This is the resume ID when we made this stop ID.
uint64_t m_value; // A generic value that can be used for things pertaining to
// this stop info
std::string m_description; // A textual description describing this stop.
LazyBool m_override_should_notify;
LazyBool m_override_should_stop;
StructuredData::ObjectSP
m_extended_info; // The extended info for this stop info
// This determines whether the target has run since this stop info. N.B.
// running to evaluate a user expression does not count.
bool HasTargetRunSinceMe();
// MakeStopInfoValid is necessary to allow saved stop infos to resurrect
// themselves as valid. It should only be used by
// Thread::RestoreThreadStateFromCheckpoint and to make sure the one-step
// needed for before-the-fact watchpoints does not prevent us from stopping
void MakeStopInfoValid();
private:
friend class Thread;
DISALLOW_COPY_AND_ASSIGN(StopInfo);
};
} // namespace lldb_private
#endif // liblldb_StopInfo_h_
| {
"pile_set_name": "Github"
} |
/*!
* Bootstrap v3.3.5 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
//
// Load core variables and mixins
// --------------------------------------------------
@import "variables";
@import "mixins";
//
// Buttons
// --------------------------------------------------
// Common styles
.btn-default,
.btn-primary,
.btn-success,
.btn-info,
.btn-warning,
.btn-danger {
text-shadow: 0 -1px 0 rgba(0,0,0,.2);
$shadow: inset 0 1px 0 rgba(255,255,255,.15), 0 1px 1px rgba(0,0,0,.075);
@include box-shadow($shadow);
// Reset the shadow
&:active,
&.active {
@include box-shadow(inset 0 3px 5px rgba(0,0,0,.125));
}
&.disabled,
&[disabled],
fieldset[disabled] & {
@include box-shadow(none);
}
.badge {
text-shadow: none;
}
}
// Mixin for generating new styles
@mixin btn-styles($btn-color: #555) {
@include gradient-vertical($start-color: $btn-color, $end-color: darken($btn-color, 12%));
@include reset-filter; // Disable gradients for IE9 because filter bleeds through rounded corners; see https://github.com/twbs/bootstrap/issues/10620
background-repeat: repeat-x;
border-color: darken($btn-color, 14%);
&:hover,
&:focus {
background-color: darken($btn-color, 12%);
background-position: 0 -15px;
}
&:active,
&.active {
background-color: darken($btn-color, 12%);
border-color: darken($btn-color, 14%);
}
&.disabled,
&[disabled],
fieldset[disabled] & {
&,
&:hover,
&:focus,
&.focus,
&:active,
&.active {
background-color: darken($btn-color, 12%);
background-image: none;
}
}
}
// Common styles
.btn {
// Remove the gradient for the pressed/active state
&:active,
&.active {
background-image: none;
}
}
// Apply the mixin to the buttons
.btn-default { @include btn-styles($btn-default-bg); text-shadow: 0 1px 0 #fff; border-color: #ccc; }
.btn-primary { @include btn-styles($btn-primary-bg); }
.btn-success { @include btn-styles($btn-success-bg); }
.btn-info { @include btn-styles($btn-info-bg); }
.btn-warning { @include btn-styles($btn-warning-bg); }
.btn-danger { @include btn-styles($btn-danger-bg); }
//
// Images
// --------------------------------------------------
.thumbnail,
.img-thumbnail {
@include box-shadow(0 1px 2px rgba(0,0,0,.075));
}
//
// Dropdowns
// --------------------------------------------------
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
@include gradient-vertical($start-color: $dropdown-link-hover-bg, $end-color: darken($dropdown-link-hover-bg, 5%));
background-color: darken($dropdown-link-hover-bg, 5%);
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
@include gradient-vertical($start-color: $dropdown-link-active-bg, $end-color: darken($dropdown-link-active-bg, 5%));
background-color: darken($dropdown-link-active-bg, 5%);
}
//
// Navbar
// --------------------------------------------------
// Default navbar
.navbar-default {
@include gradient-vertical($start-color: lighten($navbar-default-bg, 10%), $end-color: $navbar-default-bg);
@include reset-filter; // Remove gradient in IE<10 to fix bug where dropdowns don't get triggered
border-radius: $navbar-border-radius;
$shadow: inset 0 1px 0 rgba(255,255,255,.15), 0 1px 5px rgba(0,0,0,.075);
@include box-shadow($shadow);
.navbar-nav > .open > a,
.navbar-nav > .active > a {
@include gradient-vertical($start-color: darken($navbar-default-link-active-bg, 5%), $end-color: darken($navbar-default-link-active-bg, 2%));
@include box-shadow(inset 0 3px 9px rgba(0,0,0,.075));
}
}
.navbar-brand,
.navbar-nav > li > a {
text-shadow: 0 1px 0 rgba(255,255,255,.25);
}
// Inverted navbar
.navbar-inverse {
@include gradient-vertical($start-color: lighten($navbar-inverse-bg, 10%), $end-color: $navbar-inverse-bg);
@include reset-filter; // Remove gradient in IE<10 to fix bug where dropdowns don't get triggered; see https://github.com/twbs/bootstrap/issues/10257
border-radius: $navbar-border-radius;
.navbar-nav > .open > a,
.navbar-nav > .active > a {
@include gradient-vertical($start-color: $navbar-inverse-link-active-bg, $end-color: lighten($navbar-inverse-link-active-bg, 2.5%));
@include box-shadow(inset 0 3px 9px rgba(0,0,0,.25));
}
.navbar-brand,
.navbar-nav > li > a {
text-shadow: 0 -1px 0 rgba(0,0,0,.25);
}
}
// Undo rounded corners in static and fixed navbars
.navbar-static-top,
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
// Fix active state of dropdown items in collapsed mode
@media (max-width: $grid-float-breakpoint-max) {
.navbar .navbar-nav .open .dropdown-menu > .active > a {
&,
&:hover,
&:focus {
color: #fff;
@include gradient-vertical($start-color: $dropdown-link-active-bg, $end-color: darken($dropdown-link-active-bg, 5%));
}
}
}
//
// Alerts
// --------------------------------------------------
// Common styles
.alert {
text-shadow: 0 1px 0 rgba(255,255,255,.2);
$shadow: inset 0 1px 0 rgba(255,255,255,.25), 0 1px 2px rgba(0,0,0,.05);
@include box-shadow($shadow);
}
// Mixin for generating new styles
@mixin alert-styles($color) {
@include gradient-vertical($start-color: $color, $end-color: darken($color, 7.5%));
border-color: darken($color, 15%);
}
// Apply the mixin to the alerts
.alert-success { @include alert-styles($alert-success-bg); }
.alert-info { @include alert-styles($alert-info-bg); }
.alert-warning { @include alert-styles($alert-warning-bg); }
.alert-danger { @include alert-styles($alert-danger-bg); }
//
// Progress bars
// --------------------------------------------------
// Give the progress background some depth
.progress {
@include gradient-vertical($start-color: darken($progress-bg, 4%), $end-color: $progress-bg)
}
// Mixin for generating new styles
@mixin progress-bar-styles($color) {
@include gradient-vertical($start-color: $color, $end-color: darken($color, 10%));
}
// Apply the mixin to the progress bars
.progress-bar { @include progress-bar-styles($progress-bar-bg); }
.progress-bar-success { @include progress-bar-styles($progress-bar-success-bg); }
.progress-bar-info { @include progress-bar-styles($progress-bar-info-bg); }
.progress-bar-warning { @include progress-bar-styles($progress-bar-warning-bg); }
.progress-bar-danger { @include progress-bar-styles($progress-bar-danger-bg); }
// Reset the striped class because our mixins don't do multiple gradients and
// the above custom styles override the new `.progress-bar-striped` in v3.2.0.
.progress-bar-striped {
@include gradient-striped;
}
//
// List groups
// --------------------------------------------------
.list-group {
border-radius: $border-radius-base;
@include box-shadow(0 1px 2px rgba(0,0,0,.075));
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
text-shadow: 0 -1px 0 darken($list-group-active-bg, 10%);
@include gradient-vertical($start-color: $list-group-active-bg, $end-color: darken($list-group-active-bg, 7.5%));
border-color: darken($list-group-active-border, 7.5%);
.badge {
text-shadow: none;
}
}
//
// Panels
// --------------------------------------------------
// Common styles
.panel {
@include box-shadow(0 1px 2px rgba(0,0,0,.05));
}
// Mixin for generating new styles
@mixin panel-heading-styles($color) {
@include gradient-vertical($start-color: $color, $end-color: darken($color, 5%));
}
// Apply the mixin to the panel headings only
.panel-default > .panel-heading { @include panel-heading-styles($panel-default-heading-bg); }
.panel-primary > .panel-heading { @include panel-heading-styles($panel-primary-heading-bg); }
.panel-success > .panel-heading { @include panel-heading-styles($panel-success-heading-bg); }
.panel-info > .panel-heading { @include panel-heading-styles($panel-info-heading-bg); }
.panel-warning > .panel-heading { @include panel-heading-styles($panel-warning-heading-bg); }
.panel-danger > .panel-heading { @include panel-heading-styles($panel-danger-heading-bg); }
//
// Wells
// --------------------------------------------------
.well {
@include gradient-vertical($start-color: darken($well-bg, 5%), $end-color: $well-bg);
border-color: darken($well-bg, 10%);
$shadow: inset 0 1px 3px rgba(0,0,0,.05), 0 1px 0 rgba(255,255,255,.1);
@include box-shadow($shadow);
}
| {
"pile_set_name": "Github"
} |
-- original: tkt3832.test
-- credit: http://www.sqlite.org/src/tree?ci=trunk&name=test
CREATE TABLE t1(a INT, b INTEGER PRIMARY KEY);
CREATE TABLE log(x);
CREATE TRIGGER t1r1 BEFORE INSERT ON t1 BEGIN
INSERT INTO log VALUES(new.b);
END;
INSERT INTO t1 VALUES(NULL,5);
INSERT INTO t1 SELECT b, a FROM t1 ORDER BY b;
SELECT rowid, * FROM t1;
SELECT rowid, * FROM log; | {
"pile_set_name": "Github"
} |
<?php
use yii\db\Migration;
class m200529_160733_addon_shop_product extends Migration
{
public function up()
{
/* 取消外键约束 */
$this->execute('SET foreign_key_checks = 0');
/* 创建表 */
$this->createTable('{{%addon_shop_product}}', [
'id' => "int(10) unsigned NOT NULL AUTO_INCREMENT",
'merchant_id' => "int(11) NOT NULL DEFAULT '0' COMMENT '商家编号'",
'name' => "varchar(255) NOT NULL COMMENT '商品标题'",
'picture' => "varchar(100) NULL DEFAULT '' COMMENT '商品主图'",
'cate_id' => "int(11) unsigned NOT NULL COMMENT '商品分类编号'",
'brand_id' => "int(11) unsigned NULL DEFAULT '0' COMMENT '品牌编号'",
'type_id' => "tinyint(4) unsigned NULL DEFAULT '0' COMMENT '类型编号'",
'sketch' => "varchar(200) NULL DEFAULT '' COMMENT '简述'",
'intro' => "text NOT NULL COMMENT '商品描述'",
'keywords' => "varchar(200) NULL DEFAULT '' COMMENT '商品关键字'",
'tags' => "varchar(200) NULL DEFAULT '' COMMENT '标签'",
'marque' => "varchar(100) NULL DEFAULT '' COMMENT '商品型号'",
'barcode' => "varchar(100) NULL DEFAULT '' COMMENT '仓库条码'",
'sales' => "int(11) NOT NULL DEFAULT '0' COMMENT '虚拟购买量'",
'real_sales' => "int(10) NOT NULL DEFAULT '0' COMMENT '实际销量'",
'total_sales' => "int(11) NULL DEFAULT '0' COMMENT '总销量'",
'price' => "decimal(8,2) NOT NULL COMMENT '商品价格'",
'market_price' => "decimal(8,2) NULL DEFAULT '0.00' COMMENT '市场价格'",
'cost_price' => "decimal(19,2) NULL DEFAULT '0.00' COMMENT '成本价'",
'wholesale_price' => "decimal(10,2) unsigned NULL DEFAULT '0.00' COMMENT '拼团价格'",
'stock' => "int(11) NOT NULL DEFAULT '0' COMMENT '库存量'",
'warning_stock' => "int(11) NOT NULL DEFAULT '0' COMMENT '库存警告'",
'covers' => "text NOT NULL COMMENT '幻灯片'",
'posters' => "json NULL COMMENT '宣传海报'",
'state' => "tinyint(4) NOT NULL DEFAULT '0' COMMENT '审核状态 -1 审核失败 0 未审核 1 审核成功'",
'is_package' => "enum('0','1') NULL DEFAULT '0' COMMENT '是否是套餐'",
'is_attribute' => "enum('0','1') NULL DEFAULT '0' COMMENT '启用商品规格'",
'sort' => "int(11) NOT NULL DEFAULT '999' COMMENT '排序'",
'product_status' => "tinyint(4) NULL DEFAULT '1' COMMENT '商品状态 0下架,1正常,10违规(禁售)'",
'shipping_type' => "tinyint(2) NULL DEFAULT '1' COMMENT '运费类型 1免邮2买家付邮费'",
'shipping_fee' => "decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '运费'",
'shipping_fee_id' => "int(11) NOT NULL DEFAULT '0' COMMENT '物流模板id'",
'shipping_fee_type' => "int(11) NOT NULL DEFAULT '1' COMMENT '计价方式1.计件2.体积3.重量'",
'product_weight' => "decimal(8,2) NOT NULL DEFAULT '0.00' COMMENT '商品重量'",
'product_volume' => "decimal(8,2) NOT NULL DEFAULT '0.00' COMMENT '商品体积'",
'marketing_type' => "varchar(50) NOT NULL DEFAULT '0' COMMENT '促销类型'",
'marketing_id' => "int(11) NOT NULL DEFAULT '0' COMMENT '促销活动ID'",
'marketing_price' => "decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '商品促销价格'",
'point_exchange_type' => "tinyint(3) NOT NULL DEFAULT '1' COMMENT '积分兑换类型'",
'point_exchange' => "int(11) NOT NULL DEFAULT '0' COMMENT '积分兑换'",
'max_use_point' => "int(11) NOT NULL DEFAULT '0' COMMENT '积分抵现最大可用积分数 0为不可使用'",
'integral_give_type' => "int(1) NOT NULL DEFAULT '0' COMMENT '积分赠送类型 0固定值 1按比率'",
'give_point' => "int(11) NOT NULL DEFAULT '0' COMMENT '购买商品赠送积分'",
'min_buy' => "int(11) NOT NULL DEFAULT '1' COMMENT '最少买几件'",
'max_buy' => "int(11) NOT NULL DEFAULT '0' COMMENT '限购 0 不限购'",
'view' => "int(10) unsigned NOT NULL DEFAULT '0' COMMENT '商品点击数量'",
'star' => "int(10) unsigned NOT NULL DEFAULT '5' COMMENT '好评星级'",
'collect_num' => "int(10) unsigned NOT NULL DEFAULT '0' COMMENT '收藏数量'",
'comment_num' => "int(10) unsigned NOT NULL DEFAULT '0' COMMENT '评价数'",
'transmit_num' => "int(11) NOT NULL DEFAULT '0' COMMENT '分享数'",
'province_id' => "int(10) unsigned NULL DEFAULT '0' COMMENT '一级地区id'",
'city_id' => "int(10) unsigned NULL DEFAULT '0' COMMENT '二级地区id'",
'area_id' => "int(10) NULL DEFAULT '0' COMMENT '三级地区'",
'address_name' => "varchar(200) NULL DEFAULT '' COMMENT '地址'",
'is_stock_visible' => "int(1) NOT NULL DEFAULT '1' COMMENT '库存显示 0不显示1显示'",
'is_hot' => "int(1) NOT NULL DEFAULT '0' COMMENT '是否热销商品'",
'is_recommend' => "int(1) NOT NULL DEFAULT '0' COMMENT '是否推荐'",
'is_new' => "int(1) NOT NULL DEFAULT '0' COMMENT '是否新品'",
'is_bill' => "int(1) NOT NULL DEFAULT '0' COMMENT '是否开具增值税发票 1是,0否'",
'base_attribute_id' => "int(11) NOT NULL DEFAULT '0' COMMENT '商品类型'",
'base_attribute_format' => "text NULL COMMENT '商品规格'",
'match_point' => "float(10,2) NULL DEFAULT '5' COMMENT '实物与描述相符(根据评价计算)'",
'match_ratio' => "float(10,2) NULL DEFAULT '100' COMMENT '实物与描述相符(根据评价计算)百分比'",
'sale_date' => "int(11) NULL DEFAULT '0' COMMENT '上下架时间'",
'is_virtual' => "tinyint(1) NULL DEFAULT '0' COMMENT '是否虚拟商品'",
'production_date' => "int(11) NULL DEFAULT '0' COMMENT '生产日期'",
'shelf_life' => "int(11) NULL DEFAULT '0' COMMENT '保质期'",
'is_open_presell' => "tinyint(4) NULL DEFAULT '0' COMMENT '是否支持预售'",
'presell_time' => "int(11) NULL DEFAULT '0' COMMENT '预售发货时间'",
'presell_day' => "int(11) NULL DEFAULT '0' COMMENT '预售发货天数'",
'presell_delivery_type' => "int(11) NULL DEFAULT '1' COMMENT '预售发货方式1. 按照预售发货时间 2.按照预售发货天数'",
'presell_price' => "decimal(10,2) NULL DEFAULT '0.00' COMMENT '预售金额'",
'unit' => "varchar(20) NULL DEFAULT '' COMMENT '商品单位'",
'video_url' => "varchar(100) NULL DEFAULT '' COMMENT '展示视频'",
'supplier_id' => "int(11) NULL DEFAULT '0' COMMENT '供货商id'",
'is_open_commission' => "tinyint(4) NULL DEFAULT '0' COMMENT '是否支持分销'",
'status' => "tinyint(4) NULL DEFAULT '1' COMMENT '状态'",
'created_at' => "int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间'",
'updated_at' => "int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间'",
'PRIMARY KEY (`id`)'
], "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='扩展_微商城_商品表'");
/* 索引设置 */
$this->createIndex('price','{{%addon_shop_product}}','price',0);
$this->createIndex('cate_id','{{%addon_shop_product}}','cate_id',0);
$this->createIndex('brand_id','{{%addon_shop_product}}','brand_id',0);
$this->createIndex('view','{{%addon_shop_product}}','view',0);
$this->createIndex('star','{{%addon_shop_product}}','star',0);
$this->createIndex('comment_num','{{%addon_shop_product}}','comment_num',0);
$this->createIndex('sort','{{%addon_shop_product}}','sort',0);
/* 表数据 */
/* 设置外键约束 */
$this->execute('SET foreign_key_checks = 1;');
}
public function down()
{
$this->execute('SET foreign_key_checks = 0');
/* 删除表 */
$this->dropTable('{{%addon_shop_product}}');
$this->execute('SET foreign_key_checks = 1;');
}
}
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0-only */
/* Copyright (c) 2015-2018, The Linux Foundation. All rights reserved.
*/
#ifndef _DPU_HW_INTF_H
#define _DPU_HW_INTF_H
#include "dpu_hw_catalog.h"
#include "dpu_hw_mdss.h"
#include "dpu_hw_util.h"
#include "dpu_hw_blk.h"
struct dpu_hw_intf;
/* intf timing settings */
struct intf_timing_params {
u32 width; /* active width */
u32 height; /* active height */
u32 xres; /* Display panel width */
u32 yres; /* Display panel height */
u32 h_back_porch;
u32 h_front_porch;
u32 v_back_porch;
u32 v_front_porch;
u32 hsync_pulse_width;
u32 vsync_pulse_width;
u32 hsync_polarity;
u32 vsync_polarity;
u32 border_clr;
u32 underflow_clr;
u32 hsync_skew;
};
struct intf_prog_fetch {
u8 enable;
/* vsync counter for the front porch pixel line */
u32 fetch_start;
};
struct intf_status {
u8 is_en; /* interface timing engine is enabled or not */
u32 frame_count; /* frame count since timing engine enabled */
u32 line_count; /* current line count including blanking */
};
/**
* struct dpu_hw_intf_ops : Interface to the interface Hw driver functions
* Assumption is these functions will be called after clocks are enabled
* @ setup_timing_gen : programs the timing engine
* @ setup_prog_fetch : enables/disables the programmable fetch logic
* @ enable_timing: enable/disable timing engine
* @ get_status: returns if timing engine is enabled or not
* @ get_line_count: reads current vertical line counter
*/
struct dpu_hw_intf_ops {
void (*setup_timing_gen)(struct dpu_hw_intf *intf,
const struct intf_timing_params *p,
const struct dpu_format *fmt);
void (*setup_prg_fetch)(struct dpu_hw_intf *intf,
const struct intf_prog_fetch *fetch);
void (*enable_timing)(struct dpu_hw_intf *intf,
u8 enable);
void (*get_status)(struct dpu_hw_intf *intf,
struct intf_status *status);
u32 (*get_line_count)(struct dpu_hw_intf *intf);
};
struct dpu_hw_intf {
struct dpu_hw_blk base;
struct dpu_hw_blk_reg_map hw;
/* intf */
enum dpu_intf idx;
const struct dpu_intf_cfg *cap;
const struct dpu_mdss_cfg *mdss;
/* ops */
struct dpu_hw_intf_ops ops;
};
/**
* dpu_hw_intf_init(): Initializes the intf driver for the passed
* interface idx.
* @idx: interface index for which driver object is required
* @addr: mapped register io address of MDP
* @m : pointer to mdss catalog data
*/
struct dpu_hw_intf *dpu_hw_intf_init(enum dpu_intf idx,
void __iomem *addr,
struct dpu_mdss_cfg *m);
/**
* dpu_hw_intf_destroy(): Destroys INTF driver context
* @intf: Pointer to INTF driver context
*/
void dpu_hw_intf_destroy(struct dpu_hw_intf *intf);
#endif /*_DPU_HW_INTF_H */
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.