hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a9ec60846d8d2c8892c3ffac8a05595efd9f807 | 377 | h | C | Example/UICollectionView-YCHLayoutCacheCell/YCHFeedModel.h | onekyle/UICollectionView-YCHLayoutCacheCell | 2ff6d7a9721d0758a11e81a34b6b4c0a2f878a4a | [
"MIT"
] | null | null | null | Example/UICollectionView-YCHLayoutCacheCell/YCHFeedModel.h | onekyle/UICollectionView-YCHLayoutCacheCell | 2ff6d7a9721d0758a11e81a34b6b4c0a2f878a4a | [
"MIT"
] | null | null | null | Example/UICollectionView-YCHLayoutCacheCell/YCHFeedModel.h | onekyle/UICollectionView-YCHLayoutCacheCell | 2ff6d7a9721d0758a11e81a34b6b4c0a2f878a4a | [
"MIT"
] | null | null | null | //
// YCHFeedModel.h
// UICollectionView-YCHLayoutCacheCell
//
// Created by Kyle on 10/9/17.
// Copyright © 2017年 ych.wang@outlook.com. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface YCHFeedModel : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *text;
@property (nonatomic, strong) UIImage *icon;
@end
| 20.944444 | 64 | 0.729443 |
00a7b95a7f9020a853b450ee714ce97d055a8731 | 328 | h | C | hello/hello_Z4_1/include/platform_inits.h | dapperfu/mpc5748G_examples | 6ba2fd8cfa312d59036284e368a3cca2aba7df4b | [
"Unlicense"
] | 3 | 2021-03-29T14:14:15.000Z | 2021-09-09T06:19:47.000Z | hello/hello_Z4_1/include/platform_inits.h | dapperfu/mpc5748G_examples | 6ba2fd8cfa312d59036284e368a3cca2aba7df4b | [
"Unlicense"
] | 1 | 2020-10-14T14:15:21.000Z | 2020-10-14T14:15:21.000Z | hello/hello_Z4_1/include/platform_inits.h | dapperfu/mpc5748G_examples | 6ba2fd8cfa312d59036284e368a3cca2aba7df4b | [
"Unlicense"
] | 1 | 2021-01-11T05:35:00.000Z | 2021-01-11T05:35:00.000Z | /*
* platform_inits.h
*
* Created on: Feb 24, 2016
* Author: B55457
*/
#ifndef PLATFORM_INITS_H_
#define PLATFORM_INITS_H_
#include "project.h"
void memory_config_16mhz(void);
void memory_config_160mhz(void);
void crossbar_config(void);
void bridges_config(void);
#endif /* PLATFORM_INITS_H_ */
| 17.263158 | 33 | 0.695122 |
7a941769ace4b53ab05dc1c155a676dec92e2384 | 795 | c | C | sorts/quicksort.c | 115100/algos | bc5d33a4aab5c072b0e48c5cf57b9c1799a84937 | [
"BSD-3-Clause"
] | null | null | null | sorts/quicksort.c | 115100/algos | bc5d33a4aab5c072b0e48c5cf57b9c1799a84937 | [
"BSD-3-Clause"
] | null | null | null | sorts/quicksort.c | 115100/algos | bc5d33a4aab5c072b0e48c5cf57b9c1799a84937 | [
"BSD-3-Clause"
] | null | null | null | // Theoretical O(nLog(n)) average algorithm.
#include "quicksort.h"
#include "utils.h"
int medianOfThree(int A[], long lo, long hi)
{
int mid = hi - (hi - lo) / 2;
if (A[lo] > A[hi])
swap(A, lo, hi);
if (A[lo] > A[mid])
swap(A, lo, mid);
if (A[mid] > A[hi])
swap(A, mid, hi);
return A[mid];
}
int partition(int A[], long lo, long hi)
{
int pivot;
int i = lo - 1;
int j = hi + 1;
pivot = medianOfThree(A, lo, hi);
while (1)
{
do i++; while (A[i] < pivot);
do j--; while (A[j] > pivot);
if (i >= j)
return j;
swap(A, i, j);
}
}
void _quicksort(int A[], long lo, long hi)
{
if (hi - lo < 2)
return;
int p = partition(A, lo, hi);
_quicksort(A, lo, p);
_quicksort(A, p + 1, hi);
}
void quicksort(int A[], long len)
{
_quicksort(A, 0, len - 1);
}
| 13.25 | 44 | 0.540881 |
1a5facb5c6738e4fd3174aae23627a12253171bc | 2,903 | h | C | ir_viewer/include/falsecolor.h | ethz-asl/FLIR_tools | b969dbeaddc102977b87efb64cc1573f0a0eb176 | [
"Apache-2.0"
] | 9 | 2016-08-26T15:21:24.000Z | 2022-02-11T12:04:00.000Z | ir_viewer/include/falsecolor.h | ethz-asl/FLIR_tools | b969dbeaddc102977b87efb64cc1573f0a0eb176 | [
"Apache-2.0"
] | 1 | 2021-01-21T20:19:57.000Z | 2021-01-21T20:19:57.000Z | ir_viewer/include/falsecolor.h | ethz-asl/FLIR_tools | b969dbeaddc102977b87efb64cc1573f0a0eb176 | [
"Apache-2.0"
] | 3 | 2016-12-08T17:42:09.000Z | 2019-12-26T14:31:22.000Z | /*
*
* Copyright (c) 2013, Simon Lynen, ASL, ETH Zurich, Switzerland
* You can contact the authors at <firstname.lastname at ethz dot ch>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef FALSECOLOR_H_
#define FALSECOLOR_H_
#include <opencv2/core/core.hpp>
#include <opencv2/contrib/retina.hpp>
#include <boost/shared_ptr.hpp>
class converter_16_8
{
enum
{
histminmembersperbucket = 10,
};
private:
double max_;
double min_;
static converter_16_8* inst_;
bool firstframe_;
boost::shared_ptr<cv::Retina> retina_;
public:
converter_16_8();
~converter_16_8();
static converter_16_8& Instance()
{
if (!inst_)
{
inst_ = new converter_16_8;
}
return *inst_;
}
double getMax();
double getMin();
void convert_to8bit(const cv::Mat& img16, cv::Mat& img8, bool doTempConversion);
void toneMapping(const cv::Mat& img16, cv::Mat& img8);
};
struct color
{
unsigned char rgbBlue;
unsigned char rgbGreen;
unsigned char rgbRed;
color()
{
rgbBlue = rgbGreen = rgbRed = 0;
}
};
struct palette
{
enum palettetypes{
Linear_red_palettes, GammaLog_red_palettes, Inversion_red_palette, Linear_palettes, GammaLog_palettes,
Inversion_palette, False_color_palette1, False_color_palette2, False_color_palette3, False_color_palette4
};
color colors[256];
};
palette GetPalette(palette::palettetypes pal);
void convertFalseColor(const cv::Mat& srcmat, cv::Mat& dstmat, palette::palettetypes paltype, bool drawlegend = false, double mintemp = 0, double maxtemp = 0);
#endif /* FALSECOLOR_H_ */
| 30.882979 | 159 | 0.738202 |
060209aac1a076b754b493faa869ccae9b00b805 | 10,423 | h | C | Engine/Include/Core/Types/Array.h | SparkyPotato/Ignis | 40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c | [
"MIT"
] | 1 | 2021-02-27T15:42:47.000Z | 2021-02-27T15:42:47.000Z | Engine/Include/Core/Types/Array.h | SparkyPotato/Ignis | 40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c | [
"MIT"
] | null | null | null | Engine/Include/Core/Types/Array.h | SparkyPotato/Ignis | 40cf87c03db7c07d3a05ab2c30bbe4fe3b16156c | [
"MIT"
] | null | null | null | /// Copyright (c) 2021 Shaye Garg.
/// \file
/// Arrays and ArrayRefs.
#pragma once
#include <initializer_list>
#include "Core/Memory/Memory.h"
#include "Core/Memory/RawAllocator.h"
#include "Core/Misc/Assert.h"
#include "Core/Types/Traits.h"
namespace Ignis {
/// View into an Array, SafeArray, SmallArray, or StackArray.
/// You might know it as a Span.
///
/// \tparam T Type of the underlying Array.
template<typename T>
class ArrayRef
{
public:
/// Construct an ArrayRef from a pointer and size.
///
/// \param data Pointer to first element in the sequence.
/// \param size Number of elements in the sequence.
ArrayRef(T* data, u64 size) : m_Data(data), m_Size(size) {}
/// Index.
///
/// \param index The index of the element to access.
///
/// \return The element.
T& operator[](u64 index)
{
IASSERT(index < m_Size, "Out of bounds access in ArrayRef");
return m_Data[index];
}
/// Index.
///
/// \param index The index of the element to access.
///
/// \return The element.
const T& operator[](u64 index) const
{
IASSERT(index < m_Size, "Out of bounds access in ArrayRef");
return m_Data[index];
}
/// Get the size of the view.
///
/// \return The size.
u64 Size() const { return m_Size; }
/// Get the data the view points to.
///
/// \return Pointer to the first element of the view.
const T* Data() const { return m_Data; }
/// Iteration.
///
/// \return Iterator to the first element.
const T* begin() const { return m_Data; }
/// Iteration.
///
/// \return Beyond the end iterator.
const T* end() const { return m_Data + m_Size; }
private:
const T* m_Data = nullptr;
u64 m_Size = 0;
};
template<typename T>
using Span = ArrayRef<T>;
template<typename T>
bool operator==(ArrayRef<T> first, ArrayRef<T> second)
{
if (first.Size() != second.Size())
{
return false;
}
for (u64 i = 0; i < first.Size(); i++)
{
if (first[i] != second[i])
{
return false;
}
}
return true;
}
template<typename T>
bool operator!=(ArrayRef<T> first, ArrayRef<T> second)
{
return !(first == second);
}
/// Dynamically resizing array.
///
/// \tparam T Type to hold in the array.
template<typename T>
class Array
{
public:
/// Construct an Array with an allocator.
///
/// \param alloc Allocator to use for memory allocation. Defaults to the Raw Allocator.
Array(Allocator& alloc = GAlloc) : m_Alloc(&alloc)
{
m_Data = reinterpret_cast<T*>(m_Alloc->Allocate(sizeof(T) * 2));
m_Size = 0;
m_Capacity = 2;
}
/// Create an Array from an ArrayRef.
///
/// \param ref ArrayRef to create the string from.
/// \param alloc Allocator to use for memory allocation. Defaults to the Raw Allocator.
Array(ArrayRef<T> ref, Allocator& alloc = GAlloc) : m_Alloc(&alloc)
{
m_Data = reinterpret_cast<T*>(m_Alloc->Allocate(sizeof(T) * ref.Size()));
m_Size = ref.Size();
m_Capacity = ref.Size();
// Copy elements
for (u64 index = 0; auto& elem : ref)
{
Construct<T>(m_Data + index, elem);
index++;
}
}
/// Create an Array with a size.
///
/// \param size The size of the Array.
/// \param alloc Allocator to use for memory allocation. Defaults to the Raw Allocator.
///
/// \warning This should only be used if you are writing directly to the Array's buffer with Data().
Array(u64 size, Allocator& alloc = GAlloc) : m_Alloc(&alloc)
{
m_Data = reinterpret_cast<T*>(m_Alloc->Allocate(sizeof(T) * size));
m_Size = size;
m_Capacity = size;
}
Array(const std::initializer_list<T>& list, Allocator& alloc = GAlloc) : m_Alloc(&alloc)
{
m_Data = reinterpret_cast<T*>(m_Alloc->Allocate(sizeof(T) * list.size()));
m_Size = list.size();
m_Capacity = list.size();
for (u64 i = 0; const auto& elem : list)
{
Construct<T>(m_Data + i, elem);
i++;
}
}
/// Copy constructor.
///
/// \param other Array to copy.
Array(const Array& other) : m_Alloc(other.m_Alloc)
{
m_Data = reinterpret_cast<T*>(m_Alloc->Allocate(sizeof(T) * other.m_Size));
m_Size = other.m_Size;
m_Capacity = other.m_Capacity;
// Copy elements
for (u64 index = 0; auto& elem : other)
{
Construct<T>(m_Data + index, elem);
index++;
}
}
/// Move constructor.
///
/// \param other Array to move.
Array(Array&& other) : m_Alloc(other.m_Alloc)
{
m_Data = other.m_Data;
m_Size = other.m_Size;
m_Capacity = other.m_Capacity;
other.m_Data = nullptr;
}
/// Destructor.
~Array()
{
if (!m_Data)
{
return;
}
// Destroy objects
for (auto& elem : *this)
{
elem.~T();
}
m_Alloc->Deallocate(m_Data);
}
/// Copy assignment.
///
/// \param other Array to copy.
Array& operator=(const Array& other)
{
// Destroy objects
for (auto& elem : *this)
{
elem.~T();
}
m_Size = 0;
Realloc(other.m_Size);
m_Size = other.m_Size;
// Copy elements
for (u64 index = 0; auto& elem : other)
{
Construct<T>(m_Data + index, elem);
index++;
}
return *this;
}
/// Move assignment.
///
/// \param other Array to move.
Array& operator=(Array&& other)
{
this->~Array<T>();
m_Alloc = other.m_Alloc;
m_Data = other.m_Data;
m_Size = other.m_Size;
m_Capacity = other.m_Capacity;
other.m_Data = nullptr;
return *this;
}
/// Index.
///
/// \param index The index of the element to access.
///
/// \return The element.
T& operator[](u64 index)
{
IASSERT(index < m_Size, "Out of bounds access in Array");
return m_Data[index];
}
/// Index.
///
/// \param index The index of the element to access.
///
/// \return The element.
const T& operator[](u64 index) const
{
IASSERT(index < m_Size, "Out of bounds access in Array");
return m_Data[index];
}
/// Convert the Array into an ArrayRef.
operator ArrayRef<T>() { return ArrayRef<T>(Data(), Size()); }
/// Get the first element of the Array.
///
/// \return Pointer to the first element of the Array.
const T* Data() const { return m_Data; }
/// Get the first element of the Array.
///
/// \return Pointer to the first element of the Array.
T* Data() { return m_Data; }
/// Get the number of elements in the Array.
///
/// \return The number of elements.
u64 Size() const { return m_Size; }
/// Reserve space in the Array.
///
/// \param size The number of elements to reserve space for.
void Reserve(u64 size) { Realloc(size); }
/// Push a copy of an object into the end of the Array.
///
/// \param object Object to push.
///
/// \return Reference to the object in the Array.
T& Push(const T& object)
{
Realloc(m_Size + 1);
auto ptr = Construct<T>(m_Data + m_Size, object);
m_Size++;
return *ptr;
}
/// Push a copy of an object into the end of the Array.
///
/// \param object Object to push.
///
/// \return Reference to the object in the Array.
T& Push(T&& object)
{
Realloc(m_Size + 1);
auto ptr = Construct<T>(m_Data + m_Size, std::move(object));
m_Size++;
return *ptr;
}
/// Construct an object in place at the end of the array.
///
/// \param args Arguments to pass to the constructor.
///
/// \return Constructed object.
template<typename... Args>
T& Emplace(Args&&... args)
{
Realloc(m_Size + 1);
auto ptr = Construct<T>(m_Data + m_Size, static_cast<Args&&>(args)...);
m_Size++;
return *ptr;
}
/// Clear the Array, destroying all elements.
void Clear()
{
for (auto& elem : *this)
{
elem.~T();
}
m_Size = 0;
}
/// Iteration.
///
/// \return Pointer to the first element of the Array.
T* begin() { return m_Data; }
/// Iteration.
///
/// \return Pointer to the first element of the Array.
const T* begin() const { return m_Data; }
/// Iteration.
///
/// \return Pointer to the element after the last element in the Array.
T* end() { return m_Data + m_Size; }
/// Iteration.
///
/// \return Pointer to the element after the last element in the Array.
const T* end() const { return m_Data + m_Size; }
private:
/// Reallocate the vector if the capacity is not enough.
/// Only updates m_Capacity.
///
/// \param size Number of elements required.
void Realloc(u64 size)
{
if (size > m_Capacity)
{
u64 capacity = m_Capacity;
while (capacity < size)
{
capacity *= 2;
}
u64 trySize = m_Alloc->GrowAllocation(m_Data, m_Capacity * sizeof(T), capacity * sizeof(T)) / sizeof(T);
if (trySize < size)
{
auto data = reinterpret_cast<T*>(m_Alloc->Allocate(capacity * sizeof(T)));
MemCopy(data, m_Data, m_Size * sizeof(T));
for (u64 i = 0; auto& elem : *this)
{
Construct<T>(data + i, std::move(elem));
}
m_Alloc->Deallocate(m_Data);
m_Data = data;
m_Capacity = capacity;
}
else
{
m_Capacity = trySize;
}
}
}
Allocator* m_Alloc = nullptr;
T* m_Data = nullptr;
u64 m_Size = 0;
u64 m_Capacity = 0;
};
/// Array on the stack, prefer over Array if size is known at compile-time.
///
/// \tparam T Type to hold in the array.
/// \tparam S Number of elements in the array.
template<typename T, u64 S>
class StackArray
{
public:
StackArray(ArrayRef<T> ref)
{
IASSERT(ref.Size() < S, "Size of StackArray is not large enough");
for (u64 i = 0; i < ref.Size(); i++)
{
m_Array[i] = ref[i];
}
}
/// Index.
///
/// \param index The index of the element to access.
///
/// \return The element.
T& operator[](u64 index)
{
IASSERT(index < S, "Access out of range!");
return m_Array[index];
}
/// Index.
///
/// \param index The index of the element to access.
///
/// \return The element.
const T& operator[](u64 index) const
{
IASSERT(index < S, "Access out of range!");
return m_Array[index];
}
operator ArrayRef<T>() { return ArrayRef<T>(m_Array, S); }
/// Iteration.
///
/// \return Pointer to the first element of the Array.
T* begin() { return m_Array; }
/// Iteration.
///
/// \return Pointer to the first element of the Array.
const T* begin() const { return m_Array; }
/// Iteration.
///
/// \return Pointer to the element after the last element in the Array.
T* end() { return m_Array + S; }
/// Iteration.
///
/// \return Pointer to the element after the last element in the Array.
const T* end() const { return m_Array + S; }
private:
T m_Array[S];
};
/// Array on the stack, up to S elements,
/// but switches over to dynamic allocation if the elements exceed S.
///
/// \tparam T Type to hold in the array.
/// \tparam S Number of elements to hold on the stack.
template<typename T, u64 S = 16>
class SmallArray
{
};
}
| 21.535124 | 107 | 0.634366 |
ff41cdff020a725e2be8ab5abba63c6174365e66 | 4,980 | h | C | dyn_array.h | xexyl/mkiocccentry | 4df499940f269cbd2f2b6d733f29cf5b213bd2ad | [
"Unlicense"
] | 12 | 2021-12-28T20:37:08.000Z | 2022-02-27T10:12:35.000Z | dyn_array.h | xexyl/mkiocccentry | 4df499940f269cbd2f2b6d733f29cf5b213bd2ad | [
"Unlicense"
] | 130 | 2022-01-16T05:50:35.000Z | 2022-03-31T22:11:29.000Z | dyn_array.h | xexyl/mkiocccentry | 4df499940f269cbd2f2b6d733f29cf5b213bd2ad | [
"Unlicense"
] | 14 | 2022-01-16T06:05:49.000Z | 2022-03-02T11:11:26.000Z | /*
* dyn_array - dynamic array facility
*
* Copyright (c) 2014,2015,2022 by Landon Curt Noll. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose and without fee is hereby granted,
* provided that the above copyright, this permission notice and text
* this comment, and the disclaimer below appear in all of the following:
*
* supporting documentation
* source copies
* source works derived from this source
* binaries derived from this source or from derived source
*
* LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
* EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* chongo (Landon Curt Noll, http://www.isthe.com/chongo/index.html) /\oo/\
*
* Share and enjoy! :-)
*/
#if !defined(INCLUDE_DYN_ARRAY_H)
# define INCLUDE_DYN_ARRAY_H
#include <stdint.h>
/*
* util - utility functions and variable types (like bool)
*/
#if defined(STAND_ALONE)
#if !defined(SIZE_MAX)
#define SIZE_MAX (~((size_t)0))
#endif /* SIZE_MAX */
#if !defined(SIZE_MIN)
#define SIZE_MIN ((size_t)(0))
#endif /* SIZE_MIN */
#else /* STAND_ALONE */
#include "util.h"
#endif /* STAND_ALONE */
/*
* dbg - debug, warning and error reporting facility
*/
#include "dbg.h"
/*
* dynamic array convenience macros
*
* Obtain an element in a dynamic array:
*
* struct dyn_array *array_p;
* double value;
*
* value = dyn_array_value(array_p, double, i);
*
* Obtain the address of an element in a dynamic array:
*
* struct dyn_array *array_p;
* struct json *addr;
*
* addr = dyn_array_addr(array_p, struct json, i);
*
* Current element count of dynamic array:
*
* struct dyn_array *array_p;
* intmax_t pos;
*
* pos = dyn_array_tell(array_p);
*
* Address of the element just beyond the elements in use:
*
* struct dyn_array *array_p;
* struct json_member *next;
*
* next = dyn_array_beyond(array_p, struct json_member);
*
* Number of elements allocated in memory for the dynamic array:
*
* struct dyn_array *array_p;
* intmax_t size;
*
* size = dyn_array_alloced(array_p);
*
* Number of elements available (allocated but not in use) for the dynamic array:
*
* struct dyn_array *array_p;
* intmax_t avail;
*
* avail = dyn_array_avail(array_p);
*
* Rewind a dynamic array back to zero elements:
*
* struct dyn_array *array_p;
*
* dyn_array_rewind(array_p);
*/
#define dyn_array_value(array_p, type, index) (((type *)(((struct dyn_array *)(array_p))->data))[(index)])
#define dyn_array_addr(array_p, type, index) (((type *)(((struct dyn_array *)(array_p))->data))+(index))
#define dyn_array_tell(array_p) (((struct dyn_array *)(array_p))->count)
#define dyn_array_beyond(array_p, type) (dyn_array_addr(array_p, type, dyn_array_tell(array_p)))
#define dyn_array_alloced(array_p) (((struct dyn_array *)(array_p))->allocated)
#define dyn_array_avail(array_p) (dyn_array_alloced(array_p) - dyn_array_tell(array_p))
#define dyn_array_rewind(array_p) (dyn_array_seek((struct dyn_array *)(array_p), 0, SEEK_SET))
/*
* array - a dynamic array of identical elements
*
* The dynamic array maintains both an allocated element count
* and a number of elements in use.
*
* The actual storage allocated will be a number of elements
* beyond the allocated element count, to serve as a guard chunk.
*
* If zeroize is true, then all allocated elements will be
* zeroized when first allocated, and zeroized when dyn_array_free()
* is called.
*/
struct dyn_array {
size_t elm_size; /* Number of bytes for a single element */
bool zeroize; /* true ==> always zero newly allocated chunks, false ==> don't */
intmax_t count; /* Number of elements in use */
intmax_t allocated; /* Number of elements allocated (>= count) */
intmax_t chunk; /* Number of elements to expand by when allocating */
void *data; /* allocated dynamic array of identical things or NULL */
};
/*
* external allocation functions
*/
extern struct dyn_array *dyn_array_create(size_t elm_size, intmax_t chunk, intmax_t start_elm_count, bool zeroize);
extern bool dyn_array_append_value(struct dyn_array *array, void *value_to_add);
extern bool dyn_array_append_set(struct dyn_array *array, void *array_to_add_p, intmax_t count_of_elements_to_add);
extern bool dyn_array_concat_array(struct dyn_array *array, struct dyn_array *other);
extern bool dyn_array_seek(struct dyn_array *array, off_t offset, int whence);
extern void dyn_array_clear(struct dyn_array *array);
extern void dyn_array_free(struct dyn_array *array);
#endif /* INCLUDE_DYN_ARRAY_H */
| 32.54902 | 115 | 0.725502 |
9eaef56878760f72c1966ab02621991d06534d27 | 334 | c | C | d/koenig/weapon/broad.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/koenig/weapon/broad.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/koenig/weapon/broad.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | inherit "/std/weapon";
create() {
::create();
set_id(({ "sword", "broad sword", "broad" }));
set_name("broad");
set_short("A broad sword");
set_long(
"This is a shiny, well kept broad sword. "
);
set_weight(4);
set_size(2);
set("value", 10);
set_wc(2,4);
set_large_wc(1,6);
set_type("slash");
}
| 18.555556 | 49 | 0.568862 |
7fb8b81654291c8a65894f2b7de688b9d48bf60c | 4,808 | h | C | libMXF++/File.h | Limecraft/ebu-libmxfpp | 8148d928a13c13738dcc95c328c3609322d67203 | [
"BSD-3-Clause"
] | 4 | 2015-06-09T22:02:39.000Z | 2021-04-13T20:48:53.000Z | libMXF++/File.h | Limecraft/ebu-libmxfpp | 8148d928a13c13738dcc95c328c3609322d67203 | [
"BSD-3-Clause"
] | null | null | null | libMXF++/File.h | Limecraft/ebu-libmxfpp | 8148d928a13c13738dcc95c328c3609322d67203 | [
"BSD-3-Clause"
] | 1 | 2021-07-09T19:53:27.000Z | 2021-07-09T19:53:27.000Z | /*
* Copyright (C) 2008, British Broadcasting Corporation
* All Rights Reserved.
*
* Author: Philip de Nier
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the British Broadcasting Corporation nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MXFPP_FILE_H_
#define MXFPP_FILE_H_
#include <string>
#include <vector>
#include <libMXF++/Partition.h>
#include <mxf/mxf_memory_file.h>
namespace mxfpp
{
class File
{
public:
static File* openNew(std::string filename);
static File* openRead(std::string filename);
static File* openModify(std::string filename);
public:
File(::MXFFile* _cFile);
~File();
void setMinLLen(uint8_t llen);
uint8_t getMinLLen();
Partition& createPartition();
Partition& insertPartition(size_t index);
void writeRIP();
void updatePartitions();
void updateBodyPartitions(const mxfKey *pp_key);
void updateGenericStreamPartitions();
void updatePartitions(size_t rewriteFirstIndex, size_t rewriteLastIndex);
Partition& getPartition(size_t index);
const std::vector<Partition*>& getPartitions() const { return _partitions; }
bool readHeaderPartition();
bool readPartitions();
void readNextPartition(const mxfKey *key, uint64_t len);
uint8_t readUInt8();
uint16_t readUInt16();
uint32_t readUInt32();
uint64_t readUInt64();
int8_t readInt8();
int16_t readInt16();
int32_t readInt32();
int64_t readInt64();
void readK(mxfKey *key);
void readL(uint8_t *llen, uint64_t *len);
void readKL(mxfKey *key, uint8_t *llen, uint64_t *len);
void readNextNonFillerKL(mxfKey *key, uint8_t *llen, uint64_t *len);
void readLocalTL(mxfLocalTag *tag, uint16_t *len);
void readBatchHeader(uint32_t *len, uint32_t *elementLen);
uint32_t read(unsigned char *data, uint32_t count);
int64_t tell();
void seek(int64_t position, int whence);
void skip(uint64_t len);
int64_t size();
bool eof();
bool isSeekable();
uint32_t write(const unsigned char *data, uint32_t count);
void writeUInt8(uint8_t value);
void writeUInt16(uint16_t value);
void writeUInt32(uint32_t value);
void writeUInt64(uint64_t value);
void writeInt8(int8_t value);
void writeInt16(int16_t value);
void writeInt32(int32_t value);
void writeInt64(int64_t value);
void writeUL(const mxfUL *ul);
void writeKL(const mxfKey *key, uint64_t len);
void writeFixedL(uint8_t llen, uint64_t len);
void writeFixedKL(const mxfKey *key, uint8_t llen, uint64_t len);
void writeBatchHeader(uint32_t len, uint32_t eleLen);
void writeArrayHeader(uint32_t len, uint32_t eleLen);
void writeZeros(uint64_t len);
void fillToPosition(uint64_t position);
void writeFill(uint32_t size);
void openMemoryFile(uint32_t chunkSize);
void setMemoryPartitionIndexes(size_t first, size_t last = (size_t)(-1));
bool isMemoryFileOpen() const { return _cMemoryFile != 0; }
void closeMemoryFile();
void setMemoryFile(MXFMemoryFile *memFile);
::MXFFile* swapCFile(::MXFFile *newCFile);
::MXFFile* getCFile() const { return _cFile; }
private:
std::vector<Partition*> _partitions;
::MXFFile *_cFile;
::MXFFile *_cOriginalFile;
MXFMemoryFile *_cMemoryFile;
size_t _firstMemoryPartitionIndex;
size_t _lastMemoryPartitionIndex;
};
};
#endif
| 31.019355 | 80 | 0.72421 |
cfa65093d78f0d6d24973133c1f3acae55f64931 | 261 | h | C | rt-boot/common/include/reboot/reboot.h | MagicPrince666/rt-boot | 2ecfcd35c2fcd94db33acbcb4c83b357ed3d7625 | [
"MIT"
] | 97 | 2018-11-17T19:06:39.000Z | 2022-03-24T16:44:40.000Z | rt-boot/common/include/reboot/reboot.h | MagicPrince666/rt-boot | 2ecfcd35c2fcd94db33acbcb4c83b357ed3d7625 | [
"MIT"
] | 5 | 2018-11-18T15:39:06.000Z | 2019-10-30T05:22:52.000Z | rt-boot/common/include/reboot/reboot.h | MagicPrince666/rt-boot | 2ecfcd35c2fcd94db33acbcb4c83b357ed3d7625 | [
"MIT"
] | 43 | 2018-11-19T15:37:44.000Z | 2022-01-05T03:08:11.000Z | /*
* SOC common registers and helper function/macro definitions
*
* Copyright (C) 2016 Piotr Dymacz <piotr@dymacz.pl>
*
* SPDX-License-Identifier: GPL-2.0
*/
#ifndef __REBOOT_H_
#define __REBOOT_H_
void system_reboot(void);
#endif /* _SOC_COMMON_H_ */
| 17.4 | 61 | 0.724138 |
36f661a8617340c50d413248161a4c4d3acecefe | 3,796 | h | C | breakpad/src/processor/basic_code_modules.h | cvsuser-chromium/chromium | acb8e8e4a7157005f527905b48dd48ddaa3b863a | [
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | src/oslibs/google_breakpad/google-breakpad-read-only/src/processor/basic_code_modules.h | dios-game/dios | ce947382bcc8692ea70533d6def112a2838a9d0e | [
"MIT"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | breakpad/src/processor/basic_code_modules.h | cvsuser-chromium/chromium | acb8e8e4a7157005f527905b48dd48ddaa3b863a | [
"BSD-3-Clause"
] | 4 | 2017-04-05T01:52:03.000Z | 2022-02-13T17:58:45.000Z | // Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// basic_code_modules.h: Contains all of the CodeModule objects that
// were loaded into a single process.
//
// This is a basic concrete implementation of CodeModules. It cannot be
// instantiated directly, only based on other objects that implement
// the CodeModules interface. It exists to provide a CodeModules
// implementation a place to store information when the life of the original
// object (such as a MinidumpModuleList) cannot be guaranteed.
//
// Author: Mark Mentovai
#ifndef PROCESSOR_BASIC_CODE_MODULES_H__
#define PROCESSOR_BASIC_CODE_MODULES_H__
#include "google_breakpad/processor/code_modules.h"
namespace google_breakpad {
template<typename T> class linked_ptr;
template<typename AddressType, typename EntryType> class RangeMap;
class BasicCodeModules : public CodeModules {
public:
// Creates a new BasicCodeModules object given any existing CodeModules
// implementation. This is useful to make a copy of the data relevant to
// the CodeModules and CodeModule interfaces without requiring all of the
// resources that other implementations may require. A copy will be
// made of each contained CodeModule using CodeModule::Copy.
explicit BasicCodeModules(const CodeModules *that);
virtual ~BasicCodeModules();
// See code_modules.h for descriptions of these methods.
virtual unsigned int module_count() const;
virtual const CodeModule* GetModuleForAddress(uint64_t address) const;
virtual const CodeModule* GetMainModule() const;
virtual const CodeModule* GetModuleAtSequence(unsigned int sequence) const;
virtual const CodeModule* GetModuleAtIndex(unsigned int index) const;
virtual const CodeModules* Copy() const;
private:
// The base address of the main module.
uint64_t main_address_;
// The map used to contain each CodeModule, keyed by each CodeModule's
// address range.
RangeMap<uint64_t, linked_ptr<const CodeModule> > *map_;
// Disallow copy constructor and assignment operator.
BasicCodeModules(const BasicCodeModules &that);
void operator=(const BasicCodeModules &that);
};
} // namespace google_breakpad
#endif // PROCESSOR_BASIC_CODE_MODULES_H__
| 44.139535 | 78 | 0.760537 |
2c9c2520325090ad0790fb3367601a948d300581 | 11,632 | c | C | Source/Lib/Codec/EbPictureOperators.c | EwoutH/SVT-VP9 | 39bb49adfd63a34797c368a5937db0cb414d00c0 | [
"BSD-2-Clause-Patent"
] | null | null | null | Source/Lib/Codec/EbPictureOperators.c | EwoutH/SVT-VP9 | 39bb49adfd63a34797c368a5937db0cb414d00c0 | [
"BSD-2-Clause-Patent"
] | null | null | null | Source/Lib/Codec/EbPictureOperators.c | EwoutH/SVT-VP9 | 39bb49adfd63a34797c368a5937db0cb414d00c0 | [
"BSD-2-Clause-Patent"
] | 1 | 2020-01-30T17:40:00.000Z | 2020-01-30T17:40:00.000Z | /*
* Copyright(c) 2019 Intel Corporation
* SPDX - License - Identifier: BSD - 2 - Clause - Patent
*/
/*********************************
* Includes
*********************************/
#include "EbPictureOperators.h"
#define VARIANCE_PRECISION 16
#define MEAN_PRECISION (VARIANCE_PRECISION >> 1)
#include "EbDefinitions.h"
#include "EbPackUnPack.h"
/*********************************
* x86 implememtation of Picture Addition
*********************************/
void picture_addition(
uint8_t *pred_ptr,
uint32_t pred_stride,
int16_t *residual_ptr,
uint32_t residual_stride,
uint8_t *recon_ptr,
uint32_t recon_stride,
uint32_t width,
uint32_t height)
{
addition_kernel_func_ptr_array[(ASM_TYPES & PREAVX2_MASK) && 1][width >> 3](
pred_ptr,
pred_stride,
residual_ptr,
residual_stride,
recon_ptr,
recon_stride,
width,
height
);
return;
}
/*********************************
* Picture Copy 8bit Elements
*********************************/
EbErrorType picture_copy8_bit(
EbPictureBufferDesc *src,
uint32_t src_luma_origin_index,
uint32_t src_chroma_origin_index,
EbPictureBufferDesc *dst,
uint32_t dst_luma_origin_index,
uint32_t dst_chroma_origin_index,
uint32_t area_width,
uint32_t area_height,
uint32_t chroma_area_width,
uint32_t chroma_area_height,
uint32_t component_mask)
{
EbErrorType return_error = EB_ErrorNone;
// Execute the Kernels
if (component_mask & PICTURE_BUFFER_DESC_Y_FLAG) {
pic_copy_kernel_func_ptr_array[(ASM_TYPES & PREAVX2_MASK) && 1][area_width>>3](
&(src->buffer_y[src_luma_origin_index]),
src->stride_y,
&(dst->buffer_y[dst_luma_origin_index]),
dst->stride_y,
area_width,
area_height);
}
if (component_mask & PICTURE_BUFFER_DESC_Cb_FLAG) {
pic_copy_kernel_func_ptr_array[(ASM_TYPES & PREAVX2_MASK) && 1][chroma_area_width >> 3](
&(src->buffer_cb[src_chroma_origin_index]),
src->stride_cb,
&(dst->buffer_cb[dst_chroma_origin_index]),
dst->stride_cb,
chroma_area_width,
chroma_area_height);
}
if (component_mask & PICTURE_BUFFER_DESC_Cr_FLAG) {
pic_copy_kernel_func_ptr_array[(ASM_TYPES & PREAVX2_MASK) && 1][chroma_area_width >> 3](
&(src->buffer_cr[src_chroma_origin_index]),
src->stride_cr,
&(dst->buffer_cr[dst_chroma_origin_index]),
dst->stride_cr,
chroma_area_width,
chroma_area_height);
}
return return_error;
}
/*******************************************
* Picture Residue : subsampled version
Computes the residual data
*******************************************/
void picture_sub_sampled_residual(
uint8_t *input,
uint32_t input_stride,
uint8_t *pred,
uint32_t pred_stride,
int16_t *residual,
uint32_t residual_stride,
uint32_t area_width,
uint32_t area_height,
uint8_t last_line) //the last line has correct prediction data, so no duplication to be done.
{
residual_kernel_sub_sampled_func_ptr_array[(ASM_TYPES & PREAVX2_MASK) && 1][area_width>>3](
input,
input_stride,
pred,
pred_stride,
residual,
residual_stride,
area_width,
area_height,
last_line);
return;
}
/*******************************************
* Pciture Residue
Computes the residual data
*******************************************/
void picture_residual(
uint8_t *input,
uint32_t input_stride,
uint8_t *pred,
uint32_t pred_stride,
int16_t *residual,
uint32_t residual_stride,
uint32_t area_width,
uint32_t area_height)
{
residual_kernel_func_ptr_array[(ASM_TYPES & PREAVX2_MASK) && 1][area_width>>3](
input,
input_stride,
pred,
pred_stride,
residual,
residual_stride,
area_width,
area_height);
return;
}
/*******************************************
* Pciture Residue 16bit input
Computes the residual data
*******************************************/
void picture_residual16bit(
uint16_t *input,
uint32_t input_stride,
uint16_t *pred,
uint32_t pred_stride,
int16_t *residual,
uint32_t residual_stride,
uint32_t area_width,
uint32_t area_height)
{
residual_kernel_func_ptr_array16_bit[(ASM_TYPES & PREAVX2_MASK) && 1](
input,
input_stride,
pred,
pred_stride,
residual,
residual_stride,
area_width,
area_height);
return;
}
/*******************************************
* Picture Full Distortion
* Used in the Full Mode Decision Loop
*******************************************/
EbErrorType picture_full_distortion(
EbPictureBufferDesc *coeff,
uint32_t coeff_origin_index,
EbPictureBufferDesc *recon_coeff,
uint32_t recon_coeff_origin_index,
uint32_t area_size,
uint64_t distortion[DIST_CALC_TOTAL],
uint32_t eob)
{
EbErrorType return_error = EB_ErrorNone;
//TODO due to a change in full kernel distortion , ASM has to be updated to not accumulate the input distortion by the output
distortion[0] = 0;
distortion[1] = 0;
// Y
full_distortion_intrinsic_func_ptr_array[(ASM_TYPES & PREAVX2_MASK) && 1][eob != 0][0][area_size >> 3](
&(((int16_t*) coeff->buffer_y)[coeff_origin_index]),
coeff->stride_y,
&(((int16_t*) recon_coeff->buffer_y)[recon_coeff_origin_index]),
recon_coeff->stride_y,
distortion,
area_size,
area_size);
return return_error;
}
void extract_8bit_data(
uint16_t *in16_bit_buffer,
uint32_t in_stride,
uint8_t *out8_bit_buffer,
uint32_t out8_stride,
uint32_t width,
uint32_t height
)
{
unpack_8bit_func_ptr_array_16bit[((width & 3) == 0) && ((height & 1)== 0)][(ASM_TYPES & PREAVX2_MASK) && 1](
in16_bit_buffer,
in_stride,
out8_bit_buffer,
out8_stride,
width,
height);
}
void unpack_l0l1_avg(
uint16_t *ref16_l0,
uint32_t ref_l0_stride,
uint16_t *ref16_l1,
uint32_t ref_l1_stride,
uint8_t *dst_ptr,
uint32_t dst_stride,
uint32_t width,
uint32_t height)
{
unpack_avg_func_ptr_array[(ASM_TYPES & AVX2_MASK) && 1](
ref16_l0,
ref_l0_stride,
ref16_l1,
ref_l1_stride,
dst_ptr,
dst_stride,
width,
height);
}
void extract8_bitdata_safe_sub(
uint16_t *in16_bit_buffer,
uint32_t in_stride,
uint8_t *out8_bit_buffer,
uint32_t out8_stride,
uint32_t width,
uint32_t height
)
{
unpack_8bit_safe_sub_func_ptr_array_16bit[(ASM_TYPES & AVX2_MASK) && 1](
in16_bit_buffer,
in_stride,
out8_bit_buffer,
out8_stride,
width,
height
);
}
void unpack_l0l1_avg_safe_sub(
uint16_t *ref16_l0,
uint32_t ref_l0_stride,
uint16_t *ref16_l1,
uint32_t ref_l1_stride,
uint8_t *dst_ptr,
uint32_t dst_stride,
uint32_t width,
uint32_t height)
{
//fix C
unpack_avg_safe_sub_func_ptr_array[(ASM_TYPES & AVX2_MASK) && 1](
ref16_l0,
ref_l0_stride,
ref16_l1,
ref_l1_stride,
dst_ptr,
dst_stride,
width,
height);
}
void unpack_2d(
uint16_t *in16_bit_buffer,
uint32_t in_stride,
uint8_t *out8_bit_buffer,
uint32_t out8_stride,
uint8_t *outn_bit_buffer,
uint32_t outn_stride,
uint32_t width,
uint32_t height
)
{
unpack2_d_func_ptr_array_16_bit[((width & 3) == 0) && ((height & 1)== 0)][(ASM_TYPES & AVX2_MASK) && 1](
in16_bit_buffer,
in_stride,
out8_bit_buffer,
outn_bit_buffer,
out8_stride,
outn_stride,
width,
height);
}
void pack_2d_src(
uint8_t *in8_bit_buffer,
uint32_t in8_stride,
uint8_t *inn_bit_buffer,
uint32_t inn_stride,
uint16_t *out16_bit_buffer,
uint32_t out_stride,
uint32_t width,
uint32_t height
)
{
pack2_d_func_ptr_array_16_bit_src[((width & 3) == 0) && ((height & 1)== 0)][(ASM_TYPES & AVX2_MASK) && 1](
in8_bit_buffer,
in8_stride,
inn_bit_buffer,
out16_bit_buffer,
inn_stride,
out_stride,
width,
height);
}
void compressed_pack_sb(
uint8_t *in8_bit_buffer,
uint32_t in8_stride,
uint8_t *inn_bit_buffer,
uint32_t inn_stride,
uint16_t *out16_bit_buffer,
uint32_t out_stride,
uint32_t width,
uint32_t height
)
{
compressed_pack_func_ptr_array[((width == 64 || width == 32) ? ((ASM_TYPES & AVX2_MASK) && 1) : ASM_NON_AVX2)](
in8_bit_buffer,
in8_stride,
inn_bit_buffer,
out16_bit_buffer,
inn_stride,
out_stride,
width,
height);
}
void compressed_pack_blk(
uint8_t *in8_bit_buffer,
uint32_t in8_stride,
uint8_t *inn_bit_buffer,
uint32_t inn_stride,
uint16_t *out16_bit_buffer,
uint32_t out_stride,
uint32_t width,
uint32_t height
)
{
compressed_pack_func_ptr_array[((width == 64 || width == 32 || width == 16 || width == 8) ? ((ASM_TYPES & AVX2_MASK) && 1) : ASM_NON_AVX2)](
in8_bit_buffer,
in8_stride,
inn_bit_buffer,
out16_bit_buffer,
inn_stride,
out_stride,
width,
height);
}
void conv2b_to_c_pack_sb(
const uint8_t *inn_bit_buffer,
uint32_t inn_stride,
uint8_t *in_compn_bit_buffer,
uint32_t out_stride,
uint8_t *local_cache,
uint32_t width,
uint32_t height)
{
convert_unpack_c_pack_func_ptr_array[((width == 64 || width == 32) ? ((ASM_TYPES & AVX2_MASK) && 1) : ASM_NON_AVX2)](
inn_bit_buffer,
inn_stride,
in_compn_bit_buffer,
out_stride,
local_cache,
width,
height);
}
/*******************************************
* memset16bit
*******************************************/
void memset16bit(
uint16_t *in_ptr,
uint16_t value,
uint64_t num_of_elements )
{
uint64_t i;
for(i = 0; i < num_of_elements; i++) {
in_ptr[i] = value;
}
}
/*******************************************
* memcpy16bit
*******************************************/
void memcpy16bit(
uint16_t *out_ptr,
uint16_t *in_ptr,
uint64_t num_of_elements )
{
uint64_t i;
for( i =0; i<num_of_elements; i++) {
out_ptr[i] = in_ptr[i] ;
}
}
int32_t sum_residual(
int16_t *in_ptr,
uint32_t size,
uint32_t stride_in )
{
int32_t sum_block = 0;
uint32_t i,j;
for(j=0; j<size; j++)
for(i=0; i<size; i++)
sum_block+=in_ptr[j*stride_in + i];
return sum_block;
}
void memset_16bit_block (
int16_t *in_ptr,
uint32_t stride_in,
uint32_t size,
int16_t value)
{
uint32_t i;
for (i = 0; i < size; i++)
memset16bit((uint16_t*)in_ptr + i*stride_in, value, size);
}
| 24.233333 | 144 | 0.57273 |
2cd6cbd6ef1b58f3643734cd485e1eb7cd558e4a | 838 | h | C | Retro Virtual Machine/ViewControllers/rvmMachinesCollectionViewController.h | jcgamestoy/retrovm1 | 8d03a8d7f8e7483815c24493bc53c56ced13872f | [
"MIT"
] | 5 | 2021-08-31T14:21:42.000Z | 2021-09-19T11:22:54.000Z | Retro Virtual Machine/ViewControllers/rvmMachinesCollectionViewController.h | jcgamestoy/retrovm1 | 8d03a8d7f8e7483815c24493bc53c56ced13872f | [
"MIT"
] | null | null | null | Retro Virtual Machine/ViewControllers/rvmMachinesCollectionViewController.h | jcgamestoy/retrovm1 | 8d03a8d7f8e7483815c24493bc53c56ced13872f | [
"MIT"
] | null | null | null | //
// rvmMachinesCollectionViewController.h
// Retro Virtual Machine
//
// Created by Juan Carlos González Amestoy on 24/03/14.
// Copyright (c) 2014 Juan Carlos González Amestoy. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "rvmNavigationItemViewController.h"
#import "rvmSimpleCollectionView.h"
#import "rvmArchitecture.h"
@interface rvmMachinesCollectionViewController : rvmNavigationItemViewController<rvmSimpleCollectionViewDelegateProtocol>
@property NSMutableArray *recentMachines;
@property NSMutableArray *machinesDocuments;
@property (strong) IBOutlet rvmSimpleCollectionView *collection;
-(void)machineRunning:(rvmArchitecture*)doc;
-(void)machineStopped:(rvmArchitecture*)doc;
-(void)openDocument:(id)sender;
-(void)openFile:(NSURL*)filename;
-(IBAction)onClearRecent:(id)sender;
-(void)checkUpdate;
@end
| 28.896552 | 121 | 0.801909 |
32901a24546f5913b67cdced816f002de9edc6e3 | 13,216 | c | C | release/src/router/pppd/pppd/session.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src/router/pppd/pppd/session.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src/router/pppd/pppd/session.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | /*
* session.c - PPP session control.
*
* Copyright (c) 2007 Diego Rivera. 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <paulus@samba.org>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Derived from auth.c, which is:
*
* Copyright (c) 1984-2000 Carnegie Mellon University. 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. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Office of Technology Transfer
* Carnegie Mellon University
* 5000 Forbes Avenue
* Pittsburgh, PA 15213-3890
* (412) 268-4387, fax: (412) 268-7395
* tech-transfer@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <crypt.h>
#ifdef HAS_SHADOW
#include <shadow.h>
#endif
#include <time.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include "pppd.h"
#include "session.h"
#ifdef USE_PAM
#include <security/pam_appl.h>
#endif /* #ifdef USE_PAM */
#define SET_MSG(var, msg) if (var != NULL) { var[0] = msg; }
#define COPY_STRING(s) ((s) ? strdup(s) : NULL)
#define SUCCESS_MSG "Session started successfully"
#define ABORT_MSG "Session can't be started without a username"
#define SERVICE_NAME "ppp"
#define SESSION_FAILED 0
#define SESSION_OK 1
/* We have successfully started a session */
static bool logged_in = 0;
#ifdef USE_PAM
/*
* Static variables used to communicate between the conversation function
* and the server_login function
*/
static const char *PAM_username;
static const char *PAM_password;
static int PAM_session = 0;
static pam_handle_t *pamh = NULL;
/* PAM conversation function
* Here we assume (for now, at least) that echo on means login name, and
* echo off means password.
*/
static int conversation (int num_msg,
#ifndef SOL2
const
#endif
struct pam_message **msg,
struct pam_response **resp, void *appdata_ptr)
{
int replies = 0;
struct pam_response *reply = NULL;
reply = malloc(sizeof(struct pam_response) * num_msg);
if (!reply) return PAM_CONV_ERR;
for (replies = 0; replies < num_msg; replies++) {
switch (msg[replies]->msg_style) {
case PAM_PROMPT_ECHO_ON:
reply[replies].resp_retcode = PAM_SUCCESS;
reply[replies].resp = COPY_STRING(PAM_username);
/* PAM frees resp */
break;
case PAM_PROMPT_ECHO_OFF:
reply[replies].resp_retcode = PAM_SUCCESS;
reply[replies].resp = COPY_STRING(PAM_password);
/* PAM frees resp */
break;
case PAM_TEXT_INFO:
/* fall through */
case PAM_ERROR_MSG:
/* ignore it, but pam still wants a NULL response... */
reply[replies].resp_retcode = PAM_SUCCESS;
reply[replies].resp = NULL;
break;
default:
/* Must be an error of some sort... */
free (reply);
return PAM_CONV_ERR;
}
}
*resp = reply;
return PAM_SUCCESS;
}
static struct pam_conv pam_conv_data = {
&conversation,
NULL
};
#endif /* #ifdef USE_PAM */
int
session_start(flags, user, passwd, ttyName, msg)
const int flags;
const char *user;
const char *passwd;
const char *ttyName;
char **msg;
{
#ifdef USE_PAM
bool ok = 1;
const char *usr;
int pam_error;
bool try_session = 0;
#else /* #ifdef USE_PAM */
struct passwd *pw;
#ifdef HAS_SHADOW
struct spwd *spwd;
struct spwd *getspnam();
long now = 0;
#endif /* #ifdef HAS_SHADOW */
#endif /* #ifdef USE_PAM */
SET_MSG(msg, SUCCESS_MSG);
/* If no verification is requested, then simply return an OK */
if (!(SESS_ALL & flags)) {
return SESSION_OK;
}
if (user == NULL) {
SET_MSG(msg, ABORT_MSG);
return SESSION_FAILED;
}
#ifdef USE_PAM
/* Find the '\\' in the username */
/* This needs to be fixed to support different username schemes */
if ((usr = strchr(user, '\\')) == NULL)
usr = user;
else
usr++;
PAM_session = 0;
PAM_username = usr;
PAM_password = passwd;
dbglog("Initializing PAM (%d) for user %s", flags, usr);
pam_error = pam_start (SERVICE_NAME, usr, &pam_conv_data, &pamh);
dbglog("---> PAM INIT Result = %d", pam_error);
ok = (pam_error == PAM_SUCCESS);
if (ok) {
ok = (pam_set_item(pamh, PAM_TTY, ttyName) == PAM_SUCCESS) &&
(pam_set_item(pamh, PAM_RHOST, ifname) == PAM_SUCCESS);
}
if (ok && (SESS_AUTH & flags)) {
dbglog("Attempting PAM authentication");
pam_error = pam_authenticate (pamh, PAM_SILENT);
if (pam_error == PAM_SUCCESS) {
/* PAM auth was OK */
dbglog("PAM Authentication OK for %s", user);
} else {
/* No matter the reason, we fail because we're authenticating */
ok = 0;
if (pam_error == PAM_USER_UNKNOWN) {
dbglog("User unknown, failing PAM authentication");
SET_MSG(msg, "User unknown - cannot authenticate via PAM");
} else {
/* Any other error means authentication was bad */
dbglog("PAM Authentication failed: %d: %s", pam_error,
pam_strerror(pamh, pam_error));
SET_MSG(msg, (char *) pam_strerror (pamh, pam_error));
}
}
}
if (ok && (SESS_ACCT & flags)) {
dbglog("Attempting PAM account checks");
pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
if (pam_error == PAM_SUCCESS) {
/*
* PAM account was OK, set the flag which indicates that we should
* try to perform the session checks.
*/
try_session = 1;
dbglog("PAM Account OK for %s", user);
} else {
/*
* If the account checks fail, then we should not try to perform
* the session check, because they don't make sense.
*/
try_session = 0;
if (pam_error == PAM_USER_UNKNOWN) {
/*
* We're checking the account, so it's ok to not have one
* because the user might come from the secrets files, or some
* other plugin.
*/
dbglog("User unknown, ignoring PAM restrictions");
SET_MSG(msg, "User unknown - ignoring PAM restrictions");
} else {
/* Any other error means session is rejected */
ok = 0;
dbglog("PAM Account checks failed: %d: %s", pam_error,
pam_strerror(pamh, pam_error));
SET_MSG(msg, (char *) pam_strerror (pamh, pam_error));
}
}
}
if (ok && try_session && (SESS_ACCT & flags)) {
/* Only open a session if the user's account was found */
pam_error = pam_open_session (pamh, PAM_SILENT);
if (pam_error == PAM_SUCCESS) {
dbglog("PAM Session opened for user %s", user);
PAM_session = 1;
} else {
dbglog("PAM Session denied for user %s", user);
SET_MSG(msg, (char *) pam_strerror (pamh, pam_error));
ok = 0;
}
}
/* This is needed because apparently the PAM stuff closes the log */
reopen_log();
/* If our PAM checks have already failed, then we must return a failure */
if (!ok) return SESSION_FAILED;
#else /* #ifdef USE_PAM */
/*
* Use the non-PAM methods directly. 'pw' will remain NULL if the user
* has not been authenticated using local UNIX system services.
*/
pw = NULL;
if ((SESS_AUTH & flags)) {
pw = getpwnam(user);
endpwent();
/*
* Here, we bail if we have no user account, because there is nothing
* to verify against.
*/
if (pw == NULL)
return SESSION_FAILED;
#ifdef HAS_SHADOW
spwd = getspnam(user);
endspent();
/*
* If there is no shadow entry for the user, then we can't verify the
* account.
*/
if (spwd == NULL)
return SESSION_FAILED;
/*
* We check validity all the time, because if the password has expired,
* then clearly we should not authenticate against it (if we're being
* called for authentication only). Thus, in this particular instance,
* there is no real difference between using the AUTH, SESS or ACCT
* flags, or combinations thereof.
*/
now = time(NULL) / 86400L;
if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
|| ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
&& spwd->sp_lstchg >= 0
&& now >= spwd->sp_lstchg + spwd->sp_max)) {
warn("Password for %s has expired", user);
return SESSION_FAILED;
}
/* We have a valid shadow entry, keep the password */
pw->pw_passwd = spwd->sp_pwdp;
#endif /* #ifdef HAS_SHADOW */
/*
* If no passwd, don't let them login if we're authenticating.
*/
if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
|| strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
return SESSION_FAILED;
}
#endif /* #ifdef USE_PAM */
/*
* Write a wtmp entry for this user.
*/
if (SESS_ACCT & flags) {
if (strncmp(ttyName, "/dev/", 5) == 0)
ttyName += 5;
logwtmp(ttyName, user, ifname); /* Add wtmp login entry */
logged_in = 1;
#if defined(_PATH_LASTLOG) && !defined(USE_PAM)
/*
* Enter the user in lastlog only if he has been authenticated using
* local system services. If he has not, then we don't know what his
* UID might be, and lastlog is indexed by UID.
*/
if (pw != NULL) {
struct lastlog ll;
int fd;
time_t tnow;
if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
(void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
memset((void *)&ll, 0, sizeof(ll));
(void)time(&tnow);
ll.ll_time = tnow;
(void)strncpy(ll.ll_line, ttyName, sizeof(ll.ll_line));
(void)strncpy(ll.ll_host, ifname, sizeof(ll.ll_host));
(void)write(fd, (char *)&ll, sizeof(ll));
(void)close(fd);
}
}
#endif /* _PATH_LASTLOG and not USE_PAM */
info("user %s logged in on tty %s intf %s", user, ttyName, ifname);
}
return SESSION_OK;
}
/*
* session_end - Logout the user.
*/
void
session_end(const char* ttyName)
{
#ifdef USE_PAM
int pam_error = PAM_SUCCESS;
if (pamh != NULL) {
if (PAM_session) pam_error = pam_close_session (pamh, PAM_SILENT);
PAM_session = 0;
pam_end (pamh, pam_error);
pamh = NULL;
/* Apparently the pam stuff does closelog(). */
reopen_log();
}
#endif
if (logged_in) {
if (strncmp(ttyName, "/dev/", 5) == 0)
ttyName += 5;
logwtmp(ttyName, "", ""); /* Wipe out utmp logout entry */
logged_in = 0;
}
}
| 31.317536 | 78 | 0.624849 |
aab345493b9110f488b22857c565f6d8955352a5 | 447 | h | C | M3CoreData/Source/M3StoreObjectFactory.h | mcubedsw/M3CoreData | d323731e96342858a4aa6a405276456d3c5220ed | [
"MIT"
] | 2 | 2017-03-09T18:25:24.000Z | 2017-10-29T10:10:44.000Z | M3CoreData/Source/M3StoreObjectFactory.h | mcubedsw/M3CoreData | d323731e96342858a4aa6a405276456d3c5220ed | [
"MIT"
] | null | null | null | M3CoreData/Source/M3StoreObjectFactory.h | mcubedsw/M3CoreData | d323731e96342858a4aa6a405276456d3c5220ed | [
"MIT"
] | null | null | null | /*****************************************************************
M3StoreObjectFactory.h
M3CoreData
Created by Martin Pilkington on 21/01/2013.
Please read the LICENCE.txt for licensing information
*****************************************************************/
#import <Foundation/Foundation.h>
@protocol M3StoreObjectFactory <NSObject>
- (id)createObjectWithEntity:(NSEntityDescription *)aEntity JSONID:(NSString *)aJSONID;
@end
| 26.294118 | 87 | 0.557047 |
5cc24fb1e1641e1a78ae9db13615dd728b429c34 | 2,368 | h | C | HashTable.h | OzanCinci/Functional-Equivalent-of-a-Maps-Application | 0c471e1fc1152e56105fb0f7cec25bf9fab7bf71 | [
"MIT"
] | null | null | null | HashTable.h | OzanCinci/Functional-Equivalent-of-a-Maps-Application | 0c471e1fc1152e56105fb0f7cec25bf9fab7bf71 | [
"MIT"
] | null | null | null | HashTable.h | OzanCinci/Functional-Equivalent-of-a-Maps-Application | 0c471e1fc1152e56105fb0f7cec25bf9fab7bf71 | [
"MIT"
] | null | null | null | #ifndef __KEYED_HASH_TABLE_H__
#define __KEYED_HASH_TABLE_H__
#include <vector>
#include <string>
// Expand threshold is the multiplicative inverse of the 1/3 (%33)
// in order to prevent floating point math
#define EXPAND_THRESHOLD 3
// Only first 100 primes are defined, test cases would not exceed the maximum
// prime in this table
#define PRIME_TABLE_COUNT 100
struct HashData
{
std::vector<int> intArray;
std::string key;
// Constructor
HashData() { key = ""; }
};
// A Simple Hash Table class
// Holds key value pairs
// Key is a string, Value is an integer array
// using quadratic probing for collision
class KeyedHashTable
{
private:
// Stores the first 100 primes
static const int PRIME_LIST[PRIME_TABLE_COUNT];
static int FindNearestLargerPrime(int requestedCapacity);
// Hash Table Storage
HashData *table;
int tableSize;
int occupiedElementCount;
int Hash(const std::string &key) const;
// Rehash the entire table to the new expanded table
void ReHash();
// Friend class that will access private members etc.
// This will be used for testing. Do not remove/edit these
// statements.
friend class PA3_HT_TEST_CASE;
friend class PA3_MAPS_TEST_CASE;
public:
// Constructors & Destructor
KeyedHashTable();
KeyedHashTable(int requestedCapacity);
KeyedHashTable(const KeyedHashTable &);
KeyedHashTable &operator=(const KeyedHashTable &);
~KeyedHashTable();
// Inserts the key value pair
// If key already exists on the table:
// function returns false
// returns true if insertion is successful
bool Insert(const std::string &key,
const std::vector<int> &intArray);
// Tries to remove the key/value pair defined by the key
// If key/value pair is not found function returns false
// returns true if remove operation is successful
bool Remove(const std::string &key);
// Clears Entire Table removes everything
// Does NOT deallocate memory
void ClearTable();
// Finds the value pair
// returns true if found (and also populates the value out with the data)
// returns false if key is not found in the table
bool Find(std::vector<int> &valueOut,
const std::string &key) const;
// Prints the table
void Print() const;
};
#endif //__KEYED_HASH_TABLE_H__ | 30.753247 | 77 | 0.701436 |
a9361f41dcc587e344dd859e2284eb14a21dd0ef | 113 | c | C | bin/gzip/crypt.c | aaliomer/exos | 6a37c41cad910c373322441a9f23cfabdbfae275 | [
"BSD-3-Clause"
] | 1 | 2018-01-23T23:07:19.000Z | 2018-01-23T23:07:19.000Z | bin/gzip/crypt.c | aaliomer/exos | 6a37c41cad910c373322441a9f23cfabdbfae275 | [
"BSD-3-Clause"
] | null | null | null | bin/gzip/crypt.c | aaliomer/exos | 6a37c41cad910c373322441a9f23cfabdbfae275 | [
"BSD-3-Clause"
] | null | null | null | /* crypt.c (dummy version) -- do not perform encryption
* Hardly worth copyrighting :-)
*/
#ifdef RCSID
#endif
| 18.833333 | 55 | 0.690265 |
a94cfca19f88a06376ce245c63ccf6bac2b9cd91 | 11,895 | h | C | indra/llcommon/llcoros.h | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | null | null | null | indra/llcommon/llcoros.h | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | null | null | null | indra/llcommon/llcoros.h | SaladDais/LSO2-VM-Performance | d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638 | [
"ISC"
] | null | null | null | /**
* @file llcoros.h
* @author Nat Goodspeed
* @date 2009-06-02
* @brief Manage running boost::coroutine instances
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#if ! defined(LL_LLCOROS_H)
#define LL_LLCOROS_H
#include "llexception.h"
#include <boost/fiber/fss.hpp>
#include <boost/fiber/future/promise.hpp>
#include <boost/fiber/future/future.hpp>
#include "mutex.h"
#include "llsingleton.h"
#include "llinstancetracker.h"
#include <boost/function.hpp>
#include <string>
// e.g. #include LLCOROS_MUTEX_HEADER
#define LLCOROS_MUTEX_HEADER <boost/fiber/mutex.hpp>
#define LLCOROS_CONDVAR_HEADER <boost/fiber/condition_variable.hpp>
namespace boost {
namespace fibers {
class mutex;
enum class cv_status;
class condition_variable;
}
}
/**
* Registry of named Boost.Coroutine instances
*
* The Boost.Coroutine library supports the general case of a coroutine
* accepting arbitrary parameters and yielding multiple (sets of) results. For
* such use cases, it's natural for the invoking code to retain the coroutine
* instance: the consumer repeatedly calls into the coroutine, perhaps passing
* new parameter values, prompting it to yield its next result.
*
* Our typical coroutine usage is different, though. For us, coroutines
* provide an alternative to the @c Responder pattern. Our typical coroutine
* has @c void return, invoked in fire-and-forget mode: the handler for some
* user gesture launches the coroutine and promptly returns to the main loop.
* The coroutine initiates some action that will take multiple frames (e.g. a
* capability request), waits for its result, processes it and silently steals
* away.
*
* This usage poses two (related) problems:
*
* # Who should own the coroutine instance? If it's simply local to the
* handler code that launches it, return from the handler will destroy the
* coroutine object, terminating the coroutine.
* # Once the coroutine terminates, in whatever way, who's responsible for
* cleaning up the coroutine object?
*
* LLCoros is a Singleton collection of currently-active coroutine instances.
* Each has a name. You ask LLCoros to launch a new coroutine with a suggested
* name prefix; from your prefix it generates a distinct name, registers the
* new coroutine and returns the actual name.
*
* The name
* can provide diagnostic info: we can look up the name of the
* currently-running coroutine.
*/
class LL_COMMON_API LLCoros: public LLSingleton<LLCoros>
{
LLSINGLETON(LLCoros);
~LLCoros();
void cleanupSingleton();
public:
/// The viewer's use of the term "coroutine" became deeply embedded before
/// the industry term "fiber" emerged to distinguish userland threads from
/// simpler, more transient kinds of coroutines. Semantically they've
/// always been fibers. But at this point in history, we're pretty much
/// stuck with the term "coroutine."
typedef boost::fibers::fiber coro;
/// Canonical callable type
typedef boost::function<void()> callable_t;
/**
* Create and start running a new coroutine with specified name. The name
* string you pass is a suggestion; it will be tweaked for uniqueness. The
* actual name is returned to you.
*
* Usage looks like this, for (e.g.) two coroutine parameters:
* @code
* class MyClass
* {
* public:
* ...
* // Do NOT NOT NOT accept reference params!
* // Pass by value only!
* void myCoroutineMethod(std::string, LLSD);
* ...
* };
* ...
* std::string name = LLCoros::instance().launch(
* "mycoro", boost::bind(&MyClass::myCoroutineMethod, this,
* "somestring", LLSD(17));
* @endcode
*
* Your function/method can accept any parameters you want -- but ONLY BY
* VALUE! Reference parameters are a BAD IDEA! You Have Been Warned. See
* DEV-32777 comments for an explanation.
*
* Pass a nullary callable. It works to directly pass a nullary free
* function (or static method); for other cases use a lambda expression,
* std::bind() or boost::bind(). Of course, for a non-static class method,
* the first parameter must be the class instance. Any other parameters
* should be passed via the enclosing expression.
*
* launch() tweaks the suggested name so it won't collide with any
* existing coroutine instance, creates the coroutine instance, registers
* it with the tweaked name and runs it until its first wait. At that
* point it returns the tweaked name.
*/
std::string launch(const std::string& prefix, const callable_t& callable);
/**
* Abort a running coroutine by name. Normally, when a coroutine either
* runs to completion or terminates with an exception, LLCoros quietly
* cleans it up. This is for use only when you must explicitly interrupt
* one prematurely. Returns @c true if the specified name was found and
* still running at the time.
*/
// bool kill(const std::string& name);
/**
* From within a coroutine, look up the (tweaked) name string by which
* this coroutine is registered. Returns the empty string if not found
* (e.g. if the coroutine was launched by hand rather than using
* LLCoros::launch()).
*/
static std::string getName();
/**
* This variation returns a name suitable for log messages: the explicit
* name for an explicitly-launched coroutine, or "mainN" for the default
* coroutine on a thread.
*/
static std::string logname();
/**
* For delayed initialization. To be clear, this will only affect
* coroutines launched @em after this point. The underlying facility
* provides no way to alter the stack size of any running coroutine.
*/
void setStackSize(S32 stacksize);
/// diagnostic
void printActiveCoroutines(const std::string& when=std::string());
/// get the current coro::id for those who really really care
static coro::id get_self();
/**
* Most coroutines, most of the time, don't "consume" the events for which
* they're suspending. This way, an arbitrary number of listeners (whether
* coroutines or simple callbacks) can be registered on a particular
* LLEventPump, every listener responding to each of the events on that
* LLEventPump. But a particular coroutine can assert that it will consume
* each event for which it suspends. (See also llcoro::postAndSuspend(),
* llcoro::VoidListener)
*/
static void set_consuming(bool consuming);
static bool get_consuming();
/**
* RAII control of the consuming flag
*/
class OverrideConsuming
{
public:
OverrideConsuming(bool consuming):
mPrevConsuming(get_consuming())
{
set_consuming(consuming);
}
OverrideConsuming(const OverrideConsuming&) = delete;
~OverrideConsuming()
{
set_consuming(mPrevConsuming);
}
private:
bool mPrevConsuming;
};
/// set string coroutine status for diagnostic purposes
static void setStatus(const std::string& status);
static std::string getStatus();
/// RAII control of status
class TempStatus
{
public:
TempStatus(const std::string& status):
mOldStatus(getStatus())
{
setStatus(status);
}
TempStatus(const TempStatus&) = delete;
~TempStatus()
{
setStatus(mOldStatus);
}
private:
std::string mOldStatus;
};
/// thrown by checkStop()
// It may sound ironic that Stop is derived from LLContinueError, but the
// point is that LLContinueError is the category of exception that should
// not immediately crash the viewer. Stop and its subclasses are to notify
// coroutines that the viewer intends to shut down. The expected response
// is to terminate the coroutine, rather than abort the viewer.
struct Stop: public LLContinueError
{
Stop(const std::string& what): LLContinueError(what) {}
};
/// early stages
struct Stopping: public Stop
{
Stopping(const std::string& what): Stop(what) {}
};
/// cleaning up
struct Stopped: public Stop
{
Stopped(const std::string& what): Stop(what) {}
};
/// cleaned up -- not much survives!
struct Shutdown: public Stop
{
Shutdown(const std::string& what): Stop(what) {}
};
/// Call this intermittently if there's a chance your coroutine might
/// continue running into application shutdown. Throws Stop if LLCoros has
/// been cleaned up.
static void checkStop();
/**
* Aliases for promise and future. An older underlying future implementation
* required us to wrap future; that's no longer needed. However -- if it's
* important to restore kill() functionality, we might need to provide a
* proxy, so continue using the aliases.
*/
template <typename T>
using Promise = boost::fibers::promise<T>;
template <typename T>
using Future = boost::fibers::future<T>;
template <typename T>
static Future<T> getFuture(Promise<T>& promise) { return promise.get_future(); }
// use mutex, lock, condition_variable suitable for coroutines
using Mutex = boost::fibers::mutex;
using LockType = std::unique_lock<Mutex>;
using cv_status = boost::fibers::cv_status;
using ConditionVariable = boost::fibers::condition_variable;
/// for data local to each running coroutine
template <typename T>
using local_ptr = boost::fibers::fiber_specific_ptr<T>;
private:
std::string generateDistinctName(const std::string& prefix) const;
#if LL_WINDOWS
void winlevel(const std::string& name, const callable_t& callable);
#endif
void toplevelTryWrapper(const std::string& name, const callable_t& callable);
void toplevel(std::string name, callable_t callable);
struct CoroData;
static CoroData& get_CoroData(const std::string& caller);
S32 mStackSize;
// coroutine-local storage, as it were: one per coro we track
struct CoroData: public LLInstanceTracker<CoroData, std::string>
{
CoroData(const std::string& name);
CoroData(int n);
// tweaked name of the current coroutine
const std::string mName;
// set_consuming() state
bool mConsuming;
// setStatus() state
std::string mStatus;
F64 mCreationTime; // since epoch
};
// Identify the current coroutine's CoroData. This local_ptr isn't static
// because it's a member of an LLSingleton, and we rely on it being
// cleaned up in proper dependency order.
local_ptr<CoroData> mCurrent;
};
namespace llcoro
{
inline
std::string logname() { return LLCoros::logname(); }
} // llcoro
#endif /* ! defined(LL_LLCOROS_H) */
| 35.507463 | 84 | 0.680034 |
049e290d67c4ade30504d57649aa1c55f81a3054 | 3,058 | h | C | src/include/common/event_util.h | algebra2k/terrier | 8b6f4b0b0c30dc94411f197e610f634ce0ab5b0b | [
"MIT"
] | 1 | 2022-01-02T06:58:50.000Z | 2022-01-02T06:58:50.000Z | src/include/common/event_util.h | algebra2k/terrier | 8b6f4b0b0c30dc94411f197e610f634ce0ab5b0b | [
"MIT"
] | 7 | 2020-04-06T19:31:12.000Z | 2020-05-12T23:05:09.000Z | src/include/common/event_util.h | algebra2k/terrier | 8b6f4b0b0c30dc94411f197e610f634ce0ab5b0b | [
"MIT"
] | 2 | 2021-11-20T02:32:37.000Z | 2022-02-01T15:30:37.000Z | #pragma once
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/listener.h>
#include "common/exception.h"
namespace terrier {
/**
* Static utility class with wrappers for libevent functions.
*
* Wrapper functions are functions with the same signature and return
* value as the c-style functions, but consist of an extra return value
* checking. An exception is thrown instead if something is wrong. Wrappers
* are great tools for using legacy code in a modern code base.
*/
class EventUtil {
private:
template <typename T>
static bool NotNull(T *ptr) {
return ptr != nullptr;
}
static bool IsZero(int arg) { return arg == 0; }
static bool NonNegative(int arg) { return arg >= 0; }
template <typename T>
static T Wrap(T value, bool (*check)(T), const char *error_msg) {
if (!check(value)) throw NETWORK_PROCESS_EXCEPTION(error_msg);
return value;
}
public:
EventUtil() = delete;
/**
* @return A new event_base
*/
static struct event_base *EventBaseNew() {
return Wrap(event_base_new(), NotNull<struct event_base>, "Can't allocate event base");
}
/**
* @param base The event_base to exit
* @param timeout
* @return a positive integer or an exception is thrown on failure
*/
static int EventBaseLoopExit(struct event_base *base, const struct timeval *timeout) {
return Wrap(event_base_loopexit(base, timeout), IsZero, "Error when exiting loop");
}
/**
* @param event The event to delete
* @return a positive integer or an exception is thrown on failure
*/
static int EventDel(struct event *event) { return Wrap(event_del(event), IsZero, "Error when deleting event"); }
/**
* @param event The event to add
* @param timeout
* @return a positive integer or an exception is thrown on failure
*/
static int EventAdd(struct event *event, const struct timeval *timeout) {
return Wrap(event_add(event, timeout), IsZero, "Error when adding event");
}
/**
* @brief Allocates a callback event
* @param event The event being assigned
* @param base The event_base
* @param fd The filedescriptor assigned to the event
* @param flags Flags for the event
* @param callback Callback function to fire when the event is triggered
* @param arg Argument to pass to the callback function
* @return a positive integer or an exception is thrown on failure
*/
static int EventAssign(struct event *event, struct event_base *base, int fd, int16_t flags,
event_callback_fn callback, void *arg) {
return Wrap(event_assign(event, base, fd, flags, callback, arg), IsZero, "Error when assigning event");
}
/**
* @brief Runs event base dispatch loop
* @param base The event_base to dispatch on
* @return a positive integer or an exception is thrown on failure
*/
static int EventBaseDispatch(struct event_base *base) {
return Wrap(event_base_dispatch(base), NonNegative, "Error in event base dispatch");
}
};
} // namespace terrier
| 31.854167 | 114 | 0.700131 |
10fd6ddcd26c0cadc1d216f4c8f209ff57257378 | 716 | h | C | lib/air/src/collection/writer/UtilizationWriter.h | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | lib/air/src/collection/writer/UtilizationWriter.h | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | lib/air/src/collection/writer/UtilizationWriter.h | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null |
#ifndef AIR_COLLECTION_UTILIZATION_WRITER_H
#define AIR_COLLECTION_UTILIZATION_WRITER_H
#include "src/collection/writer/Writer.h"
#include "src/lib/Data.h"
namespace collection
{
class UtilizationWriter : public Writer
{
public:
UtilizationWriter(void)
{
}
virtual ~UtilizationWriter(void)
{
}
inline void
LogData(lib::Data* data, uint64_t usage) override
{
lib::UtilizationData* util_data = static_cast<lib::UtilizationData*>(data);
util_data->access = true;
util_data->usage += usage;
}
int
SetSamplingRate(uint32_t rate) override
{
return 0;
}
};
} // namespace collection
#endif // AIR_COLLECTION_UTILIZATION_WRITER_H
| 19.351351 | 83 | 0.687151 |
b7b4a558278ab1a41e1ec14a2246a31b0980cf7f | 813 | h | C | src/Loaders/Shared/CanFile.h | AmrikSadhra/FCE-To-Obj | a3c928077add2bd5d5f3463daee6008f150a0a54 | [
"MIT"
] | 212 | 2019-08-10T16:57:57.000Z | 2022-03-30T02:21:05.000Z | src/Loaders/Shared/CanFile.h | AmrikSadhra/FCE-To-Obj | a3c928077add2bd5d5f3463daee6008f150a0a54 | [
"MIT"
] | 11 | 2018-07-10T18:01:09.000Z | 2019-06-26T13:41:24.000Z | src/Loaders/Shared/CanFile.h | AmrikSadhra/FCE-to-OBJ | a3c928077add2bd5d5f3463daee6008f150a0a54 | [
"MIT"
] | 20 | 2020-02-09T02:38:35.000Z | 2022-03-23T20:26:28.000Z | #pragma once
#include "../Common/IRawData.h"
struct CameraAnimPoint
{
glm::ivec3 pt;
int16_t od1, od2, od3, od4; // OD2 seems to be something more than just rotation, like zoom or some shit
// OD3 seems to set perspective
// OD4 similar to OD1, induces wavyness but animation remains
};
class CanFile : IRawData
{
public:
CanFile() = default;
static bool Load(const std::string &canPath, CanFile &canFile);
static void Save(const std::string &canPath, CanFile &canFile);
uint16_t size;
uint8_t type, struct3D;
uint16_t animLength, unknown;
std::vector<CameraAnimPoint> animPoints;
private:
bool _SerializeIn(std::ifstream &ifstream) override;
void _SerializeOut(std::ofstream &ofstream) override;
};
| 28.034483 | 108 | 0.659287 |
a2c730aad319ded836cf234a73deb476321a78d4 | 359 | h | C | Classes/YYChatMarqueeLabelView.h | 673697831/YYChatMarqueeLabelView | 4621cc19181bec3e1beb1d99947bcec0a630d1a2 | [
"MIT"
] | null | null | null | Classes/YYChatMarqueeLabelView.h | 673697831/YYChatMarqueeLabelView | 4621cc19181bec3e1beb1d99947bcec0a630d1a2 | [
"MIT"
] | null | null | null | Classes/YYChatMarqueeLabelView.h | 673697831/YYChatMarqueeLabelView | 4621cc19181bec3e1beb1d99947bcec0a630d1a2 | [
"MIT"
] | null | null | null | //
// YYChatMarqueeLabel.h
// YYChatMarqueeLabel
//
// Created by ouzhirui on 2019/1/21.
// Copyright © 2019年 ozr. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "YYChatMarqueeText.h"
NS_ASSUME_NONNULL_BEGIN
@interface YYChatMarqueeLabelView : UIView
@property (nonatomic, strong) YYChatMarqueeText *marqueeText;
@end
NS_ASSUME_NONNULL_END
| 17.095238 | 61 | 0.760446 |
aeb141c3db68424fdd271be58fc4b136748d0125 | 1,132 | c | C | src/xrt/targets/common/target_instance_no_comp.c | leviathanch/monado | 36a540a764fd5529018dfceb28e10804db9596bf | [
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 2 | 2021-11-08T05:17:12.000Z | 2022-01-24T12:50:59.000Z | src/xrt/targets/common/target_instance_no_comp.c | SimulaVR/monado | b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21 | [
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/xrt/targets/common/target_instance_no_comp.c | SimulaVR/monado | b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21 | [
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020, Collabora, Ltd.
// SPDX-License-Identifier: BSL-1.0
/*!
* @file
* @brief Shared default implementation of the instance, but with no compositor
* usage
* @author Jakob Bornecrantz <jakob@collabora.com>
*/
#include "target_instance_parts.h"
static int
t_instance_create_system_compositor_stub(struct xrt_instance *xinst,
struct xrt_device *xdev,
struct xrt_system_compositor **out_xsysc)
{
*out_xsysc = NULL;
return -1;
}
/*
*
* Exported function(s).
*
*/
int
xrt_instance_create(struct xrt_instance_info *i_info, struct xrt_instance **out_xinst)
{
struct xrt_prober *xp = NULL;
int ret = xrt_prober_create_with_lists(&xp, &target_lists);
if (ret < 0) {
return ret;
}
struct t_instance *tinst = U_TYPED_CALLOC(struct t_instance);
tinst->base.select = t_instance_select;
tinst->base.create_system_compositor = t_instance_create_system_compositor_stub;
tinst->base.get_prober = t_instance_get_prober;
tinst->base.destroy = t_instance_destroy;
tinst->xp = xp;
*out_xinst = &tinst->base;
return 0;
}
| 22.196078 | 86 | 0.69258 |
b7db9f8fb3d738e07deec5c238dab6e0bd950ae7 | 58,401 | h | C | lib/wlan/common/include/wlan/common/element.h | kong1191/garnet | 609c727895e477ac086db38c1cee654dc10f2008 | [
"BSD-3-Clause"
] | null | null | null | lib/wlan/common/include/wlan/common/element.h | kong1191/garnet | 609c727895e477ac086db38c1cee654dc10f2008 | [
"BSD-3-Clause"
] | null | null | null | lib/wlan/common/include/wlan/common/element.h | kong1191/garnet | 609c727895e477ac086db38c1cee654dc10f2008 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <fbl/type_support.h>
#include <wlan/common/bitfield.h>
#include <wlan/common/element_id.h>
#include <wlan/common/logging.h>
#include <wlan/common/macaddr.h>
#include <wlan/protocol/info.h>
#include <fuchsia/wlan/mlme/cpp/fidl.h>
#include <zircon/assert.h>
#include <zircon/compiler.h>
#include <zircon/types.h>
#include <cstdint>
#include <unordered_map>
#include <utility>
#include <vector>
namespace wlan {
// IEEE Std 802.11-2016, 9.4.2.1
struct ElementHeader {
uint8_t id;
uint8_t len;
} __PACKED;
template <typename E, uint8_t ID> struct Element {
static constexpr uint8_t element_id() { return ID; }
size_t body_len() const { return static_cast<const E*>(this)->hdr.len; }
size_t len() const { return sizeof(ElementHeader) + body_len(); }
bool is_len_valid() const {
// E::kMinLen and E::kMaxLen captures the range of the IE body length, excluding the IE
// header whose size is fixed to 2 octets.
if (body_len() >= E::kMinLen && body_len() <= E::kMaxLen) return true;
// Crush dark arts.
debugbcn(
"rxed Invalid IE: ID %2d elem_len %2zu body_len %3zu (not in range "
"[%3zu:%3zu]\n",
E::element_id(), len(), body_len(), E::kMinLen, E::kMaxLen);
return false;
}
bool is_valid() const { return is_len_valid(); }
};
// An ElementReader can be used to retrieve Elements from a Management frame. The peek() method will
// read the ElementHeader without advancing the iterator. The caller may then use the id in the
// header and call read() to retrieve the next Element. is_valid() will return false after reaching
// the end or parse errors. It is an error to call read() for a type different than the one
// specified in the ElementHeader.
class ElementReader {
public:
ElementReader(const uint8_t* buf, size_t len);
bool is_valid() const;
size_t offset() const { return offset_; }
const ElementHeader* peek() const;
void skip(size_t offset) { offset_ += offset; }
void skip(const ElementHeader& hdr) { offset_ += sizeof(ElementHeader) + hdr.len; }
template <typename E> const E* read() {
static_assert(fbl::is_base_of<Element<E, E::element_id()>, E>::value,
"Only Elements may be retrieved.");
if (!is_valid()) {
debugbcn("IE validity test failed: ID %3u len_ %3zu offset_ %3zu elem_len %3zu\n",
E::element_id(), len_, offset_, NextElementLen());
return nullptr;
}
if (offset_ + sizeof(E) > len_) {
debugbcn(
"IE validity test failed: ID %3u len_ %3zu offset_ %3zu elem_len %3zu sizeof(E) "
"%3zu\n",
E::element_id(), len_, offset_, NextElementLen(), sizeof(E));
return nullptr;
}
const E* elt = reinterpret_cast<const E*>(buf_ + offset_);
ZX_DEBUG_ASSERT(elt->hdr.id == E::element_id());
if (!elt->is_valid()) return nullptr;
offset_ += sizeof(ElementHeader) + elt->hdr.len;
return elt;
}
private:
size_t NextElementLen() const;
const uint8_t* const buf_;
const size_t len_;
size_t offset_ = 0;
};
// An ElementWriter will serialize Elements into a buffer. The size() method will return the total
// length of the buffer.
class ElementWriter {
public:
ElementWriter(uint8_t* buf, size_t len);
template <typename E, typename... Args> bool write(Args&&... args) {
static_assert(fbl::is_base_of<Element<E, E::element_id()>, E>::value,
"Only Elements may be inserted.");
if (offset_ >= len_) return false;
size_t actual = 0;
bool success =
E::Create(buf_ + offset_, len_ - offset_, &actual, std::forward<Args>(args)...);
if (!success) return false;
auto elem = reinterpret_cast<const E*>(buf_ + offset_);
if (!elem->is_valid()) {
warnf("ElementWriter: IE %3u has invalid body length: %3u\n", E::element_id(),
elem->hdr.len);
}
offset_ += actual;
ZX_DEBUG_ASSERT(offset_ <= len_);
return true;
}
size_t size() const { return offset_; }
private:
uint8_t* buf_;
const size_t len_;
size_t offset_ = 0;
};
// IEEE Std 802.11-2016, 9.4.2.2
struct SsidElement : public Element<SsidElement, element_id::kSsid> {
static bool Create(void* buf, size_t len, size_t* actual, const uint8_t* ssid, size_t ssid_len);
static const size_t kMinLen = 0;
static const size_t kMaxLen = 32;
ElementHeader hdr;
uint8_t ssid[];
} __PACKED;
// IEEE 802.11-2016 9.4.2.3.
// The MSB in a rate indicates "basic rate" and is ignored during comparison.
// Rates are in 0.5Mbps increment: 12 -> 6 Mbps, 11 -> 5.5 Mbps, etc.
struct SupportedRate : public common::BitField<uint8_t> {
constexpr SupportedRate() = default;
constexpr explicit SupportedRate(uint8_t val) : common::BitField<uint8_t>(val) {}
constexpr explicit SupportedRate(uint8_t val, bool is_basic) : common::BitField<uint8_t>(val) {
set_is_basic(static_cast<uint8_t>(is_basic));
}
static SupportedRate basic(uint8_t rate) { return SupportedRate(rate, true); }
WLAN_BIT_FIELD(rate, 0, 7);
WLAN_BIT_FIELD(is_basic, 7, 1);
operator uint8_t() const { return val(); }
bool operator==(const SupportedRate& other) const { return rate() == other.rate(); }
bool operator!=(const SupportedRate& other) const { return !this->operator==(other); }
bool operator<(const SupportedRate& other) const { return rate() < other.rate(); }
bool operator>(const SupportedRate& other) const { return rate() > other.rate(); }
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.3
struct SupportedRatesElement : public Element<SupportedRatesElement, element_id::kSuppRates> {
static bool Create(void* buf, size_t len, size_t* actual,
const SupportedRate rates[], size_t num_rates);
static const size_t kMinLen = 1;
static const size_t kMaxLen = 8;
ElementHeader hdr;
SupportedRate rates[];
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.4
struct DsssParamSetElement : public Element<DsssParamSetElement, element_id::kDsssParamSet> {
static bool Create(void* buf, size_t len, size_t* actual, uint8_t chan);
static const size_t kMinLen = 1;
static const size_t kMaxLen = 1;
ElementHeader hdr;
uint8_t current_chan;
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.5
struct CfParamSetElement : public Element<CfParamSetElement, element_id::kCfParamSet> {
static bool Create(void* buf, size_t len, size_t* actual, uint8_t count, uint8_t period,
uint16_t max_duration, uint16_t dur_remaining);
static const size_t kMinLen = 6;
static const size_t kMaxLen = 6;
ElementHeader hdr;
uint8_t count;
uint8_t period;
uint16_t max_duration;
uint16_t dur_remaining;
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.6
class BitmapControl : public common::BitField<uint8_t> {
public:
WLAN_BIT_FIELD(group_traffic_ind, 0, 1);
WLAN_BIT_FIELD(offset, 1, 7);
};
// IEEE Std 802.11-2016, 9.4.2.6
struct TimElement : public Element<TimElement, element_id::kTim> {
static bool Create(void* buf, size_t len, size_t* actual, uint8_t dtim_count,
uint8_t dtim_period, BitmapControl bmp_ctrl, const uint8_t* bmp,
size_t bmp_len);
static const size_t kMinLenBmp = 1;
static const size_t kMaxLenBmp = 251;
static const size_t kFixedLenBody = 3;
static const size_t kMinLen = kFixedLenBody + kMinLenBmp;
static const size_t kMaxLen = kFixedLenBody + kMaxLenBmp;
ElementHeader hdr;
// body: fixed 3 bytes
uint8_t dtim_count;
uint8_t dtim_period;
BitmapControl bmp_ctrl;
// body: variable length 1-251 bytes.
uint8_t bmp[];
bool traffic_buffered(uint16_t aid) const;
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.9. Figure 9-131, 9-132.
struct SubbandTriplet {
uint8_t first_channel_number;
uint8_t number_of_channels;
uint8_t max_tx_power; // dBm
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.9
struct CountryElement : public Element<CountryElement, element_id::kCountry> {
static bool Create(void* buf, size_t len, size_t* actual, const uint8_t* country,
const std::vector<SubbandTriplet>& subbands);
static const size_t kCountryLen = 3;
static const size_t kMinLen = 3; // TODO(porce): revisit the spec.
static const size_t kMaxLen = 255;
ElementHeader hdr;
// TODO(NET-799): Validate dot11CountryString
// Note, country octets is not a null-terminated string.
// IEEE802.11-MIB Object Identifier 1.2.840.10036.1.1.1.23: dot11CountryString
// First two octets is the two character country code defined in ISO/IEC 3166-1
// The third octets
// - ASCII space character: all environments
// - ASCII 'O' : Outdoor environment only
// - ASCII 'I' : Indoor environment only
// - ASCII 'X' : Noncountry entity
// - Binary value of the Operating Class table number. Annex E Table E-1 becomes 0x01.
uint8_t country[kCountryLen];
static_assert(sizeof(SubbandTriplet) == 3,
"Wireformat for SubbandTriplet is of length 3 octets.");
// One or more SubbandTriplet, if dot11OperatingClassesRequired is false.
// TODO(porce): Revisit for VHT, and if dot11OperatingClassesRequired is true.
uint8_t triplets[];
// Zero-padding, zero or one octect. Make the length of the CountryElement be even.
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.13
struct ExtendedSupportedRatesElement
: public Element<ExtendedSupportedRatesElement, element_id::kExtSuppRates> {
static bool Create(void* buf, size_t len, size_t* actual,
const SupportedRate rates[], size_t num_rates);
static const size_t kMinLen = 1;
static const size_t kMaxLen = 255;
ElementHeader hdr;
SupportedRate rates[];
} __PACKED;
const uint16_t kEapolProtocolId = 0x888E;
// IEEE Std 802.11-2016, 9.4.2.25.1
// The MLME always forwards the RSNE and never requires to decode the element itself. Hence, support
// for accessing optional fields is left out and implemented only by the SME.
struct RsnElement : public Element<RsnElement, element_id::kRsn> {
static bool Create(void* buf, size_t len, size_t* actual, const uint8_t* raw, size_t raw_len);
static const size_t kMinLen = 2;
static const size_t kMaxLen = 255;
ElementHeader hdr;
uint16_t version;
uint8_t fields[];
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.98
struct MeshConfiguration {
enum PathSelProtoId : uint8_t {
kHwmp = 1u,
};
enum PathSelMetricId : uint8_t {
kAirtime = 1u,
};
enum CongestCtrlModeId : uint8_t {
kCongestCtrlInactive = 0u,
kCongestCtrlSignaling = 1u,
};
enum SyncMethodId : uint8_t {
kNeighborOffsetSync = 1u,
};
enum AuthProtoId : uint8_t {
kNoAuth = 0u,
kSae = 1u,
kIeee8021X = 2u,
};
struct MeshFormationInfo : public common::BitField<uint8_t> {
WLAN_BIT_FIELD(connected_to_mesh_gate, 0, 1);
WLAN_BIT_FIELD(num_peerings, 1, 6);
WLAN_BIT_FIELD(connected_to_as, 7, 1);
} __PACKED;
struct MeshCapability : public common::BitField<uint8_t> {
WLAN_BIT_FIELD(accepting_additional_peerings, 0, 1);
WLAN_BIT_FIELD(mcca_supported, 1, 1);
WLAN_BIT_FIELD(mcca_enabled, 2, 1);
WLAN_BIT_FIELD(forwarding, 3, 1);
WLAN_BIT_FIELD(mbca_enabled, 4, 1);
WLAN_BIT_FIELD(tbtt_adjusting, 5, 1);
WLAN_BIT_FIELD(power_save_level, 6, 1);
// bit 7 is reserved
} __PACKED;
PathSelProtoId active_path_sel_proto_id;
PathSelMetricId active_path_sel_metric_id;
CongestCtrlModeId congest_ctrl_method_id;
SyncMethodId sync_method_id;
AuthProtoId auth_proto_id;
MeshFormationInfo mesh_formation_info;
MeshCapability mesh_capability;
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.98
struct MeshConfigurationElement
: public Element<MeshConfigurationElement, element_id::kMeshConfiguration>
{
static bool Create(void* buf, size_t len, size_t* actual, MeshConfiguration body);
static constexpr size_t kMinLen = 7;
static constexpr size_t kMaxLen = 7;
ElementHeader hdr;
MeshConfiguration body;
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.99
struct MeshIdElement : public Element<MeshIdElement, element_id::kMeshId> {
static bool Create(void* buf, size_t len, size_t* actual, const uint8_t* mesh_id,
size_t mesh_id_len);
static constexpr size_t kMinLen = 0;
static constexpr size_t kMaxLen = 32;
ElementHeader hdr;
uint8_t mesh_id[];
} __PACKED;
// IEEE Std 802.11-2016, 9.4.1.17
class QosInfo : public common::BitField<uint8_t> {
public:
constexpr explicit QosInfo(uint8_t value) : common::BitField<uint8_t>(value) {}
constexpr QosInfo() = default;
// AP specific QoS Info structure: IEEE Std 802.11-2016, 9.4.1.17, Figure 9-82
WLAN_BIT_FIELD(edca_param_set_update_count, 0, 4);
WLAN_BIT_FIELD(qack, 4, 1);
WLAN_BIT_FIELD(queue_request, 5, 1);
WLAN_BIT_FIELD(txop_request, 6, 1);
// 8th bit reserved
// Non-AP STA specific QoS Info structure: IEEE Std 802.11-2016, 9.4.1.17, Figure 9-83
WLAN_BIT_FIELD(ac_vo_uapsd_flag, 0, 1);
WLAN_BIT_FIELD(ac_vi_uapsd_flag, 1, 1);
WLAN_BIT_FIELD(ac_bk_uapsd_flag, 2, 1);
WLAN_BIT_FIELD(ac_be_uapsd_flag, 3, 1);
// qack already defined in AP specific structure.
WLAN_BIT_FIELD(max_sp_len, 5, 1);
WLAN_BIT_FIELD(more_data_ack, 6, 1);
// 8th bit reserved
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.30, Table 9-139
enum TsDirection : uint8_t {
kUplink = 0,
kDownlink = 1,
kDirectLink = 2,
kBidirectionalLink = 3,
};
// IEEE Std 802.11-2016, 9.4.2.30, Table 9-140
enum TsAccessPolicy : uint8_t {
// 0 reserved
kEdca = 1,
kHccaSpca = 2,
kMixedMode = 3,
};
// IEEE Std 802.11-2016, 9.4.2.30, Table 9-141
namespace ts_ack_policy {
enum TsAckPolicy : uint8_t {
kNormalAck = 0,
kNoAck = 1,
// 2 reserved
kBlockAck = 3,
};
} // namespace ts_ack_policy
// IEEE Std 802.11-2016, 9.4.2.30, Table 9-142
// Only used if TsInfo's access policy uses EDCA.
// Schedule Setting depends on TsInfo's ASPD and schedule fields.
enum TsScheduleSetting : uint8_t {
kNoSchedule = 0,
kUnschedledApsd = 1,
kScheduledPsmp_GcrSp = 2,
kScheduledApsd = 3,
};
// IEEE Std 802.11-2016, 9.4.2.30, Figure 9-266
class TsInfoPart1 : public common::BitField<uint16_t> {
public:
WLAN_BIT_FIELD(traffic_type, 0, 1);
WLAN_BIT_FIELD(tsid, 1, 4);
WLAN_BIT_FIELD(direction, 5, 2);
WLAN_BIT_FIELD(access_policy, 7, 2);
WLAN_BIT_FIELD(aggregation, 9, 1);
WLAN_BIT_FIELD(apsd, 10, 1);
WLAN_BIT_FIELD(user_priority, 11, 3);
WLAN_BIT_FIELD(ack_policy, 14, 2);
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.30, Figure 9-266
class TsInfoPart2 : public common::BitField<uint8_t> {
public:
WLAN_BIT_FIELD(schedule, 0, 1);
// Bit 17-23 reserved.
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.30, Figure 9-266
// Note: In order to use a 3 byte packed struct, the TsInfo was split into two parts.
struct TsInfo {
TsInfoPart1 p1;
TsInfoPart2 p2;
bool IsValidAggregation() const {
if (p1.access_policy() == TsAccessPolicy::kHccaSpca) { return true; }
return p1.access_policy() == TsAccessPolicy::kEdca && p2.schedule();
}
bool IsScheduleReserved() const { return p1.access_policy() != TsAccessPolicy::kEdca; }
TsScheduleSetting GetScheduleSetting() const {
return static_cast<TsScheduleSetting>(p1.apsd() | (p2.schedule() << 1));
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.30, Figure 9-267
struct NominalMsduSize : public common::BitField<uint16_t> {
WLAN_BIT_FIELD(size, 0, 15);
WLAN_BIT_FIELD(fixed, 15, 1);
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.30
struct TspecElement : public Element<TspecElement, element_id::kTspec> {
// TODO(hahnr): The element will for now only be read by the AP when received from an associated
// client and there is no need for providing a custom constructor yet.
ElementHeader hdr;
TsInfo ts_info;
NominalMsduSize nominal_msdu_size;
uint16_t max_msdu_size;
uint32_t min_service_interval;
uint32_t max_service_interval;
uint32_t inactivity_interval;
uint32_t suspension_interval;
uint32_t service_start_time;
uint32_t min_data_rate;
uint32_t mean_data_rate;
uint32_t peak_data_rate;
uint32_t burst_size;
uint32_t delay_bound;
uint32_t min_phy_rate;
uint16_t surplus_bw_allowance;
uint16_t medium_time;
// TODO(hahnr): Add min/mean/peak data rate support based on the provided fields.
// TODO(hahnr): Add min PHY rate support based on the provided field.
// TODO(hahnr): Add DMG support.
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.35
struct QosCapabilityElement : public Element<QosCapabilityElement, element_id::kQosCapability> {
static bool Create(void* buf, size_t len, size_t* actual, const QosInfo& qos_info);
ElementHeader hdr;
QosInfo qos_info;
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.2
// Note this is a field of HtCapabilities element.
class HtCapabilityInfo : public common::BitField<uint16_t> {
public:
constexpr explicit HtCapabilityInfo(uint16_t ht_cap_info)
: common::BitField<uint16_t>(ht_cap_info) {}
constexpr HtCapabilityInfo() = default;
WLAN_BIT_FIELD(ldpc_coding_cap, 0, 1);
WLAN_BIT_FIELD(chan_width_set, 1, 1); // In spec: Supported Channel Width Set
WLAN_BIT_FIELD(sm_power_save, 2, 2); // Spatial Multiplexing Power Save
WLAN_BIT_FIELD(greenfield, 4, 1); // HT-Greenfield.
WLAN_BIT_FIELD(short_gi_20, 5, 1); // Short Guard Interval for 20 MHz
WLAN_BIT_FIELD(short_gi_40, 6, 1); // Short Guard Interval for 40 MHz
WLAN_BIT_FIELD(tx_stbc, 7, 1);
WLAN_BIT_FIELD(rx_stbc, 8, 2); // maximum number of spatial streams. Up to 3.
WLAN_BIT_FIELD(delayed_block_ack, 10, 1); // HT-delayed Block Ack
WLAN_BIT_FIELD(max_amsdu_len, 11, 1);
WLAN_BIT_FIELD(dsss_in_40, 12, 1); // DSSS/CCK Mode in 40 MHz
WLAN_BIT_FIELD(reserved, 13, 1);
WLAN_BIT_FIELD(intolerant_40, 14, 1); // 40 MHz Intolerant
WLAN_BIT_FIELD(lsig_txop_protect, 15, 1);
enum ChanWidthSet {
TWENTY_ONLY = 0,
TWENTY_FORTY = 1,
};
enum SmPowerSave {
STATIC = 0,
DYNAMIC = 1,
RESERVED = 2,
DISABLED = 3,
};
enum MaxAmsduLen {
OCTETS_3839 = 0,
OCTETS_7935 = 1,
};
static HtCapabilityInfo FromFidl(const ::fuchsia::wlan::mlme::HtCapabilityInfo& fidl) {
HtCapabilityInfo dst;
dst.set_ldpc_coding_cap(fidl.ldpc_coding_cap ? 1 : 0);
dst.set_chan_width_set(static_cast<ChanWidthSet>(fidl.chan_width_set));
dst.set_sm_power_save(static_cast<SmPowerSave>(fidl.sm_power_save));
dst.set_greenfield(fidl.greenfield ? 1 : 0);
dst.set_short_gi_20(fidl.short_gi_20 ? 1 : 0);
dst.set_short_gi_40(fidl.short_gi_40 ? 1 : 0);
dst.set_tx_stbc(fidl.tx_stbc ? 1 : 0);
dst.set_rx_stbc(fidl.rx_stbc);
dst.set_delayed_block_ack(fidl.delayed_block_ack ? 1 : 0);
dst.set_max_amsdu_len(static_cast<MaxAmsduLen>(fidl.max_amsdu_len));
dst.set_dsss_in_40(fidl.dsss_in_40 ? 1 : 0);
dst.set_intolerant_40(fidl.intolerant_40 ? 1 : 0);
dst.set_lsig_txop_protect(fidl.lsig_txop_protect ? 1 : 0);
return dst;
}
::fuchsia::wlan::mlme::HtCapabilityInfo ToFidl() const {
::fuchsia::wlan::mlme::HtCapabilityInfo fidl;
fidl.ldpc_coding_cap = (ldpc_coding_cap() == 1);
fidl.chan_width_set = chan_width_set();
fidl.sm_power_save = sm_power_save();
fidl.greenfield = (greenfield() == 1);
fidl.short_gi_20 = (short_gi_20() == 1);
fidl.short_gi_40 = (short_gi_40() == 1);
fidl.tx_stbc = (tx_stbc() == 1);
fidl.rx_stbc = rx_stbc();
fidl.delayed_block_ack = (delayed_block_ack() == 1);
fidl.max_amsdu_len = max_amsdu_len();
fidl.dsss_in_40 = (dsss_in_40() == 1);
fidl.intolerant_40 = (intolerant_40() == 1);
fidl.lsig_txop_protect = (lsig_txop_protect() == 1);
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.3
class AmpduParams : public common::BitField<uint8_t> {
public:
constexpr explicit AmpduParams(uint8_t params) : common::BitField<uint8_t>(params) {}
constexpr AmpduParams() = default;
WLAN_BIT_FIELD(exponent, 0, 2); // Maximum A-MPDU Length Exponent.
WLAN_BIT_FIELD(min_start_spacing, 2, 3); // Minimum MPDU Start Spacing.
WLAN_BIT_FIELD(reserved, 5, 3);
size_t max_ampdu_len() const { return (1 << (13 + exponent())) - 1; }
enum MinMPDUStartSpacing {
NO_RESTRICT = 0,
QUARTER_USEC = 1,
HALF_USEC = 2,
ONE_USEC = 3,
TWO_USEC = 4,
FOUR_USEC = 5,
EIGHT_USEC = 6,
SIXTEEN_USEC = 7,
};
static AmpduParams FromFidl(const ::fuchsia::wlan::mlme::AmpduParams& fidl) {
AmpduParams dst;
dst.set_exponent(fidl.exponent);
dst.set_min_start_spacing(static_cast<MinMPDUStartSpacing>(fidl.min_start_spacing));
return dst;
}
::fuchsia::wlan::mlme::AmpduParams ToFidl() const {
fuchsia::wlan::mlme::AmpduParams fidl;
fidl.exponent = exponent();
fidl.min_start_spacing = min_start_spacing();
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.4
class SupportedMcsRxMcsHead : public common::BitField<uint64_t> {
public:
constexpr explicit SupportedMcsRxMcsHead(uint64_t val) : common::BitField<uint64_t>(val) {}
constexpr SupportedMcsRxMcsHead() = default;
bool Support(uint8_t mcs_index) const { return 1 == (1 & (bitmask() >> mcs_index)); }
// HT-MCS table in IEEE Std 802.11-2016, Annex B.4.17.2
// VHT-MCS tables in IEEE Std 802.11-2016, 21.5
WLAN_BIT_FIELD(bitmask, 0, 64);
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.4
class SupportedMcsRxMcsTail : public common::BitField<uint32_t> {
public:
constexpr explicit SupportedMcsRxMcsTail(uint32_t val) : common::BitField<uint32_t>(val) {}
constexpr SupportedMcsRxMcsTail() = default;
WLAN_BIT_FIELD(bitmask, 0, 13);
WLAN_BIT_FIELD(reserved1, 13, 3);
WLAN_BIT_FIELD(highest_rate, 16, 10); // Mbps. Rx Highest Supported Rate.
WLAN_BIT_FIELD(reserved2, 26, 6);
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.4
class SupportedMcsTxMcs : public common::BitField<uint32_t> {
public:
constexpr explicit SupportedMcsTxMcs(uint32_t chunk) : common::BitField<uint32_t>(chunk) {}
constexpr SupportedMcsTxMcs() = default;
WLAN_BIT_FIELD(set_defined, 0, 1); // Add 96 for the original bit location
WLAN_BIT_FIELD(rx_diff, 1, 1);
WLAN_BIT_FIELD(max_ss, 2, 2);
WLAN_BIT_FIELD(ueqm, 4, 1); // Transmit Unequal Modulation.
WLAN_BIT_FIELD(reserved, 5, 27);
uint8_t max_ss_human() const { return max_ss() + 1; }
void set_max_ss_human(uint8_t num) {
constexpr uint8_t kLowerbound = 1;
constexpr uint8_t kUpperbound = 4;
if (num < kLowerbound) num = kLowerbound;
if (num > kUpperbound) num = kUpperbound;
set_max_ss(num - 1);
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.4
struct SupportedMcsSet {
SupportedMcsRxMcsHead rx_mcs_head;
SupportedMcsRxMcsTail rx_mcs_tail;
SupportedMcsTxMcs tx_mcs;
static SupportedMcsSet FromFidl(const ::fuchsia::wlan::mlme::SupportedMcsSet& fidl) {
SupportedMcsSet dst;
dst.rx_mcs_head.set_bitmask(fidl.rx_mcs_set);
dst.rx_mcs_tail.set_highest_rate(fidl.rx_highest_rate);
dst.tx_mcs.set_set_defined(fidl.tx_mcs_set_defined ? 1 : 0);
dst.tx_mcs.set_rx_diff(fidl.tx_rx_diff ? 1 : 0);
dst.tx_mcs.set_max_ss_human(fidl.tx_max_ss);
dst.tx_mcs.set_ueqm(fidl.tx_ueqm ? 1 : 0);
return dst;
}
::fuchsia::wlan::mlme::SupportedMcsSet ToFidl() const {
::fuchsia::wlan::mlme::SupportedMcsSet fidl;
fidl.rx_mcs_set = rx_mcs_head.bitmask();
fidl.rx_highest_rate = rx_mcs_tail.highest_rate();
fidl.tx_mcs_set_defined = (tx_mcs.set_defined() == 1);
fidl.tx_rx_diff = (tx_mcs.rx_diff() == 1);
fidl.tx_max_ss = tx_mcs.max_ss_human(); // Converting to human readable
fidl.tx_ueqm = (tx_mcs.ueqm() == 1);
return fidl;
}
// TODO(porce): Implement accessors
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.5
class HtExtCapabilities : public common::BitField<uint16_t> {
public:
constexpr explicit HtExtCapabilities(uint16_t ht_ext_cap)
: common::BitField<uint16_t>(ht_ext_cap) {}
constexpr HtExtCapabilities() = default;
WLAN_BIT_FIELD(pco, 0, 1);
WLAN_BIT_FIELD(pco_transition, 1, 2);
WLAN_BIT_FIELD(reserved1, 3, 5);
WLAN_BIT_FIELD(mcs_feedback, 8, 2);
WLAN_BIT_FIELD(htc_ht_support, 10, 1);
WLAN_BIT_FIELD(rd_responder, 11, 1);
WLAN_BIT_FIELD(reserved2, 12, 4);
enum PcoTransitionTime {
PCO_RESERVED = 0, // Often translated as "No transition".
PCO_400_USEC = 1,
PCO_1500_USEC = 2,
PCO_5000_USEC = 3,
};
enum McsFeedback {
MCS_NOFEEDBACK = 0,
MCS_RESERVED = 1,
MCS_UNSOLICIED = 2,
MCS_BOTH = 3,
};
static HtExtCapabilities FromFidl(const ::fuchsia::wlan::mlme::HtExtCapabilities& fidl) {
HtExtCapabilities dst;
dst.set_pco(fidl.pco);
dst.set_pco_transition(static_cast<PcoTransitionTime>(fidl.pco_transition));
dst.set_mcs_feedback(static_cast<McsFeedback>(fidl.mcs_feedback));
dst.set_htc_ht_support(fidl.htc_ht_support ? 1 : 0);
dst.set_rd_responder(fidl.rd_responder ? 1 : 0);
return dst;
}
::fuchsia::wlan::mlme::HtExtCapabilities ToFidl() const {
::fuchsia::wlan::mlme::HtExtCapabilities fidl;
fidl.pco = (pco() == 1);
fidl.pco_transition = pco_transition();
fidl.mcs_feedback = mcs_feedback();
fidl.htc_ht_support = (htc_ht_support() == 1);
fidl.rd_responder = (rd_responder() == 1);
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56.6
class TxBfCapability : public common::BitField<uint32_t> {
public:
constexpr explicit TxBfCapability(uint32_t txbf_cap) : common::BitField<uint32_t>(txbf_cap) {}
constexpr TxBfCapability() = default;
WLAN_BIT_FIELD(implicit_rx, 0, 1);
WLAN_BIT_FIELD(rx_stag_sounding, 1, 1);
WLAN_BIT_FIELD(tx_stag_sounding, 2, 1);
WLAN_BIT_FIELD(rx_ndp, 3, 1);
WLAN_BIT_FIELD(tx_ndp, 4, 1);
WLAN_BIT_FIELD(implicit, 5, 1);
WLAN_BIT_FIELD(calibration, 6, 2);
WLAN_BIT_FIELD(csi, 8, 1); // Explicit CSI Transmit Beamforming.
WLAN_BIT_FIELD(noncomp_steering, 9, 1); // Explicit Noncompressed Steering
WLAN_BIT_FIELD(comp_steering, 10, 1); // Explicit Compressed Steering
WLAN_BIT_FIELD(csi_feedback, 11, 2);
WLAN_BIT_FIELD(noncomp_feedback, 13, 2);
WLAN_BIT_FIELD(comp_feedback, 15, 2);
WLAN_BIT_FIELD(min_grouping, 17, 2);
WLAN_BIT_FIELD(csi_antennas, 19, 2);
WLAN_BIT_FIELD(noncomp_steering_ants, 21, 2);
WLAN_BIT_FIELD(comp_steering_ants, 23, 2);
WLAN_BIT_FIELD(csi_rows, 25, 2);
WLAN_BIT_FIELD(chan_estimation, 27, 2);
WLAN_BIT_FIELD(reserved, 29, 3);
enum Calibration {
CALIBRATION_NONE = 0,
CALIBRATION_RESPOND_NOINITIATE = 1,
CALIBRATION_RESERVED = 2,
CALIBRATION_RESPOND_INITIATE = 3,
};
enum Feedback {
// Shared for csi_feedback, noncomp_feedback, comp_feedback
FEEDBACK_NONE = 0,
FEEDBACK_DELAYED = 1,
FEEDBACK_IMMEDIATE = 2,
FEEDBACK_DELAYED_IMMEDIATE = 3,
};
enum MinGroup {
MIN_GROUP_ONE = 0, // Meaning no grouping
MIN_GROUP_ONE_TWO = 1,
MIN_GROUP_ONE_FOUR = 2,
MIN_GROUP_ONE_TWO_FOUR = 3,
};
uint8_t csi_antennas_human() const { return csi_antennas() + 1; }
void set_csi_antennas_human(uint8_t num) {
constexpr uint8_t kLowerbound = 1;
constexpr uint8_t kUpperbound = 4;
if (num < kLowerbound) num = kLowerbound;
if (num > kUpperbound) num = kUpperbound;
set_csi_antennas(num - 1);
};
uint8_t noncomp_steering_ants_human() const { return noncomp_steering_ants() + 1; }
void set_noncomp_steering_ants_human(uint8_t num) {
constexpr uint8_t kLowerbound = 1;
constexpr uint8_t kUpperbound = 4;
if (num < kLowerbound) num = kLowerbound;
if (num > kUpperbound) num = kUpperbound;
set_noncomp_steering_ants(num - 1);
}
uint8_t comp_steering_ants_human() const { return comp_steering_ants() + 1; }
void set_comp_steering_ants_human(uint8_t num) {
constexpr uint8_t kLowerbound = 1;
constexpr uint8_t kUpperbound = 4;
if (num < kLowerbound) num = kLowerbound;
if (num > kUpperbound) num = kUpperbound;
set_comp_steering_ants(num - 1);
}
uint8_t csi_rows_human() const { return csi_rows() + 1; }
void set_csi_rows_human(uint8_t num) {
constexpr uint8_t kLowerbound = 1;
constexpr uint8_t kUpperbound = 4;
if (num < kLowerbound) num = kLowerbound;
if (num > kUpperbound) num = kUpperbound;
set_csi_rows(num - 1);
}
uint8_t chan_estimation_human() const { return chan_estimation() + 1; }
void set_chan_estimation_human(uint8_t num) {
constexpr uint8_t kLowerbound = 1;
constexpr uint8_t kUpperbound = 4;
if (num < kLowerbound) num = kLowerbound;
if (num > kUpperbound) num = kUpperbound;
set_chan_estimation(num - 1);
}
static TxBfCapability FromFidl(const ::fuchsia::wlan::mlme::TxBfCapability& fidl) {
TxBfCapability dst;
dst.set_implicit_rx(fidl.implicit_rx ? 1 : 0);
dst.set_rx_stag_sounding(fidl.rx_stag_sounding ? 1 : 0);
dst.set_tx_stag_sounding(fidl.tx_stag_sounding ? 1 : 0);
dst.set_rx_ndp(fidl.rx_ndp ? 1 : 0);
dst.set_tx_ndp(fidl.tx_ndp ? 1 : 0);
dst.set_implicit(fidl.implicit ? 1 : 0);
dst.set_calibration(static_cast<Calibration>(fidl.calibration));
dst.set_csi(fidl.csi ? 1 : 0);
dst.set_noncomp_steering(fidl.noncomp_steering ? 1 : 0);
dst.set_comp_steering(fidl.comp_steering ? 1 : 0);
dst.set_csi_feedback(static_cast<Feedback>(fidl.csi_feedback));
dst.set_noncomp_feedback(static_cast<Feedback>(fidl.noncomp_feedback));
dst.set_comp_feedback(static_cast<Feedback>(fidl.comp_feedback));
dst.set_min_grouping(static_cast<MinGroup>(fidl.min_grouping));
dst.set_csi_antennas_human(fidl.csi_antennas);
dst.set_noncomp_steering_ants_human(fidl.noncomp_steering_ants);
dst.set_comp_steering_ants_human(fidl.comp_steering_ants);
dst.set_csi_rows_human(fidl.csi_rows);
dst.set_chan_estimation_human(fidl.chan_estimation);
return dst;
}
::fuchsia::wlan::mlme::TxBfCapability ToFidl() const {
::fuchsia::wlan::mlme::TxBfCapability fidl;
fidl.implicit_rx = (implicit_rx() == 1);
fidl.rx_stag_sounding = (rx_stag_sounding() == 1);
fidl.tx_stag_sounding = (tx_stag_sounding() == 1);
fidl.rx_ndp = (rx_ndp() == 1);
fidl.tx_ndp = (tx_ndp() == 1);
fidl.implicit = (implicit() == 1);
fidl.calibration = calibration();
fidl.csi = (csi() == 1);
fidl.noncomp_steering = (noncomp_steering() == 1);
fidl.comp_steering = (comp_steering() == 1);
fidl.csi_feedback = csi_feedback();
fidl.noncomp_feedback = noncomp_feedback();
fidl.comp_feedback = comp_feedback();
fidl.min_grouping = min_grouping();
fidl.csi_antennas = csi_antennas_human(); // Converting to human readable
fidl.noncomp_steering_ants = noncomp_steering_ants_human(); // Converting to human readable
fidl.comp_steering_ants = comp_steering_ants_human(); // Converting to human readable
fidl.csi_rows = csi_rows_human(); // Converting to human readable
fidl.chan_estimation = chan_estimation_human(); // Converting to human readable
return fidl;
}
} __PACKED;
class AselCapability : public common::BitField<uint8_t> {
public:
constexpr explicit AselCapability(uint8_t asel_cap) : common::BitField<uint8_t>(asel_cap) {}
constexpr AselCapability() = default;
WLAN_BIT_FIELD(asel, 0, 1);
WLAN_BIT_FIELD(csi_feedback_tx_asel, 1, 1); // Explicit CSI Feedback based Transmit ASEL
WLAN_BIT_FIELD(ant_idx_feedback_tx_asel, 2, 1);
WLAN_BIT_FIELD(explicit_csi_feedback, 3, 1);
WLAN_BIT_FIELD(antenna_idx_feedback, 4, 1);
WLAN_BIT_FIELD(rx_asel, 5, 1);
WLAN_BIT_FIELD(tx_sounding_ppdu, 6, 1);
WLAN_BIT_FIELD(reserved, 7, 1);
static AselCapability FromFidl(const ::fuchsia::wlan::mlme::AselCapability& fidl) {
AselCapability dst;
dst.set_asel(fidl.asel ? 1 : 0);
dst.set_csi_feedback_tx_asel(fidl.csi_feedback_tx_asel ? 1 : 0);
dst.set_ant_idx_feedback_tx_asel(fidl.ant_idx_feedback_tx_asel ? 1 : 0);
dst.set_explicit_csi_feedback(fidl.explicit_csi_feedback ? 1 : 0);
dst.set_antenna_idx_feedback(fidl.antenna_idx_feedback ? 1 : 0);
dst.set_rx_asel(fidl.rx_asel ? 1 : 0);
dst.set_tx_sounding_ppdu(fidl.tx_sounding_ppdu ? 1 : 0);
return dst;
}
::fuchsia::wlan::mlme::AselCapability ToFidl() const {
::fuchsia::wlan::mlme::AselCapability fidl;
fidl.asel = (asel() == 1);
fidl.csi_feedback_tx_asel = (csi_feedback_tx_asel() == 1);
fidl.ant_idx_feedback_tx_asel = (ant_idx_feedback_tx_asel() == 1);
fidl.explicit_csi_feedback = (explicit_csi_feedback() == 1);
fidl.antenna_idx_feedback = (antenna_idx_feedback() == 1);
fidl.rx_asel = (rx_asel() == 1);
fidl.tx_sounding_ppdu = (tx_sounding_ppdu() == 1);
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.56
struct HtCapabilities : public Element<HtCapabilities, element_id::kHtCapabilities> {
static bool Create(void* buf, size_t len, size_t* actual, HtCapabilityInfo ht_cap_info,
AmpduParams ampdu_params, SupportedMcsSet mcs_set,
HtExtCapabilities ht_ext_cap, TxBfCapability txbf_cap,
AselCapability asel_cap);
static constexpr size_t kMinLen = 26;
static constexpr size_t kMaxLen = 26;
ElementHeader hdr;
HtCapabilityInfo ht_cap_info;
AmpduParams ampdu_params;
SupportedMcsSet mcs_set;
HtExtCapabilities ht_ext_cap;
TxBfCapability txbf_cap;
AselCapability asel_cap;
static HtCapabilities FromDdk(const wlan_ht_caps_t& ddk) {
HtCapabilities dst{};
dst.hdr.id = element_id::kHtCapabilities;
dst.hdr.len = HtCapabilities::kMaxLen; // same as kMinLen
dst.ht_cap_info.set_val(ddk.ht_capability_info);
dst.ampdu_params.set_val(ddk.ampdu_params);
dst.mcs_set.rx_mcs_head.set_val(ddk.mcs_set.rx_mcs_head);
dst.mcs_set.rx_mcs_tail.set_val(ddk.mcs_set.rx_mcs_tail);
dst.mcs_set.tx_mcs.set_val(ddk.mcs_set.tx_mcs);
dst.ht_ext_cap.set_val(ddk.ht_ext_capabilities);
dst.txbf_cap.set_val(ddk.tx_beamforming_capabilities);
dst.asel_cap.set_val(ddk.asel_capabilities);
return dst;
}
wlan_ht_caps_t ToDdk() const {
wlan_ht_caps_t ddk{};
ddk.ht_capability_info = ht_cap_info.val();
ddk.ampdu_params = ampdu_params.val();
ddk.mcs_set.rx_mcs_head = mcs_set.rx_mcs_head.val();
ddk.mcs_set.rx_mcs_tail = mcs_set.rx_mcs_tail.val();
ddk.mcs_set.tx_mcs = mcs_set.tx_mcs.val();
ddk.ht_ext_capabilities = ht_ext_cap.val();
ddk.tx_beamforming_capabilities = txbf_cap.val();
ddk.asel_capabilities = asel_cap.val();
return ddk;
}
static HtCapabilities FromFidl(const ::fuchsia::wlan::mlme::HtCapabilities& fidl) {
HtCapabilities dst;
dst.hdr.id = element_id::kHtCapabilities;
dst.hdr.len = HtCapabilities::kMaxLen; // same as kMinLen
dst.ht_cap_info = HtCapabilityInfo::FromFidl(fidl.ht_cap_info);
dst.ampdu_params = AmpduParams::FromFidl(fidl.ampdu_params);
dst.mcs_set = SupportedMcsSet::FromFidl(fidl.mcs_set);
dst.ht_ext_cap = HtExtCapabilities::FromFidl(fidl.ht_ext_cap);
dst.txbf_cap = TxBfCapability::FromFidl(fidl.txbf_cap);
dst.asel_cap = AselCapability::FromFidl(fidl.asel_cap);
return dst;
}
::fuchsia::wlan::mlme::HtCapabilities ToFidl() const {
::fuchsia::wlan::mlme::HtCapabilities fidl;
fidl.ht_cap_info = ht_cap_info.ToFidl();
fidl.ampdu_params = ampdu_params.ToFidl();
fidl.mcs_set = mcs_set.ToFidl();
fidl.ht_ext_cap = ht_ext_cap.ToFidl();
fidl.txbf_cap = txbf_cap.ToFidl();
fidl.asel_cap = asel_cap.ToFidl();
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.57
// Note this is a field within HtOperation element.
class HtOpInfoHead : public common::BitField<uint32_t> {
public:
constexpr explicit HtOpInfoHead(uint32_t op_info) : common::BitField<uint32_t>(op_info) {}
constexpr HtOpInfoHead() = default;
WLAN_BIT_FIELD(secondary_chan_offset, 0, 2);
WLAN_BIT_FIELD(sta_chan_width, 2, 1);
WLAN_BIT_FIELD(rifs_mode, 3, 1);
WLAN_BIT_FIELD(reserved1, 4, 4); // Note 802.11n D1.10 implementaions use these.
WLAN_BIT_FIELD(ht_protect, 8, 2);
WLAN_BIT_FIELD(nongreenfield_present, 10, 1); // Nongreenfield HT STAs present.
WLAN_BIT_FIELD(reserved2, 11, 1); // Note 802.11n D1.10 implementations use these.
WLAN_BIT_FIELD(obss_non_ht, 12, 1); // OBSS Non-HT STAs present.
// IEEE 802.11-2016 Figure 9-339 has an incosistency so this is Fuchsia interpretation:
// The channel number for the second segment in a 80+80 Mhz channel
WLAN_BIT_FIELD(center_freq_seg2, 13, 8); // VHT
WLAN_BIT_FIELD(reserved3, 21, 3);
WLAN_BIT_FIELD(reserved4, 24, 6);
WLAN_BIT_FIELD(dual_beacon, 30, 1);
WLAN_BIT_FIELD(dual_cts_protect, 31, 1);
enum SecChanOffset {
SECONDARY_NONE = 0, // No secondary channel
SECONDARY_ABOVE = 1, // Secondary channel is above the primary channel
RESERVED = 2,
SECONDARY_BELOW = 3, // Secondary channel is below the primary channel
};
enum StaChanWidth {
TWENTY = 0, // MHz
ANY = 1, // Any in the Supported Channel Width set
};
enum HtProtect {
NONE = 0,
NONMEMBER = 1,
TWENTY_MHZ = 2,
NON_HT_MIXED = 3,
};
} __PACKED;
class HtOpInfoTail : public common::BitField<uint8_t> {
public:
constexpr explicit HtOpInfoTail(uint8_t val) : common::BitField<uint8_t>(val) {}
constexpr HtOpInfoTail() = default;
WLAN_BIT_FIELD(stbc_beacon, 0, 1); // Add 32 for the original bit location.
WLAN_BIT_FIELD(lsig_txop_protect, 1, 1);
WLAN_BIT_FIELD(pco_active, 2, 1);
WLAN_BIT_FIELD(pco_phase, 3, 1);
WLAN_BIT_FIELD(reserved5, 4, 4);
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.57
struct HtOperation : public Element<HtOperation, element_id::kHtOperation> {
static bool Create(void* buf, size_t len, size_t* actual, uint8_t primary_chan,
HtOpInfoHead head, HtOpInfoTail tail, SupportedMcsSet basic_mcs_set);
static constexpr size_t kMinLen = 22;
static constexpr size_t kMaxLen = 22;
ElementHeader hdr;
uint8_t primary_chan; // Primary 20 MHz channel.
// Implementation hack to support 40bits bitmap.
HtOpInfoHead head;
HtOpInfoTail tail;
SupportedMcsSet basic_mcs_set;
static HtOperation FromDdk(const wlan_ht_op_t& ddk) {
HtOperation dst{};
dst.hdr.id = element_id::kHtOperation;
dst.hdr.id = HtOperation::kMaxLen; // same as kMinLen
dst.primary_chan = ddk.primary_chan;
dst.head.set_val(ddk.head);
dst.tail.set_val(ddk.tail);
dst.basic_mcs_set.rx_mcs_head.set_val(ddk.basic_mcs_set.rx_mcs_head);
dst.basic_mcs_set.rx_mcs_tail.set_val(ddk.basic_mcs_set.rx_mcs_tail);
dst.basic_mcs_set.tx_mcs.set_val(ddk.basic_mcs_set.tx_mcs);
return dst;
}
wlan_ht_op_t ToDdk() const {
wlan_ht_op_t ddk{};
ddk.primary_chan = primary_chan;
ddk.head = head.val();
ddk.tail = tail.val();
ddk.basic_mcs_set.rx_mcs_head = basic_mcs_set.rx_mcs_head.val();
ddk.basic_mcs_set.rx_mcs_tail = basic_mcs_set.rx_mcs_tail.val();
ddk.basic_mcs_set.tx_mcs = basic_mcs_set.tx_mcs.val();
return ddk;
}
static HtOperation FromFidl(const ::fuchsia::wlan::mlme::HtOperation& fidl) {
HtOperation dst;
dst.primary_chan = fidl.primary_chan;
dst.basic_mcs_set = SupportedMcsSet::FromFidl(fidl.basic_mcs_set);
const auto& hoi = fidl.ht_op_info;
dst.head.set_secondary_chan_offset(
static_cast<HtOpInfoHead::SecChanOffset>(hoi.secondary_chan_offset));
dst.head.set_sta_chan_width(static_cast<HtOpInfoHead::StaChanWidth>(hoi.sta_chan_width));
dst.head.set_rifs_mode(hoi.rifs_mode ? 1 : 0);
dst.head.set_ht_protect(static_cast<HtOpInfoHead::HtProtect>(hoi.ht_protect));
dst.head.set_nongreenfield_present(hoi.nongreenfield_present ? 1 : 0);
dst.head.set_obss_non_ht(hoi.obss_non_ht ? 1 : 0);
dst.head.set_center_freq_seg2(hoi.center_freq_seg2);
dst.head.set_dual_beacon(hoi.dual_beacon ? 1 : 0);
dst.head.set_dual_cts_protect(hoi.dual_cts_protect ? 1 : 0);
dst.tail.set_stbc_beacon(hoi.stbc_beacon ? 1 : 0);
dst.tail.set_lsig_txop_protect(hoi.lsig_txop_protect ? 1 : 0);
dst.tail.set_pco_active(hoi.pco_active ? 1 : 0);
dst.tail.set_pco_phase(hoi.pco_phase ? 1 : 0);
return dst;
}
::fuchsia::wlan::mlme::HtOperation ToFidl() const {
::fuchsia::wlan::mlme::HtOperation fidl;
fidl.primary_chan = primary_chan;
fidl.basic_mcs_set = basic_mcs_set.ToFidl();
auto* ht_op_info = &fidl.ht_op_info;
ht_op_info->secondary_chan_offset = head.secondary_chan_offset();
ht_op_info->sta_chan_width = head.sta_chan_width();
ht_op_info->rifs_mode = (head.rifs_mode() == 1);
ht_op_info->ht_protect = head.ht_protect();
ht_op_info->nongreenfield_present = (head.nongreenfield_present() == 1);
ht_op_info->obss_non_ht = (head.obss_non_ht() == 1);
ht_op_info->center_freq_seg2 = head.center_freq_seg2();
ht_op_info->dual_beacon = (head.dual_beacon() == 1);
ht_op_info->dual_cts_protect = (head.dual_cts_protect() == 1);
ht_op_info->stbc_beacon = (tail.stbc_beacon() == 1);
ht_op_info->lsig_txop_protect = (tail.lsig_txop_protect() == 1);
ht_op_info->pco_active = (tail.pco_active() == 1);
ht_op_info->pco_phase = (tail.pco_phase() == 1);
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.126
struct GcrGroupAddressElement {
static bool Create(void* buf, size_t len, size_t* actual, const common::MacAddr& addr);
static const size_t kMinLen = common::kMacAddrLen;
static const size_t kMaxLen = common::kMacAddrLen;
ElementHeader hdr;
common::MacAddr gcr_group_addr;
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.158.2
// Note this is a field of VhtCapabilities element
struct VhtCapabilitiesInfo : public common::BitField<uint32_t> {
public:
constexpr explicit VhtCapabilitiesInfo(uint32_t vht_cap_info)
: common::BitField<uint32_t>(vht_cap_info) {}
constexpr VhtCapabilitiesInfo() = default;
WLAN_BIT_FIELD(max_mpdu_len, 0, 2);
// Supported channel width set. See IEEE Std 80.211-2016, Table 9-250.
WLAN_BIT_FIELD(supported_cbw_set, 2, 2);
WLAN_BIT_FIELD(rx_ldpc, 4, 1);
WLAN_BIT_FIELD(sgi_cbw80, 5, 1); // CBW80 only
WLAN_BIT_FIELD(sgi_cbw160, 6, 1); // CBW160 and CBW80P80
WLAN_BIT_FIELD(tx_stbc, 7, 1);
WLAN_BIT_FIELD(rx_stbc, 8, 3);
WLAN_BIT_FIELD(su_bfer, 11, 1); // Single user beamformer capable
WLAN_BIT_FIELD(su_bfee, 12, 1); // Single user beamformee capable
WLAN_BIT_FIELD(bfee_sts, 13, 3); // Beamformee Space-time spreading
WLAN_BIT_FIELD(num_sounding, 16, 3); // number of sounding dimensions
WLAN_BIT_FIELD(mu_bfer, 19, 1); // Multi user beamformer capable
WLAN_BIT_FIELD(mu_bfee, 20, 1); // Multi user beamformee capable
WLAN_BIT_FIELD(txop_ps, 21, 1); // Txop power save mode
WLAN_BIT_FIELD(htc_vht, 22, 1);
WLAN_BIT_FIELD(max_ampdu_exp, 23, 3);
WLAN_BIT_FIELD(link_adapt, 26, 2); // VHT link adaptation capable
WLAN_BIT_FIELD(rx_ant_pattern, 28, 1);
WLAN_BIT_FIELD(tx_ant_pattern, 29, 1);
// Extended number of spatial stream bandwidth supported
// See IEEE Std 80.211-2016, Table 9-250.
WLAN_BIT_FIELD(ext_nss_bw, 30, 2);
enum MaxMpduLen {
OCTETS_3895 = 0,
OCTETS_7991 = 1,
OCTETS_11454 = 2,
// 3 reserved
};
enum VhtLinkAdaptation {
LINK_ADAPT_NO_FEEDBACK = 0,
// 1 reserved
LINK_ADAPT_UNSOLICITED = 2,
LINK_ADAPT_BOTH = 3,
};
static VhtCapabilitiesInfo FromFidl(const ::fuchsia::wlan::mlme::VhtCapabilitiesInfo& fidl) {
VhtCapabilitiesInfo dst;
dst.set_max_mpdu_len(static_cast<MaxMpduLen>(fidl.max_mpdu_len));
dst.set_supported_cbw_set(fidl.supported_cbw_set);
dst.set_rx_ldpc(fidl.rx_ldpc ? 1 : 0);
dst.set_sgi_cbw80(fidl.sgi_cbw80 ? 1 : 0);
dst.set_sgi_cbw160(fidl.sgi_cbw160 ? 1 : 0);
dst.set_tx_stbc(fidl.tx_stbc ? 1 : 0);
dst.set_rx_stbc(fidl.rx_stbc ? 1 : 0);
dst.set_su_bfer(fidl.su_bfer ? 1 : 0);
dst.set_su_bfee(fidl.su_bfee ? 1 : 0);
dst.set_bfee_sts(fidl.bfee_sts);
dst.set_num_sounding(fidl.num_sounding);
dst.set_mu_bfer(fidl.mu_bfer ? 1 : 0);
dst.set_mu_bfee(fidl.mu_bfee ? 1 : 0);
dst.set_txop_ps(fidl.txop_ps ? 1 : 0);
dst.set_htc_vht(fidl.htc_vht ? 1 : 0);
dst.set_max_ampdu_exp(fidl.max_ampdu_exp);
dst.set_link_adapt(static_cast<VhtLinkAdaptation>(fidl.link_adapt));
dst.set_rx_ant_pattern(fidl.rx_ant_pattern ? 1 : 0);
dst.set_tx_ant_pattern(fidl.tx_ant_pattern ? 1 : 0);
dst.set_ext_nss_bw(fidl.ext_nss_bw);
return dst;
}
::fuchsia::wlan::mlme::VhtCapabilitiesInfo ToFidl() const {
::fuchsia::wlan::mlme::VhtCapabilitiesInfo fidl;
fidl.max_mpdu_len = max_mpdu_len();
fidl.supported_cbw_set = supported_cbw_set();
fidl.rx_ldpc = (rx_ldpc() == 1);
fidl.sgi_cbw80 = (sgi_cbw80() == 1);
fidl.sgi_cbw160 = (sgi_cbw160() == 1);
fidl.tx_stbc = (tx_stbc() == 1);
fidl.rx_stbc = (rx_stbc() == 1);
fidl.su_bfer = (su_bfer() == 1);
fidl.su_bfee = (su_bfee() == 1);
fidl.bfee_sts = bfee_sts();
fidl.num_sounding = num_sounding();
fidl.mu_bfer = (mu_bfer() == 1);
fidl.mu_bfee = (mu_bfee() == 1);
fidl.txop_ps = (txop_ps() == 1);
fidl.htc_vht = (htc_vht() == 1);
fidl.max_ampdu_exp = max_ampdu_exp();
fidl.link_adapt = link_adapt();
fidl.rx_ant_pattern = (rx_ant_pattern() == 1);
fidl.tx_ant_pattern = (tx_ant_pattern() == 1);
fidl.ext_nss_bw = ext_nss_bw();
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.158.3
struct VhtMcsNss : public common::BitField<uint64_t> {
public:
constexpr explicit VhtMcsNss(uint64_t vht_mcs_nss) : common::BitField<uint64_t>(vht_mcs_nss) {}
constexpr VhtMcsNss() = default;
// Rx VHT-MCS Map
WLAN_BIT_FIELD(rx_max_mcs_ss1, 0, 2);
WLAN_BIT_FIELD(rx_max_mcs_ss2, 2, 2);
WLAN_BIT_FIELD(rx_max_mcs_ss3, 4, 2);
WLAN_BIT_FIELD(rx_max_mcs_ss4, 6, 2);
WLAN_BIT_FIELD(rx_max_mcs_ss5, 8, 2);
WLAN_BIT_FIELD(rx_max_mcs_ss6, 10, 2);
WLAN_BIT_FIELD(rx_max_mcs_ss7, 12, 2);
WLAN_BIT_FIELD(rx_max_mcs_ss8, 14, 2);
WLAN_BIT_FIELD(rx_max_data_rate, 16, 13);
WLAN_BIT_FIELD(max_nsts, 29, 3);
// Tx VHT-MCS Map
WLAN_BIT_FIELD(tx_max_mcs_ss1, 32, 2);
WLAN_BIT_FIELD(tx_max_mcs_ss2, 34, 2);
WLAN_BIT_FIELD(tx_max_mcs_ss3, 36, 2);
WLAN_BIT_FIELD(tx_max_mcs_ss4, 38, 2);
WLAN_BIT_FIELD(tx_max_mcs_ss5, 40, 2);
WLAN_BIT_FIELD(tx_max_mcs_ss6, 42, 2);
WLAN_BIT_FIELD(tx_max_mcs_ss7, 44, 2);
WLAN_BIT_FIELD(tx_max_mcs_ss8, 46, 2);
WLAN_BIT_FIELD(tx_max_data_rate, 48, 13);
WLAN_BIT_FIELD(ext_nss_bw, 61, 1);
// bit 62, 63 reserved
enum VhtMcsSet {
VHT_MCS_0_TO_7 = 0,
VHT_MCS_0_TO_8 = 1,
VHT_MCS_0_TO_9 = 2,
VHT_MCS_NONE = 3,
};
uint8_t get_rx_max_mcs_ss(uint8_t ss_num) const {
ZX_DEBUG_ASSERT(1 <= ss_num && ss_num <= 8);
constexpr uint8_t kMcsBitOffset = 0; // rx_max_mcs_ss1
constexpr uint8_t kBitWidth = 2;
uint8_t offset = kMcsBitOffset + (ss_num - 1) * kBitWidth;
uint64_t mask = ((1ull << kBitWidth) - 1) << offset;
return (val() & mask) >> offset;
}
uint8_t get_tx_max_mcs_ss(uint8_t ss_num) const {
ZX_DEBUG_ASSERT(1 <= ss_num && ss_num <= 8);
constexpr uint8_t kMcsBitOffset = 32; // tx_max_mcs_ss1
constexpr uint8_t kBitWidth = 2;
uint8_t offset = kMcsBitOffset + (ss_num - 1) * kBitWidth;
uint64_t mask = ((1ull << kBitWidth) - 1) << offset;
return (val() & mask) >> offset;
}
void set_rx_max_mcs_ss(uint8_t ss_num, uint8_t mcs) {
ZX_DEBUG_ASSERT(1 <= ss_num && ss_num <= 8);
constexpr uint8_t kMcsBitOffset = 0; // rx_max_mcs_ss1
constexpr uint8_t kBitWidth = 2;
uint8_t offset = kMcsBitOffset + (ss_num - 1) * kBitWidth;
uint64_t mcs_val = static_cast<uint64_t>(mcs) << offset;
set_val(val() | mcs_val);
}
void set_tx_max_mcs_ss(uint8_t ss_num, uint8_t mcs) {
ZX_DEBUG_ASSERT(1 <= ss_num && ss_num <= 8);
constexpr uint8_t kMcsBitOffset = 32; // tx_max_mcs_ss1
constexpr uint8_t kBitWidth = 2;
uint8_t offset = kMcsBitOffset + (ss_num - 1) * kBitWidth;
uint64_t mcs_val = static_cast<uint64_t>(mcs) << offset;
set_val(val() | mcs_val);
}
static VhtMcsNss FromFidl(const ::fuchsia::wlan::mlme::VhtMcsNss& fidl) {
VhtMcsNss dst;
for (uint8_t ss_num = 1; ss_num <= 8; ss_num++) {
dst.set_rx_max_mcs_ss(ss_num, fidl.rx_max_mcs[ss_num - 1]);
}
dst.set_rx_max_data_rate(fidl.rx_max_data_rate);
dst.set_tx_max_data_rate(fidl.tx_max_data_rate);
for (uint8_t ss_num = 1; ss_num <= 8; ss_num++) {
dst.set_tx_max_mcs_ss(ss_num, fidl.tx_max_mcs[ss_num - 1]);
}
dst.set_max_nsts(fidl.max_nsts);
dst.set_ext_nss_bw(fidl.ext_nss_bw);
return dst;
}
::fuchsia::wlan::mlme::VhtMcsNss ToFidl() const {
::fuchsia::wlan::mlme::VhtMcsNss fidl;
for (uint8_t ss_num = 1; ss_num <= 8; ss_num++) {
fidl.rx_max_mcs[ss_num - 1] = get_rx_max_mcs_ss(ss_num);
}
fidl.rx_max_data_rate = rx_max_data_rate();
fidl.max_nsts = max_nsts();
for (uint8_t ss_num = 1; ss_num <= 8; ss_num++) {
fidl.tx_max_mcs[ss_num - 1] = get_tx_max_mcs_ss(ss_num);
}
fidl.tx_max_data_rate = tx_max_data_rate();
fidl.ext_nss_bw = (ext_nss_bw() == 1);
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, 9.4.2.158
struct VhtCapabilities : public Element<VhtCapabilities, element_id::kVhtCapabilities> {
static bool Create(void* buf, size_t len, size_t* actual,
const VhtCapabilitiesInfo& vht_cap_info, const VhtMcsNss& vht_mcs_nss);
static constexpr size_t kMinLen = 12;
static constexpr size_t kMaxLen = 12;
ElementHeader hdr;
VhtCapabilitiesInfo vht_cap_info;
VhtMcsNss vht_mcs_nss;
static VhtCapabilities FromDdk(const wlan_vht_caps_t& ddk) {
VhtCapabilities dst{};
dst.hdr.id = element_id::kVhtCapabilities;
dst.hdr.len = VhtCapabilities::kMaxLen; // same as kMinLen
dst.vht_cap_info.set_val(ddk.vht_capability_info);
dst.vht_mcs_nss.set_val(ddk.supported_vht_mcs_and_nss_set);
return dst;
}
wlan_vht_caps_t ToDdk() const {
wlan_vht_caps_t ddk{};
ddk.vht_capability_info = vht_cap_info.val();
ddk.supported_vht_mcs_and_nss_set = vht_mcs_nss.val();
return ddk;
}
static VhtCapabilities FromFidl(const ::fuchsia::wlan::mlme::VhtCapabilities& fidl) {
VhtCapabilities dst;
dst.vht_cap_info = VhtCapabilitiesInfo::FromFidl(fidl.vht_cap_info);
dst.vht_mcs_nss = VhtMcsNss::FromFidl(fidl.vht_mcs_nss);
return dst;
}
::fuchsia::wlan::mlme::VhtCapabilities ToFidl() const {
::fuchsia::wlan::mlme::VhtCapabilities fidl;
fidl.vht_cap_info = vht_cap_info.ToFidl();
fidl.vht_mcs_nss = vht_mcs_nss.ToFidl();
return fidl;
}
} __PACKED;
// IEEE Std 802.11-2016, Figure 9-562
struct BasicVhtMcsNss : public common::BitField<uint16_t> {
public:
constexpr explicit BasicVhtMcsNss(uint16_t basic_mcs) : common::BitField<uint16_t>(basic_mcs) {}
constexpr BasicVhtMcsNss() = default;
WLAN_BIT_FIELD(ss1, 0, 2);
WLAN_BIT_FIELD(ss2, 2, 2);
WLAN_BIT_FIELD(ss3, 4, 2);
WLAN_BIT_FIELD(ss4, 6, 2);
WLAN_BIT_FIELD(ss5, 8, 2);
WLAN_BIT_FIELD(ss6, 10, 2);
WLAN_BIT_FIELD(ss7, 12, 2);
WLAN_BIT_FIELD(ss8, 14, 2);
enum VhtMcsEncoding {
VHT_MCS_0_TO_7 = 0,
VHT_MCS_0_TO_8 = 1,
VHT_MCS_0_TO_9 = 2,
VHT_MCS_NONE = 3,
};
uint8_t get_max_mcs_ss(uint8_t ss_num) const {
ZX_DEBUG_ASSERT(1 <= ss_num && ss_num <= 8);
constexpr uint8_t kMcsBitOffset = 0; // ss1
constexpr uint8_t kBitWidth = 2;
uint8_t offset = kMcsBitOffset + (ss_num - 1) * kBitWidth;
uint64_t mask = ((1ull << kBitWidth) - 1) << offset;
return (val() & mask) >> offset;
}
void set_max_mcs_ss(uint8_t ss_num, uint8_t mcs) {
ZX_DEBUG_ASSERT(1 <= ss_num && ss_num <= 8);
constexpr uint8_t kMcsBitOffset = 0; // ss1
constexpr uint8_t kBitWidth = 2;
uint8_t offset = kMcsBitOffset + (ss_num - 1) * kBitWidth;
uint64_t mcs_val = static_cast<uint64_t>(mcs) << offset;
set_val(val() | mcs_val);
}
static BasicVhtMcsNss FromFidl(const ::fuchsia::wlan::mlme::BasicVhtMcsNss& fidl) {
BasicVhtMcsNss dst;
for (uint8_t ss_num = 1; ss_num <= 8; ++ss_num) {
dst.set_max_mcs_ss(ss_num, fidl.max_mcs[ss_num - 1]);
}
return dst;
}
::fuchsia::wlan::mlme::BasicVhtMcsNss ToFidl() const {
::fuchsia::wlan::mlme::BasicVhtMcsNss fidl;
for (uint8_t ss_num = 1; ss_num <= 8; ss_num++) {
fidl.max_mcs[ss_num - 1] = get_max_mcs_ss(ss_num);
}
return fidl;
}
};
// IEEE Std 802.11-2016, 9.4.2.159
struct VhtOperation : public Element<VhtOperation, element_id::kVhtOperation> {
static bool Create(void* buf, size_t len, size_t* actual, uint8_t vht_cbw,
uint8_t center_freq_seg0, uint8_t center_freq_seg1,
const BasicVhtMcsNss& basic_mcs);
static constexpr size_t kMinLen = 5;
static constexpr size_t kMaxLen = 5;
ElementHeader hdr;
uint8_t vht_cbw;
uint8_t center_freq_seg0;
uint8_t center_freq_seg1;
BasicVhtMcsNss basic_mcs;
enum VhtChannelBandwidth {
VHT_CBW_20_40 = 0,
VHT_CBW_80_160_80P80 = 1,
VHT_CBW_160 = 2, // Deprecated
VHT_CBW_80P80 = 3, // Deprecated
// 4 - 255 reserved
};
static VhtOperation FromDdk(const wlan_vht_op_t& ddk) {
VhtOperation dst{};
dst.vht_cbw = ddk.vht_cbw;
dst.center_freq_seg0 = ddk.center_freq_seg0;
dst.center_freq_seg1 = ddk.center_freq_seg1;
dst.basic_mcs.set_val(ddk.basic_mcs);
return dst;
}
wlan_vht_op_t ToDdk() const {
wlan_vht_op_t dst{};
dst.vht_cbw = vht_cbw;
dst.center_freq_seg0 = center_freq_seg0;
dst.center_freq_seg1 = center_freq_seg1;
dst.basic_mcs = basic_mcs.val();
return dst;
}
static VhtOperation FromFidl(const ::fuchsia::wlan::mlme::VhtOperation& fidl) {
VhtOperation dst;
dst.vht_cbw = static_cast<VhtChannelBandwidth>(fidl.vht_cbw);
dst.center_freq_seg0 = fidl.center_freq_seg0;
dst.center_freq_seg1 = fidl.center_freq_seg1;
dst.basic_mcs = BasicVhtMcsNss::FromFidl(fidl.basic_mcs);
return dst;
}
::fuchsia::wlan::mlme::VhtOperation ToFidl() const {
::fuchsia::wlan::mlme::VhtOperation fidl;
fidl.vht_cbw = vht_cbw;
fidl.center_freq_seg0 = center_freq_seg0;
fidl.center_freq_seg1 = center_freq_seg1;
fidl.basic_mcs = basic_mcs.ToFidl();
return fidl;
}
} __PACKED;
SupportedMcsSet IntersectMcs(const SupportedMcsSet& lhs, const SupportedMcsSet& rhs);
HtCapabilities IntersectHtCap(const HtCapabilities& lhs, const HtCapabilities& rhs);
VhtCapabilities IntersectVhtCap(const VhtCapabilities& lhs, const VhtCapabilities& rhs);
// Find common legacy rates between AP and client.
// The outcoming "Basic rates" follows those specified in AP
std::vector<SupportedRate> IntersectRatesAp(const std::vector<SupportedRate>& ap_rates,
const std::vector<SupportedRate>& client_rates);
} // namespace wlan
| 36.477826 | 100 | 0.662609 |
4d149f984ecb4aa5654fab94d8c56e0dd6fbfb9b | 2,884 | h | C | dbms/src/Common/HashTable/FixedClearableHashMap.h | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 85 | 2022-03-25T09:03:16.000Z | 2022-03-25T09:45:03.000Z | dbms/src/Common/HashTable/FixedClearableHashMap.h | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 7 | 2022-03-25T08:59:10.000Z | 2022-03-25T09:40:13.000Z | dbms/src/Common/HashTable/FixedClearableHashMap.h | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 11 | 2022-03-25T09:15:36.000Z | 2022-03-25T09:45:07.000Z | // Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <Common/HashTable/ClearableHashMap.h>
#include <Common/HashTable/FixedHashMap.h>
template <typename Key, typename TMapped>
struct FixedClearableHashMapCell
{
using Mapped = TMapped;
using State = ClearableHashSetState;
using value_type = PairNoInit<Key, Mapped>;
using mapped_type = Mapped;
UInt32 version;
Mapped mapped;
FixedClearableHashMapCell() = default;
FixedClearableHashMapCell(const Key &, const State & state)
: version(state.version)
{}
FixedClearableHashMapCell(const value_type & value_, const State & state)
: version(state.version)
, mapped(value_.second)
{}
VoidKey getKey() const { return {}; }
Mapped & getMapped() { return mapped; }
const Mapped & getMapped() const { return mapped; }
bool isZero(const State & state) const { return version != state.version; }
void setZero() { version = 0; }
struct CellExt
{
CellExt() = default;
CellExt(Key && key_, FixedClearableHashMapCell * ptr_)
: key(key_)
, ptr(ptr_)
{}
void update(Key && key_, FixedClearableHashMapCell * ptr_)
{
key = key_;
ptr = ptr_;
}
Key key;
FixedClearableHashMapCell * ptr;
const Key & getKey() const { return key; }
Mapped & getMapped() { return ptr->mapped; }
const Mapped & getMapped() const { return *ptr->mapped; }
value_type getValue() const { return {key, *ptr->mapped}; }
};
};
template <typename Key, typename Mapped, typename Allocator = HashTableAllocator>
class FixedClearableHashMap : public FixedHashMap<Key, Mapped, FixedClearableHashMapCell<Key, Mapped>, Allocator>
{
public:
using Base = FixedHashMap<Key, Mapped, FixedClearableHashMapCell<Key, Mapped>, Allocator>;
using Self = FixedClearableHashMap;
using LookupResult = typename Base::LookupResult;
using Base::Base;
Mapped & operator[](const Key & x)
{
LookupResult it;
bool inserted;
this->emplace(x, it, inserted);
if (inserted)
new (&it->getMapped()) Mapped();
return it->getMapped();
}
void clear()
{
++this->version;
this->m_size = 0;
}
};
| 29.428571 | 113 | 0.648405 |
3116626a807fefdfaae356103fd4ca8238db229e | 626 | h | C | src/cpp/IdpResponse.h | VitalElement/IdpProtocol | 323531da023d853ddb59794d225fb7e39c0a6943 | [
"MIT"
] | 2 | 2018-10-02T19:06:41.000Z | 2019-03-14T02:20:08.000Z | src/cpp/IdpResponse.h | VitalElement/IdpProtocol | 323531da023d853ddb59794d225fb7e39c0a6943 | [
"MIT"
] | null | null | null | src/cpp/IdpResponse.h | VitalElement/IdpProtocol | 323531da023d853ddb59794d225fb7e39c0a6943 | [
"MIT"
] | null | null | null | // Copyright (c) VitalElement. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for
// full license information.
#pragma once
#include "IncomingTransaction.h"
/**
* IdpResponse
*/
class IdpResponse
{
private:
IdpResponseCode _responseCode;
uint16_t _responseId;
std::shared_ptr<IncomingTransaction> _transaction;
public:
IdpResponse (std::shared_ptr<IncomingTransaction> incomingTransaction);
IdpResponseCode ResponseCode ();
uint16_t ResponseId ();
uint32_t TransactionId ();
std::shared_ptr<IncomingTransaction> Transaction ();
};
| 21.586207 | 78 | 0.736422 |
035a86a48dd19def5d98327313f7ac34c1cf44a1 | 1,162 | h | C | tools/ifaceed/ifaceed/scripting/scenenodes/scenenodesoptionssetter.h | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 58 | 2015-08-09T14:56:35.000Z | 2022-01-15T22:06:58.000Z | tools/ifaceed/ifaceed/scripting/scenenodes/scenenodesoptionssetter.h | mamontov-cpp/saddy-graphics-engine-2d | e25a6637fcc49cb26614bf03b70e5d03a3a436c7 | [
"BSD-2-Clause"
] | 245 | 2015-08-08T08:44:22.000Z | 2022-01-04T09:18:08.000Z | tools/ifaceed/ifaceed/scripting/scenenodes/scenenodesoptionssetter.h | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 23 | 2015-12-06T03:57:49.000Z | 2020-10-12T14:15:50.000Z | /*! \file scenenodesoptionssetter.h
Describes a setter for options property of scene node (used for sad::Sprite2D and custom objects)
*/
#pragma once
#include "scenenodessetter.h"
namespace scripting
{
namespace scenenodes
{
/*! A setter for options property of sprite
*/
class OptionsSetter: public scripting::scenenodes::AbstractSetter<sad::String>
{
public:
/*! Creates new setter for setting options property of object
\param scripting a scripting object
*/
OptionsSetter(scripting::Scripting* scripting);
/*! Clones an object
\return copy of object
*/
dukpp03::qt::Callable* clone() override;
/*! Could be inherited
*/
virtual ~OptionsSetter();
/*! Returns command for editing a property
\param[in] obj an object to be set
\param[in] prop property name
\param[in] old_value old value
\param[in] new_value new value
\return a command to be used
*/
virtual history::Command* command(sad::SceneNode* obj, const sad::String& prop, sad::String old_value, sad::String new_value) override;
};
}
}
| 27.023256 | 140 | 0.650602 |
03eed6ce162156915217f47fe90c510e3d4b695f | 927 | h | C | DashWallet/Sources/UI/Views/DWUIKit.h | magicwave/dashwallet-ios | 57ca6d4cc2cd8ea699f294580e6e3f62d25c3f22 | [
"MIT"
] | 51 | 2016-01-19T12:01:58.000Z | 2019-02-03T19:46:24.000Z | DashWallet/Sources/UI/Views/DWUIKit.h | magicwave/dashwallet-ios | 57ca6d4cc2cd8ea699f294580e6e3f62d25c3f22 | [
"MIT"
] | 32 | 2015-10-31T07:01:03.000Z | 2019-01-09T15:48:54.000Z | DashWallet/Sources/UI/Views/DWUIKit.h | magicwave/dashwallet-ios | 57ca6d4cc2cd8ea699f294580e6e3f62d25c3f22 | [
"MIT"
] | 38 | 2015-09-17T00:35:53.000Z | 2021-04-29T06:08:40.000Z | //
// Created by Andrew Podkovyrin
// Copyright © 2019 Dash Core Group. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef DWUIKit_h
#define DWUIKit_h
#import "UIColor+DWStyle.h"
#import "UIFont+DWFont.h"
#import "UIView+DWAnimations.h"
#import "CALayer+DWShadow.h"
#import "DevicesCompatibility.h"
#import "UIView+DWReuseHelper.h"
#import "UIViewController+DWEmbedding.h"
#endif /* DWUIKit_h */
| 28.090909 | 76 | 0.740022 |
03fb7da5048ae9a53cbf519459c1323c73bfcc63 | 958 | h | C | src/hash.h | jaitengill/crypt-local | 6e003ab5ee7f936a8e2def8b5e9f793f8e76d685 | [
"MIT"
] | 6 | 2015-01-08T09:58:37.000Z | 2022-02-16T03:45:58.000Z | src/hash.h | GabrielJacobson91/dcrypt | 988ecc26edf397abf82dca7217a0f6234b7cf4aa | [
"MIT"
] | 1 | 2015-05-29T16:13:18.000Z | 2015-05-29T16:13:18.000Z | src/hash.h | GabrielJacobson91/dcrypt | 988ecc26edf397abf82dca7217a0f6234b7cf4aa | [
"MIT"
] | 6 | 2015-01-09T13:04:13.000Z | 2022-02-16T03:45:59.000Z | #ifndef __NODE_DCRYPT_HASH_H__
#define __NODE_DCRYPT_HASH_H__
#include <v8.h>
#include <node.h>
#include <node_object_wrap.h>
#include <node_buffer.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "common.h"
using namespace v8;
using namespace node;
class Hash: node::ObjectWrap {
public:
static Persistent<FunctionTemplate> constructor;
static void Initialize(Handle<Object> target);
bool HashInit(const char *hashType, const Arguments &args);
int HashUpdate(char *data, int len);
Hash();
protected:
static Handle<Value> New(const Arguments &args);
static Handle<Value> HashUpdate(const Arguments &args);
static Handle<Value> HashDigest(const Arguments &args);
private:
EVP_MD_CTX *mdctx; /* coverity[member_decl] */
const EVP_MD *md; /* coverity[member_decl] */
bool initialised_;
~Hash();
};
#endif
| 21.288889 | 63 | 0.7119 |
26d3a2dcb451a105e6a2e5c12cce499aca8e4c22 | 11,155 | c | C | contrib/python/scikit-learn/py2/sklearn/svm/src/libsvm/libsvm_helper.c | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | contrib/python/scikit-learn/py2/sklearn/svm/src/libsvm/libsvm_helper.c | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | contrib/python/scikit-learn/py2/sklearn/svm/src/libsvm/libsvm_helper.c | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | #include <stdlib.h>
#include <numpy/arrayobject.h>
#include "svm.h"
/*
* Some helper methods for libsvm bindings.
*
* We need to access from python some parameters stored in svm_model
* but libsvm does not expose this structure, so we define it here
* along some utilities to convert from numpy arrays.
*
* License: BSD 3 clause
*
* Author: 2010 Fabian Pedregosa <fabian.pedregosa@inria.fr>
*/
/*
* Convert matrix to sparse representation suitable for libsvm. x is
* expected to be an array of length nrow*ncol.
*
* Typically the matrix will be dense, so we speed up the routine for
* this case. We create a temporary array temp that collects non-zero
* elements and after we just memcpy that to the proper array.
*
* Special care must be taken with indinces, since libsvm indices start
* at 1 and not at 0.
*
* Strictly speaking, the C standard does not require that structs are
* contiguous, but in practice its a reasonable assumption.
*
*/
static
struct svm_node *dense_to_libsvm (double *x, npy_intp *dims)
{
struct svm_node *node;
npy_intp len_row = dims[1];
double *tx = x;
int i;
node = malloc (dims[0] * sizeof(struct svm_node));
if (node == NULL) return NULL;
for (i=0; i<dims[0]; ++i) {
node[i].values = tx;
node[i].dim = (int) len_row;
node[i].ind = i; /* only used if kernel=precomputed, but not
too much overhead */
tx += len_row;
}
return node;
}
/*
* Fill an svm_parameter struct.
*/
static
void set_parameter(struct svm_parameter *param, int svm_type, int kernel_type, int degree,
double gamma, double coef0, double nu, double cache_size, double C,
double eps, double p, int shrinking, int probability, int nr_weight,
char *weight_label, char *weight, int max_iter, int random_seed)
{
param->svm_type = svm_type;
param->kernel_type = kernel_type;
param->degree = degree;
param->coef0 = coef0;
param->nu = nu;
param->cache_size = cache_size;
param->C = C;
param->eps = eps;
param->p = p;
param->shrinking = shrinking;
param->probability = probability;
param->nr_weight = nr_weight;
param->weight_label = (int *) weight_label;
param->weight = (double *) weight;
param->gamma = gamma;
param->max_iter = max_iter;
param->random_seed = random_seed;
}
/*
* Fill an svm_problem struct. problem->x will be malloc'd.
*/
static
void set_problem(struct svm_problem *problem, char *X, char *Y, char *sample_weight, npy_intp *dims, int kernel_type)
{
if (problem == NULL) return;
problem->l = (int) dims[0]; /* number of samples */
problem->y = (double *) Y;
problem->x = dense_to_libsvm((double *) X, dims); /* implicit call to malloc */
problem->W = (double *) sample_weight;
}
/*
* Create and return an instance of svm_model.
*
* The copy of model->sv_coef should be straightforward, but
* unfortunately to represent a matrix numpy and libsvm use different
* approaches, so it requires some iteration.
*
* Possible issue: on 64 bits, the number of columns that numpy can
* store is a long, but libsvm enforces this number (model->l) to be
* an int, so we might have numpy matrices that do not fit into libsvm's
* data structure.
*
*/
static
struct svm_model *set_model(struct svm_parameter *param, int nr_class,
char *SV, npy_intp *SV_dims,
char *support, npy_intp *support_dims,
npy_intp *sv_coef_strides,
char *sv_coef, char *rho, char *nSV,
char *probA, char *probB)
{
struct svm_model *model;
double *dsv_coef = (double *) sv_coef;
int i, m;
m = nr_class * (nr_class-1)/2;
if ((model = malloc(sizeof(struct svm_model))) == NULL)
goto model_error;
if ((model->nSV = malloc(nr_class * sizeof(int))) == NULL)
goto nsv_error;
if ((model->label = malloc(nr_class * sizeof(int))) == NULL)
goto label_error;
if ((model->sv_coef = malloc((nr_class-1)*sizeof(double *))) == NULL)
goto sv_coef_error;
if ((model->rho = malloc( m * sizeof(double))) == NULL)
goto rho_error;
model->nr_class = nr_class;
model->param = *param;
model->l = (int) support_dims[0];
if (param->kernel_type == PRECOMPUTED) {
if ((model->SV = malloc ((model->l) * sizeof(struct svm_node))) == NULL)
goto SV_error;
for (i=0; i<model->l; ++i) {
model->SV[i].ind = ((int *) support)[i];
model->SV[i].values = NULL;
}
} else {
model->SV = dense_to_libsvm((double *) SV, SV_dims);
}
/*
* regression and one-class does not use nSV, label.
* TODO: does this provoke memory leaks (we just malloc'ed them)?
*/
if (param->svm_type < 2) {
memcpy(model->nSV, nSV, model->nr_class * sizeof(int));
for(i=0; i < model->nr_class; i++)
model->label[i] = i;
}
for (i=0; i < model->nr_class-1; i++) {
model->sv_coef[i] = dsv_coef + i*(model->l);
}
for (i=0; i<m; ++i) {
(model->rho)[i] = -((double *) rho)[i];
}
/*
* just to avoid segfaults, these features are not wrapped but
* svm_destroy_model will try to free them.
*/
if (param->probability) {
if ((model->probA = malloc(m * sizeof(double))) == NULL)
goto probA_error;
memcpy(model->probA, probA, m * sizeof(double));
if ((model->probB = malloc(m * sizeof(double))) == NULL)
goto probB_error;
memcpy(model->probB, probB, m * sizeof(double));
} else {
model->probA = NULL;
model->probB = NULL;
}
/* We'll free SV ourselves */
model->free_sv = 0;
return model;
probB_error:
free(model->probA);
probA_error:
free(model->SV);
SV_error:
free(model->rho);
rho_error:
free(model->sv_coef);
sv_coef_error:
free(model->label);
label_error:
free(model->nSV);
nsv_error:
free(model);
model_error:
return NULL;
}
/*
* Get the number of support vectors in a model.
*/
static
npy_intp get_l(struct svm_model *model)
{
return (npy_intp) model->l;
}
/*
* Get the number of classes in a model, = 2 in regression/one class
* svm.
*/
static
npy_intp get_nr(struct svm_model *model)
{
return (npy_intp) model->nr_class;
}
/*
* Some helpers to convert from libsvm sparse data structures
* model->sv_coef is a double **, whereas data is just a double *,
* so we have to do some stupid copying.
*/
static
void copy_sv_coef(char *data, struct svm_model *model)
{
int i, len = model->nr_class-1;
double *temp = (double *) data;
for(i=0; i<len; ++i) {
memcpy(temp, model->sv_coef[i], sizeof(double) * model->l);
temp += model->l;
}
}
static
void copy_intercept(char *data, struct svm_model *model, npy_intp *dims)
{
/* intercept = -rho */
npy_intp i, n = dims[0];
double t, *ddata = (double *) data;
for (i=0; i<n; ++i) {
t = model->rho[i];
/* we do this to avoid ugly -0.0 */
*ddata = (t != 0) ? -t : 0;
++ddata;
}
}
/*
* This is a bit more complex since SV are stored as sparse
* structures, so we have to do the conversion on the fly and also
* iterate fast over data.
*/
static
void copy_SV(char *data, struct svm_model *model, npy_intp *dims)
{
int i, n = model->l;
double *tdata = (double *) data;
int dim = model->SV[0].dim;
for (i=0; i<n; ++i) {
memcpy (tdata, model->SV[i].values, dim * sizeof(double));
tdata += dim;
}
}
static
void copy_support (char *data, struct svm_model *model)
{
memcpy (data, model->sv_ind, (model->l) * sizeof(int));
}
/*
* copy svm_model.nSV, an array with the number of SV for each class
* will be NULL in the case of SVR, OneClass
*/
static
void copy_nSV(char *data, struct svm_model *model)
{
if (model->label == NULL) return;
memcpy(data, model->nSV, model->nr_class * sizeof(int));
}
static
void copy_probA(char *data, struct svm_model *model, npy_intp * dims)
{
memcpy(data, model->probA, dims[0] * sizeof(double));
}
static
void copy_probB(char *data, struct svm_model *model, npy_intp * dims)
{
memcpy(data, model->probB, dims[0] * sizeof(double));
}
/*
* Predict using model.
*
* It will return -1 if we run out of memory.
*/
static
int copy_predict(char *predict, struct svm_model *model, npy_intp *predict_dims,
char *dec_values)
{
double *t = (double *) dec_values;
struct svm_node *predict_nodes;
npy_intp i;
predict_nodes = dense_to_libsvm((double *) predict, predict_dims);
if (predict_nodes == NULL)
return -1;
for(i=0; i<predict_dims[0]; ++i) {
*t = svm_predict(model, &predict_nodes[i]);
++t;
}
free(predict_nodes);
return 0;
}
static
int copy_predict_values(char *predict, struct svm_model *model,
npy_intp *predict_dims, char *dec_values, int nr_class)
{
npy_intp i;
struct svm_node *predict_nodes;
predict_nodes = dense_to_libsvm((double *) predict, predict_dims);
if (predict_nodes == NULL)
return -1;
for(i=0; i<predict_dims[0]; ++i) {
svm_predict_values(model, &predict_nodes[i],
((double *) dec_values) + i*nr_class);
}
free(predict_nodes);
return 0;
}
static
int copy_predict_proba(char *predict, struct svm_model *model, npy_intp *predict_dims,
char *dec_values)
{
npy_intp i, n, m;
struct svm_node *predict_nodes;
n = predict_dims[0];
m = (npy_intp) model->nr_class;
predict_nodes = dense_to_libsvm((double *) predict, predict_dims);
if (predict_nodes == NULL)
return -1;
for(i=0; i<n; ++i) {
svm_predict_probability(model, &predict_nodes[i],
((double *) dec_values) + i*m);
}
free(predict_nodes);
return 0;
}
/*
* Some free routines. Some of them are nontrivial since a lot of
* sharing happens across objects (they *must* be called in the
* correct order)
*/
static
int free_model(struct svm_model *model)
{
/* like svm_free_and_destroy_model, but does not free sv_coef[i] */
if (model == NULL) return -1;
free(model->SV);
/* We don't free sv_ind, since we did not create them in
set_model */
/* free(model->sv_ind); */
free(model->sv_coef);
free(model->rho);
free(model->label);
free(model->probA);
free(model->probB);
free(model->nSV);
free(model);
return 0;
}
static
int free_param(struct svm_parameter *param)
{
if (param == NULL) return -1;
free(param);
return 0;
}
/* borrowed from original libsvm code */
static void print_null(const char *s) {}
static void print_string_stdout(const char *s)
{
fputs(s,stdout);
fflush(stdout);
}
/* provide convenience wrapper */
static
void set_verbosity(int verbosity_flag){
if (verbosity_flag)
svm_set_print_string_function(&print_string_stdout);
else
svm_set_print_string_function(&print_null);
}
| 26.496437 | 117 | 0.620977 |
c17ea9f92710a8bea110042974c1792d0199fd41 | 9,762 | h | C | CPPQEDcore/quantumdata/DensityOperator.h | vukics/cppqed | a933375f53b982b14cebf7cb63de300996ddd00b | [
"BSL-1.0"
] | 5 | 2021-02-21T14:00:54.000Z | 2021-07-29T15:12:11.000Z | CPPQEDcore/quantumdata/DensityOperator.h | vukics/cppqed | a933375f53b982b14cebf7cb63de300996ddd00b | [
"BSL-1.0"
] | 10 | 2020-04-14T11:18:02.000Z | 2021-07-04T20:11:23.000Z | CPPQEDcore/quantumdata/DensityOperator.h | vukics/cppqed | a933375f53b982b14cebf7cb63de300996ddd00b | [
"BSL-1.0"
] | 2 | 2021-01-25T10:16:35.000Z | 2021-01-28T18:29:01.000Z | // Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)
/// \briefFileDefault
#ifndef CPPQEDCORE_QUANTUMDATA_DENSITYOPERATOR_H_INCLUDED
#define CPPQEDCORE_QUANTUMDATA_DENSITYOPERATOR_H_INCLUDED
#include "QuantumDataFwd.h"
#include "ArrayBase.h"
#include "DimensionsBookkeeper.h"
#include "LazyDensityOperator.h"
#include "Types.h"
#include "BlitzArrayExtensions.h"
#include "MultiIndexIterator.h"
namespace quantumdata {
/// Density operator of arbitrary arity
/**
* Cf. \ref quantumdatahighlevel "rationale"
*
* \tparamRANK
*
* The DensityOperator interface is similar to StateVector with obvious differences.
*
* \note A DensityOperator `<RANK>` represents a density operator on a Hilbert space of arity `RANK`. This makes that the number of its indices is actually `2*RANK`.
*
*/
template<int RANK>
class DensityOperator
: public LazyDensityOperator<RANK>,
public ArrayBase<DensityOperator<RANK>>
{
public:
static const int N_RANK=RANK;
typedef LazyDensityOperator<RANK> LDO_Base;
typedef ArrayBase<DensityOperator<RANK>> ABase;
typedef typename LDO_Base::Dimensions Dimensions;
typedef typename LDO_Base::Idx Idx;
using DensityOperatorLow=typename ABase::ArrayLow;
typedef linalg::CMatrix CMatrix;
using ABase::frobeniusNorm; using ABase::getArray; using ABase::operator=;
/*
DensityOperator() : Base() {}
DensityOperatorBase() : LDO_Base(Dimensions()), ABase(DensityOperatorLow()), matrixView_() {}
*/
DensityOperator(const DensityOperatorLow& rho, ByReference) ///< Referencing constructor implemented in terms of blitzplusplus::halfCutTiny
: LDO_Base(blitzplusplus::halfCutTiny(rho.shape())), ABase(rho) {}
explicit DensityOperator(const Dimensions& dimensions, bool init=true)
: LDO_Base(dimensions),
ABase(DensityOperatorLow(blitzplusplus::concatenateTinies(dimensions,dimensions))) {if (init) *this=0;}
explicit DensityOperator(const StateVector<RANK>& psi) ///< Constructs the class as a dyadic product of `psi` with itself.
: LDO_Base(psi.getDimensions()), ABase(psi.dyad()) {}
DensityOperator(const DensityOperator& rho) ///< By-value copy constructor (deep copy)
: LDO_Base(rho.getDimensions()), ABase(rho.getArray().copy()) {}
DensityOperator(DensityOperator&& rho) ///< Move constructor (shallow copy)
: LDO_Base(rho.getDimensions()), ABase(std::move(rho.getArray())) {}
DensityOperator() : LDO_Base(Dimensions{size_t(0)}), ABase() {}
DensityOperator& operator=(const DensityOperator&) = default;
DensityOperator& operator=(DensityOperator&& rho)
{
ABase::operator=(std::move(rho));
LDO_Base::setDimensions(rho.getDimensions());
return *this;
}
DensityOperator& operator=(const StateVector<RANK>& psi)
{
using namespace linalg;
CMatrix matrix(matrixView());
CVector vector(psi.vectorView());
int dim(this->getTotalDimension());
for (int i=0; i<dim; i++) for (int j=0; j<dim; j++) matrix(i,j)=vector(i)*conj(vector(j));
return *this;
}
private:
class IndexerProxy
{
public:
IndexerProxy(const DensityOperator* rho, const Idx& firstIndex) : rho_(rho), firstIndex_(firstIndex) {}
template<typename... SubscriptPack>
IndexerProxy(const DensityOperator* rho, int s0, SubscriptPack... subscriptPack) : IndexerProxy(rho,Idx(s0,subscriptPack...))
{static_assert( sizeof...(SubscriptPack)==RANK-1 , "Incorrect number of subscripts for DensityOperator." );}
const dcomp& operator()(const Idx& secondIndex) const {return rho_->indexWithTiny(firstIndex_,secondIndex);}
dcomp& operator()(const Idx& secondIndex) {return const_cast<dcomp&>(static_cast<const IndexerProxy&>(*this)(secondIndex));}
template<typename... SubscriptPack>
const dcomp& operator()(int s0, SubscriptPack... subscriptPack) const
{
static_assert( sizeof...(SubscriptPack)==RANK-1 , "Incorrect number of subscripts for DensityOperator." );
return operator()(Idx(s0,subscriptPack...));
}
template<typename... SubscriptPack>
dcomp& operator()(int s0, SubscriptPack... subscriptPack) {return const_cast<dcomp&>(static_cast<const IndexerProxy&>(*this)(s0,subscriptPack...));}
private:
const DensityOperator*const rho_;
const Idx firstIndex_;
};
friend class IndexerProxy;
public:
/// \name (Multi-)matrix style indexing
//@{
const IndexerProxy operator()(const Idx& firstIndex) const {return IndexerProxy(this,firstIndex);}
IndexerProxy operator()(const Idx& firstIndex) {return IndexerProxy(this,firstIndex);}
template<typename... SubscriptPack>
const IndexerProxy operator()(int s0, SubscriptPack... subscriptPack) const {return IndexerProxy(this,s0,subscriptPack...);}
template<typename... SubscriptPack>
IndexerProxy operator()(int s0, SubscriptPack... subscriptPack) {return IndexerProxy(this,s0,subscriptPack...);}
//@}
/// \name LazyDensityOperator diagonal iteration
//@{
template<typename... SubscriptPack>
auto diagonalSliceIndex(const SubscriptPack&... subscriptPack) const
{
static_assert( sizeof...(SubscriptPack)==RANK , "Incorrect number of subscripts for DensityOperator." );
#define SLICE_EXPR getArray()(subscriptPack...,subscriptPack...)
return DensityOperator<cppqedutils::Rank_v<decltype(SLICE_EXPR)>/2>(SLICE_EXPR,byReference);
#undef SLICE_EXPR
}
template<typename... SubscriptPack>
void transposeSelf(SubscriptPack... subscriptPack)
{
static_assert( sizeof...(SubscriptPack)==RANK , "Incorrect number of subscripts for DensityOperator." );
getArray().transposeSelf(subscriptPack...,(subscriptPack+RANK)...);
this->setDimensions(blitzplusplus::halfCutTiny(getArray().shape()));
}
//@}
/// \name Norm
//@{
double norm() const ///< returns the trace norm
{
using blitz::tensor::i;
const linalg::CMatrix m(matrixView());
return real(sum(m(i,i)));
}
double renorm() ///< ” and also renormalises
{
double trace=norm();
*this/=trace;
return trace;
}
//@}
/// \name Matrix view
//@{
auto matrixView() const {return blitzplusplus::binaryArray(getArray());} ///< returns a two-dimensional view of the underlying data, created on the fly via blitzplusplus::binaryArray
//@}
void reference(const DensityOperator& other) {getArray().reference(other.getArray()); this->setDimensions(other.getDimensions());}
auto lbound() const {return blitzplusplus::halfCutTiny(getArray().lbound());}
auto ubound() const {return blitzplusplus::halfCutTiny(getArray().ubound());}
private:
const dcomp& indexWithTiny(const Idx& i, const Idx& j) const ///< Used for implementing operator() and the index function below.
{
return getArray()(blitzplusplus::concatenateTinies<int,int,RANK,RANK>(i,j));
}
const dcomp index(const Idx& i, const Idx& j) const override {return indexWithTiny(i,j);} ///< This function implements the LazyDensityOperator interface in a trivial element-access way
double trace_v() const override {return norm();} ///< A straightforward implementation of a LazyDensityOperator virtual
};
template<int RANK1, int RANK2>
inline
const DensityOperator<RANK1+RANK2>
operator*(const DensityOperator<RANK1>&, const DensityOperator<RANK2>&);
template<int RANK>
inline
double frobeniusNorm(const DensityOperator<RANK>& rho) {return rho.frobeniusNorm();}
/// Performs the opposite of quantumdata::deflate
template<int RANK>
void inflate(const DArray<1>& flattened, DensityOperator<RANK>& rho, bool offDiagonals)
{
const size_t dim=rho.getTotalDimension();
typedef cppqedutils::MultiIndexIterator<RANK> Iterator;
const Iterator etalon(rho.getDimensions()-1,cppqedutils::mii::begin);
size_t idx=0;
// Diagonal
for (Iterator i(etalon); idx<dim; ++i)
rho(*i)(*i)=flattened(idx++);
// OffDiagonal
if (offDiagonals)
for (Iterator i(etalon); idx<cppqedutils::sqr(dim); ++i)
for (Iterator j=++Iterator(i); j!=etalon.getEnd(); ++j, idx+=2) {
dcomp matrixElement(rho(*i)(*j)=dcomp(flattened(idx),flattened(idx+1)));
rho(*j)(*i)=conj(matrixElement);
}
}
/// Creates a DensityOperator as the (deep) copy of the data of a LazyDensityOperator of the same arity
template<int RANK>
const DensityOperator<RANK>
densityOperatorize(const LazyDensityOperator<RANK>& matrix)
{
DensityOperator<RANK> res(matrix.getDimension());
typedef cppqedutils::MultiIndexIterator<RANK> Iterator;
const Iterator etalon(matrix.getDimensions()-1,cppqedutils::mii::begin);
for (Iterator i(etalon); i!=etalon.getEnd(); ++i) {
res(*i)(*i)=matrix(*i);
for (Iterator j=++Iterator(i); j!=etalon.getEnd(); ++j) {
dcomp matrixElement(res(*i)(*j)=matrix(*i)(*j));
res(*j)(*i)=conj(matrixElement);
}
}
return res;
}
template<int... SUBSYSTEM, int RANK>
const DensityOperator<sizeof...(SUBSYSTEM)>
reduce(const LazyDensityOperator<RANK>& matrix)
{
static const int RES_ARITY=sizeof...(SUBSYSTEM);
return partialTrace<tmptools::Vector<SUBSYSTEM...>,DensityOperator<RES_ARITY> >(matrix,densityOperatorize<RES_ARITY>);
}
template<int RANK>
inline auto
dyad(const StateVector<RANK>& sv1, const StateVector<RANK>& sv2)
{
return DensityOperator<RANK>(sv1.dyad(sv2),byReference);
}
template <int RANK>
constexpr auto ArrayRank_v<DensityOperator<RANK>> = 2*RANK;
template<int RANK, typename ... SubscriptPack>
auto subscript(const quantumdata::DensityOperator<RANK>& rho, const SubscriptPack&... subscriptPack) ///< for use in cppqedutils::SliceIterator
{
return rho.diagonalSliceIndex(subscriptPack...);
}
} // quantumdata
#endif // CPPQEDCORE_QUANTUMDATA_DENSITYOPERATOR_H_INCLUDED
| 33.662069 | 187 | 0.71932 |
88c73a73ef6138494091967cbe28d6b47cf6240a | 637 | h | C | NewStock/View/GoodStockView/TaoIndexSkillBottomView.h | JiangYongKang/NewStock-iOS | 012dd017b89ff7a093bf79f882f46c56f0492e25 | [
"Apache-2.0"
] | null | null | null | NewStock/View/GoodStockView/TaoIndexSkillBottomView.h | JiangYongKang/NewStock-iOS | 012dd017b89ff7a093bf79f882f46c56f0492e25 | [
"Apache-2.0"
] | null | null | null | NewStock/View/GoodStockView/TaoIndexSkillBottomView.h | JiangYongKang/NewStock-iOS | 012dd017b89ff7a093bf79f882f46c56f0492e25 | [
"Apache-2.0"
] | null | null | null | //
// TaoIndexSkillBottomView.h
// NewStock
//
// Created by 王迪 on 2017/6/22.
// Copyright © 2017年 Willey. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol TaoIndexSkillBottomViewDelegate <NSObject>
- (void)taoIndexSkillBottomViewDelegatePushTo:(NSString *)url title:(NSString *)title;
@end
@interface TaoIndexSkillBottomView : UIView
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, weak) id <TaoIndexSkillBottomViewDelegate> delegate;
@end
@interface TaoIndexSkillBottomButton : UIButton
@property (nonatomic, strong) NSString *code;
@property (nonatomic, strong) NSString *title;
@end
| 19.30303 | 86 | 0.759812 |
bb0843809bdf4d282db528161ca1591c9070fdcb | 12,188 | h | C | FriendLink-Common/game_structures.h | m6jones/FriendLink | 8c7cae54ebc7f6673a76532edca2debc3c30d16c | [
"MIT"
] | 1 | 2020-01-23T21:33:52.000Z | 2020-01-23T21:33:52.000Z | FriendLink-Common/game_structures.h | m6jones/FriendLink | 8c7cae54ebc7f6673a76532edca2debc3c30d16c | [
"MIT"
] | null | null | null | FriendLink-Common/game_structures.h | m6jones/FriendLink | 8c7cae54ebc7f6673a76532edca2debc3c30d16c | [
"MIT"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2016 Matthew Jones
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file
* The point of this file is to build basic structures contianing game data and
* prepare that data for network transfer.
*/
#pragma once
#include <string>
#include <vector>
#include <mutex>
#include "DataHandling.h"
/**
* Game related content.
*/
namespace Game {
/**
* Character Properties.
*/
namespace Property {
///Is the number of properties in PropertyType
///@see Game::Data::PropertyType
constexpr uint8_t kTypeCount = 7;
///The different properties for a character that will be sent over the network.
enum class Type {
kId, //uint8 server slot.
ksCellName, //String of the cell name.
kStatus, //ConnectionSatus of players.
ksName, //String of the player name.
kLocation, //Location object
ksWorldSpaceName, //String of the world space name.
kLoadedState //Loaded State
//If adding more properties remember to increase kPropertyTypeCount or the
//new property will not work.
};
/**
* Converts a property type into a string. The strings may not be unique and
* some might return "Unknown".
*/
std::string TypeToString(Type);
/**
* Packs a property type into a unique char based on conversion to type uint8_t.
* @throw runtime_error
*/
char PackType(Type);
/**
* Unpacks a char into property type.
* @param After c is converted to uint8_t it must be in the range of 0
* to 1-kPropertyTypeCount.
* @throw runtime_error
* @see Game::Data::kPropertyTypeCount
*/
Type UnpackType(char c);
/**
* A structure to pack different character properties.
*/
struct Property {
Type type;
std::vector<char> value;
};
/**
* Uses stream syntax to pack and unpack properties to vector<char>.
* Example:
* @code
* std::vector<char> properties { ... } //packed_properties
* PropertyStream property_stream { properties };
* for (Property p; property_stream >> p;) {
* Update(p);
* }
* @endcode
* @see Game::Data::Property
*/
class Stream {
public:
Stream() {}
/**
* Constructs Property Stream from a packed properties.
* @param packed_properties is a vector<char> that represents a list of
* properties. To form such a vector encode a list using this class.
*/
Stream(std::vector<char> packed_properties)
: properties_packed_(packed_properties) {}
Stream(Stream&) = default;
Stream(Stream&&) = default;
operator bool() {
if(test) return false;
if(Empty()) {
test = true;
}
return true;
}
Stream& operator<<(const Stream&);
Stream& operator<<(const Property&);
Stream& operator>>(Property&);
void Clear() { properties_packed_.clear(); }
bool Empty() const { return properties_packed_.empty(); }
std::vector<char> Packed() { return properties_packed_; }
private:
std::vector<char> properties_packed_;
bool test = false;
};
/**
* Properties allows you to keep track of one instance of each property type.
* This class is thread safe by the use of locks.
* @todo Determine if Properties is still required.
*/
class Properties {
public:
Properties()
: properties_(kTypeCount),
property_contained_(kTypeCount, false) {}
/**
* Updates property with type Property.type with new value.
*/
void Update(Property);
/**
* Updates all properties in the stream with the new values.
*/
void Update(Stream);
/**
* Updates all properties in the packed with the new values.
* @param properties is required to have PacketType properties.
*/
void Update(Network::Packet::Packet properties);
Stream ToStream();
/**
* Packs all the set properties for sending.
*/
std::vector<char> Packed();
private:
std::mutex update_mtx_;
std::vector<Property> properties_;
std::vector<bool> property_contained_;
};
/**
* Extracts a string from a property where its value represents a string.
* @param ks_property with its value of type string. These types have prefex ks.
*/
std::string UnpackString(Property ks_property);
/**
* Packs a string into a property where its value represents a string.
* @param ks_type that has a prefex of ks.
*/
Property PackString(Type ks_type, std::string);
/**
* Unpacks a property to a form id which has type uint32_t.
* @param form_id_property with its value of type uint32_t.
* @throw runtime_error
* @remarks The properties that fillful this property no longer exists.
*/
uint32_t UnpackFormId(Property form_id_property);
/**
* Packs a form id which has type uint32_t into a property.
* @param type with its value of type uint32_t.
* @param form_id is a form id of a object in skyrim.
* @remarks The properties that fillful this property no longer exists.
*/
Property PackFormId(Type form_id_type, uint32_t form_id);
}//namespace Property
/**
* Describes a location in skyrim.
* A location in skyrim is made up of three parts.
*
* World Space which is null while in interior cells. The world space is
* encoded in a form id, UInt32.
*
* Cell which is only null between loading, so the location is considered empty
* when the cell is null. The cell is encoded in a form id, UInt32.
*
* World coordinates which is given by normal cartesian coordinates represented
* by floats.
*
* Location is ordered by time.
*/
class Location {
typedef std::chrono::steady_clock SteadyClock;
typedef std::chrono::duration<int32_t, std::milli> Duration;
typedef std::chrono::time_point<SteadyClock, Duration> TimePoint;
static constexpr size_t kDimension = 3;
static constexpr size_t kLocationTypeSize
= sizeof(int32_t) + sizeof(char) + 2 * sizeof(uint32_t)
+ kDimension * Network::kSizeOfPackedFloat;
///Keeps track of the time that the first Location was constructed.
static const TimePoint kReferenceTime;
public:
Location() : has_world_space_(false), has_cell_(false) {}
/**
* Builds location from the location property.
* @throw runtime_error if the property isn't of location type.
*/
explicit Location(Property::Property location_property);
/**
* Builds location from base components.
* @param world_space_id is the form id for the world space or false when
* there isn't a word space for this location.
* @param cell_id is the form id for the cell or false when there isn't a
* cell for this location. When this value is false you are creating
* location that will be considered empty.
* @param position is a vector<float> of length kdimension.
* @throw runtime_error if the property isn't of location type.
* @see Game::Data::Location::kDimension
*/
Location(uint32_t world_space_id, uint32_t cell_id, std::vector<float> position);
///@cond LocationConstructors
//These constructors allow you to input false for world_space_id and cell_id
//Given the value true for any of the bools will still build the Location as
//if you gave the value false.
Location(bool world_space_id, uint32_t cell_id, std::vector<float> position);
Location(uint32_t world_space_id, bool cell_id, std::vector<float> position);
Location(bool world_space_id, bool cell_id, std::vector<float> position);
///@endcond
///Does this location have a world space connected to it.
bool has_world_space() const { return has_world_space_; }
///Does this location have a cell connected to it.
bool has_cell() const { return has_cell_; }
///Does this location give a location in skyrim game.
bool is_empty() const { return !has_cell_; } //cell cannot be null.
/// @return world space form id. If there is no world space then it returns 0.
uint32_t world_space_id() const { return world_space_id_; }
/// @return cell form id. If there is no cell then this returns 0.
uint32_t cell_id() const { return cell_id_; }
/// @return The amount of time in milliseconds this location was this created
/// after the first location was created.
int32_t time_elapsed() const { return time_elapsed_; }
float x() const { return position_[0]; }
float y() const { return position_[1]; }
float z() const { return position_[2]; }
/// @return vector<float> of size 3 that represents the position.
std::vector<float> position() const { return position_; }
/// @return A property of type kLocation that represents this location.
Property::Property ToProperty();
/// @return A string that represents this location in a readable way.
std::string ToString();
private:
/**
* Double checks that position is in the right format.
* @throw runtime_error
*/
void CheckPosition(std::vector<float> position);
/**
* Packs the values of has_world_space_ and has_cell_ into one char.
*/
char PackNotNulls();
/**
* Unpacks a char to sets the values of has_world_space_ and has_cell_.
*/
void UnpackNotNulls(char c);
/**
* Sets the elapsed time in milliseconds after the first location is created
* using kReferenceTime.
* @see Game::Data::Location::kReferenceTime
*/
void SetTimeElapsed();
bool has_world_space_ = true;
bool has_cell_ = true;
std::uint32_t world_space_id_ = 0;
uint32_t cell_id_ = 0;
int32_t time_elapsed_ = 0;
std::vector<float> position_ = {0,0,0};
};
/**
* Takes in two location and finds the difference in the time created. Note,
* this is will not return the absolute value. So if location a was created
* before location b then the result will be negative.
* @return The difference in time creation in milliseconds or if either of the
* location is empty then returns Network::Connection::kAntiCongestion.
* @remark Showing that the default return value is good or bad is required.
* @see Network::Connection::kAntiCongestion
*/
int TimeSubtract(Location a, Location b);
/**
* The distance between two locations.
* @return The distance between the two locations. If either location is empty
* then 0 is returned.
*/
float DistanceBetween(Location, Location);
/**
* Checks to see if the two locations are in the same cell.
* @return Returns true if both locations don't have a cell or when their cell
* ids match.
*/
bool InSameCell(Location, Location);
/**
* Checks to see if the two locations are in the same world space.
* @return Returns true if both locations don't have a world space or when their
* world space ids match.
*/
bool InSameWorldSpace(Location, Location);
/**
* Checks to see if the two locations are in the same area. That is if they are
* in the same cell or if they both have a worldspace and their world space id
* match.
*/
bool InSameArea(Location, Location);
/**
* Extracts a string from a property where its value represents a string.
*/
std::string PrintPosition(Location);
struct LoadedState {
uint32_t unk00; // 00
uint32_t unk04; // 04
uint32_t unk08; // 08
uint32_t unk0C; // 0C
uint32_t unk10; // 10
uint32_t unk14; // 14
uint32_t unk18; // 18
uint32_t unk1C; // 1C
LoadedState() {}
LoadedState(Property::Property props);
Property::Property ToProperty();
std::string ToString();
};
}//namespace Game | 35.123919 | 125 | 0.708976 |
15f411d79366c210c58aff2a9fd84bcefc4ea119 | 4,635 | c | C | src/astrometry/util/test_starutil.c | zfedoran/astrometry.js | 38d14d490f33fc933c3d90226691dd1e685ced08 | [
"BSD-3-Clause"
] | 4 | 2018-02-13T23:11:40.000Z | 2021-09-30T16:02:22.000Z | src/astrometry/util/test_starutil.c | zfedoran/astrometry.js | 38d14d490f33fc933c3d90226691dd1e685ced08 | [
"BSD-3-Clause"
] | null | null | null | src/astrometry/util/test_starutil.c | zfedoran/astrometry.js | 38d14d490f33fc933c3d90226691dd1e685ced08 | [
"BSD-3-Clause"
] | 1 | 2019-02-11T06:56:30.000Z | 2019-02-11T06:56:30.000Z | /*
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
#include <unistd.h>
#include <stdio.h>
#include "starutil.h"
#include "cutest.h"
void test_ra2hmsstring(CuTest* tc) {
char rastr[32], decstr[32];
double hr;
double as;
ra2hmsstring(0, rastr);
CuAssertStrEquals(tc, "00:00:00.000", rastr);
printf("ra %s\n", rastr);
hr = 15.0;
ra2hmsstring(-hr, rastr);
CuAssertStrEquals(tc, "23:00:00.000", rastr);
printf("ra %s\n", rastr);
ra2hmsstring(hr, rastr);
CuAssertStrEquals(tc, "01:00:00.000", rastr);
printf("ra %s\n", rastr);
as = 15.0/3600.0;
ra2hmsstring(60.0*as, rastr);
CuAssertStrEquals(tc, "00:01:00.000", rastr);
printf("ra %s\n", rastr);
ra2hmsstring(as, rastr);
CuAssertStrEquals(tc, "00:00:01.000", rastr);
printf("ra %s\n", rastr);
ra2hmsstring(0.001*as, rastr);
CuAssertStrEquals(tc, "00:00:00.001", rastr);
printf("ra %s\n", rastr);
ra2hmsstring(0.000999*as, rastr);
CuAssertStrEquals(tc, "00:00:00.001", rastr);
printf("ra %s\n", rastr);
ra2hmsstring(360.0 - 0.001*as, rastr);
CuAssertStrEquals(tc, "23:59:59.999", rastr);
printf("ra %s\n", rastr);
as = 1.0/3600.0;
dec2dmsstring(0, decstr);
CuAssertStrEquals(tc, "+00:00:00.000", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(-0, decstr);
CuAssertStrEquals(tc, "+00:00:00.000", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(-1, decstr);
CuAssertStrEquals(tc, "-01:00:00.000", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(-1*as, decstr);
CuAssertStrEquals(tc, "-00:00:01.000", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(-0.001*as, decstr);
CuAssertStrEquals(tc, "-00:00:00.001", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(-0.000999*as, decstr);
CuAssertStrEquals(tc, "-00:00:00.001", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(as, decstr);
CuAssertStrEquals(tc, "+00:00:01.000", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(0.5, decstr);
CuAssertStrEquals(tc, "+00:30:00.000", decstr);
printf("dec %s\n", decstr);
dec2dmsstring(-0.5, decstr);
CuAssertStrEquals(tc, "-00:30:00.000", decstr);
printf("dec %s\n", decstr);
}
void test_hammer_aitoff(CuTest* tc) {
double xyz[3];
double px, py;
double ras [] = { 0, 0, 0, 0, 0, 45, 90, 135, 180, 225, 270, 315, 360};
double decs[] = { 0, 45, 90, -45, -89, 0, 0, 0, 0, 0, 0, 0, 0};
int i;
for (i=0; i<sizeof(ras)/sizeof(double); i++) {
double ra, dec;
ra = ras [i];
dec = decs[i];
radecdeg2xyzarr(ra, dec, xyz);
project_hammer_aitoff_x(xyz[0], xyz[1], xyz[2], &px, &py);
printf("RA,Dec (%f,%f) => (%g, %g)\n", ra, dec, px, py);
}
}
void test_atora(CuTest* tc) {
CuAssertDblEquals(tc, 0.0, atora("00:00:00.0"), 1e-6);
CuAssertDblEquals(tc, 15.0, atora("01:00:00.0"), 1e-6);
CuAssertDblEquals(tc, 0.25, atora("00:01:00.0"), 1e-6);
CuAssertDblEquals(tc, 0.25/60.0, atora("00:00:01.0"), 1e-6);
CuAssertDblEquals(tc, 0.25/60.0/10.0, atora("00:00:00.1"), 1e-6);
CuAssertDblEquals(tc, 0.0, atora("0:00:00.0"), 1e-6);
CuAssertDblEquals(tc, 15.0, atora("1:00:00.0"), 1e-6);
CuAssertDblEquals(tc, 0.25, atora("0:01:00.0"), 1e-6);
CuAssertDblEquals(tc, 0.25/60.0, atora("0:00:01.0"), 1e-6);
CuAssertDblEquals(tc, 0.25/60.0/10.0, atora("0:00:00.1"), 1e-6);
CuAssertDblEquals(tc, 0.0, atora("00:0:00.0"), 1e-6);
CuAssertDblEquals(tc, 15.0, atora("01:0:00.0"), 1e-6);
CuAssertDblEquals(tc, 0.25, atora("00:1:00.0"), 1e-6);
CuAssertDblEquals(tc, 0.25/60.0, atora("00:0:01.0"), 1e-6);
CuAssertDblEquals(tc, 0.25/60.0/10.0, atora("00:0:00.1"), 1e-6);
CuAssertDblEquals(tc, 6 * 15 + 8 * 0.25 + 41.0 * 0.25/60.0, atora("06:08:41.0"), 1e-6);
CuAssertDblEquals(tc, 6 * 15 + 8 * 0.25 + 41.0 * 0.25/60.0, atora("6:08:41.0"), 1e-6);
CuAssertDblEquals(tc, 6 * 15 + 8 * 0.25 + 41.0 * 0.25/60.0, atora("6:8:41.0"), 1e-6);
}
void test_atodec(CuTest* tc) {
CuAssertDblEquals(tc, 0.0, atodec("00:00:00.0"), 1e-6);
CuAssertDblEquals(tc, 1.0, atodec("01:00:00.0"), 1e-6);
CuAssertDblEquals(tc, 1.0/60.0, atodec("00:01:00.0"), 1e-6);
CuAssertDblEquals(tc, 1.0/3600.0, atodec("00:00:01.0"), 1e-6);
CuAssertDblEquals(tc, 1.0/36000.0, atodec("00:00:00.1"), 1e-6);
CuAssertDblEquals(tc, -1.0, atodec("-01:00:00.0"), 1e-6);
CuAssertDblEquals(tc, -(1.0 + 1.0/60.0), atodec("-01:01:00.0"), 1e-6);
}
void test_xtodistsq(CuTest* tc) {
double distsq = 1e-4;
double x;
x = distsq2rad(distsq);
CuAssertDblEquals(tc, distsq, rad2distsq(x), 1e-8);
x = distsq2arcsec(distsq);
CuAssertDblEquals(tc, distsq, arcsec2distsq(x), 1e-8);
}
| 29.903226 | 91 | 0.626537 |
10a31d242609a3f0e185859e87aa822896d676e3 | 751 | h | C | CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/TXCAudioEffect.h | ceekay1991/CallTraceForWeChat | 5767cb6f781821b6bf9facc8c87e58e15fa88541 | [
"MIT"
] | 30 | 2020-03-22T12:30:21.000Z | 2022-02-09T08:49:13.000Z | CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/TXCAudioEffect.h | ceekay1991/CallTraceForWeChat | 5767cb6f781821b6bf9facc8c87e58e15fa88541 | [
"MIT"
] | null | null | null | CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/TXCAudioEffect.h | ceekay1991/CallTraceForWeChat | 5767cb6f781821b6bf9facc8c87e58e15fa88541 | [
"MIT"
] | 8 | 2020-03-22T12:30:23.000Z | 2020-09-22T04:01:47.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@class NSString;
@interface TXCAudioEffect : NSObject
{
_Bool _publish;
int _effectId;
int _loopCount;
NSString *_path;
double _volume;
}
@property(nonatomic) double volume; // @synthesize volume=_volume;
@property(nonatomic) _Bool publish; // @synthesize publish=_publish;
@property(nonatomic) int loopCount; // @synthesize loopCount=_loopCount;
@property(copy, nonatomic) NSString *path; // @synthesize path=_path;
@property(nonatomic) int effectId; // @synthesize effectId=_effectId;
- (void).cxx_destruct;
@end
| 25.896552 | 90 | 0.715047 |
a158a915109ac6c27f20eca57cd15398822f5158 | 1,737 | h | C | drivers/gpu/drm/tegra/plane.h | CPU-Code/-Linux_kernel | 44dc3358bc640197528f5b10dbed0fd3717af65b | [
"AFL-3.0"
] | 2 | 2020-09-18T07:01:49.000Z | 2022-01-27T08:59:04.000Z | drivers/gpu/drm/tegra/plane.h | CPU-Code/-Linux_kernel | 44dc3358bc640197528f5b10dbed0fd3717af65b | [
"AFL-3.0"
] | null | null | null | drivers/gpu/drm/tegra/plane.h | CPU-Code/-Linux_kernel | 44dc3358bc640197528f5b10dbed0fd3717af65b | [
"AFL-3.0"
] | 4 | 2020-06-29T04:09:48.000Z | 2022-01-27T08:59:01.000Z | /* SPDX-License-Identifier: GPL-2.0-only */
/*
* Copyright (C) 2017 NVIDIA CORPORATION. All rights reserved.
*/
#ifndef TEGRA_PLANE_H
#define TEGRA_PLANE_H 1
#include <drm/drm_plane.h>
struct tegra_bo;
struct tegra_dc;
struct tegra_plane {
struct drm_plane base;
struct tegra_dc *dc;
unsigned int offset;
unsigned int index;
};
struct tegra_cursor {
struct tegra_plane base;
struct tegra_bo *bo;
unsigned int width;
unsigned int height;
};
static inline struct tegra_plane *to_tegra_plane(struct drm_plane *plane)
{
return container_of(plane, struct tegra_plane, base);
}
struct tegra_plane_legacy_blending_state {
bool alpha;
bool top;
};
struct tegra_plane_state {
struct drm_plane_state base;
struct sg_table *sgt[3];
dma_addr_t iova[3];
struct tegra_bo_tiling tiling;
u32 format;
u32 swap;
bool bottom_up;
/* used for legacy blending support only */
struct tegra_plane_legacy_blending_state blending[2];
bool opaque;
};
static inline struct tegra_plane_state *
to_tegra_plane_state(struct drm_plane_state *state)
{
if (state)
return container_of(state, struct tegra_plane_state, base);
return NULL;
}
extern const struct drm_plane_funcs tegra_plane_funcs;
int tegra_plane_prepare_fb(struct drm_plane *plane,
struct drm_plane_state *state);
void tegra_plane_cleanup_fb(struct drm_plane *plane,
struct drm_plane_state *state);
int tegra_plane_state_add(struct tegra_plane *plane,
struct drm_plane_state *state);
int tegra_plane_format(u32 fourcc, u32 *format, u32 *swap);
bool tegra_plane_format_is_yuv(unsigned int format, bool *planar);
int tegra_plane_setup_legacy_state(struct tegra_plane *tegra,
struct tegra_plane_state *state);
#endif /* TEGRA_PLANE_H */
| 21.444444 | 73 | 0.772596 |
3159781e0c27667e3a1de892029e9fb3dabd78e2 | 1,382 | h | C | System/Library/PrivateFrameworks/ExchangeSync.framework/Frameworks/DAEAS.framework/ASAutodiscoverV2Task.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/ExchangeSync.framework/Frameworks/DAEAS.framework/ASAutodiscoverV2Task.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/ExchangeSync.framework/Frameworks/DAEAS.framework/ASAutodiscoverV2Task.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:54:26 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/ExchangeSync.framework/Frameworks/DAEAS.framework/DAEAS
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <DAEAS/ASTask.h>
@class NSString, NSMutableDictionary;
@interface ASAutodiscoverV2Task : ASTask {
NSString* _emailAddress;
NSMutableDictionary* _accountInfo;
BOOL _addEmptyBearer;
BOOL _discoverOAuthEndpoint;
NSString* _easEndPoint;
}
-(id)_url;
-(void)finishWithError:(id)arg1 ;
-(id)contentType;
-(id)initWithEmailAddress:(id)arg1 ;
-(void)URLSession:(id)arg1 dataTask:(id)arg2 didReceiveResponse:(id)arg3 completionHandler:(/*^block*/id)arg4 ;
-(double)timeoutInterval;
-(void)loadRequest:(id)arg1 ;
-(BOOL)processContext:(id)arg1 ;
-(void)didProcessContext:(id)arg1 ;
-(id)_easVersion;
-(id)_policyKey;
-(id)_HTTPMethodForRequest:(id)arg1 ;
-(BOOL)_shouldSendAuthForRequest:(id)arg1 ;
-(BOOL)_shouldRedirectToHTTPForRequest:(id)arg1 ;
-(id)localizedErrorStringForCertificateErrorCode:(int)arg1 host:(id)arg2 ;
-(BOOL)shouldHandlePasswordErrors;
-(BOOL)shouldStallAfterConnectionLost;
-(BOOL)requiresEASVersionInformaton;
-(BOOL)shouldLogIncomingData;
-(id)_OAuthURLFromResponseData:(id)arg1 ;
@end
| 31.409091 | 111 | 0.78437 |
c8ce05bfc1c1c18f35b642e76d961cb94aa00db3 | 1,924 | c | C | week-1/credit.c | rogersanbr/cs50 | 9d81456fbf60c033efa895ac849a383d48782c98 | [
"Apache-2.0"
] | null | null | null | week-1/credit.c | rogersanbr/cs50 | 9d81456fbf60c033efa895ac849a383d48782c98 | [
"Apache-2.0"
] | null | null | null | week-1/credit.c | rogersanbr/cs50 | 9d81456fbf60c033efa895ac849a383d48782c98 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <regex.h>
#include <string.h>
#include <cs50.h>
bool is_number(string digits);
string is_valid(string digits);
bool validate_luhn_algorithm(string digits);
bool is_mastercard(string digits);
bool is_visa(string digits);
bool is_amex(string digits);
int main(void)
{
string digits = get_string("Number: ");
while (is_number(digits) != 0)
{
digits = get_string("Number: ");
}
printf("%s\n", is_valid(digits));
}
bool is_number(string digits)
{
regex_t regex;
regcomp(®ex, "[^A-Za-z\\-]", 0);
return regexec(®ex, digits, 0, NULL, 0);
}
string is_valid(string digits)
{
if (strlen(digits) < 13)
{
return "INVALID";
}
bool valid = validate_luhn_algorithm(digits);
if (!valid)
{
return "INVALID";
}
if (is_visa(digits))
{
return "VISA";
}
if (is_amex(digits))
{
return "AMEX";
}
if (is_mastercard(digits))
{
return "MASTERCARD";
}
return "INVALID";
}
bool validate_luhn_algorithm(string digits)
{
int sum = 0;
for (int i = strlen(digits) - 2; i < strlen(digits); i = i - 2)
{
int digit = (digits[i] - 48) * 2;
if (digit > 9)
{
sum += (int)(digit / 10);
sum += digit % 10;
}
else
{
sum += (int)digit;
}
}
for (int k = strlen(digits) - 1; k < strlen(digits); k = k - 2)
{
sum += digits[k] - 48;
}
if (sum % 10 == 0)
{
return true;
}
return false;
}
bool is_mastercard(string digits)
{
return digits[0] == '5' && (digits[1] == '1' || digits[1] == '2' || digits[1] == '3' || digits[1] == '4' || digits[1] == '5');
}
bool is_amex(string digits)
{
return digits[0] == '3' && (digits[1] == '4' || digits[1] == '7');
}
bool is_visa(string digits)
{
return digits[0] == '4';
} | 18.32381 | 130 | 0.527027 |
eab74aed5c23d3d58282f5a80ffdb221b2e18bd3 | 7,451 | c | C | Mesa-7.11.2_GPGPU-Sim/src/mesa/drivers/dri/nouveau/nv20_state_tex.c | ayoubg/gem5-graphics_v1 | d74a968d5854dc02797139558430ccda1f71108e | [
"BSD-3-Clause"
] | 1 | 2019-01-26T10:34:02.000Z | 2019-01-26T10:34:02.000Z | Mesa-7.11.2_GPGPU-Sim/src/mesa/drivers/dri/nouveau/nv20_state_tex.c | ayoubg/gem5-graphics_v1 | d74a968d5854dc02797139558430ccda1f71108e | [
"BSD-3-Clause"
] | null | null | null | Mesa-7.11.2_GPGPU-Sim/src/mesa/drivers/dri/nouveau/nv20_state_tex.c | ayoubg/gem5-graphics_v1 | d74a968d5854dc02797139558430ccda1f71108e | [
"BSD-3-Clause"
] | 1 | 2021-07-06T10:40:34.000Z | 2021-07-06T10:40:34.000Z | /*
* Copyright (C) 2009 Francisco Jerez.
* 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, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (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 NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) 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.
*
*/
#include "nouveau_driver.h"
#include "nouveau_context.h"
#include "nouveau_gldefs.h"
#include "nouveau_texture.h"
#include "nv20_3d.xml.h"
#include "nouveau_util.h"
#include "nv20_driver.h"
void
nv20_emit_tex_gen(struct gl_context *ctx, int emit)
{
const int i = emit - NOUVEAU_STATE_TEX_GEN0;
struct nouveau_context *nctx = to_nouveau_context(ctx);
struct nouveau_channel *chan = context_chan(ctx);
struct nouveau_grobj *kelvin = context_eng3d(ctx);
struct gl_texture_unit *unit = &ctx->Texture.Unit[i];
int j;
for (j = 0; j < 4; j++) {
if (nctx->fallback == HWTNL && (unit->TexGenEnabled & 1 << j)) {
struct gl_texgen *coord = get_texgen_coord(unit, j);
float *k = get_texgen_coeff(coord);
if (k) {
BEGIN_RING(chan, kelvin,
NV20_3D_TEX_GEN_COEFF(i, j), 4);
OUT_RINGp(chan, k, 4);
}
BEGIN_RING(chan, kelvin, NV20_3D_TEX_GEN_MODE(i, j), 1);
OUT_RING(chan, nvgl_texgen_mode(coord->Mode));
} else {
BEGIN_RING(chan, kelvin, NV20_3D_TEX_GEN_MODE(i, j), 1);
OUT_RING(chan, 0);
}
}
}
void
nv20_emit_tex_mat(struct gl_context *ctx, int emit)
{
const int i = emit - NOUVEAU_STATE_TEX_MAT0;
struct nouveau_context *nctx = to_nouveau_context(ctx);
struct nouveau_channel *chan = context_chan(ctx);
struct nouveau_grobj *kelvin = context_eng3d(ctx);
if (nctx->fallback == HWTNL &&
(ctx->Texture._TexMatEnabled & 1 << i)) {
BEGIN_RING(chan, kelvin, NV20_3D_TEX_MATRIX_ENABLE(i), 1);
OUT_RING(chan, 1);
BEGIN_RING(chan, kelvin, NV20_3D_TEX_MATRIX(i,0), 16);
OUT_RINGm(chan, ctx->TextureMatrixStack[i].Top->m);
} else {
BEGIN_RING(chan, kelvin, NV20_3D_TEX_MATRIX_ENABLE(i), 1);
OUT_RING(chan, 0);
}
}
static uint32_t
get_tex_format_pot(struct gl_texture_image *ti)
{
switch (ti->TexFormat) {
case MESA_FORMAT_ARGB8888:
return NV20_3D_TEX_FORMAT_FORMAT_A8R8G8B8;
case MESA_FORMAT_ARGB1555:
return NV20_3D_TEX_FORMAT_FORMAT_A1R5G5B5;
case MESA_FORMAT_ARGB4444:
return NV20_3D_TEX_FORMAT_FORMAT_A4R4G4B4;
case MESA_FORMAT_XRGB8888:
return NV20_3D_TEX_FORMAT_FORMAT_X8R8G8B8;
case MESA_FORMAT_RGB565:
return NV20_3D_TEX_FORMAT_FORMAT_R5G6B5;
case MESA_FORMAT_A8:
case MESA_FORMAT_I8:
return NV20_3D_TEX_FORMAT_FORMAT_I8;
case MESA_FORMAT_L8:
return NV20_3D_TEX_FORMAT_FORMAT_L8;
case MESA_FORMAT_CI8:
return NV20_3D_TEX_FORMAT_FORMAT_INDEX8;
default:
assert(0);
}
}
static uint32_t
get_tex_format_rect(struct gl_texture_image *ti)
{
switch (ti->TexFormat) {
case MESA_FORMAT_ARGB8888:
return NV20_3D_TEX_FORMAT_FORMAT_A8R8G8B8_RECT;
case MESA_FORMAT_ARGB1555:
return NV20_3D_TEX_FORMAT_FORMAT_A1R5G5B5_RECT;
case MESA_FORMAT_ARGB4444:
return NV20_3D_TEX_FORMAT_FORMAT_A4R4G4B4_RECT;
case MESA_FORMAT_XRGB8888:
return NV20_3D_TEX_FORMAT_FORMAT_R8G8B8_RECT;
case MESA_FORMAT_RGB565:
return NV20_3D_TEX_FORMAT_FORMAT_R5G6B5_RECT;
case MESA_FORMAT_L8:
return NV20_3D_TEX_FORMAT_FORMAT_L8_RECT;
case MESA_FORMAT_A8:
case MESA_FORMAT_I8:
return NV20_3D_TEX_FORMAT_FORMAT_I8_RECT;
default:
assert(0);
}
}
void
nv20_emit_tex_obj(struct gl_context *ctx, int emit)
{
const int i = emit - NOUVEAU_STATE_TEX_OBJ0;
struct nouveau_channel *chan = context_chan(ctx);
struct nouveau_grobj *kelvin = context_eng3d(ctx);
struct nouveau_bo_context *bctx = context_bctx_i(ctx, TEXTURE, i);
const int bo_flags = NOUVEAU_BO_RD | NOUVEAU_BO_GART | NOUVEAU_BO_VRAM;
struct gl_texture_object *t;
struct nouveau_surface *s;
struct gl_texture_image *ti;
uint32_t tx_format, tx_filter, tx_wrap, tx_enable;
if (!ctx->Texture.Unit[i]._ReallyEnabled) {
BEGIN_RING(chan, kelvin, NV20_3D_TEX_ENABLE(i), 1);
OUT_RING(chan, 0);
context_dirty(ctx, TEX_SHADER);
return;
}
t = ctx->Texture.Unit[i]._Current;
s = &to_nouveau_texture(t)->surfaces[t->BaseLevel];
ti = t->Image[0][t->BaseLevel];
if (!nouveau_texture_validate(ctx, t))
return;
/* Recompute the texturing registers. */
tx_format = ti->DepthLog2 << 28
| ti->HeightLog2 << 24
| ti->WidthLog2 << 20
| NV20_3D_TEX_FORMAT_DIMS_2D
| NV20_3D_TEX_FORMAT_NO_BORDER
| 1 << 16;
tx_wrap = nvgl_wrap_mode(t->Sampler.WrapR) << 16
| nvgl_wrap_mode(t->Sampler.WrapT) << 8
| nvgl_wrap_mode(t->Sampler.WrapS) << 0;
tx_filter = nvgl_filter_mode(t->Sampler.MagFilter) << 24
| nvgl_filter_mode(t->Sampler.MinFilter) << 16
| 2 << 12;
tx_enable = NV20_3D_TEX_ENABLE_ENABLE
| log2i(t->Sampler.MaxAnisotropy) << 4;
if (t->Target == GL_TEXTURE_RECTANGLE) {
BEGIN_RING(chan, kelvin, NV20_3D_TEX_NPOT_PITCH(i), 1);
OUT_RING(chan, s->pitch << 16);
BEGIN_RING(chan, kelvin, NV20_3D_TEX_NPOT_SIZE(i), 1);
OUT_RING(chan, s->width << 16 | s->height);
tx_format |= get_tex_format_rect(ti);
} else {
tx_format |= get_tex_format_pot(ti);
}
if (t->Sampler.MinFilter != GL_NEAREST &&
t->Sampler.MinFilter != GL_LINEAR) {
int lod_min = t->Sampler.MinLod;
int lod_max = MIN2(t->Sampler.MaxLod, t->_MaxLambda);
int lod_bias = t->Sampler.LodBias
+ ctx->Texture.Unit[i].LodBias;
lod_max = CLAMP(lod_max, 0, 15);
lod_min = CLAMP(lod_min, 0, 15);
lod_bias = CLAMP(lod_bias, 0, 15);
tx_format |= NV20_3D_TEX_FORMAT_MIPMAP;
tx_filter |= lod_bias << 8;
tx_enable |= lod_min << 26
| lod_max << 14;
}
/* Write it to the hardware. */
nouveau_bo_mark(bctx, kelvin, NV20_3D_TEX_FORMAT(i),
s->bo, tx_format, 0,
NV20_3D_TEX_FORMAT_DMA0,
NV20_3D_TEX_FORMAT_DMA1,
bo_flags | NOUVEAU_BO_OR);
nouveau_bo_markl(bctx, kelvin, NV20_3D_TEX_OFFSET(i),
s->bo, s->offset, bo_flags);
BEGIN_RING(chan, kelvin, NV20_3D_TEX_WRAP(i), 1);
OUT_RING(chan, tx_wrap);
BEGIN_RING(chan, kelvin, NV20_3D_TEX_FILTER(i), 1);
OUT_RING(chan, tx_filter);
BEGIN_RING(chan, kelvin, NV20_3D_TEX_ENABLE(i), 1);
OUT_RING(chan, tx_enable);
context_dirty(ctx, TEX_SHADER);
}
void
nv20_emit_tex_shader(struct gl_context *ctx, int emit)
{
struct nouveau_channel *chan = context_chan(ctx);
struct nouveau_grobj *kelvin = context_eng3d(ctx);
uint32_t tx_shader_op = 0;
int i;
for (i = 0; i < NV20_TEXTURE_UNITS; i++) {
if (!ctx->Texture.Unit[i]._ReallyEnabled)
continue;
tx_shader_op |= NV20_3D_TEX_SHADER_OP_TX0_TEXTURE_2D << 5 * i;
}
BEGIN_RING(chan, kelvin, NV20_3D_TEX_SHADER_OP, 1);
OUT_RING(chan, tx_shader_op);
}
| 27.802239 | 73 | 0.737753 |
8ae42de8b6c9d038d966eb7aeed0814b82d08703 | 383 | h | C | Code/BBearEditor/Engine/Render/BufferObject/BBShaderStorageBufferObject.h | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | 1 | 2021-09-01T08:19:34.000Z | 2021-09-01T08:19:34.000Z | Code/BBearEditor/Engine/Render/BufferObject/BBShaderStorageBufferObject.h | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | null | null | null | Code/BBearEditor/Engine/Render/BufferObject/BBShaderStorageBufferObject.h | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | null | null | null | #ifndef BBSHADERSTORAGEBUFFEROBJECT_H
#define BBSHADERSTORAGEBUFFEROBJECT_H
#include "BBVertexBufferObject.h"
class BBShaderStorageBufferObject : public BBVertexBufferObject
{
public:
BBShaderStorageBufferObject(int nVertexCount);
~BBShaderStorageBufferObject();
void bind() override;
void unbind() override;
private:
};
#endif // BBSHADERSTORAGEBUFFEROBJECT_H
| 19.15 | 63 | 0.798956 |
d82d7e2d72b87de4f480826f7bca2e3b34984f3a | 20,706 | c | C | src/driver-logitech-g600.c | kyokenn/libratbag | 1e3a85433af41955424f237af1975243edeabefa | [
"MIT"
] | 1,531 | 2015-09-16T00:40:44.000Z | 2022-03-29T14:02:01.000Z | src/driver-logitech-g600.c | kyokenn/libratbag | 1e3a85433af41955424f237af1975243edeabefa | [
"MIT"
] | 979 | 2015-09-01T16:06:24.000Z | 2022-03-23T05:59:01.000Z | src/driver-logitech-g600.c | kyokenn/libratbag | 1e3a85433af41955424f237af1975243edeabefa | [
"MIT"
] | 271 | 2015-08-31T23:09:03.000Z | 2022-03-23T08:56:27.000Z | /*
* Copyright © 2018 Thomas Hindoe Paaboel Andersen.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (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 NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <libevdev/libevdev.h>
#include <linux/input.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "libratbag-private.h"
#include "libratbag-hidraw.h"
#define LOGITECH_G600_NUM_PROFILES 3
#define LOGITECH_G600_NUM_BUTTONS 41 // 20 buttons + 1 color buffer + 20 G-shift
#define LOGITECH_G600_NUM_DPI 4
#define LOGITECH_G600_NUM_LED 1
#define LOGITECH_G600_DPI_MIN 200
#define LOGITECH_G600_DPI_MAX 8200
#define LOGITECH_G600_REPORT_ID_GET_ACTIVE 0xF0
#define LOGITECH_G600_REPORT_ID_SET_ACTIVE 0xF0
#define LOGITECH_G600_REPORT_ID_PROFILE_0 0xF3
#define LOGITECH_G600_REPORT_ID_PROFILE_1 0xF4
#define LOGITECH_G600_REPORT_ID_PROFILE_2 0xF5
#define LOGITECH_G600_REPORT_SIZE_PROFILE 154
#define LOGITECH_G600_LED_SOLID 0x00
#define LOGITECH_G600_LED_BREATHE 0x01
#define LOGITECH_G600_LED_CYCLE 0x02
struct logitech_g600_button {
uint8_t code;
uint8_t modifier;
uint8_t key;
} __attribute__((packed));
struct logitech_g600_profile_report {
uint8_t id;
uint8_t led_red;
uint8_t led_green;
uint8_t led_blue;
uint8_t led_effect;
uint8_t led_duration;
uint8_t unknown1[5];
uint8_t frequency; /* frequency = 1000 / (value + 1) */
uint8_t dpi_shift; /* value is a linear range between 200->0x04, 8200->0xa4, so value * 50, 0x00 is disabled */
uint8_t dpi_default; /* between 1 and 4*/
uint8_t dpi[4]; /* value is a linear range between 200->0x04, 8200->0xa4, so value * 50, 0x00 is disabled */
uint8_t unknown2[13];
struct logitech_g600_button buttons[20];
uint8_t g_shift_color[3]; /* can't assign it in LGS, but the 3rd profile has one that shows the feature :) */
struct logitech_g600_button g_shift_buttons[20];
} __attribute__((packed));
struct logitech_g600_active_profile_report {
uint8_t id;
uint8_t unknown1 :1;
uint8_t resolution :2;
uint8_t unknown2 :1;
uint8_t profile :4;
uint8_t unknown3;
uint8_t unknown4;
} __attribute__((packed));
struct logitech_g600_profile_data {
struct logitech_g600_profile_report report;
};
struct logitech_g600_data {
struct logitech_g600_profile_data profile_data[LOGITECH_G600_NUM_PROFILES];
};
_Static_assert(sizeof(struct logitech_g600_profile_report) == LOGITECH_G600_REPORT_SIZE_PROFILE,
"Size of logitech_g600_profile_report is wrong");
struct logitech_g600_button_type_mapping {
uint8_t raw;
enum ratbag_button_type type;
};
static const struct logitech_g600_button_type_mapping logitech_g600_button_type_mapping[] = {
{ 0, RATBAG_BUTTON_TYPE_LEFT },
{ 1, RATBAG_BUTTON_TYPE_RIGHT },
{ 2, RATBAG_BUTTON_TYPE_MIDDLE },
{ 3, RATBAG_BUTTON_TYPE_WHEEL_LEFT },
{ 4, RATBAG_BUTTON_TYPE_WHEEL_RIGHT },
{ 5, RATBAG_BUTTON_TYPE_PINKIE },
{ 6, RATBAG_BUTTON_TYPE_PROFILE_CYCLE_UP }, // G07
{ 7, RATBAG_BUTTON_TYPE_RESOLUTION_CYCLE_UP }, // G08
{ 8, RATBAG_BUTTON_TYPE_SIDE }, // G09
{ 9, RATBAG_BUTTON_TYPE_SIDE }, // G10
{ 10, RATBAG_BUTTON_TYPE_SIDE }, // G11
{ 11, RATBAG_BUTTON_TYPE_SIDE }, // G12
{ 12, RATBAG_BUTTON_TYPE_SIDE }, // G13
{ 13, RATBAG_BUTTON_TYPE_SIDE }, // G14
{ 14, RATBAG_BUTTON_TYPE_SIDE }, // G15
{ 15, RATBAG_BUTTON_TYPE_SIDE }, // G16
{ 16, RATBAG_BUTTON_TYPE_SIDE }, // G17
{ 17, RATBAG_BUTTON_TYPE_SIDE }, // G18
{ 18, RATBAG_BUTTON_TYPE_SIDE }, // G19
{ 19, RATBAG_BUTTON_TYPE_SIDE }, // G20
{ 20, RATBAG_BUTTON_TYPE_UNKNOWN }, //HACK is where the G-shift color information is located
{ 21, RATBAG_BUTTON_TYPE_LEFT }, // G-shift + left
{ 22, RATBAG_BUTTON_TYPE_RIGHT }, // G-shift + right click
{ 23, RATBAG_BUTTON_TYPE_MIDDLE }, // G-shift + middle
{ 24, RATBAG_BUTTON_TYPE_WHEEL_LEFT}, // G-shift + scroll left
{ 25, RATBAG_BUTTON_TYPE_WHEEL_RIGHT}, // G-shift + scroll right
{ 26, RATBAG_BUTTON_TYPE_PINKIE }, // G-shift + Pinky(shift modifer)
{ 27, RATBAG_BUTTON_TYPE_PROFILE_CYCLE_UP }, // G-shift + 07
{ 28, RATBAG_BUTTON_TYPE_RESOLUTION_CYCLE_UP }, // G-shift + G08
{ 29, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G09
{ 30, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G10
{ 31, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G11
{ 32, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G12
{ 33, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G13
{ 34, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G14
{ 35, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G15
{ 36, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G16
{ 37, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G17
{ 38, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G18
{ 39, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G19
{ 40, RATBAG_BUTTON_TYPE_SIDE }, // G-shift + G20
};
static enum ratbag_button_type
logitech_g600_raw_to_button_type(uint8_t data)
{
const struct logitech_g600_button_type_mapping *mapping;
ARRAY_FOR_EACH(logitech_g600_button_type_mapping, mapping) {
if (mapping->raw == data)
return mapping->type;
}
return RATBAG_BUTTON_TYPE_UNKNOWN;
}
struct logitech_g600_button_mapping {
uint8_t raw;
struct ratbag_button_action action;
};
static struct logitech_g600_button_mapping logitech_g600_button_mapping[] = {
/* 0x00 is either key or unassigned. Must be handled separately */
{ 0x01, BUTTON_ACTION_BUTTON(1) },
{ 0x02, BUTTON_ACTION_BUTTON(2) },
{ 0x03, BUTTON_ACTION_BUTTON(3) },
{ 0x04, BUTTON_ACTION_BUTTON(4) },
{ 0x05, BUTTON_ACTION_BUTTON(5) },
{ 0x11, BUTTON_ACTION_SPECIAL(RATBAG_BUTTON_ACTION_SPECIAL_RESOLUTION_UP) },
{ 0x12, BUTTON_ACTION_SPECIAL(RATBAG_BUTTON_ACTION_SPECIAL_RESOLUTION_DOWN) },
{ 0x13, BUTTON_ACTION_SPECIAL(RATBAG_BUTTON_ACTION_SPECIAL_RESOLUTION_CYCLE_UP) },
{ 0x14, BUTTON_ACTION_SPECIAL(RATBAG_BUTTON_ACTION_SPECIAL_PROFILE_CYCLE_UP) },
{ 0x15, BUTTON_ACTION_SPECIAL(RATBAG_BUTTON_ACTION_SPECIAL_RESOLUTION_ALTERNATE) },
{ 0x17, BUTTON_ACTION_SPECIAL(RATBAG_BUTTON_ACTION_SPECIAL_SECOND_MODE) },
};
static const struct ratbag_button_action*
logitech_g600_raw_to_button_action(uint8_t data)
{
struct logitech_g600_button_mapping *mapping;
ARRAY_FOR_EACH(logitech_g600_button_mapping, mapping) {
if (mapping->raw == data)
return &mapping->action;
}
return NULL;
}
static uint8_t logitech_g600_modifier_to_raw(int modifier_flags)
{
uint8_t modifiers = 0x00;
if (modifier_flags & MODIFIER_LEFTCTRL)
modifiers |= 0x01;
if (modifier_flags & MODIFIER_LEFTSHIFT)
modifiers |= 0x02;
if (modifier_flags & MODIFIER_LEFTALT)
modifiers |= 0x04;
if (modifier_flags & MODIFIER_LEFTMETA)
modifiers |= 0x08;
if (modifier_flags & MODIFIER_RIGHTCTRL)
modifiers |= 0x10;
if (modifier_flags & MODIFIER_RIGHTSHIFT)
modifiers |= 0x20;
if (modifier_flags & MODIFIER_RIGHTALT)
modifiers |= 0x40;
if (modifier_flags & MODIFIER_RIGHTMETA)
modifiers |= 0x80;
return modifiers;
}
static int logitech_g600_raw_to_modifiers(uint8_t data)
{
int modifiers = 0;
if (data & 0x01)
modifiers |= MODIFIER_LEFTCTRL;
if (data & 0x02)
modifiers |= MODIFIER_LEFTSHIFT;
if (data & 0x04)
modifiers |= MODIFIER_LEFTALT;
if (data & 0x08)
modifiers |= MODIFIER_LEFTMETA;
if (data & 0x10)
modifiers |= MODIFIER_RIGHTCTRL;
if (data & 0x20)
modifiers |= MODIFIER_RIGHTSHIFT;
if (data & 0x40)
modifiers |= MODIFIER_RIGHTALT;
if (data & 0x80)
modifiers |= MODIFIER_RIGHTMETA;
return modifiers;
}
static uint8_t
logitech_g600_button_action_to_raw(const struct ratbag_button_action *action)
{
struct logitech_g600_button_mapping *mapping;
ARRAY_FOR_EACH(logitech_g600_button_mapping, mapping) {
if (ratbag_button_action_match(&mapping->action, action))
return mapping->raw;
}
return 0;
}
static int
logitech_g600_get_active_profile_and_resolution(struct ratbag_device *device)
{
struct ratbag_profile *profile;
struct logitech_g600_active_profile_report buf;
int ret;
ret = ratbag_hidraw_raw_request(device, LOGITECH_G600_REPORT_ID_GET_ACTIVE,
(uint8_t*)&buf, sizeof(buf),
HID_FEATURE_REPORT, HID_REQ_GET_REPORT);
if (ret < 0)
return ret;
if (ret != sizeof(buf))
return -EIO;
list_for_each(profile, &device->profiles, link) {
struct ratbag_resolution *resolution;
if (profile->index != buf.profile)
continue;
profile->is_active = true;
ratbag_profile_for_each_resolution(profile, resolution) {
resolution->is_active = resolution->index == buf.resolution;
}
}
return 0;
}
static int
logitech_g600_set_current_resolution(struct ratbag_device *device, unsigned int index)
{
uint8_t buf[] = {LOGITECH_G600_REPORT_ID_SET_ACTIVE, 0x40 | (index << 1), 0x00, 0x00};
int ret;
log_debug(device->ratbag, "Setting active resolution to %d\n", index);
if (index >= LOGITECH_G600_NUM_DPI)
return -EINVAL;
ret = ratbag_hidraw_raw_request(device, buf[0], buf, sizeof(buf),
HID_FEATURE_REPORT, HID_REQ_SET_REPORT);
return ret == sizeof(buf) ? 0 : ret;
}
static int
logitech_g600_set_active_profile(struct ratbag_device *device, unsigned int index)
{
struct ratbag_profile *profile;
uint8_t buf[] = {LOGITECH_G600_REPORT_ID_SET_ACTIVE, 0x80 | (index << 4), 0x00, 0x00};
int ret, active_resolution = 0;
if (index >= LOGITECH_G600_NUM_PROFILES)
return -EINVAL;
ret = ratbag_hidraw_raw_request(device, buf[0], buf, sizeof(buf),
HID_FEATURE_REPORT, HID_REQ_SET_REPORT);
if (ret != sizeof(buf))
return ret;
/* Update the active resolution. After profile change the default is used. */
list_for_each(profile, &device->profiles, link) {
struct ratbag_resolution *resolution;
if (profile->index != index)
continue;
ratbag_profile_for_each_resolution(profile, resolution) {
resolution->is_active = resolution->is_default;
if (resolution->is_active)
active_resolution = resolution->index;
}
}
ret = logitech_g600_set_current_resolution(device, active_resolution);
if (ret < 0)
return ret;
return 0;
}
static void
logitech_g600_read_button(struct ratbag_button *button)
{
const struct ratbag_button_action *action;
struct ratbag_profile *profile = button->profile;
struct ratbag_device *device = profile->device;
struct logitech_g600_data *drv_data = device->drv_data;
struct logitech_g600_profile_data *pdata;
struct logitech_g600_profile_report *profile_report;
struct logitech_g600_button *button_report;
pdata = &drv_data->profile_data[profile->index];
profile_report = &pdata->report;
button_report = &profile_report->buttons[button->index];
ratbag_button_enable_action_type(button, RATBAG_BUTTON_ACTION_TYPE_BUTTON);
ratbag_button_enable_action_type(button, RATBAG_BUTTON_ACTION_TYPE_SPECIAL);
ratbag_button_enable_action_type(button, RATBAG_BUTTON_ACTION_TYPE_KEY);
ratbag_button_enable_action_type(button, RATBAG_BUTTON_ACTION_TYPE_MACRO);
button->type = logitech_g600_raw_to_button_type(button->index);
action = logitech_g600_raw_to_button_action(button_report->code);
if (action) {
ratbag_button_set_action(button, action);
}
else if (button_report->code == 0x00 && (button_report->modifier > 0x00 || button_report->key > 0x00))
{
unsigned int key, modifiers;
int rc;
key = ratbag_hidraw_get_keycode_from_keyboard_usage(device,
button_report->key);
modifiers = logitech_g600_raw_to_modifiers(button_report->modifier);
rc = ratbag_button_macro_new_from_keycode(button, key, modifiers);
if (rc < 0) {
log_error(device->ratbag,
"Error while reading button %d\n",
button->index);
button->action.type = RATBAG_BUTTON_ACTION_TYPE_NONE;
}
}
}
static void
logitech_g600_read_led(struct ratbag_led *led)
{
struct ratbag_profile *profile = led->profile;
struct ratbag_device *device = profile->device;
struct logitech_g600_data *drv_data = device->drv_data;
struct logitech_g600_profile_data *pdata;
struct logitech_g600_profile_report *report;
pdata = &drv_data->profile_data[profile->index];
report = &pdata->report;
led->type = RATBAG_LED_TYPE_SIDE;
led->colordepth = RATBAG_LED_COLORDEPTH_RGB_888;
ratbag_led_set_mode_capability(led, RATBAG_LED_OFF);
ratbag_led_set_mode_capability(led, RATBAG_LED_ON);
ratbag_led_set_mode_capability(led, RATBAG_LED_BREATHING);
ratbag_led_set_mode_capability(led, RATBAG_LED_CYCLE);
switch (report->led_effect) {
case LOGITECH_G600_LED_SOLID:
led->mode = RATBAG_LED_ON;
break;
case LOGITECH_G600_LED_BREATHE:
led->mode = RATBAG_LED_BREATHING;
led->ms = report->led_duration * 1000;
break;
case LOGITECH_G600_LED_CYCLE:
led->mode = RATBAG_LED_CYCLE;
led->ms = report->led_duration * 1000;
break;
}
led->color.red = report->led_red;
led->color.green = report->led_green;
led->color.blue = report->led_blue;
}
static void
logitech_g600_read_profile(struct ratbag_profile *profile)
{
struct ratbag_device *device = profile->device;
struct logitech_g600_data *drv_data = device->drv_data;
struct logitech_g600_profile_data *pdata;
struct logitech_g600_profile_report *report;
struct ratbag_resolution *resolution;
unsigned int report_rates[] = { 125, 142, 166, 200, 250, 333, 500, 1000 };
uint8_t report_id;
int rc;
struct ratbag_button *button;
struct ratbag_led *led;
assert(profile->index < LOGITECH_G600_NUM_PROFILES);
pdata = &drv_data->profile_data[profile->index];
report = &pdata->report;
switch (profile->index) {
case 0: report_id = LOGITECH_G600_REPORT_ID_PROFILE_0; break;
case 1: report_id = LOGITECH_G600_REPORT_ID_PROFILE_1; break;
case 2: report_id = LOGITECH_G600_REPORT_ID_PROFILE_2; break;
}
rc = ratbag_hidraw_raw_request(device, report_id,
(uint8_t*)report,
sizeof(*report),
HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (rc < (int)sizeof(*report)) {
log_error(device->ratbag,
"Error while requesting profile: %d\n", rc);
return;
}
ratbag_profile_set_report_rate_list(profile, report_rates,
ARRAY_LENGTH(report_rates));
ratbag_profile_set_report_rate(profile, 1000 / (report->frequency + 1));
ratbag_profile_for_each_resolution(profile, resolution) {
resolution->dpi_x = report->dpi[resolution->index] * 50;
resolution->dpi_y = report->dpi[resolution->index] * 50;
resolution->is_default = report->dpi_default - 1U == resolution->index;
resolution->is_active = resolution->is_default;
ratbag_resolution_set_dpi_list_from_range(resolution,
LOGITECH_G600_DPI_MIN,
LOGITECH_G600_DPI_MAX);
}
ratbag_profile_for_each_button(profile, button)
logitech_g600_read_button(button);
ratbag_profile_for_each_led(profile, led)
logitech_g600_read_led(led);
log_debug(device->ratbag, "Unknown data in profile %d\n", profile->index);
log_buf_debug(device->ratbag, " profile->unknown1: ",
report->unknown1, 5);
log_buf_debug(device->ratbag, " profile->unknown2: ",
report->unknown2, 13);
}
static int
logitech_g600_test_hidraw(struct ratbag_device *device)
{
return ratbag_hidraw_has_report(device, LOGITECH_G600_REPORT_ID_GET_ACTIVE);
}
static int
logitech_g600_probe(struct ratbag_device *device)
{
int rc;
struct logitech_g600_data *drv_data = NULL;
struct ratbag_profile *profile;
rc = ratbag_find_hidraw(device, logitech_g600_test_hidraw);
if (rc)
goto err;
drv_data = zalloc(sizeof(*drv_data));
ratbag_set_drv_data(device, drv_data);
ratbag_device_init_profiles(device,
LOGITECH_G600_NUM_PROFILES,
LOGITECH_G600_NUM_DPI,
LOGITECH_G600_NUM_BUTTONS,
LOGITECH_G600_NUM_LED);
ratbag_device_for_each_profile(device, profile)
logitech_g600_read_profile(profile);
rc = logitech_g600_get_active_profile_and_resolution(device);
if (rc < 0) {
log_error(device->ratbag,
"Can't talk to the mouse: '%s' (%d)\n",
strerror(-rc),
rc);
rc = -ENODEV;
goto err;
}
return 0;
err:
free(drv_data);
ratbag_set_drv_data(device, NULL);
return rc;
}
static int
logitech_g600_write_profile(struct ratbag_profile *profile)
{
struct ratbag_device *device = profile->device;
struct logitech_g600_data *drv_data = device->drv_data;
struct logitech_g600_profile_data *pdata;
struct logitech_g600_profile_report *report;
struct ratbag_resolution *resolution;
struct ratbag_button *button;
struct ratbag_led *led;
uint8_t *buf;
int rc, active_resolution = 0;
pdata = &drv_data->profile_data[profile->index];
report = &pdata->report;
report->frequency = (1000 / profile->hz) - 1;
ratbag_profile_for_each_resolution(profile, resolution) {
report->dpi[resolution->index] = resolution->dpi_x / 50;
if (resolution->is_default)
report->dpi_default = resolution->index + 1;
if (profile->is_active && resolution->is_active)
active_resolution = resolution->index;
}
list_for_each(button, &profile->buttons, link) {
struct ratbag_button_action *action = &button->action;
struct logitech_g600_button *raw_button;
raw_button = &report->buttons[button->index];
raw_button->code = logitech_g600_button_action_to_raw(action);
raw_button->modifier = 0x00;
raw_button->key = 0x00;
if (action->type == RATBAG_BUTTON_ACTION_TYPE_MACRO) {
unsigned int key, modifiers;
rc = ratbag_action_keycode_from_macro(action,
&key,
&modifiers);
if (rc < 0) {
log_error(device->ratbag,
"Error while writing macro for button %d\n",
button->index);
}
raw_button->key = ratbag_hidraw_get_keyboard_usage_from_keycode(
device, key);
raw_button->modifier = logitech_g600_modifier_to_raw(modifiers);
}
}
list_for_each(led, &profile->leds, link) {
report->led_red = led->color.red;
report->led_green = led->color.green;
report->led_blue = led->color.blue;
switch (led->mode) {
case RATBAG_LED_ON:
report->led_effect = LOGITECH_G600_LED_SOLID;
break;
case RATBAG_LED_OFF:
report->led_effect = LOGITECH_G600_LED_SOLID;
report->led_red = 0x00;
report->led_green = 0x00;
report->led_blue = 0x00;
break;
case RATBAG_LED_BREATHING:
report->led_effect = LOGITECH_G600_LED_BREATHE;
report->led_duration = led->ms / 1000;
break;
case RATBAG_LED_CYCLE:
report->led_effect = LOGITECH_G600_LED_CYCLE;
report->led_duration = led->ms / 1000;
break;
}
if (report->led_duration > 0x0f)
report->led_duration = 0x0f;
}
// For now the default will copy over the main color into the g-shift color
// future update may add support to set this via cli command
report->g_shift_color[0] = report->led_red;
report->g_shift_color[1] = report->led_green;
report->g_shift_color[2] = report->led_blue;
buf = (uint8_t*)report;
rc = ratbag_hidraw_raw_request(device, report->id,
buf,
sizeof(*report),
HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (rc < (int)sizeof(*report)) {
log_error(device->ratbag,
"Error while writing profile: %d\n", rc);
return rc;
}
if (profile->is_active) {
rc = logitech_g600_set_current_resolution(device, active_resolution);
if (rc < 0)
return rc;
}
return 0;
}
static int
logitech_g600_commit(struct ratbag_device *device)
{
struct ratbag_profile *profile;
int rc = 0;
list_for_each(profile, &device->profiles, link) {
if (!profile->dirty)
continue;
log_debug(device->ratbag,
"Profile %d changed, rewriting\n", profile->index);
rc = logitech_g600_write_profile(profile);
if (rc)
return rc;
}
return 0;
}
static void
logitech_g600_remove(struct ratbag_device *device)
{
ratbag_close_hidraw(device);
free(ratbag_get_drv_data(device));
}
struct ratbag_driver logitech_g600_driver = {
.name = "Logitech G600",
.id = "logitech_g600",
.probe = logitech_g600_probe,
.remove = logitech_g600_remove,
.commit = logitech_g600_commit,
.set_active_profile = logitech_g600_set_active_profile,
};
| 30.05225 | 113 | 0.748189 |
b32bade8289b61492c5633c9f86c176386cbd501 | 3,065 | h | C | ui/base/gestures/gesture_recognizer.h | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2017-03-21T23:19:25.000Z | 2019-02-03T05:32:47.000Z | ui/base/gestures/gesture_recognizer.h | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/base/gestures/gesture_recognizer.h | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2017-07-31T19:09:52.000Z | 2019-01-04T18:48:50.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_BASE_GESTURES_GESTURE_RECOGNIZER_H_
#define UI_BASE_GESTURES_GESTURE_RECOGNIZER_H_
#include <vector>
#include "base/memory/scoped_vector.h"
#include "ui/base/events/event_constants.h"
#include "ui/base/gestures/gesture_types.h"
#include "ui/base/ui_export.h"
namespace ui {
// A GestureRecognizer is an abstract base class for conversion of touch events
// into gestures.
class UI_EXPORT GestureRecognizer {
public:
static GestureRecognizer* Create(GestureEventHelper* helper);
// List of GestureEvent*.
typedef ScopedVector<GestureEvent> Gestures;
virtual ~GestureRecognizer() {}
// Invoked for each touch event that could contribute to the current gesture.
// Returns list of zero or more GestureEvents identified after processing
// TouchEvent.
// Caller would be responsible for freeing up Gestures.
virtual Gestures* ProcessTouchEventForGesture(const TouchEvent& event,
ui::EventResult result,
GestureConsumer* consumer) = 0;
// This is called when the consumer is destroyed. So this should cleanup any
// internal state maintained for |consumer|.
virtual void CleanupStateForConsumer(GestureConsumer* consumer) = 0;
// Return the window which should handle this TouchEvent, in the case where
// the touch is already associated with a target.
// Otherwise, returns null.
virtual GestureConsumer* GetTouchLockedTarget(TouchEvent* event) = 0;
// Return the window which should handle this GestureEvent.
virtual GestureConsumer* GetTargetForGestureEvent(GestureEvent* event) = 0;
// If there is an active touch within
// GestureConfiguration::max_separation_for_gesture_touches_in_pixels,
// of |location|, returns the target of the nearest active touch.
virtual GestureConsumer* GetTargetForLocation(const gfx::Point& location) = 0;
// Makes |new_consumer| the target for events previously targeting
// |current_consumer|. All other targets are canceled.
// The caller is responsible for updating the state of the consumers to
// be aware of this transfer of control (there are no ENTERED/EXITED events).
// If |new_consumer| is NULL, all events are canceled.
// If |old_consumer| is NULL, all events not already targeting |new_consumer|
// are canceled.
virtual void TransferEventsTo(GestureConsumer* current_consumer,
GestureConsumer* new_consumer) = 0;
// If a gesture is underway for |consumer| |point| is set to the last touch
// point and true is returned. If no touch events have been processed for
// |consumer| false is returned and |point| is untouched.
virtual bool GetLastTouchPointForTarget(GestureConsumer* consumer,
gfx::Point* point) = 0;
};
} // namespace ui
#endif // UI_BASE_GESTURES_GESTURE_RECOGNIZER_H_
| 42.569444 | 80 | 0.726917 |
cad75b0e22a6286eb08e196044e13fd4368c9896 | 6,571 | h | C | TDEngine2/include/ecs/CSystemManager.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-15T01:14:15.000Z | 2019-07-15T01:14:15.000Z | TDEngine2/include/ecs/CSystemManager.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 76 | 2018-10-27T16:59:36.000Z | 2022-03-30T17:40:39.000Z | TDEngine2/include/ecs/CSystemManager.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-29T02:02:08.000Z | 2019-07-29T02:02:08.000Z | /*!
\file CSystemManager.h
\date 29.09.2018
\authors Kasimov Ildar
*/
#pragma once
#include "ISystemManager.h"
#include "../core/CBaseObject.h"
#include "../utils/Utils.h"
#include "../core/Event.h"
#include <unordered_map>
#include <vector>
#include <list>
#include <algorithm>
#include <mutex>
namespace TDEngine2
{
class IWorld;
class ISystem;
/*!
\brief A factory function for creation objects of CSystemManager's type.
\param[in, out] pWorld A pointer to IWorld implementation
\param[in, out] pEventManager A pointer to IEventManager implementation
\param[out] result Contains RC_OK if everything went ok, or some other code, which describes an error
\return A pointer to CSystemManager's implementation
*/
TDE2_API ISystemManager* CreateSystemManager(IWorld* pWorld, IEventManager* pEventManager, E_RESULT_CODE& result);
/*!
class CSystemManager
\brief The implementation of ISystemManager. The manager
registers, activates and update existing systems.
*/
class CSystemManager : public CBaseObject, public ISystemManager, public IEventHandler
{
public:
friend TDE2_API ISystemManager* CreateSystemManager(IWorld* pWorld, IEventManager* pEventManager, E_RESULT_CODE& result);
protected:
typedef struct TSystemDesc
{
TSystemId mSystemId; /// low bytes contains system's unique id, high bytes contains its priority
ISystem* mpSystem;
} TSystemDesc, *TSystemDescPtr;
typedef std::vector<TSystemDesc> TSystemsArray;
typedef std::list<TSystemDesc> TSystemsList;
typedef std::unordered_map<E_SYSTEM_PRIORITY, U32> TSystemsAccountTable;
public:
TDE2_REGISTER_TYPE(CSystemManager)
/*!
\brief The method initializes a ISystemManager's instance
\param[in, out] pWorld A pointer to IWorld implementation
\param[in, out] pEventManager A pointer to IEventManager implementation
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Init(IWorld* pWorld, IEventManager* pEventManager) override;
/*!
\brief The method frees all memory occupied by the object
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Free() override;
/*!
\brief The method registers specified system
\param[in] A pointer to ISystem's implementation
\param[in] priority A value that represents a priority of a system. Than higher
priority value then sooner a system will be executed
\return Either registered system's identifier or an error code
*/
TDE2_API TResult<TSystemId> RegisterSystem(ISystem* pSystem, E_SYSTEM_PRIORITY priority = E_SYSTEM_PRIORITY::SP_NORMAL_PRIORITY) override;
/*!
\brief The method unregisters specified system, but doesn't free its memory
\param[in] systemId A system's identifier
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE UnregisterSystem(TSystemId systemId) override;
/*!
\brief The method unregisters specified system and free its memory
\param[in] systemId A system's identifier
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE UnregisterSystemImmediately(TSystemId systemId) override;
/*!
\brief The method marks specified system as an active
\param[in] systemId A system's identifier
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE ActivateSystem(TSystemId systemId) override;
/*!
\brief The method deactivates specified system
\param[in] systemId A system's identifier
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE DeactivateSystem(TSystemId systemId) override;
/*!
\brief The method calls ISystem::OnInit method on each system that is currently active
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE InitSystems() override;
/*!
\brief The method unregisters and frees all existing systems
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE ClearSystemsRegistry() override;
/*!
\brief The main method that should be implemented in all derived classes.
It contains all the logic that the system will execute during engine's work.
\param[in] pWorld A pointer to a main scene's object
\param[in] dt A delta time's value
*/
TDE2_API void Update(IWorld* pWorld, F32 dt) override;
/*!
\brief The method calls ISystem::OnDestroy method on each system
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE DestroySystems() override;
/*!
\brief The method receives a given event and processes it
\param[in] pEvent A pointer to event data
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE OnEvent(const TBaseEvent* pEvent) override;
/*!
\brief The method returns an identifier of a listener
\return The method returns an identifier of a listener
*/
TDE2_API TEventListenerId GetListenerId() const override;
/*!
\brief The method returns an identifier of a registered system by its type. IF there is no
active system of given type then InvalidSystemId is returned
\param[in] systemTypeId A system type's identifier
\return The method returns an identifier of a registered system by its type
*/
TDE2_API TSystemId FindSystem(TypeId systemTypeId) override;
protected:
DECLARE_INTERFACE_IMPL_PROTECTED_MEMBERS(CSystemManager)
template<typename T>
T _findSystemDesc(T first, T end, TSystemId systemId)
{
return std::find_if(first, end, [systemId](const TSystemDesc& systemDesc)
{
return systemDesc.mSystemId == systemId;
});
}
TDE2_API E_RESULT_CODE _internalUnregisterSystem(TSystemId systemId);
TDE2_API E_RESULT_CODE _internalUnregisterSystemImmediately(TSystemId systemId);
protected:
TSystemsArray mpActiveSystems;
TSystemsList mpDeactivatedSystems;
IEventManager* mpEventManager;
IWorld* mpWorld;
TSystemsAccountTable mSystemsIdentifiersTable;
mutable std::mutex mMutex;
bool mIsDirty;
};
} | 28.201717 | 141 | 0.730026 |
1e6ea5496384e01924015c29a80976e29f7ba66a | 1,516 | h | C | src/transactions/test/test_helper/WithdrawRequestHelper.h | RomanTkachenkoDistr/SwarmCore | db0544758e7bb3c879778cfdd6946b9a72ba23ab | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/transactions/test/test_helper/WithdrawRequestHelper.h | RomanTkachenkoDistr/SwarmCore | db0544758e7bb3c879778cfdd6946b9a72ba23ab | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/transactions/test/test_helper/WithdrawRequestHelper.h | RomanTkachenkoDistr/SwarmCore | db0544758e7bb3c879778cfdd6946b9a72ba23ab | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | #pragma once
// Copyright 2014 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include <ledger/ReviewableRequestFrame.h>
#include "overlay/StellarXDR.h"
#include "TxHelper.h"
namespace stellar
{
namespace txtest
{
class WithdrawRequestHelper : TxHelper
{
private:
// returns true if there are stats asset and corresponding asset pair
bool canCalculateStats(AssetCode baseAsset);
void validateStatsChange(StatisticsFrame::pointer statsBefore, StatisticsFrame::pointer statsAfter,
ReviewableRequestFrame::pointer withdrawRequest);
public:
WithdrawRequestHelper(TestManager::pointer testManager);
CreateWithdrawalRequestResult applyCreateWithdrawRequest(
Account& source, WithdrawalRequest request,
CreateWithdrawalRequestResultCode expectedResult =
CreateWithdrawalRequestResultCode::SUCCESS);
static WithdrawalRequest createWithdrawRequest(BalanceID balance, uint64_t amount,
Fee fee,
std::string externalDetails,
AssetCode autoConversionDestAsset,
uint64_t expectedAutoConversion);
TransactionFramePtr createWithdrawalRequestTx(
Account& source, WithdrawalRequest request);
};
}
}
| 36.095238 | 103 | 0.687995 |
f033fc4ff9622c814f43b98c31cdcd43d1ef7ffd | 557 | h | C | selection2.h | CelestialAmber/tobutobugirl-dx | 5c2ec21f800966c67825afe825765a082021b2da | [
"MIT"
] | 47 | 2019-10-28T21:49:06.000Z | 2022-03-06T12:21:38.000Z | selection2.h | CelestialAmber/tobutobugirl-dx | 5c2ec21f800966c67825afe825765a082021b2da | [
"MIT"
] | null | null | null | selection2.h | CelestialAmber/tobutobugirl-dx | 5c2ec21f800966c67825afe825765a082021b2da | [
"MIT"
] | 5 | 2019-10-29T02:38:16.000Z | 2021-09-12T02:51:03.000Z | #ifndef SELECTION2_MAP_H
#define SELECTION2_MAP_H
#define selection2_data_length 28U
#define selection2_data_length2 28U
#define selection2_tiles_width 16U
#define selection2_tiles_height 6U
#define selection2_tiles_offset 90U
#define selection2_palette_data_length 1U
#define selection2_palette_offset 3U
extern const unsigned char selection2_data[];
extern const unsigned char selection2_data2[];
extern const unsigned char selection2_tiles[];
extern const unsigned char selection2_palettes[];
extern const unsigned int selection2_palette_data[];
#endif
| 32.764706 | 52 | 0.861759 |
29f4585bf8022b7ee233f5b16f33431f8a6f41ee | 3,404 | h | C | src/ajs_target.h | artynet/alljoyn-js | 1e910726267ae294012ee097e4effa82cc188d23 | [
"Apache-2.0"
] | null | null | null | src/ajs_target.h | artynet/alljoyn-js | 1e910726267ae294012ee097e4effa82cc188d23 | [
"Apache-2.0"
] | null | null | null | src/ajs_target.h | artynet/alljoyn-js | 1e910726267ae294012ee097e4effa82cc188d23 | [
"Apache-2.0"
] | null | null | null | #ifndef _AJS_TARGET_H
#define _AJS_TARGET_H
/**
* @file
*/
/******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include "ajs.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Returns maximum size of a script for this target
*/
size_t AJS_GetMaxScriptLen();
/**
* Delete the currently installed script.
*/
AJ_Status AJS_DeleteScript();
/**
* Find out if a script is installed
*
* @return Returns TRUE if a script is installed.
*/
uint8_t AJS_IsScriptInstalled();
#define AJS_SCRIPT_READ 0 /**< Opens a script is read mode */
#define AJS_SCRIPT_WRITE 1 /**< Opens a script in write mode */
/**
* Open a script to read or write. Returns a pointer to an opaque structure required by
* AJS_ReadScript() and AJS_WriteScript(). If the script is opened to write the currently installed
* script is deleted.
*
* @param mode Indicates if the script is being opened to read it or write it.
*/
void* AJS_OpenScriptFile(uint8_t mode);
/**
* Writes data to a script file.
*
* @param scriptf A pointer to an opaque data structure that maintains state information
* @param data The data to be appended to the script
* @param len The length of the data to be appended to the script
*
* @return - AJ_OK if the data was succesfully appended to the script file.
* - AJ_ERR_RESOURCES if attempting to write more that AJS_MaxScriptLen() bytes
*/
AJ_Status AJS_WriteScriptFile(void* scriptf, const uint8_t* data, size_t len);
/**
* Reads a script returning a pointer the entire contiguous script file.
*/
AJ_Status AJS_ReadScriptFile(void* scriptf, const uint8_t** data, size_t* len);
/**
* Close an open script freeing any resources.
*
* @param scriptf A pointer to an opaque data structure that maintains state information
*
* @return - AJ_OK if the script was closed
* - AJ_ERR_UNEXPECTED if the script was not open
*/
AJ_Status AJS_CloseScriptFile(void* scriptf);
#ifdef __cplusplus
}
#endif
#endif | 33.70297 | 99 | 0.685664 |
7654729274eb39f28c13f1f70235520c19841272 | 1,455 | h | C | windows/wrapper/impl_org_webRtc_RTCCertificate.h | webrtc-uwp/webrtc-windows-apis | accb133e195da9b0e77f59d749a282d133a80f24 | [
"BSD-3-Clause"
] | 9 | 2019-03-27T12:19:29.000Z | 2022-01-25T05:13:55.000Z | windows/wrapper/impl_org_webRtc_RTCCertificate.h | webrtc-uwp/webrtc-windows-apis | accb133e195da9b0e77f59d749a282d133a80f24 | [
"BSD-3-Clause"
] | 8 | 2018-11-07T19:09:19.000Z | 2019-11-27T15:20:08.000Z | windows/wrapper/impl_org_webRtc_RTCCertificate.h | webrtc-uwp/webrtc-windows-apis | accb133e195da9b0e77f59d749a282d133a80f24 | [
"BSD-3-Clause"
] | 12 | 2019-06-06T14:15:26.000Z | 2022-01-24T13:35:30.000Z |
#pragma once
#include "types.h"
#include "generated/org_webRtc_RTCCertificate.h"
#include "impl_org_webRtc_pre_include.h"
#include "rtc_base/scoped_ref_ptr.h"
#include "impl_org_webRtc_post_include.h"
namespace wrapper {
namespace impl {
namespace org {
namespace webRtc {
struct RTCCertificate : public wrapper::org::webRtc::RTCCertificate
{
ZS_DECLARE_TYPEDEF_PTR(wrapper::org::webRtc::RTCCertificate, WrapperType);
ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::RTCCertificate, WrapperImplType);
ZS_DECLARE_TYPEDEF_PTR(::rtc::RTCCertificate, NativeType);
typedef ::rtc::scoped_refptr<NativeType> NativeTypeScopedPtr;
NativeTypeScopedPtr native_;
RTCCertificateWeakPtr thisWeak_;
RTCCertificate() noexcept;
virtual ~RTCCertificate() noexcept;
// properties RTCCertificate
::zsLib::Time get_expires() noexcept override;
shared_ptr< list< wrapper::org::webRtc::RTCDtlsFingerprintPtr > > get_fingerprints() noexcept override;
ZS_NO_DISCARD() static WrapperImplTypePtr toWrapper(NativeType *native) noexcept;
ZS_NO_DISCARD() static WrapperImplTypePtr toWrapper(NativeTypeScopedPtr native) noexcept;
ZS_NO_DISCARD() static NativeTypeScopedPtr toNative(WrapperTypePtr wrapper) noexcept;
};
} // webRtc
} // org
} // namespace impl
} // namespace wrapper
| 32.333333 | 113 | 0.704467 |
6392e01da0d06c1715c60ad80db388da18fc254e | 2,188 | h | C | AlfrescoSDK/CMIS/AlfrescoCMIS/AlfrescoCMISUtil.h | Alfresco/alfresco-ios-sdk | c2290a19793e650a22bbfde505f7825f3107138a | [
"Apache-2.0"
] | 10 | 2015-01-12T16:42:25.000Z | 2021-05-25T13:37:51.000Z | AlfrescoSDK/CMIS/AlfrescoCMIS/AlfrescoCMISUtil.h | Alfresco/alfresco-ios-sdk | c2290a19793e650a22bbfde505f7825f3107138a | [
"Apache-2.0"
] | 10 | 2015-01-12T16:14:20.000Z | 2020-08-05T14:42:35.000Z | AlfrescoSDK/CMIS/AlfrescoCMIS/AlfrescoCMISUtil.h | Alfresco/alfresco-ios-sdk | c2290a19793e650a22bbfde505f7825f3107138a | [
"Apache-2.0"
] | 12 | 2015-02-13T07:43:03.000Z | 2021-05-25T13:37:53.000Z | /*
******************************************************************************
* Copyright (C) 2005-2020 Alfresco Software Limited.
*
* This file is part of the Alfresco Mobile SDK.
*
* 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.
*****************************************************************************
*/
//
// AlfrescoCMISUtil
//
#import <Foundation/Foundation.h>
#import "AlfrescoNode.h"
@class CMISObject, CMISProperties, CMISSession;
@interface AlfrescoCMISUtil : NSObject
/**
* Processes Alfresco cmis extensions:
* - Returns an array with al the aspect type ids for the object
* - Adds all extension properties to the properties property of the object.
*/
+ (NSMutableArray *)processExtensionElementsForObject:(CMISObject *)cmisObject;
/**
maps CMIS errors to Alfresco Errors
*/
+ (NSError *)alfrescoErrorWithCMISError:(NSError *)cmisError;
/**
* Prepares the CMIS objectTypeId property for the given set of properties.
*/
+ (NSString *)prepareObjectTypeIdForProperties:(NSDictionary *)alfrescoProperties
type:(NSString *)type
aspects:(NSArray *)aspects
folder:(BOOL)folder;
/**
* Prepares the given dictionary of Alfresco properties for update via CMIS
*/
+ (void)preparePropertiesForUpdate:(NSDictionary *)alfrescoProperties
aspects:(NSArray *)aspects
node:(AlfrescoNode *)node
cmisSession:(CMISSession *)cmisSession
completionBlock:(void (^)(CMISProperties *cmisProperties, NSError *error))completionBlock;
@end
| 35.290323 | 109 | 0.626143 |
e4187a600ae548d6386c0b8bd0613e5b4ad52ed4 | 751 | h | C | source/slang/object-meta-begin.h | 0xafbf/slang | 43ce8d2a6aa654a8e6877b5423cf5d8d52636710 | [
"MIT"
] | 2 | 2019-02-11T11:17:42.000Z | 2019-03-16T03:20:33.000Z | source/slang/object-meta-begin.h | 0xafbf/slang | 43ce8d2a6aa654a8e6877b5423cf5d8d52636710 | [
"MIT"
] | null | null | null | source/slang/object-meta-begin.h | 0xafbf/slang | 43ce8d2a6aa654a8e6877b5423cf5d8d52636710 | [
"MIT"
] | null | null | null | // object-meta-begin.h
#ifndef SYNTAX_CLASS
#error The 'SYNTAX_CLASS' macro should be defined before including 'object-meta-begin.h'
#endif
#ifndef ABSTRACT_SYNTAX_CLASS
#define ABSTRACT_SYNTAX_CLASS(NAME, BASE) SYNTAX_CLASS(NAME, BASE)
#endif
#ifndef END_SYNTAX_CLASS
#define END_SYNTAX_CLASS() /* empty */
#endif
#ifndef DECL_FIELD
#define DECL_FIELD(TYPE, NAME) SYNTAX_FIELD(TYPE, NAME)
#endif
#ifndef SYNTAX_FIELD
#define SYNTAX_FIELD(TYPE, NAME) FIELD(TYPE, NAME)
#endif
#ifndef FIELD_INIT
#define FIELD_INIT(TYPE, NAME, INIT) FIELD(TYPE, NAME)
#endif
#ifndef FIELD
#define FIELD(...) /* empty */
#endif
#ifndef RAW
#define RAW(...) /* empty */
#endif
#define SIMPLE_SYNTAX_CLASS(NAME, BASE) SYNTAX_CLASS(NAME, BASE) END_SYNTAX_CLASS()
| 20.297297 | 88 | 0.757656 |
8d4e7ad0f403ae1f176480817815f69d46bb4a4f | 5,213 | c | C | Chapter16/carddeck_1c.c | Biswajeetray7/Learn-C-Programming | b5d7f9a6ab0d753089912f54f060b5b2cb3118cb | [
"MIT"
] | 105 | 2020-06-08T02:48:35.000Z | 2022-03-29T17:50:38.000Z | Chapter16/carddeck_1c.c | Biswajeetray7/Learn-C-Programming | b5d7f9a6ab0d753089912f54f060b5b2cb3118cb | [
"MIT"
] | 2 | 2021-06-01T16:56:48.000Z | 2021-12-04T06:51:59.000Z | Chapter16/carddeck_1c.c | Biswajeetray7/Learn-C-Programming | b5d7f9a6ab0d753089912f54f060b5b2cb3118cb | [
"MIT"
] | 37 | 2020-06-24T01:17:04.000Z | 2022-03-30T13:40:09.000Z | // carddeck_1c.c
// Chapter 16
// Learn C Programming
//
// carddeck_1c.c builds upon carddeck_1b.c.
// In this version, we add an array of structures, called Deck
// and some functions to manipulate the Deck array.
//
// compile with
//
// cc carddeck_1c.c -o carddeck_1c -Wall -Werror =std=c11
//
#include <stdbool.h> // for Boolean
#include <stdio.h> // for printf()
#include <string.h> // for strcpy() and strcat()
// Useful constants (avoid "magic numbers" whose meaning is
// sometimes vague and whose values may change). Use these instead
// of literals; when you need to change these, they are applied
// everywhere.
//
enum {
kCardsInDeck = 52, // For now, 52 cards in a deck. This will change
// depending upon the card game and the # of wild
// cards, etc.
kCardsInSuit = 13 // For now, kCardsInDeck / 4. This will change
// depending upon the card game.
};
const bool kWildCard = true;
const bool kNotWildCard = false;
// ============================================
// Definitions related to a Card
//
// Card Suits
//
typedef enum
{
club = 1,
diamond,
heart,
spade
} Suit;
// Card Faces
//
typedef enum
{
one = 1,
two ,
three ,
four ,
five ,
six ,
seven ,
eight ,
nine ,
ten ,
jack ,
queen ,
king ,
ace
} Face;
// A Card
//
typedef struct
{
Suit suit;
int suitValue;
Face face;
int faceValue;
bool isWild;
} Card;
// Operations on a Card
//
void InitializeCard( Card* pCard , Suit s , Face f , bool w );
void PrintCard( Card* pCard );
void CardToString( Card* pCard , char pCardStr[20] );
// ============================================
// Definitions related to a Deck
//
// A Deck
// For now, the deck will be declared as an array of Cards in main().
// operations on a Deck (array of cards)
//
void InitializeDeck( Card* pDeck );
void PrintDeck( Card* pDeck );
int main( void )
{
Card deck[ kCardsInDeck ];
InitializeDeck( &deck[0] );
PrintDeck( &deck[0] );
}
// ============================================
// Operations on a Card
// ============================================
void InitializeCard( Card* pCard, Suit s , Face f , bool w )
{
pCard->suit = s;
pCard->suitValue = (int)s;
pCard->face = f;
pCard->faceValue = (int)f;
pCard->isWild = w;
}
void PrintCard( Card* pCard )
{
char cardStr[20] = {0};
CardToString( pCard , cardStr );
printf( "%18s" , cardStr );
}
void CardToString( Card* pCard , char pCardStr[20] )
{
switch( pCard->face )
{
case two: strcpy( pCardStr , " 2 " ); break;
case three: strcpy( pCardStr , " 3 " ); break;
case four: strcpy( pCardStr , " 4 " ); break;
case five: strcpy( pCardStr , " 5 " ); break;
case six: strcpy( pCardStr , " 6 " ); break;
case seven: strcpy( pCardStr , " 7 " ); break;
case eight: strcpy( pCardStr , " 8 " ); break;
case nine: strcpy( pCardStr , " 9 " ); break;
case ten: strcpy( pCardStr , " 10 " ); break;
case jack: strcpy( pCardStr , " Jack " ); break;
case queen: strcpy( pCardStr , "Queen " ); break;
case king: strcpy( pCardStr , " King " ); break;
case ace: strcpy( pCardStr , " Ace " ); break;
default: strcpy( pCardStr , " ??? " ); break;
}
switch( pCard->suit )
{
case spade: strcat( pCardStr , "of Spades "); break;
case heart: strcat( pCardStr , "of Hearts "); break;
case diamond: strcat( pCardStr , "of Diamonds"); break;
case club: strcat( pCardStr , "of Clubs "); break;
default: strcat( pCardStr , "of ???s "); break;
}
}
// ============================================
// Operations on a Deck of Cards
// ============================================
void InitializeDeck( Card* pDeck )
{
Face f[] = { two , three , four , five , six , seven ,
eight , nine , ten , jack , queen , king , ace };
Card* pC;
for( int i = 0 ; i < kCardsInSuit ; i++ )
{
pC = &(pDeck[ i + (0*kCardsInSuit) ]);
InitializeCard( pC , spade , f[i], kNotWildCard );
pC = &(pDeck[ i + (1*kCardsInSuit) ]);
InitializeCard( pC , heart , f[i], kNotWildCard );
pC = &(pDeck[ i + (2*kCardsInSuit) ]);
InitializeCard( pC , diamond , f[i], kNotWildCard );
pC = &(pDeck[ i + (3*kCardsInSuit) ]);
InitializeCard( pC , club , f[i], kNotWildCard );
}
}
void PrintDeck( Card* pDeck )
{
printf( "%d cards in the deck\n\n" ,
kCardsInDeck );
printf( "The ordered deck: \n" );
for( int i = 0 ; i < kCardsInSuit ; i++ )
{
int index = i + (0*kCardsInSuit);
printf( "(%2d)" , index+1 );
PrintCard( &(pDeck[ index ] ) );
index = i + (1*kCardsInSuit);
printf( " (%2d)" , index+1 );
PrintCard( &(pDeck[ index ] ) );
index = i + (2*kCardsInSuit);
printf( " (%2d)" , index+1 );
PrintCard( &(pDeck[ i + (2*kCardsInSuit) ] ) );
index = i + (3*kCardsInSuit);
printf( " (%2d)" , index+1 );
PrintCard( &(pDeck[ index ] ) );
printf( "\n" );
}
printf( "\n\n" );
}
// eof
| 23.803653 | 71 | 0.532323 |
a55b1b930392e33f6de2eb33863df67eb8076d78 | 15,826 | c | C | lib/console.c | noahbliss/shim | c252b9ee94c342f9074a3e9064fd254eef203a63 | [
"BSD-2-Clause"
] | 1 | 2020-12-15T18:37:13.000Z | 2020-12-15T18:37:13.000Z | lib/console.c | noahbliss/shim | c252b9ee94c342f9074a3e9064fd254eef203a63 | [
"BSD-2-Clause"
] | null | null | null | lib/console.c | noahbliss/shim | c252b9ee94c342f9074a3e9064fd254eef203a63 | [
"BSD-2-Clause"
] | 3 | 2021-01-29T17:37:02.000Z | 2021-02-10T19:35:26.000Z | /*
* Copyright 2012 <James.Bottomley@HansenPartnership.com>
* Copyright 2013 Red Hat Inc. <pjones@redhat.com>
*
* see COPYING file
*/
#include <efi.h>
#include <efilib.h>
#include <stdarg.h>
#include <stdbool.h>
#include "shim.h"
static UINT8 console_text_mode = 0;
static int
count_lines(CHAR16 *str_arr[])
{
int i = 0;
while (str_arr[i])
i++;
return i;
}
static void
SetMem16(CHAR16 *dst, UINT32 n, CHAR16 c)
{
unsigned int i;
for (i = 0; i < n/2; i++) {
dst[i] = c;
}
}
EFI_STATUS
console_get_keystroke(EFI_INPUT_KEY *key)
{
SIMPLE_INPUT_INTERFACE *ci = ST->ConIn;
UINTN EventIndex;
EFI_STATUS efi_status;
do {
gBS->WaitForEvent(1, &ci->WaitForKey, &EventIndex);
efi_status = ci->ReadKeyStroke(ci, key);
} while (efi_status == EFI_NOT_READY);
return efi_status;
}
static VOID setup_console (int text)
{
EFI_STATUS efi_status;
EFI_CONSOLE_CONTROL_PROTOCOL *concon;
static EFI_CONSOLE_CONTROL_SCREEN_MODE mode =
EfiConsoleControlScreenGraphics;
EFI_CONSOLE_CONTROL_SCREEN_MODE new_mode;
efi_status = LibLocateProtocol(&EFI_CONSOLE_CONTROL_GUID,
(VOID **)&concon);
if (EFI_ERROR(efi_status))
return;
if (text) {
new_mode = EfiConsoleControlScreenText;
efi_status = concon->GetMode(concon, &mode, 0, 0);
/* If that didn't work, assume it's graphics */
if (EFI_ERROR(efi_status))
mode = EfiConsoleControlScreenGraphics;
if (text < 0) {
if (mode == EfiConsoleControlScreenGraphics)
console_text_mode = 0;
else
console_text_mode = 1;
return;
}
} else {
new_mode = mode;
}
concon->SetMode(concon, new_mode);
console_text_mode = text;
}
VOID console_fini(VOID)
{
if (console_text_mode)
setup_console(0);
}
UINTN
console_print(const CHAR16 *fmt, ...)
{
va_list args;
UINTN ret;
if (!console_text_mode)
setup_console(1);
va_start(args, fmt);
ret = VPrint(fmt, args);
va_end(args);
return ret;
}
UINTN
console_print_at(UINTN col, UINTN row, const CHAR16 *fmt, ...)
{
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
va_list args;
UINTN ret;
if (!console_text_mode)
setup_console(1);
co->SetCursorPosition(co, col, row);
va_start(args, fmt);
ret = VPrint(fmt, args);
va_end(args);
return ret;
}
void
console_print_box_at(CHAR16 *str_arr[], int highlight,
int start_col, int start_row,
int size_cols, int size_rows,
int offset, int lines)
{
int i;
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
UINTN rows, cols;
CHAR16 *Line;
if (lines == 0)
return;
if (!console_text_mode)
setup_console(1);
co->QueryMode(co, co->Mode->Mode, &cols, &rows);
/* last row on screen is unusable without scrolling, so ignore it */
rows--;
if (size_rows < 0)
size_rows = rows + size_rows + 1;
if (size_cols < 0)
size_cols = cols + size_cols + 1;
if (start_col < 0)
start_col = (cols + start_col + 2)/2;
if (start_row < 0)
start_row = (rows + start_row + 2)/2;
if (start_col < 0)
start_col = 0;
if (start_row < 0)
start_row = 0;
if (start_col > (int)cols || start_row > (int)rows) {
console_print(L"Starting Position (%d,%d) is off screen\n",
start_col, start_row);
return;
}
if (size_cols + start_col > (int)cols)
size_cols = cols - start_col;
if (size_rows + start_row > (int)rows)
size_rows = rows - start_row;
if (lines > size_rows - 2)
lines = size_rows - 2;
Line = AllocatePool((size_cols+1)*sizeof(CHAR16));
if (!Line) {
console_print(L"Failed Allocation\n");
return;
}
SetMem16 (Line, size_cols * 2, BOXDRAW_HORIZONTAL);
Line[0] = BOXDRAW_DOWN_RIGHT;
Line[size_cols - 1] = BOXDRAW_DOWN_LEFT;
Line[size_cols] = L'\0';
co->SetCursorPosition(co, start_col, start_row);
co->OutputString(co, Line);
int start;
if (offset == 0)
/* middle */
start = (size_rows - lines)/2 + start_row + offset;
else if (offset < 0)
/* from bottom */
start = start_row + size_rows - lines + offset - 1;
else
/* from top */
start = start_row + offset;
for (i = start_row + 1; i < size_rows + start_row - 1; i++) {
int line = i - start;
SetMem16 (Line, size_cols*2, L' ');
Line[0] = BOXDRAW_VERTICAL;
Line[size_cols - 1] = BOXDRAW_VERTICAL;
Line[size_cols] = L'\0';
if (line >= 0 && line < lines) {
CHAR16 *s = str_arr[line];
int len = StrLen(s);
int col = (size_cols - 2 - len)/2;
if (col < 0)
col = 0;
CopyMem(Line + col + 1, s, min(len, size_cols - 2)*2);
}
if (line >= 0 && line == highlight)
co->SetAttribute(co, EFI_LIGHTGRAY |
EFI_BACKGROUND_BLACK);
co->SetCursorPosition(co, start_col, i);
co->OutputString(co, Line);
if (line >= 0 && line == highlight)
co->SetAttribute(co, EFI_LIGHTGRAY |
EFI_BACKGROUND_BLUE);
}
SetMem16 (Line, size_cols * 2, BOXDRAW_HORIZONTAL);
Line[0] = BOXDRAW_UP_RIGHT;
Line[size_cols - 1] = BOXDRAW_UP_LEFT;
Line[size_cols] = L'\0';
co->SetCursorPosition(co, start_col, i);
co->OutputString(co, Line);
FreePool (Line);
}
void
console_print_box(CHAR16 *str_arr[], int highlight)
{
SIMPLE_TEXT_OUTPUT_MODE SavedConsoleMode;
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
EFI_INPUT_KEY key;
if (!console_text_mode)
setup_console(1);
CopyMem(&SavedConsoleMode, co->Mode, sizeof(SavedConsoleMode));
co->EnableCursor(co, FALSE);
co->SetAttribute(co, EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE);
console_print_box_at(str_arr, highlight, 0, 0, -1, -1, 0,
count_lines(str_arr));
console_get_keystroke(&key);
co->EnableCursor(co, SavedConsoleMode.CursorVisible);
co->SetCursorPosition(co, SavedConsoleMode.CursorColumn,
SavedConsoleMode.CursorRow);
co->SetAttribute(co, SavedConsoleMode.Attribute);
}
int
console_select(CHAR16 *title[], CHAR16* selectors[], unsigned int start)
{
SIMPLE_TEXT_OUTPUT_MODE SavedConsoleMode;
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
EFI_INPUT_KEY k;
EFI_STATUS efi_status;
int selector;
unsigned int selector_lines = count_lines(selectors);
int selector_max_cols = 0;
unsigned int i;
int offs_col, offs_row, size_cols, size_rows, lines;
unsigned int selector_offset;
UINTN cols, rows;
if (!console_text_mode)
setup_console(1);
co->QueryMode(co, co->Mode->Mode, &cols, &rows);
for (i = 0; i < selector_lines; i++) {
int len = StrLen(selectors[i]);
if (len > selector_max_cols)
selector_max_cols = len;
}
if (start >= selector_lines)
start = selector_lines - 1;
offs_col = - selector_max_cols - 4;
size_cols = selector_max_cols + 4;
if (selector_lines > rows - 10) {
int title_lines = count_lines(title);
offs_row = title_lines + 1;
size_rows = rows - 3 - title_lines;
lines = size_rows - 2;
} else {
offs_row = - selector_lines - 4;
size_rows = selector_lines + 2;
lines = selector_lines;
}
if (start > (unsigned)lines) {
selector = lines;
selector_offset = start - lines;
} else {
selector = start;
selector_offset = 0;
}
CopyMem(&SavedConsoleMode, co->Mode, sizeof(SavedConsoleMode));
co->EnableCursor(co, FALSE);
co->SetAttribute(co, EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE);
console_print_box_at(title, -1, 0, 0, -1, -1, 1, count_lines(title));
console_print_box_at(selectors, selector, offs_col, offs_row,
size_cols, size_rows, 0, lines);
do {
efi_status = console_get_keystroke(&k);
if (EFI_ERROR (efi_status)) {
console_print(L"Failed to read the keystroke: %r",
efi_status);
selector = -1;
break;
}
if (k.ScanCode == SCAN_ESC) {
selector = -1;
break;
}
if (k.ScanCode == SCAN_UP) {
if (selector > 0)
selector--;
else if (selector_offset > 0)
selector_offset--;
} else if (k.ScanCode == SCAN_DOWN) {
if (selector < lines - 1)
selector++;
else if (selector_offset < (selector_lines - lines))
selector_offset++;
}
console_print_box_at(&selectors[selector_offset], selector,
offs_col, offs_row,
size_cols, size_rows, 0, lines);
} while (!(k.ScanCode == SCAN_NULL
&& k.UnicodeChar == CHAR_CARRIAGE_RETURN));
co->EnableCursor(co, SavedConsoleMode.CursorVisible);
co->SetCursorPosition(co, SavedConsoleMode.CursorColumn,
SavedConsoleMode.CursorRow);
co->SetAttribute(co, SavedConsoleMode.Attribute);
if (selector < 0)
/* ESC pressed */
return selector;
return selector + selector_offset;
}
int
console_yes_no(CHAR16 *str_arr[])
{
CHAR16 *yes_no[] = { L"No", L"Yes", NULL };
return console_select(str_arr, yes_no, 0);
}
void
console_alertbox(CHAR16 **title)
{
CHAR16 *okay[] = { L"OK", NULL };
console_select(title, okay, 0);
}
void
console_errorbox(CHAR16 *err)
{
CHAR16 **err_arr = (CHAR16 *[]){
L"ERROR",
L"",
0,
0,
};
err_arr[2] = err;
console_alertbox(err_arr);
}
void
console_notify(CHAR16 *string)
{
CHAR16 **str_arr = (CHAR16 *[]){
0,
0,
};
str_arr[0] = string;
console_alertbox(str_arr);
}
void
console_save_and_set_mode(SIMPLE_TEXT_OUTPUT_MODE * SavedMode)
{
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
if (!SavedMode) {
console_print(L"Invalid parameter: SavedMode\n");
return;
}
CopyMem(SavedMode, co->Mode, sizeof(SIMPLE_TEXT_OUTPUT_MODE));
co->EnableCursor(co, FALSE);
co->SetAttribute(co, EFI_LIGHTGRAY | EFI_BACKGROUND_BLUE);
}
void
console_restore_mode(SIMPLE_TEXT_OUTPUT_MODE * SavedMode)
{
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
co->EnableCursor(co, SavedMode->CursorVisible);
co->SetCursorPosition(co, SavedMode->CursorColumn,
SavedMode->CursorRow);
co->SetAttribute(co, SavedMode->Attribute);
}
int
console_countdown(CHAR16* title, const CHAR16* message, int timeout)
{
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
SIMPLE_INPUT_INTERFACE *ci = ST->ConIn;
SIMPLE_TEXT_OUTPUT_MODE SavedMode;
EFI_INPUT_KEY key;
EFI_STATUS efi_status;
UINTN cols, rows;
CHAR16 *titles[2];
int wait = 10000000;
console_save_and_set_mode(&SavedMode);
titles[0] = title;
titles[1] = NULL;
console_print_box_at(titles, -1, 0, 0, -1, -1, 1, 1);
co->QueryMode(co, co->Mode->Mode, &cols, &rows);
console_print_at((cols - StrLen(message)) / 2, rows / 2, message);
while (1) {
if (timeout > 1)
console_print_at(2, rows - 3,
L"Booting in %d seconds ",
timeout);
else if (timeout)
console_print_at(2, rows - 3,
L"Booting in %d second ",
timeout);
efi_status = WaitForSingleEvent(ci->WaitForKey, wait);
if (efi_status != EFI_TIMEOUT) {
/* Clear the key in the queue */
ci->ReadKeyStroke(ci, &key);
break;
}
timeout--;
if (!timeout)
break;
}
console_restore_mode(&SavedMode);
return timeout;
}
#define HORIZONTAL_MAX_OK 1920
#define VERTICAL_MAX_OK 1080
#define COLUMNS_MAX_OK 200
#define ROWS_MAX_OK 100
void
console_mode_handle(VOID)
{
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
EFI_GRAPHICS_OUTPUT_PROTOCOL *gop;
EFI_GUID gop_guid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
UINTN mode_set;
UINTN rows = 0, columns = 0;
EFI_STATUS efi_status = EFI_SUCCESS;
efi_status = gBS->LocateProtocol(&gop_guid, NULL, (void **)&gop);
if (EFI_ERROR(efi_status)) {
console_error(L"Locate graphic output protocol fail", efi_status);
return;
}
Info = gop->Mode->Info;
/*
* Start verifying if we are in a resolution larger than Full HD
* (1920x1080). If we're not, assume we're in a good mode and do not
* try to change it.
*/
if (Info->HorizontalResolution <= HORIZONTAL_MAX_OK &&
Info->VerticalResolution <= VERTICAL_MAX_OK) {
/* keep original mode and return */
return;
}
efi_status = co->QueryMode(co, co->Mode->Mode, &columns, &rows);
if (EFI_ERROR(efi_status)) {
console_error(L"Console query mode fail", efi_status);
return;
}
/*
* Verify current console output to check if the character columns and
* rows in a good mode.
*/
if (columns <= COLUMNS_MAX_OK && rows <= ROWS_MAX_OK) {
/* keep original mode and return */
return;
}
if (!console_text_mode)
setup_console(1);
co->Reset(co, TRUE);
/*
* If we reached here, then we have a high resolution screen and the
* text too small. Try to switch to a better mode. Mode number 2 is
* first non standard mode, which is provided by the device
* manufacturer, so it should be a good mode.
*/
if (co->Mode->MaxMode > 2)
mode_set = 2;
else
mode_set = 0;
efi_status = co->SetMode(co, mode_set);
if (EFI_ERROR(efi_status) && mode_set != 0) {
/*
* Set to 0 mode which is required that all output devices
* support at least 80x25 text mode.
*/
mode_set = 0;
efi_status = co->SetMode(co, mode_set);
}
co->ClearScreen(co);
if (EFI_ERROR(efi_status)) {
console_error(L"Console set mode fail", efi_status);
}
return;
}
/* Copy of gnu-efi-3.0 with the added secure boot strings */
static struct {
EFI_STATUS Code;
WCHAR *Desc;
} error_table[] = {
{ EFI_SUCCESS, L"Success"},
{ EFI_LOAD_ERROR, L"Load Error"},
{ EFI_INVALID_PARAMETER, L"Invalid Parameter"},
{ EFI_UNSUPPORTED, L"Unsupported"},
{ EFI_BAD_BUFFER_SIZE, L"Bad Buffer Size"},
{ EFI_BUFFER_TOO_SMALL, L"Buffer Too Small"},
{ EFI_NOT_READY, L"Not Ready"},
{ EFI_DEVICE_ERROR, L"Device Error"},
{ EFI_WRITE_PROTECTED, L"Write Protected"},
{ EFI_OUT_OF_RESOURCES, L"Out of Resources"},
{ EFI_VOLUME_CORRUPTED, L"Volume Corrupt"},
{ EFI_VOLUME_FULL, L"Volume Full"},
{ EFI_NO_MEDIA, L"No Media"},
{ EFI_MEDIA_CHANGED, L"Media changed"},
{ EFI_NOT_FOUND, L"Not Found"},
{ EFI_ACCESS_DENIED, L"Access Denied"},
{ EFI_NO_RESPONSE, L"No Response"},
{ EFI_NO_MAPPING, L"No mapping"},
{ EFI_TIMEOUT, L"Time out"},
{ EFI_NOT_STARTED, L"Not started"},
{ EFI_ALREADY_STARTED, L"Already started"},
{ EFI_ABORTED, L"Aborted"},
{ EFI_ICMP_ERROR, L"ICMP Error"},
{ EFI_TFTP_ERROR, L"TFTP Error"},
{ EFI_PROTOCOL_ERROR, L"Protocol Error"},
{ EFI_INCOMPATIBLE_VERSION, L"Incompatible Version"},
{ EFI_SECURITY_VIOLATION, L"Security Violation"},
// warnings
{ EFI_WARN_UNKNOWN_GLYPH, L"Warning Unknown Glyph"},
{ EFI_WARN_DELETE_FAILURE, L"Warning Delete Failure"},
{ EFI_WARN_WRITE_FAILURE, L"Warning Write Failure"},
{ EFI_WARN_BUFFER_TOO_SMALL, L"Warning Buffer Too Small"},
{ 0, NULL}
} ;
static CHAR16 *
err_string (
IN EFI_STATUS efi_status
)
{
UINTN Index;
for (Index = 0; error_table[Index].Desc; Index +=1) {
if (error_table[Index].Code == efi_status) {
return error_table[Index].Desc;
}
}
return L"";
}
void
console_error(CHAR16 *err, EFI_STATUS efi_status)
{
CHAR16 **err_arr = (CHAR16 *[]){
L"ERROR",
L"",
0,
0,
};
CHAR16 str[512];
SPrint(str, sizeof(str), L"%s: (0x%x) %s", err, efi_status,
err_string(efi_status));
err_arr[2] = str;
console_alertbox(err_arr);
}
void
console_reset(void)
{
SIMPLE_TEXT_OUTPUT_INTERFACE *co = ST->ConOut;
if (!console_text_mode)
setup_console(1);
co->Reset(co, TRUE);
/* set mode 0 - required to be 80x25 */
co->SetMode(co, 0);
co->ClearScreen(co);
}
UINT32 verbose = 0;
VOID
setup_verbosity(VOID)
{
EFI_STATUS efi_status;
UINT8 *verbose_check_ptr = NULL;
UINTN verbose_check_size;
verbose_check_size = sizeof(verbose);
efi_status = get_variable(L"SHIM_VERBOSE", &verbose_check_ptr,
&verbose_check_size, SHIM_LOCK_GUID);
if (!EFI_ERROR(efi_status)) {
verbose = *(__typeof__(verbose) *)verbose_check_ptr;
verbose &= (1ULL << (8 * verbose_check_size)) - 1ULL;
FreePool(verbose_check_ptr);
}
setup_console(-1);
}
VOID
msleep(unsigned long msecs)
{
gBS->Stall(msecs);
}
/* This is used in various things to determine if we should print to the
* console */
UINT8 in_protocol = 0;
| 22.836941 | 72 | 0.672691 |
a57a4f0f772c93c93f42b86db4904ad1326cd4db | 16,929 | c | C | example/ofp_vs/main.c | mfhw/ofp | 064dba8b3da7e4a1ad9b639a581c7423ed1b7490 | [
"BSD-3-Clause"
] | null | null | null | example/ofp_vs/main.c | mfhw/ofp | 064dba8b3da7e4a1ad9b639a581c7423ed1b7490 | [
"BSD-3-Clause"
] | null | null | null | example/ofp_vs/main.c | mfhw/ofp | 064dba8b3da7e4a1ad9b639a581c7423ed1b7490 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016, lvsgate@163.com
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <getopt.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include "ofp.h"
#include "ofp_vs.h"
#define MAX_WORKERS 32
/**
* Parsed command line application arguments
*/
typedef struct {
int core_count;
int if_count; /**< Number of interfaces to be used */
char **if_names; /**< Array of pointers to interface names */
char *conf_file;
int inner_port;
int outer_port;
} appl_args_t;
static appl_args_t appl_params;
/* helper funcs */
static void parse_args(int argc, char *argv[], appl_args_t *appl_args);
static void print_info(char *progname, appl_args_t *appl_args);
static void usage(char *progname);
ofp_init_global_t app_init_params; /**< global OFP init parms */
/** Get rid of path in filename - only for unix-type paths using '/' */
#define NO_PATH(file_name) (strrchr((file_name), '/') ? \
strrchr((file_name), '/') + 1 : (file_name))
static unsigned int ofp_vs_num_workers;
odp_cpumask_t ofp_vs_worker_cpumask;
unsigned int ofp_vs_worker_count(void)
{
return ofp_vs_num_workers;
}
int ofp_vs_outer_port(void)
{
return appl_params.outer_port;
}
int ofp_vs_inner_port(void)
{
return appl_params.inner_port;
}
struct pktin_table_s {
int num_in_queue;
odp_pktin_queue_t in_queue[OFP_PKTIN_QUEUE_MAX];
} pktin_table[OFP_FP_INTERFACE_MAX];
static odp_pktin_queue_t if_iq_bind_to_core[OFP_FP_INTERFACE_MAX][OFP_MAX_NUM_CPU];
static void signal_handler(int signal)
{
const char *signal_name;
switch (signal) {
case SIGILL:
signal_name = "SIGILL"; break;
case SIGFPE:
signal_name = "SIGFPE"; break;
case SIGSEGV:
signal_name = "SIGSEGV"; break;
case SIGTERM:
signal_name = "SIGTERM"; break;
case SIGINT:
signal_name = "SIGINT"; break;
case SIGBUS:
signal_name = "SIGBUS"; break;
default:
signal_name = "UNKNOWN"; break;
}
ofp_stop_processing();
fprintf(stderr, "Recv signal %u (%s) exiting.\n", signal, signal_name);
}
static void direct_recv(const appl_args_t *appl_params)
{
int i;
int port;
int cpu = odp_cpu_id();
ofp_pkt_processing_func pkt_func = ofp_eth_vlan_processing;
for (port = 0; port < appl_params->if_count; port++) {
int pkts;
odp_pktin_queue_t in_queue;
odp_packet_t pkt_tbl[OFP_PKT_RX_BURST_SIZE];
in_queue = if_iq_bind_to_core[port][cpu];
pkts = odp_pktin_recv(in_queue, pkt_tbl,
OFP_PKT_RX_BURST_SIZE);
if (odp_unlikely(pkts) <= 0)
continue;
for (i = 0; i < pkts; i++) {
odp_packet_t pkt = pkt_tbl[i];
#if 0
if (odp_unlikely(odp_packet_has_error(pkt))) {
OFP_DBG("Dropping packet with error");
odp_packet_free(pkt);
continue;
}
#endif
ofp_packet_input(pkt, ODP_QUEUE_INVALID, pkt_func);
}
}
}
static void *event_dispatcher(void *arg)
{
odp_event_t ev;
odp_packet_t pkt;
odp_queue_t in_queue;
odp_event_t events[OFP_EVT_RX_BURST_SIZE];
int event_idx = 0;
int event_cnt = 0;
uint64_t loop_cnt = 0;
//ofp_pkt_processing_func pkt_func = (ofp_pkt_processing_func)arg;
ofp_pkt_processing_func pkt_func = ofp_eth_vlan_processing;
odp_bool_t *is_running = NULL;
//int cpuid = odp_cpu_id();
//odp_queue_t time_queue_cpu;
const appl_args_t *appl_params = (appl_args_t *)arg;
if (ofp_init_local()) {
OFP_ERR("ofp_init_local failed");
return NULL;
}
is_running = ofp_get_processing_state();
if (is_running == NULL) {
OFP_ERR("ofp_get_processing_state failed");
ofp_term_local();
return NULL;
}
//time_queue_cpu = ofp_timer_queue_cpu(cpuid);
/* PER CORE DISPATCHER */
while (*is_running) {
if (odp_likely(app_init_params.burst_recv_mode)) {
direct_recv(appl_params);
} else {
event_cnt = odp_schedule_multi(&in_queue,
ODP_SCHED_WAIT,
events, OFP_EVT_RX_BURST_SIZE);
for (event_idx = 0; event_idx < event_cnt; event_idx++) {
ev = events[event_idx];
if (ev == ODP_EVENT_INVALID)
continue;
if (odp_event_type(ev) == ODP_EVENT_TIMEOUT) {
ofp_timer_handle(ev);
continue;
}
if (odp_event_type(ev) == ODP_EVENT_PACKET) {
pkt = odp_packet_from_event(ev);
#if 0
if (odp_unlikely(odp_packet_has_error(pkt))) {
OFP_DBG("Dropping packet with error");
odp_packet_free(pkt);
continue;
}
#endif
ofp_packet_input(pkt, in_queue, pkt_func);
continue;
}
OFP_ERR("Unexpected event type: %u", odp_event_type(ev));
/* Free events by type */
if (odp_event_type(ev) == ODP_EVENT_BUFFER) {
odp_buffer_free(odp_buffer_from_event(ev));
continue;
}
if (odp_event_type(ev) == ODP_EVENT_CRYPTO_COMPL) {
odp_crypto_compl_free(
odp_crypto_compl_from_event(ev));
continue;
}
}
}
ofp_send_pending_pkt();
/* per cpu ofp timer schedule */
/*
event_cnt = odp_queue_deq_multi(time_queue_cpu,
events,
OFP_EVT_RX_BURST_SIZE);
for (event_idx = 0; event_idx < event_cnt; event_idx++) {
ev = events[event_idx];
if (odp_event_type(ev) == ODP_EVENT_TIMEOUT) {
ofp_timer_handle(ev);
continue;
} else {
OFP_ERR("Unexpected event type: %u",
odp_event_type(ev));
}
}
*/
if ((loop_cnt++)%1024) {
/* dpdk timer schedule */
rte_timer_manage();
}
}
if (ofp_term_local())
OFP_ERR("ofp_term_local failed");
return NULL;
}
static void ofp_pktin_queue_param_init(odp_pktin_queue_param_t *param,
odp_pktin_mode_t in_mode, uint16_t rx_queues)
{
odp_queue_param_t *queue_param;
odp_pktin_queue_param_init(param);
param->num_queues = rx_queues;
queue_param = ¶m->queue_param;
odp_queue_param_init(queue_param);
if (in_mode == ODP_PKTIN_MODE_SCHED) {
queue_param->type = ODP_QUEUE_TYPE_SCHED;
queue_param->enq_mode = ODP_QUEUE_OP_MT;
queue_param->deq_mode = ODP_QUEUE_OP_MT;
queue_param->context = NULL;
queue_param->sched.prio = ODP_SCHED_PRIO_DEFAULT;
queue_param->sched.sync = ODP_SCHED_SYNC_ATOMIC;
queue_param->sched.group = ODP_SCHED_GROUP_ALL;
} else if (in_mode == ODP_PKTIN_MODE_QUEUE) {
queue_param->type = ODP_QUEUE_TYPE_PLAIN;
queue_param->enq_mode = ODP_QUEUE_OP_MT;
queue_param->deq_mode = ODP_QUEUE_OP_MT;
queue_param->context = NULL;
}
if (in_mode == ODP_PKTIN_MODE_DIRECT) {
param->op_mode = ODP_PKTIO_OP_MT_UNSAFE;
}
}
static void ofp_pktout_queue_param_init(
odp_pktout_queue_param_t *param,
uint16_t tx_queues)
{
odp_pktout_queue_param_init(param);
param->op_mode = ODP_PKTIO_OP_MT;
param->num_queues = tx_queues;
}
static int create_ifnet_and_bind_queues(odp_instance_t instance,
appl_args_t *params,
const odp_cpumask_t *cpumask)
{
int i;
unsigned cpu_count = odp_cpumask_count(cpumask);
for (i = 0; i < params->if_count; i++) {
int cpu;
int rx_q;
odp_pktio_param_t pktio_param;
odp_pktin_queue_param_t pktin_param;
odp_pktout_queue_param_t pktout_param;
odp_pktio_t pktio;
odp_pktio_config_t pktio_config;
unsigned short port_mask = 0x0;
unsigned int laddr_mask = 0x0;
if (i == params->outer_port)
port_mask = __roundup_pow_of_two(cpu_count) - 1;
if (i == params->inner_port)
laddr_mask = 0xffffffff;
odp_pktio_param_init(&pktio_param);
pktio_param.in_mode = ODP_PKTIN_MODE_DIRECT;
pktio_param.out_mode = ODP_PKTOUT_MODE_DIRECT;
ofp_pktin_queue_param_init(
&pktin_param,
pktio_param.in_mode,
cpu_count);
ofp_pktout_queue_param_init(&pktout_param, cpu_count);
/* Configure fdir for FULLNAT local address */
odp_pktio_config_init(&pktio_config);
pktio_config.fdir_conf.fdir_mode = RTE_FDIR_MODE_PERFECT;
pktio_config.fdir_conf.src_ipv4_mask =
rte_cpu_to_be_32(0x00000000);
pktio_config.fdir_conf.dst_ipv4_mask =
rte_cpu_to_be_32(laddr_mask);
pktio_config.fdir_conf.src_port_mask =
rte_cpu_to_be_16(0x0000);
pktio_config.fdir_conf.dst_port_mask =
rte_cpu_to_be_16(port_mask);
if (ofp_ifnet_create2(instance, params->if_names[i],
&pktio_param,
&pktin_param,
&pktout_param,
&pktio_config) < 0) {
OFP_ERR("Failed to init interface %s",
params->if_names[i]);
return -1;
}
pktio = odp_pktio_lookup(params->if_names[i]);
if (pktio == ODP_PKTIO_INVALID) {
OFP_ERR("Failed locate pktio %s",
params->if_names[i]);
return -1;
}
pktin_table[i].num_in_queue = odp_pktin_queue(pktio,
pktin_table[i].in_queue, OFP_PKTIN_QUEUE_MAX);
if (pktin_table[i].num_in_queue < 0) {
OFP_ERR("Failed get input queues for %s",
params->if_names[i]);
return -1;
}
cpu = odp_cpumask_first(cpumask);
if (cpu < 0)
return -1;
for (rx_q = 0; rx_q < pktin_table[i].num_in_queue; rx_q++) {
if (cpu < 0)
cpu = odp_cpumask_first(cpumask);
if_iq_bind_to_core[i][cpu] =
pktin_table[i].in_queue[rx_q];
OFP_INFO("if %d rx_q %d bind to cpu %d",
i, rx_q, cpu);
cpu = odp_cpumask_next(cpumask, cpu);
}
}
return 0;
}
/** main() Application entry point
*
* @param argc int
* @param argv[] char*
* @return int
*
*/
#include <sys/time.h>
#include <sys/resource.h>
int main(int argc, char *argv[])
{
odph_linux_pthread_t thread_tbl[MAX_WORKERS];
int core_count, num_workers;
odp_cpumask_t cpumask;
char cpumaskstr[64];
odph_linux_thr_params_t thr_params;
odp_instance_t instance;
struct sigaction signal_action;
struct rlimit rlp;
memset(&signal_action, 0, sizeof(signal_action));
signal_action.sa_handler = signal_handler;
sigfillset(&signal_action.sa_mask);
//sigaction(SIGILL, &signal_action, NULL);
//sigaction(SIGFPE, &signal_action, NULL);
//sigaction(SIGSEGV, &signal_action, NULL);
sigaction(SIGTERM, &signal_action, NULL);
sigaction(SIGINT, &signal_action, NULL);
//sigaction(SIGBUS, &signal_action, NULL);
signal(SIGPIPE, SIG_IGN);
getrlimit(RLIMIT_CORE, &rlp);
printf("RLIMIT_CORE: %ld/%ld\n", rlp.rlim_cur, rlp.rlim_max);
rlp.rlim_cur = 200000000;
printf("Setting to max: %d\n", setrlimit(RLIMIT_CORE, &rlp));
/* Parse and store the application arguments */
parse_args(argc, argv, &appl_params);
/* Print both system and application information */
print_info(NO_PATH(argv[0]), &appl_params);
if (odp_init_global(&instance, NULL, NULL)) {
OFP_ERR("Error: ODP global init failed.\n");
exit(EXIT_FAILURE);
}
if (odp_init_local(instance, ODP_THREAD_CONTROL)) {
OFP_ERR("Error: ODP local init failed.\n");
exit(EXIT_FAILURE);
}
core_count = odp_cpu_count();
num_workers = core_count;
if (appl_params.core_count)
num_workers = appl_params.core_count;
if (num_workers > MAX_WORKERS)
num_workers = MAX_WORKERS;
num_workers = odp_cpumask_default_worker(&cpumask, num_workers);
odp_cpumask_to_str(&cpumask, cpumaskstr, sizeof(cpumaskstr));
ofp_vs_num_workers = num_workers;
odp_cpumask_copy(&ofp_vs_worker_cpumask, &cpumask);
printf("odp_cpu_count : %i\n", core_count);
printf("Num worker threads: %i\n", num_workers);
printf("first CPU: %i\n", odp_cpumask_first(&cpumask));
printf("cpu mask: %s\n", cpumaskstr);
/*
* By default core #0 runs Linux kernel background tasks.
* Start mapping thread from core #1
*/
memset(&app_init_params, 0, sizeof(app_init_params));
app_init_params.linux_core_id = 0;
app_init_params.burst_recv_mode = 1;
app_init_params.pkt_hook[OFP_HOOK_PREROUTING] = ofp_vs_in;
app_init_params.pkt_hook[OFP_HOOK_FWD_IPv4] = ofp_vs_out;
if (!app_init_params.burst_recv_mode) {
app_init_params.if_count = appl_params.if_count;
app_init_params.if_names = appl_params.if_names;
}
if (ofp_init_global(instance, &app_init_params)) {
OFP_ERR("Error: OFP global init failed.\n");
exit(EXIT_FAILURE);
}
if (app_init_params.burst_recv_mode &&
create_ifnet_and_bind_queues(instance, &appl_params, &cpumask) != 0) {
OFP_ERR("create_ifnet_and_bind_queues failed\n");
exit(EXIT_FAILURE);
}
memset(thread_tbl, 0, sizeof(thread_tbl));
/* Start dataplane dispatcher worker threads */
//thr_params.start = default_event_dispatcher;
thr_params.start = event_dispatcher;
//thr_params.arg = ofp_eth_vlan_processing;
thr_params.arg = &appl_params;
thr_params.thr_type = ODP_THREAD_WORKER;
thr_params.instance = instance;
odph_linux_pthread_create(thread_tbl,
&cpumask,
&thr_params);
ofp_vs_cli_cmd_init();
if (ofp_vs_init(instance, &app_init_params) < 0) {
ofp_stop_processing();
OFP_ERR("ofp_vs_init() failed\n");
}
/* other app code here.*/
/* Start CLI */
ofp_start_cli_thread(instance, app_init_params.linux_core_id,
appl_params.conf_file);
rte_timer_subsystem_init();
odph_linux_pthread_join(thread_tbl, num_workers);
printf("End Worker\n");
ofp_vs_finish();
printf("End Main()\n");
return 0;
}
/**
* Parse and store the command line arguments
*
* @param argc argument count
* @param argv[] argument vector
* @param appl_args Store application arguments here
*/
static void parse_args(int argc, char *argv[], appl_args_t *appl_args)
{
int opt;
int long_index;
char *names, *str, *token, *save;
size_t len;
int i;
static struct option longopts[] = {
{"count", required_argument, NULL, 'c'},
{"interface", required_argument, NULL, 'i'}, /* return 'i' */
{"outer interface", required_argument, NULL, 'o'}, /* return 'i' */
{"inter interface", required_argument, NULL, 'p'}, /* return 'i' */
{"help", no_argument, NULL, 'h'}, /* return 'h' */
{"configuration file", required_argument,
NULL, 'f'},/* return 'f' */
{NULL, 0, NULL, 0}
};
memset(appl_args, 0, sizeof(*appl_args));
appl_params.inner_port = -1;
appl_params.outer_port = -1;
while (1) {
opt = getopt_long(argc, argv, "+c:i:o:p:hf:",
longopts, &long_index);
if (opt == -1)
break; /* No more options */
switch (opt) {
case 'c':
appl_args->core_count = atoi(optarg);
break;
/* parse packet-io interface names */
case 'i':
len = strlen(optarg);
if (len == 0) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
len += 1; /* add room for '\0' */
names = malloc(len);
if (names == NULL) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
/* count the number of tokens separated by ',' */
strcpy(names, optarg);
for (str = names, i = 0;; str = NULL, i++) {
token = strtok_r(str, ",", &save);
if (token == NULL)
break;
}
appl_args->if_count = i;
if (appl_args->if_count == 0) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
/* allocate storage for the if names */
appl_args->if_names =
calloc(appl_args->if_count, sizeof(char *));
/* store the if names (reset names string) */
strcpy(names, optarg);
for (str = names, i = 0;; str = NULL, i++) {
token = strtok_r(str, ",", &save);
if (token == NULL)
break;
appl_args->if_names[i] = token;
}
break;
case 'h':
usage(argv[0]);
exit(EXIT_SUCCESS);
break;
case 'f':
len = strlen(optarg);
if (len == 0) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
len += 1; /* add room for '\0' */
appl_args->conf_file = malloc(len);
if (appl_args->conf_file == NULL) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
strcpy(appl_args->conf_file, optarg);
break;
case 'o':
appl_args->outer_port = atoi(optarg);
break;
case 'p':
appl_args->inner_port = atoi(optarg);
break;
default:
break;
}
}
if (appl_args->if_count == 0) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
optind = 1; /* reset 'extern optind' from the getopt lib */
}
/**
* Print system and application info
*/
static void print_info(char *progname, appl_args_t *appl_args)
{
int i;
printf("\n"
"ODP system info\n"
"---------------\n"
"ODP API version: %s\n"
"CPU model: %s\n"
"CPU freq (hz): %"PRIu64"\n"
"Cache line size: %i\n"
"Core count: %i\n"
"Outer port: %i\n"
"Inner port: %i\n"
"\n",
odp_version_api_str(), odp_cpu_model_str(),
odp_cpu_hz(), odp_sys_cache_line_size(),
odp_cpu_count(), appl_args->outer_port,
appl_args->inner_port);
printf("Running ODP appl: \"%s\"\n"
"-----------------\n"
"IF-count: %i\n"
"Using IFs: ",
progname, appl_args->if_count);
for (i = 0; i < appl_args->if_count; ++i)
printf(" %s", appl_args->if_names[i]);
printf("\n\n");
fflush(NULL);
}
/**
* Prinf usage information
*/
static void usage(char *progname)
{
printf("\n"
"Usage: %s OPTIONS\n"
" E.g. %s -i eth1,eth2,eth3\n"
"\n"
"ODPFastpath application.\n"
"\n"
"Mandatory OPTIONS:\n"
" -i, --interface Eth interfaces (comma-separated, no spaces)\n"
" -o, Outer interface to set snat fdir rules\n"
" -p, Inner interface to set fnat laddr fdir rules\n"
"\n"
"Optional OPTIONS\n"
" -c, --count <number> Core count.\n"
" -h, --help Display help and exit.\n"
"\n", NO_PATH(progname), NO_PATH(progname)
);
}
| 24.253582 | 83 | 0.679721 |
a57f14911906b4a963aecc8d9b5470d8338fc2f8 | 487 | h | C | COMSC-165/PandemicLite/Program.h | aadiego/CollegeProjects | 404dc798f152ce10c974e16a88c7f81a6fdd9156 | [
"MIT"
] | null | null | null | COMSC-165/PandemicLite/Program.h | aadiego/CollegeProjects | 404dc798f152ce10c974e16a88c7f81a6fdd9156 | [
"MIT"
] | 18 | 2018-11-30T03:49:18.000Z | 2019-05-22T01:46:45.000Z | COMSC-165/PandemicLite/Program.h | aadiego/CollegeProjects | 404dc798f152ce10c974e16a88c7f81a6fdd9156 | [
"MIT"
] | null | null | null | #pragma once
#ifndef PROGRAM_H
#define PROGRAM_H
#include <string>
#include "Game.h"
using namespace std;
// Function Prototypes
bool parseCmdLineArgs(int, char* []);
void displayHelpMessage(string&);
void displayHowToPlayMessage();
// Variables and Constants
extern Game::Options options; // Holds the game options used by the Game class constructor to build the game objects.
extern Game* CurrentGame; // Holds a pointer to the current game
#endif
| 25.631579 | 125 | 0.720739 |
9d24c344ea89f3c643b98f62819267847a1fcfb4 | 5,190 | h | C | src/adera/Machines/Rocket.h | haennes/osp-magnum | 242958d71ab34a79250b9f426d97ab4dfdfc775f | [
"MIT"
] | null | null | null | src/adera/Machines/Rocket.h | haennes/osp-magnum | 242958d71ab34a79250b9f426d97ab4dfdfc775f | [
"MIT"
] | null | null | null | src/adera/Machines/Rocket.h | haennes/osp-magnum | 242958d71ab34a79250b9f426d97ab4dfdfc775f | [
"MIT"
] | null | null | null | /**
* Open Space Program
* Copyright © 2019-2020 Open Space Program Project
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <utility>
#include <osp/Active/SysMachine.h>
#include <osp/Active/physics.h>
#include <osp/Resource/blueprints.h>
#include "adera/ShipResources.h"
namespace adera::active::machines
{
class MachineRocket;
class SysMachineRocket :
public osp::active::SysMachine<SysMachineRocket, MachineRocket>
{
public:
static inline std::string smc_name = "Rocket";
SysMachineRocket(osp::active::ActiveScene &scene);
//void update_sensor();
void update_physics(osp::active::ActiveScene& rScene);
/**
* Attach a visual exhaust plume effect to MachineRocket
*
* Searches the hierarchy under the specified MachineRocket entity and
* attaches an ACompExhaustPlume to the rocket's plume node. A graphical
* exhaust plume effect will be attached to the node by SysExhaustPlume
* when it processes the component.
* @param ent The MachineRocket entity
*/
void attach_plume_effect(osp::active::ActiveEnt ent);
/**
* Attach a MachineRocket to an entity
*
* Also attempts to attach a plume component to the appropriate child node
* @param ent The entity that owns the MachineRocket
* @return The new MachineRocket instance
*/
osp::active::Machine& instantiate(osp::active::ActiveEnt ent,
osp::PrototypeMachine config, osp::BlueprintMachine settings) override;
osp::active::Machine& get(osp::active::ActiveEnt ent) override;
private:
osp::active::UpdateOrderHandle_t m_updatePhysics;
}; // SysMachineRocket
/**
*
*/
class MachineRocket : public osp::active::Machine
{
friend SysMachineRocket;
struct ResourceInput
{
osp::DependRes<ShipResourceType> m_type;
float m_massRateFraction;
osp::active::ActiveEnt m_sourceEnt;
};
using fuel_list_t = std::vector<ResourceInput>;
struct Parameters
{
float m_maxThrust;
float m_specImpulse;
};
public:
MachineRocket(Parameters params, fuel_list_t& resources);
MachineRocket(MachineRocket &&move) noexcept;
MachineRocket& operator=(MachineRocket&& move) noexcept;
MachineRocket(MachineRocket const& copy) = delete;
MachineRocket& operator=(MachineRocket const& move) = delete;
void propagate_output(osp::active::WireOutput *output) override;
osp::active::WireInput* request_input(osp::WireInPort port) override;
osp::active::WireOutput* request_output(osp::WireOutPort port) override;
std::vector<osp::active::WireInput*> existing_inputs() override;
std::vector<osp::active::WireOutput*> existing_outputs() override;
private:
osp::active::WireInput m_wiGimbal { this, "Gimbal" };
osp::active::WireInput m_wiIgnition { this, "Ignition" };
osp::active::WireInput m_wiThrottle { this, "Throttle" };
osp::active::ActiveEnt m_rigidBody { entt::null };
fuel_list_t m_resourceLines;
Parameters m_params;
}; // MachineRocket
inline MachineRocket::MachineRocket(Parameters params, fuel_list_t& resources)
: Machine(true)
, m_params(params)
, m_resourceLines(std::move(resources))
{ }
inline MachineRocket::MachineRocket(MachineRocket&& move) noexcept
: Machine(std::move(move))
, m_wiGimbal(this, std::move(move.m_wiGimbal))
, m_wiIgnition(this, std::move(move.m_wiIgnition))
, m_wiThrottle(this, std::move(move.m_wiThrottle))
, m_rigidBody(std::move(move.m_rigidBody))
, m_params(std::move(move.m_params))
, m_resourceLines(std::move(move.m_resourceLines))
{ }
inline MachineRocket& MachineRocket::operator=(MachineRocket&& move) noexcept
{
Machine::operator=(std::move(move));
m_wiGimbal = { this, std::move(move.m_wiGimbal) };
m_wiIgnition = { this, std::move(move.m_wiIgnition) };
m_wiThrottle = { this, std::move(move.m_wiThrottle) };
m_rigidBody = std::move(move.m_rigidBody);
m_params = std::move(move.m_params);
m_resourceLines = std::move(move.m_resourceLines);
return *this;
}
} // namespace adera::active::machines
| 33.701299 | 80 | 0.718112 |
4fdc1c4d3d7ff5ea6bec02b615c766600a90ca75 | 4,492 | h | C | osprey/common/com/erirb.h | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/erirb.h | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/erirb.h | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#ifndef erirb_INCLUDED
#define erirb_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
/* ====================================================================
* ====================================================================
*
* Module: erirb.h
* $Revision$
* $Date$
* $Author$
* $Source$
*
* Revision history:
* 23-Jun-89 - Original Version
* 12-Jun-91 - Integrated from Josie
*
* Description:
*
* IR Builder error code definitions.
*
* ====================================================================
* ====================================================================
*/
#ifdef _KEEP_RCS_ID
static char *erirb_rcs_id = "$Source$ $Revision$";
#endif /* _KEEP_RCS_ID */
/* Include errors.h for the benefit of any users: */
#include "errors.h"
/* Define the initial error code to use: */
#define EC_IRB_Start (EP_IR_BUILDER)*1000
/* General irb error codes: */
#define EC_Irb_Internal EC_IRB_Start /* str */
/* irbmain error codes: */
#define EC_No_ASSIGN EC_IRB_Start+1 /* str */
/* irbmem error codes: */
#define EC_Array_OOB EC_IRB_Start+11 /* sym */
#define EC_Bad_Formal EC_IRB_Start+12 /* sym */
#define EC_Addr_Formal EC_IRB_Start+13 /* sym */
#define EC_Null_Base EC_IRB_Start+14 /* tree, tree */
#define EC_Invalid_Addr EC_IRB_Start+15 /* str */
#define EC_Var_TN EC_IRB_Start+16 /* tn, str */
#define EC_Bad_Const EC_IRB_Start+17 /* int, str */
#define EC_Mult_Defer EC_IRB_Start+18 /* sym, tree */
#define EC_Abs_Addr EC_IRB_Start+19 /* tree, tree, str */
#define EC_Load_Opnds EC_IRB_Start+20 /* int, str, str */
/* irbcall/callutil error codes: */
#define EC_Return_Style EC_IRB_Start+31 /* int, str */
#define EC_Need_Value EC_IRB_Start+32 /* str */
#define EC_Inv_Actual EC_IRB_Start+33 /* node, int */
#define EC_Mem_Actual EC_IRB_Start+34 /* int, int */
#define EC_No_Einfo EC_IRB_Start+35 /* tree */
#define EC_Not_Entry EC_IRB_Start+37 /* sym, sym */
#define EC_Flt_Varargs1 EC_IRB_Start+38 /* str */
#define EC_Flt_Varargs2 EC_IRB_Start+39 /* str */
/* irbexec error codes: */
#define EC_Agt_Uninit EC_IRB_Start+41 /* sym */
/* irbdo error codes: */
#define EC_Inv_GOTO EC_IRB_Start+51 /* int, sym */
/* irbexpr error codes: */
#define EC_Inv_Field_At EC_IRB_Start+61 /* int, int, int */
#define EC_Inv_Alloca_Size EC_IRB_Start+62 /* int64 */
#define EC_Zero_Alloca_Size EC_IRB_Start+63 /* none */
#define EC_Inv_TAS_Size EC_IRB_Start+64 /* nd, int, nd, int, str */
#define EC_TAS_Nonload EC_IRB_Start+65 /* nd, nd, tn */
/* Memory model errors: */
#define EC_Ill_TDT_Seg EC_IRB_Start+80 /* int, stab */
#define EC_Large_Temp EC_IRB_Start+81 /* int, stab */
#define EC_Ill_Stack_Base EC_IRB_Start+82 /* stab, stab */
#define EC_Huge_Frame EC_IRB_Start+83 /* int, int */
#define EC_Huge_Frame2 EC_IRB_Start+84 /* none */
#define EC_Not_Sorted EC_IRB_Start+85 /* str */
#define EC_Pop_Scope EC_IRB_Start+86 /* none */
#define EC_Ill_Frame_Seg EC_IRB_Start+87 /* int, str */
#define EC_Ill_Stack_Model EC_IRB_Start+88 /* int, str */
#define EC_Sym_Removal EC_IRB_Start+89 /* stab, str */
#define EC_Gnum_Range EC_IRB_Start+90 /* str */
#ifdef __cplusplus
}
#endif
#endif /* erirb_INCLUDED */
| 34.290076 | 73 | 0.680098 |
411731def71062f55016f0e4c20d3dfacd2903d6 | 1,160 | h | C | pj_tflite_style_transfer/ImageProcessor/StyleTransferEngine.h | bjarkirafn/play_with_tflite | ab20bcfa79f1bbcf1cb5d8e2887df6253ef0a0c0 | [
"Apache-2.0"
] | 1 | 2021-01-13T00:52:14.000Z | 2021-01-13T00:52:14.000Z | pj_tflite_style_transfer/ImageProcessor/StyleTransferEngine.h | chiminghui/play_with_tflite | 6359e7a4677ae70418f653a77e478d1fae1e3d40 | [
"Apache-2.0"
] | null | null | null | pj_tflite_style_transfer/ImageProcessor/StyleTransferEngine.h | chiminghui/play_with_tflite | 6359e7a4677ae70418f653a77e478d1fae1e3d40 | [
"Apache-2.0"
] | null | null | null | #ifndef STYLE_TRANSFER_ENGINE_
#define STYLE_TRANSFER_ENGINE_
/* for general */
#include <cstdint>
#include <cmath>
#include <string>
#include <vector>
#include <array>
#include <memory>
/* for OpenCV */
#include <opencv2/opencv.hpp>
/* for My modules */
#include "InferenceHelper.h"
class StyleTransferEngine {
public:
enum {
RET_OK = 0,
RET_ERR = -1,
};
typedef struct RESULT_ {
cv::Mat image;
double timePreProcess; // [msec]
double timeInference; // [msec]
double timePostProcess; // [msec]
RESULT_() : timePreProcess(0), timeInference(0), timePostProcess(0)
{}
} RESULT;
public:
StyleTransferEngine() {}
~StyleTransferEngine() {}
int32_t initialize(const std::string& workDir, const int32_t numThreads);
int32_t finalize(void);
int32_t invoke(const cv::Mat& originalMat, const float styleBottleneck[], const int lengthStyleBottleneck, RESULT& result);
private:
std::unique_ptr<InferenceHelper> m_inferenceHelper;
std::vector<InputTensorInfo> m_inputTensorList;
std::vector<OutputTensorInfo> m_outputTensorList;
};
#endif
| 23.2 | 125 | 0.675 |
3f908c1f9f99c96932e971d3abcc8a02587dd09f | 954 | h | C | src/ui/SDL2/shared_state.h | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 349 | 2017-11-15T22:51:00.000Z | 2022-03-21T13:43:57.000Z | src/ui/SDL2/shared_state.h | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 12 | 2018-08-28T21:38:29.000Z | 2021-12-11T16:24:36.000Z | src/ui/SDL2/shared_state.h | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 28 | 2018-06-10T07:31:13.000Z | 2022-03-21T10:54:26.000Z | #pragma once
#include <string>
#include <SDL.h>
#include "config.h"
#include "nes/cartridge/cartridge.h"
#include "nes/nes.h"
#include "nes/params.h"
class GUIModule;
struct SDL_Common {
SDL_GameController* controller = nullptr;
};
struct GUIStatus {
bool in_menu = true;
uint avg_fps = 60;
};
struct SharedState {
const std::map<std::string, GUIModule*>& modules;
GUIStatus& status;
SDL_Common& sdl;
Config& config;
NES_Params& nes_params;
NES& nes;
Cartridge* cart = nullptr;
const Serializable::Chunk* savestate [4] = { nullptr };
std::string current_rom_file;
int load_rom(const char* rompath);
int unload_rom();
SharedState(
const std::map<std::string, GUIModule*>& modules,
GUIStatus& status,
SDL_Common& sdl,
Config& config,
NES_Params& nes_params,
NES& nes
)
: modules(modules)
, status(status)
, sdl(sdl)
, config(config)
, nes_params(nes_params)
, nes(nes)
{}
};
| 17.345455 | 57 | 0.672956 |
8b6b4d8ebf029dd70d3ce7184fa55338bd2bc836 | 3,291 | h | C | Code/Framework/AzToolsFramework/AzToolsFramework/UI/Notifications/ToastBus.h | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Framework/AzToolsFramework/AzToolsFramework/UI/Notifications/ToastBus.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Framework/AzToolsFramework/AzToolsFramework/UI/Notifications/ToastBus.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#if !defined(Q_MOC_RUN)
#include <AzCore/EBus/EBus.h>
#include <AzCore/Component/EntityId.h>
#include <AzQtComponents/Components/ToastNotificationConfiguration.h>
#include <QPoint>
#endif
namespace AzToolsFramework
{
typedef AZ::EntityId ToastId;
/**
* An EBus for receiving notifications when a user interacts with or dismisses
* a toast notification.
*/
class ToastNotifications
: public AZ::EBusTraits
{
public:
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple;
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById;
using BusIdType = ToastId;
virtual void OnToastInteraction() {}
virtual void OnToastDismissed() {}
};
using ToastNotificationBus = AZ::EBus<ToastNotifications>;
typedef AZ::u32 ToastRequestBusId;
/**
* An EBus used to hide or show toast notifications. Generally, these request are handled by a
* ToastNotificationsView that has been created with a specific ToastRequestBusId
* e.g. AZ_CRC("ExampleToastNotificationView")
*/
class ToastRequests
: public AZ::EBusTraits
{
public:
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple;
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById;
using BusIdType = ToastRequestBusId; // bus is addressed by CRC of the view name
/**
* Hide a toast notification widget.
*
* @param toastId The toast notification's ToastId
*/
virtual void HideToastNotification(const ToastId& toastId) = 0;
/**
* Show a toast notification with the specified toast configuration. When handled by a ToastNotificationsView,
* notifications are queued and presented to the user in sequence.
*
* @param toastConfiguration The toast configuration
* @return a ToastId
*/
virtual ToastId ShowToastNotification(const AzQtComponents::ToastConfiguration& toastConfiguration) = 0;
/**
* Show a toast notification with the specified toast configuration at the current moust cursor location.
*
* @param toastConfiguration The toast configuration
* @return a ToastId
*/
virtual ToastId ShowToastAtCursor(const AzQtComponents::ToastConfiguration& toastConfiguration) = 0;
/**
* Show a toast notification with the specified toast configuration at the specified location.
*
* @param screenPosition The screen position
* @param anchorPoint The anchorPoint for the toast notification widget
* @param toastConfiguration The toast configuration
* @return a ToastId
*/
virtual ToastId ShowToastAtPoint(const QPoint& screenPosition, const QPointF& anchorPoint, const AzQtComponents::ToastConfiguration&) = 0;
};
using ToastRequestBus = AZ::EBus<ToastRequests>;
}
| 35.771739 | 146 | 0.68186 |
6a5a00b1838d7b0b99b2db3a7ec9f181ee1190aa | 560 | h | C | MapillarySDK/MapillarySDK/MAPLoginManagerDelegate.h | mapillary/mapillary-sdk-ios | 22090ff19902960f2bf2a1143257e4a152391d5f | [
"MIT"
] | 15 | 2017-11-01T13:00:39.000Z | 2021-05-21T20:25:12.000Z | MapillarySDK/MapillarySDK/MAPLoginManagerDelegate.h | mapillary/mapillary-sdk-ios | 22090ff19902960f2bf2a1143257e4a152391d5f | [
"MIT"
] | 2 | 2018-12-04T12:31:53.000Z | 2020-12-07T18:20:36.000Z | MapillarySDK/MapillarySDK/MAPLoginManagerDelegate.h | mapillary/mapillary-sdk-ios | 22090ff19902960f2bf2a1143257e4a152391d5f | [
"MIT"
] | 3 | 2019-02-26T18:34:43.000Z | 2021-06-11T13:49:22.000Z | //
// MAPLoginManagerDelegate.h
// MapillarySDK
//
// Created by martensson on 2020-08-06.
//
#import <Foundation/Foundation.h>
@class MAPLoginManager;
@protocol MAPLoginManagerDelegate <NSObject>
@optional
/**
Delegate method for when the user was logged out.
@param loginManager The login manager object that is .
@param user The user that was logged out.
@param reason A string that is used to explain why the user was signed out.
*/
- (void)userWasSignedOut:(MAPLoginManager*)loginManager user:(MAPUser*)user reason:(NSString*)reason;
@end
| 21.538462 | 101 | 0.748214 |
ac07196a0fa4c3708413ae0ad2385454ba8de2f0 | 5,046 | h | C | jni/Box2D/binding/dynamics/joints/com_wiyun_engine_box2d_dynamics_joints_WheelJoint.h | zchajax/WiEngine | ea2fa297f00aa5367bb5b819d6714ac84a8a8e25 | [
"MIT"
] | 39 | 2015-01-23T10:01:31.000Z | 2021-06-10T03:01:18.000Z | jni/Box2D/binding/dynamics/joints/com_wiyun_engine_box2d_dynamics_joints_WheelJoint.h | luckypen/WiEngine | 7e80641fe15a77a2fc43db90f15dad6aa2c2860a | [
"MIT"
] | 1 | 2015-04-15T08:07:47.000Z | 2015-04-15T08:07:47.000Z | jni/Box2D/binding/dynamics/joints/com_wiyun_engine_box2d_dynamics_joints_WheelJoint.h | luckypen/WiEngine | 7e80641fe15a77a2fc43db90f15dad6aa2c2860a | [
"MIT"
] | 20 | 2015-01-20T07:36:10.000Z | 2019-09-15T01:02:19.000Z | /* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_wiyun_engine_box2d_dynamics_joints_WheelJoint */
#ifndef _Included_com_wiyun_engine_box2d_dynamics_joints_WheelJoint
#define _Included_com_wiyun_engine_box2d_dynamics_joints_WheelJoint
#ifdef __cplusplus
extern "C" {
#endif
#undef com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_INACTIVE
#define com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_INACTIVE 0L
#undef com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_AT_LOWER
#define com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_AT_LOWER 1L
#undef com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_AT_UPPER
#define com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_AT_UPPER 2L
#undef com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_EQUAL
#define com_wiyun_engine_box2d_dynamics_joints_WheelJoint_LIMIT_STATE_EQUAL 3L
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: nativeGetLocalAnchorA
* Signature: (Lcom/wiyun/engine/types/WYPoint;)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_nativeGetLocalAnchorA
(JNIEnv *, jobject, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: nativeGetLocalAnchorB
* Signature: (Lcom/wiyun/engine/types/WYPoint;)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_nativeGetLocalAnchorB
(JNIEnv *, jobject, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: nativeGetLocalAxisA
* Signature: (Lcom/wiyun/engine/types/WYPoint;)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_nativeGetLocalAxisA
(JNIEnv *, jobject, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: getJointTranslation
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_getJointTranslation
(JNIEnv *, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: getJointSpeed
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_getJointSpeed
(JNIEnv *, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: isMotorEnabled
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_isMotorEnabled
(JNIEnv *, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: enableMotor
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_enableMotor
(JNIEnv *, jobject, jboolean);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: setMotorSpeed
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_setMotorSpeed
(JNIEnv *, jobject, jfloat);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: getMotorSpeed
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_getMotorSpeed
(JNIEnv *, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: setMaxMotorTorque
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_setMaxMotorTorque
(JNIEnv *, jobject, jfloat);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: getMaxMotorTorque
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_getMaxMotorTorque
(JNIEnv *, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: getMotorTorque
* Signature: (F)F
*/
JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_getMotorTorque
(JNIEnv *, jobject, jfloat);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: setSpringFrequencyHz
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_setSpringFrequencyHz
(JNIEnv *, jobject, jfloat);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: getSpringFrequencyHz
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_getSpringFrequencyHz
(JNIEnv *, jobject);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: setSpringDampingRatio
* Signature: (F)V
*/
JNIEXPORT void JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_setSpringDampingRatio
(JNIEnv *, jobject, jfloat);
/*
* Class: com_wiyun_engine_box2d_dynamics_joints_WheelJoint
* Method: getSpringDampingRatio
* Signature: ()F
*/
JNIEXPORT jfloat JNICALL Java_com_wiyun_engine_box2d_dynamics_joints_WheelJoint_getSpringDampingRatio
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
| 33.64 | 101 | 0.82065 |
16c14332116b42006d6d1ce0d285c7da9ba3d079 | 1,618 | h | C | lib/lib_mixer.h | Fadoli/EasierSDL2 | 734cfe308db16e9eae175b0772254e8eb58ce372 | [
"MIT"
] | 1 | 2019-07-08T20:34:58.000Z | 2019-07-08T20:34:58.000Z | lib/lib_mixer.h | Fadoli/EasierSDL2 | 734cfe308db16e9eae175b0772254e8eb58ce372 | [
"MIT"
] | null | null | null | lib/lib_mixer.h | Fadoli/EasierSDL2 | 734cfe308db16e9eae175b0772254e8eb58ce372 | [
"MIT"
] | null | null | null | /**
* @file lib_mixer.h
* @author Franck Mourre (franck.mourre@gmail.com)
* @brief Wrapper around sounds / sounds volume and angles
* @version 0.1
* @date 2019-07-13
*
* @copyright Copyright (c) 2019
*/
#ifndef mixer_H
#define mixer_H
#include <SDL2/SDL_mixer.h>
/// viens de la lib sous sdl 1.2
typedef Mix_Chunk SDL_Sound;
namespace sdl2_lib
{
class soundManager
{
public:
void AllocateChannels(int channels);
private:
soundManager();
~soundManager();
int targetChannels;
};
class sound
{
public:
sound(const char *name);
~sound();
SDL_Sound *_sound;
};
class soundPlay
{
public:
soundPlay(sound *sound, int soundLevel = 64, int loopCount = 0);
~soundPlay();
/**
* @brief Set the Volume of the sound
*
* @param volume 0-128 (128 is 100%)
* @return const soundPlay&
*/
const soundPlay &setVolume(int volume);
/**
* @brief Set the Angle of the sound
*
* @param angle 0-360 (automaticly wraps other value around), precision is by 5 unit
* @return const soundPlay&
*/
const soundPlay &setAngle(int angle);
/**
* @brief Set the Distance of the sound
*
* @param distance 0-255 (0 is closest, 255 is furthest), precision is by 5 unit
* @return const soundPlay&
*/
const soundPlay &setDistance(int distance);
const soundPlay &Pause();
const soundPlay &Resume();
private:
sound *_sound;
int channel;
int angle, distance;
};
} // namespace sdl2_lib
#endif // mixer_H
| 20.481013 | 89 | 0.605686 |
cede0c0c4523a86ac2c579c37938abfe933bb7df | 3,656 | h | C | simulator/src/event_recorder.h | CMU-SAFARI/DAMOV | ed39a0642f22d551bed6ab6baaf91c89cc8a3855 | [
"MIT"
] | 17 | 2021-07-10T13:22:26.000Z | 2022-02-09T20:11:39.000Z | simulator/src/event_recorder.h | CMU-SAFARI/DAMOV | ed39a0642f22d551bed6ab6baaf91c89cc8a3855 | [
"MIT"
] | 4 | 2021-08-18T14:07:24.000Z | 2022-01-24T16:38:06.000Z | simulator/src/event_recorder.h | CMU-SAFARI/DAMOV | ed39a0642f22d551bed6ab6baaf91c89cc8a3855 | [
"MIT"
] | 2 | 2021-08-03T10:56:16.000Z | 2022-01-31T12:10:56.000Z | /** $lic$
* Copyright (C) 2012-2015 by Massachusetts Institute of Technology
* Copyright (C) 2010-2013 by The Board of Trustees of Stanford University
*
* This file is part of zsim.
*
* zsim 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.
*
* If you use this software in your research, we request that you reference
* the zsim paper ("ZSim: Fast and Accurate Microarchitectural Simulation of
* Thousand-Core Systems", Sanchez and Kozyrakis, ISCA-40, June 2013) as the
* source of the simulator in any publications that use this software, and that
* you send us a citation of your work.
*
* zsim 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/>.
*/
#ifndef EVENT_RECORDER_H_
#define EVENT_RECORDER_H_
#include "g_std/g_vector.h"
#include "memory_hierarchy.h"
#include "pad.h"
#include "slab_alloc.h"
class TimingEvent;
// Encodes an event that the core should capture for the contention simulation
struct TimingRecord {
Address addr;
uint64_t reqCycle;
uint64_t respCycle;
AccessType type;
TimingEvent* startEvent;
TimingEvent* endEvent;
bool isValid() const { return startEvent; }
void clear() { startEvent = nullptr; }
};
//class CoreRecorder;
class CrossingEvent;
typedef g_vector<CrossingEvent*> CrossingStack;
class EventRecorder : public GlobAlloc {
private:
slab::SlabAlloc slabAlloc;
TimingRecord tr;
CrossingStack crossingStack;
uint32_t srcId;
volatile uint64_t lastGapCycles;
PAD();
volatile uint64_t lastStartSlack;
PAD();
public:
EventRecorder() {
tr.clear();
}
//Alloc interface
template <typename T>
T* alloc() {
return slabAlloc.alloc<T>();
}
void* alloc(size_t sz) {
return slabAlloc.alloc(sz);
}
//Event recording interface
void pushRecord(const TimingRecord& rec) {
assert(!tr.isValid());
tr = rec;
assert(tr.isValid());
}
// Inline to avoid extra copy
inline TimingRecord popRecord() __attribute__((always_inline)) {
TimingRecord rec = tr;
tr.clear();
return rec;
}
inline size_t hasRecord() const {
return tr.isValid();
}
//Called by crossing events
inline uint64_t getSlack(uint64_t origStartCycle) const {
return origStartCycle + lastStartSlack;
}
inline uint64_t getGapCycles() const {
return lastGapCycles;
}
//Called by the core's recorder
//infrequently
void setGapCycles(uint64_t gapCycles) {
lastGapCycles = gapCycles;
}
//frequently
inline void setStartSlack(uint64_t startSlack) {
//Avoid a write, it can cost a bunch of coherence misses
if (lastStartSlack != startSlack) lastStartSlack = startSlack;
}
uint32_t getSourceId() const {return srcId;}
void setSourceId(uint32_t i) {srcId = i;}
inline CrossingStack& getCrossingStack() {
return crossingStack;
}
};
#endif // EVENT_RECORDER_H_
| 28.123077 | 79 | 0.6436 |
771b55c779125aacb097e0f0f8b702c713153c7d | 3,086 | c | C | lib/libc/mingw/math/tgammaf.c | shiimizu/zig | 7277670843d259d19093c8900b1f8445e41202ae | [
"MIT"
] | 1 | 2020-02-27T05:17:53.000Z | 2020-02-27T05:17:53.000Z | lib/libc/mingw/math/tgammaf.c | shiimizu/zig | 7277670843d259d19093c8900b1f8445e41202ae | [
"MIT"
] | 2 | 2019-07-01T17:05:03.000Z | 2019-08-27T19:42:45.000Z | lib/libc/mingw/math/tgammaf.c | shiimizu/zig | 7277670843d259d19093c8900b1f8445e41202ae | [
"MIT"
] | 1 | 2020-11-05T02:32:51.000Z | 2020-11-05T02:32:51.000Z | /**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#include "cephes_mconf.h"
/* define MAXGAM 34.84425627277176174 */
/* Stirling's formula for the gamma function
* gamma(x) = sqrt(2 pi) x^(x-.5) exp(-x) ( 1 + 1/x P(1/x) )
* .028 < 1/x < .1
* relative error < 1.9e-11
*/
static const float STIR[] = {
-2.705194986674176E-003,
3.473255786154910E-003,
8.333331788340907E-002,
};
static const float MAXSTIR = 26.77;
static const float SQTPIF = 2.50662827463100050242; /* sqrt( 2 pi ) */
static float stirf(float);
/* Gamma function computed by Stirling's formula,
* sqrt(2 pi) x^(x-.5) exp(-x) (1 + 1/x P(1/x))
* The polynomial STIR is valid for 33 <= x <= 172.
*/
static float stirf( float x )
{
float y, w, v;
w = 1.0/x;
w = 1.0 + w * polevlf(w, STIR, 2);
y = expf(-x);
if (x > MAXSTIR)
{ /* Avoid overflow in pow() */
v = powf(x, 0.5 * x - 0.25);
y *= v;
y *= v;
}
else
{
y = powf(x, x - 0.5) * y;
}
y = SQTPIF * y * w;
return (y);
}
/* gamma(x+2), 0 < x < 1 */
static const float P[] = {
1.536830450601906E-003,
5.397581592950993E-003,
4.130370201859976E-003,
7.232307985516519E-002,
8.203960091619193E-002,
4.117857447645796E-001,
4.227867745131584E-001,
9.999999822945073E-001,
};
float __tgammaf_r( float x, int* sgngamf);
float __tgammaf_r( float x, int* sgngamf)
{
float p, q, z, nz;
int i, direction, negative;
#ifdef NANS
if (isnan(x))
return (x);
#endif
#ifdef INFINITIES
#ifdef NANS
if (x == INFINITYF)
return (x);
if (x == -INFINITYF)
return (NANF);
#else
if (!isfinite(x))
return (x);
#endif
#endif
*sgngamf = 1;
negative = 0;
nz = 0.0;
if (x < 0.0)
{
negative = 1;
q = -x;
p = floorf(q);
if (p == q)
{
gsing:
_SET_ERRNO(EDOM);
mtherr("tgammaf", SING);
#ifdef INFINITIES
return (INFINITYF);
#else
return (MAXNUMF);
#endif
}
i = p;
if ((i & 1) == 0)
*sgngamf = -1;
nz = q - p;
if (nz > 0.5)
{
p += 1.0;
nz = q - p;
}
nz = q * sinf(PIF * nz);
if (nz == 0.0)
{
_SET_ERRNO(ERANGE);
mtherr("tgamma", OVERFLOW);
#ifdef INFINITIES
return(*sgngamf * INFINITYF);
#else
return(*sgngamf * MAXNUMF);
#endif
}
if (nz < 0)
nz = -nz;
x = q;
}
if (x >= 10.0)
{
z = stirf(x);
}
if (x < 2.0)
direction = 1;
else
direction = 0;
z = 1.0;
while (x >= 3.0)
{
x -= 1.0;
z *= x;
}
/*
while (x < 0.0)
{
if (x > -1.E-4)
goto Small;
z *=x;
x += 1.0;
}
*/
while (x < 2.0)
{
if (x < 1.e-4)
goto Small;
z *=x;
x += 1.0;
}
if (direction)
z = 1.0/z;
if (x == 2.0)
return (z);
x -= 2.0;
p = z * polevlf(x, P, 7);
gdone:
if (negative)
{
p = *sgngamf * PIF/(nz * p );
}
return (p);
Small:
if (x == 0.0)
{
goto gsing;
}
else
{
p = z / ((1.0 + 0.5772156649015329 * x) * x);
goto gdone;
}
}
/* This is the C99 version */
float tgammaf(float x)
{
int local_sgngamf = 0;
return (__tgammaf_r(x, &local_sgngamf));
}
| 15.825641 | 77 | 0.562541 |
dca4e84addeab1300b2bbbe3a14104a13b3851c1 | 1,127 | c | C | bucket_17/arc/patches/patch-arcrun.c | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 17 | 2017-04-22T21:53:52.000Z | 2021-01-21T16:57:55.000Z | bucket_17/arc/patches/patch-arcrun.c | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 186 | 2017-09-12T20:46:52.000Z | 2021-11-27T18:15:14.000Z | bucket_17/arc/patches/patch-arcrun.c | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 74 | 2017-09-06T14:48:01.000Z | 2021-08-28T02:48:27.000Z | --- arcrun.c.orig 2013-06-27 02:00:19 UTC
+++ arcrun.c
@@ -96,7 +96,7 @@ runfile(hdr, num, arg) /* run a file */
strcpy(sys, buf);
else {
- if (warn) {
+ if (arcwarn) {
printf("File %s is not a .BAS, .BAT, .COM, or .EXE\n",
hdr->name);
nerrs++;
@@ -110,7 +110,7 @@ runfile(hdr, num, arg) /* run a file */
&& strcmp(i, ".TTP")
&& strcmp(i, ".TOS"))
{
- if (warn) {
+ if (arcwarn) {
printf("File %s is not a .PRG, .TOS, or .TTP\n",
hdr->name);
nerrs++;
@@ -120,7 +120,7 @@ runfile(hdr, num, arg) /* run a file */
}
#endif
- if (warn)
+ if (arcwarn)
if ((tmp = fopen(buf, "r")))
arcdie("Temporary file %s already exists", buf);
if (!(tmp = tmpopen(buf)))
@@ -144,7 +144,7 @@ runfile(hdr, num, arg) /* run a file */
if (system(buf)) /* try to invoke it */
arcdie("Execution failed for %s", buf);
#endif
- if (unlink(buf) && warn) {
+ if (unlink(buf) && arcwarn) {
printf("Cannot unsave temporary file %s\n", buf);
nerrs++;
}
| 28.897436 | 71 | 0.4685 |
98aa5cbc892fc77dbe8c7e9547bd1505ba20eb8f | 1,603 | h | C | syn/core/grm_parser.h | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | 1 | 2019-02-08T02:23:56.000Z | 2019-02-08T02:23:56.000Z | syn/core/grm_parser.h | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | null | null | null | syn/core/grm_parser.h | asmwarrior/syncpp | df34b95b308d7f2e6479087d629017efa7ab9f1f | [
"Apache-2.0"
] | 1 | 2020-12-02T02:37:40.000Z | 2020-12-02T02:37:40.000Z | /*
* Copyright 2014 Anton Karmanov
*
* 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.
*/
//EBNF Grammar parser definitions.
#ifndef SYN_CORE_GRM_PARSER_H_INCLUDED
#define SYN_CORE_GRM_PARSER_H_INCLUDED
#include <memory>
#include <string>
#include "commons.h"
#include "ebnf__imp.h"
#include "grm_parser_res.h"
#include "util_mptr.h"
#include "util_string.h"
namespace synbin {
namespace grm_parser {
//
//ParserException
//
class ParserException : public TextException {
public:
ParserException(const std::string& message, const FilePos& pos)
: TextException(message, pos)
{}
ParserException(const std::string& message, const util::String& file_name)
: TextException(message, FilePos(file_name, TextPos()))
{}
ParserException(const std::string& message, const util::String& file_name, TextPos text_pos)
: TextException(message, FilePos(file_name, text_pos))
{}
};
//Parse EBNF grammar.
std::unique_ptr<GrammarParsingResult> parse_grammar(std::istream& in, const util::String& file_name);
}
}
#endif//SYN_CORE_GRM_PARSER_H_INCLUDED
| 26.716667 | 103 | 0.736744 |
0731daff9f1e19940cce065fdda9eba28b55b99f | 496 | h | C | NO76/NO76.h | wanyakun/YKLeetCode | d27efca74a5af7ff1dc566b98900f33482721ca7 | [
"MIT"
] | null | null | null | NO76/NO76.h | wanyakun/YKLeetCode | d27efca74a5af7ff1dc566b98900f33482721ca7 | [
"MIT"
] | null | null | null | NO76/NO76.h | wanyakun/YKLeetCode | d27efca74a5af7ff1dc566b98900f33482721ca7 | [
"MIT"
] | null | null | null | //
// NO76.h
// NO76
//
// Created by wanyakun on 2020/11/12.
//
/**
76. 最小覆盖子串
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"
示例 2:
输入:s = "a", t = "a"
输出:"a"
提示:
1 <= s.length, t.length <= 105
s 和 t 由英文字母组成
进阶:你能设计一个在 o(n) 时间内解决此问题的算法吗?
*/
#ifndef NO76_h
#define NO76_h
#include <stdio.h>
char * minWindow(char * s, char * t);
#endif /* NO76_h */
| 11.809524 | 76 | 0.578629 |
e69d2f7ede377e7622d200a38cdd7992d1d03130 | 1,446 | h | C | Sprite_shared.h | lighterlightbulb/JFKMW | 693793def1c2beb6c92596a5aa99a69c6d48133d | [
"WTFPL"
] | null | null | null | Sprite_shared.h | lighterlightbulb/JFKMW | 693793def1c2beb6c92596a5aa99a69c6d48133d | [
"WTFPL"
] | null | null | null | Sprite_shared.h | lighterlightbulb/JFKMW | 693793def1c2beb6c92596a5aa99a69c6d48133d | [
"WTFPL"
] | null | null | null | #pragma once
string SPR_CODE[256]; //Cache
void preloadSpriteCache()
{
for (int i = 0; i < 256; i++) {
SPR_CODE[i] = "";
}
int sprs = 0;
for (int i = 0; i < 256; i++)
{
ifstream SprCode(path + "Code/Sprites/" + int_to_hex(i, true) + ".lua");
if (SprCode.is_open()) {
std::stringstream buffer;
buffer << SprCode.rdbuf();
SPR_CODE[i] = buffer.str();
sprs++;
}
SprCode.close();
}
cout << lua_color << "[Lua] Preloaded " << sprs << " sprites." << white << endl;
}
uint_fast8_t spawnSpriteJFKMarioWorld(uint_fast8_t sprite_num, uint_fast8_t new_state, uint_fast16_t x, uint_fast16_t y, uint_fast8_t direction, bool is_lua)
{
for (uint_fast8_t i = 0; i < 128; i++)
{
if (RAM[0x2000 + i] == 0)
{
RAM[0x2000 + i] = new_state;
RAM[0x2080 + i] = sprite_num;
RAM[0x2F80 + i] = 0;
RAM[0x2100 + i] = uint_fast8_t(x & 0xFF);
RAM[0x2180 + i] = uint_fast8_t(x >> 8);
RAM[0x2200 + i] = 0;
RAM[0x2280 + i] = uint_fast8_t(y & 0xFF);
RAM[0x2300 + i] = uint_fast8_t(y >> 8);
RAM[0x2380 + i] = 0;
RAM[0x2600 + i] = 0;
RAM[0x2400 + i] = 0;
RAM[0x2480 + i] = 0;
RAM[0x2700 + i] = 0;
RAM[0x2780 + i] = 0;
RAM[0x2680 + i] = direction;
RAM[0x2700 + i] = 0;
RAM[0x2E00 + i] = 0x01;
RAM[0x2F00 + i] = 0x00;
RAM[0x2A00 + i] = 0x00;
RAM[0x2A80 + i] = 0x02;
RAM[0x2B00 + i] = 0;
RAM[0x2800 + i] = is_lua;
RAM[0x2880 + i] = 0;
return i;
}
}
return 0xFF;
} | 21.264706 | 157 | 0.568465 |
9031cf11186a5ab622c5f09bb981b819d99db6f2 | 9,192 | h | C | tests/cuda2.2/sdk/rendercheck_gl.h | florianjacob/gpuocelot | fa63920ee7c5f9a86e264cd8acd4264657cbd190 | [
"BSD-3-Clause"
] | 221 | 2015-03-29T02:05:49.000Z | 2022-03-25T01:45:36.000Z | tests/cuda2.2/sdk/rendercheck_gl.h | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 106 | 2015-03-29T01:28:42.000Z | 2022-02-15T19:38:23.000Z | tests/cuda2.2/sdk/rendercheck_gl.h | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 83 | 2015-07-10T23:09:57.000Z | 2022-03-25T03:01:00.000Z | /*
* Copyright 1993-2009 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO USER:
*
* This source code is subject to NVIDIA ownership rights under U.S. and
* international Copyright laws. Users and possessors of this source code
* are hereby granted a nonexclusive, royalty-free license to use this code
* in individual and commercial software.
*
* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOURCE CODE.
*
* U.S. Government End Users. This source code is a "commercial item" as
* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
* "commercial computer software" and "commercial computer software
* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
* and is provided to the U.S. Government only as a commercial end item.
* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
* source code with only those rights set forth herein.
*
* Any use of this source code in individual and commercial software must
* include, in the user documentation and internal comments to the code,
* the above Disclaimer and U.S. Government End Users Notice.
*/
#ifndef _RENDERCHECK_GL_H_
#define _RENDERCHECK_GL_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <vector>
#include <map>
#include <string>
#include <GL/glew.h>
#if defined(__APPLE__) || defined(MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <nvShaderUtils.h>
using std::vector;
using std::map;
using std::string;
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
#if _DEBUG
#define CHECK_FBO checkStatus(__FILE__, __LINE__, true)
#else
#define CHECK_FBO true
#endif
class CheckRender
{
public:
CheckRender(unsigned int width, unsigned int height, unsigned int Bpp,
bool bQAReadback, bool bUseFBO, bool bUsePBO);
virtual ~CheckRender();
virtual void allocateMemory( unsigned int width, unsigned int height, unsigned int Bpp,
bool bQAReadback, bool bUseFBO, bool bUsePBO );
virtual void setExecPath(char *path) {
strcpy(m_ExecPath, path);
}
virtual void EnableQAReadback(bool bStatus) { m_bQAReadback = bStatus; }
virtual bool IsQAReadback() { return m_bQAReadback; }
virtual bool IsFBO() { return m_bUseFBO; }
virtual bool IsPBO() { return m_bUsePBO; }
virtual void * imageData() { return m_pImageData; }
// Interface to this class functions
virtual void setPixelFormat(GLenum format) { m_PixelFormat = format; }
virtual int getPixelFormat() { return m_PixelFormat; }
virtual bool checkStatus(const char *zfile, int line, bool silent) = 0;
virtual bool readback( GLuint width, GLuint height ) = 0;
virtual bool readback( GLuint width, GLuint height, GLuint bufObject ) = 0;
virtual bool readback( GLuint width, GLuint height, unsigned char *membuf ) = 0;
virtual void bindReadback();
virtual void unbindReadback();
virtual void savePGM( const char *zfilename, bool bInvert, void **ppReadBuf );
virtual void savePPM( const char *zfilename, bool bInvert, void **ppReadBuf );
virtual bool PGMvsPGM( const char *src_file, const char *ref_file, const float epsilon, const float threshold = 0.0f );
virtual bool PPMvsPPM( const char *src_file, const char *ref_file, const float epsilon, const float threshold = 0.0f );
void setThresholdCompare(float value) { m_fThresholdCompare = value; }
virtual void dumpBin(void *data, unsigned int bytes, char *filename);
virtual bool compareBin2BinUint(const char *src_file, const char *ref_file, unsigned int nelements, const float epsilon, const float threshold);
virtual bool compareBin2BinFloat(const char *src_file, const char *ref_file, unsigned int nelements, const float epsilon, const float threshold);
protected:
unsigned int m_Width, m_Height, m_Bpp;
unsigned char *m_pImageData; // This is the image data stored in system memory
bool m_bQAReadback, m_bUseFBO, m_bUsePBO;
GLuint m_pboReadback;
GLenum m_PixelFormat;
float m_fThresholdCompare;
char m_ExecPath[256];
};
class CheckBackBuffer : public CheckRender
{
public:
CheckBackBuffer(unsigned int width, unsigned int height, unsigned int Bpp, bool bUseOpenGL = true);
virtual ~CheckBackBuffer();
virtual bool checkStatus(const char *zfile, int line, bool silent);
virtual bool readback( GLuint width, GLuint height );
virtual bool readback( GLuint width, GLuint height, GLuint bufObject );
virtual bool readback( GLuint width, GLuint height, unsigned char *membuf );
private:
virtual void bindFragmentProgram() {};
virtual void bindRenderPath() {};
virtual void unbindRenderPath() {};
// bind to the FBO to Texture
virtual void bindTexture() {};
// release this bind
virtual void unbindTexture() {};
};
// structure defining the properties of a single buffer
struct bufferConfig {
string name;
GLenum format;
int bits;
};
// structures defining properties of an FBO
struct fboConfig {
string name;
GLenum colorFormat;
GLenum depthFormat;
int redbits;
int depthBits;
int depthSamples;
int coverageSamples;
};
struct fboData {
GLuint colorTex; //color texture
GLuint depthTex; //depth texture
GLuint fb; // render framebuffer
GLuint resolveFB; //multisample resolve target
GLuint colorRB; //color render buffer
GLuint depthRB; // depth render buffer
};
class CFrameBufferObject
{
public:
CFrameBufferObject (unsigned int width, unsigned int height, unsigned int Bpp, bool bUseFloat, GLenum eTarget);
CFrameBufferObject (unsigned int width, unsigned int height, unsigned int Bpp, fboData &data, fboConfig &config, bool bUseFloat = false);
CFrameBufferObject (unsigned int width, unsigned int height, unsigned int Bpp, fboData &data, fboConfig &config, bool bUseFloat, GLenum eTarget);
virtual ~CFrameBufferObject();
GLuint createTexture(GLenum target, int w, int h, GLint internalformat, GLenum format);
void attachTexture( GLenum texTarget,
GLuint texId,
GLenum attachment = GL_COLOR_ATTACHMENT0_EXT,
int mipLevel = 0,
int zSlice = 0);
bool initialize(unsigned width, unsigned height, fboConfig & rConfigFBO, fboData & rActiveFBO);
bool create( GLuint width, GLuint height, fboConfig &config, fboData &data );
bool createMSAA( GLuint width, GLuint height, fboConfig *p_config, fboData *p_data );
bool createCSAA( GLuint width, GLuint height, fboConfig *p_config, fboData *p_data );
virtual void freeResources();
virtual bool checkStatus(const char *zfile, int line, bool silent);
virtual void renderQuad(int width, int height, GLenum eTarget);
// bind to the Fragment Program
void bindFragmentProgram() {
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_textureProgram);
glEnable(GL_FRAGMENT_PROGRAM_ARB);
}
// bind to the FrameBuffer Object
void bindRenderPath() {
glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_fboData.fb );
}
// release current FrameBuffer Object
void unbindRenderPath() {
glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
}
// bind to the FBO to Texture
void bindTexture() {
glBindTexture( m_eGLTarget, m_fboData.colorTex );
}
// release this bind
void unbindTexture() {
glBindTexture( m_eGLTarget, 0 );
}
GLuint getFbo() { return m_fboData.fb; }
GLuint getTex() { return m_fboData.colorTex; }
GLuint getDepthTex() { return m_fboData.depthTex; }
private:
fboData m_fboData;
fboConfig m_fboConfig;
GLuint m_textureProgram;
GLuint m_overlayProgram;
bool m_bUseFloat;
GLenum m_eGLTarget;
};
// CheckFBO - render and verify contents of the FBO
class CheckFBO: public CheckRender
{
public:
CheckFBO(unsigned int width, unsigned int height, unsigned int Bpp);
CheckFBO(unsigned int width, unsigned int height, unsigned int Bpp, CFrameBufferObject *pFrameBufferObject);
virtual ~CheckFBO();
virtual bool checkStatus(const char *zfile, int line, bool silent);
virtual bool readback( GLuint width, GLuint height );
virtual bool readback( GLuint width, GLuint height, GLuint bufObject );
virtual bool readback( GLuint width, GLuint height, unsigned char *membuf );
private:
CFrameBufferObject *m_pFrameBufferObject;
};
#endif // _RENDERCHECK_GL_H_
| 34.556391 | 149 | 0.71943 |
9055309b8f8123d8f4ef283e9aedca031e8716c9 | 2,408 | c | C | ClassMaterials/CV_ProducerConsumer/prodcons_solution.c | 17hsteward/CSSE_WorkingPersonal | b51f3d174b0c3e07712ca68022b5e2256cda4c6c | [
"MIT"
] | null | null | null | ClassMaterials/CV_ProducerConsumer/prodcons_solution.c | 17hsteward/CSSE_WorkingPersonal | b51f3d174b0c3e07712ca68022b5e2256cda4c6c | [
"MIT"
] | null | null | null | ClassMaterials/CV_ProducerConsumer/prodcons_solution.c | 17hsteward/CSSE_WorkingPersonal | b51f3d174b0c3e07712ca68022b5e2256cda4c6c | [
"MIT"
] | null | null | null | #include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/**
* The goal of this activity is to implement the correct concurrency management
* for the producer/consumer problem using condition variables.
*/
const int loops = 100;
#define MAX 10
#define NUM_PRODUCERS 5
#define NUM_CONSUMERS 5
int buffer[MAX];
int fill = 0;
int use = 0;
int count = 0;
pthread_mutex_t lock;
pthread_cond_t empty;
pthread_cond_t full;
/**
* Put a value into the buffer and increment the fill index.
*/
void put(int value) {
buffer[fill] = value;
fill = (fill + 1) % MAX;
count++;
}
/**
* Get a value from the buffer and increment the use index.
*/
int get() {
int value = buffer[use];
use = (use + 1) % MAX;
count--;
return value;
}
/**
* The producer can fill item in the buffer when empty
*/
void *
producer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&lock);
while (count == MAX)
pthread_cond_wait(&empty, &lock);
put(i);
pthread_cond_signal(&full);
pthread_mutex_unlock(&lock);
printf("Producer produced %d\n", i);
}
}
/**
* The consumer can consume items from the buffer when full
*/
void *
consumer(void *arg) {
int value = 0, i = 0;
for (; i < loops; i++) {
pthread_mutex_lock(&lock);
while (count == 0)
pthread_cond_wait(&full, &lock);
value = get();
pthread_cond_signal(&empty);
pthread_mutex_unlock(&lock);
printf("Consumer consumed %d\n", value);
}
}
int main(int argc, char **argv) {
/* the threads */
pthread_t producer_threads[NUM_PRODUCERS];
pthread_t consumer_threads[NUM_CONSUMERS];
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&empty, NULL);
pthread_cond_init(&full, NULL);
/* create the producer threads */
for (int i = 0; i < NUM_PRODUCERS; ++i)
pthread_create(&producer_threads[i], 0, producer, NULL);
/* create the consumer threads */
for (int i = 0; i < NUM_CONSUMERS; ++i)
pthread_create(&consumer_threads[i], 0, consumer, NULL);
/* wait for producers */
for (int i = 0; i < NUM_PRODUCERS; ++i)
pthread_join(producer_threads[i], NULL);
/* wait for consumers */
for (int i = 0; i < NUM_CONSUMERS; ++i)
pthread_join(consumer_threads[i], NULL);
}
| 23.153846 | 79 | 0.61794 |
11c688c1d7ecf74cd116bbf6a9b926f50320f62c | 255 | h | C | kernel/linux-5.4/arch/alpha/include/asm/syscall.h | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 31 | 2021-04-27T08:50:40.000Z | 2022-03-01T02:26:21.000Z | kernel/linux-5.4/arch/alpha/include/asm/syscall.h | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 13 | 2021-07-10T04:36:17.000Z | 2022-03-03T10:50:05.000Z | kernel/linux-5.4/arch/alpha/include/asm/syscall.h | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 12 | 2021-04-06T02:23:10.000Z | 2022-02-28T11:43:19.000Z | /* SPDX-License-Identifier: GPL-2.0 */
#ifndef _ASM_ALPHA_SYSCALL_H
#define _ASM_ALPHA_SYSCALL_H
#include <uapi/linux/audit.h>
static inline int syscall_get_arch(struct task_struct *task)
{
return AUDIT_ARCH_ALPHA;
}
#endif /* _ASM_ALPHA_SYSCALL_H */
| 19.615385 | 60 | 0.780392 |
507c6d18616b63ad56ea04da2ccc1dd85f4a2cdf | 6,665 | c | C | ports/esp32s2/common-hal/wifi/ScannedNetworks.c | MakeItZone/circuitpython | 7f803c0b51c333210ed267502422ed7bb28b9be7 | [
"Unlicense",
"BSD-3-Clause",
"MIT-0",
"MIT"
] | 1 | 2021-08-08T18:53:00.000Z | 2021-08-08T18:53:00.000Z | ports/esp32s2/common-hal/wifi/ScannedNetworks.c | MakeItZone/circuitpython | 7f803c0b51c333210ed267502422ed7bb28b9be7 | [
"Unlicense",
"BSD-3-Clause",
"MIT-0",
"MIT"
] | null | null | null | ports/esp32s2/common-hal/wifi/ScannedNetworks.c | MakeItZone/circuitpython | 7f803c0b51c333210ed267502422ed7bb28b9be7 | [
"Unlicense",
"BSD-3-Clause",
"MIT-0",
"MIT"
] | 2 | 2020-11-27T19:47:47.000Z | 2021-09-13T12:15:25.000Z | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Dan Halbert for Adafruit Industries
* Copyright (c) 2018 Artur Pacholec
* Copyright (c) 2017 Glenn Ruben Bakke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <string.h>
#include "lib/utils/interrupt_char.h"
#include "py/gc.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "shared-bindings/wifi/__init__.h"
#include "shared-bindings/wifi/Network.h"
#include "shared-bindings/wifi/Radio.h"
#include "shared-bindings/wifi/ScannedNetworks.h"
#include "esp-idf/components/esp_wifi/include/esp_wifi.h"
static void wifi_scannednetworks_done(wifi_scannednetworks_obj_t *self) {
self->done = true;
if (self->results != NULL) {
// Check to see if the heap is still active. If not, it'll be freed automatically.
if (gc_alloc_possible()) {
m_free(self->results);
}
self->results = NULL;
}
}
static bool wifi_scannednetworks_wait_for_scan(wifi_scannednetworks_obj_t *self) {
EventBits_t bits = xEventGroupWaitBits(self->radio_event_group,
WIFI_SCAN_DONE_BIT,
pdTRUE,
pdTRUE,
0);
while ((bits & WIFI_SCAN_DONE_BIT) == 0 && !mp_hal_is_interrupted()) {
RUN_BACKGROUND_TASKS;
bits = xEventGroupWaitBits(self->radio_event_group,
WIFI_SCAN_DONE_BIT,
pdTRUE,
pdTRUE,
0);
}
return !mp_hal_is_interrupted();
}
mp_obj_t common_hal_wifi_scannednetworks_next(wifi_scannednetworks_obj_t *self) {
if (self->done) {
return mp_const_none;
}
// If we are scanning, wait and then load them.
if (self->scanning) {
// We may have to scan more than one channel to get a result.
while (!self->done) {
if (!wifi_scannednetworks_wait_for_scan(self)) {
wifi_scannednetworks_done(self);
return mp_const_none;
}
esp_wifi_scan_get_ap_num(&self->total_results);
self->scanning = false;
if (self->total_results > 0) {
break;
}
// If total_results is zero then we need to start a scan and wait again.
wifi_scannednetworks_scan_next_channel(self);
}
// We not have found any more results so we're done.
if (self->done) {
return mp_const_none;
}
// If we need more space than we have, realloc.
if (self->total_results > self->max_results) {
wifi_ap_record_t* results = m_renew_maybe(wifi_ap_record_t,
self->results,
self->max_results,
self->total_results,
true /* allow move */);
if (results != NULL) {
self->results = results;
self->max_results = self->total_results;
} else {
if (self->max_results == 0) {
// No room for any results should error.
mp_raise_msg(&mp_type_MemoryError, translate("Failed to allocate wifi scan memory"));
}
// Unable to allocate more results, so load what we can.
self->total_results = self->max_results;
}
}
esp_wifi_scan_get_ap_records(&self->total_results, self->results);
self->scanning = false;
}
wifi_network_obj_t *entry = m_new_obj(wifi_network_obj_t);
entry->base.type = &wifi_network_type;
memcpy(&entry->record, &self->results[self->current_result], sizeof(wifi_ap_record_t));
self->current_result++;
// If we're returning our last network then start the next channel scan or
// be done.
if (self->current_result >= self->total_results) {
wifi_scannednetworks_scan_next_channel(self);
self->total_results = 0;
self->current_result = 0;
}
return MP_OBJ_FROM_PTR(entry);
}
// We don't do a linear scan so that we look at a variety of spectrum up front.
static uint8_t scan_pattern[] = {6, 1, 11, 3, 9, 13, 2, 4, 8, 12, 5, 7, 10, 14};
void wifi_scannednetworks_scan_next_channel(wifi_scannednetworks_obj_t *self) {
uint8_t next_channel = sizeof(scan_pattern);
while (self->current_channel_index < sizeof(scan_pattern)) {
next_channel = scan_pattern[self->current_channel_index];
self->current_channel_index++;
if (self->start_channel <= next_channel && next_channel <= self->end_channel) {
break;
}
}
wifi_scan_config_t config = { 0 };
config.channel = next_channel;
if (next_channel == sizeof(scan_pattern)) {
wifi_scannednetworks_done(self);
} else {
esp_err_t result = esp_wifi_scan_start(&config, false);
if (result != ESP_OK) {
wifi_scannednetworks_done(self);
} else {
self->scanning = true;
}
}
}
void wifi_scannednetworks_deinit(wifi_scannednetworks_obj_t* self) {
// if a scan is active, make sure and clean up the idf's buffer of results.
if (self->scanning) {
esp_wifi_scan_stop();
if (wifi_scannednetworks_wait_for_scan(self)) {
// Ignore the number of records since we're throwing them away.
uint16_t number = 0;
esp_wifi_scan_get_ap_records(&number, NULL);
self->scanning = false;
}
}
wifi_scannednetworks_done(self);
}
| 38.526012 | 105 | 0.628507 |
1f514105888608b2940bed011d16692d38ab63d1 | 107 | h | C | jt_helpers.h | barak/JoppyType | d2e64583084b2d3445ca4ffff26e17470311ed8b | [
"MIT"
] | null | null | null | jt_helpers.h | barak/JoppyType | d2e64583084b2d3445ca4ffff26e17470311ed8b | [
"MIT"
] | null | null | null | jt_helpers.h | barak/JoppyType | d2e64583084b2d3445ca4ffff26e17470311ed8b | [
"MIT"
] | 1 | 2020-03-25T14:01:35.000Z | 2020-03-25T14:01:35.000Z | SDL_Surface *loadImage(char *filename);
SDL_Texture *loadTexture(SDL_Renderer *renderer, char *filename);
| 26.75 | 65 | 0.803738 |
d3140765093897d47642312f8dab2e5dfa35e701 | 1,047 | c | C | hello_world.c | vcalderon2009/Cprogramming | 52fd9e15e38c6ba1023f816dfca51035935a08f9 | [
"MIT"
] | 7 | 2019-03-11T23:17:55.000Z | 2021-07-27T20:57:31.000Z | hello_world.c | vcalderon2009/Cprogramming | 52fd9e15e38c6ba1023f816dfca51035935a08f9 | [
"MIT"
] | 2 | 2019-03-11T23:05:01.000Z | 2019-04-30T22:56:21.000Z | hello_world.c | vcalderon2009/Cprogramming | 52fd9e15e38c6ba1023f816dfca51035935a08f9 | [
"MIT"
] | 15 | 2015-05-29T20:11:30.000Z | 2020-10-10T09:05:09.000Z | #include <stdio.h> // printf is defined in this header file
// This defines a function called "main"
// The return type is an int (integer)
// And it takes no arguments
//
// The main function is required for all
// C programs. It's where execution of the
// code begins. The return type must be an
// int.
int main()
{
// I tend to use spaces to make blocks
// of code more readable, you can also
// use tabs.
//
// This line calls a function called printf,
// and passes a "Hello World!" string, along
// with a special end of line character (\n)
//
// A semi-colon is required at the end of
// each line
printf("Hello world!\n");
// Recall that the return type for the main
// function is an int. Here, we return the
// integer zero, which is the convention
// for signifying that the program exited
// normally. You actually don't need to
// include this line at all. You might get
// a warning from the compiler but the program
// will compile and run normally.
return 0;
} | 29.914286 | 60 | 0.662846 |
2057b28bc3054877e725040f6985ebaea1aecd29 | 6,193 | h | C | base/DynamicVector.h | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 23 | 2015-08-13T07:36:00.000Z | 2022-01-24T19:00:04.000Z | base/DynamicVector.h | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | null | null | null | base/DynamicVector.h | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 6 | 2015-07-06T21:37:31.000Z | 2020-07-01T04:07:50.000Z | // Copyright Ryan Schmidt 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef _RMS_DYNAMIC_VECTOR_H
#define _RMS_DYNAMIC_VECTOR_H
#include <cstddef> // 'size_t'
#include "config.h"
#include <vector>
namespace rms
{
template<class Type>
class DataSegment {
public:
Type * pData;
size_t nSize;
size_t nCur;
DataSegment() { pData = NULL; }
~DataSegment() { }
};
template<class Type>
class DynamicVector
{
public:
DynamicVector(unsigned int nSegmentSize = 0);
DynamicVector(const DynamicVector & copy);
virtual ~DynamicVector();
const DynamicVector & operator=( const DynamicVector & copy );
void clear( bool bFreeSegments = false );
void resize( size_t nCount );
void resize( size_t nCount, const Type & init_value );
size_t size() const;
void push_back( const Type & data );
Type * push_back();
void push_back( const DynamicVector<Type> & data );
Type & operator[]( unsigned int nIndex );
const Type & operator[]( unsigned int nIndex ) const;
protected:
unsigned int m_nSegmentSize;
unsigned int m_nCurSeg;
std::vector< DataSegment<Type> > m_vSegments;
Type * allocate_element();
};
template <class Type>
DynamicVector<Type>::DynamicVector(unsigned int nSegmentSize)
{
if ( nSegmentSize == 0 )
m_nSegmentSize = (1 << 16) / sizeof(Type); // 64k
else
m_nSegmentSize = nSegmentSize;
m_vSegments.resize(1);
m_vSegments[0].pData = new Type[ m_nSegmentSize ];
m_vSegments[0].nSize = m_nSegmentSize;
m_vSegments[0].nCur = 0;
m_nCurSeg = 0;
}
template <class Type>
DynamicVector<Type>::DynamicVector(const DynamicVector<Type> & copy)
{
*this = copy;
}
template <class Type>
DynamicVector<Type>::~DynamicVector()
{
size_t nCount = m_vSegments.size();
for (unsigned int i = 0; i < nCount; ++i)
delete [] m_vSegments[i].pData;
}
template <class Type>
const DynamicVector<Type> & DynamicVector<Type>::operator=( const DynamicVector & copy )
{
// if segments are the same size, we don't need to re-allocate any existing ones (woot!)
if ( m_nSegmentSize != copy.m_nSegmentSize )
clear(true);
m_nSegmentSize = copy.m_nSegmentSize;
m_nCurSeg = copy.m_nCurSeg;
// allocate memory (or discard exisiting memory) for segments
resize( copy.size() );
// copy segment contents
size_t nSegs = copy.m_vSegments.size();
for ( unsigned int k = 0; k < nSegs; ++k ) {
#ifdef WIN32
memcpy_s( m_vSegments[k].pData, m_nSegmentSize*sizeof(Type), copy.m_vSegments[k].pData, m_nSegmentSize*sizeof(Type) );
#else
memcpy( m_vSegments[k].pData, copy.m_vSegments[k].pData, m_nSegmentSize*sizeof(Type) );
#endif
m_vSegments[k].nSize = m_nSegmentSize;
m_vSegments[k].nCur = copy.m_vSegments[k].nCur;
}
return *this;
}
template <class Type>
void DynamicVector<Type>::clear( bool bFreeSegments )
{
size_t nCount = m_vSegments.size();
for (unsigned int i = 0; i < nCount; ++i)
m_vSegments[i].nCur = 0;
if (bFreeSegments) {
for (unsigned int i = 1; i < nCount; ++i)
delete [] m_vSegments[i].pData;
m_vSegments.resize(1);
}
m_nCurSeg = 0;
}
template <class Type>
void DynamicVector<Type>::resize( size_t nCount )
{
// figure out how many segments we need
unsigned int nNumSegs = 1 + (unsigned int)nCount / m_nSegmentSize;
// figure out how many are currently allocated...
size_t nCurCount = m_vSegments.size();
// erase extra segments memory
for ( unsigned int i = nNumSegs; i < nCurCount; ++i )
delete [] m_vSegments[i].pData;
// resize to right number of segments
m_vSegments.resize(nNumSegs);
// allocate new segments
for (unsigned int i = (unsigned int)nCurCount; i < nNumSegs; ++i) {
m_vSegments[i].pData = new Type[ m_nSegmentSize ];
m_vSegments[i].nSize = m_nSegmentSize;
m_vSegments[i].nCur = 0;
}
// mark full segments as used
for (unsigned int i = 0; i < nNumSegs-1; ++i)
// m_vSegments[i-1].nCur = m_nSegmentSize;
m_vSegments[i].nCur = m_nSegmentSize;
// mark last segment
m_vSegments[nNumSegs-1].nCur = nCount - (nNumSegs-1)*m_nSegmentSize;
m_nCurSeg = nNumSegs-1;
}
template <class Type>
void DynamicVector<Type>::resize( size_t nCount, const Type & init_value )
{
size_t nCurSize = size();
resize(nCount);
for ( size_t nIndex = nCurSize; nIndex < nCount; ++nIndex )
m_vSegments[ nIndex / m_nSegmentSize ].pData[ nIndex % m_nSegmentSize ] = init_value;
}
template <class Type>
size_t DynamicVector<Type>::size() const
{
return (m_nCurSeg)*m_nSegmentSize + m_vSegments[m_nCurSeg].nCur;
}
template <class Type>
Type * DynamicVector<Type>::allocate_element()
{
DataSegment<Type> & seg = m_vSegments[m_nCurSeg];
if ( seg.nCur == seg.nSize ) {
if ( m_nCurSeg == m_vSegments.size() - 1 ) {
m_vSegments.resize( m_vSegments.size() + 1 );
DataSegment<Type> & newSeg = m_vSegments.back();
newSeg.pData = new Type[ m_nSegmentSize ];
newSeg.nSize = m_nSegmentSize;
newSeg.nCur = 0;
}
m_nCurSeg++;
}
DataSegment<Type> & returnSeg = m_vSegments[m_nCurSeg];
return & returnSeg.pData[ returnSeg.nCur++ ];
}
template <class Type>
void DynamicVector<Type>::push_back( const Type & data )
{
Type * pNewElem = allocate_element();
*pNewElem = data;
}
template <class Type>
Type * DynamicVector<Type>::push_back()
{
return allocate_element();
}
template <class Type>
void DynamicVector<Type>::push_back( const DynamicVector<Type> & data )
{
// [RMS TODO] it would be a lot more efficient to use memcopies here...
size_t nSize = data.size();
for ( unsigned int k = 0; k < nSize; ++k )
push_back( data[k] );
}
template <class Type>
Type & DynamicVector<Type>::operator[]( unsigned int nIndex )
{
return m_vSegments[ nIndex / m_nSegmentSize ].pData[ nIndex % m_nSegmentSize ];
}
template <class Type>
const Type & DynamicVector<Type>::operator[]( unsigned int nIndex ) const
{
return m_vSegments[ nIndex / m_nSegmentSize ].pData[ nIndex % m_nSegmentSize ];
}
} // end namespace rms
#endif _RMS_DYNAMIC_VECTOR_H
| 24.971774 | 123 | 0.677539 |
2d26be2aedabdcfb4de1622e3969aa7ac29d695f | 2,921 | c | C | ips/block.c | aaaaaa123456789/bspbuild | 7563c218cc2eaaa271f9962f89e1d6d87d485622 | [
"Unlicense"
] | 4 | 2017-11-18T02:10:35.000Z | 2018-10-30T04:04:07.000Z | ips/block.c | aaaaaa123456789/xorbsp | 7563c218cc2eaaa271f9962f89e1d6d87d485622 | [
"Unlicense"
] | 4 | 2018-02-17T19:10:47.000Z | 2018-07-18T10:48:47.000Z | ips/block.c | aaaaaa123456789/bspbuild | 7563c218cc2eaaa271f9962f89e1d6d87d485622 | [
"Unlicense"
] | null | null | null | #include "proto.h"
void write_ips_blocks_for_data (const void * data, unsigned length, unsigned offset) {
if (!(data && length)) return;
unsigned block_size;
while (length) {
if (offset == IPS_EOF_MARKER) {
char * buf = malloc(length + 1);
*buf = ips_target[IPS_EOF_MARKER - 1];
memcpy(buf + 1, data, length);
block_size = write_next_ips_block(buf, length + 1, offset - 1);
free(buf);
} else
block_size = write_next_ips_block(data, length, offset);
data = ((const char *) data) + block_size;
length -= block_size;
offset += block_size;
}
}
unsigned write_next_ips_block (const char * data, unsigned length, unsigned offset) {
unsigned remaining = length;
unsigned short last_run;
do {
last_run = write_next_run_block(data, remaining, offset);
data += last_run;
remaining -= last_run;
offset += last_run;
} while (last_run >= MAXIMUM_IPS_BLOCK_SIZE);
if (!remaining) return length;
unsigned current = remaining;
if (current > MAXIMUM_IPS_BLOCK_SIZE) {
current = MAXIMUM_IPS_BLOCK_SIZE;
remaining -= MAXIMUM_IPS_BLOCK_SIZE;
} else
remaining = 0;
int run_pos = check_runs(data, current);
if (run_pos >= 0) {
remaining += current - run_pos;
current = run_pos;
if ((offset + current) == IPS_EOF_MARKER) {
remaining --;
current ++;
}
}
write_next_data_block(data, current, offset);
return length - remaining;
}
void write_next_data_block (const char * data, unsigned short length, unsigned offset) {
if (!length) return;
append_big_endian_number_to_buffer(&ips_buffer, offset, 3);
append_big_endian_number_to_buffer(&ips_buffer, length, 2);
append_data_to_buffer(&ips_buffer, data, length);
}
unsigned short write_next_run_block (const char * data, unsigned length, unsigned offset) {
unsigned short run;
if (length > MAXIMUM_IPS_BLOCK_SIZE) length = MAXIMUM_IPS_BLOCK_SIZE;
for (run = 1; (run < length) && (data[run] == *data); run ++);
if (run < MINIMUM_IPS_RUN) return 0;
append_big_endian_number_to_buffer(&ips_buffer, offset, 3);
append_data_to_buffer(&ips_buffer, (unsigned char []) {0, 0}, 2); // just a zero, but this is faster
append_big_endian_number_to_buffer(&ips_buffer, run, 2);
append_data_to_buffer(&ips_buffer, data, 1);
return run;
}
unsigned get_segment_length (const char * first_buffer, const char * second_buffer, unsigned length, int kind) {
// 0: differing, 1: equal
unsigned pos;
for (pos = 0; (pos < length) && ((first_buffer[pos] == second_buffer[pos]) == kind); pos ++);
return pos;
}
int check_runs (const char * data, unsigned length) {
unsigned pos, cmp;
if (length < MINIMUM_IPS_RUN) return -1;
for (pos = 0; pos <= (length - MINIMUM_IPS_RUN); pos ++) {
for (cmp = 0; (cmp < MINIMUM_IPS_RUN) && (data[pos] == data[pos + cmp]); cmp ++);
if (cmp >= MINIMUM_IPS_RUN) return pos;
}
return -1;
}
| 34.364706 | 112 | 0.678877 |
5a23da37994c4870b72058d35603a3637fa78156 | 2,147 | h | C | frameworks/entity/plugins/state/dmzEntityPluginAutoRestoreHealth.h | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | 2 | 2015-11-05T03:03:43.000Z | 2017-05-15T12:55:39.000Z | frameworks/entity/plugins/state/dmzEntityPluginAutoRestoreHealth.h | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | frameworks/entity/plugins/state/dmzEntityPluginAutoRestoreHealth.h | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | #ifndef DMZ_ENTITY_PLUGIN_AUTO_RESTORE_HEALTH_DOT_H
#define DMZ_ENTITY_PLUGIN_AUTO_RESTORE_HEALTH_DOT_H
#include <dmzObjectObserverUtil.h>
#include <dmzRuntimeLog.h>
#include <dmzRuntimePlugin.h>
#include <dmzRuntimeTimeSlice.h>
#include <dmzTypesHashTableHandleTemplate.h>
namespace dmz {
class EntityPluginAutoRestoreHealth :
public Plugin,
public TimeSlice,
public ObjectObserverUtil {
public:
//! \cond
EntityPluginAutoRestoreHealth (const PluginInfo &Info, Config &local);
~EntityPluginAutoRestoreHealth ();
// Plugin Interface
virtual void update_plugin_state (
const PluginStateEnum State,
const UInt32 Level);
virtual void discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr);
// TimeSlice Interface
virtual void update_time_slice (const Float64 TimeDelta);
// Object Observer Interface
virtual void destroy_object (const UUID &Identity, const Handle ObjectHandle);
virtual void update_object_scalar (
const UUID &Identity,
const Handle ObjectHandle,
const Handle AttributeHandle,
const Float64 Value,
const Float64 *PreviousValue);
protected:
struct HealthStruct {
const Handle ObjectHandle;
Float64 timer;
HealthStruct (const Handle TheObjectHandle) :
ObjectHandle (TheObjectHandle),
timer (0.0) {;}
};
void _init (Config &local);
Log _log;
HashTableHandleTemplate<HealthStruct> _objTable;
Float64 _healRate;
Float64 _maxHealth;
Float64 _healthIncrease;
Handle _healthAttrHandle;
//! \endcond
private:
EntityPluginAutoRestoreHealth ();
EntityPluginAutoRestoreHealth (const EntityPluginAutoRestoreHealth &);
EntityPluginAutoRestoreHealth &operator= (const EntityPluginAutoRestoreHealth &);
};
};
#endif // DMZ_ENTITY_PLUGIN_AUTO_RESTORE_HEALTH_DOT_H
| 27.883117 | 90 | 0.649278 |
6e8a1f4fbe9325bb2fb7f6c4d47d36ac977f750b | 806 | c | C | src/a0.c | rybchanivskyi/2D_Game-About-Fish- | 6d7b0896adcec19d236ce25c3736173668ba26de | [
"MIT"
] | 7 | 2019-08-15T11:53:40.000Z | 2019-11-06T13:57:39.000Z | src/a0.c | rybchanivskyi/2D_Game-About-Fish- | 6d7b0896adcec19d236ce25c3736173668ba26de | [
"MIT"
] | 1 | 2020-05-31T05:02:14.000Z | 2020-05-31T05:11:45.000Z | src/a0.c | viacheslavpleshkov/unit-factory-ucode-endgame | 38282684e90340a070144a3f5c19ecf53d7f126f | [
"MIT"
] | null | null | null | #include "header.h"
int A0(int randAy, int Ay0, int Ax0 , int *Ay0r) {
switch(randAy) {
case 0:
mvprintw(Ay0 + 1, Ax0, "<><");
Ax0 = Ax0 - 1;
*Ay0r = Ay0 + 1;
break;
case 1:
mvprintw(Ay0 + 10, Ax0, "<><");
Ax0 = Ax0 -1;
*Ay0r = Ay0 + 10;
break;
case 2:
mvprintw(Ay0 + 25, Ax0, "<><");
Ax0 = Ax0 -1;
*Ay0r = Ay0 + 25;
break;
case 3:
mvprintw(Ay0 - 15, Ax0, "<><");
Ax0 = Ax0 -1;
*Ay0r = Ay0 -15 ;
break;
case 4:
mvprintw(Ay0 + 35, Ax0, "<><");
Ax0 = Ax0 -1;
*Ay0r = Ay0 + 35;
break;
}
refresh();
return Ax0;
}
| 23.705882 | 50 | 0.351117 |
0c620c29f92006fb5ab9d45df02d18886cb431c2 | 448 | c | C | lang/C/random-numbers.c | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 2 | 2017-06-10T14:21:53.000Z | 2017-06-26T18:52:29.000Z | lang/C/random-numbers.c | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C/random-numbers.c | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2018-11-09T22:08:40.000Z | 2018-11-09T22:08:40.000Z | #include <stdlib.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
double drand() /* uniform distribution, (0..1] */
{
return (rand()+1.0)/(RAND_MAX+1.0);
}
double random_normal() /* normal distribution, centered on 0, std dev 1 */
{
return sqrt(-2*log(drand())) * cos(2*M_PI*drand());
}
int main()
{
int i;
double rands[1000];
for (i=0; i<1000; i++)
rands[i] = 1.0 + 0.5*random_normal();
return 0;
}
| 19.478261 | 75 | 0.625 |
673f81f73f846d420659bffd64f49120e3c78235 | 130 | c | C | src/crypto/crypto_ops_builder/ref10CommentedCombined/fe_invert.c | OIEIEIO/ombre-working-old-chain-before-for-test | 4069cc254c3a142b2d40a665185e58130e3ded8d | [
"BSD-3-Clause"
] | 107 | 2018-07-03T19:35:21.000Z | 2022-01-12T09:05:44.000Z | src/crypto/crypto_ops_builder/ref10CommentedCombined/fe_invert.c | OIEIEIO/ombre-working-old-chain-before-for-test | 4069cc254c3a142b2d40a665185e58130e3ded8d | [
"BSD-3-Clause"
] | 87 | 2018-06-25T14:04:20.000Z | 2021-05-31T08:15:47.000Z | src/crypto/crypto_ops_builder/ref10CommentedCombined/fe_invert.c | OIEIEIO/ombre-working-old-chain-before-for-test | 4069cc254c3a142b2d40a665185e58130e3ded8d | [
"BSD-3-Clause"
] | 69 | 2018-06-25T05:41:34.000Z | 2022-03-09T08:57:37.000Z | #include "fe.h"
void fe_invert(fe out, const fe z)
{
fe t0;
fe t1;
fe t2;
fe t3;
int i;
#include "pow225521.h"
return;
}
| 8.666667 | 34 | 0.607692 |
67780c4b65730597e6d66d08e238b44669456823 | 1,511 | c | C | linux-4.14.90-dev/linux-4.14.90/arch/mips/jz4740/reset.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 34 | 2019-07-19T20:44:15.000Z | 2022-03-07T12:09:00.000Z | linux-4.14.90-dev/linux-4.14.90/arch/mips/jz4740/reset.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 5 | 2020-04-04T09:24:09.000Z | 2020-04-19T12:33:55.000Z | linux-4.14.90-dev/linux-4.14.90/arch/mips/jz4740/reset.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 30 | 2018-05-02T08:43:27.000Z | 2022-01-23T03:25:54.000Z | /*
* Copyright (C) 2010, Lars-Peter Clausen <lars@metafoo.de>
*
* 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.
*
* 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.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/pm.h>
#include <asm/reboot.h>
#include <asm/mach-jz4740/base.h>
#include <asm/mach-jz4740/timer.h>
#include "reset.h"
#include "clock.h"
static void jz4740_halt(void)
{
while (1) {
__asm__(".set push;\n"
".set mips3;\n"
"wait;\n"
".set pop;\n"
);
}
}
#define JZ_REG_WDT_DATA 0x00
#define JZ_REG_WDT_COUNTER_ENABLE 0x04
#define JZ_REG_WDT_COUNTER 0x08
#define JZ_REG_WDT_CTRL 0x0c
static void jz4740_restart(char *command)
{
void __iomem *wdt_base = ioremap(JZ4740_WDT_BASE_ADDR, 0x0f);
jz4740_timer_enable_watchdog();
writeb(0, wdt_base + JZ_REG_WDT_COUNTER_ENABLE);
writew(0, wdt_base + JZ_REG_WDT_COUNTER);
writew(0, wdt_base + JZ_REG_WDT_DATA);
writew(BIT(2), wdt_base + JZ_REG_WDT_CTRL);
writeb(1, wdt_base + JZ_REG_WDT_COUNTER_ENABLE);
jz4740_halt();
}
void jz4740_reset_init(void)
{
_machine_restart = jz4740_restart;
_machine_halt = jz4740_halt;
}
| 23.246154 | 75 | 0.725347 |
7be6cd4f2f45de66183e360b33833e2171e32032 | 5,716 | c | C | netbsd/sys/arch/hpcmips/vr/com_vrip.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 1 | 2019-10-15T06:29:32.000Z | 2019-10-15T06:29:32.000Z | netbsd/sys/arch/hpcmips/vr/com_vrip.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | null | null | null | netbsd/sys/arch/hpcmips/vr/com_vrip.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 3 | 2017-01-09T02:15:36.000Z | 2019-10-15T06:30:25.000Z | /* $NetBSD: com_vrip.c,v 1.12 2002/02/02 10:50:09 takemura Exp $ */
/*-
* Copyright (c) 1999 SASAKI Takesi. All rights reserved.
* Copyright (c) 1999, 2002 PocketBSD Project. 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the PocketBSD project
* and its contributors.
* 4. Neither the name of the project 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.
*
*/
#include "opt_kgdb.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/reboot.h>
#include <sys/termios.h>
#include <machine/intr.h>
#include <machine/bus.h>
#include <machine/platid.h>
#include <machine/platid_mask.h>
#include <machine/config_hook.h>
#include <hpcmips/vr/vr.h>
#include <hpcmips/vr/vrcpudef.h>
#include <hpcmips/vr/vripif.h>
#include <hpcmips/vr/vripvar.h>
#include <hpcmips/vr/cmureg.h>
#include <hpcmips/vr/siureg.h>
#include <dev/ic/comvar.h>
#include <dev/ic/comreg.h>
#include "opt_vr41xx.h"
#include <hpcmips/vr/com_vripvar.h>
#include "locators.h"
#define COMVRIPDEBUG
#ifdef COMVRIPDEBUG
int com_vrip_debug = 0;
#define DPRINTF(arg) if (com_vrip_debug) printf arg;
#define VPRINTF(arg) if (com_vrip_debug || bootverbose) printf arg;
#else
#define DPRINTF(arg)
#define VPRINTF(arg) if (bootverbose) printf arg;
#endif
struct com_vrip_softc {
struct com_softc sc_com;
int sc_pwctl;
};
static int com_vrip_probe(struct device *, struct cfdata *, void *);
static void com_vrip_attach(struct device *, struct device *, void *);
static int com_vrip_common_probe(bus_space_tag_t, int);
void vrcmu_init(void);
void vrcmu_supply(int);
void vrcmu_mask(int);
struct cfattach com_vrip_ca = {
sizeof(struct com_vrip_softc), com_vrip_probe, com_vrip_attach
};
int
com_vrip_cndb_attach(bus_space_tag_t iot, int iobase, int rate, int frequency,
tcflag_t cflag, int kgdb)
{
if (!com_vrip_common_probe(iot, iobase))
return (EIO); /* I can't find appropriate error number. */
#ifdef KGDB
if (kgdb)
return (com_kgdb_attach(iot, iobase, rate, frequency, cflag));
else
#endif
return (comcnattach(iot, iobase, rate, frequency, cflag));
}
static int
com_vrip_common_probe(bus_space_tag_t iot, int iobase)
{
bus_space_handle_t ioh;
int rv;
if (bus_space_map(iot, iobase, 1, 0, &ioh)) {
printf(": can't map i/o space\n");
return 0;
}
rv = comprobe1(iot, ioh);
bus_space_unmap(iot, ioh, 1);
return (rv);
}
static int
com_vrip_probe(struct device *parent, struct cfdata *cf, void *aux)
{
struct vrip_attach_args *va = aux;
bus_space_tag_t iot = va->va_iot;
int rv;
DPRINTF(("==com_vrip_probe"));
if (va->va_addr == VRIPIFCF_ADDR_DEFAULT ||
va->va_unit == VRIPIFCF_UNIT_DEFAULT) {
printf(": need addr and intr.\n");
return (0);
}
vrip_power(va->va_vc, va->va_unit, 1);
if (com_is_console(iot, va->va_addr, 0)) {
/*
* We have alredy probed.
*/
rv = 1;
} else {
rv = com_vrip_common_probe(iot, va->va_addr);
}
DPRINTF((rv ? ": found COM ports\n" : ": can't probe COM device\n"));
if (rv) {
va->va_size = COM_NPORTS;
}
return (rv);
}
static void
com_vrip_attach(struct device *parent, struct device *self, void *aux)
{
struct com_vrip_softc *vsc = (void *) self;
struct com_softc *sc = &vsc->sc_com;
struct vrip_attach_args *va = aux;
bus_space_tag_t iot = va->va_iot;
bus_space_handle_t ioh;
vsc->sc_pwctl = sc->sc_dev.dv_cfdata->cf_loc[VRIPIFCF_PWCTL];
DPRINTF(("==com_vrip_attach"));
if (bus_space_map(iot, va->va_addr, 1, 0, &ioh)) {
printf(": can't map bus space\n");
return;
}
sc->sc_iobase = va->va_addr;
sc->sc_iot = iot;
sc->sc_ioh = ioh;
sc->enable = NULL; /* XXX: CMU control */
sc->disable = NULL;
sc->sc_frequency = VRCOM_FREQ;
/* Power management */
vrip_power(va->va_vc, va->va_unit, 1);
/* XXX, locale 'ID' must be need */
config_hook_call(CONFIG_HOOK_POWERCONTROL, vsc->sc_pwctl, (void*)1);
DPRINTF(("Try to attach com.\n"));
com_attach_subr(sc);
DPRINTF(("Establish intr"));
if (!vrip_intr_establish(va->va_vc, va->va_unit, 0, IPL_TTY,
comintr, self)) {
printf("%s: can't map interrupt line.\n", sc->sc_dev.dv_xname);
}
DPRINTF((":return()"));
VPRINTF(("%s: pwctl %d\n", vsc->sc_com.sc_dev.dv_xname, vsc->sc_pwctl));
}
| 28.157635 | 78 | 0.718509 |
bc2b696cbbe1b78e9f127c1a1c897c2309eadd13 | 834 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/PromotionDAOManage.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/PromotionDAOManage.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/PromotionDAOManage.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
@class APCustomStorage;
@protocol PromotionDAOProxy;
@interface PromotionDAOManage : NSObject
{
id <PromotionDAOProxy> _daoProxy;
APCustomStorage *_storage;
}
+ (id)sharedInstace;
@property(retain, nonatomic) APCustomStorage *storage; // @synthesize storage=_storage;
@property(retain, nonatomic) id <PromotionDAOProxy> daoProxy; // @synthesize daoProxy=_daoProxy;
- (void).cxx_destruct;
- (id)getAllSpaceInfos;
- (void)deleteSpaceInfo:(id)arg1;
- (void)updateSpaceObjectInfo:(id)arg1;
- (id)getSpaceInfo:(id)arg1;
- (void)saveSpaceInfoList:(id)arg1;
- (void)saveSpaceInfo:(id)arg1;
- (void)initDataBase;
@end
| 26.0625 | 96 | 0.732614 |
421e84390f7f91ac6191a03f3bb08ed63e5e52e6 | 437 | h | C | linux/Chess/RuleManager.h | bricsi0000000000000/Chess | f1d93153bc7d2f25a117cdc81c69ac23b6407f87 | [
"MIT"
] | null | null | null | linux/Chess/RuleManager.h | bricsi0000000000000/Chess | f1d93153bc7d2f25a117cdc81c69ac23b6407f87 | [
"MIT"
] | null | null | null | linux/Chess/RuleManager.h | bricsi0000000000000/Chess | f1d93153bc7d2f25a117cdc81c69ac23b6407f87 | [
"MIT"
] | null | null | null | #ifndef RULEMANAGER_H
#define RULEMANAGER_H
#include <iostream>
#include <cmath>
#include "Piece.h"
#include "Position.h"
#include "PieceManager.h"
class RuleManager {
private:
~RuleManager();
RuleManager() {}
static RuleManager* instance;
public:
static RuleManager* Instance();
static bool CanStep(std::shared_ptr<Piece> piece, std::shared_ptr<Position> position, PieceManager* piece_manager);
};
#endif // RULEMANAGER_H
| 19.863636 | 117 | 0.748284 |
223ad00b575c23c1ee47857c687e72589e83a879 | 4,487 | c | C | libsrc/_DEVELOPMENT/EXAMPLES/sms/SpaceHawks/screens/screen_title.c | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 640 | 2017-01-14T23:33:45.000Z | 2022-03-30T11:28:42.000Z | libsrc/_DEVELOPMENT/EXAMPLES/sms/SpaceHawks/screens/screen_title.c | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 1,600 | 2017-01-15T16:12:02.000Z | 2022-03-31T12:11:12.000Z | libsrc/_DEVELOPMENT/EXAMPLES/sms/SpaceHawks/screens/screen_title.c | jpoikela/z88dk | 7108b2d7e3a98a77de99b30c9a7c9199da9c75cb | [
"ClArtistic"
] | 215 | 2017-01-17T10:43:03.000Z | 2022-03-23T17:25:02.000Z | #include <stdbool.h> //for true/false
#include <stddef.h> //for null
#include <arch/sms/SMSlib.h>
#include "../s8/joy.h"
#include "../s8/rastercolor.h"
#include "../s8/vdp.h"
#include "../game/game_hud.h"
#include "../game/game_setup.h"
#include "../game/game_text.h"
#include "../game/game_sound.h"
#include "../resource.h"
#include "screenManager.h"
/*************************
*
* Draw one of the two title screen
* Reset setup (ready for next game)
* Auto jump to hiscore if no input after end of SW theme (20sec)
* 1 to 1 player mode
* 2 to 2 players mode, on SMS
* then move to level select screen
*
*
* Cool stuff :
* => some rows need another color.
* On Genny, I would use several of the 4 available pals but here, raster is the key
*
* Sound : infamous Star Wars theme ripoff !
*
* Todo : More GG version title (perhaps 1 only, not 2)
*
*************************/
#define DELAY 20*50 //20 seconds because of sw theme length
#define DELAY_MIN 30 //wait at least 1/2 second before exiting
static int delayCounter;
static bool done = false;
static u8 titleID = 0;
static void jumpBack()
{
setCurrentScreen(HISCORE_SCREEN);
}
static void launchGame()
{
//reset id
titleID = 0;
currentPlayer = gameSetup.player1;
gameSetup.difficulty = 0;
setCurrentScreen(SELECT_SCREEN);
}
//player1 select if 1 or 2 players mode
//2 players mode could be done with 1 or 2 pads
//in case of 2 pads, it's up to players to avoid playing at the same time
//not perfect but....
static void joyPressed(unsigned char joy, unsigned int pressed, unsigned int state)
{
if (delayCounter < DELAY_MIN) return;
#ifndef TARGET_GG
if (pressed & PORT_A_KEY_2) // PORT_B_KEY_1)
{
gameSetup.nbPlayers = 2;
done = true;
return;
}
#endif
if (pressed & PORT_A_KEY_1)
{
gameSetup.nbPlayers = 1;
done = true;
}
}
static void titleInit( )
{
done = false;
delayCounter = 0;
SMS_displayOff();
setup_reset();
TEXT_loadFontDouble(0);
VDP_loadSpritePalette(shawks_pal_bin);
#ifndef TARGET_GG
hud_load();
hud_refresh(); //call it right now, it won't change on loop
#endif
VDP_loadBGPalette(shawks_pal_bin);
rastercolor_init();
rastercolor_fill(shawks_pal_bin, 1);
if (titleID == 1)
{
//green
#ifdef TARGET_GG
TEXT_drawTextDouble("S P A C E", TILE_X(1), TILE_Y(6));
TEXT_drawTextDouble("H A W K S", TILE_X(5), TILE_Y(8));
rastercolor_setRowColor(TILE_Y(6), shawks_pal_bin, 7);
rastercolor_setRowColor(TILE_Y(8), shawks_pal_bin, 7);
//white
rastercolor_setRowColor(TILE_Y(18-1-1), shawks_pal_bin, 9);
#else
TEXT_drawTextDouble("S P A C E", 1, 10);
TEXT_drawTextDouble("H A W K S", 5, 12);
rastercolor_setRowColor(10, shawks_pal_bin, 7);
rastercolor_setRowColor(12, shawks_pal_bin, 7);
//white
rastercolor_setRowColor(22, shawks_pal_bin, 9);
#endif
}
else
{
//yellow
#ifdef TARGET_GG
TEXT_drawTextDouble("Space Hawks", TILE_X((20-11)/2), TILE_Y(4));
TEXT_drawTextDouble("S.Francis 84", TILE_X(2), TILE_Y(10));
TEXT_drawTextDouble("SpritesMind 16", TILE_X(2) , TILE_Y(12));
rastercolor_setRowColor( TILE_Y(4), shawks_pal_bin, 2);
rastercolor_setRowColor( TILE_Y(10), shawks_pal_bin, 2);
rastercolor_setRowColor( TILE_Y(12), shawks_pal_bin, 2);
//red
rastercolor_setRowColor(TILE_Y(18-1-1), shawks_pal_bin, 4);
#else
TEXT_drawTextDouble("Space Hawks", TILE_X(5), 8);
TEXT_drawTextDouble("S.Francis 84", TILE_X(1), 13);
TEXT_drawTextDouble("SpritesMind 16", TILE_X(1) , 15);
rastercolor_setRowColor( 8, shawks_pal_bin, 2);
rastercolor_setRowColor(13, shawks_pal_bin, 2);
rastercolor_setRowColor(15, shawks_pal_bin, 2);
//red
rastercolor_setRowColor(22, shawks_pal_bin, 4);
#endif
}
//white or red
#ifdef TARGET_GG
TEXT_drawTextDouble("Press 1", TILE_X(1+(20-7)/2), TILE_Y(18-1-1));
#else
TEXT_drawTextDouble("Press 1 or 2", TILE_X(4), TILE_Y(22));
#endif
JOY_init();
JOY_setPressedCallback(&joyPressed);
rastercolor_start();
SMS_displayOn();
titleID++;
titleID%=2;
sound_playTheme( );
}
static void titleUpdate( )
{
rastercolor_vint();
if (done)
{
launchGame();
return;
}
//nothing to draw on VBlank here
//just update sound
sound_update( );
JOY_update();
delayCounter++;
if ( delayCounter == DELAY)
{
jumpBack();
delayCounter = 0;
}
}
static void titleClose( )
{
sound_reset();
}
gameScreen titleScreen =
{
TITLE_SCREEN,
&titleInit,
&titleUpdate,
NULL,
&rastercolor_hint,
&titleClose
};
| 21.265403 | 84 | 0.689325 |
e82cc1e812afd9697318ea8f009cf5ae42e3400f | 2,677 | h | C | MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/SpeechPlugin.h | microsoft/Microsoft-OpenXR-Unreal | e7a21e859e2797d5881f3e5b383a22c0d960ec10 | [
"MIT"
] | 105 | 2020-11-24T17:24:36.000Z | 2022-03-31T05:33:24.000Z | MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/SpeechPlugin.h | fieldsJacksonG/Microsoft-OpenXR-Unreal | fccb12a31070bab0d45e8e948f809e6dbdde5937 | [
"MIT"
] | 20 | 2021-02-06T16:08:34.000Z | 2022-03-10T15:07:30.000Z | MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/SpeechPlugin.h | fieldsJacksonG/Microsoft-OpenXR-Unreal | fccb12a31070bab0d45e8e948f809e6dbdde5937 | [
"MIT"
] | 36 | 2020-11-26T15:14:50.000Z | 2022-03-30T21:34:42.000Z | // Copyright (c) 2020 Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#if PLATFORM_WINDOWS || PLATFORM_HOLOLENS
#include "OpenXRCommon.h"
#include "OpenXRCore.h"
#include "MicrosoftOpenXR.h"
#include "HeadMountedDisplayTypes.h"
#include "GameFramework/PlayerInput.h"
#include "GameFramework/PlayerController.h"
#include "GameFramework/InputSettings.h"
#include "UObject/NameTypes.h"
#include "UObject/UObjectGlobals.h"
#include "Async/Async.h"
#include "Windows/AllowWindowsPlatformTypes.h"
#include "Windows/AllowWindowsPlatformAtomics.h"
#include "Windows/PreWindowsApi.h"
#include <unknwn.h>
#include <winrt/Windows.Media.SpeechRecognition.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include "Windows/PostWindowsApi.h"
#include "Windows/HideWindowsPlatformAtomics.h"
#include "Windows/HideWindowsPlatformTypes.h"
#if SUPPORTS_REMOTING
#include "openxr_msft_holographic_remoting.h "
#include "openxr_msft_remoting_speech.h"
#endif
namespace MicrosoftOpenXR
{
class FSpeechPlugin : public IOpenXRExtensionPlugin
{
public:
void Register();
void Unregister();
bool GetOptionalExtensions(TArray<const ANSICHAR*>& OutExtensions) override;
const void* OnCreateSession(XrInstance InInstance, XrSystemId InSystem, const void* InNext) override;
const void* OnBeginSession(XrSession InSession, const void* InNext) override;
void OnEvent(XrSession InSession, const XrEventDataBaseHeader* InHeader) override;
void OnEndPlay();
void AddKeywords(TArray<FKeywordInput> KeywordsToAdd);
void RemoveKeywords(TArray<FString> KeywordsToRemove);
private:
winrt::Windows::Media::SpeechRecognition::SpeechRecognizer SpeechRecognizer = nullptr;
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Media::SpeechRecognition::SpeechRecognitionCompilationResult> CompileConstraintsAsyncOperation;
winrt::Windows::Foundation::IAsyncAction SessionStartAction;
winrt::event_token ResultsGeneratedToken;
std::vector<winrt::hstring> Keywords;
TMap<FString, FKey> KeywordMap;
APlayerController* GetPlayerController();
void RegisterKeyword(FKey Key, FString Keyword);
void CallSpeechCallback(FKey InKey);
void StartSpeechRecognizer();
void StopSpeechRecognizer();
XrSession Session;
// Remoting
#if SUPPORTS_REMOTING
PFN_xrInitializeRemotingSpeechMSFT xrInitializeRemotingSpeechMSFT;
PFN_xrRetrieveRemotingSpeechRecognizedTextMSFT xrRetrieveRemotingSpeechRecognizedTextMSFT;
#endif
bool bIsRemotingSpeechExtensionEnabled = false;
void RegisterSpeechCommandsWithRemoting();
};
} // namespace MicrosoftOpenXR
#endif //PLATFORM_WINDOWS || PLATFORM_HOLOLENS
| 31.494118 | 157 | 0.809862 |
0f06dc385daa40386333f53c2e74d681d33ddc99 | 14,441 | c | C | test-core.c | data-respons-solutions/libnvram | 6924f5136f45679d8fb3d87f2cd5d49628626cfe | [
"MIT"
] | null | null | null | test-core.c | data-respons-solutions/libnvram | 6924f5136f45679d8fb3d87f2cd5d49628626cfe | [
"MIT"
] | null | null | null | test-core.c | data-respons-solutions/libnvram | 6924f5136f45679d8fb3d87f2cd5d49628626cfe | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <inttypes.h>
#include "libnvram.h"
#include "test-common.h"
static int test_libnvram_header_size()
{
const uint32_t required = 24;
if (libnvram_header_len() != required) {
printf("libnvram_header_len != %u\n", required);
return 1;
}
return 0;
}
static int test_libnvram_validate_header()
{
const uint8_t test_section[] = {
0xb4, 0x41, 0x2c, 0xb3, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00,
0x78, 0x97, 0xbf, 0xef, 0x04, 0xca, 0x55, 0x4d,
};
struct libnvram_header hdr;
int r = libnvram_validate_header(test_section, sizeof(test_section), &hdr);
if (r) {
printf("libnvram_validate_header: %d\n", r);
return 1;
}
if (hdr.type != LIBNVRAM_TYPE_LIST) {
printf("header wrong type returned\n");
return 1;
}
if (hdr.user != 16) {
printf("header wrong user returned\n");
return 1;
}
if (hdr.len != 39) {
printf("header wrong data_len returned\n");
return 1;
}
if (hdr.crc32 != 0xefbf9778) {
printf("header wrong data_crc32 returned\n");
return 1;
}
if (hdr.hdr_crc32 != 0x4d55ca04) {
printf("header wrong header_crc32 returned\n");
return 1;
}
return 0;
}
static int test_libnvram_validate_header_empty_data()
{
const uint8_t test_section[] = {
0xb4, 0x41, 0x2c, 0xb3, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x27, 0xb4, 0x55
};
struct libnvram_header hdr;
int r = libnvram_validate_header(test_section, sizeof(test_section), &hdr);
if (r) {
printf("libnvram_validate_header: %d\n", r);
return 1;
}
if (hdr.type != LIBNVRAM_TYPE_LIST) {
printf("header wrong type returned\n");
return 1;
}
if (hdr.user != 0) {
printf("header wrong user returned\n");
return 1;
}
if (hdr.len != 0) {
printf("header wrong data_len returned\n");
return 1;
}
if (hdr.crc32 != 0) {
printf("header wrong data_crc32 returned\n");
return 1;
}
if (hdr.hdr_crc32 != 0x55b42703) {
printf("header wrong header_crc32 returned\n");
return 1;
}
return 0;
}
static int test_libnvram_validate_header_corrupt_crc()
{
const uint8_t test_section[] = {
0xb4, 0x41, 0x2c, 0xb3, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00,
0x78, 0x97, 0xbf, 0xef, 0x01, 0x02, 0x03, 0x04,
};
struct libnvram_header hdr;
int r = libnvram_validate_header(test_section, sizeof(test_section), &hdr);
if (r != -LIBNVRAM_ERROR_CRC) {
printf("libnvram_validate_header: no crc error\n");
return 1;
}
return 0;
}
static int test_libnvram_validate_header_wrong_magic()
{
const uint8_t test_section[] = {
0x01, 0x02, 0x03, 0x04, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00,
0x78, 0x97, 0xbf, 0xef, 0xcf, 0x7b, 0x28, 0x51,
};
struct libnvram_header hdr;
int r = libnvram_validate_header(test_section, sizeof(test_section), &hdr);
if (r != -LIBNVRAM_ERROR_INVALID) {
printf("libnvram_validate_header: no invalid error\n");
return 1;
}
return 0;
}
static int test_libnvram_validate_data()
{
struct libnvram_header hdr;
hdr.user = 16;
hdr.len = 39;
hdr.crc32 = 0x6c9dd729;
const uint8_t test_section[] = {
0x05, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x61, 0x62, 0x63,
0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x05,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x54,
0x45, 0x53, 0x54, 0x32, 0x64, 0x65, 0x66
};
int r = libnvram_validate_data(test_section, sizeof(test_section), &hdr);
if (r) {
printf("libnvram_validate_data: %d\n", r);
return 1;
}
return 0;
}
static int test_libnvram_validate_data_crc_corrupt()
{
struct libnvram_header hdr;
hdr.user = 16;
hdr.len = 39;
hdr.crc32 = 0x6c9dd729;
const uint8_t test_section[] = {
0x05, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x61, 0x62, 0x63,
0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x05,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x54,
0x45, 0x53, 0x54, 0x32, 0x64, 0x65, 0x67
};
int r = libnvram_validate_data(test_section, sizeof(test_section), &hdr);
if (!r) {
printf("libnvram_validate_data no error\n");
return 1;
}
return 0;
}
static int test_libnvram_validate_data_entry_corrupt()
{
struct libnvram_header hdr;
hdr.user = 16;
hdr.len = 39;
hdr.crc32 = 0x5cc70915;
const uint8_t test_section[] = {
0x05, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x61, 0x62, 0x63,
0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x05,
0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x54,
0x45, 0x53, 0x54, 0x32, 0x64, 0x65, 0x66
};
int r = libnvram_validate_data(test_section, sizeof(test_section), &hdr);
if (!r) {
printf("libnvram_validate_data no error\n");
return 1;
}
return 0;
}
static int test_libnvram_deserialize()
{
struct libnvram_header hdr;
hdr.type = LIBNVRAM_TYPE_LIST;
hdr.len = 39;
const uint8_t test_section[] = {
0x05, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x61, 0x62, 0x63,
0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x05,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x54,
0x45, 0x53, 0x54, 0x32, 0x64, 0x65, 0x66
};
struct libnvram_entry entry1;
fill_entry(&entry1, "TEST1", "abcdefghij");
struct libnvram_entry entry2;
fill_entry(&entry2, "TEST2", "def");
struct libnvram_list *list = NULL;
int r = libnvram_deserialize(&list, test_section, sizeof(test_section), &hdr);
if (r) {
printf("libnvram_section_deserialize failed: %d\n", r);
goto error_exit;
}
if (!list) {
printf("list empty\n");
goto error_exit;
}
if (entrycmp(list->entry, &entry1)) {
printf("entry1 wrong\n");
goto error_exit;
}
if (entrycmp(list->next->entry, &entry2)) {
printf("entry2 wrong\n");
goto error_exit;
}
destroy_libnvram_list(&list);
return 0;
error_exit:
destroy_libnvram_list(&list);
return 1;
}
static int test_libnvram_deserialize_single()
{
struct libnvram_header hdr;
hdr.type = LIBNVRAM_TYPE_LIST;
hdr.len = 25;
const uint8_t test_section[] = {
0x06, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x00, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a,
0x00
};
struct libnvram_entry entry1;
const char* key = "TEST1";
const char* value = "abcdefghij";
entry1.key = (uint8_t*) key;
entry1.key_len = strlen(key) + 1;
entry1.value = (uint8_t*) value;
entry1.value_len = strlen(value) + 1;
struct libnvram_list *list = NULL;
int r = libnvram_deserialize(&list, test_section, sizeof(test_section), &hdr);
if (r) {
printf("libnvram_section_deserialize failed: %d\n", r);
goto error_exit;
}
if (!list) {
printf("list empty\n");
goto error_exit;
}
if (entrycmp(list->entry, &entry1)) {
printf("entry1 wrong\n");
goto error_exit;
}
destroy_libnvram_list(&list);
return 0;
error_exit:
destroy_libnvram_list(&list);
return 1;
}
static int test_libnvram_deserialize_empty_data()
{
struct libnvram_header hdr;
hdr.type = LIBNVRAM_TYPE_LIST;
hdr.len = 0;
struct libnvram_list *list = NULL;
const uint8_t test_section[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00
};
int r = libnvram_deserialize(&list, test_section, sizeof(test_section), &hdr);
if (r) {
printf("libnvram_section_deserialize failed: %d\n", r);
goto error_exit;
}
if (list) {
printf("list not empty\n");
goto error_exit;
}
return 0;
error_exit:
destroy_libnvram_list(&list);
return 1;
}
static int test_libnvram_deserialize_wrong_type()
{
struct libnvram_header hdr;
hdr.type = UINT8_MAX;
hdr.len = 25;
const uint8_t test_section[] = {
0x06, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x00, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a,
0x00
};
struct libnvram_list *list = NULL;
int r = libnvram_deserialize(&list, test_section, sizeof(test_section), &hdr);
if (r != -LIBNVRAM_ERROR_INVALID) {
printf("libnvram_section_deserialize failed: no invalid error\n");
goto error_exit;
}
destroy_libnvram_list(&list);
return 0;
error_exit:
destroy_libnvram_list(&list);
return 1;
}
static int test_libnvram_serialize_size()
{
struct libnvram_entry entry1;
fill_entry(&entry1, "TEST1", "abcdefghij");
struct libnvram_list *list = NULL;
int r = libnvram_list_set(&list, &entry1);
if (r) {
printf("libnvram_list_set: %d\n", r);
goto error_exit;
}
const uint32_t required = 47;
uint32_t size = libnvram_serialize_size(list, LIBNVRAM_TYPE_LIST);
if (size != required) {
printf("returned %u != %u\n", size, required);
goto error_exit;
}
destroy_libnvram_list(&list);
return 0;
error_exit:
destroy_libnvram_list(&list);
return 1;
}
static int test_libnvram_serialize_size_empty_data()
{
struct libnvram_list *list = NULL;
const uint32_t required = 24;
uint32_t size = libnvram_serialize_size(list, LIBNVRAM_TYPE_LIST);
if (size != required) {
printf("returned %u != %u\n", size, required);
goto error_exit;
}
return 0;
error_exit:
return 1;
}
static int test_libnvram_serialize()
{
struct libnvram_header hdr;
hdr.user = 16;
hdr.type = LIBNVRAM_TYPE_LIST;
const uint8_t test_section[] = {
0xb4, 0x41, 0x2c, 0xb3, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00,
0x29, 0xd7, 0x9d, 0x6c, 0x9b, 0xa2, 0x0a, 0x25,
0x05, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x61, 0x62, 0x63,
0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x05,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x54,
0x45, 0x53, 0x54, 0x32, 0x64, 0x65, 0x66
};
struct libnvram_entry entry1;
fill_entry(&entry1, "TEST1", "abcdefghij");
struct libnvram_entry entry2;
fill_entry(&entry2, "TEST2", "def");
struct libnvram_list *list = NULL;
int r = libnvram_list_set(&list, &entry1);
if (r) {
printf("libnvram_list_set failed: %d\n", r);
goto error_exit;
}
r = libnvram_list_set(&list, &entry2);
if (r) {
printf("libnvram_list_set failed: %d\n", r);
goto error_exit;
}
uint8_t buf[sizeof(test_section)];
const uint32_t size = sizeof(test_section);
const uint32_t bytes = libnvram_serialize(list, buf, size, &hdr);
if (bytes != size) {
printf("libnvram_serialize: returned %u != %u\n", bytes, size);
goto error_exit;
}
if (hdr.len != 39) {
printf("hdr.len: %u != %u\n", hdr.len, 39);
goto error_exit;
}
if (hdr.user != 16) {
printf("hdr.user: %u != %u\n", hdr.user, 16);
goto error_exit;
}
if (hdr.crc32 != 0x6c9dd729) {
printf("hdr.crc32: %04x != %04x\n", hdr.crc32, 0x6c9dd729);
goto error_exit;
}
if (hdr.hdr_crc32 != 0x250aa29b) {
printf("hdr.hdr_crc32: %04x != %04x\n", hdr.hdr_crc32, 0x250aa29b);
goto error_exit;
}
if (memcmp(test_section, buf, size) != 0) {
printf("buf != test_section\n");
goto error_exit;
}
destroy_libnvram_list(&list);
return 0;
error_exit:
destroy_libnvram_list(&list);
return 1;
}
static int test_libnvram_serialize_empty_data()
{
struct libnvram_header hdr;
hdr.user = 16;
hdr.type = LIBNVRAM_TYPE_LIST;
const uint8_t test_section[] = {
0xb4, 0x41, 0x2c, 0xb3, 0x10, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xcd, 0xef, 0x4d, 0xa7
};
struct libnvram_list *list = NULL;
uint32_t size = sizeof(test_section);
uint8_t buf[size];
uint32_t bytes = libnvram_serialize(list, buf, size, &hdr);
if (bytes != size) {
printf("libnvram_serialize: returned %u != %u\n", bytes, size);
goto error_exit;
}
if (hdr.len != 0) {
printf("hdr.len: %u != %u\n", hdr.len, 0);
goto error_exit;
}
if (hdr.user != 16) {
printf("hdr.user: %u != %u\n", hdr.user, 16);
goto error_exit;
}
if (hdr.crc32 != 0x00000000) {
printf("hdr.crc32: %04x != %04x\n", hdr.crc32, 0x00000000);
goto error_exit;
}
if (hdr.hdr_crc32 != 0xa74defcd) {
printf("hdr.hdr_crc32: %04x != %04x\n", hdr.hdr_crc32, 0xa74defcd);
goto error_exit;
}
if (memcmp(test_section, buf, size) != 0) {
printf("buf != test_section\n");
goto error_exit;
}
destroy_libnvram_list(&list);
return 0;
error_exit:
destroy_libnvram_list(&list);
return 1;
}
static int test_iterator()
{
struct libnvram_header hdr;
hdr.user = 16;
hdr.len = 39;
hdr.crc32 = 0x6c9dd729;
const uint8_t test_section[] = {
0x05, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x54, 0x45, 0x53, 0x54, 0x31, 0x61, 0x62, 0x63,
0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x05,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x54,
0x45, 0x53, 0x54, 0x32, 0x64, 0x65, 0x66
};
uint8_t *begin = libnvram_it_begin(test_section, sizeof(test_section), &hdr);
if (begin != test_section) {
printf("libnvram_it_begin not pointing to start of data\n");
goto error_exit;
}
uint8_t *end = libnvram_it_end(test_section, sizeof(test_section), &hdr);
if (end != test_section + sizeof(test_section)) {
printf("libnvram_it_end not pointing to end of data\n");
goto error_exit;
}
uint8_t* it = begin;
struct libnvram_entry entry1;
fill_entry(&entry1, "TEST1", "abcdefghij");
struct libnvram_entry entry;
libnvram_it_deref(it, &entry);
if (entrycmp(&entry, &entry1)) {
printf("libnvram_it_deref: 1st entry wrong\n");
goto error_exit;
}
it = libnvram_it_next(it);
struct libnvram_entry entry2;
fill_entry(&entry2, "TEST2", "def");
libnvram_it_deref(it, &entry);
if (entrycmp(&entry, &entry2)) {
printf("libnvram_it_deref: 2nd entry wrong\n");
goto error_exit;
}
it = libnvram_it_next(it);
if (it != end) {
printf("libnvram_it_next: did not end\n");
goto error_exit;
}
return 0;
error_exit:
return 1;
}
struct test test_array[] = {
ADD_TEST(test_libnvram_header_size),
ADD_TEST(test_libnvram_validate_header),
ADD_TEST(test_libnvram_validate_header_empty_data),
ADD_TEST(test_libnvram_validate_header_corrupt_crc),
ADD_TEST(test_libnvram_validate_header_wrong_magic),
ADD_TEST(test_libnvram_validate_data),
ADD_TEST(test_libnvram_validate_data_crc_corrupt),
ADD_TEST(test_libnvram_validate_data_entry_corrupt),
ADD_TEST(test_libnvram_deserialize),
ADD_TEST(test_libnvram_deserialize_single),
ADD_TEST(test_libnvram_deserialize_empty_data),
ADD_TEST(test_libnvram_deserialize_wrong_type),
ADD_TEST(test_libnvram_serialize_size),
ADD_TEST(test_libnvram_serialize_size_empty_data),
ADD_TEST(test_libnvram_serialize),
ADD_TEST(test_libnvram_serialize_empty_data),
ADD_TEST(test_iterator),
{NULL, NULL},
};
| 23.329564 | 79 | 0.691434 |
45031c3862ff803302fcba0c9ab0e9f0fe6a58ec | 37 | h | C | iRemeber/Pods/Headers/Private/WCDB/os_wcdb.h | cclovett/iRemeberM | ca7ecf9aa2a20156c638e23e4859e10d9bd2bb54 | [
"MIT"
] | 1,208 | 2016-01-28T05:21:36.000Z | 2022-03-30T11:50:00.000Z | Pods/Headers/Private/WCDB/os_wcdb.h | zhaijunyu/TLChat | 9a1ec8b623356813a9179750f9f3ca2112d52ecd | [
"MIT"
] | 55 | 2016-03-04T11:18:34.000Z | 2021-10-21T07:37:59.000Z | Pods/Headers/Private/WCDB/os_wcdb.h | zhaijunyu/TLChat | 9a1ec8b623356813a9179750f9f3ca2112d52ecd | [
"MIT"
] | 423 | 2016-02-15T13:47:07.000Z | 2022-03-10T09:07:44.000Z | ../../../WCDB/sqlcipher/src/os_wcdb.h | 37 | 37 | 0.648649 |
451b1fe6cd46e5c80b119e684abd2c17135212ea | 258 | c | C | examples/gdb/test2.c | lanahuong/dubrayn.github.io | fd78edb38442966395161cfcf9dfd9b464703ddd | [
"MIT"
] | 7 | 2019-04-12T07:46:05.000Z | 2022-03-30T06:11:47.000Z | examples/gdb/test2.c | lanahuong/dubrayn.github.io | fd78edb38442966395161cfcf9dfd9b464703ddd | [
"MIT"
] | 3 | 2018-03-05T20:35:50.000Z | 2022-03-28T13:09:44.000Z | examples/gdb/test2.c | lanahuong/dubrayn.github.io | fd78edb38442966395161cfcf9dfd9b464703ddd | [
"MIT"
] | 10 | 2017-10-04T07:05:51.000Z | 2020-12-15T12:08:32.000Z | #include "stdlib.h"
#include "stdio.h"
// new function
int addition(int a, int b)
{
return a + b;
}
#define SIZE 3
int main(int argc, char **argv)
{
for (int i = 0; i < SIZE; i++)
{
printf("i=%d i+3=%d\n", i, addition(i, 3));
}
return 0;
}
| 12.285714 | 47 | 0.550388 |
ba53081ee856496eda803f419de9d540784d222b | 1,049 | h | C | src/Engine/sithTemplate.h | MacSourcePorts/OpenJKDF2 | 4e129d1429ff549fbf95945d5675865a154aabde | [
"0BSD"
] | null | null | null | src/Engine/sithTemplate.h | MacSourcePorts/OpenJKDF2 | 4e129d1429ff549fbf95945d5675865a154aabde | [
"0BSD"
] | null | null | null | src/Engine/sithTemplate.h | MacSourcePorts/OpenJKDF2 | 4e129d1429ff549fbf95945d5675865a154aabde | [
"0BSD"
] | null | null | null | #ifndef _SITHTEMPLATE_H
#define _SITHTEMPLATE_H
#include "types.h"
#include "globals.h"
#define sithTemplate_Startup_ADDR (0x004DD880)
#define sithTemplate_Shutdown_ADDR (0x004DD8A0)
#define sithTemplate_New_ADDR (0x004DD8C0)
#define sithTemplate_GetEntryByIdx_ADDR (0x004DD970)
#define sithTemplate_Load_ADDR (0x004DD9B0)
#define sithTemplate_OldNew_ADDR (0x004DDB00)
#define sithTemplate_OldFree_ADDR (0x004DDCE0)
#define sithTemplate_FreeWorld_ADDR (0x004DDDB0)
#define sithTemplate_GetEntryByName_ADDR (0x004DDE50)
#define sithTemplate_CreateEntry_ADDR (0x004DDF30)
int sithTemplate_Startup();
void sithTemplate_Shutdown();
int sithTemplate_New(sithWorld *world, unsigned int numTemplates);
sithThing* sithTemplate_GetEntryByIdx(int idx);
int sithTemplate_Load(sithWorld *world, int a2);
int sithTemplate_OldNew(char *fpath);
void sithTemplate_OldFree();
void sithTemplate_FreeWorld(sithWorld *world);
sithThing* sithTemplate_GetEntryByName(const char *name);
sithThing* sithTemplate_CreateEntry(sithWorld *world);
#endif // _SITHTEMPLATE_H
| 34.966667 | 66 | 0.845567 |
a7f6c5a96b9b6d9702f4ffb0afc02cf60d807455 | 920 | h | C | src/all/frm/core/world/components/LookAtComponent.h | john-chapman/GfxSampleFramework | 6c19d1c7fdf28d8a74884876aa8839b4b982d65a | [
"MIT"
] | 19 | 2017-02-22T21:02:44.000Z | 2021-05-19T16:41:30.000Z | src/all/frm/core/world/components/LookAtComponent.h | john-chapman/GfxSampleFramework | 6c19d1c7fdf28d8a74884876aa8839b4b982d65a | [
"MIT"
] | 68 | 2016-11-14T17:48:54.000Z | 2021-11-08T13:41:06.000Z | src/all/frm/core/world/components/LookAtComponent.h | john-chapman/GfxSampleFramework | 6c19d1c7fdf28d8a74884876aa8839b4b982d65a | [
"MIT"
] | 7 | 2017-05-05T17:49:02.000Z | 2020-12-31T06:51:13.000Z | #pragma once
#include "Component.h"
namespace frm {
////////////////////////////////////////////////////////////////////////////////
// LookAtComponent
////////////////////////////////////////////////////////////////////////////////
FRM_COMPONENT_DECLARE(LookAtComponent)
{
public:
static void Update(Component** _from, Component** _to, float _dt, World::UpdatePhase _phase);
void setTargetNode(GlobalNodeReference& _nodeRef);
private:
GlobalNodeReference m_targetNode; // If set, world space position is the target.
vec3 m_offset; // Offset from the node position, or target if node isn't set.
static void OnNodeShutdown(SceneNode* _node, void* _component);
bool postInitImpl() override;
void shutdownImpl() override;
bool editImpl() override;
bool serializeImpl(Serializer& _serializer_) override;
bool isStatic() override { return false; }
};
} // namespace frm
| 27.878788 | 97 | 0.6 |
f1e547ef6b4c21c576f45edd53e743da1459b57f | 373 | h | C | SDL2Sandbox/SDL2Sandbox/Renderers/BaseRenderer.h | playdeezgames/SDL2Sandbox | bd71595f6b890d00fdf91341b467d1cd9fe755c5 | [
"MIT"
] | null | null | null | SDL2Sandbox/SDL2Sandbox/Renderers/BaseRenderer.h | playdeezgames/SDL2Sandbox | bd71595f6b890d00fdf91341b467d1cd9fe755c5 | [
"MIT"
] | null | null | null | SDL2Sandbox/SDL2Sandbox/Renderers/BaseRenderer.h | playdeezgames/SDL2Sandbox | bd71595f6b890d00fdf91341b467d1cd9fe755c5 | [
"MIT"
] | null | null | null | #pragma once
#include "..\Common\Application.h"
#include "..\Managers\RomFontManager.h"
class BaseRenderer : public tggd::common::Renderer
{
private:
SDL_Renderer* renderer;
const RomFontManager& romFontManager;
protected:
SDL_Renderer* GetMainRenderer() const;
const RomFontManager& GetRomFont() const;
public:
BaseRenderer(SDL_Renderer*, const RomFontManager&);
};
| 23.3125 | 52 | 0.77748 |
24cce1f9479ac5f7b2b3147a0f8a112b2cb9708f | 8,816 | c | C | mon/mons_handlers.c | janetuk/trust_router | 2f4ae52389bf44238b4b45c6818152c17c37c34a | [
"BSD-3-Clause"
] | 2 | 2015-05-21T19:15:17.000Z | 2016-03-29T22:47:32.000Z | mon/mons_handlers.c | janetuk/trust_router | 2f4ae52389bf44238b4b45c6818152c17c37c34a | [
"BSD-3-Clause"
] | 2 | 2015-03-09T15:26:20.000Z | 2016-03-17T13:13:46.000Z | mon/mons_handlers.c | janetuk/trust_router | 2f4ae52389bf44238b4b45c6818152c17c37c34a | [
"BSD-3-Clause"
] | 2 | 2016-03-17T11:18:02.000Z | 2017-11-07T10:20:10.000Z | /*
* Copyright (c) 2018, JANET(UK)
* 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 JANET(UK) nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/* Handlers for monitoring requests */
#include <glib.h>
#include <tr_debug.h>
#include <mon_internal.h>
#include <mons_handlers.h>
/* Static Prototypes */
static int dispatch_entry_matches(MONS_DISPATCH_TABLE_ENTRY *e, MON_CMD command, MON_OPT_TYPE opt_type);
static MONS_HANDLER_FUNC *mons_find_handler(MONS_INSTANCE *mons, MON_CMD cmd, MON_OPT_TYPE opt_type);
static void request_helper(void *element, void *data);
struct request_helper_data {
MON_CMD command;
MON_OPT_TYPE opt_type;
json_t *payload; /* json object to add responses to */
GArray *results;
};
struct handler_result {
MON_OPT_TYPE opt_type; /* what opt type set this? */
MON_RC rc; /* what was its result code? */
json_t *json_data; /* what data, if any, is it returning? */
};
/**
* Call the appropriate handler for a request
*
* TODO: report errors from handlers
*
* @return a MON_RESP structure or null if there was a processing error
*/
MON_RESP *mons_handle_request(TALLOC_CTX *mem_ctx, MONS_INSTANCE *mons, MON_REQ *req)
{
MON_RESP *resp = NULL;
json_t *payload = NULL;
struct request_helper_data cookie = {0};
size_t ii = 0;
tr_debug("mons_handle_request: Handling a request");
/* Start off by allocating our response with a generic error message */
resp = mon_resp_new(mem_ctx,
MON_RESP_ERROR,
"error processing request",
NULL);
if (resp == NULL) {
/* we can't respond, just return */
tr_crit("mons_handle_request: Error allocating response structure.");
goto cleanup;
}
/* Now get a JSON object for our return payload */
payload = json_object();
if (payload == NULL) {
tr_crit("mons_handle_request: Error allocating response payload.");
goto cleanup; /* This will return the generic error message set earlier */
}
/* Now call handlers */
cookie.command = req->command;
cookie.results = g_array_new(FALSE, TRUE, sizeof(struct handler_result));
if (mon_req_opt_count(req) == 0) {
/* call every handler that matches the command */
cookie.opt_type = OPT_TYPE_ANY;
g_ptr_array_foreach(mons->handlers, request_helper, &cookie);
} else {
/* call only those handlers that match an option */
for (ii=0; ii < mon_req_opt_count(req); ii++) {
cookie.opt_type = mon_req_opt_index(req, ii)->type;
/* Loop over all handlers - we know we can only have one match for each opt type */
g_ptr_array_foreach(mons->handlers, request_helper, &cookie);
}
}
/* We now have an array of results in cookie.results. If any of these failed, return an error. */
tr_debug("mons_handle_request: Examining %d handler results", cookie.results->len);
resp->code = MON_RESP_SUCCESS; /* tentatively set this to success */
for (ii=0; ii < cookie.results->len; ii++) {
struct handler_result *this = &g_array_index(cookie.results, struct handler_result, ii);
if (this->rc != MON_SUCCESS) {
tr_debug("mons_handle_request: Result %d was an error.", ii);
resp->code = MON_RESP_ERROR;
}
/* add the JSON response even if there was an error */
if (this->json_data) {
tr_debug("mons_handle_request: Result %d returned JSON data.", ii);
json_object_set_new(payload, mon_opt_type_to_string(this->opt_type), this->json_data);
}
}
if (resp->code == MON_RESP_SUCCESS) {
if (mon_resp_set_message(resp, "success") == 0) {
/* Failed to set the response message to success - fail ironically, don't send
* an inconsistent response. */
tr_crit("mons_handle_request: Error setting response message to 'success'.");
goto cleanup;
}
} else {
/* Failed - send a response indicating that the overall command succeeded */
if (mon_resp_set_message(resp, "request processed but an error occurred") == 0) {
tr_crit("mons_handle_request: Error setting response message after a handler error.");
goto cleanup;
}
}
/* Attach the accumulated payload to the response */
if (json_object_size(payload) > 0) {
tr_debug("mons_handle_request: Attaching payload to response.");
mon_resp_set_payload(resp, payload);
}
tr_debug("mons_handle_request: Successfully processed request.");
cleanup:
if (payload)
json_decref(payload);
if (cookie.results)
g_array_free(cookie.results, TRUE);
return resp;
}
/**
* Register a handler for a command/option combination
*
* @param mons
* @param cmd
* @param opt_type
* @param f
* @param cookie
* @return
*/
MON_RC mons_register_handler(MONS_INSTANCE *mons,
MON_CMD cmd,
MON_OPT_TYPE opt_type,
MONS_HANDLER_FUNC *f,
void *cookie)
{
MONS_DISPATCH_TABLE_ENTRY *entry = NULL;
if (mons_find_handler(mons, cmd, opt_type) != NULL) {
return MON_ERROR;
}
/* Put these in the mons talloc context so we don't have to muck about with
* a free function for the GPtrArray */
entry = talloc(mons, MONS_DISPATCH_TABLE_ENTRY);
if (entry == NULL) {
return MON_NOMEM;
}
entry->command = cmd;
entry->opt_type = opt_type;
entry->handler = f;
entry->cookie = cookie;
g_ptr_array_add(mons->handlers, entry);
return MON_SUCCESS;
}
/**
* Two table entries match if none of the commands or opt_types are unknown,
* if the commands match, and if the opt types either match or at least one is
* OPT_TYPE_ANY.
*
* No comparison of the handler pointer is included.
*
* @return 1 if the two match, 0 if not
*/
static int dispatch_entry_matches(MONS_DISPATCH_TABLE_ENTRY *e,
MON_CMD command,
MON_OPT_TYPE opt_type)
{
if ((command == MON_CMD_UNKNOWN) || (opt_type == OPT_TYPE_UNKNOWN))
return 0; /* request is invalid */
if ((e->command == MON_CMD_UNKNOWN) || (e->opt_type == OPT_TYPE_UNKNOWN))
return 0; /* e1 is invalid */
if (e->command != command)
return 0; /* commands do not match */
if (e->opt_type == opt_type)
return 1; /* exact match */
if ( (e->opt_type == OPT_TYPE_ANY) || (opt_type == OPT_TYPE_ANY) )
return 1; /* one is a wildcard */
return 0; /* commands matched but opt_types did not */
}
static MONS_HANDLER_FUNC *mons_find_handler(MONS_INSTANCE *mons, MON_CMD cmd, MON_OPT_TYPE opt_type)
{
guint index;
for (index=0; index < mons->handlers->len; index++) {
if (dispatch_entry_matches(g_ptr_array_index(mons->handlers, index), cmd, opt_type))
return g_ptr_array_index(mons->handlers, index);
}
return NULL;
}
/**
* This calls every request handler that matches a command/opt_type,
* gathering their results.
*
* @param element
* @param data
*/
static void request_helper(void *element, void *data)
{
MONS_DISPATCH_TABLE_ENTRY *entry = talloc_get_type_abort(element, MONS_DISPATCH_TABLE_ENTRY);
struct request_helper_data *helper_data = data;
struct handler_result result = {0};
if (dispatch_entry_matches(entry, helper_data->command, helper_data->opt_type)) {
result.rc = entry->handler(entry->cookie, &(result.json_data));
result.opt_type = entry->opt_type;
g_array_append_val(helper_data->results, result);
}
}
| 33.907692 | 104 | 0.690222 |
2ab2cf88b69d15060997873f72d8055e5d9ac66a | 1,766 | h | C | source/kernel.h | mgowanlock/gpu_lomb_scargle | a99dd11e49a8e72620dd926b8e37a42d7bf996c6 | [
"MIT"
] | 4 | 2021-05-11T07:51:50.000Z | 2021-10-31T21:25:51.000Z | source/kernel.h | mgowanlock/gpu_lomb_scargle | a99dd11e49a8e72620dd926b8e37a42d7bf996c6 | [
"MIT"
] | null | null | null | source/kernel.h | mgowanlock/gpu_lomb_scargle | a99dd11e49a8e72620dd926b8e37a42d7bf996c6 | [
"MIT"
] | null | null | null | #include "structs.h"
#include <math.h>
//Only include parameters file if we're not creating the shared library
#ifndef PYTHON
#include "params.h"
#endif
__global__ void lombscarglegpuonethread(DTYPE * x, DTYPE * y, DTYPE * freqs, unsigned int * sizexy, unsigned int * sizefreqs, DTYPE * pgram);
__global__ void lombscargleFindMaxPowers(struct lookupObj * objectLookup, DTYPE * pgram, unsigned int * sizefreqs, DTYPE * periodsList, DTYPE * maxPower);
__forceinline__ __device__ void parReductionMaximumPowerinSM(DTYPE maxPowerForComputingPeriod[], unsigned int maxPowerIdxForComputingPeriod[]);
__global__ void lombscargleBatch(DTYPE * x, DTYPE * y, struct lookupObj * objectLookup, DTYPE * pgram, DTYPE * foundPeriod, const double minFreq, const double maxFreq, const unsigned int numFreqs);
__global__ void lombscargleBatchSM(DTYPE * x, DTYPE * y, struct lookupObj * objectLookup, DTYPE * pgram, DTYPE * foundPeriod, const double minFreq, const double maxFreq, const unsigned int numFreqs);
__global__ void lombscargleOneObject(DTYPE * x, DTYPE * y, DTYPE * pgram, const unsigned int sizeData, const double minFreq, const double maxFreq, const unsigned int numFreqs);
__global__ void lombscargleOneObjectSM(DTYPE * x, DTYPE * y, DTYPE * pgram, const unsigned int sizeData, const double minFreq, const double maxFreq, const unsigned int numFreqs);
__global__ void lombscargleBatchError(DTYPE * x, DTYPE * y, DTYPE * dy, struct lookupObj * objectLookup, DTYPE * pgram, DTYPE * foundPeriod,
const double minFreq, const double maxFreq, const unsigned int numFreqs);
__global__ void lombscargleOneObjectError(DTYPE * x, DTYPE * y, DTYPE * dy, DTYPE * pgram, const unsigned int sizeData, const double minFreq, const double maxFreq, const unsigned int numFreqs); | 92.947368 | 200 | 0.785391 |
a4b4a0fb3668416310af22d09933e16558cce9cd | 5,269 | h | C | src/Router/RouterImp.h | lsqtzj/DCache | 29af38f55422556ec4e00f45a4f77212a46f0047 | [
"BSD-3-Clause"
] | 735 | 2019-04-10T10:00:52.000Z | 2022-03-17T06:28:53.000Z | src/Router/RouterImp.h | lsqtzj/DCache | 29af38f55422556ec4e00f45a4f77212a46f0047 | [
"BSD-3-Clause"
] | 67 | 2019-04-10T10:25:41.000Z | 2022-03-20T03:41:50.000Z | src/Router/RouterImp.h | lsqtzj/DCache | 29af38f55422556ec4e00f45a4f77212a46f0047 | [
"BSD-3-Clause"
] | 186 | 2019-04-10T10:18:22.000Z | 2022-03-10T06:39:42.000Z | /**
* Tencent is pleased to support the open source community by making DCache available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
#ifndef __ROUTERIMP_H__
#define __ROUTERIMP_H__
#include "Router.h"
#include "RouterServer.h"
#include "RouterShare.h"
#include "global.h"
#include "servant/Application.h"
using namespace tars;
using namespace std;
using namespace DCache;
class DbHandle;
namespace DCache
{
class Transfer;
}
class RouterImp : public Router
{
public:
RouterImp() = default;
virtual ~RouterImp() = default;
virtual void initialize();
virtual void destroy(){};
public:
virtual tars::Int32 getRouterInfo(const string &moduleName,
PackTable &packTable,
tars::TarsCurrentPtr current);
virtual tars::Int32 getRouterInfoFromCache(const string &moduleName,
PackTable &packTable,
tars::TarsCurrentPtr current);
virtual tars::Int32 getTransRouterInfo(const string &moduleName,
tars::Int32 &transInfoListVer,
vector<TransferInfo> &transferingInfoList,
PackTable &packTable,
tars::TarsCurrentPtr current);
virtual tars::Int32 getVersion(const std::string &moduleName, tars::TarsCurrentPtr current);
virtual tars::Int32 getRouterVersion(const string &moduleName,
tars::Int32 &version,
tars::TarsCurrentPtr current);
virtual tars::Int32 getRouterVersionBatch(const vector<string> &moduleList,
map<string, tars::Int32> &mapModuleVersion,
tars::TarsCurrentPtr current);
virtual tars::Int32 heartBeatReport(const string &moduleName,
const string &groupName,
const string &serverName,
tars::TarsCurrentPtr current);
virtual tars::Int32 getModuleList(vector<string> &moduleList, tars::TarsCurrentPtr current);
virtual tars::Int32 recoverMirrorStat(const string &moduleName,
const string &groupName,
const string &mirrorIdc,
string &err,
tars::TarsCurrentPtr current);
virtual tars::Int32 switchByGroup(const string &moduleName,
const string &groupName,
bool bForceSwitch,
tars::Int32 iDifBinlogTime,
string &err,
tars::TarsCurrentPtr current);
virtual tars::Int32 getIdcInfo(const string &moduleName,
const MachineInfo &machineInfo,
IDCInfo &idcInfo,
tars::TarsCurrentPtr current);
virtual tars::Int32 serviceRestartReport(const string &moduleName,
const string &groupName,
tars::TarsCurrentPtr current);
virtual tars::Bool procAdminCommand(const string &command,
const string ¶ms,
string &result,
tars::TarsCurrentPtr current);
private:
int sendHeartBeat(const std::string &serverName);
// 更新Router Master的Prx
int updateMasterPrx();
// 当前机器是否是主机
bool isMaster() const;
int queryGroupHeartBeatInfo(const string &moduleName,
const string &groupName,
string &errMsg,
GroupHeartBeatInfo **info);
int queryMirrorInfo(const string &moduleName,
const string &groupName,
const string &mirrorIdc,
string &errMsg,
vector<string> **idcList);
private:
std::shared_ptr<DbHandle> _dbHandle; // 数据库操作的句柄
map<string, string> _cityToIDC; // idc_city到idc的映射
std::string _masterRouterObj; // Router master的OBJ字符串
RouterPrx _prx; // 和Router master通信的proxy
std::string _selfObj; // Router本机的obj
};
#endif // __ROUTERIMP_H__
| 40.844961 | 96 | 0.541279 |
2baee0ebfeaa41cd69306a6a3970e72e7bab717c | 551 | h | C | libhwsec/overalls/overalls_api.h | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | libhwsec/overalls/overalls_api.h | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | libhwsec/overalls/overalls_api.h | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LIBHWSEC_OVERALLS_OVERALLS_API_H_
#define LIBHWSEC_OVERALLS_OVERALLS_API_H_
#include "libhwsec/hwsec_export.h"
#include "libhwsec/overalls/overalls.h"
namespace hwsec {
namespace overalls {
// Returns the singleton of |Overalls| instance.
HWSEC_EXPORT Overalls* GetOveralls();
} // namespace overalls
} // namespace hwsec
#endif // LIBHWSEC_OVERALLS_OVERALLS_API_H_
| 26.238095 | 73 | 0.785844 |
0097625b8d26cbf5b98044e3907099a471ee93cd | 400 | h | C | DiscuzQ_Mobile/DiscuzQ/Classes/Library/PRScaleAlert/DZScaleView.h | webersongao/DiscuzQ_iOS | 71ee9bdbcce2fcadc18e1916febcea8d3470e704 | [
"Apache-2.0"
] | 27 | 2020-04-05T14:02:58.000Z | 2021-09-13T02:14:12.000Z | DiscuzQ_Mobile/DiscuzQ/Classes/Library/PRScaleAlert/DZScaleView.h | webersongao/DiscuzQ_iOS | 71ee9bdbcce2fcadc18e1916febcea8d3470e704 | [
"Apache-2.0"
] | null | null | null | DiscuzQ_Mobile/DiscuzQ/Classes/Library/PRScaleAlert/DZScaleView.h | webersongao/DiscuzQ_iOS | 71ee9bdbcce2fcadc18e1916febcea8d3470e704 | [
"Apache-2.0"
] | 6 | 2020-07-18T11:36:11.000Z | 2022-01-30T06:09:48.000Z | //
// DZScaleView.h
// DiscuzQ
// 联系作者:微信: ChinaMasker gao@btbk.org
// Github :https://github.com/webersongao/DiscuzQ_iOS
// Created by WebersonGao on 2018/9/28.
//
#import <UIKit/UIKit.h>
@interface DZScaleView : UIView
@property(nonatomic,copy) void (^dismissBlock)(void); /// 移除弹窗后执行的block
@property(nonatomic,copy) void (^touchAlertblock)(CGPoint Point); /// 点击到弹窗上时 返回tap位置的block
@end
| 23.529412 | 91 | 0.7225 |
7ab7b246f437bd2b21bc31ab64bbb838c48eb942 | 2,068 | h | C | qqtw/qqheaders7.2/QQSMItemElementVideoViewForQZone.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 5 | 2018-02-20T14:24:17.000Z | 2020-08-06T09:31:21.000Z | qqtw/qqheaders7.2/QQSMItemElementVideoViewForQZone.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 1 | 2020-06-10T07:49:16.000Z | 2020-06-12T02:08:35.000Z | qqtw/qqheaders7.2/QQSMItemElementVideoViewForQZone.h | onezens/SmartQQ | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "QQSMItemElementPictureView.h"
@class NSString, QQAIOTinyVideoCellPlayView, QQURLRichMsgHelper, QQVideoCircleProgressView, UIActivityIndicatorView, UIImageView;
@interface QQSMItemElementVideoViewForQZone : QQSMItemElementPictureView
{
int _networkState;
_Bool _isWithCheckVideoSourceTag;
long long _videoPlayStatus;
int _xo;
_Bool _hasCheckVideoSource;
NSString *_source;
NSString *_srcUrl;
UIActivityIndicatorView *_indicator;
UIImageView *_statusView;
QQURLRichMsgHelper *_urlRichMsgHelper;
QQAIOTinyVideoCellPlayView *_playView;
NSString *_videoSavePath;
QQVideoCircleProgressView *_progressView;
long long _videoPlayStyle;
}
- (void)alertView:(id)arg1 clickedButtonAtIndex:(long long)arg2;
- (void)dealloc;
- (void)handleTapVideo;
@property(nonatomic) _Bool hasCheckVideoSource; // @synthesize hasCheckVideoSource=_hasCheckVideoSource;
@property(retain, nonatomic) UIActivityIndicatorView *indicator; // @synthesize indicator=_indicator;
- (id)initWithFrame:(struct CGRect)arg1;
- (void)openUrl;
- (void)playVideo;
@property(retain, nonatomic) QQAIOTinyVideoCellPlayView *playView; // @synthesize playView=_playView;
- (void)prepareForReuse;
@property(retain, nonatomic) QQVideoCircleProgressView *progressView; // @synthesize progressView=_progressView;
- (void)setQQSMItemElementBase:(id)arg1;
@property(copy, nonatomic) NSString *source; // @synthesize source=_source;
@property(copy, nonatomic) NSString *srcUrl; // @synthesize srcUrl=_srcUrl;
@property(retain, nonatomic) UIImageView *statusView; // @synthesize statusView=_statusView;
@property(retain, nonatomic) QQURLRichMsgHelper *urlRichMsgHelper; // @synthesize urlRichMsgHelper=_urlRichMsgHelper;
@property(nonatomic) long long videoPlayStyle; // @synthesize videoPlayStyle=_videoPlayStyle;
@property(copy, nonatomic) NSString *videoSavePath; // @synthesize videoSavePath=_videoSavePath;
@end
| 41.36 | 129 | 0.788685 |
1aacbd4a30a5f8b03f1ac6573131e3fa09e47be0 | 5,261 | c | C | mdsshr/mds_dsc_string.c | consorzio-rfx/mdsplus | 81cdbfc759d92b101d84328e6eb7b3a6e6e22103 | [
"BSD-2-Clause"
] | null | null | null | mdsshr/mds_dsc_string.c | consorzio-rfx/mdsplus | 81cdbfc759d92b101d84328e6eb7b3a6e6e22103 | [
"BSD-2-Clause"
] | null | null | null | mdsshr/mds_dsc_string.c | consorzio-rfx/mdsplus | 81cdbfc759d92b101d84328e6eb7b3a6e6e22103 | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <mdsdescrip.h>
#include <usagedef.h>
#include <STATICdef.h>
#include <mdsshr.h>
#define checkString(S) if (id==S) return #S ;
#define checkAltStr(A, S) if (id==A) return #S ;
EXPORT char *MdsDtypeString(const unsigned char id)
{
STATIC_THREADSAFE char dtypeString[24]; /* not really threadsafe but should be ok */
checkString(DTYPE_MISSING)
checkString(DTYPE_IDENT)
checkString(DTYPE_NID)
checkString(DTYPE_PATH)
checkString(DTYPE_PARAM)
checkString(DTYPE_SIGNAL)
checkString(DTYPE_DIMENSION)
checkString(DTYPE_WINDOW)
checkString(DTYPE_SLOPE)
checkString(DTYPE_FUNCTION)
checkString(DTYPE_CONGLOM)
checkString(DTYPE_RANGE)
checkString(DTYPE_ACTION)
checkString(DTYPE_DISPATCH)
checkString(DTYPE_PROGRAM)
checkString(DTYPE_ROUTINE)
checkString(DTYPE_PROCEDURE)
checkString(DTYPE_METHOD)
checkString(DTYPE_DEPENDENCY)
checkString(DTYPE_CONDITION)
checkString(DTYPE_EVENT)
checkString(DTYPE_WITH_UNITS)
checkString(DTYPE_CALL)
checkString(DTYPE_WITH_ERROR)
checkString(DTYPE_Z)
checkString(DTYPE_BU)
checkString(DTYPE_WU)
checkString(DTYPE_LU)
checkString(DTYPE_QU)
checkString(DTYPE_OU)
checkString(DTYPE_B)
checkString(DTYPE_W)
checkString(DTYPE_L)
checkString(DTYPE_Q)
checkString(DTYPE_O)
checkString(DTYPE_F)
checkString(DTYPE_D)
checkString(DTYPE_G)
checkString(DTYPE_H)
checkString(DTYPE_FC)
checkString(DTYPE_DC)
checkString(DTYPE_GC)
checkString(DTYPE_HC)
checkString(DTYPE_CIT)
checkString(DTYPE_T)
checkString(DTYPE_VT)
checkString(DTYPE_NU)
checkString(DTYPE_NL)
checkString(DTYPE_NLO)
checkString(DTYPE_NR)
checkString(DTYPE_NRO)
checkString(DTYPE_NZ)
checkString(DTYPE_P)
checkString(DTYPE_V)
checkString(DTYPE_VU)
checkString(DTYPE_FS)
checkString(DTYPE_FT)
checkString(DTYPE_FSC)
checkString(DTYPE_FTC)
checkString(DTYPE_ZI)
checkString(DTYPE_ZEM)
checkString(DTYPE_DSC)
checkString(DTYPE_BPV)
checkString(DTYPE_BLV)
checkString(DTYPE_ADT)
checkString(DTYPE_LIST)
checkString(DTYPE_TUPLE)
checkString(DTYPE_DICTIONARY)
checkString(DTYPE_OPAQUE)
sprintf(dtypeString, "DTYPE_?_0x%02X", id);
return (dtypeString);
}
EXPORT char *MdsClassString(const unsigned char id)
{
STATIC_THREADSAFE char classString[24]; /* not really threadsafe but ok */
checkString(CLASS_XD)
checkString(CLASS_XS)
checkString(CLASS_R)
checkString(CLASS_CA)
checkString(CLASS_APD)
checkString(CLASS_S)
checkString(CLASS_D)
checkString(CLASS_A)
checkString(CLASS_P)
checkString(CLASS_SD)
checkString(CLASS_NCA)
checkString(CLASS_VS)
checkString(CLASS_VSA)
checkString(CLASS_UBS)
checkString(CLASS_UBA)
checkString(CLASS_SB)
checkString(CLASS_UBSB)
sprintf(classString, "CLASS_?_0x%02X", id);
return (classString);
}
EXPORT char *MdsUsageString(const unsigned char id)
{
STATIC_THREADSAFE char usageString[24]; /* not really threadsafe but should be ok */
checkString(TreeUSAGE_ANY)
checkString(TreeUSAGE_STRUCTURE)
checkString(TreeUSAGE_ACTION)
checkString(TreeUSAGE_DEVICE)
checkString(TreeUSAGE_DISPATCH)
checkString(TreeUSAGE_NUMERIC)
checkString(TreeUSAGE_SIGNAL)
checkString(TreeUSAGE_TASK)
checkString(TreeUSAGE_TEXT)
checkString(TreeUSAGE_WINDOW)
checkString(TreeUSAGE_AXIS)
checkString(TreeUSAGE_SUBTREE)
checkAltStr(TreeUSAGE_SUBTREE_TOP, TreeUSAGE_SUBTREE)
checkString(TreeUSAGE_COMPOUND_DATA)
sprintf(usageString, "TreeUSAGE_?_0x%02X", id);
return (usageString);
}
| 33.724359 | 86 | 0.73218 |
1ac476000330677a48db7b7de23ba2743a765684 | 466 | h | C | contoso_asset_tracker/trace.h | kartben/contoso_asset_tracker | 23eccb6a6400e8f941ea0c76e9105fbce0cf5f48 | [
"MIT"
] | 2 | 2019-11-01T08:23:17.000Z | 2020-08-10T10:50:21.000Z | contoso_asset_tracker/trace.h | kartben/contoso_asset_tracker | 23eccb6a6400e8f941ea0c76e9105fbce0cf5f48 | [
"MIT"
] | null | null | null | contoso_asset_tracker/trace.h | kartben/contoso_asset_tracker | 23eccb6a6400e8f941ea0c76e9105fbce0cf5f48 | [
"MIT"
] | null | null | null | #ifndef _TRACE_H_
#define _TRACE_H_
#ifdef DEBUG
#define __TRACE__(msg) Serial.println(msg)
#define __TRACEF__(fmt, ...) Serial_printf(fmt, __VA_ARGS__)
#else
#define __TRACE__(msg) {}
#define __TRACEF__(fmt, ...) {}
#endif
#if USE_DISPLAY
#include "./graphics/contoso_display.h"
#ifdef DEBUG
#define __TRACE__(msg) drawMessage(msg)
#define __TRACEF__(fmt, ...) drawMessageF(fmt, __VA_ARGS__)
#endif
#else
#define __REFRESH_DISPLAY__ {}
#endif
#endif | 21.181818 | 61 | 0.73176 |
4f2bd620a3527e62d71d816d12d5c26543ed2c32 | 347 | h | C | utils/dfuse-dfu-util/src/portable.h | multigcs/multigcs | bd37e2a81411474c6adc5a51bfaef64656920fa3 | [
"libpng-2.0"
] | 25 | 2015-03-30T20:19:23.000Z | 2021-12-10T06:18:10.000Z | utils/dfuse-dfu-util/src/portable.h | multigcs/multigcs | bd37e2a81411474c6adc5a51bfaef64656920fa3 | [
"libpng-2.0"
] | null | null | null | utils/dfuse-dfu-util/src/portable.h | multigcs/multigcs | bd37e2a81411474c6adc5a51bfaef64656920fa3 | [
"libpng-2.0"
] | 16 | 2015-01-02T22:43:29.000Z | 2020-04-22T08:44:36.000Z |
#ifndef PORTABLE_H
#define PORTABLE_H
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef HAVE_USLEEP
# include <unistd.h>
# define milli_sleep(msec) usleep(1000 * (msec))
#elif defined HAVE_WINDOWS_H
# define milli_sleep(msec) Sleep(msec)
#else
# error "Can't get no sleep! Please report"
#endif /* HAVE_USLEEP */
#endif /* PORTABLE_H */
| 18.263158 | 48 | 0.73487 |
94cf72ace2bb9f815f82117e36d88f0dbd2b95ba | 2,523 | c | C | components/hal_csi/csi2/timer.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | 9 | 2020-05-12T03:01:55.000Z | 2021-08-12T10:22:31.000Z | components/hal_csi/csi2/timer.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | null | null | null | components/hal_csi/csi2/timer.c | 1847123212/YoC-open | f4e20c67256472d863ea6d118e3ecbaa1e879d4a | [
"Apache-2.0"
] | 12 | 2020-04-15T11:37:33.000Z | 2021-09-13T13:19:04.000Z | /*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include "soc.h"
#include "aos/hal/timer.h"
#include "drv/timer.h"
#define CONFIG_TIMER_NUM 4
typedef struct {
csi_timer_t csi_tim_handle;
timer_dev_t *hal_tim_handle;
} timer_handlers_t;
static timer_handlers_t timer_handlers[CONFIG_TIMER_NUM];
typedef struct {
csi_timer_t *csi_tim_handle;
void *arg;
} timer_callback_t;
static void hal_timer_cb_func(csi_timer_t *timer, void *arg)
{
timer_callback_t hal_tim_cb;
hal_tim_cb.csi_tim_handle = timer;
hal_tim_cb.arg = arg;
timer_handlers[timer->dev.idx].hal_tim_handle->config.cb(&hal_tim_cb);
if((uint32_t)arg==TIMER_RELOAD_MANU)
{
csi_timer_stop(timer);
}
}
int32_t hal_timer_init(timer_dev_t *tim)
{
if (!tim) {
return -1;
}
int32_t ret = 0;
ret = csi_timer_init(&timer_handlers[tim->port].csi_tim_handle, tim->port);
if (ret < 0) {
return -1;
}
timer_handlers[tim->port].hal_tim_handle = tim;
csi_timer_attach_callback(&timer_handlers[tim->port].csi_tim_handle, hal_timer_cb_func,(void *)((uint32_t) tim->config.reload_mode));
return 0;
}
/**
* start a hardware timer
*
* @param[in] tim timer device
*
* @return 0 : on success, EIO : if an error occurred with any step
*/
int32_t hal_timer_start(timer_dev_t *tim)
{
if (tim == NULL) {
return -1;
}
return csi_timer_start(&timer_handlers[tim->port].csi_tim_handle, tim->config.period);
}
/**
* stop a hardware timer
*
* @param[in] tim timer device
*
* @return none
*/
void hal_timer_stop(timer_dev_t *tim)
{
if (tim == NULL) {
return;
}
csi_timer_stop(&timer_handlers[tim->port].csi_tim_handle);
}
/**
* change the config of a hardware timer
*
* @param[in] tim timer device
* @param[in] para timer config
*
* @return 0 : on success, EIO : if an error occurred with any step
*/
int32_t hal_timer_para_chg(timer_dev_t *tim, timer_config_t para)
{
if (tim == NULL) {
return -1;
}
return csi_timer_start(&timer_handlers[tim->port].csi_tim_handle, para.period);
}
/**
* De-initialises an TIMER interface, Turns off an TIMER hardware interface
*
* @param[in] tim timer device
*
* @return 0 : on success, EIO : if an error occurred with any step
*/
int32_t hal_timer_finalize(timer_dev_t *tim)
{
if (tim == NULL) {
return -1;
}
csi_timer_uninit(&timer_handlers[tim->port].csi_tim_handle);
return 0;
}
| 20.184 | 137 | 0.663099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.