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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0fc030d38434afa88114e6da61470bfc5e01576d | 457 | h | C | BaseFramework/BaseFramework/ui/home/mine/service/MineService.h | AndRickyChan/BaseFramework | 8a22020329118f88ad99e2d7024f92f8059b560f | [
"Apache-2.0"
] | 1 | 2017-09-06T09:04:30.000Z | 2017-09-06T09:04:30.000Z | BaseFramework/BaseFramework/ui/home/mine/service/MineService.h | AndRickyChan/BaseFramework | 8a22020329118f88ad99e2d7024f92f8059b560f | [
"Apache-2.0"
] | null | null | null | BaseFramework/BaseFramework/ui/home/mine/service/MineService.h | AndRickyChan/BaseFramework | 8a22020329118f88ad99e2d7024f92f8059b560f | [
"Apache-2.0"
] | null | null | null | //
// MineService.h
// BaseFramework
//
// Created by rickychan on 2017/9/11.
// Copyright © 2017年 rickychan. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol MineDelegate <NSObject>
-(void)initDataSuccess:(NSString *)header nickName:(NSString *)nickName;
@end
@interface MineService : NSObject
@property(nonatomic,weak) id<MineDelegate>delegate;
-(id)initWithDelegate:(id<MineDelegate>) delegate;
-(void)shareInitData;
@end
| 17.576923 | 72 | 0.739606 |
a77299466f7930612012787da400ffb091f435e0 | 873 | h | C | app/app_state.h | tomaskrcka/nbiot-gps-asset-tracking | fbcc1f0293076d0fe9d29760116b32c6d3fb2899 | [
"Apache-2.0"
] | null | null | null | app/app_state.h | tomaskrcka/nbiot-gps-asset-tracking | fbcc1f0293076d0fe9d29760116b32c6d3fb2899 | [
"Apache-2.0"
] | 3 | 2019-08-20T09:43:52.000Z | 2020-02-06T21:13:01.000Z | app/app_state.h | tomaskrcka/nbiot-gps-asset-tracking | fbcc1f0293076d0fe9d29760116b32c6d3fb2899 | [
"Apache-2.0"
] | 1 | 2019-12-25T16:54:40.000Z | 2019-12-25T16:54:40.000Z | #ifndef APP_STATE_H
#define APP_STATE_H
#include "../../system/dev/stm32_sleep.h"
#include "config_default.h"
namespace tag12 {
typedef union app_state_data {
struct {
unsigned state : 4; // 4 bits state machine
unsigned log_err_sent : 1; // 1 previous message lost
unsigned last_wokeup_acc: 1; // if the last woke up was by acc
unsigned backup : 25; // just backup, not in use
} bits;
uint32_t intValue;
} AppStateData;
/**
* The class is reponsible to keep the application state
* during the sleeping period
*
*/
class AppState {
public:
AppState(STM32Sleep * const sleep);
AppStateData GetAppStateData();
void SetState(int state);
void SetLogErrSent(bool err);
void SetLastWokeupAcc(bool wokenup);
private:
void StoreAppStateData(const AppStateData & data);
STM32Sleep * const sleep_;
};
} // namespace tag12
#endif
| 20.785714 | 66 | 0.71134 |
68d234b73d554fb4145a06893afc27016e2f2411 | 344 | c | C | aoj/0/AOJ0054.c | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | 1 | 2018-11-12T15:18:55.000Z | 2018-11-12T15:18:55.000Z | aoj/0/AOJ0054.c | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | aoj/0/AOJ0054.c | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | //
// AOJ0054.c
//
//
// Created by n_knuu on 2014/03/01.
//
//
#include <stdio.h>
int main(void) {
int a,b,n,sum,i;
while (scanf("%d %d %d\n",&a,&b,&n)!=EOF) {
sum=0;
a=(a%b)*10;
for (i=0; i<n; i++) {
sum+=a/b;
a=(a%b)*10;
}
printf("%d\n",sum);
}
return 0;
} | 15.636364 | 47 | 0.383721 |
db5f3e0cadd18d9bbddc7db0f1aeacfd95c944c3 | 500 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/torture/pr51528.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/torture/pr51528.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/torture/pr51528.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* { dg-do run } */
/* { dg-options "-fno-early-inlining" } */
extern void abort (void);
union U
{
int i;
_Bool b;
};
_Bool gb;
void __attribute__ ((noinline))
use_bool (union U u)
{
gb = u.b;
}
union U
bar (void)
{
union U u;
u.i = 0xFFFE;
return u;
}
union U __attribute__ ((noinline))
foo (void)
{
union U u,v;
u.b = 1;
use_bool (u);
u = bar ();
return u;
}
int main (int argc, char **argv)
{
union U u = foo ();
if (u.i != 0xFFFE)
abort ();
return 0;
}
| 10.638298 | 42 | 0.544 |
80e3bf13b2b97ed613c4126413bfbde8766dbda4 | 2,075 | h | C | release/src-rt-6.x.4708/linux/linux-2.6.36/include/asm-generic/bitops/le.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 55 | 2015-01-20T00:09:45.000Z | 2021-08-19T05:40:27.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/include/asm-generic/bitops/le.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 1 | 2018-08-21T03:42:06.000Z | 2018-08-21T03:42:06.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/include/asm-generic/bitops/le.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 36 | 2015-02-13T00:58:22.000Z | 2021-08-19T08:08:07.000Z | #ifndef _ASM_GENERIC_BITOPS_LE_H_
#define _ASM_GENERIC_BITOPS_LE_H_
#include <asm/types.h>
#include <asm/byteorder.h>
#define BITOP_WORD(nr) ((nr) / BITS_PER_LONG)
#define BITOP_LE_SWIZZLE ((BITS_PER_LONG-1) & ~0x7)
#if defined(__LITTLE_ENDIAN)
#define generic_test_le_bit(nr, addr) test_bit(nr, addr)
#define generic___set_le_bit(nr, addr) __set_bit(nr, addr)
#define generic___clear_le_bit(nr, addr) __clear_bit(nr, addr)
#define generic_test_and_set_le_bit(nr, addr) test_and_set_bit(nr, addr)
#define generic_test_and_clear_le_bit(nr, addr) test_and_clear_bit(nr, addr)
#define generic___test_and_set_le_bit(nr, addr) __test_and_set_bit(nr, addr)
#define generic___test_and_clear_le_bit(nr, addr) __test_and_clear_bit(nr, addr)
#define generic_find_next_zero_le_bit(addr, size, offset) find_next_zero_bit(addr, size, offset)
#define generic_find_next_le_bit(addr, size, offset) \
find_next_bit(addr, size, offset)
#elif defined(__BIG_ENDIAN)
#define generic_test_le_bit(nr, addr) \
test_bit((nr) ^ BITOP_LE_SWIZZLE, (addr))
#define generic___set_le_bit(nr, addr) \
__set_bit((nr) ^ BITOP_LE_SWIZZLE, (addr))
#define generic___clear_le_bit(nr, addr) \
__clear_bit((nr) ^ BITOP_LE_SWIZZLE, (addr))
#define generic_test_and_set_le_bit(nr, addr) \
test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, (addr))
#define generic_test_and_clear_le_bit(nr, addr) \
test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, (addr))
#define generic___test_and_set_le_bit(nr, addr) \
__test_and_set_bit((nr) ^ BITOP_LE_SWIZZLE, (addr))
#define generic___test_and_clear_le_bit(nr, addr) \
__test_and_clear_bit((nr) ^ BITOP_LE_SWIZZLE, (addr))
extern unsigned long generic_find_next_zero_le_bit(const unsigned long *addr,
unsigned long size, unsigned long offset);
extern unsigned long generic_find_next_le_bit(const unsigned long *addr,
unsigned long size, unsigned long offset);
#else
#error "Please fix <asm/byteorder.h>"
#endif
#define generic_find_first_zero_le_bit(addr, size) \
generic_find_next_zero_le_bit((addr), (size), 0)
#endif /* _ASM_GENERIC_BITOPS_LE_H_ */
| 35.775862 | 96 | 0.78747 |
d5e0bb9f37177713f477d3641a8cff8dab9f5a26 | 409 | h | C | MyCustomUsage/Preprocess/autodeletefile.h | phidra/ULTRA | d3de3dbbbd651ee8279dd605e6d8f73365c81735 | [
"MIT"
] | null | null | null | MyCustomUsage/Preprocess/autodeletefile.h | phidra/ULTRA | d3de3dbbbd651ee8279dd605e6d8f73365c81735 | [
"MIT"
] | null | null | null | MyCustomUsage/Preprocess/autodeletefile.h | phidra/ULTRA | d3de3dbbbd651ee8279dd605e6d8f73365c81735 | [
"MIT"
] | null | null | null | #pragma once
#include <filesystem>
#include <cstdio>
namespace my {
struct AutoDeleteTempFile {
// file path is computed at construction, but no file is created on disk :
inline AutoDeleteTempFile() : file{tmpnam(nullptr)} {}
// attemps to remove file on destruction :
inline ~AutoDeleteTempFile() { std::filesystem::remove(file); }
std::filesystem::path file;
};
} // namespace my
| 21.526316 | 78 | 0.691932 |
cb162aaf44a6037908b6b7891e4ba9f3dfd59f3a | 1,448 | c | C | projects/gate_test/test.c | zevv/red-pitaya-notes | 68bfc2decbf9209f0afa6707344c8a5695a925cf | [
"MIT"
] | 240 | 2015-02-28T19:14:08.000Z | 2022-03-26T13:52:30.000Z | projects/gate_test/test.c | gaintpd/red-pitaya-notes | 63010b6b722bc4ba208f7ed868987feee2ddfc9a | [
"MIT"
] | 402 | 2015-05-08T11:51:32.000Z | 2022-03-22T21:28:43.000Z | projects/gate_test/test.c | gaintpd/red-pitaya-notes | 63010b6b722bc4ba208f7ed868987feee2ddfc9a | [
"MIT"
] | 179 | 2015-01-08T22:53:02.000Z | 2022-03-21T16:42:18.000Z | #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <sys/mman.h>
int main(int argc, char *argv[])
{
int fd, i;
volatile void *cfg, *sts;
volatile uint32_t *wr, *rd;
volatile uint8_t *rst;
volatile uint32_t *freq;
uint32_t buffer;
int16_t value;
if((fd = open("/dev/mem", O_RDWR)) < 0)
{
fprintf(stderr, "Cannot open /dev/mem.\n");
return EXIT_FAILURE;
}
sts = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40000000);
cfg = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40001000);
wr = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40002000);
rd = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40003000);
rst = cfg + 0;
freq = cfg + 4;
*rst &= ~6;
*freq = (uint32_t)floor(25.0 / 125.0 * (1<<30) + 0.5);
*rst |= 1;
*rst &= ~1;
*wr = 32766;
*wr = (uint32_t)floor(0.25 * (1<<30) + 0.5);
*wr = 7-2;
*wr = 5;
*wr = 0;
*wr = 0;
*wr = 3-2;
*wr = 1;
*wr = 32766;
*wr = (uint32_t)floor(0.25 * (1<<30) + 0.5);
*wr = 7-2;
*wr = 5;
*rst |= 4;
*rst |= 2;
sleep(1);
for(i = 0; i < 100; ++i)
{
buffer = *rd;
value = buffer & 0xffff;
printf("%6d %d %d\n", value, (buffer >> 16) & 1, (buffer >> 24) & 1);
}
return EXIT_SUCCESS;
}
| 20.394366 | 92 | 0.584945 |
7ef9546a426a429d63d0f62fb3f385b9bdebb6af | 15,614 | h | C | src/Haplotype.h | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 11 | 2017-06-06T23:02:48.000Z | 2021-08-17T20:13:05.000Z | src/Haplotype.h | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | 1 | 2017-06-06T23:08:05.000Z | 2017-06-07T09:28:08.000Z | src/Haplotype.h | RemiMattheyDoret/SimBit | ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43 | [
"MIT"
] | null | null | null | /*
Author: Remi Matthey-Doret
MIT License
Copyright (c) 2017 Remi Matthey-Doret
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.
*/
class Haplotype // a Haplotype is a whole halotype but can correspond to several independent chromosomes.
{
friend class T56_memoryManager;
private:
std::vector<unsigned char> T1_Alleles; // Type 1 Each bit is a binary site
std::vector<unsigned char> T2_Alleles; // Type 2 Each byte is a locus for which number of mutations are counted.
std::vector<T3type> T3_Alleles; // Type 3 QTLs
// T4 types are tracked with T4Tree
std::vector<uint32_t> T5sel_Alleles; // Type 5 SLimM style. Just like T1 except that only mutations are keeping tracked of
std::vector<uint32_t> T5ntrl_Alleles;
CompressedSortedDeque T6sel_Alleles; // Type 6 is like Type 5 except that it tries to reduce RAM by separating values into prefix and suffix
CompressedSortedDeque T6ntrl_Alleles;
std::vector<T7Gene> T7_Alleles; // Type 7 use for ENTWINE type of development and produce a phenotype on the same space than T3
std::vector<fitnesstype> W_T1;
std::vector<fitnesstype> W_T2;
std::vector<fitnesstype> W_T56;
fitnesstype W_T8=1.0; // This is a bad fix to a problem of construction I could not figure out. I am assuming that all T8 loci start out with wildtype
// No W_T3 as the fitness makes sense for the individual only
std::vector<uint32_t> getT56ntrlTrueHaplotype();
std::vector<uint32_t> getT56selTrueHaplotype();
/*
template<typename T>
void insertEraseAtPositions(
std::vector<T>& x,
std::vector<size_t>& toInsert,
std::vector<size_t>& toErase
);
*/
public:
// Used for T4Tree
// ID is a little bit of a weird attribute because Haplotype does not manage its value but T4Tree and T8Tree do. It will remain uninitialized here.
uint32_t T4ID;
uint32_t T8ID;
void dealWithT8Info(std::pair<T8ID_type, fitnesstype> pair);
ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> T5ntrl_AllelesBegin();
ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> T5ntrl_AllelesEnd();
std::vector<uint32_t>::iterator T5sel_AllelesBegin();
std::vector<uint32_t>::iterator T5sel_AllelesEnd();
ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> T6ntrl_AllelesBegin();
ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> T6ntrl_AllelesEnd();
CompressedSortedDeque::iterator T6sel_AllelesBegin();
CompressedSortedDeque::iterator T6sel_AllelesEnd();
ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> T56ntrl_AllelesBegin(ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> nothing);
ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> T56ntrl_AllelesEnd(ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> nothing);
std::vector<uint32_t>::iterator T56sel_AllelesBegin(std::vector<uint32_t>::iterator& nothing);
std::vector<uint32_t>::iterator T56sel_AllelesEnd(std::vector<uint32_t>::iterator& nothing);
ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> T56ntrl_AllelesBegin(ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> nothing);
ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> T56ntrl_AllelesEnd(ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> nothing);
CompressedSortedDeque::iterator T56sel_AllelesBegin(CompressedSortedDeque::iterator& nothing);
CompressedSortedDeque::iterator T56sel_AllelesEnd(CompressedSortedDeque::iterator& nothing);
ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> T56ntrl_AllelesIterator(ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator> nothing, unsigned value);
std::vector<uint32_t>::iterator T56sel_AllelesIterator(std::vector<uint32_t>::iterator& nothing, unsigned value);
ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> T56ntrl_AllelesIterator(ZipIterator<CompressedSortedDeque, CompressedSortedDeque::iterator> nothing, unsigned value);
CompressedSortedDeque::iterator T56sel_AllelesIterator(CompressedSortedDeque::iterator& nothing, unsigned value);
fitnesstype getW_T1(int fitnessMapIndex);
fitnesstype getW_T2(int fitnessMapIndex);
fitnesstype getW_T56(int fitnessMapIndex);
fitnesstype getW_T8();
void setAllW_T1(fitnesstype w);
void setAllW_T2(fitnesstype w);
void setAllW_T56(fitnesstype w);
void setW_T1(fitnesstype w, int fitnessMapIndex);
void setW_T2(fitnesstype w, int fitnessMapIndex);
void setW_T56(fitnesstype w, int fitnessMapIndex);
void setW_T8(fitnesstype w);
size_t getW_T56_size();
template<typename INT = uint32_t> void removeT7Gene(INT index);
template<typename INT = uint32_t> void duplicateT7Gene(INT index);
void clearT7Genes();
template<typename INT = uint32_t>
unsigned char getT1_char(INT T1_char_index);
template<typename INT = uint32_t>
bool getT1_Allele(const INT T1Locus);
template<typename INT1 = uint32_t, typename INT2 = uint32_t>
bool getT1_Allele(const INT1 char_index, const INT2 bit_index);
template<typename INT = uint32_t>
unsigned char getT2_Allele(const INT char_index);
template<typename INT = uint32_t>
T3type getT3_Allele(const INT index);
template<typename INT = uint32_t>
T7Gene& getT7_Allele(const INT index);
size_t nbT7Genes();
//bool getT56_Allele(const int Locus);
//bool getT5ntrl_Allele(const int Locus);
//bool getT5sel_Allele(const int Locus);
//int getT5ntrl_nthMutation(const int n);
//int getT5sel_nthMutation(const int n);
template<typename valueType, typename INT = uint32_t>
void setT1_Allele(const INT char_index, const INT bit_index, const valueType& value);
template<typename INT = uint32_t>
void setT1_AlleleToOne(INT char_index, INT bit_index);
template<typename INT = uint32_t>
void setT1_AlleleToZero(INT char_index, INT bit_index);
template<typename INT = uint32_t>
void setT1_char(INT T1_char_index, unsigned char& c);
template<typename INT = uint32_t>
void setT1_char(INT T1_char_index, unsigned char&& c);
template<typename INT = uint32_t>
void setT2_Allele(const INT char_index, const unsigned char value);
template<typename INT = uint32_t>
void setT3_Allele(const INT index, const T3type value);
template<typename INT = uint32_t>
void setEntireT5_Allele(std::vector<INT>& t5a);
template<typename INT = uint32_t>
void setT5_Allele(const INT locus, const bool& value);
template<typename INT = uint32_t>
void setT5ntrl_Allele(const INT locus, const bool& value);
template<typename INT = uint32_t>
void setT5sel_Allele(const INT locus, const bool& value);
template<typename INT = uint32_t>
void setT5sel_AlleleToOne(INT locus);
template<typename INT = uint32_t>
void setT5sel_AlleleToZero(INT locus);
template<typename INT = uint32_t>
void setT5sel_AlleleToOne_JustPushBack(INT locus);
template<typename INT = uint32_t>
void setT5ntrl_AlleleToOne(INT locus);
template<typename INT = uint32_t>
void setT5ntrl_AlleleToZero(INT locus);
template<typename INT = uint32_t>
void setT5ntrl_AlleleToOne_JustPushBack(INT locus);
template<typename INT = uint32_t>
void setEntireT6_Allele(std::vector<INT>& t6a);
template<typename INT = uint32_t>
void setT6_Allele(const INT locus, const bool& value);
template<typename INT = uint32_t>
void setT6ntrl_Allele(const INT locus, const bool& value);
template<typename INT = uint32_t>
void setT6sel_Allele(const INT locus, const bool& value);
template<typename INT = uint32_t>
void setT6sel_AlleleToOne(INT locus);
template<typename INT = uint32_t>
void setT6sel_AlleleToZero(INT locus);
template<typename INT = uint32_t>
void setT6sel_AlleleToOne_JustPushBack(INT locus);
template<typename INT = uint32_t>
void setT6ntrl_AlleleToOne(INT locus);
template<typename INT = uint32_t>
void setT6ntrl_AlleleToZero(INT locus);
template<typename INT = uint32_t>
void setT6ntrl_AlleleToOne_JustPushBack(INT locus);
template<typename INT = uint32_t>
void mutateT1_Allele(INT MutPosition, int& Habitat);
template<typename INT = uint32_t>
void toggleT1_Allele(INT byte_index, INT bit_index);
template<typename INT = uint32_t>
void AddMutT2_Allele(INT char_index);
template<typename INT = uint32_t>
void AddMutT2_Allele(INT char_index, int Habitat);
template<typename INT = uint32_t>
void mutateT3_Allele(INT index);
template<typename INTORINTVECTOR = uint32_t>
void mutateT56ntrl_Allele(INTORINTVECTOR MutPosition);
template<typename INTORINTVECTOR = uint32_t>
void mutateT56sel_Allele(INTORINTVECTOR MutPosition, int Habitat);
template<typename INT = uint32_t>
void mutateT5ntrl_Allele(std::vector<INT>& MutPositions);
template<typename INT = uint32_t>
void mutateT5ntrl_Allele(INT MutPosition);
template<typename INT = uint32_t>
void mutateT5sel_Allele(INT MutPosition, int Habitat);
template<typename INT = uint32_t>
void toggleT5ntrl_Allele(INT MutPosition);
template<typename INT = uint32_t>
void toggleT5sel_Allele(INT MutPosition);
template<typename INT = uint32_t>
void mutateT6ntrl_Allele(INT MutPosition);
template<typename INT = uint32_t>
void mutateT6sel_Allele(INT MutPosition, int Habitat);
template<typename INT = uint32_t>
void toggleT6ntrl_Allele(INT MutPosition);
template<typename INT = uint32_t>
void toggleT6sel_Allele(INT MutPosition);
template<typename INT = uint32_t>
void copyIntoT1(INT from, INT to, Haplotype& SourceChromo);
template<typename INT = uint32_t>
void copyIntoT2(INT from, INT to, Haplotype& SourceChromo);
template<typename INT = uint32_t>
void copyIntoT3(INT from, INT to, Haplotype& SourceChromo);
void clearT56Alleles();
template<typename INT = uint32_t>
void copyIntoT56ntrl(INT from, INT to, Haplotype& SourceChromo);
template<typename INT = uint32_t>
void copyIntoT56sel(INT from, INT to, Haplotype& SourceChromo);
void print(bool WithRecDist, std::string& prefix);
void AssertBitSetSize(int T1_nbChars);
Haplotype(std::vector<unsigned char> T1_info, std::vector<unsigned char> T2_info, std::vector<T3type> T3_info, uint32_t t4id, std::vector<uint32_t> T56_info);
Haplotype(const std::vector<unsigned char>& T1_Allel);
Haplotype(const int patch_index,char Abiogenesis, int indHaplo_index);
Haplotype(bool ShouldReadPopFromBinary);
Haplotype(); // default constructor
//Haplotype( Haplotype&& other); // MOVE constructor
Haplotype(const Haplotype& other); // copy constructor
Haplotype& operator=(const Haplotype& other); // copy assignment operator
//Haplotype& operator=(Haplotype&& other); // move assignment operator
void swap(Haplotype& other);
void PrintBinaryFile(OutputFile& file);
int getT3_AllelesSize() //For debug purposes
{
return T3_Alleles.size();
};
bool isFreeFromMutations();
bool isFreeFromMutations(int T1_locusFrom, int T1_locusTo);
/*
std::vector<uint32_t>::const_iterator T5sel_AllelesCBegin();
std::vector<uint32_t>::const_iterator T5sel_AllelesCEnd();
std::vector<uint32_t>::const_iterator T5sel_AllelesCiterator(int locus, std::vector<uint32_t>::const_iterator from);
std::vector<uint32_t>::const_iterator T5sel_AllelesCiterator(int locus);
std::vector<uint32_t>::const_iterator T5ntrl_AllelesCBegin();
std::vector<uint32_t>::const_iterator T5ntrl_AllelesCEnd();
std::vector<uint32_t>::const_iterator T5ntrl_AllelesCiterator(int locus, std::vector<uint32_t>::const_iterator from);
std::vector<uint32_t>::const_iterator T5ntrl_AllelesCiterator(int locus);*/
//int T5_AllelesPosition(int locus, int from);
//int T5_AllelesPosition(int locus);
//int T5_howManyMutations();
void toggleT56ntrlLoci(std::vector<int>& lociToToggle);
//void toggleT56selLoci(std::vector<int>& lociToToggle, int Habitat);
void toggleFromT5ntrl_Allele(int& MutPosition, uint32_t& from);
void toggleFromT6ntrl_Allele(int& MutPosition, uint32_t& blockIndexFrom, uint32_t& fromInBlock);
void toggleFromT5sel_Allele(int& MutPosition, uint32_t& from, int Habitat);
void toggleFromT6sel_Allele(int& MutPosition, uint32_t& blockIndexFrom, uint32_t& fromInBlock, int Habitat);
int getNbT5ntrl();
int getNbT6ntrl();
int getNbT5sel();
int getNbT6sel();
void printT5sel_Alleles();
void printT5ntrl_Alleles();
bool isT5ntrlMutation(int locus);
bool isT5selMutation(int locus);
void printT6sel_Alleles();
void printT6ntrl_Alleles();
bool isT6ntrlMutation(int locus);
bool isT6selMutation(int locus);
void assertT5orderAndUniqueness();
template<typename INT = uint32_t>
void updateFitnessAfterT56Mutation(INT MutPosition, bool isNowFoundInAlleles, int Habitat);
template<typename ITERATOR, typename CONTAINER, typename INT = uint32_t>
char T56finishMutation(ITERATOR& haploP, CONTAINER& container, INT MutPosition);
uint32_t nbT56muts();
uint32_t nbT56muts(int fitnessMapIndex);
// Multiplicity fitness calculator
fitnesstype CalculateT1FitnessMultiplicity(const int& Habitat);
fitnesstype CalculateT2Fitness(const int& Habitat);
fitnesstype CalculateT56FitnessMultiplicity(const int& Habitat);
fitnesstype CalculateT5FitnessMultiplicity(const int& Habitat);
fitnesstype CalculateT6FitnessMultiplicity(const int& Habitat);
fitnesstype CalculateT1FitnessMultiplicityOnSubsetOfLoci(const int& Habitat, const std::vector<int>& LociSet);
fitnesstype CalculateT2FitnessOnSubsetOfLoci(const int& Habitat, const std::vector<int>& LociSet);
template<typename Iterator>
fitnesstype CalculateT56FitnessMultiplicityOnSubsetOfLoci(const int& Habitat, const std::vector<int>& LociSet, Iterator it, Iterator itEnd);
fitnesstype CalculateT56FitnessMultiplicityOnSubsetOfLoci(const int& Habitat, const std::vector<int>& LociSet);
void freeT56Memory();
void shrink_to_fitT56();
T3type sumOfT3Alleles(){return std::accumulate(T3_Alleles.begin(), T3_Alleles.end(), 0);}
};
| 45.654971 | 189 | 0.746638 |
9a1368c1ab3e9fe5304c9d6e3c36922dc64bca95 | 549 | c | C | squantorLibCtests/src/test_memmove.c | Squantor/squantorLibCtests | b12c99f04b3aed8d45f8d91951f029bcd8ce5d75 | [
"MIT"
] | null | null | null | squantorLibCtests/src/test_memmove.c | Squantor/squantorLibCtests | b12c99f04b3aed8d45f8d91951f029bcd8ce5d75 | [
"MIT"
] | null | null | null | squantorLibCtests/src/test_memmove.c | Squantor/squantorLibCtests | b12c99f04b3aed8d45f8d91951f029bcd8ce5d75 | [
"MIT"
] | null | null | null | /*
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2021 Bart Bilos
* For conditions of distribution and use, see LICENSE file
*/
#include <MinUnit.h>
#include <string.h>
MINUNIT_ADD(testMemmoveOverlapLower)
{
static char s[] = "xxxxabcde";
minUnitCheck(memmove(s, s + 4, 5) == s);
minUnitCheck(s[0] == 'a');
minUnitCheck(s[4] == 'e');
minUnitCheck(s[5] == 'b');
}
MINUNIT_ADD(testMemmoveOverlapHigher)
{
static char s[] = "abcdexxxx";
minUnitCheck(memmove(s + 4, s, 5) == s + 4);
minUnitCheck(s[4] == 'a');
}
| 21.96 | 59 | 0.621129 |
625fcf94d8bf3a91a9f03443bd453815601c336a | 4,196 | h | C | inc/uls.h | oivannikov/my_ls | bd7ffdffed802a17e6d07a697200cc16813aa13e | [
"MIT"
] | null | null | null | inc/uls.h | oivannikov/my_ls | bd7ffdffed802a17e6d07a697200cc16813aa13e | [
"MIT"
] | null | null | null | inc/uls.h | oivannikov/my_ls | bd7ffdffed802a17e6d07a697200cc16813aa13e | [
"MIT"
] | null | null | null | #ifndef ULS_H
#define ULS_H
#include <time.h>
#include "libmx.h"
#include <sys/types.h>
#include <dirent.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/acl.h>
#include <sys/xattr.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <grp.h>
#include <pwd.h>
#include <sys/errno.h>
#define MX_HALF_YEAR 15768000
#define MX_MINOR(x) ((x) & 0xFFFFFF)
#define MX_MAJOR(x) (((x) >> 24) & 0xFF)
typedef enum f_errors {
INVALID_ARGV,
INVALID_FLAGS
} t_errors;
typedef struct s_data_const {
time_t time;
char *ful_n;
char *stracl;
char *name;
char *name_c;
char *strrwx;
char *strtime;
char *strlink;
char *strgid;
char *struid;
char *strmaj;
char *strmin;
char *strlinkcount;
char *strbytes;
char *strblocks;
char *strino;
int min;
int maj;
long nsec;
long long ino;
long rdev;
long dev;
long size_bytes;
long link;
long blocks;
struct s_data_const *next;
} t_const;
typedef struct s_sort_list {
t_const *cnst;
struct s_sort_list *next;
} t_sort;
typedef struct s_big_data {
t_const *cnst;
t_sort *sort;
char *strtotal;
char **name_all;
char **file;
int *flags;
char *path;
bool isattyflag;
int colums;
int size;
int size_all;
int width;
int max_len_name;
bool flag_minmaj;
int max_len_uid;
int max_len_gid;
int max_len_bytes;
int max_len_link;
int max_len_min;
int max_len_maj;
int max_len_ino;
int max_len_blocks;
bool acl;
int total;
bool errors;
bool link;
//____________________________________________________//
char **dir_arr;
char *str;
char *dir_name;
} t_data;
void mx_get_file_col(t_const *data_l, t_data *data);
void mx_creat_list(t_sort *gen);
void mx_sort_time(t_sort *general);
void mx_sort_size(t_sort *gen);
void mx_sort_all(t_data *data, t_sort *general);
void mx_sort_revers(t_sort *general, t_data *data);
void mx_many_arguments(t_data *data);
void mx_control_char_name(char **str);
void mx_check_control_char(char ***str);
void mx_get_data(t_data *data, t_const *cnst);
void mx_full_path(t_data *data, t_const *data_l);
void mx_printstr_update(char *str1, char *str2, char *str3,
char *str4, char *str5);
void mx_print_spase(int count);
void mx_sort_my_list(t_sort *gen);
void mx_print_l(t_const *cnst, t_data *data);
void mx_get_flag_l(t_const *cnst, t_data *data);
bool mx_isspecial(t_const *cnst);
bool mx_islink(t_const *cnst);
void mx_get_acl(t_const *cnst);
void mx_get_minmaj(t_const *cnst);
void mx_get_rdev(struct stat st, t_const *cnst);
void mx_get_dev(struct stat st, t_const *cnst);
void mx_get_law(struct stat st, t_const *cnst);
void mx_get_blocks(struct stat st, t_const *cnst);
void mx_get_uid(struct stat st, t_const *cnst);
void mx_get_gid(struct stat st, t_const *cnst);
void mx_get_link(struct stat st, t_const *cnst);
void mx_get_size_bytes(struct stat st, t_const *cnst);
void mx_get_ino(struct stat st, t_const *cnst);
void mx_get_time(struct stat st, t_const *cnst, t_data *data);
void mx_read_link(t_const *cnst);
void mx_get_is(t_const *cnst, t_data *data);
char *mx_itoa_sp(long long number);
void mx_print_to_file(char **file, t_data *data);
void mx_sort_file(char **str, int size);
int mx_size_a(t_data *data);
char **mx_get_result(char **file, t_data *data);
void mx_head_size(t_const *cnst, t_data *data);
int mx_columns();
void mx_print_file(t_data *data);
void mx_num_file(t_const *cnst, t_data *data);
int mx_read_dir(char *dirname, t_data *data);
// Мои
void mx_flags_into_arr(char *s, t_data *app);
void mx_read_flags(char **argv, int argc, t_data *app);
void mx_count_flags_in_str(char **argv, t_data *app, int argc);
int mx_dir_arr(char **argv, int argc, t_data *app);
void mx_printerr(t_errors errors, char s);
void mx_print_error(const char *s);
void mx_check_flags(char *s, t_data *app);
void mx_basic_flags(char *cont, t_data *app, int len);
void mx_flags_for_sort(char *cont, t_data *app);
void mx_other_flags(char *cont, t_data *app);
void mx_printerr_char(char s);
void mx_flags_into_arr(char *s, t_data *app);
//
#endif
| 26.897436 | 63 | 0.714252 |
cd0856113cfe374cb7b7ab619462ac77a7ec6beb | 2,855 | h | C | Test/PKTest/Native/Src/UART/UART.h | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 529 | 2015-03-10T00:17:45.000Z | 2022-03-17T02:21:19.000Z | Test/PKTest/Native/Src/UART/UART.h | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 495 | 2015-03-10T22:02:46.000Z | 2019-05-16T13:05:00.000Z | Test/PKTest/Native/Src/UART/UART.h | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 332 | 2015-03-10T08:04:36.000Z | 2022-03-29T04:18:36.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <tinyhal.h>
#include <usart_decl.h>
#include "..\Log\Log.h"
#ifndef _UART_NMT_
#define _UART_NMT_ 1
#define BUFFER_SIZE 8
#define FlowCtrlNone USART_FLOW_NONE
#define FlowCtrlSW USART_FLOW_SW_IN_EN | USART_FLOW_SW_OUT_EN
#define FlowCtrlHW USART_FLOW_HW_IN_EN | USART_FLOW_HW_OUT_EN
typedef
struct _UART : Log
{
int ComPort; // Com port, begins at 0
int BaudRate; //{1200, 9600, 57600, 115200, 230400, ...};
int Parity;
int Stop; // Stop bit
int Data; // Data bit
int FlowValue;
char XmitBuffer[BUFFER_SIZE];
char RecvBuffer[BUFFER_SIZE];
_UART(int ComNum,
int BaudNum,
int ParityNum,
int StopNum,
int DataNum,
int FlowNum)
{
ComPort = ComNum;
BaudRate = BaudNum;
Parity = ParityNum;
Stop = StopNum;
Data = DataNum;
FlowValue = FlowNum;
InitXmitBuffer();
};
BOOL UART_Transmit(char *, int, int);
BOOL UART_Receive(char *, int, int);
BOOL UARTTest(NMT_STREAM Stream)
{
Log::Result=false;
//
// Initialize the Log object
//
Initialize(Stream);
BeginTest("UART");
if (!USART_Initialize(ComPort, BaudRate, Parity, Stop, Data, FlowValue ))
{
return false;
}
if (UART_Transmit(XmitBuffer,BUFFER_SIZE, 3) &&
UART_Receive(RecvBuffer,BUFFER_SIZE, 3))
{
Log::Result = Validate(BUFFER_SIZE);
}
EndTest(Log::Result);
return Result;
};
INT8 SomeValue(int i)
{
return ((i + 0x80) % 0x100);
}
BOOL Validate(int CountReceived)
{
if (CountReceived > BUFFER_SIZE)
CountReceived = BUFFER_SIZE;
for(INT16 i=0; i<CountReceived; i++)
{
if (RecvBuffer[i] != (char) SomeValue(i) )
{
return false;
}
}
return true;
};
void InitXmitBuffer()
{
//
// Initialize entire buffer in strips of 128-255
//
for(INT16 i=0; i<BUFFER_SIZE; i++)
XmitBuffer[i] = SomeValue(i);
};
} UART;
#endif
| 26.192661 | 201 | 0.442732 |
9f7435c0d7ed40ff553518cab83f3e0a13bfd680 | 7,601 | c | C | qmk_firmware/keyboards/ergodox_ez/keymaps/rmw/keymap-win.c | codextypes/dz60rgb-v2-endgame | a03058b0fc4fdb459692ffa42c8db3f417c73aa0 | [
"MIT"
] | null | null | null | qmk_firmware/keyboards/ergodox_ez/keymaps/rmw/keymap-win.c | codextypes/dz60rgb-v2-endgame | a03058b0fc4fdb459692ffa42c8db3f417c73aa0 | [
"MIT"
] | null | null | null | qmk_firmware/keyboards/ergodox_ez/keymaps/rmw/keymap-win.c | codextypes/dz60rgb-v2-endgame | a03058b0fc4fdb459692ffa42c8db3f417c73aa0 | [
"MIT"
] | null | null | null | #include "rmw.h"
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[QWERTY] = LAYOUT_ergodox( // LEFT HAND
TD(FRBK), KC_1, KC_2, KC_3, KC_4, KC_5, KC_F4,
KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, TO(EDIT),
OSL(EDIT), KC_A, LT(NUMPAD,KC_S), KC_D, LT(FSYM,KC_F), KC_G,
OSM(MOD_LSFT), KC_Z, KC_X, KC_C, KC_V, SFT_T(KC_B), KC_TAB,
TD(CTLAND), OSL(ADJUST), TD(SCAG), TD(TDGUI), TD(ACG),
OS_ALT, OS_CTL ,
KC_ESCAPE,
KC_BSPACE, TD(SHENT), OSL(EDIT),
// RIGHT HAND
KC_F5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_BSPC,
TO(NUMPAD), KC_Y, KC_U, KC_I, KC_O, KC_P, KC_BSLS,
KC_H, LT(JSYM,KC_J), KC_K, KC_L, LT(EDIT,KC_SCLN), KC_QUOTE,
CTL_T(KC_B), KC_N, KC_M, KC_COMM, KC_DOT, LT(MEDIA,KC_SLSH), TD(SHENT),
TD(CAG), TD(TDGUI), KC_LBRC, KC_RBRC, KC_MS_BTN1,
OS_ALT, KC_TAB,
KC_DEL,
KC_CAPS, SFT_T(KC_ENT), KC_SPC),
[NUMPAD] = LAYOUT_ergodox(VRSN, KC_F11, KC_F12, KC_F1, KC_F2, KC_F3, _______,
_______, _______, KC_PGUP, KC_UP, KC_PGDOWN, _______, TO(0),
_______, _______, KC_LEFT, KC_DOWN, KC_RIGHT, _______,
_______, LCTL(KC_Z), LCTL(KC_X), LCTL(KC_C), LCTL(KC_V), LCTL(KC_Y), _______,
_______, _______, _______, _______, _______,
_______, _______, KC_PSCREEN, _______, _______, TO(0),
_______, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, _______,
TO(EDIT), _______, KC_7, KC_8, KC_9, KC_KP_MINUS, _______,
_______, KC_4, KC_5, KC_6, KC_KP_PLUS, _______,
_______, KC_COMM, KC_1, KC_2, KC_3, KC_KP_SLASH, _______,
KC_0, KC_DOT, KC_EQUAL, KC_KP_ASTERISK, _______,
_______, _______, KC_INSERT, TO(EDIT), _______, _______),
[EDIT] = LAYOUT_ergodox(KC_ESCAPE, LALT(LCTL(KC_DELETE)), KC_MS_WH_UP, KC_MS_BTN1, KC_MS_BTN2, _______, _______,
_______, LCTL(S(KC_ESCAPE)), KC_MS_WH_DOWN, LCTL(S(KC_LEFT)), LCTL(S(KC_RIGHT)), _______, TO(NUMPAD),
_______, _______, KC_LEFT, LCTL(KC_LEFT), LCTL(KC_RIGHT), _______,
_______, LCTL(KC_Z), LCTL(KC_X), LCTL(KC_C), LCTL(KC_V), LCTL(KC_Y), _______,
_______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, TO(NUMPAD),
_______, _______, _______, S(KC_UP), _______, _______, KC_DELETE,
TO(0), LCTL(KC_T), KC_PGUP, KC_UP, KC_PGDOWN, KC_PSCREEN, _______,
KC_HOME, KC_LEFT, KC_DOWN, KC_RIGHT, KC_END, _______,
_______, S(KC_HOME), S(KC_LEFT), S(KC_DOWN), S(KC_RIGHT), S(KC_END), _______,
_______, _______, _______, _______, _______,
_______, _______, _______, S(KC_F10), _______, _______),
[FSYM] = LAYOUT_ergodox(_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, KC_TILD, KC_EXLM, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, KC_CIRC, KC_AMPR , KC_ASTR, KC_GRV , _______, _______,
KC_EQUAL, KC_MINUS, KC_UNDS, KC_BSLS, KC_COLON, KC_DQT ,
_______, _______, KC_PLUS , KC_SLSH, KC_PIPE, _______ , _______,
_______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______),
[JSYM] = LAYOUT_ergodox(_______, _______, _______, _______, _______, _______, _______,
_______, KC_GRV, KC_AT , KC_LCBR, KC_RCBR, _______, _______,
_______, KC_HASH, KC_DLR , KC_LPRN, KC_RPRN, KC_LEFT,
_______, KC_PERC, KC_CIRC, KC_LBRACKET, KC_RBRACKET, _______, _______,
_______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, KC_QUES, KC_SLSH, KC_COLON, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______),
[MEDIA] = LAYOUT_ergodox(_______, _______, KC_MS_BTN4, _______, KC_MS_BTN5, _______, _______,
_______, KC_MS_WH_UP, KC_MS_WH_LEFT, KC_MS_UP, KC_MS_WH_RIGHT, _______, _______,
_______, KC_MS_WH_DOWN, KC_MS_LEFT, KC_MS_DOWN, KC_MS_RIGHT, _______,
_______, _______, KC_MS_ACCEL0, KC_MS_ACCEL1, KC_MS_ACCEL2, _______, _______,
_______, _______, _______, _______, KC_MS_BTN3,
_______, _______, _______, KC_MS_BTN1, KC_MS_BTN2, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______,
_______, _______, KC_AUDIO_VOL_DOWN, KC_AUDIO_MUTE, KC_AUDIO_VOL_UP, _______, _______,
KC_MEDIA_PREV_TRACK, KC_MEDIA_NEXT_TRACK, _______, _______, _______,
_______, _______, _______, _______, KC_MS_BTN1, KC_MEDIA_PLAY_PAUSE),
[ADJUST] = LAYOUT_ergodox(_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, TO(EDIT), TO(NUMPAD), TO(FSYM), TO(JSYM), TO(MEDIA),
_______, _______, _______, _______, _______, _______, _______,
_______, TO(QWERTY), _______, _______, _______,
_______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______, _______,
_______, _______, _______, _______, _______,
_______, _______, _______, _______, _______, _______),
};
bool process_record_user(uint16_t keycode, keyrecord_t *record) {
switch (keycode) {
// dynamically generate these.
case VRSN:
if (record->event.pressed) {
SEND_STRING (QMK_KEYBOARD "/" QMK_KEYMAP " @ " QMK_VERSION);
}
return false;
}
return true;
}
layer_state_t layer_state_set_user(layer_state_t state) {
switch (get_highest_layer(state)) {
case QWERTY:
ergodox_right_led_1_off();
ergodox_right_led_2_off();
ergodox_right_led_3_off();
break;
case NUMPAD:
ergodox_right_led_1_on();
ergodox_right_led_2_off();
ergodox_right_led_3_off();
break;
case EDIT:
ergodox_right_led_1_off();
ergodox_right_led_2_on();
ergodox_right_led_3_off();
break;
case FSYM:
ergodox_right_led_1_on();
ergodox_right_led_2_on();
ergodox_right_led_3_off();
break;
case JSYM:
ergodox_right_led_1_on();
ergodox_right_led_2_off();
ergodox_right_led_3_on();
break;
case MEDIA:
ergodox_right_led_1_off();
ergodox_right_led_2_on();
ergodox_right_led_3_on();
break;
case ADJUST:
ergodox_right_led_1_on();
ergodox_right_led_2_on();
ergodox_right_led_3_on();
break;
}
return state;
}
| 47.50625 | 115 | 0.642021 |
c3fc9fd7d85a6b9d338a63b816badd37c2da272b | 2,059 | c | C | src/ruuvi_endpoint/ruuvi_endpoint.c | alueger/ruuvitag_fw_zephyr | 5b6de32a691de4da3f506e9bbd350e08e84ea3cf | [
"MIT"
] | 4 | 2020-11-08T12:09:42.000Z | 2021-10-20T18:52:44.000Z | src/ruuvi_endpoint/ruuvi_endpoint.c | theBASTI0N/ruuvitag_fw_zephyr | 7088c81b5aaddf34bb819d2623d3e4558697ea52 | [
"MIT"
] | 16 | 2020-11-07T03:57:08.000Z | 2022-03-30T14:06:22.000Z | src/ruuvi_endpoint/ruuvi_endpoint.c | alueger/ruuvitag_fw_zephyr | 5b6de32a691de4da3f506e9bbd350e08e84ea3cf | [
"MIT"
] | 3 | 2021-11-11T11:54:52.000Z | 2022-02-22T12:43:09.000Z | /*
* Copyright (c) 2020 theB@STI0N
*
* SPDX-License-Identifier: MIT
*/
#include <zephyr.h>
#include <stdio.h>
#include "ruuvi.h"
#include "board_info.h"
#include "ruuvi_endpoint.h"
static bool device_mac_rx = false;
mac_address_bin_t device_mac;
static int8_t tx_pwr = RUUVI_TX_POWER;
/*
* Needs ENV data to be more accurate.
* Adjusted from:
* https://github.com/ruuvi/ruuvitag_fw/blob/master/libraries/ruuvi_sensor_formats/ruuvi_endpoints.c
* Data found here is not as accurate as found in on current ruuvi fw.
*/
void ruuvi_raw_v2_encode(uint8_t *data, sensor_data_t sensor_data, uint16_t acc_events ){
static uint32_t packet_counter = 0;
data[0] = RUUVI_RAWv2;
int32_t t = sensor_data.temperature * 2;
data[1] = ((t) >> 8);
data[2] = ((t) & 0xFF);
uint32_t h = sensor_data.humidity * 400 / 1024;
data[3] = ((h)>>8);
data[4] = ((h) & 0xFF);
data[5] = ((sensor_data.pressure)>>8);
data[6] = ((sensor_data.pressure) & 0xFF);
data[7] = ((sensor_data.x)>>8);
data[8] = ((sensor_data.x) & 0xFF);
data[9] = ((sensor_data.y)>>8);
data[10] = ((sensor_data.y) & 0xFF);
data[11] = ((sensor_data.z)>>8);
data[12] = ((sensor_data.z) & 0xFF);
int16_t vbatt = sensor_data.vbatt;
vbatt -= 1600; //Bias by 1600 mV
vbatt <<= 5; //Shift by 5 to fit TX PWR in
data[13] = (vbatt)>>8;
data[14] = (vbatt)&0xFF; //Zeroes tx-pwr bits
int8_t tx = tx_pwr;
/* Prepare TX power for packet */
tx += 40;
tx /= 2;
data[14] |= ((uint8_t)tx)&0x1F; //5 lowest bits for TX pwr
data[15] = acc_events % 256;
data[16] = (packet_counter>>8);
data[17] = (packet_counter&0xFF);
if(!device_mac_rx){
get_mac(&device_mac);
device_mac_rx = true;
}
data[18] = device_mac.mac[5];
data[19] = device_mac.mac[4];
data[20] = device_mac.mac[3];
data[21] = device_mac.mac[2];
data[22] = device_mac.mac[1];
data[23] = device_mac.mac[0];
++packet_counter;
}
| 31.19697 | 100 | 0.598349 |
95c82ec6e4a417dd58c18fd8e008515b88eef85f | 783 | c | C | ku06/ku06-2.c | umchemurziev/CAOS | aa1578dc8a0e863098011d700b6ff5ae10ba47df | [
"MIT"
] | null | null | null | ku06/ku06-2.c | umchemurziev/CAOS | aa1578dc8a0e863098011d700b6ff5ae10ba47df | [
"MIT"
] | null | null | null | ku06/ku06-2.c | umchemurziev/CAOS | aa1578dc8a0e863098011d700b6ff5ae10ba47df | [
"MIT"
] | null | null | null | #include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
typedef u_int8_t uint8_t;
int main(int argc, const char *argv[]) {
int in_fd = open(argv[1], O_RDONLY);
int out_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0600);
int64_t mod = strtol(argv[3], NULL, 10);
uint8_t val = 0;
int64_t res = 0;
int64_t order = 1;
while (read(in_fd, &val, sizeof(val)) > 0) {
for (size_t i = 0; i < 8; ++i, ++order) {
int64_t sqrt = (order % mod) * (order % mod);
sqrt %= mod;
res += sqrt;
res %= mod;
if (((val >> i) % 2) != 0) {
int32_t final_res = res % mod;
write(out_fd, &final_res, 4);
}
}
}
close(in_fd);
close(out_fd);
}
| 23.727273 | 65 | 0.490421 |
45292a517f1a5085be78fac92d54a932f29cdb5e | 3,595 | h | C | System/Library/PrivateFrameworks/HomeKitDaemon.framework/HMDCameraRecordingSessionNotificationTrigger.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 11 | 2019-11-06T04:48:48.000Z | 2022-02-09T17:48:15.000Z | System/Library/PrivateFrameworks/HomeKitDaemon.framework/HMDCameraRecordingSessionNotificationTrigger.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 1 | 2020-04-16T01:41:56.000Z | 2020-04-16T04:32:00.000Z | System/Library/PrivateFrameworks/HomeKitDaemon.framework/HMDCameraRecordingSessionNotificationTrigger.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 3 | 2019-12-22T20:17:53.000Z | 2021-01-25T09:47:49.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:41:45 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/HomeKitDaemon.framework/HomeKitDaemon
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <HMFoundation/HMFObject.h>
#import <HomeKitDaemon/HMDCameraNotificationCharacteristicsAvailabilityListenerDelegate.h>
#import <HomeKitDaemon/HMFLogging.h>
@protocol HMDCameraRecordingSessionNotificationTriggerDelegate, OS_dispatch_queue;
@class NSObject, HMDHAPAccessory, HMDCameraNotificationCharacteristicsAvailabilityListener, NSNotificationCenter, NSString;
@interface HMDCameraRecordingSessionNotificationTrigger : HMFObject <HMDCameraNotificationCharacteristicsAvailabilityListenerDelegate, HMFLogging> {
id<HMDCameraRecordingSessionNotificationTriggerDelegate> _delegate;
NSObject*<OS_dispatch_queue> _workQueue;
HMDHAPAccessory* _cameraAccessory;
HMDCameraNotificationCharacteristicsAvailabilityListener* _availabilityListener;
NSNotificationCenter* _notificationCenter;
NSString* _logIdentifier;
}
@property (readonly) NSObject*<OS_dispatch_queue> workQueue; //@synthesize workQueue=_workQueue - In the implementation block
@property (__weak,readonly) HMDHAPAccessory * cameraAccessory; //@synthesize cameraAccessory=_cameraAccessory - In the implementation block
@property (readonly) HMDCameraNotificationCharacteristicsAvailabilityListener * availabilityListener; //@synthesize availabilityListener=_availabilityListener - In the implementation block
@property (readonly) NSNotificationCenter * notificationCenter; //@synthesize notificationCenter=_notificationCenter - In the implementation block
@property (readonly) NSString * logIdentifier; //@synthesize logIdentifier=_logIdentifier - In the implementation block
@property (__weak) id<HMDCameraRecordingSessionNotificationTriggerDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(id)clientIdentifier;
+(id)logCategory;
-(void)dealloc;
-(id<HMDCameraRecordingSessionNotificationTriggerDelegate>)delegate;
-(void)setDelegate:(id<HMDCameraRecordingSessionNotificationTriggerDelegate>)arg1 ;
-(NSObject*<OS_dispatch_queue>)workQueue;
-(void)start;
-(NSNotificationCenter *)notificationCenter;
-(void)_registerForNotifications:(id)arg1 ;
-(NSString *)logIdentifier;
-(void)listener:(id)arg1 didUpdateAvailableCharacteristics:(id)arg2 previousCharacteristics:(id)arg3 ;
-(id)initWithCamera:(id)arg1 workQueue:(id)arg2 ;
-(id)initWithCamera:(id)arg1 workQueue:(id)arg2 availabilityListener:(id)arg3 notificationCenter:(id)arg4 ;
-(HMDCameraNotificationCharacteristicsAvailabilityListener *)availabilityListener;
-(void)_setNotificationForCharacteristics:(id)arg1 to:(BOOL)arg2 ;
-(HMDHAPAccessory *)cameraAccessory;
-(void)_handleObservedCharacteristicsValueUpdate:(id)arg1 ;
-(void)_handleAccessoryLocalReachabilityChanged:(id)arg1 ;
-(void)_handleCharacteristicsValueUpdated:(id)arg1 ;
-(void)_configureAvailableCharacteristics:(id)arg1 previousCharacteristics:(id)arg2 ;
@end
| 60.932203 | 201 | 0.776356 |
9c5840c7a1fcec64a68e5ee3cebd4adb2ef3d073 | 875 | h | C | syscall.h | fatemehvalipour/xv6 | e02f7bfb332e5e6b881d1370d7594f3b1305709c | [
"MIT-0"
] | null | null | null | syscall.h | fatemehvalipour/xv6 | e02f7bfb332e5e6b881d1370d7594f3b1305709c | [
"MIT-0"
] | null | null | null | syscall.h | fatemehvalipour/xv6 | e02f7bfb332e5e6b881d1370d7594f3b1305709c | [
"MIT-0"
] | null | null | null | // System call numbers
#define SYS_fork 1
#define SYS_exit 2
#define SYS_wait 3
#define SYS_pipe 4
#define SYS_read 5
#define SYS_kill 6
#define SYS_exec 7
#define SYS_fstat 8
#define SYS_chdir 9
#define SYS_dup 10
#define SYS_getpid 11
#define SYS_sbrk 12
#define SYS_sleep 13
#define SYS_uptime 14
#define SYS_open 15
#define SYS_write 16
#define SYS_mknod 17
#define SYS_unlink 18
#define SYS_link 19
#define SYS_mkdir 20
#define SYS_close 21
#define SYS_getparentid 22
#define SYS_getChildren 23
#define SYS_setpriority 24
#define SYS_changepolicy 25
#define SYS_getSystemCallCount 26
#define SYS_getCreationTime 27
#define SYS_getTerminationTime 28
#define SYS_getRunningTime 29
#define SYS_getReadyTime 30
#define SYS_getSleepingTime 31
#define SYS_getAvgWaitingTime 32
#define SYS_getAvgTurnaroundTime 33
#define SYS_setGroup 34
| 24.305556 | 35 | 0.793143 |
cb0a7b7b7d096af35321b830fd0aaa3fd66e91a7 | 918 | h | C | include/lnSerial.h | mean00/Arduino_gd32_freeRTOS | de1828faaa5df79ee244c93ad45cf1dd63986f9f | [
"MIT"
] | 4 | 2021-09-06T14:38:23.000Z | 2022-03-13T01:15:48.000Z | include/lnSerial.h | mean00/Arduino_gd32_freeRTOS | de1828faaa5df79ee244c93ad45cf1dd63986f9f | [
"MIT"
] | 1 | 2021-10-14T09:38:56.000Z | 2021-10-14T10:11:21.000Z | include/lnSerial.h | mean00/lnArduino | de1828faaa5df79ee244c93ad45cf1dd63986f9f | [
"MIT"
] | null | null | null | /*
* (C) 2021 MEAN00 fixounet@free.fr
* See license file
*/
#pragma once
#include "lnArduino.h"
#include "lnDma.h"
/**
*/
class lnSerial
{
public:
enum txState
{
txIdle,
txTransmitting,
txLast
};
enum txMode
{
txNone,
txInterrupt,
txDma
};
lnSerial(int instance);
bool init();
bool setSpeed(int speed);
bool enableTx(txMode mode);
bool transmit(int size,uint8_t *buffer);
bool dmaTransmit(int size,uint8_t *buffer);
void _interrupt(void);
static void interrupts(int instance);
protected:
int _instance;
LnIRQ _irq;
bool _stateTx;
uint32_t _adr;
xMutex _mutex;
xBinarySemaphore _txDone;
uint8_t *_cur,*_tail;
txState _txState;
lnDMA _txDma;
protected:
void txDmaCb();
static void _dmaCallback(void *c,lnDMA::DmaInterruptType it);
}; | 18 | 65 | 0.602397 |
5f128c8aed31d93092c4bf720d8139cf1b4aa515 | 410 | h | C | esp/bindings/SOAP/xpp/xpp/xpputils.h | jeclrsg/HPCC-Platform | c1daafb6060f0c47c95bce98e5431fedc33c592d | [
"Apache-2.0"
] | 286 | 2015-01-03T12:45:17.000Z | 2022-03-25T18:12:57.000Z | esp/bindings/SOAP/xpp/xpp/xpputils.h | jeclrsg/HPCC-Platform | c1daafb6060f0c47c95bce98e5431fedc33c592d | [
"Apache-2.0"
] | 9,034 | 2015-01-02T08:49:19.000Z | 2022-03-31T20:34:44.000Z | esp/bindings/SOAP/xpp/xpp/xpputils.h | jeclrsg/HPCC-Platform | c1daafb6060f0c47c95bce98e5431fedc33c592d | [
"Apache-2.0"
] | 208 | 2015-01-02T03:27:28.000Z | 2022-02-11T05:54:52.000Z | // -*-c++-*- --------------74-columns-wide-------------------------------|
#ifndef XPP_UTILS_H_
#define XPP_UTILS_H_
#pragma warning(disable:4290)
using namespace xpp;
IMultiException *xppMakeException(IXmlPullParser &xppx);
void xppToXmlString(IXmlPullParser &xpp, StartTag &stag, StringBuffer & buffer);
bool xppGotoTag(IXmlPullParser &xppx, const char *tagname, StartTag &stag);
#endif // XPP_UTILS_H_
| 27.333333 | 80 | 0.687805 |
467143cd4e2f35d9b75dbe1351ce4ec9098cdd82 | 1,962 | h | C | linsched-linsched-alpha/include/net/mld.h | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | 47 | 2015-03-10T23:21:52.000Z | 2022-02-17T01:04:14.000Z | linsched-linsched-alpha/include/net/mld.h | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | 1 | 2020-06-30T18:01:37.000Z | 2020-06-30T18:01:37.000Z | linsched-linsched-alpha/include/net/mld.h | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | 19 | 2015-02-25T19:50:05.000Z | 2021-10-05T14:35:54.000Z | #ifndef LINUX_MLD_H
#define LINUX_MLD_H
#include <linux/in6.h>
#include <linux/icmpv6.h>
/* MLDv1 Query/Report/Done */
struct mld_msg {
struct icmp6hdr mld_hdr;
struct in6_addr mld_mca;
};
#define mld_type mld_hdr.icmp6_type
#define mld_code mld_hdr.icmp6_code
#define mld_cksum mld_hdr.icmp6_cksum
#define mld_maxdelay mld_hdr.icmp6_maxdelay
#define mld_reserved mld_hdr.icmp6_dataun.un_data16[1]
/* Multicast Listener Discovery version 2 headers */
/* MLDv2 Report */
struct mld2_grec {
__u8 grec_type;
__u8 grec_auxwords;
__be16 grec_nsrcs;
struct in6_addr grec_mca;
struct in6_addr grec_src[0];
};
struct mld2_report {
struct icmp6hdr mld2r_hdr;
struct mld2_grec mld2r_grec[0];
};
#define mld2r_type mld2r_hdr.icmp6_type
#define mld2r_resv1 mld2r_hdr.icmp6_code
#define mld2r_cksum mld2r_hdr.icmp6_cksum
#define mld2r_resv2 mld2r_hdr.icmp6_dataun.un_data16[0]
#define mld2r_ngrec mld2r_hdr.icmp6_dataun.un_data16[1]
/* MLDv2 Query */
struct mld2_query {
struct icmp6hdr mld2q_hdr;
struct in6_addr mld2q_mca;
#if defined(__LITTLE_ENDIAN_BITFIELD)
__u8 mld2q_qrv:3,
mld2q_suppress:1,
mld2q_resv2:4;
#elif defined(__BIG_ENDIAN_BITFIELD)
__u8 mld2q_resv2:4,
mld2q_suppress:1,
mld2q_qrv:3;
#else
#error "Please fix <asm/byteorder.h>"
#endif
__u8 mld2q_qqic;
__be16 mld2q_nsrcs;
struct in6_addr mld2q_srcs[0];
};
#define mld2q_type mld2q_hdr.icmp6_type
#define mld2q_code mld2q_hdr.icmp6_code
#define mld2q_cksum mld2q_hdr.icmp6_cksum
#define mld2q_mrc mld2q_hdr.icmp6_maxdelay
#define mld2q_resv1 mld2q_hdr.icmp6_dataun.un_data16[1]
/* Max Response Code */
#define MLDV2_MASK(value, nb) ((nb)>=32 ? (value) : ((1<<(nb))-1) & (value))
#define MLDV2_EXP(thresh, nbmant, nbexp, value) \
((value) < (thresh) ? (value) : \
((MLDV2_MASK(value, nbmant) | (1<<(nbmant))) << \
(MLDV2_MASK((value) >> (nbmant), nbexp) + (nbexp))))
#define MLDV2_MRC(value) MLDV2_EXP(0x8000, 12, 3, value)
#endif
| 25.815789 | 76 | 0.750765 |
f150afd20734345607b8f53772b39a4feaf9e434 | 546 | h | C | Framework/DJIUILibrary.framework/Headers/DULWidgetItem.h | rcjetpilot/Mobile-UILibrary-iOS | 1762a07d8f24c8e0f569b696bda4bfe11780a1db | [
"MIT"
] | null | null | null | Framework/DJIUILibrary.framework/Headers/DULWidgetItem.h | rcjetpilot/Mobile-UILibrary-iOS | 1762a07d8f24c8e0f569b696bda4bfe11780a1db | [
"MIT"
] | null | null | null | Framework/DJIUILibrary.framework/Headers/DULWidgetItem.h | rcjetpilot/Mobile-UILibrary-iOS | 1762a07d8f24c8e0f569b696bda4bfe11780a1db | [
"MIT"
] | null | null | null | //
// DULWidgetItem.h
// DJIUILibrary
//
// Copyright © 2016 DJI. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <DJIUILibrary/DULWidgetProtocol.h>
/**
* A carrying object that associates a widgets with additional layout-related
* attributes.
*/
@interface DULWidgetItem : NSObject
/**
* The associated widget.
*/
@property UIView <DULWidgetProtocol> *widget;
/**
* The edget inset attributes. These will be a padding around the widget inside its
* collection.
*/
@property UIEdgeInsets edgeInset;
@end
| 17.0625 | 84 | 0.714286 |
cc0f39ca0c705de714871a667884610c823f1200 | 260 | h | C | examples/use-openssl.h | ytomino/headmaster | 11571992e480aa9fbc5821fe1be1b62edf5f924f | [
"BSD-2-Clause"
] | 15 | 2015-06-29T20:15:08.000Z | 2021-06-12T07:42:04.000Z | examples/use-openssl.h | ytomino/headmaster | 11571992e480aa9fbc5821fe1be1b62edf5f924f | [
"BSD-2-Clause"
] | 5 | 2017-11-16T19:00:09.000Z | 2018-07-05T14:53:33.000Z | examples/use-openssl.h | ytomino/headmaster | 11571992e480aa9fbc5821fe1be1b62edf5f924f | [
"BSD-2-Clause"
] | 2 | 2017-11-16T19:17:02.000Z | 2021-06-12T07:42:06.000Z | #if defined(__FreeBSD__)
#include <stdint.h> /* uintptr_t is used in <sys/cdefs.h> */
#endif
#define OPENSSL_NO_DEPRECATED
#define OPENSSL_NO_FILENAMES
#include <openssl/md5.h>
#include <openssl/sha.h>
#undef OPENSSL_NO_DEPRECATED
#undef OPENSSL_NO_FILENAMES
| 23.636364 | 60 | 0.788462 |
9a1b1c2e0c36fb75dcc69b9789101b429bd5892b | 11,476 | h | C | src/calculateG0/calculateG0.h | mnmpdadish/ctint | 6628ae12d0072e059af66ff9208610dacae1ffee | [
"MIT"
] | null | null | null | src/calculateG0/calculateG0.h | mnmpdadish/ctint | 6628ae12d0072e059af66ff9208610dacae1ffee | [
"MIT"
] | null | null | null | src/calculateG0/calculateG0.h | mnmpdadish/ctint | 6628ae12d0072e059af66ff9208610dacae1ffee | [
"MIT"
] | null | null | null | #pragma once
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "model.h"
#define N_PTS_MAT 200
#define N_PTS_TAU 1000
// -------------------------------------------------------------------------
typedef struct {
cMatrix matrices[N_PTS_MAT];
cMatrix M0; //zeroth moment
cMatrix M1; //first moment
cMatrix M2; //second moment
cMatrix M3; //third moment
double beta;
unsigned int nLoaded;
} cMatrixFunction;
typedef struct {
dMatrix matrices[N_PTS_TAU];
double beta;
} dMatrixFunction;
void init_cMatrixFunction(cMatrixFunction * cMatFun, Model * model) {
init_cMatrix(&cMatFun->M0,model->nSites);
init_cMatrix(&cMatFun->M1,model->nSites);
init_cMatrix(&cMatFun->M2,model->nSites);
init_cMatrix(&cMatFun->M3,model->nSites);
reset_cMatrix(&cMatFun->M0);
reset_cMatrix(&cMatFun->M1);
reset_cMatrix(&cMatFun->M2);
reset_cMatrix(&cMatFun->M3);
int n;
for(n=0; n<N_PTS_MAT; n++){
init_cMatrix(&cMatFun->matrices[n],model->nSites);
reset_cMatrix(&cMatFun->matrices[n]);
}
cMatFun->beta = model->beta;
cMatFun->nLoaded = 0;
}
void free_cMatrixFunction(cMatrixFunction * cMatFun) {
free_cMatrix(&cMatFun->M0);
free_cMatrix(&cMatFun->M1);
free_cMatrix(&cMatFun->M2);
free_cMatrix(&cMatFun->M3);
int n;
for(n=0; n<N_PTS_MAT; n++) free_cMatrix(&cMatFun->matrices[n]);
}
void init_dMatrixFunction(dMatrixFunction * dMatFun, Model * model) {
int n;
for(n=0; n<N_PTS_TAU; n++){
init_dMatrix(&dMatFun->matrices[n],model->nSites);
reset_dMatrix(&dMatFun->matrices[n]);
}
dMatFun->beta = model->beta;
}
void free_dMatrixFunction(dMatrixFunction * dMatFun) {
int n;
for(n=0; n<N_PTS_TAU; n++) free_dMatrix(&dMatFun->matrices[n]);
}
//A=factorA*A+factorB*B
unsigned int dMatrix_cMatrixAdditionInPlace(dMatrix * A, cMatrix const * B, double complex factorA, double complex factorB) {
assert(A->N == B->N);
unsigned int i;
for(i=0; i<(A->N*A->N); i++) A->data[i]=creal(factorA*A->data[i] + factorB*B->data[i]);
return 0;
}
//A=factorA*A+factorB*B
unsigned int cMatrix_dMatrixAdditionInPlace(cMatrix * A, dMatrix const * B, double complex factorA, double complex factorB) {
assert(A->N == B->N);
unsigned int i;
for(i=0; i<(A->N*A->N); i++) A->data[i]=factorA*A->data[i]+factorB*B->data[i];
return 0;
}
void calculate_G0_matsubara(cMatrixFunction * g0_matsubara, Model * model, cMatrixFunction * hyb_matsubara, double mu, int verbose) {
int i,n;
cMatrix tLoc;
init_cMatrix(&tLoc,model->nSites);
calculate_HoppingMatrixLoc(&model->tMat, &tLoc);
for(i=0; i<model->nSites; i++) ELEM_VAL(g0_matsubara->M1, i, i) = 1.0;
if(verbose) {printf("M1:\n"); print_cMatrix_real(&g0_matsubara->M1);}
for(i=0; i<model->nSites; i++) ELEM_VAL(g0_matsubara->M2, i, i) = -mu;
cMatrixMatrixAdditionInPlace(&g0_matsubara->M2, &tLoc, 1.0, 1.0);
if(verbose) {printf("M2:\n"); print_cMatrix_real(&g0_matsubara->M2);}
cMatrixMatrixMultiplication(&g0_matsubara->M2, &g0_matsubara->M2, &g0_matsubara->M3); //M2=M1*M1
if(hyb_matsubara != NULL)
cMatrix_dMatrixAdditionInPlace(&g0_matsubara->M3,&model->hybFM, 1.0, -1.0); // g = g - hyb
if(verbose) {printf("M3:\n"); print_cMatrix_real(&g0_matsubara->M3);}
for(n=0; n<N_PTS_MAT; n++){
reset_cMatrix(&g0_matsubara->matrices[n]);
double complex z = I*(2.*n+1)*M_PI/g0_matsubara->beta;
for(i=0; i<model->nSites; i++) ELEM_VAL(g0_matsubara->matrices[n], i, i) = z + mu; // g = diagonal()
cMatrixMatrixAdditionInPlace(&g0_matsubara->matrices[n],&tLoc, 1.0, -1.0); // g = g - tLoc
if(hyb_matsubara != NULL)
cMatrixMatrixAdditionInPlace(&g0_matsubara->matrices[n],&hyb_matsubara->matrices[n], 1.0, -1.0); // g = g - hyb
invert_cMatrix(&g0_matsubara->matrices[n]); // g=g^-1
}
}
void patch_HYB_matsubara(Model * model, cMatrixFunction * hyb_matsubara){
int n;
printf("hybFM:\n"); print_dMatrix(&model->hybFM);
for(n = hyb_matsubara->nLoaded; n<N_PTS_MAT; n++){
double complex z = I*(2.*n+1)*M_PI/hyb_matsubara->beta;
cMatrix_dMatrixAdditionInPlace(&hyb_matsubara->matrices[n],&model->hybFM, 1.0, +1.0/z); // g = g -tLoc
}
}
void calculateInversFourierTransform(cMatrixFunction * g0_matsubara, dMatrixFunction * g0_tau) {
int n1, n2;
for(n1=0; n1<N_PTS_TAU; n1++){
//printf("salut3\n");
reset_dMatrix(&g0_tau->matrices[n1]);
double tau = g0_matsubara->beta*n1/(N_PTS_TAU - 1);
for(n2=N_PTS_MAT-1; n2>=0; n2--){
double omega_n2 = (2.*n2+1)*M_PI/g0_matsubara->beta;
double complex expFactor = 2.*cexp(-I*omega_n2*tau)/(g0_matsubara->beta);
//double complex expFactor2 = 1.*cexp(I*omega_n2*tau)/(g0_matsubara->beta);
dMatrix_cMatrixAdditionInPlace(&g0_tau->matrices[n1],&g0_matsubara->matrices[n2], 1.0, expFactor); // g = g -tLoc
//dMatrix_cMatrixAdditionInPlace(&g0_tau->matrices[n1],&g0_matsubara->matrices[n2], 1.0, expFactor2); // g = g -tLoc
//printf("&g0_tau->matrices[n1] = \n");
//print_cMatrix(&g0_tau->matrices[n1]);
}
}
}
void removeMoments_G0_matsubara(cMatrixFunction * g0_matsubara) {
int n;
for(n=0; n<N_PTS_MAT; n++){
double complex z = I*(2.*n+1)*M_PI/g0_matsubara->beta;
//cMatrixMatrixAdditionInPlace(&g0_matsubara->matrices[n],&g0_matsubara->M0, 1.0, -1.0);
//printf("before:\n"); print_cMatrix(&g0_matsubara->matrices[n]);
//printf("M1:\n"); print_cMatrix(&g0_matsubara->M1);
cMatrixMatrixAdditionInPlace(&g0_matsubara->matrices[n],&g0_matsubara->M1, 1.0, -1.0/z);
//printf("after: \n"); print_cMatrix(&g0_matsubara->matrices[n]);
cMatrixMatrixAdditionInPlace(&g0_matsubara->matrices[n],&g0_matsubara->M2, 1.0, -1.0/z/z);
cMatrixMatrixAdditionInPlace(&g0_matsubara->matrices[n],&g0_matsubara->M3, 1.0, -1.0/z/z/z);
}
}
void addMoments_G0_tau(cMatrixFunction * g0_matsubara, dMatrixFunction * g0_tau) { // can be in mat(tsubara) or (imaginary time) tau, as long a moments are defined
int n;
double beta = g0_tau->beta;
for(n=0; n<N_PTS_TAU; n++){
double tau = g0_tau->beta*n/(N_PTS_TAU - 1);
dMatrix_cMatrixAdditionInPlace(&g0_tau->matrices[n],&g0_matsubara->M1, 1.0, -0.5);
dMatrix_cMatrixAdditionInPlace(&g0_tau->matrices[n],&g0_matsubara->M2, 1.0, 0.5*(tau-0.5*beta));
dMatrix_cMatrixAdditionInPlace(&g0_tau->matrices[n],&g0_matsubara->M3, 1.0, 0.25*(beta-tau)*tau);
}
}
void calculate_G0_tau(cMatrixFunction * g0_matsubara, dMatrixFunction * g0_tau) {
g0_tau->beta = g0_matsubara->beta;
removeMoments_G0_matsubara(g0_matsubara);
calculateInversFourierTransform(g0_matsubara, g0_tau);
addMoments_G0_tau(g0_matsubara, g0_tau);
}
void writeToFile_cMatrixFunction(FILE *fileOut, cMatrixFunction * cMatFun, Model * model) {
int k,n;
fprintf(fileOut, "# w_matsubara");
for(k=0; k<model->greenSymMat.nIndep; k++) {
int i=model->greenSymMat.iFirstIndep[k];
int j=model->greenSymMat.jFirstIndep[k];
char nameReal[4];
char nameImag[4];
nameGreenSymmetriesElement(&model->greenSymMat, i, j, nameReal);
nameGreenSymmetriesElement(&model->greenSymMat, i, j, nameImag);
fprintf(fileOut, " %s_re %s_im", nameReal, nameImag);
}
for(n=0; n<N_PTS_MAT; n++){
fprintf(fileOut,"\n");
double omega_n = (2.*n+1)*M_PI/cMatFun->beta;
fprintf(fileOut, "% 3.6e ", omega_n);
for(k=0; k<model->greenSymMat.nIndep; k++) {
int i=model->greenSymMat.iFirstIndep[k];
int j=model->greenSymMat.jFirstIndep[k];
fprintf(fileOut, "% 3.6e % 3.6e ", creal(ELEM_VAL(cMatFun->matrices[n], i, j)), cimag(ELEM_VAL(cMatFun->matrices[n], i, j)) );
}
}
}
void writeToFile_dMatrixFunction(FILE *fileOut, dMatrixFunction * dMatFun, Model * model) {
int k,n;
fprintf(fileOut, "# tau ");
for(k=0; k<model->greenSymMat.nIndep; k++) {
int i=model->greenSymMat.iFirstIndep[k];
int j=model->greenSymMat.jFirstIndep[k];
char nameReal[4];
nameGreenSymmetriesElement(&model->greenSymMat, i, j, nameReal);
fprintf(fileOut, " %s_re", nameReal);
}
for(n=0; n<N_PTS_TAU; n++){
fprintf(fileOut,"\n");
double tau = dMatFun->beta*n/(N_PTS_TAU - 1);
fprintf(fileOut, "% 3.6e ", tau);
for(k=0; k<model->greenSymMat.nIndep; k++) {
int i=model->greenSymMat.iFirstIndep[k];
int j=model->greenSymMat.jFirstIndep[k];
fprintf(fileOut, "% 3.6e ", ELEM_VAL(dMatFun->matrices[n], i, j) );
}
}
}
void readFile_cMatrixFunction(FILE *fileIn, cMatrixFunction * cMatFun, Model * model) {
rewind(fileIn);
char tempbuff[4096]; //each line should not be above 4096 char long.
int i=0, j=0, nRead;
float w_matsubara;
float valR, valI;
char *pos;
int n, n_matsubara=0;
double complex indep_cMatrixValue[model->greenSymMat.nIndep];
while(!feof(fileIn))
{
if (fgets(tempbuff,4096,fileIn)) {
//printf("%s",tempbuff);
/*int lenString = strlen(tempbuff);
if(tempbuff[lenString-1]!='\n' && tempbuff[lenString] != EOF) {
printf("error. buffer too short? \\x%02x %d\n",tempbuff[lenString-1], lenString);
printf("%s\n",tempbuff);
printf("%d %d\n",tempbuff[lenString-1], 'a');
exit(1);
}*/
unsigned int nElement = countElementInStr(tempbuff, " \t\n");
//printf("nElement=%d\n",nElement);
if(tempbuff[0] == '#') continue;
//else if(strBeginWithToken(tempbuff,"time")) sym->timeReversal=1;
else if((tempbuff[0] != '\n') && nElement > 1) {
pos = &tempbuff[0];
valI=0.; valR=0.; w_matsubara=0.;
nRead = sscanf(pos,"%e%n", &w_matsubara, &n);
//printf("nRead=%d\n",nRead);
if(nRead!=1) {
printf("Cannot read correctly the line: \n%s", tempbuff);
exit(1);
}
if(nElement > 2*model->greenSymMat.nIndep+1) {
printf("Error, too many elements to read for the model\n");
exit(1);
}
else if (nElement < 2*model->greenSymMat.nIndep+1) {
printf("Error, not enough elements to read for the model, expected=%d, found=%d\n", 2*model->greenSymMat.nIndep+1, nElement);
exit(1);
}
if(n_matsubara==0) cMatFun->beta = M_PI/w_matsubara;
pos+=n;
//printf("beta=%f\n", cMatFun->beta);
for(i=0; i<model->greenSymMat.nIndep; i++){
nRead = sscanf(pos,"%e%n", &valR, &n); pos+=n;
nRead += sscanf(pos,"%e%n", &valI, &n); pos+=n;
if(nRead!=2) {
printf("Cannot read correctly the one-body line: \n%s", tempbuff);
exit(1);
}
//printf("i=%d of %d\n",i, model->greenSymMat.nIndep);
indep_cMatrixValue[i] = valR + I*valI;
//printf("indep_cMatrixValue[i]=%f + %fi\n",creal(indep_cMatrixValue[i]),cimag(indep_cMatrixValue[i]));
}
//printf("salut\n");
//print_cMatrix(&cMatFun->matrices[n_matsubara]);
//printf("salut\n");
for(i=0;i<model->nSites;i++) {
for(j=0;j<model->nSites;j++) {
unsigned int index = model->greenSymMat.indexIndep[model->nSites*i+j];
ELEM_VAL(cMatFun->matrices[n_matsubara],i,j) = indep_cMatrixValue[index];
}
}
//print_cMatrix(&cMatFun->matrices[n_matsubara]);
n_matsubara++;
if(n_matsubara >= N_PTS_MAT) break;
}
else break;
}
//printf("\n");
}
cMatFun->nLoaded=n_matsubara;
return;
}
| 35.310769 | 163 | 0.637679 |
a4b8b00e82ffa59901395017f673f2cf0fa97cbe | 4,198 | h | C | code/LiliEngine/VulkanDevice.h | deltafran/Tiny3DRPG | 59aab39bd844b3f242d14a739622d481e7e83283 | [
"MIT"
] | 1 | 2020-12-28T15:33:53.000Z | 2020-12-28T15:33:53.000Z | code/LiliEngine/VulkanDevice.h | deltafran/Tiny3DRPG | 59aab39bd844b3f242d14a739622d481e7e83283 | [
"MIT"
] | null | null | null | code/LiliEngine/VulkanDevice.h | deltafran/Tiny3DRPG | 59aab39bd844b3f242d14a739622d481e7e83283 | [
"MIT"
] | null | null | null | #pragma once
#include "VulkanQueue.h"
#include "VulkanGlobals.h"
#include "PixelFormat.h"
class VulkanFenceManager;
class VulkanDeviceMemoryManager;
class VulkanDevice final
{
public:
VulkanDevice(VkPhysicalDevice physicalDevice) noexcept;
~VulkanDevice();
bool QueryGPU(int32_t deviceIndex) noexcept;
void InitGPU(int32_t deviceIndex) noexcept;
void CreateDevice() noexcept;
void Destroy() noexcept;
inline std::shared_ptr<VulkanQueue> GetGraphicsQueue() noexcept
{
return m_gfxQueue;
}
inline std::shared_ptr<VulkanQueue> GetComputeQueue() noexcept
{
return m_computeQueue;
}
inline std::shared_ptr<VulkanQueue> GetTransferQueue() noexcept
{
return m_transferQueue;
}
inline std::shared_ptr<VulkanQueue> GetPresentQueue() noexcept
{
return m_presentQueue;
}
inline VkPhysicalDevice GetPhysicalHandle() const noexcept
{
return m_physicalDevice;
}
inline const VkPhysicalDeviceProperties& GetDeviceProperties() const noexcept
{
return m_physicalDeviceProperties;
}
inline const VkPhysicalDeviceLimits& GetLimits() const noexcept
{
return m_physicalDeviceProperties.limits;
}
inline const VkPhysicalDeviceFeatures& GetPhysicalFeatures() const noexcept
{
return m_physicalDeviceFeatures;
}
inline VkDevice GetInstanceHandle() const noexcept
{
return m_device;
}
inline const VkFormatProperties* GetFormatProperties() const noexcept
{
return m_formatProperties;
}
inline VulkanFenceManager& GetFenceManager() noexcept
{
return *m_fenceManager;
}
inline VulkanDeviceMemoryManager& GetMemoryManager() noexcept
{
return *m_memoryManager;
}
inline void AddAppDeviceExtensions(const char* name) noexcept
{
m_appDeviceExtensions.push_back(name);
}
inline void SetPhysicalDeviceFeatures(VkPhysicalDeviceFeatures2* deviceFeatures) noexcept
{
m_physicalDeviceFeatures2 = deviceFeatures;
}
bool IsFormatSupported(VkFormat format) noexcept;
const VkComponentMapping& GetFormatComponentMapping(PixelFormat format) const noexcept;
void SetupPresentQueue(VkSurfaceKHR surface);
private:
VulkanDevice() = delete;
VulkanDevice(const VulkanDevice&) = delete;
VulkanDevice(VulkanDevice&&) = delete;
VulkanDevice& operator=(const VulkanDevice&) = delete;
VulkanDevice& operator=(VulkanDevice&&) = delete;
void setupFormats() noexcept;
void mapFormatSupport(PixelFormat format, VkFormat vkFormat) noexcept;
void mapFormatSupport(PixelFormat format, VkFormat vkormat, int32_t blockBytes) noexcept;
void setComponentMapping(PixelFormat format, VkComponentSwizzle r, VkComponentSwizzle g, VkComponentSwizzle b, VkComponentSwizzle a) noexcept;
void getDeviceExtensionsAndLayers(std::vector<const char*>& outDeviceExtensions, std::vector<const char*>& outDeviceLayers, bool& bOutDebugMarkers) noexcept;
VkDevice m_device = VK_NULL_HANDLE;
VkPhysicalDevice m_physicalDevice = VK_NULL_HANDLE;
VkPhysicalDeviceProperties m_physicalDeviceProperties;
VkPhysicalDeviceFeatures m_physicalDeviceFeatures;
std::vector<VkQueueFamilyProperties> m_queueFamilyProps;
VkFormatProperties m_formatProperties[VK_FORMAT_RANGE_SIZE];
std::map<VkFormat, VkFormatProperties> m_extensionFormatProperties;
VkComponentMapping m_pixelFormatComponentMapping[PF_MAX];
std::shared_ptr<VulkanQueue> m_gfxQueue = nullptr;
std::shared_ptr<VulkanQueue> m_computeQueue = nullptr;
std::shared_ptr<VulkanQueue> m_transferQueue = nullptr;
std::shared_ptr<VulkanQueue> m_presentQueue = nullptr;
VulkanFenceManager* m_fenceManager = nullptr;
VulkanDeviceMemoryManager* m_memoryManager = nullptr;
std::vector<const char*> m_appDeviceExtensions;
VkPhysicalDeviceFeatures2* m_physicalDeviceFeatures2 = nullptr;
}; | 31.56391 | 161 | 0.7101 |
2f22a37944cb7c786440e181dd1362788ecfb011 | 1,129 | h | C | PrivateFrameworks/PhotoPrintProduct/KHThemeChooserModel.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/PhotoPrintProduct/KHThemeChooserModel.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/PhotoPrintProduct/KHThemeChooserModel.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSArray, NSIndexPath, NSMutableArray, NSString;
@interface KHThemeChooserModel : NSObject
{
NSMutableArray *_filteredThemes;
NSArray *_themes;
NSIndexPath *_currentlySelectedIndexPath;
NSString *_filterString;
}
@property(retain, nonatomic) NSString *filterString; // @synthesize filterString=_filterString;
@property(retain, nonatomic) NSIndexPath *currentlySelectedIndexPath; // @synthesize currentlySelectedIndexPath=_currentlySelectedIndexPath;
@property(retain, nonatomic) NSArray *themes; // @synthesize themes=_themes;
@property(readonly, nonatomic) NSArray *filteredThemes; // @synthesize filteredThemes=_filteredThemes;
- (void).cxx_destruct;
@property(readonly, nonatomic) NSArray *themesIfFiltered;
- (id)indexPathMatchingSearchString:(id)arg1;
- (id)themeProviderAtIndexPath:(id)arg1;
- (unsigned long long)numberOfItemsInSection:(unsigned long long)arg1;
@property(readonly, nonatomic) unsigned long long numberOfSections;
@end
| 35.28125 | 140 | 0.778565 |
2f43157d093aa652179af9656f44157a80854a24 | 550 | h | C | Headers/Frameworks/Ozone/OZAutoBehaviorHUDController.h | CommandPost/FinalCutProFrameworks | d98b00ff0c84af80942d71514e9238d624aca50a | [
"MIT"
] | 3 | 2020-11-19T10:04:02.000Z | 2021-10-02T17:25:21.000Z | Headers/Frameworks/Ozone/OZAutoBehaviorHUDController.h | CommandPost/FinalCutProFrameworks | d98b00ff0c84af80942d71514e9238d624aca50a | [
"MIT"
] | null | null | null | Headers/Frameworks/Ozone/OZAutoBehaviorHUDController.h | CommandPost/FinalCutProFrameworks | d98b00ff0c84af80942d71514e9238d624aca50a | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <Ozone/OZAutoHUDController.h>
@interface OZAutoBehaviorHUDController : OZAutoHUDController
{
list_64b41211 *_pBehaviorList;
}
- (void)didUpdateHiddenFlags;
- (list_64b41211 *)getBehaviorList;
- (struct OZChannelFolder *)getRootChan:(struct OZObjectManipulator *)arg1;
- (void)notify:(unsigned int)arg1;
- (BOOL)loadView;
- (void)dealloc;
- (id)initWithObjectList:(list_93048c9c *)arg1;
@end
| 22.916667 | 90 | 0.736364 |
4d6d4cce8d470e1cd23cb739e08a14eefb1373b2 | 447 | h | C | include/math/core/algorithms.h | oren12321/math | cb45fdb48bbee7e74f5b0608ca2bd34c5b50234e | [
"MIT"
] | null | null | null | include/math/core/algorithms.h | oren12321/math | cb45fdb48bbee7e74f5b0608ca2bd34c5b50234e | [
"MIT"
] | null | null | null | include/math/core/algorithms.h | oren12321/math | cb45fdb48bbee7e74f5b0608ca2bd34c5b50234e | [
"MIT"
] | null | null | null | #ifndef MATH_ALGORITHMS_H
#define MATH_ALGORITHMS_H
#include <type_traits>
#include <cmath>
#include <limits>
#include <math/core/utils.h>
namespace math::algorithms {
template <typename T>
concept Arithmetic = std::is_arithmetic_v<T>;
template <Arithmetic T>
bool is_equal(T a, T b, T epsilon = std::sqrt(std::numeric_limits<T>::epsilon()))
{
return std::abs(a - b) <= epsilon;
}
}
#endif // MATH_ALGORITHMS_H | 21.285714 | 85 | 0.680089 |
061e85a1a0713586615cfb893e682b2292b41eb3 | 6,510 | c | C | src/mame/drivers/news.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | src/mame/drivers/news.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | src/mame/drivers/news.c | Zoltan45/Mame-mkp119 | d219a3549eafb4215727c974e09e43b28d058328 | [
"CC0-1.0"
] | null | null | null | /*
News
from the program ROM:
PROGRAMED BY KWANG-HO CHO
COPYRIGHT(C) 1993
ALL RIGHTS RESERVED BY POBY
Hi-tel ID:poby:
driver by David Haywood
*/
#include "driver.h"
#include "news.h"
#include "sound/okim6295.h"
static ADDRESS_MAP_START( readmem, ADDRESS_SPACE_PROGRAM, 8 )
AM_RANGE(0x0000, 0x7fff) AM_READ(MRA8_ROM)
AM_RANGE(0x8000, 0x8fff) AM_READ(MRA8_RAM)
AM_RANGE(0xc000, 0xc000) AM_READ(input_port_0_r)
AM_RANGE(0xc001, 0xc001) AM_READ(input_port_1_r)
AM_RANGE(0xc002, 0xc002) AM_READ(OKIM6295_status_0_r)
AM_RANGE(0xe000, 0xffff) AM_READ(MRA8_RAM)
ADDRESS_MAP_END
static ADDRESS_MAP_START( writemem, ADDRESS_SPACE_PROGRAM, 8 )
AM_RANGE(0x0000, 0x7fff) AM_WRITE(MWA8_ROM) /* 4000-7fff is written to during startup, probably leftover code */
AM_RANGE(0x8000, 0x87ff) AM_WRITE(news_fgram_w) AM_BASE(&news_fgram)
AM_RANGE(0x8800, 0x8fff) AM_WRITE(news_bgram_w) AM_BASE(&news_bgram)
AM_RANGE(0x9000, 0x91ff) AM_WRITE(paletteram_xxxxRRRRGGGGBBBB_be_w) AM_BASE(&paletteram)
AM_RANGE(0xc002, 0xc002) AM_WRITE(OKIM6295_data_0_w) /* ?? */
AM_RANGE(0xc003, 0xc003) AM_WRITE(news_bgpic_w)
AM_RANGE(0xe000, 0xffff) AM_WRITE(MWA8_RAM)
ADDRESS_MAP_END
INPUT_PORTS_START( news )
PORT_START /* DSW */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SWA:1,2")
PORT_DIPSETTING( 0x00, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x03, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SWA:3,4")
PORT_DIPSETTING( 0x0c, DEF_STR( Easy ) )
PORT_DIPSETTING( 0x08, DEF_STR( Medium ) )
PORT_DIPSETTING( 0x04, DEF_STR( Hard ) )
PORT_DIPSETTING( 0x00, DEF_STR( Hardest ) )
PORT_DIPNAME( 0x10, 0x10, "Helps" ) PORT_DIPLOCATION("SWA:5")
PORT_DIPSETTING( 0x10, "1" )
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPNAME( 0x20, 0x00, "Copyright" ) PORT_DIPLOCATION("SWA:6")
PORT_DIPSETTING( 0x00, "Poby" )
PORT_DIPSETTING( 0x20, "Virus" )
PORT_DIPUNUSED_DIPLOC( 0x40, IP_ACTIVE_LOW, "SWA:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, IP_ACTIVE_LOW, "SWA:8" )
PORT_START
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 )
INPUT_PORTS_END
INPUT_PORTS_START( newsa )
PORT_START /* DSW */
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SWA:1,2")
PORT_DIPSETTING( 0x00, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x03, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C ) )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SWA:3,4")
PORT_DIPSETTING( 0x0c, DEF_STR( Easy ) )
PORT_DIPSETTING( 0x08, DEF_STR( Medium ) )
PORT_DIPSETTING( 0x04, DEF_STR( Hard ) )
PORT_DIPSETTING( 0x00, DEF_STR( Hardest ) )
PORT_DIPNAME( 0x10, 0x10, "Helps" ) PORT_DIPLOCATION("SWA:5")
PORT_DIPSETTING( 0x10, "1" )
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPLOCATION("SWA:6")
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPUNUSED_DIPLOC( 0x40, IP_ACTIVE_LOW, "SWA:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, IP_ACTIVE_LOW, "SWA:8" )
PORT_START
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 )
INPUT_PORTS_END
static const gfx_layout tiles8x8_layout =
{
8,8,
RGN_FRAC(1,1),
4,
{ 0, 1, 2, 3 },
{ 0, 4, 8, 12, 16, 20, 24, 28 },
{ 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 },
32*8
};
static const gfx_decode gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tiles8x8_layout, 0, 16 },
{ -1 }
};
static MACHINE_DRIVER_START( news )
/* basic machine hardware */
MDRV_CPU_ADD(Z80,8000000) /* ? MHz */
MDRV_CPU_PROGRAM_MAP(readmem,writemem)
MDRV_CPU_VBLANK_INT(irq0_line_hold,1)
MDRV_SCREEN_REFRESH_RATE(60)
MDRV_SCREEN_VBLANK_TIME(DEFAULT_60HZ_VBLANK_DURATION)
/* video hardware */
MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER )
MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16)
MDRV_SCREEN_SIZE(256, 256)
MDRV_SCREEN_VISIBLE_AREA(0, 256-1, 16, 256-16-1)
MDRV_GFXDECODE(gfxdecodeinfo)
MDRV_PALETTE_LENGTH(0x100)
MDRV_VIDEO_START(news)
MDRV_VIDEO_UPDATE(news)
/* sound hardware */
MDRV_SPEAKER_STANDARD_MONO("mono")
MDRV_SOUND_ADD(OKIM6295, 1056000)
MDRV_SOUND_CONFIG(okim6295_interface_region_1_pin7high) // clock frequency & pin 7 not verified
MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
MACHINE_DRIVER_END
ROM_START( news )
ROM_REGION( 0x10000, REGION_CPU1, 0 )
ROM_LOAD( "virus.4", 0x00000, 0x08000, BAD_DUMP CRC(aa005dfb) SHA1(52f4dd399a30568851d43d052b83cfaa6682665d) ) /* The Original was too short, I padded it with 0xFF */
ROM_REGION( 0x80000, REGION_GFX1, 0 )
ROM_LOAD16_BYTE( "virus.2", 0x00000, 0x40000, CRC(b5af58d8) SHA1(5dd8c6ab8b53df695463bd0c3620adf8c08daaec) )
ROM_LOAD16_BYTE( "virus.3", 0x00001, 0x40000, CRC(a4b1c175) SHA1(b1ac0da4d91bc3a3454ea80aa4cdbbc68bbdf7f1) )
ROM_REGION( 0x40000, REGION_SOUND1, 0 )
ROM_LOAD( "virus.1", 0x00000, 0x40000, CRC(41f5935a) SHA1(1566d243f165019660cd4dd69df9f049e0130f15) )
ROM_END
ROM_START( newsa )
ROM_REGION( 0x10000, REGION_CPU1, 0 )
ROM_LOAD( "newsa_virus.4", 0x00000, 0x10000, CRC(74a257da) SHA1(f1f6db521312f152ec3b1e6efa45a514433b2ffc) )
ROM_REGION( 0x80000, REGION_GFX1, 0 )
ROM_LOAD16_BYTE( "virus.2", 0x00000, 0x40000, CRC(b5af58d8) SHA1(5dd8c6ab8b53df695463bd0c3620adf8c08daaec) )
ROM_LOAD16_BYTE( "virus.3", 0x00001, 0x40000, CRC(a4b1c175) SHA1(b1ac0da4d91bc3a3454ea80aa4cdbbc68bbdf7f1) )
ROM_REGION( 0x40000, REGION_SOUND1, 0 )
ROM_LOAD( "virus.1", 0x00000, 0x40000, CRC(41f5935a) SHA1(1566d243f165019660cd4dd69df9f049e0130f15) )
ROM_END
GAME( 1993, news, 0, news, news, 0, ROT0, "Poby / Virus", "News (set 1)", 0 )
GAME( 1993, newsa, news, news, newsa, 0, ROT0, "Poby", "News (set 2)", 0 )
| 36.166667 | 168 | 0.749616 |
ff65df90ebffcba923ddee53c7a100650173518b | 593 | c | C | quardatic.c | Fumenoid/C-programing | 185928ff04d2db8eac915d86c86a30488ca5991f | [
"MIT"
] | null | null | null | quardatic.c | Fumenoid/C-programing | 185928ff04d2db8eac915d86c86a30488ca5991f | [
"MIT"
] | null | null | null | quardatic.c | Fumenoid/C-programing | 185928ff04d2db8eac915d86c86a30488ca5991f | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,d,r1,r2,rp,imp;
printf("The standard equationof a quardatic equation = ax2+bx+c,so enter a,b and c\n");
scanf("%f%f%f", &a, &b,&c);
if(a!=0)
{
d=((b*b)-(4*a*c));
if(d>=0)
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("The roots of quardatic equation are %0.3f and %0.3f\n",r1,r2);
}
else
{
rp=(-b/(2*a));
imp=sqrt(-d)/(2*a);
printf("The roots of quardatic equation are %0.3f+i%0.3f\n",rp,imp);
printf("The roots of quardatic equation are %0.3f-i%0.3f\n",rp,imp);
}
}
else
{
printf("Invalid!,LinearEquaton\n");
}
return 0;
}
| 19.129032 | 87 | 0.615514 |
9e3590ea86001419c6c3501ef23e72ce440a3e38 | 4,485 | h | C | CondFormats/SiStripObjects/interface/NoiseAnalysis.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CondFormats/SiStripObjects/interface/NoiseAnalysis.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CondFormats/SiStripObjects/interface/NoiseAnalysis.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef CondFormats_SiStripObjects_NoiseAnalysis_H
#define CondFormats_SiStripObjects_NoiseAnalysis_H
#include "CondFormats/SiStripObjects/interface/CommissioningAnalysis.h"
#include "DataFormats/SiStripCommon/interface/SiStripConstants.h"
#include <boost/cstdint.hpp>
#include <sstream>
#include <vector>
/**
@class NoiseAnalysis
@author M. Wingham, R.Bainbridge
@brief Histogram-based analysis for pedestal run.
*/
class NoiseAnalysis : public CommissioningAnalysis {
public:
// ---------- con(de)structors ----------
NoiseAnalysis( const uint32_t& key );
NoiseAnalysis();
virtual ~NoiseAnalysis() {;}
friend class NoiseAlgorithm;
// ---------- public interface ----------
/** Identifies if analysis is valid or not. */
bool isValid() const;
// Pedestal, noise and raw noise (128-strip vector per APV)
inline const VVFloat& peds() const;
inline const VVFloat& noise() const;
inline const VVFloat& raw() const;
// Dead and noisy strips (vector per APV)
inline const VVInt& dead() const;
inline const VVInt& noisy() const;
// Mean and rms spread (value per APV)
inline const VFloat& pedsMean() const;
inline const VFloat& pedsSpread() const;
inline const VFloat& noiseMean() const;
inline const VFloat& noiseSpread() const;
inline const VFloat& rawMean() const;
inline const VFloat& rawSpread() const;
// Max and min values (value per APV)
inline const VFloat& pedsMax() const;
inline const VFloat& pedsMin() const;
inline const VFloat& noiseMax() const;
inline const VFloat& noiseMin() const;
inline const VFloat& rawMax() const;
inline const VFloat& rawMin() const;
// ---------- misc ----------
/** Prints analysis results. */
void print( std::stringstream&, uint32_t apv_number = 0 );
/** Overrides base method. */
void summary( std::stringstream& ) const;
/** Resets analysis member data. */
void reset();
// ---------- private member data ----------
private:
// VVFloats means: 1 vector per APV, 1 value per strip.
/** Peds values. */
VVFloat peds_;
/** Noise values. */
VVFloat noise_;
/** Raw noise values. */
VVFloat raw_;
// VVInts means: 1 vector per APV, values are strip numbers.
/** Dead strips. */
VVInt dead_;
/** Noisy strips. */
VVInt noisy_;
// VFloat: 1 value per APV
/** Mean peds value. */
VFloat pedsMean_;
/** Rms spread in peds. */
VFloat pedsSpread_;
/** Mean noise value. */
VFloat noiseMean_;
/** Rms spread in noise. */
VFloat noiseSpread_;
/** Mean raw noise value. */
VFloat rawMean_;
/** Rms spread in raw noise. */
VFloat rawSpread_;
/** Max peds value. */
VFloat pedsMax_;
/** Min peds value. */
VFloat pedsMin_;
/** Max noise value. */
VFloat noiseMax_;
/** Min noise value. */
VFloat noiseMin_;
/** Max raw noise value. */
VFloat rawMax_;
/** Min raw noise value. */
VFloat rawMin_;
// true if legacy histogram naming is used
bool legacy_;
};
// ---------- Inline methods ----------
const NoiseAnalysis::VVFloat& NoiseAnalysis::peds() const { return peds_; }
const NoiseAnalysis::VVFloat& NoiseAnalysis::noise() const { return noise_; }
const NoiseAnalysis::VVFloat& NoiseAnalysis::raw() const { return raw_; }
const NoiseAnalysis::VVInt& NoiseAnalysis::dead() const { return dead_; }
const NoiseAnalysis::VVInt& NoiseAnalysis::noisy() const { return noisy_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::pedsMean() const { return pedsMean_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::pedsSpread() const { return pedsSpread_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::noiseMean() const { return noiseMean_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::noiseSpread() const { return noiseSpread_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::rawMean() const { return rawMean_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::rawSpread() const { return rawSpread_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::pedsMax() const { return pedsMax_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::pedsMin() const { return pedsMin_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::noiseMax() const { return noiseMax_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::noiseMin() const { return noiseMin_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::rawMax() const { return rawMax_; }
const NoiseAnalysis::VFloat& NoiseAnalysis::rawMin() const { return rawMin_; }
#endif // CondFormats_SiStripObjects_NoiseAnalysis_H
| 28.03125 | 88 | 0.691639 |
36b896d06240cf1e16ddf20120fb9d79aeaa67ad | 9,696 | c | C | kcfi/llvm-kcfi/tools/clang/test/CodeGen/exceptions-seh-leave.c | IntelSTORM/Projects | b983417a5ca22c7679da5a1144b348863bea5698 | [
"Intel"
] | 1 | 2022-01-11T11:12:00.000Z | 2022-01-11T11:12:00.000Z | kcfi/llvm-kcfi/tools/clang/test/CodeGen/exceptions-seh-leave.c | IntelSTORMteam/Jurassic-Projects | b983417a5ca22c7679da5a1144b348863bea5698 | [
"Intel"
] | null | null | null | kcfi/llvm-kcfi/tools/clang/test/CodeGen/exceptions-seh-leave.c | IntelSTORMteam/Jurassic-Projects | b983417a5ca22c7679da5a1144b348863bea5698 | [
"Intel"
] | null | null | null | // RUN: %clang_cc1 %s -triple x86_64-pc-win32 -fms-extensions -emit-llvm -o - | FileCheck %s
void g(void);
//////////////////////////////////////////////////////////////////////////////
// __leave with __except
// Nothing in the __try block can trap, so __try.cont isn't created.
int __leave_with___except_simple() {
int myres = 0;
__try {
myres = 15;
__leave;
myres = 23;
} __except (1) {
return 0;
}
return 1;
}
// CHECK-LABEL: define i32 @__leave_with___except_simple()
// CHECK: store i32 15, i32* %myres
// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
// CHECK-NOT: store i32 23
// CHECK: [[tryleave]]
// CHECK-NEXT: ret i32 1
// The "normal" case.
int __leave_with___except() {
int myres = 0;
__try {
g();
__leave;
myres = 23;
} __except (1) {
return 0;
}
return 1;
}
// CHECK-LABEL: define i32 @__leave_with___except()
// CHECK: invoke void @g()
// CHECK-NEXT: to label %[[cont:.*]] unwind label %{{.*}}
// For __excepts, instead of an explicit __try.__leave label, we could use
// use invoke.cont as __leave jump target instead. However, not doing this
// keeps the CodeGen code simpler, __leave is very rare, and SimplifyCFG will
// simplify this anyways.
// CHECK: [[cont]]
// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
// CHECK-NOT: store i32 23
// CHECK: [[tryleave]]
// CHECK-NEXT: br label %
//////////////////////////////////////////////////////////////////////////////
// __leave with __finally
void abort(void) __attribute__((noreturn));
// Nothing in the __try block can trap, so __finally.cont and friends aren't
// created.
int __leave_with___finally_simple() {
int myres = 0;
__try {
myres = 15;
__leave;
myres = 23;
} __finally {
return 0;
}
return 1;
}
// CHECK-LABEL: define i32 @__leave_with___finally_simple()
// CHECK: store i32 15, i32* %myres
// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
// CHECK-NOT: store i32 23
// CHECK: [[tryleave]]
// CHECK-NEXT: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: call void @"\01?fin$0@0@__leave_with___finally_simple@@"(i8 0, i8* %[[fp]])
// __finally block doesn't return, __finally.cont doesn't exist.
int __leave_with___finally_noreturn() {
int myres = 0;
__try {
myres = 15;
__leave;
myres = 23;
} __finally {
abort();
}
return 1;
}
// CHECK-LABEL: define i32 @__leave_with___finally_noreturn()
// CHECK: store i32 15, i32* %myres
// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
// CHECK-NOT: store i32 23
// CHECK: [[tryleave]]
// CHECK-NEXT: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: call void @"\01?fin$0@0@__leave_with___finally_noreturn@@"(i8 0, i8* %[[fp]])
// The "normal" case.
int __leave_with___finally() {
int myres = 0;
__try {
g();
__leave;
myres = 23;
} __finally {
return 0;
}
return 1;
}
// CHECK-LABEL: define i32 @__leave_with___finally()
// CHECK: invoke void @g()
// CHECK-NEXT: to label %[[cont:.*]] unwind label %{{.*}}
// For __finally, there needs to be an explicit __try.__leave, because
// abnormal.termination.slot needs to be set there.
// CHECK: [[cont]]
// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
// CHECK-NOT: store i32 23
// CHECK: [[tryleave]]
// CHECK-NEXT: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: call void @"\01?fin$0@0@__leave_with___finally@@"(i8 0, i8* %[[fp]])
//////////////////////////////////////////////////////////////////////////////
// Mixed, nested cases.
int nested___except___finally() {
int myres = 0;
__try {
__try {
g();
} __finally {
g();
__leave; // Refers to the outer __try, not the __finally!
myres = 23;
return 0;
}
myres = 51;
} __except (1) {
}
return 1;
}
// CHECK-LABEL: define i32 @nested___except___finally()
// CHECK-LABEL: invoke void @g()
// CHECK-NEXT: to label %[[g1_cont1:.*]] unwind label %[[g1_lpad:.*]]
// CHECK: [[g1_cont1]]
// CHECK-NEXT: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: invoke void @"\01?fin$0@0@nested___except___finally@@"(i8 0, i8* %[[fp]])
// CHECK-NEXT: to label %[[fin_cont:.*]] unwind label %[[g2_lpad:.*]]
// CHECK: [[fin_cont]]
// CHECK: store i32 51, i32* %
// CHECK-NEXT: br label %[[trycont:[^ ]*]]
// CHECK: [[g1_lpad]]
// CHECK-NEXT: landingpad
// CHECK-NEXT: catch i8* null
// CHECK: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: invoke void @"\01?fin$0@0@nested___except___finally@@"(i8 1, i8* %[[fp]])
// CHECK-NEXT: to label %[[g1_resume:.*]] unwind label %[[g2_lpad]]
// CHECK: [[g2_lpad]]
// CHECK: br label %[[trycont]]
// CHECK: [[trycont]]
// CHECK-NEXT: ret i32 1
// CHECK-LABEL: define internal void @"\01?fin$0@0@nested___except___finally@@"(i8 %abnormal_termination, i8* %frame_pointer)
// CHECK: call void @g()
// CHECK: unreachable
int nested___except___except() {
int myres = 0;
__try {
__try {
g();
myres = 16;
} __except (1) {
g();
__leave; // Refers to the outer __try, not the __except we're in!
myres = 23;
return 0;
}
myres = 51;
} __except (1) {
}
return 1;
}
// The order of basic blocks in the below doesn't matter.
// CHECK-LABEL: define i32 @nested___except___except()
// CHECK-LABEL: invoke void @g()
// CHECK-NEXT: to label %[[g1_cont:.*]] unwind label %[[g1_lpad:.*]]
// CHECK: [[g1_cont]]
// CHECK: store i32 16, i32* %myres
// CHECK-NEXT: br label %[[trycont:[^ ]*]]
// CHECK: [[g1_lpad]]
// CHECK: br label %[[except:[^ ]*]]
// CHECK: [[except]]
// CHECK-NEXT: invoke void @g()
// CHECK-NEXT: to label %[[g2_cont:.*]] unwind label %[[g2_lpad:.*]]
// CHECK: [[g2_cont]]
// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
// CHECK-NOT: store i32 23
// CHECK: [[g2_lpad]]
// CHECK: br label %[[outerexcept:[^ ]*]]
// CHECK: [[outerexcept]]
// CHECK-NEXT: br label %[[trycont4:[^ ]*]]
// CHECK: [[trycont4]]
// CHECK-NEXT: ret i32 1
// CHECK: [[trycont]]
// CHECK-NEXT: store i32 51, i32* %myres
// CHECK-NEXT: br label %[[tryleave]]
// CHECK: [[tryleave]]
// CHECK-NEXT: br label %[[trycont4]]
int nested___finally___except() {
int myres = 0;
__try {
__try {
g();
} __except (1) {
g();
__leave; // Refers to the outer __try, not the __except!
myres = 23;
return 0;
}
myres = 51;
} __finally {
}
return 1;
}
// The order of basic blocks in the below doesn't matter.
// CHECK-LABEL: define i32 @nested___finally___except()
// CHECK-LABEL: invoke void @g()
// CHECK-NEXT: to label %[[g1_cont:.*]] unwind label %[[g1_lpad:.*]]
// CHECK: [[g1_cont]]
// CHECK-NEXT: br label %[[trycont:[^ ]*]]
// CHECK: [[g1_lpad]]
// CHECK: br label %[[except:[^ ]*]]
// CHECK: [[except]]
// CHECK-NEXT: invoke void @g()
// CHECK-NEXT: to label %[[g2_cont:.*]] unwind label %[[g2_lpad:.*]]
// CHECK: [[g2_cont]]
// CHECK-NEXT: br label %[[tryleave:[^ ]*]]
// CHECK-NOT: 23
// CHECK: [[g2_lpad]]
// CHECK: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: call void @"\01?fin$0@0@nested___finally___except@@"(i8 1, i8* %[[fp]])
// CHECK-NEXT: br label %[[ehresume:[^ ]*]]
// CHECK: [[trycont]]
// CHECK: store i32 51, i32* %
// CHECK-NEXT: br label %[[tryleave]]
// CHECK: [[tryleave]]
// CHECK: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: call void @"\01?fin$0@0@nested___finally___except@@"(i8 0, i8* %[[fp]])
// CHECK-NEXT: ret i32 1
// CHECK: [[ehresume]]
// CHECK: resume
// CHECK-LABEL: define internal void @"\01?fin$0@0@nested___finally___except@@"(i8 %abnormal_termination, i8* %frame_pointer)
// CHECK: ret void
int nested___finally___finally() {
int myres = 0;
__try {
__try {
g();
myres = 16;
} __finally {
g();
__leave; // Refers to the outer __try, not the __finally we're in!
myres = 23;
return 0;
}
myres = 51;
} __finally {
}
return 1;
}
// The order of basic blocks in the below doesn't matter.
// CHECK-LABEL: define i32 @nested___finally___finally()
// CHECK-LABEL: invoke void @g()
// CHECK-NEXT: to label %[[g1_cont:.*]] unwind label %[[g1_lpad:.*]]
// CHECK: [[g1_cont]]
// CHECK: store i32 16, i32* %[[myres:[^ ]*]],
// CHECK: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: invoke void @"\01?fin$1@0@nested___finally___finally@@"(i8 0, i8* %[[fp]])
// CHECK-NEXT: to label %[[finally_cont:.*]] unwind label %[[g2_lpad:.*]]
// CHECK: [[finally_cont]]
// CHECK: store i32 51, i32* %[[myres]]
// CHECK: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: call void @"\01?fin$0@0@nested___finally___finally@@"(i8 0, i8* %[[fp]])
// CHECK-NEXT: ret i32 1
// CHECK: [[g1_lpad]]
// CHECK-NEXT: landingpad
// CHECK-NEXT: cleanup
// CHECK: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: invoke void @"\01?fin$1@0@nested___finally___finally@@"(i8 1, i8* %[[fp]])
// CHECK-NEXT: to label %[[finally_cont2:.*]] unwind label %[[g2_lpad]]
// CHECK: [[g2_lpad]]
// CHECK-NEXT: landingpad
// CHECK-NEXT: cleanup
// CHECK: br label %[[ehcleanup:.*]]
// CHECK: [[finally_cont2]]
// CHECK: br label %[[ehcleanup]]
// CHECK: [[ehcleanup]]
// CHECK: %[[fp:[^ ]*]] = call i8* @llvm.frameaddress(i32 0)
// CHECK-NEXT: call void @"\01?fin$0@0@nested___finally___finally@@"(i8 1, i8* %[[fp]])
// CHECK: resume
// CHECK-LABEL: define internal void @"\01?fin$0@0@nested___finally___finally@@"(i8 %abnormal_termination, i8* %frame_pointer)
// CHECK: ret void
// CHECK-LABEL: define internal void @"\01?fin$1@0@nested___finally___finally@@"(i8 %abnormal_termination, i8* %frame_pointer)
// CHECK: call void @g()
// CHECK: unreachable
| 27.702857 | 126 | 0.594988 |
9a9fd5ebb0d0c0862c98ed756dc5d1c7cb504e93 | 1,059 | c | C | My_Captain_C_Programming_Task_9.c | ADVAIT135/My_Captain_C_MARCH_21 | 19ebb24fe380cdadfe7f1616cb61a0b466d9968e | [
"MIT"
] | 1 | 2021-03-21T05:49:28.000Z | 2021-03-21T05:49:28.000Z | My_Captain_C_Programming_Task_9.c | ADVAIT135/My_Captain_C_MARCH_21 | 19ebb24fe380cdadfe7f1616cb61a0b466d9968e | [
"MIT"
] | null | null | null | My_Captain_C_Programming_Task_9.c | ADVAIT135/My_Captain_C_MARCH_21 | 19ebb24fe380cdadfe7f1616cb61a0b466d9968e | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<string.h>
int main(){
char a[80];
printf("Enter the string to reverse : ");
gets(a); //Taking User input
FILE *fp;
fp = fopen("Input-String.txt","w"); //Making a new file named Input-String to store the text entered by the user
fprintf(fp,"%s",a); //Storing the input given by the user
fclose(fp); //Closing the file
printf("\n");
fp = fopen("Input-String.txt","r");
printf("The input string is :%s",a); //Printing the content which is entered by the user and is stored in the Input-String file
fclose(fp); //Closing the file
printf("\n");
fp = fopen("Reverse-of-the-Input-String.txt","w"); //Making a new file named Reverse-of-the-Input-String to the reverse of the content entered and stored in the Input-String File
fprintf(fp,"%s",strrev(a)); //Storing the reverse of the input
printf("\nThe reverse of the entered input string is: %s",a);//Printing the reverse of the file
fclose(fp);//Closing the file
printf("\n");
return 0;
}
| 42.36 | 183 | 0.643059 |
966115e8b0d4a091c0eae88f6818046f47bf53bc | 273 | h | C | version.h | tizenorg/tools.nasm | c238cd4ffa8bdd99911c40b32da9265175ea3b81 | [
"BSD-2-Clause"
] | null | null | null | version.h | tizenorg/tools.nasm | c238cd4ffa8bdd99911c40b32da9265175ea3b81 | [
"BSD-2-Clause"
] | null | null | null | version.h | tizenorg/tools.nasm | c238cd4ffa8bdd99911c40b32da9265175ea3b81 | [
"BSD-2-Clause"
] | null | null | null | #ifndef NASM_VERSION_H
#define NASM_VERSION_H
#define NASM_MAJOR_VER 2
#define NASM_MINOR_VER 7
#define NASM_SUBMINOR_VER 99
#define NASM_PATCHLEVEL_VER 97
#define NASM_VERSION_ID 0x02076361
#define NASM_VER "2.08rc7"
#endif /* NASM_VERSION_H */
| 27.3 | 38 | 0.747253 |
960b629504698e64809eabdc316e359f76cbc2bf | 15,157 | c | C | Relinquish/r_draw_framebuffer.c | valiet/quel_solaar | 70dc81fc77858c2b96a2a9ceb7d1672e52758977 | [
"BSD-3-Clause"
] | 2 | 2022-01-20T16:24:55.000Z | 2022-01-29T04:11:47.000Z | Relinquish/r_draw_framebuffer.c | valiet/quel_solaar | 70dc81fc77858c2b96a2a9ceb7d1672e52758977 | [
"BSD-3-Clause"
] | null | null | null | Relinquish/r_draw_framebuffer.c | valiet/quel_solaar | 70dc81fc77858c2b96a2a9ceb7d1672e52758977 | [
"BSD-3-Clause"
] | null | null | null | #include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "forge.h"
#include "r_include.h"
void (APIENTRY *r_glBindFramebufferEXT)(GLenum target, GLuint framebuffer) = NULL;
void (APIENTRY *r_glDeleteFramebuffersEXT)(GLsizei n, const GLuint *framebuffers) = NULL;
void (APIENTRY *r_glGenFramebuffersEXT)(GLsizei n, GLuint *framebuffers) = NULL;
void (APIENTRY *r_glBindRenderbufferEXT)(GLenum target, GLuint renderbuffer) = NULL;
void (APIENTRY *r_glDeleteRenderbuffersEXT)(GLsizei n, const GLuint *renderbuffers) = NULL;
void (APIENTRY *r_glGenRenderbuffersEXT)(GLsizei n, GLuint *renderbuffers) = NULL;
GLenum (APIENTRY *r_glCheckFramebufferStatusEXT)(GLenum target) = NULL;
void (APIENTRY *r_glRenderbufferStorageEXT)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) = NULL;
void (APIENTRY *r_glFramebufferTexture2DEXT)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) = NULL;
void (APIENTRY *r_glFramebufferRenderbufferEXT)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) = NULL;
void (APIENTRY *r_glDrawBuffersARB)(GLuint, GLenum *buffers) = NULL;
void (APIENTRY *r_glTexImage3D)(enum target, int level, enum internalformat, uint width, uint height, uint depth, int border, enum format, enum type, const void* pixels) = NULL;
#define GL_R8 0x8229
#define GL_RG8 0x822B
#define GL_R16F 0x822D
#define GL_R32F 0x822E
#define GL_RG16F 0x822F
#define GL_RG32F 0x8230
#define GL_RED 0x1903
#define GL_RG 0x8227
#define GL_RGB16F_ARB 0x881B
#define GL_RGBA16F_ARB 0x881A
#define GL_RGB32F_ARB 0x8815
#define GL_RGBA32F_ARB 0x8814
#define GL_TEXTURE_WRAP_R 0x8072
#define GL_TEXTURE_3D 0x806F
#define GL_DEPTH_COMPONENT16 0x81A5
#define GL_DEPTH24_STENCIL8_EXT 0x88F0
#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
boolean r_framebuffer_status(void)
{
GLenum status;
if (!r_glBindFramebufferEXT)
return FALSE;
status = r_glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
switch(status)
{
case GL_FRAMEBUFFER_COMPLETE_EXT:
return TRUE;
break;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
fprintf(stderr, "Unsupported framebuffer format\n");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
fprintf(stderr, "Framebuffer incomplete, missing attachment\n");
break;
/* case GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT:
printf("Framebuffer incomplete, duplicate attachment\n");
break;*/
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
fprintf(stderr, "Framebuffer incomplete, attached images must have same dimensions\n");
break;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
fprintf(stderr, "Framebuffer incomplete, attached images must have same format\n");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
fprintf(stderr, "Framebuffer incomplete, missing draw buffer\n");
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
fprintf(stderr, "Framebuffer incomplete, missing read buffer\n");
break;
default:
fprintf(stderr, "Error id %x\n", status);
break;
}
return FALSE;
}
uint r_framebuffer_allocate(uint *buffers, uint buffer_count, uint depth_buffer)
{
uint i, fbo;
r_glGenFramebuffersEXT(1, &fbo);
r_glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
for(i = 0; i < buffer_count; i++)
r_glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, buffers[i], 0);
if(depth_buffer != -1)
r_glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_buffer);
if(!r_framebuffer_status())
{
r_glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
return -1;
}
r_glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
return fbo;
}
void r_framebuffer_bind(uint id)
{
/* GLenum attachements[8] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT0_EXT + 1, GL_COLOR_ATTACHMENT0_EXT + 2, GL_COLOR_ATTACHMENT0_EXT + 3, GL_COLOR_ATTACHMENT0_EXT + 4, GL_COLOR_ATTACHMENT0_EXT + 5, GL_COLOR_ATTACHMENT0_EXT + 6, GL_COLOR_ATTACHMENT0_EXT + 7};
p_glDrawBuffersARB(8, attachements);
*/ r_glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id);
}
void r_framebuffer_free(uint fbo)
{
r_glDeleteFramebuffersEXT(1, &fbo);
}
void r_framebuffer_clear(float red, float green, float blue, float alpha, boolean color, boolean depth_stencil)
{
uint32 bits = 0;
glClearColor(red, green, blue, alpha);
if(color)
bits = GL_COLOR_BUFFER_BIT;
if(depth_stencil)
bits = bits | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
glClear(bits);
}
boolean r_framebuffer_init(void)
{
if(r_extension_test("GL_EXT_texture3D"))
r_glTexImage3D = r_extension_get_address("glTexImage3D");
if(r_extension_test("GL_ARB_draw_buffers"))
r_glDrawBuffersARB = r_extension_get_address("glDrawBuffersARB");
if(r_extension_test("GL_EXT_framebuffer_object"))
{
r_glBindFramebufferEXT = r_extension_get_address("glBindFramebufferEXT");
r_glDeleteFramebuffersEXT = r_extension_get_address("glDeleteFramebuffersEXT");
r_glGenFramebuffersEXT = r_extension_get_address("glGenFramebuffersEXT");
r_glBindRenderbufferEXT = r_extension_get_address("glBindRenderbufferEXT");
r_glDeleteRenderbuffersEXT = r_extension_get_address("glDeleteRenderbuffersEXT");
r_glGenRenderbuffersEXT = r_extension_get_address("glGenRenderbuffersEXT");
r_glCheckFramebufferStatusEXT = r_extension_get_address("glCheckFramebufferStatusEXT");
r_glRenderbufferStorageEXT = r_extension_get_address("glRenderbufferStorageEXT");
r_glFramebufferTexture2DEXT = r_extension_get_address("glFramebufferTexture2DEXT");
r_glFramebufferRenderbufferEXT = r_extension_get_address("glFramebufferRenderbufferEXT");
return TRUE;
}
return FALSE;
}
uint r_texture_allocate(PImageFormat format, uint x, uint y, uint z, boolean filter, boolean tile, void *data)
{
uint i, texture_id, type, dimensions = GL_TEXTURE_2D, internal_format, input_format, data_type, stride;
boolean free_data;
if(x == 0)
x = 1;
if(y == 0)
y = 1;
if(z == 0)
z = 1;
if(r_glTexImage3D == NULL && z != 1 && z != R_IB_IMAGE_CUBE)
{
printf("RELINQUISH Error: Graphics driver does not support 3D textures\n");
return -1;
}
if(format >= R_IF_DEPTH16)
{
r_glGenRenderbuffersEXT(1, &texture_id);
r_glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, texture_id);
if(format == R_IF_DEPTH16)
r_glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, x, y);
else if(format == R_IF_DEPTH24)
r_glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, x, y);
else if(format == R_IF_DEPTH32)
r_glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT32, x, y);
else
r_glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, x, y);
return texture_id;
}else
{
if(z == R_IB_IMAGE_CUBE)
dimensions = GL_TEXTURE_CUBE_MAP_EXT;
else if(z != 1)
dimensions = GL_TEXTURE_3D;
glEnable(dimensions);
glGenTextures(1, &texture_id);
glBindTexture(dimensions, texture_id);
switch(format)
{
case R_IF_R_UINT8 :
internal_format = GL_R8;
input_format = GL_RED;
data_type = GL_UNSIGNED_BYTE;
break;
case R_IF_RG_UINT8 :
internal_format = GL_RG8;
input_format = GL_RG;
data_type = GL_UNSIGNED_BYTE;
break;
case R_IF_RGB_UINT8 :
internal_format = GL_RGB;
input_format = GL_RGB;
data_type = GL_UNSIGNED_BYTE;
break;
case R_IF_RGBA_UINT8 :
internal_format = GL_RGBA;
input_format = GL_RGBA;
data_type = GL_UNSIGNED_BYTE;
break;
case R_IF_R_FLOAT16 :
internal_format = GL_R16F;
input_format = GL_RED;
data_type = GL_FLOAT;
break;
case R_IF_RG_FLOAT16 :
internal_format = GL_RG16F;
input_format = GL_RG;
data_type = GL_FLOAT;
break;
case R_IF_RGB_FLOAT16 :
internal_format = GL_RGB16F_ARB;
input_format = GL_RGB;
data_type = GL_FLOAT;
break;
case R_IF_RGBA_FLOAT16 :
internal_format = GL_RGBA16F_ARB;
input_format = GL_RGBA;
data_type = GL_FLOAT;
break;
case R_IF_R_FLOAT32 :
internal_format = GL_R32F;
input_format = GL_RED;
data_type = GL_FLOAT;
break;
case R_IF_RG_FLOAT32 :
internal_format = GL_RG32F;
input_format = GL_RG;
data_type = GL_FLOAT;
break;
case R_IF_RGB_FLOAT32 :
internal_format = GL_RGB32F_ARB;
input_format = GL_RGB;
data_type = GL_FLOAT;
break;
case R_IF_RGBA_FLOAT32 :
internal_format = GL_RGBA32F_ARB;
input_format = GL_RGBA;
data_type = GL_FLOAT;
break;
}
stride = 3 + format % 2;
free_data = data == NULL;
if(free_data)
{
float *buf = NULL;
data_type = GL_FLOAT;
if(dimensions == GL_TEXTURE_2D)
{
buf = malloc((sizeof *buf) * x * y * stride);
for(i = 0; i < x * y; i++)
{
buf[i * stride + 0] = (float)(i % x) / (float)x;
buf[i * stride + 1] = (float)(i / x) / (float)y;
buf[i * stride + 2] = 1.0;
if(((i % x) / 16 + (i / x) / 16) % 2 == 0)
{
buf[i * stride + 0] = 1.0 - buf[i * stride + 0];
buf[i * stride + 1] = 1.0 - buf[i * stride + 1];
buf[i * stride + 2] = 1.0 - buf[i * stride + 2];
}
if(stride == 4)
buf[i * stride + 3] = (float)(((i % x) / 16 + (i / x) / 16) % 2);
}
}
if(dimensions == GL_TEXTURE_3D)
{
buf = malloc((sizeof *buf) * x * y * z * stride);
for(i = 0; i < x * y * z; i++)
{
buf[i * stride + 0] = (float)(i % x) / (float)x;
buf[i * stride + 1] = (float)((i / x) % y) / (float)y;
buf[i * stride + 2] = (float)(i / (x * y)) / (float)z;
if(((i % x) / 8 + ((i / x) % y) / 8 + (i / (x * y)) / 8) % 2 == 0)
{
buf[i * stride + 0] = 1.0 - buf[i * stride + 0];
buf[i * stride + 1] = 1.0 - buf[i * stride + 1];
buf[i * stride + 2] = 1.0 - buf[i * stride + 2];
}
if(stride == 4)
buf[i * stride + 3] = (float)(((i % x) / 8 + ((i / x) % y) / 8 + (i / (x * y)) / 8) % 2);
}
}
if(dimensions == GL_TEXTURE_CUBE_MAP_EXT)
{
buf = malloc((sizeof *buf) * x * y * 6 * stride);
for(i = 0; i < x * y; i++)
{
buf[i * stride + 0] = (float)(i % x) / (float)x;
buf[i * stride + 1] = (float)((i / x) % y) / (float)y;
buf[i * stride + 2] = (float)(i % x) / (float)x;
if(((i % x) / 16 + ((i / x) % (x * y)) / 16) % 2 == 0)
{
buf[i * stride + 0] = 1.0 - buf[i * stride + 0];
buf[i * stride + 1] = 1.0 - buf[i * stride + 1];
buf[i * stride + 2] = 1.0 - buf[i * stride + 2];
}
if(stride == 4)
buf[i * stride + 3] = (float)(((i % x) / 16 + ((i / x) % (x * y)) / 16) % 2);
}
for(i = x * y * stride * 0 + 0; i < x * y * stride * 1; i += stride)
buf[i] = 1.0;
for(i = x * y * stride * 1 + 1; i < x * y * stride * 2; i += stride)
buf[i] = 1.0;
for(i = x * y * stride * 2 + 3; i < x * y * stride * 3; i += stride)
buf[i] = 1.0;
for(i = x * y * stride * 3 + 0; i < x * y * stride * 4; i += stride)
buf[i] = 0.0;
for(i = x * y * stride * 4 + 1; i < x * y * stride * 5; i += stride)
buf[i] = 0.0;
for(i = x * y * stride * 5 + 2; i < x * y * stride * 6; i += stride)
buf[i] = 0.0;
}
data = buf;
}
if(dimensions == GL_TEXTURE_CUBE_MAP_EXT)
{
if(data == NULL)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT, 0, internal_format, x, y, 0, input_format, data_type, NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT, 0, internal_format, x, y, 0, input_format, data_type, NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT, 0, internal_format, x, y, 0, input_format, data_type, NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT, 0, internal_format, x, y, 0, input_format, data_type, NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT, 0, internal_format, x, y, 0, input_format, data_type, NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT, 0, internal_format, x, y, 0, input_format, data_type, NULL);
}else
{
if(data_type == GL_FLOAT)
{
float *d;
d = data;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT, 0, internal_format, x, y, 0, input_format, data_type, d);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 1]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 2]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 3]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 4]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 5]);
}else
{
unsigned char *d;
d = data;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT, 0, internal_format, x, y, 0, input_format, data_type, d);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 1]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 2]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 3]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 4]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT, 0, internal_format, x, y, 0, input_format, data_type, &d[stride * x * y * 5]);
}
}
}else if(dimensions == GL_TEXTURE_3D)
r_glTexImage3D(dimensions, 0, internal_format, x, y, z, 0, input_format, data_type, data);
else
glTexImage2D(dimensions, 0, internal_format, x, y, 0, input_format, data_type, data);
if(free_data && data != NULL)
free(data);
if(tile)
type = GL_REPEAT;
else
type = GL_CLAMP;
glTexParameterf(dimensions, GL_TEXTURE_WRAP_S, type);
glTexParameterf(dimensions, GL_TEXTURE_WRAP_T, type);
if(dimensions == GL_TEXTURE_3D)
glTexParameterf(dimensions, GL_TEXTURE_WRAP_R, type);
if(filter)
type = GL_LINEAR;
else
type = GL_NEAREST;
glTexParameterf(dimensions, GL_TEXTURE_MAG_FILTER, type);
glTexParameterf(dimensions, GL_TEXTURE_MIN_FILTER, type);
}
return texture_id;
}
void r_texture_free(uint texture_id)
{
glDeleteTextures(1, &texture_id);
}
uint64 r_shader_uniform_texture_pointer_get(uint texture_id)
{
if(r_glGetTextureHandleARB == NULL)
return (uint64)texture_id;
else
{
uint64 handle;
handle = r_glGetTextureHandleARB(texture_id);
r_glMakeTextureHandleResidentARB(handle);
return handle;
}
} | 36.174224 | 265 | 0.670449 |
c58c42ba75469fc5ad2288f0ca0eb97c76cbc052 | 117 | h | C | src/termios/B110.h | ung-org/lib-c | 55fc64c7ffd7792bc88451a736c2e94e5865282f | [
"MIT"
] | null | null | null | src/termios/B110.h | ung-org/lib-c | 55fc64c7ffd7792bc88451a736c2e94e5865282f | [
"MIT"
] | null | null | null | src/termios/B110.h | ung-org/lib-c | 55fc64c7ffd7792bc88451a736c2e94e5865282f | [
"MIT"
] | null | null | null | #include <termios.h>
#define B110 (0x3)
/*
POSIX(1)
*/
| 19.5 | 80 | 0.290598 |
5ca30fe071db8fbe54015da03e5d06911b2bf6dd | 1,770 | h | C | src/mapleall/maple_ir/include/prim_types.h | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 5 | 2019-09-02T04:44:52.000Z | 2021-11-08T12:23:51.000Z | src/mapleall/maple_ir/include/prim_types.h | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 2 | 2020-07-21T01:22:01.000Z | 2021-12-06T08:07:16.000Z | src/mapleall/maple_ir/include/prim_types.h | MapleSystem/OpenArkCompiler | fc250857642ca38ac8b83ae7486513fadf3ab742 | [
"MulanPSL-1.0"
] | 4 | 2019-09-02T04:46:52.000Z | 2020-09-10T11:30:03.000Z | /*
* Copyright (c) [2019] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef MAPLE_IR_INCLUDE_PRIM_TYPES_H
#define MAPLE_IR_INCLUDE_PRIM_TYPES_H
#include "types_def.h"
#include "cfg_primitive_types.h"
namespace maple {
class PrimitiveType {
public:
// we need implicit conversion from PrimType to PrimitiveType, so there is no explicit keyword here.
PrimitiveType(PrimType type) : property(GetPrimitiveTypeProperty(type)) {}
~PrimitiveType() = default;
PrimType GetType() const {
return property.type;
}
bool IsInteger() const {
return property.isInteger;
}
bool IsUnsigned() const {
return property.isUnsigned;
}
bool IsAddress() const {
return property.isAddress;
}
bool IsFloat() const {
return property.isFloat;
}
bool IsPointer() const {
return property.isPointer;
}
bool IsDynamic() const {
return property.isDynamic;
}
bool IsSimple() const {
return property.isSimple;
}
bool IsDynamicAny() const {
return property.isDynamicAny;
}
bool IsDynamicNone() const {
return property.isDynamicNone;
}
bool IsVector() const {
return property.isVector;
}
private:
const PrimitiveTypeProperty &property;
};
} // namespace maple
#endif // MAPLE_IR_INCLUDE_PRIM_TYPES_H
| 26.41791 | 102 | 0.720339 |
5cf8982e2ff5b188a90c93c592bbbdd429e07b23 | 3,593 | h | C | modules/skottie/utils/SkottieUtils.h | Cosmic-OS/platform_external_skia | f89680c603e4327be728cc757fdf162540ec7a58 | [
"BSD-3-Clause"
] | 2 | 2020-10-25T09:03:03.000Z | 2021-06-24T13:20:01.000Z | modules/skottie/utils/SkottieUtils.h | Cosmic-OS/platform_external_skia | f89680c603e4327be728cc757fdf162540ec7a58 | [
"BSD-3-Clause"
] | 2 | 2020-08-11T17:14:27.000Z | 2020-09-12T17:08:46.000Z | modules/skottie/utils/SkottieUtils.h | Cosmic-OS/platform_external_skia | f89680c603e4327be728cc757fdf162540ec7a58 | [
"BSD-3-Clause"
] | 14 | 2015-07-17T17:23:53.000Z | 2020-07-06T21:06:57.000Z | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkottieUtils_DEFINED
#define SkottieUtils_DEFINED
#include "modules/skottie/include/Skottie.h"
#include "modules/skottie/include/SkottieProperty.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace skottie_utils {
/**
* CustomPropertyManager implements a property management scheme where color/opacity/transform
* attributes are grouped and manipulated by name (one-to-many mapping).
*
* - setters apply the value to all properties in a named group
*
* - getters return all the managed property groups, and the first value within each of them
* (unchecked assumption: all properties within the same group have the same value)
*
* Attach to an Animation::Builder using the utility methods below to intercept properties and
* markers at build time.
*/
class CustomPropertyManager final {
public:
CustomPropertyManager();
~CustomPropertyManager();
using PropKey = std::string;
std::vector<PropKey> getColorProps() const;
skottie::ColorPropertyValue getColor(const PropKey&) const;
bool setColor(const PropKey&, const skottie::ColorPropertyValue&);
std::vector<PropKey> getOpacityProps() const;
skottie::OpacityPropertyValue getOpacity(const PropKey&) const;
bool setOpacity(const PropKey&, const skottie::OpacityPropertyValue&);
std::vector<PropKey> getTransformProps() const;
skottie::TransformPropertyValue getTransform(const PropKey&) const;
bool setTransform(const PropKey&, const skottie::TransformPropertyValue&);
std::vector<PropKey> getTextProps() const;
skottie::TextPropertyValue getText(const PropKey&) const;
bool setText(const PropKey&, const skottie::TextPropertyValue&);
struct MarkerInfo {
std::string name;
float t0, t1;
};
const std::vector<MarkerInfo>& markers() const { return fMarkers; }
// Returns a property observer to be attached to an animation builder.
sk_sp<skottie::PropertyObserver> getPropertyObserver() const;
// Returns a marker observer to be attached to an animation builder.
sk_sp<skottie::MarkerObserver> getMarkerObserver() const;
private:
class PropertyInterceptor;
class MarkerInterceptor;
static std::string acceptKey(const char* name) {
static constexpr char kPrefix = '$';
return (name[0] == kPrefix && name[1] != '\0')
? std::string(name + 1)
: std::string();
}
sk_sp<PropertyInterceptor> fPropertyInterceptor;
sk_sp<MarkerInterceptor> fMarkerInterceptor;
template <typename T>
using PropGroup = std::vector<std::unique_ptr<T>>;
template <typename T>
using PropMap = std::unordered_map<PropKey, PropGroup<T>>;
template <typename T>
std::vector<PropKey> getProps(const PropMap<T>& container) const;
template <typename V, typename T>
V get(const PropKey&, const PropMap<T>& container) const;
template <typename V, typename T>
bool set(const PropKey&, const V&, const PropMap<T>& container);
PropMap<skottie::ColorPropertyHandle> fColorMap;
PropMap<skottie::OpacityPropertyHandle> fOpacityMap;
PropMap<skottie::TransformPropertyHandle> fTransformMap;
PropMap<skottie::TextPropertyHandle> fTextMap;
std::vector<MarkerInfo> fMarkers;
std::string fCurrentNode;
};
} // namespace skottie_utils
#endif // SkottieUtils_DEFINED
| 32.963303 | 94 | 0.71027 |
d04c76cdd1205ce12517c814057126edf351e12f | 716 | h | C | Resources/WC_7_0_5_Headers/FTSFavCell.h | shuangwei-Ye/WeChat_tweak | 0f496f38f0336908258d606dcbef7067a096926a | [
"MIT"
] | 2 | 2021-05-30T07:50:20.000Z | 2022-02-23T15:42:53.000Z | Resources/WC_7_0_5_Headers/FTSFavCell.h | LP36911/WeChat_tweak | 0f496f38f0336908258d606dcbef7067a096926a | [
"MIT"
] | null | null | null | Resources/WC_7_0_5_Headers/FTSFavCell.h | LP36911/WeChat_tweak | 0f496f38f0336908258d606dcbef7067a096926a | [
"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 "MMTableViewCell.h"
@class AttributeLabel, FTSFavSearchItem, NSMutableArray, UIView;
@interface FTSFavCell : MMTableViewCell
{
FTSFavSearchItem *_searchItem;
NSMutableArray *_arrKeyword;
AttributeLabel *_titleLabel;
AttributeLabel *_descLabel;
AttributeLabel *_detailLabel;
UIView *_thumbImageView;
}
- (void).cxx_destruct;
- (void)initView;
- (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2;
- (void)setLineSpaceForLabel:(id)arg1;
- (void)updateFavSearchItem:(id)arg1 arrKeyword:(id)arg2;
- (void)updateStatus:(_Bool)arg1;
@end
| 23.866667 | 83 | 0.730447 |
fd9e6550172ec4da3f44aa3e3bf1b3985f717728 | 765 | c | C | src/line_separator.c | prasertcbs/C_tutorial | 8f277f4e7aff51da269fc66d22b52f34ea524e8a | [
"MIT"
] | null | null | null | src/line_separator.c | prasertcbs/C_tutorial | 8f277f4e7aff51da269fc66d22b52f34ea524e8a | [
"MIT"
] | null | null | null | src/line_separator.c | prasertcbs/C_tutorial | 8f277f4e7aff51da269fc66d22b52f34ea524e8a | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
//char *removeNewLine(char *s) {
// char *p0 = strchr(s, '\r');
// if (p0 != NULL) {
// *p0 = '\0';
// return s;
// }
//
// char *p = strchr(s, '\n'); // LF (Unix, Linux, macOS)
// if (p != NULL) {
// *p = '\0';
// return s;
// }
//}
char *removeNewLine(char *s) {
size_t pos = strcspn(s, "\r\n");
s[pos] = '\0';
return s;
}
int main() {
// Windows - CRLF (\r\n)
// Unix, macOS - LF (\n)
// FILE *f = fopen("movie_lf.txt", "r");
FILE *f = fopen("movie_crlf.txt", "r");
char str[500] = "";
int line = 0;
while ((fgets(str, 500, f)) != NULL) {
printf("%d: %s\n", ++line, removeNewLine(str));
}
fclose(f);
return 0;
} | 21.25 | 59 | 0.443137 |
fdc61b5621c4363408ba9b04ff59566da23b4175 | 3,368 | c | C | runtime/stdlib/ioctl.c | block8437/FailSafeC | 1458e382518ba8b56f680436873c3b42a89e1636 | [
"Apache-2.0"
] | 1 | 2018-02-10T02:52:09.000Z | 2018-02-10T02:52:09.000Z | runtime/stdlib/ioctl.c | block8437/FailSafeC | 1458e382518ba8b56f680436873c3b42a89e1636 | [
"Apache-2.0"
] | null | null | null | runtime/stdlib/ioctl.c | block8437/FailSafeC | 1458e382518ba8b56f680436873c3b42a89e1636 | [
"Apache-2.0"
] | null | null | null | /*
Part of Fail-Safe C Runtime. Produced by Yutaka Oiwa.
(c) 2001-2005 Yutaka Oiwa.
(c) 2005-2006 AIST.
(c) 2006 Lepidum Co. Ltd.
This file is written by Lepidum Co. Ltd. in 2006.
This file is distributed under Apache License 2.0 with a special exception.
See the file LICENSE contained in the distribution.
*/
/**
* @file stdlib/ioctl.c
*/
#define FSC_RUNTIME_LIBRARY
#include <fsc_runtime.h>
#include <wrapper_helper.h>
#include <copydata.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <stropts.h>
#include <stdio.h>
#define IOC_MAX_LEN (256-8)
#define IOC_MAGIC 0xabad10c0
struct ioc_buf {
char buf[IOC_MAX_LEN];
unsigned int magic_1;
unsigned int magic_2;
};
static int ioctl_ptr(int fd, int req, base_t buf_b, ofs_t buf_o, size_t len)
{
if (fsc_is_nullpointer(buf_b, buf_o)) {
return ioctl(fd, req, (void *)0);
} else {
struct ioc_buf b;
int ret;
if (len > IOC_MAX_LEN) {
errno = EINVAL;
return -1;
}
fsc_copy_to_raw(&b.buf[IOC_MAX_LEN-len], buf_b, buf_o, len);
b.magic_1 = IOC_MAGIC;
b.magic_2 = IOC_MAGIC;
ret = ioctl(fd, req, &b.buf[IOC_MAX_LEN-len]);
if (ret < 0 && errno == EFAULT) {
fsc_raise_error_library(0, req, ERR_SYSERROR, "ioctl returns EFAULT");
}
if (b.magic_1 != IOC_MAGIC || b.magic_2 != IOC_MAGIC) {
fsc_raise_error_library(0, req, ERR_SYSERROR, "ioctl corrupts memory");
}
fsc_copy_from_raw(buf_b, buf_o, &b.buf[IOC_MAX_LEN-len], len);
return value_of_int(ret);
}
}
static int ioctl_value(int fd, int req, unsigned int value)
{
int ret = ioctl(fd, req, value);
if (ret < 0 && errno == EFAULT) {
fsc_raise_error_library(0, req, ERR_SYSERROR, "ioctl returns EFAULT");
}
return ret;
}
/**
* @fn int ioctl(int fd, int req, ...)
* @param fd file descriptor.
* @param req function specifier.
* @param ... request specific arguments.
*
* @crashcase unknown
* @fsctype special
*
* @author Lepidum Co., Ltd.
*/
value FS_FiiV_i_ioctl(base_t fd_b, unsigned int fd_o,
base_t req_b, unsigned int req_o,
base_t va_b, unsigned int va_o)
{
#define IOCTL_ENTRY(req, name, is_ptr, tp, condition) \
IOCTL_ENTRY_##is_ptr(req, name, tp, condition)
#define IOCTL_ENTRY_PTR(req, name, tp, condition) \
case req: \
if (condition) { \
return ioctl_ptr(fd_o, name, value_b, value_o, sizeof (tp)); \
} \
break;
#define IOCTL_ENTRY_VALUE(req, name, tp, condition) \
case req: \
if (condition) { \
return ioctl_value(fd_o, name, value_o); \
} \
break;
#define IOCTL_ENTRY_NONE(req, name, tp, condition) \
case req: \
if (condition) { \
return ioctl_value(fd_o, name, 0); \
} \
break;
base_t value_b = 0;
ofs_t value_o = 0;
int FIFO = 0;
int SOCK = 0;
int TTY = 0;
struct stat st;
if (va_b != 0 && is_offset_ok(va_b, va_o)) {
/* ioctl(fd, req, value) */
value v = read_word(va_b, va_o);
value_b = base_remove_castflag(base_of_value(v));
value_o = ofs_of_value(v);
}
if (fstat(fd_o, &st) < 0) {
return value_of_int(-1);
}
FIFO = S_ISFIFO(st.st_mode);
SOCK = S_ISSOCK(st.st_mode);
if (S_ISCHR(st.st_mode)) {
TTY = isatty(fd_o);
}
switch (req_o) {
#include "ioctl_list.h"
}
errno = ENOTTY;
return value_of_int(-1);
}
| 24.948148 | 78 | 0.637173 |
6557ff2f272676d63c6043fb9606458c7b191e88 | 5,344 | h | C | IT Push/Pods/Headers/Public/ShareSDK2/Comment/UIViewController+Comment.h | DisillusionXuZX/IT-Push | 98db9de977c3580edd5ec13b8cb51fdecbb8aa57 | [
"Apache-2.0"
] | null | null | null | IT Push/Pods/Headers/Public/ShareSDK2/Comment/UIViewController+Comment.h | DisillusionXuZX/IT-Push | 98db9de977c3580edd5ec13b8cb51fdecbb8aa57 | [
"Apache-2.0"
] | null | null | null | IT Push/Pods/Headers/Public/ShareSDK2/Comment/UIViewController+Comment.h | DisillusionXuZX/IT-Push | 98db9de977c3580edd5ec13b8cb51fdecbb8aa57 | [
"Apache-2.0"
] | null | null | null | ///#begin zh-cn
//
// Created by ShareSDK.cn on 13-1-14.
// 官网地址:http://www.ShareSDK.cn
// 技术支持邮箱:support@sharesdk.cn
// 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复)
// 商务QQ:4006852216
// Copyright (c) 2013年 ShareSDK.cn. All rights reserved.
//
///#end
///#begin en
//
// Created by ShareSDK.cn on 13-1-14.
// Website:http://www.ShareSDK.cn
// Support E-mail:support@sharesdk.cn
// WeChat ID:ShareSDK (If publish a new version, we will be push the updates content of version to you. If you have any questions about the ShareSDK, you can get in touch through the WeChat with us, we will respond within 24 hours)
// Business QQ:4006852216
// Copyright (c) 2013年 ShareSDK.cn. All rights reserved.
//
///#end
#import <UIKit/UIKit.h>
#import "SSCCommentListViewController.h"
#import "SSCCommentViewController.h"
#import "SSCCommentToolbar.h"
@interface UIViewController (Comment)
///#begin zh-cn
/**
* @brief 弹出评论列表视图控制器
*
* @param contentId 内容唯一标识
* @param title 标题
* @param animated 动画标识,YES 表示动画过渡, NO 表示无动画过渡
*
* @return 评论列表视图控制器
*/
///#end
///#begin en
/**
* @brief Presend a comment list view controller.
*
* @param contentId Content id
* @param title Title
* @param animated Animated flag, YES, said animated transitions, NO means no animated transitions
*
* @return A comment list view controller.
*/
///#end
- (SSCCommentListViewController *)presentCommentListViewControllerWithContentId:(NSString *)contentId
title:(NSString *)title
animated:(BOOL)animated;
///#begin zh-cn
/**
* @brief 从导航控制器中放入评论列表视图控制器,此方法必须要当前视图控制器在导航视图容器中。
*
* @param contentId 内容唯一标识
* @param title 标题
* @param animated 动画标识,YES 表示动画过渡, NO 表示无动画过渡
*/
///#end
///#begin en
/**
* @brief Add comment list view controller from the navigation controller, this method must be the current view controller in the navigation view container.
*
* @param contentId Content id.
* @param title Title
* @param animated Animated flag, YES, said animated transitions, NO means no animated transitions
*/
///#end
- (SSCCommentListViewController *)pushCommentListViewControllerWithContentId:(NSString *)contentId
title:(NSString *)title
animated:(BOOL)animated;
///#begin zh-cn
/**
* @brief 弹出评论视图控制器
*
* @param contentId 内容唯一标识
* @param title 标题
* @param comment 被评论信息,如果为nil,则表示对主题进行评论
* @param animated 动画标识,YES 表示动画过渡, NO 表示无动画过渡
* @param resultHandler 评论回调事件
*
* @return 评论视图控制器
*/
///#end
///#begin en
/**
* @brief present a comment view controller.
*
* @param contentId Content id.
* @param title Title
* @param comment Commented information, if it is nil, it means to comment on the topic
* @param animated Animated flag, YES, said animated transitions, NO means no animated transitions
* @param resultHandler Result handler.
*
* @return A comment view controller.
*/
///#end
- (SSCCommentViewController *)presentCommentViewControllerWithContentId:(NSString *)contentId
title:(NSString *)title
comment:(id<ISSCComment>)comment
animated:(BOOL)animated
result:(SSCReplyResultEvent)resultHandler;
///#begin zh-cn
/**
* @brief 从导航控制器中放入评论视图控制器,此方法必须要当前视图控制器在导航视图容器中。
*
* @param contentId 内容唯一标识
* @param title 标题
* @param comment 被评论信息,如果为nil,则表示对主题进行评论
* @param animated 动画标识,YES 表示动画过渡, NO 表示无动画过渡
* @param resultHandler 评论回调事件
*
* @return 评论视图控制器
*/
///#end
///#begin en
/**
* @brief Add comment view controller from the navigation controller, this method must be the current view controller in the navigation view container.
*
* @param contentId Content id.
* @param title Title
* @param comment Commented information, if it is nil, it means to comment on the topic
* @param animated Animated flag, YES, said animated transitions, NO means no animated transitions
* @param resultHandler Result handler.
*
* @return Comment view controller.
*/
///#end
- (SSCCommentViewController *)pushCommentViewControllerWithContentId:(NSString *)contentId
title:(NSString *)title
comment:(id<ISSCComment>)comment
animated:(BOOL)animated
result:(SSCReplyResultEvent)resultHandler;
///#begin zh-cn
/**
* @brief 显示评论工具栏
*
* @param contentId 内容唯一标识
* @param title 标题
*/
///#end
///#begin en
/**
* @brief Show comment toolbar.
*
* @param contentId Content id.
* @param title Title.
*/
///#end
- (SSCCommentToolbar *)showCommentToolbarWithContentId:(NSString *)contentId
title:(NSString *)title;
@end
| 32.785276 | 234 | 0.603855 |
a9b82dca35aabae49243cce859874896a32a2e2e | 2,578 | h | C | src/api/streams/ccpp/include/ccpp_StreamDataWriter_impl.h | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 133 | 2017-11-09T02:10:00.000Z | 2022-03-29T09:45:10.000Z | src/api/streams/ccpp/include/ccpp_StreamDataWriter_impl.h | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 131 | 2017-11-07T14:48:43.000Z | 2022-03-13T15:30:47.000Z | src/api/streams/ccpp/include/ccpp_StreamDataWriter_impl.h | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 94 | 2017-11-09T02:26:19.000Z | 2022-02-24T06:38:25.000Z | /*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef CCPP_STREAMDATAWRITER_H
#define CCPP_STREAMDATAWRITER_H
#include "ccpp_dds_dcps.h"
#include "streams_ccpp.h"
#include "vortex_os.h"
#include "ccpp_StreamsUtils.h"
#include "ccpp_streams_if.h"
namespace DDS {
namespace Streams {
extern OS_STREAMS_API StreamDataWriterQos DefaultStreamDataWriterQos;
class OS_STREAMS_API StreamDataWriter_impl :
public virtual StreamDataWriter,
public LOCAL_REFCOUNTED_OBJECT
{
private:
static DDS::DomainParticipant_var participant;
static os_uint32 nrParticipantUsers;
protected:
DDS::Streams::StreamDataWriterQos qos;
DDS::Publisher_var publisher;
DDS::Topic_var topic;
StreamDataWriter_impl(
DDS::Publisher_ptr publisher,
DDS::DomainId_t domainId,
DDS::Streams::StreamDataWriterQos &qos,
DDS::TypeSupport_ptr typeSupport,
const char *streamName);
~StreamDataWriter_impl();
public:
static ::DDS::ReturnCode_t get_default_qos(
::DDS::Streams::StreamDataWriterQos & qos) THROW_ORB_EXCEPTIONS;
virtual ::DDS::ReturnCode_t set_qos(
const ::DDS::Streams::StreamDataWriterQos & qos) THROW_ORB_EXCEPTIONS = 0;
::DDS::ReturnCode_t get_qos(
::DDS::Streams::StreamDataWriterQos & qos) THROW_ORB_EXCEPTIONS;
private:
StreamDataWriter_impl (const StreamDataWriter_impl &);
StreamDataWriter_impl & operator = (const StreamDataWriter_impl &);
};
}
}
#undef OS_STREAMS_API
#endif /* CCPP_STREAMDATAWRITER_H */
| 34.373333 | 94 | 0.642746 |
a9ca859c084d051ffcfdde3295fabfb61b3af1dd | 9,160 | c | C | platform/STM32L476RC_NBEK/Display/DisplayTFT128.c | lupyuen/NB-EK-L476 | d0cd0d27e21434f585f4ba3b912b2837a24cb843 | [
"BSD-3-Clause"
] | 5 | 2019-10-13T18:50:15.000Z | 2021-01-14T23:04:21.000Z | platform/STM32L476RC_NBEK/Display/DisplayTFT128.c | lupyuen/NB-EK-L476 | d0cd0d27e21434f585f4ba3b912b2837a24cb843 | [
"BSD-3-Clause"
] | null | null | null | platform/STM32L476RC_NBEK/Display/DisplayTFT128.c | lupyuen/NB-EK-L476 | d0cd0d27e21434f585f4ba3b912b2837a24cb843 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2017, Ghostyu Co.,Ltd.
* 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 Texas Instruments Incorporated 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.
*/
/* -----------------------------------------------------------------------------
* Includes
* -----------------------------------------------------------------------------
*/
//
#include <stdio.h>
#include "stm32l4xx_hal.h"
#include "stm32l4xx_nbek.h"
#include "Display.h"
#include "DisplayTFT128.h"
#include "TFT128.h"
#include "stm32l4xx_hal_gpio.h"
#include "stm32l4xx_hal_spi.h"
/* -----------------------------------------------------------------------------
* Constants and macros
* -----------------------------------------------------------------------------
*/
// Timeout of semaphore that controls exclusive to the LCD (500 ms)
#define ACCESS_TIMEOUT 50000
/* -----------------------------------------------------------------------------
* Type definitions
* -----------------------------------------------------------------------------
*/
/* -----------------------------------------------------------------------------
* Local variables
* -----------------------------------------------------------------------------
*/
/* Display function table for tft1.44 128x128 implementation */
const Display_FxnTable DisplayTFT128_fxnTable = {
DisplayTFT128_open,
DisplayTFT128_clear,
DisplayTFT128_clearLines,
DisplayTFT128_put5,
DisplayTFT128_close,
DisplayTFT128_control,
DisplayTFT128_getType,
};
/* -----------------------------------------------------------------------------
* Functions
* -----------------------------------------------------------------------------
*/
//******************************************************************************
// fn : DisplayTFT128_open
//
// brief : Initialize the LCD
//
// descr : Initializes the pins used by the LCD, creates resource access
// protection semaphore, turns on the LCD device, initializes the
// frame buffer, initializes to white background/dark foreground,
// and finally clears the object->displayColor.
//
// param : hDisplay - pointer to Display_Config struct
// params - display parameters
//
// return : Pointer to Display_Config struct
Display_Handle DisplayTFT128_open(Display_Handle hDisplay,
Display_Params *params)
{
DisplayTFT128_HWAttrs *hwAttrs = (DisplayTFT128_HWAttrs *)hDisplay->hwAttrs;
DisplayTFT128_Object *object = (DisplayTFT128_Object *)hDisplay->object;
object->hPins = &hwAttrs->powerPin;
HAL_GPIO_WritePin(hwAttrs->powerPin.Port,hwAttrs->powerPin.pin,GPIO_PIN_SET);
object->lineClearMode = params->lineClearMode;
object->lcdColor.blackColor = YELLOW;
object->lcdColor.frontColor = BULE;
object->lcdBuffers[0].pcBuffer = object->lcdBuffer0;
object->lcdBuffers[0].bufSize = 512;
object->hLcd = LCDTFT_open(&object->lcdBuffers[0], 1, NULL);
object->hLcd->object->pColorInfo = &object->lcdColor;
if (object->hLcd)
{
Color color;
LCDTFT_bufferClear(object->hLcd);
LCDTFT_bufferStartCover(object->hLcd);
color = BLACK;
DisplayTFT128_control(hDisplay,CMD_BLACK_COLOR,&color);
color = WHITE;
DisplayTFT128_control(hDisplay,CMD_FRONT_COLOR,&color);
LCDTFT_bufferClear(object->hLcd);
return hDisplay;
}
else
{
return NULL;
}
}
//******************************************************************************
// fn : DisplayTFT128_clear
//
// brief : Clears the display
//
// param : hDisplay - pointer to Display_Config struct
//
// return : void
void DisplayTFT128_clear(Display_Handle hDisplay)
{
DisplayTFT128_Object *object = (DisplayTFT128_Object *)hDisplay->object;
if (object->hLcd)
{
LCDTFT_bufferClear(object->hLcd);
}
}
//******************************************************************************
// fn : DisplayTFT128_clearLines
//
// brief : Clears lines lineFrom-lineTo of the display, inclusive
//
// param : hDisplay - pointer to Display_Config struct
// lineFrom - line index (0 .. )
// lineTo - line index (0 .. )
//
// return : void
void DisplayTFT128_clearLines(Display_Handle hDisplay,
uint8_t lineFrom, uint8_t lineTo)
{
DisplayTFT128_Object *object = (DisplayTFT128_Object *)hDisplay->object;
if (lineTo < lineFrom)
{
lineTo = lineFrom;
}
if (object->hLcd)
{
uint8_t xMin = 0;
uint8_t xMax = 127;
LCDTFT_bufferClearPart(object->hLcd, xMin, xMax,
(LCD_Page)lineFrom, (LCD_Page)lineTo);
}
}
//******************************************************************************
// fn : DisplayTFT128_put5
//
// brief : Write a text string to a specific line/column of the display
//
// param : hDisplay - pointer to Display_Config struct
// cle - clear the remain space
// line - line index (0..)
// column - column index (0..)
// fmt - format string
// aN - optional format arguments
//
// return : void
void DisplayTFT128_put5(Display_Handle hDisplay,uint8_t cle, uint8_t line,
uint8_t column, char* fmt, va_list va)
{
DisplayTFT128_Object *object = (DisplayTFT128_Object *)hDisplay->object;
char dispStr[16] = { 0 };
uint8_t len = 0;
uint8_t xp;
xp = column * 8; //ascii = 16 * 8
len = vsnprintf(dispStr, sizeof(dispStr), fmt, va);
if(cle)
{
for(;len < sizeof(dispStr); len++)
{
dispStr[len] = ' ';
}
}
LCDTFT_bufferPrintString(object->hLcd, dispStr, xp, (LCD_Page)line);
}
//******************************************************************************
// fn : DisplayTFT128_close
//
// brief: Turns of the display and releases the LCD control pins
//
// param : hDisplay - pointer to Display_Config struct
//
// return : void
void DisplayTFT128_close(Display_Handle hDisplay)
{
DisplayTFT128_Object *object = (DisplayTFT128_Object *)hDisplay->object;
if (object->hPins == NULL)
{
return;
}
// Turn off the display
object->hPins = NULL;
LCDTFT_close(object->hLcd);
object->hLcd = NULL;
}
//******************************************************************************
// fn : DisplayTFT128_control
//
// brief : Function for setting control parameters of the Display driver
// after it has been opened.
//
// param : hDisplay - pointer to Display_Config struct
// cmd - command to execute
// arg - argument to the command
//
// return : DISPLAY_STATUS_UNDEFINEDCMD because no commands are supported
int DisplayTFT128_control(Display_Handle handle, unsigned int cmd, void *arg)
{
DisplayTFT128_Object *object = (DisplayTFT128_Object *)handle->object;
if(CMD_BLACK_COLOR == cmd)
{
object->lcdColor.blackColor = (Color)(*((int*)arg));
}
else if(CMD_FRONT_COLOR == cmd)
{
object->lcdColor.frontColor = (Color)(*((int*)arg));
}
return DISPLAY_STATUS_UNDEFINEDCMD;
}
//******************************************************************************
// fn : DisplayTFT128_getType
//
// brief : Returns type of transport
//
// param :
//
// return : Display type define LCD
unsigned int DisplayTFT128_getType(void)
{
return Display_Type_LCD;
}
| 32.94964 | 81 | 0.555677 |
e72442bc6e83d1864805d1a4b67d6204823035c6 | 5,093 | h | C | FilenameFunctions_Impl.h | eigie/AnimatedGIFs | d8b7b7c7902a9ce0143384f0d6cefeafce459017 | [
"MIT"
] | 44 | 2018-07-14T16:58:32.000Z | 2022-03-05T07:11:42.000Z | FilenameFunctions_Impl.h | eigie/AnimatedGIFs | d8b7b7c7902a9ce0143384f0d6cefeafce459017 | [
"MIT"
] | 14 | 2019-04-18T19:39:30.000Z | 2022-01-21T18:59:03.000Z | FilenameFunctions_Impl.h | eigie/AnimatedGIFs | d8b7b7c7902a9ce0143384f0d6cefeafce459017 | [
"MIT"
] | 17 | 2018-08-24T12:59:46.000Z | 2022-03-31T18:24:05.000Z | /*
* Animated GIFs Display Code for SmartMatrix and 32x32 RGB LED Panels
*
* This file contains code to enumerate and select animated GIF files by name
* Originally written by: Craig A. Lindley
* Largely reworked by Marc MERLIN <marc_soft@merlins.org> to support SPIFFS and FatFS
*/
#include "animatedgif_config.h"
File file;
// This can be used by the caller to retrieve the name by index
char pathname[128];
int numberOfFiles;
bool fileSeekCallback(unsigned long position) {
return file.seek(position);
}
unsigned long filePositionCallback(void) {
return file.position();
}
int fileReadCallback(void) {
return file.read();
}
int fileReadBlockCallback(void * buffer, int numberOfBytes) {
return file.read((uint8_t*)buffer, numberOfBytes);
}
#ifdef FSOSD
int initSdCard(int chipSelectPin) {
// initialize the SD card at full speed
pinMode(chipSelectPin, OUTPUT);
if (!SD.begin(chipSelectPin)) die("SD Begin failed");
return 0;
}
bool isAnimationFile(const char filename []) {
String filenameString(filename);
#else
bool isAnimationFile(String filenameString) {
// ESP32 filename includes the full path, so need to remove the path before looking at the filename
int pathindex = filenameString.lastIndexOf("/");
if(pathindex >= 0)
filenameString.remove(0, pathindex + 1);
#endif
//Serial.print(filenameString);
if ((filenameString[0] == '_') || (filenameString[0] == '~') || (filenameString[0] == '.')) {
Serial.println(" ignoring: leading _/~/. character");
return false;
}
filenameString.toUpperCase();
if (filenameString.endsWith(".GIF") != 1) {
Serial.println(" ignoring: doesn't end of .GIF");
return false;
}
return true;
}
// Enumerate and possibly display the animated GIF filenames in GIFS directory
int enumerateGIFFiles(const char *directoryName, boolean displayFilenames) {
numberOfFiles = 0;
Serial.print("Enumerate files in dir ");
Serial.println(directoryName);
#ifdef ESP8266
// ESP8266 SPIFFS uses special directory objects
Dir dir = SPIFFS.openDir(directoryName);
while (dir.next()) {
String filename = dir.fileName();
if (isAnimationFile(filename)) {
numberOfFiles++;
if (displayFilenames) Serial.println(filename);
}
}
#else
File directory = FSO.open(directoryName);
if (!directory) die("Can't open directory");
while (File file = directory.openNextFile()) {
if (isAnimationFile(file.name())) {
numberOfFiles++;
if (displayFilenames) Serial.println(file.name());
}
file.close();
}
directory.close();
#endif
return numberOfFiles;
}
// Get the full path/filename of the GIF file with specified index
void getGIFFilenameByIndex(const char *directoryName, int index, char *pnBuffer) {
// Make sure index is in range
if ((index < 0) || (index >= numberOfFiles)) return;
#ifndef FSOSD
#ifdef ESP32
File dir = FSO.open(directoryName);
while (File file = dir.openNextFile()) {
String filename = file.name();
if (isAnimationFile(filename)) {
filename.toCharArray(pnBuffer, 127);
if (!index) break;
index--;
}
}
#else
Dir dir = FSO.openDir(directoryName);
while (dir.next() && index >= 0) {
String filename = dir.fileName();
if (isAnimationFile(filename)) {
index--;
filename.toCharArray(pnBuffer, 127);
}
}
#endif
#else
File directory = SD.open(directoryName);
if (!directory) return;
File file = directory.openNextFile();
while (file && (index >= 0)) {
char* filename = (char*)file.name();
if (isAnimationFile(file.name())) {
index--;
#if !defined(ESP32)
// Copy the directory name into the pathname buffer -
// ESP32 SD Library includes the full path name in the filename, so no need to add the directory name
strcpy(pnBuffer, directoryName);
// Append the filename to the pathname
strcat(pnBuffer, filename);
#else
strcpy(pnBuffer, filename);
#endif
}
file.close();
file = directory.openNextFile();
}
directory.close();
#endif
Serial.print("Selected file ");
Serial.println(pnBuffer);
file.close();
}
int openGifFilenameByIndex(const char *directoryName, int index) {
getGIFFilenameByIndex(directoryName, index, pathname);
// Pathname: /gifs/32anim_balls.gif
//Serial.print("Pathname: ");
//Serial.println(pathname);
if (file) file.close();
// Attempt to open the file for reading
#ifdef FSOSPIFFS
if (! (file = SPIFFS.open(pathname, "r")) ) die ("Error opening GIF file");
#else
if (! (file = FSO.open(pathname)) ) die ("Error opening GIF file");
#endif
return 0;
}
// Return a random animated gif path/filename from the specified directory
void chooseRandomGIFFilename(const char *directoryName, char *pnBuffer) {
int index = random(numberOfFiles);
getGIFFilenameByIndex(directoryName, index, pnBuffer);
}
| 27.38172 | 106 | 0.65914 |
4381ab8afac26a7cbb5adcef421606018fea31fb | 25,382 | h | C | nuttx/include/nuttx/camera/v4l2_camera_ext_ctrls.h | AriDine/MotoWallet | 47562467292024d09bfeb2c6a597bc536a6b7574 | [
"Apache-2.0"
] | 4 | 2018-06-30T17:04:44.000Z | 2022-02-22T04:00:32.000Z | nuttx/nuttx/include/nuttx/camera/v4l2_camera_ext_ctrls.h | vixadd/FMoto | a266307517a19069813b3480d10073f73970c11b | [
"MIT"
] | 11 | 2017-10-22T09:45:51.000Z | 2019-05-28T23:25:29.000Z | nuttx/nuttx/include/nuttx/camera/v4l2_camera_ext_ctrls.h | vixadd/Moto.Mod.MDK.Capstone | a266307517a19069813b3480d10073f73970c11b | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015-16 Motorola Mobility, LLC.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef __CAMERA_EXT_CTRLS_H
#define __CAMERA_EXT_CTRLS_H
#define V4L2_CTRL_CLASS_MOD 0x00f00000
#define CID_CAM_EXT_CLASS_BASE (V4L2_CTRL_CLASS_MOD | 0xf000)
#define MOD_CID_MOD_CLASS (V4L2_CTRL_CLASS_MOD | 1)
/* int menu */
#define CAM_EXT_CID_COLOR_CORRECTION_ABERRATION_MODE CID_CAM_EXT_CLASS_BASE
enum {
CAM_EXT_COLOR_CORRECTION_ABERRATION_OFF,
CAM_EXT_COLOR_CORRECTION_ABERRATION_FAST,
CAM_EXT_COLOR_CORRECTION_ABERRATION_HQ,
CAM_EXT_COLOR_CORRECTION_ABERRATION_MAX =
CAM_EXT_COLOR_CORRECTION_ABERRATION_HQ,
};
/* int menu */
#define CAM_EXT_CID_AE_ANTIBANDING_MODE (CID_CAM_EXT_CLASS_BASE + 1)
enum {
CAM_EXT_AE_ANTIBANDING_OFF,
CAM_EXT_AE_ANTIBANDING_50HZ,
CAM_EXT_AE_ANTIBANDING_60HZ,
CAM_EXT_AE_ANTIBANDING_AUTO,
CAM_EXT_AE_ANTIBANDING_MAX = CAM_EXT_AE_ANTIBANDING_AUTO,
};
/* integer, range and step from mod */
#define CAM_EXT_CID_AE_EXPOSURE_COMPENSATION (CID_CAM_EXT_CLASS_BASE + 2)
/* boolean */
#define CAM_EXT_CID_AE_LOCK (CID_CAM_EXT_CLASS_BASE + 3)
/* int menu */
#define CAM_EXT_CID_AE_MODE (CID_CAM_EXT_CLASS_BASE + 4)
enum {
CAM_EXT_AE_MODE_OFF,
CAM_EXT_AE_MODE_ON,
CAM_EXT_AE_MODE_ON_AUTO_FLASH,
CAM_EXT_AE_MODE_ON_ALWAYS_FLASH,
CAM_EXT_AE_MODE_ON_AUTO_FLASH_REDEYE,
CAM_EXT_AE_MODE_MAX = CAM_EXT_AE_MODE_ON_AUTO_FLASH_REDEYE,
};
/* int menu, each menu item (64bit integer) stands for a range
* (32bit high, 32bit low)
* The available ranges (menu item list) are from MOD.
*/
#define CAM_EXT_CID_AE_TARGET_FPS_RANGE (CID_CAM_EXT_CLASS_BASE + 5)
/* int menu */
#define CAM_EXT_CID_AF_MODE (CID_CAM_EXT_CLASS_BASE + 6)
enum {
CAM_EXT_AF_MODE_OFF,
CAM_EXT_AF_MODE_AUTO,
CAM_EXT_AF_MODE_MACRO,
CAM_EXT_AF_MODE_CONTINUOUS_VIDEO,
CAM_EXT_AF_MODE_CONTINUOUS_PICTURE,
CAM_EXT_AF_MODE_EDOF,
CAM_EXT_AF_MODE_MAX = CAM_EXT_AF_MODE_EDOF,
};
/* int menu */
#define CAM_EXT_CID_AF_TRIGGER (CID_CAM_EXT_CLASS_BASE + 7)
enum {
CAM_EXT_AF_TRIGGER_IDLE,
CAM_EXT_AF_TRIGGER_START,
CAM_EXT_AF_TRIGGER_CANCEL,
CAM_EXT_AF_TRIGGER_MAX = CAM_EXT_AF_TRIGGER_CANCEL,
};
/* boolean */
#define CAM_EXT_CID_AWB_LOCK (CID_CAM_EXT_CLASS_BASE + 8)
/* int menu */
#define CAM_EXT_CID_AWB_MODE (CID_CAM_EXT_CLASS_BASE + 9)
enum {
CAM_EXT_AWB_MODE_OFF,
CAM_EXT_AWB_MODE_AUTO,
CAM_EXT_AWB_MODE_INCANDESCENT,
CAM_EXT_AWB_MODE_FLUORESCENT,
CAM_EXT_AWB_MODE_DAYLIGHT,
CAM_EXT_AWB_MODE_CLOUDY_DAYLIGHT,
CAM_EXT_AWB_MODE_TWILIGHT,
CAM_EXT_AWB_MODE_SHADE,
CAM_EXT_AWB_MODE_MAX = CAM_EXT_AWB_MODE_SHADE,
};
/* int menu */
#define CAM_EXT_CID_EFFECT_MODE (CID_CAM_EXT_CLASS_BASE + 10)
enum {
CAM_EXT_EFFECT_MODE_OFF,
CAM_EXT_EFFECT_MODE_MONO,
CAM_EXT_EFFECT_MODE_NEGATIVE,
CAM_EXT_EFFECT_MODE_SOLARIZE,
CAM_EXT_EFFECT_MODE_SEPIA,
CAM_EXT_EFFECT_MODE_POSTERIZE,
CAM_EXT_EFFECT_MODE_WHITEBOARD,
CAM_EXT_EFFECT_MODE_BLACKBOARD,
CAM_EXT_EFFECT_MODE_AQUA,
CAM_EXT_EFFECT_MODE_MAX = CAM_EXT_EFFECT_MODE_AQUA,
};
/* int menu */
#define CAM_EXT_CID_CONTROL_MODE (CID_CAM_EXT_CLASS_BASE + 11)
enum {
CAM_EXT_CONTROL_MODE_OFF,
CAM_EXT_CONTROL_MODE_AUTO,
CAM_EXT_CONTROL_MODE_USE_SCENE_MODE,
CAM_EXT_CONTROL_MODE_OFF_KEEP_STATE,
CAM_EXT_CONTROL_MODE_MAX = CAM_EXT_CONTROL_MODE_OFF_KEEP_STATE,
};
/* int menu */
#define CAM_EXT_CID_SCENE_MODE (CID_CAM_EXT_CLASS_BASE + 12)
enum {
CAM_EXT_SCENE_MODE_DISABLED,
CAM_EXT_SCENE_MODE_FACE_PRIORITY,
CAM_EXT_SCENE_MODE_ACTION,
CAM_EXT_SCENE_MODE_PORTRAIT,
CAM_EXT_SCENE_MODE_LANDSCAPE,
CAM_EXT_SCENE_MODE_NIGHT,
CAM_EXT_SCENE_MODE_NIGHT_PORTRAIT,
CAM_EXT_SCENE_MODE_THEATRE,
CAM_EXT_SCENE_MODE_BEACH,
CAM_EXT_SCENE_MODE_SNOW,
CAM_EXT_SCENE_MODE_SUNSET,
CAM_EXT_SCENE_MODE_STEADYPHOTO,
CAM_EXT_SCENE_MODE_FIREWORKS,
CAM_EXT_SCENE_MODE_SPORTS,
CAM_EXT_SCENE_MODE_PARTY,
CAM_EXT_SCENE_MODE_CANDLELIGHT,
CAM_EXT_SCENE_MODE_BARCODE,
CAM_EXT_SCENE_MODE_HDR,
CAM_EXT_SCENE_MODE_MAX = CAM_EXT_SCENE_MODE_HDR,
};
/* int menu */
#define CAM_EXT_CID_VIDEO_STABILIZATION_MODE (CID_CAM_EXT_CLASS_BASE + 13)
enum {
CAM_EXT_VIDEO_STABILIZATION_MODE_ON,
CAM_EXT_VIDEO_STABILIZATION_MODE_OFF,
CAM_EXT_VIDEO_STABILIZATION_MODE_MAX =
CAM_EXT_VIDEO_STABILIZATION_MODE_OFF,
};
/* double[2] */
#define CAM_EXT_CID_JPEG_GPS_LOCATION (CID_CAM_EXT_CLASS_BASE + 14)
/* int menu */
#define CAM_EXT_CID_JPEG_ORIENTATION (CID_CAM_EXT_CLASS_BASE + 15)
enum {
CAM_EXT_JPEG_ORIENTATION_0,
CAM_EXT_JPEG_ORIENTATION_90,
CAM_EXT_JPEG_ORIENTATION_180,
CAM_EXT_JPEG_ORIENTATION_270,
CAM_EXT_JPEG_ORIENTATION_MAX = CAM_EXT_JPEG_ORIENTATION_270,
};
/* int 0 - 100 */
#define CAM_EXT_CID_JPEG_QUALITY (CID_CAM_EXT_CLASS_BASE + 16)
/* int read only */
#define CAM_EXT_CID_LENS_FACING (CID_CAM_EXT_CLASS_BASE + 17)
enum {
CAM_EXT_LENS_FACING_FRONT,
CAM_EXT_LENS_FACING_BACK,
CAM_EXT_LENS_FACING_EXTERNAL,
CAM_EXT_LENS_FACING_MAX = CAM_EXT_LENS_FACING_EXTERNAL,
};
/* int menu */
#define CAM_EXT_CID_FLASH_MODE (CID_CAM_EXT_CLASS_BASE + 18)
enum {
CAM_EXT_FLASH_MODE_OFF,
CAM_EXT_FLASH_MODE_SINGLE,
CAM_EXT_FLASH_MODE_TORCH,
CAM_EXT_FLASH_MODE_MAX = CAM_EXT_FLASH_MODE_TORCH,
};
/* float menu (floats defined at mod side) */
#define CAM_EXT_CID_FOCAL_LENGTH (CID_CAM_EXT_CLASS_BASE + 19)
/* int menu read only */
#define CAM_EXT_CID_CAPABILITIES (CID_CAM_EXT_CLASS_BASE + 20)
enum {
CAM_EXT_CAPABILITIES_BACKWARD_COMPATIBLE,
CAM_EXT_CAPABILITIES_MANUAL_SENSOR,
CAM_EXT_CAPABILITIES_POST_PROCESSING,
CAM_EXT_CAPABILITIES_RAW,
CAM_EXT_CAPABILITIES_PRIVATE_REPROCESSING,
CAM_EXT_CAPABILITIES_READ_SENSOR_SETTING,
CAM_EXT_CAPABILITIES_BURST_CAPTURE,
CAM_EXT_CAPABILITIES_YUV_REPROCESSING,
CAM_EXT_CAPABILITIES_DEPTH_OUTPUT,
CAM_EXT_CAPABILITIES_CONSTRAINED_HIGHT_SPEED_VIDEO,
CAM_EXT_CAPABILITIES_MAX
= CAM_EXT_CAPABILITIES_CONSTRAINED_HIGHT_SPEED_VIDEO,
};
/* integer read only */
#define CAM_EXT_CID_MAX_NUM_OUTPUT_PROC (CID_CAM_EXT_CLASS_BASE + 21)
/* integer read only */
#define CAM_EXT_CID_MAX_NUM_OUTPUT_PROC_STALLING (CID_CAM_EXT_CLASS_BASE + 22)
/* intger read only */
#define CAM_EXT_CID_MAX_NUM_OUTPUT_RAW (CID_CAM_EXT_CLASS_BASE + 23)
/* integer read only */
#define CAM_EXT_CID_PIPLELINE_MAX_DEPTH (CID_CAM_EXT_CLASS_BASE + 24)
/* float read only */
#define CAM_EXT_CID_SCALER_MAX_DIGITAL_ZOOM (CID_CAM_EXT_CLASS_BASE + 25)
/* integer menu, read only */
#define CAM_EXT_CID_SCALER_CROPPING_TYPE (CID_CAM_EXT_CLASS_BASE + 26)
enum {
CAM_EXT_SCALER_CROPPING_TYPE_CENTER_ONLY,
CAM_EXT_SCALER_CROPPING_TYPE_FREEFORM,
CAM_EXT_SCALER_CROPPING_TYPE_MAX =
CAM_EXT_SCALER_CROPPING_TYPE_FREEFORM,
};
/* integer [4] */
#define CAM_EXT_CID_SCALER_CROP_REGION (CID_CAM_EXT_CLASS_BASE + 27)
/* float [2] ==> w, h read only */
#define CAM_EXT_CID_SENSOR_INFO_PHYSICAL_SIZE (CID_CAM_EXT_CLASS_BASE + 28)
/* integer [2] ==> w, h read only */
#define CAM_EXT_CID_SENSOR_INFO_PIXEL_ARRAY_SIZE (CID_CAM_EXT_CLASS_BASE + 29)
/* integer [4] ==> left, top, right, bottom read only */
#define CAM_EXT_CID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE \
(CID_CAM_EXT_CLASS_BASE + 30)
/* integer [4] ==> left, top, right, bottom read only */
#define CAM_EXT_CID_SENSOR_INFO_ACTIVE_ARRAY_SIZE (CID_CAM_EXT_CLASS_BASE + 31)
/* integer read only */
#define CAM_EXT_CID_SENSOR_INFO_TIMESTAMP_SOURCE (CID_CAM_EXT_CLASS_BASE + 32)
enum {
CAM_EXT_SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN,
CAM_EXT_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME,
CAM_EXT_SENSOR_INFO_TIMESTAMP_SOURCE_MAX =
CAM_EXT_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME,
};
/* integer read only */
#define CAM_EXT_CID_SENSOR_ORIENTATION (CID_CAM_EXT_CLASS_BASE + 33)
enum {
CAM_EXT_SENSOR_ORIENTATION_0,
CAM_EXT_SENSOR_ORIENTATION_90,
CAM_EXT_SENSOR_ORIENTATION_180,
CAM_EXT_SENSOR_ORIENTATION_270,
CAM_EXT_SENSOR_ORIENTATION_MAX = CAM_EXT_SENSOR_ORIENTATION_270,
};
/* int menu */
#define CAM_EXT_CID_STATISTICS_FACE_DETECT_MODE (CID_CAM_EXT_CLASS_BASE + 34)
enum {
CAM_EXT_STATISTICS_FACE_DETECT_MODE_OFF,
CAM_EXT_STATISTICS_FACE_DETECT_MODE_SIMPLE,
CAM_EXT_STATISTICS_FACE_DETECT_MODE_FULL,
CAM_EXT_STATISTICS_FACE_DETECT_MODE_MAX =
CAM_EXT_STATISTICS_FACE_DETECT_MODE_FULL,
};
/* int read only */
#define CAM_EXT_CID_STATISTICS_INFO_MAX_FACE_COUNT (CID_CAM_EXT_CLASS_BASE + 35)
/* int read only */
#define CAM_EXT_CID_SYNC_MAX_LATENCY (CID_CAM_EXT_CLASS_BASE + 36)
enum {
CAM_EXT_SYNC_MAX_LATENCY_PER_FRAME_CONTROL,
CAM_EXT_SYNC_MAX_LATENCY_UNKNOWN,
CAM_EXT_SYNC_MAX_LATENCY_MAX = CAM_EXT_SYNC_MAX_LATENCY_UNKNOWN,
};
/*************************OPTIONAL CONTROLS***********************************/
/* int menu */
#define CAM_EXT_CID_CONTROL_AE_PRECATURE_TRIGGER (CID_CAM_EXT_CLASS_BASE + 37)
enum {
CAM_EXT_CONTROL_AE_PRECATURE_TRIGGER_IDLE,
CAM_EXT_CONTROL_AE_PRECATURE_TRIGGER_START,
CAM_EXT_CONTROL_AE_PRECATURE_TRIGGER_CANCEL,
CAM_EXT_CONTROL_AE_PRECATURE_TRIGGER_MAX =
CAM_EXT_CONTROL_AE_PRECATURE_TRIGGER_CANCEL,
};
/* int read only */
#define CAM_EXT_CID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION \
(CID_CAM_EXT_CLASS_BASE + 38)
enum {
CAM_EXT_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_UNCALIBRATED,
CAM_EXT_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_APPROXIMATE,
CAM_EXT_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_CALIBRATED,
CAM_EXT_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_MAX =
CAM_EXT_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_CALIBRATED,
};
/* float read only */
#define CAM_EXT_CID_LENS_INFO_FOCUS_HYPERFOCAL_DISTANCE \
(CID_CAM_EXT_CLASS_BASE + 39)
/* float read only */
#define CAM_EXT_CID_LENS_INFO_MINIMUM_FOCUS_DISTANCE \
(CID_CAM_EXT_CLASS_BASE + 40)
/* float */
#define CAM_EXT_CID_LENS_FOCUS_DISTANCE (CID_CAM_EXT_CLASS_BASE + 41)
/* int menu */
#define CAM_EXT_CID_LENS_OPTICAL_STABILIZATION_MODE \
(CID_CAM_EXT_CLASS_BASE + 42)
enum {
CAM_EXT_CID_LENS_OPTICAL_STABILIZATION_MODE_OFF,
CAM_EXT_CID_LENS_OPTICAL_STABILIZATION_MODE_ON,
CAM_EXT_CID_LENS_OPTICAL_STABILIZATION_MODE_MAX =
CAM_EXT_CID_LENS_OPTICAL_STABILIZATION_MODE_ON,
};
/* float */
#define CAM_EXT_CID_REPROCESS_EFFECTIVE_EXPOSURE_FACTOR \
(CID_CAM_EXT_CLASS_BASE + 43)
/* integer read only */
#define CAM_EXT_CID_REPROCESS_MAX_CAPTURE_STALL (CID_CAM_EXT_CLASS_BASE + 44)
/* boolean read only */
#define CAM_EXT_CID_DEPTH_DEPTH_IS_EXCLUSIVE (CID_CAM_EXT_CLASS_BASE + 45)
/* boolean */
#define CAM_EXT_CID_BLACK_LEVEL_LOCK (CID_CAM_EXT_CLASS_BASE + 46)
/* int menu */
#define CAM_EXT_CID_COLOR_CORRECTION_MODE (CID_CAM_EXT_CLASS_BASE + 47)
enum {
CAM_EXT_COLOR_CORRECTION_MODE_TRANSFORM_MATRIX,
CAM_EXT_COLOR_CORRECTION_MODE_FAST,
CAM_EXT_COLOR_CORRECTION_MODE_HIGH_QUALITY,
CAM_EXT_COLOR_CORRECTION_MODE_MAX =
CAM_EXT_COLOR_CORRECTION_MODE_HIGH_QUALITY,
};
/* float [4] ==> RGGB gains */
#define CAM_EXT_CID_COLOR_CORRECTION_GAINS (CID_CAM_EXT_CLASS_BASE + 48)
/* float [3][3] ==> matrix transform RGB to sRGB */
#define CAM_EXT_CID_COLOR_CORRECTION_TRANSFORM (CID_CAM_EXT_CLASS_BASE + 49)
/* int menu */
#define CAM_EXT_CID_EDGE_MODE (CID_CAM_EXT_CLASS_BASE + 50)
enum {
CAM_EXT_EDGE_MODE_OFF,
CAM_EXT_EDGE_MODE_FAST,
CAM_EXT_EDGE_MODE_HIGH_QUALITY,
CAM_EXT_EDGE_MODE_ZERO_SHUTTER_LAG,
CAM_EXT_EDGE_MODE_MAX = CAM_EXT_EDGE_MODE_ZERO_SHUTTER_LAG,
};
/* float menu, need to read list of float from mod */
#define CAM_EXT_CID_LENS_APERTURES (CID_CAM_EXT_CLASS_BASE + 51)
/* float menu, need to read list of float from mod */
#define CAM_EXT_CID_LENS_FILTER_DENSITY (CID_CAM_EXT_CLASS_BASE + 52)
/* int menu */
#define CAM_EXT_CID_NOISE_REDUCTION_MODE (CID_CAM_EXT_CLASS_BASE + 53)
enum {
CAM_EXT_NOISE_REDUCTION_MODE_OFF,
CAM_EXT_NOISE_REDUCTION_MODE_FAST,
CAM_EXT_NOISE_REDUCTION_MODE_HIGH_QUALITY,
CAM_EXT_NOISE_REDUCTION_MODE_MINIMAL,
CAM_EXT_NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG,
CAM_EXT_NOISE_REDUCTION_MODE_MAX =
CAM_EXT_NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG,
};
/* int (0,1) read only */
#define CAM_EXT_CID_REQUEST_MAX_NUM_INPUT_STREAM (CID_CAM_EXT_CLASS_BASE + 54)
/* int >= 1 read only */
#define CAM_EXT_CID_REQUEST_PARTIAL_RESULT_COUNT (CID_CAM_EXT_CLASS_BASE + 55)
/* integer64 */
#define CAM_EXT_CID_SENSOR_EXPOSURE_TIME (CID_CAM_EXT_CLASS_BASE + 56)
/* intger64 */
#define CAM_EXT_CID_SENSOR_FRAME_DURATION (CID_CAM_EXT_CLASS_BASE + 57)
/* integer ISO*/
#define CAM_EXT_CID_SENSOR_SENSITIVITY (CID_CAM_EXT_CLASS_BASE + 58)
/* integer read only */
#define CAM_EXT_CID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT \
(CID_CAM_EXT_CLASS_BASE + 59)
enum {
CAM_EXT_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB,
CAM_EXT_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG,
CAM_EXT_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG,
CAM_EXT_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR,
CAM_EXT_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGB,
CAM_EXT_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_MAX =
CAM_EXT_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGB,
};
/* integer read only */
#define CAM_EXT_CID_SENSOR_MAX_ANALOG_SENSITIVITY \
(CID_CAM_EXT_CLASS_BASE + 60)
/* int menu */
#define CAM_EXT_CID_SHADING_MODE (CID_CAM_EXT_CLASS_BASE + 61)
enum {
CAM_EXT_SHADING_MODE_OFF,
CAM_EXT_SHADING_MODE_FAST,
CAM_EXT_SHADING_MODE_HIGH_QUALITY,
CAM_EXT_SHADING_MODE_MAX = CAM_EXT_SHADING_MODE_HIGH_QUALITY,
};
/* int menu */
#define CAM_EXT_CID_STATISTICS_LENS_SHADING_MAP_MODE \
(CID_CAM_EXT_CLASS_BASE + 62)
enum {
CAM_EXT_CID_STATISTICS_LENS_SHADING_MAP_MODE_OFF,
CAM_EXT_CID_STATISTICS_LENS_SHADING_MAP_MODE_ON,
CAM_EXT_CID_STATISTICS_LENS_SHADING_MAP_MODE_MAX =
CAM_EXT_CID_STATISTICS_LENS_SHADING_MAP_MODE_ON,
};
/* float of array [M][3][2], size is from MOD */
#define CAM_EXT_CID_TONEMAP_CURVE (CID_CAM_EXT_CLASS_BASE + 63)
/* float */
#define CAM_EXT_CID_TONEMAP_GAMMA (CID_CAM_EXT_CLASS_BASE + 64)
/* int menu */
#define CAM_EXT_CID_TONEMAP_MODE (CID_CAM_EXT_CLASS_BASE + 65)
enum {
CAM_EXT_TONEMAP_MODE_CONTRAST_CURVE,
CAM_EXT_TONEMAP_MODE_FAST,
CAM_EXT_TONEMAP_MODE_HIGH_QUALITY,
CAM_EXT_TONEMAP_MODE_GAMMA_VALUE,
CAM_EXT_TONEMAP_MODE_PRESET_CURVE,
CAM_EXT_TONEMAP_MODE_MAX =
CAM_EXT_TONEMAP_MODE_PRESET_CURVE,
};
/* int menu */
#define CAM_EXT_CID_TONEMAP_PRESET_CURVE (CID_CAM_EXT_CLASS_BASE + 66)
enum {
CAM_EXT_TONEMAP_PRESET_CURVE_SRGB,
CAM_EXT_TONEMAP_PRESET_CURVE_REC709,
CAM_EXT_TONEMAP_PRESET_CURVE_MAX = CAM_EXT_TONEMAP_PRESET_CURVE_REC709,
};
/* integer read only */
#define CAM_EXT_CID_TONEMAP_MAX_CURVE_POINSTS (CID_CAM_EXT_CLASS_BASE + 67)
/* list of integer [4] x,y,w,h */
#define CAM_EXT_CID_AE_REGIONS (CID_CAM_EXT_CLASS_BASE + 68)
/* list of integer [4] x,y,w,h */
#define CAM_EXT_CID_AF_REGIONS (CID_CAM_EXT_CLASS_BASE + 69)
/* list of integer [4] x,y,w,h */
#define CAM_EXT_CID_AWB_REGIONS (CID_CAM_EXT_CLASS_BASE + 70)
/* int menu */
#define CAM_EXT_CID_HOT_PIXEL_MODE (CID_CAM_EXT_CLASS_BASE + 71)
enum {
CAM_EXT_HOT_PIXEL_MODE_OFF,
CAM_EXT_HOT_PIXEL_MODE_FAST,
CAM_EXT_HOT_PIXEL_MODE_HIGH_QUALITY,
CAM_EXT_HOT_PIXEL_MODE_MAX = CAM_EXT_HOT_PIXEL_MODE_HIGH_QUALITY,
};
/* float [5] f_x, f_y, c_x, c_y, s read only */
#define CAM_EXT_CID_LENS_INTRINSIC_CALIBRATION (CID_CAM_EXT_CLASS_BASE + 72)
/* float [7] x, y, z, w, a_x, a_y, a_z read only */
#define CAM_EXT_CID_LENS_POSE_ROTATION (CID_CAM_EXT_CLASS_BASE + 73)
/* float [3] x, y, z read only */
#define CAM_EXT_CID_LENS_POSE_TRANSLATION (CID_CAM_EXT_CLASS_BASE + 74)
/* float [6] kappa_0, kappa_1, kappa_2, kappa_3, kappa_4, kappa_5 read only */
#define CAM_EXT_CID_LENS_RADIAL_DISTORTION (CID_CAM_EXT_CLASS_BASE + 75)
/* integer [4] rggb, solid color test pattern */
#define CAM_EXT_CID_SENSOR_TEST_PATTERN_DATA (CID_CAM_EXT_CLASS_BASE + 76)
/* int menu */
#define CAM_EXT_CID_SENSOR_TEST_PATTERN_MODE (CID_CAM_EXT_CLASS_BASE + 77)
enum {
CAM_EXT_SENSOR_TEST_PATTERN_MODE_OFF,
CAM_EXT_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR,
CAM_EXT_SENSOR_TEST_PATTERN_MODE_COLOR_BARS,
CAM_EXT_SENSOR_TEST_PATTERN_MODE_COLOR_BARS_FADE_TO_GRAY,
CAM_EXT_SENSOR_TEST_PATTERN_MODE_PN9,
CAM_EXT_SENSOR_TEST_PATTERN_MODE_CUSTOM1,
CAM_EXT_SENSOR_TEST_PATTERN_MODE_MAX =
CAM_EXT_SENSOR_TEST_PATTERN_MODE_CUSTOM1,
};
/* integer [4] read only */
#define CAM_EXT_CID_SENSOR_BLACK_LEVEL_PATTERN (CID_CAM_EXT_CLASS_BASE + 78)
/* float[3][3] read only */
#define CAM_EXT_CID_SENSOR_CALIBRATION_TRANSFORM1 \
(CID_CAM_EXT_CLASS_BASE + 79)
/* float[3][3] read only */
#define CAM_EXT_CID_SENSOR_CALIBRATION_TRANSFORM2 \
(CID_CAM_EXT_CLASS_BASE + 80)
/* float[3][3] read only */
#define CAM_EXT_CID_SENSOR_COLOR_TRANSFORM1 (CID_CAM_EXT_CLASS_BASE + 81)
/* float[3][3] read only */
#define CAM_EXT_CID_SENSOR_COLOR_TRANSFORM2 (CID_CAM_EXT_CLASS_BASE + 82)
/* float[3][3] read only */
#define CAM_EXT_CID_SENSOR_FORWARD_MATRIX1 (CID_CAM_EXT_CLASS_BASE + 83)
/* float[3][3] read only */
#define CAM_EXT_CID_SENSOR_FORWARD_MATRIX2 (CID_CAM_EXT_CLASS_BASE + 84)
/* boolean read only */
#define CAM_EXT_CID_SENSOR_INFO_LENS_SHADING_APPLIED \
(CID_CAM_EXT_CLASS_BASE + 85)
/* integer > 255 read only */
#define CAM_EXT_CID_SENSOR_INFO_WHITE_LEVEL (CID_CAM_EXT_CLASS_BASE + 86)
/* int read only */
#define CAM_EXT_CID_SENSOR_PREFERENCE_ILLUMINANT1 (CID_CAM_EXT_CLASS_BASE + 87)
enum {
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_DAYLIGHT,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_FLUORESCENT,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_TUNGSTEN,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_FLASH,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_FINE_WEATHER,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_CLOUDY_WHEATHER,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_SHADE,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_DAYLIGHT_FLUORESCENT,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_DAY_WHITE_FLUORESCENT,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_COOL_WHITE_FLUORESCENT,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_WHITE_FLUORESCENT,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_STANDARD_A,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_STANDARD_B,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_STANDARD_C,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_D55,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_D65,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_D75,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_D50,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_ISO_STUDIO_TUNGSTEN,
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_MAX =
CAM_EXT_SENSOR_PREFERENCE_ILLUMINANT_ISO_STUDIO_TUNGSTEN,
};
/* int read only */
#define CAM_EXT_CID_SENSOR_PREFERENCE_ILLUMINANT2 (CID_CAM_EXT_CLASS_BASE + 88)
/* boolean */
#define CAM_EXT_CID_STATISTICS_HOT_PIXEL_MAP_MODE (CID_CAM_EXT_CLASS_BASE + 89)
/* integer [M][2] */
#define CAM_EXT_CID_HOT_PIXEL_MAP (CID_CAM_EXT_CLASS_BASE + 90)
/* bit mask, write only */
#define CAM_EXT_CID_CAPTURE (CID_CAM_EXT_CLASS_BASE + 91)
enum {
CAM_EXT_CID_CAPTURE_STILL_CAPTURE = 1,
CAM_EXT_CID_CAPTURE_VIDEO_SNAPSHOT = 1 << 1,
CAM_EXT_CID_CAPTURE_ZSL_CAPTURE = 1 << 2,
CAM_EXT_CID_CAPTURE_RAW = 1 << 3,
CAM_EXT_CID_CAPTURE_JPG = 1 << 4,
CAM_EXT_CID_CAPTURE_BURST = 1 << 5,
CAM_EXT_CID_CAPTURE_MAX = CAM_EXT_CID_CAPTURE_STILL_CAPTURE
| CAM_EXT_CID_CAPTURE_VIDEO_SNAPSHOT
| CAM_EXT_CID_CAPTURE_ZSL_CAPTURE
| CAM_EXT_CID_CAPTURE_RAW
| CAM_EXT_CID_CAPTURE_JPG
| CAM_EXT_CID_CAPTURE_BURST
};
/* int menu, as extension to CAM_EXT_CID_AF_MODE */
#define CAM_EXT_CID_AF_MODE_EXT (CID_CAM_EXT_CLASS_BASE + 92)
enum {
CAM_EXT_AF_MODE_EXT_NULL,
CAM_EXT_AF_MODE_EXT_INFINITY,
CAM_EXT_AF_MODE_EXT_FIXED,
CAM_EXT_AF_MODE_EXT_MAX = CAM_EXT_AF_MODE_EXT_FIXED,
};
/* int menu */
#define CAM_EXT_CID_ISO (CID_CAM_EXT_CLASS_BASE + 93)
enum {
CAM_EXT_ISO_AUTO,
CAM_EXT_ISO_50,
CAM_EXT_ISO_100,
CAM_EXT_ISO_200,
CAM_EXT_ISO_400,
CAM_EXT_ISO_800,
CAM_EXT_ISO_1600,
CAM_EXT_ISO_3200,
CAM_EXT_ISO_MAX = CAM_EXT_ISO_3200,
};
/* int menu */
#define CAM_EXT_CID_ND_FILTER (CID_CAM_EXT_CLASS_BASE + 94)
enum {
CAM_EXT_ND_FILTER_AUTO,
CAM_EXT_ND_FILTER_ON,
CAM_EXT_ND_FILTER_OFF,
CAM_EXT_ND_FILTER_MAX = CAM_EXT_ND_FILTER_OFF,
};
/* integer */
#define CAM_EXT_CID_JPEG_SHARPNESS (CID_CAM_EXT_CLASS_BASE + 95)
/* integer */
#define CAM_EXT_CID_JPEG_CONTRAST (CID_CAM_EXT_CLASS_BASE + 96)
/* integer */
#define CAM_EXT_CID_JPEG_SATURATION (CID_CAM_EXT_CLASS_BASE + 97)
/* integer64 */
#define CAM_EXT_CID_TIME_SYNC (CID_CAM_EXT_CLASS_BASE + 98)
/* integer64 */
#define CAM_EXT_CID_JPEG_GPS_TIMESTAMP (CID_CAM_EXT_CLASS_BASE + 99)
/* string */
#define CAM_EXT_CID_JPEG_GPS_PROC_METHOD (CID_CAM_EXT_CLASS_BASE + 100)
/* int menu */
#define CAM_EXT_CID_FACE_DETECTION (CID_CAM_EXT_CLASS_BASE + 101)
enum {
CAM_EXT_CID_FACE_DETECTION_STOP,
CAM_EXT_CID_FACE_DETECTION_START,
CAM_EXT_CID_FACE_DETECTION_MAX = CAM_EXT_CID_FACE_DETECTION_START,
};
/* int[3] ready only: [has_uvc, vid, pid] */
#define CAM_EXT_CID_MOD_CAPS_UVC_SNAPSHOT (CID_CAM_EXT_CLASS_BASE + 102)
/* int read only */
#define CAM_EXT_CID_MOD_META_DATA_PATH (CID_CAM_EXT_CLASS_BASE + 103)
enum {
CAM_EXT_CID_MOD_META_DATA_PATH_NONE,
CAM_EXT_CID_MOD_META_DATA_PATH_CSI,
CAM_EXT_CID_MOD_META_DATA_PATH_GB,
CAM_EXT_CID_MOD_META_DATA_PATH_MAX = CAM_EXT_CID_MOD_META_DATA_PATH_GB,
};
/* int, read only. For GB path, it's packet size. For CSI path, it's line num */
#define CAM_EXT_CID_MOD_META_DATA_SIZE (CID_CAM_EXT_CLASS_BASE + 104)
/* boolean */
#define CAM_EXT_CID_ZOOM_LOCK_1X (CID_CAM_EXT_CLASS_BASE + 105)
/* reserved (CID_CAM_EXT_CLASS_BASE + 106) */
/* string read only */
#define CAM_EXT_CID_MODEL_NUMBER (CID_CAM_EXT_CLASS_BASE + 107)
/* string read only */
#define CAM_EXT_CID_FIRMWARE_VERSION (CID_CAM_EXT_CLASS_BASE + 108)
/* int menu */
#define CAM_EXT_CID_AE_MODE_EXT (CID_CAM_EXT_CLASS_BASE + 109)
enum {
CAM_EXT_AE_MODE_EXT_NULL,
CAM_EXT_AE_MODE_EXT_OFF_FLASH,
CAM_EXT_AE_MODE_EXT_OFF_FLASH_REDEYE,
CAM_EXT_AE_MODE_EXT_MAX = CAM_EXT_AE_MODE_EXT_OFF_FLASH_REDEYE,
};
/* int menu */
#define CAM_EXT_CID_SCENE_MODE_EXT (CID_CAM_EXT_CLASS_BASE + 110)
enum {
CAM_EXT_SCENE_MODE_EXT_NULL,
CAM_EXT_SCENE_MODE_EXT_AUTO_HDR,
CAM_EXT_SCENE_MODE_EXT_BACKLIGHT_PORTRAIT,
CAM_EXT_SCENE_MODE_EXT_CLOSEUP,
CAM_EXT_SCENE_MODE_EXT_DUSK_DAWN,
CAM_EXT_SCENE_MODE_EXT_FOOD,
CAM_EXT_SCENE_MODE_EXT_NIGHT_LANDSCAPE,
CAM_EXT_SCENE_MODE_EXT_PET_PORTRAIT,
CAM_EXT_SCENE_MODE_EXT_MAX = CAM_EXT_SCENE_MODE_EXT_PET_PORTRAIT,
};
/* int 0 - 100 */
#define CAM_EXT_CID_MANUAL_FOCUS_POSITION (CID_CAM_EXT_CLASS_BASE + 111)
/* integer, limit the max zoom level, 100 means 1x, 1000 means 10x */
#define CAM_EXT_CID_ZOOM_LIMIT (CID_CAM_EXT_CLASS_BASE + 112)
/* reserved (CID_CAM_EXT_CLASS_BASE + 113) */
/* integer [][4]: eis_w, eis_h, w, h. optional for MOD */
#define CAM_EXT_CID_EIS_FRAME_SIZE_MAP (CID_CAM_EXT_CLASS_BASE + 114)
/* integer [][2]: w, h for thumbnail */
#define CAM_EXT_CID_JPEG_AVAILABLE_THUMBNAIL_SIZES \
(CID_CAM_EXT_CLASS_BASE + 115)
/* int: index of thumbnail in JPEG_AVAILABLE_THUMBNAIL_SIZE, [0...] */
#define CAM_EXT_CID_JPEG_THUMBNAIL_SIZE_INDEX (CID_CAM_EXT_CLASS_BASE + 116)
/* string */
#define CAM_EXT_CID_PHONE_VERSION (CID_CAM_EXT_CLASS_BASE + 117)
/* int, mask for key capability, read only */
#define CAM_EXT_CID_SUPPLEMENTAL_KEY_MASK (CID_CAM_EXT_CLASS_BASE + 118)
enum {
CAM_EXT_HW_KEY_POWER = 1,
CAM_EXT_HW_KEY_POWER_EVT = 1 << 1,
CAM_EXT_HW_KEY_ZOOM_IN = 1 << 2,
CAM_EXT_HW_KEY_ZOOM_IN_EVT = 1 << 3,
CAM_EXT_HW_KEY_ZOOM_OUT = 1 << 4,
CAM_EXT_HW_KEY_ZOOM_OUT_EVT = 1 << 5,
CAM_EXT_HW_KEY_FOCUS = 1 << 6,
CAM_EXT_HW_KEY_FOCUS_EVT = 1 << 7,
CAM_EXT_HW_KEY_CAMERA = 1 << 8,
CAM_EXT_HW_KEY_CAMERA_EVT = 1 << 9,
CAM_EXT_HW_KEY_MAX = CAM_EXT_HW_KEY_POWER
| CAM_EXT_HW_KEY_POWER_EVT
| CAM_EXT_HW_KEY_ZOOM_IN
| CAM_EXT_HW_KEY_ZOOM_IN_EVT
| CAM_EXT_HW_KEY_ZOOM_OUT
| CAM_EXT_HW_KEY_ZOOM_OUT_EVT
| CAM_EXT_HW_KEY_FOCUS
| CAM_EXT_HW_KEY_FOCUS_EVT
| CAM_EXT_HW_KEY_CAMERA
| CAM_EXT_HW_KEY_CAMERA_EVT
};
/* interger, to group controls */
#define CAM_EXT_CID_GROUP_IND (CID_CAM_EXT_CLASS_BASE + 119)
enum {
CAM_EXT_CID_GROUP_IND_BEGIN,
CAM_EXT_CID_GROUP_IND_END,
CAM_EXT_CID_GROUP_IND_MAX = CAM_EXT_CID_GROUP_IND_END,
};
/* boolean */
#define CAM_EXT_CID_VIDEO_RECORD_HINT (CID_CAM_EXT_CLASS_BASE + 120)
/* float[3] r/g/b gain used in raw to yuv conversion */
#define CAM_EXT_CID_RAW_TO_YUV_GAIN (CID_CAM_EXT_CLASS_BASE + 121)
/* int menu */
#define CAM_EXT_CID_EFFECT_MODE_EXT (CID_CAM_EXT_CLASS_BASE + 122)
enum {
CAM_EXT_EFFECT_MODE_EXT_NULL,
CAM_EXT_EFFECT_MODE_EXT_BLACK_BLUE,
CAM_EXT_EFFECT_MODE_EXT_PURE,
CAM_EXT_EFFECT_MODE_EXT_MIRROR,
CAM_EXT_EFFECT_MODE_EXT_BUBBLE,
CAM_EXT_EFFECT_MODE_EXT_NEON,
CAM_EXT_EFFECT_MODE_EXT_CARTOON,
CAM_EXT_EFFECT_MODE_EXT_SOFT,
CAM_EXT_EFFECT_MODE_EXT_DIORAMA,
CAM_EXT_EFFECT_MODE_EXT_MAX = CAM_EXT_EFFECT_MODE_EXT_DIORAMA,
};
/* int */
#define CAM_EXT_CID_ZSL_BUFFER_DEPTH (CID_CAM_EXT_CLASS_BASE + 123)
/* string */
#define CAM_EXT_CID_CUSTOM_PARAMETER (CID_CAM_EXT_CLASS_BASE + 124)
/***************** camera_ext ver 1.1 controls *****************/
/* int[2] max jpeg size, max raw image size, optional for uvc fragment buffers */
#define CAM_EXT_CID_UVC_FRAG_CFG (CID_CAM_EXT_CLASS_BASE + 125)
/* float, Mod's capability of the continuous snapshot, optional */
#define CAM_EXT_CID_CONTINUOUS_SNAPSHOT_FPS (CID_CAM_EXT_CLASS_BASE + 126)
#endif /* __CAMERA_EXT_CTRLS_H */
| 29.966942 | 81 | 0.816366 |
43d43c3cb34be0dd46a8d5bd80ab8f851b8a048d | 4,484 | h | C | tensorflow/core/lib/random/weighted_picker.h | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | 6 | 2022-02-04T18:12:24.000Z | 2022-03-21T23:57:12.000Z | Lib/site-packages/tensorflow/include/tensorflow/core/lib/random/weighted_picker.h | shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings | 1fa4cd6a566c8745f455fc3d2273208f21f88ced | [
"bzip2-1.0.6"
] | null | null | null | Lib/site-packages/tensorflow/include/tensorflow/core/lib/random/weighted_picker.h | shfkdroal/Robot-Learning-in-Mixed-Adversarial-and-Collaborative-Settings | 1fa4cd6a566c8745f455fc3d2273208f21f88ced | [
"bzip2-1.0.6"
] | 1 | 2022-02-08T03:53:23.000Z | 2022-02-08T03:53:23.000Z | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// An abstraction to pick from one of N elements with a specified
// weight per element.
//
// The weight for a given element can be changed in O(lg N) time
// An element can be picked in O(lg N) time.
//
// Uses O(N) bytes of memory.
//
// Alternative: distribution-sampler.h allows O(1) time picking, but no weight
// adjustment after construction.
#ifndef TENSORFLOW_LIB_RANDOM_WEIGHTED_PICKER_H_
#define TENSORFLOW_LIB_RANDOM_WEIGHTED_PICKER_H_
#include <assert.h>
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace random {
class SimplePhilox;
class WeightedPicker {
public:
// REQUIRES N >= 0
// Initializes the elements with a weight of one per element
explicit WeightedPicker(int N);
// Releases all resources
~WeightedPicker();
// Pick a random element with probability proportional to its weight.
// If total weight is zero, returns -1.
int Pick(SimplePhilox* rnd) const;
// Deterministically pick element x whose weight covers the
// specified weight_index.
// Returns -1 if weight_index is not in the range [ 0 .. total_weight()-1 ]
int PickAt(int32 weight_index) const;
// Get the weight associated with an element
// REQUIRES 0 <= index < N
int32 get_weight(int index) const;
// Set the weight associated with an element
// REQUIRES weight >= 0.0f
// REQUIRES 0 <= index < N
void set_weight(int index, int32 weight);
// Get the total combined weight of all elements
int32 total_weight() const;
// Get the number of elements in the picker
int num_elements() const;
// Set weight of each element to "weight"
void SetAllWeights(int32 weight);
// Resizes the picker to N and
// sets the weight of each element i to weight[i].
// The sum of the weights should not exceed 2^31 - 2
// Complexity O(N).
void SetWeightsFromArray(int N, const int32* weights);
// REQUIRES N >= 0
//
// Resize the weighted picker so that it has "N" elements.
// Any newly added entries have zero weight.
//
// Note: Resizing to a smaller size than num_elements() will
// not reclaim any memory. If you wish to reduce memory usage,
// allocate a new WeightedPicker of the appropriate size.
//
// It is efficient to use repeated calls to Resize(num_elements() + 1)
// to grow the picker to size X (takes total time O(X)).
void Resize(int N);
// Grow the picker by one and set the weight of the new entry to "weight".
//
// Repeated calls to Append() in order to grow the
// picker to size X takes a total time of O(X lg(X)).
// Consider using SetWeightsFromArray instead.
void Append(int32 weight);
private:
// We keep a binary tree with N leaves. The "i"th leaf contains
// the weight of the "i"th element. An internal node contains
// the sum of the weights of its children.
int N_; // Number of elements
int num_levels_; // Number of levels in tree (level-0 is root)
int32** level_; // Array that holds nodes per level
// Size of each level
static int LevelSize(int level) { return 1 << level; }
// Rebuild the tree weights using the leaf weights
void RebuildTreeWeights();
TF_DISALLOW_COPY_AND_ASSIGN(WeightedPicker);
};
inline int32 WeightedPicker::get_weight(int index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, N_);
return level_[num_levels_ - 1][index];
}
inline int32 WeightedPicker::total_weight() const { return level_[0][0]; }
inline int WeightedPicker::num_elements() const { return N_; }
} // namespace random
} // namespace tensorflow
#endif // TENSORFLOW_LIB_RANDOM_WEIGHTED_PICKER_H_
| 33.462687 | 81 | 0.688002 |
b765db3cd581e515766ee1be1eeec2af79c9e59c | 656 | h | C | bin/R-3.5.1/src/extra/graphapp/stdimg.h | lifebit-ai/exomedepth | 5a775ae5e2a247aeadc5208a34e8717c7855d080 | [
"MIT"
] | 1 | 2019-07-28T20:32:29.000Z | 2019-07-28T20:32:29.000Z | bin/R-3.5.1/src/extra/graphapp/stdimg.h | lifebit-ai/exomedepth | 5a775ae5e2a247aeadc5208a34e8717c7855d080 | [
"MIT"
] | 1 | 2020-04-22T14:02:10.000Z | 2020-04-22T14:02:10.000Z | bin/R-3.5.1/src/extra/graphapp/stdimg.h | lifebit-ai/exomedepth | 5a775ae5e2a247aeadc5208a34e8717c7855d080 | [
"MIT"
] | 1 | 2018-08-29T09:43:52.000Z | 2018-08-29T09:43:52.000Z | #include <R_ext/libextern.h>
#undef LibExtern
#ifdef GA_DLL_BUILD
# define LibExtern LibExport
#else
# define LibExtern extern LibImport
#endif
LibExtern image cam_image;
LibExtern image color_image;
LibExtern image console_image;
LibExtern image console1_image;
LibExtern image copy_image;
LibExtern image copy1_image;
LibExtern image copypaste_image;
LibExtern image cut_image;
LibExtern image erase_image;
LibExtern image help_image;
LibExtern image open_image;
LibExtern image open1_image;
LibExtern image paste_image;
LibExtern image paste1_image;
LibExtern image print_image;
LibExtern image save_image;
LibExtern image stop_image;
#undef LibExtern
| 24.296296 | 35 | 0.847561 |
aed4c3a1eaa5fe2becd680d80ca6b340119e6fd7 | 65,442 | c | C | deparse.c | daniel-garcia/jdbc_fdw | d20b5838c61786dbbe85408a314ac0dd69d52328 | [
"RSA-MD"
] | null | null | null | deparse.c | daniel-garcia/jdbc_fdw | d20b5838c61786dbbe85408a314ac0dd69d52328 | [
"RSA-MD"
] | null | null | null | deparse.c | daniel-garcia/jdbc_fdw | d20b5838c61786dbbe85408a314ac0dd69d52328 | [
"RSA-MD"
] | null | null | null | /*-------------------------------------------------------------------------
*
* deparse.c
* Query deparser for jdbc_fdw
*
* This file includes functions that examine query WHERE clauses to see
* whether they're safe to send to the remote server for execution, as
* well as functions to construct the query text to be sent. The latter
* functionality is annoyingly duplicative of ruleutils.c, but there are
* enough special considerations that it seems best to keep this separate.
* One saving grace is that we only need deparse logic for node types that
* we consider safe to send.
*
* We assume that the remote session's search_path is exactly "pg_catalog",
* and thus we need schema-qualify all and only names outside pg_catalog.
*
* We do not consider that it is ever safe to send COLLATE expressions to
* the remote server: it might not have the same collation names we do.
* (Later we might consider it safe to send COLLATE "C", but even that would
* fail on old remote servers.) An expression is considered safe to send only
* if all collations used in it are traceable to Var(s) of the foreign table.
* That implies that if the remote server gets a different answer than we do,
* the foreign table's columns are not marked with collations that match the
* remote table's columns, which we can consider to be user error.
*
* Portions Copyright (c) 2012-2014, PostgreSQL Global Development Group
*
* Portions Copyright (c) 2021, TOSHIBA CORPORATION
*
* IDENTIFICATION
* contrib/jdbc_fdw/deparse.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "jdbc_fdw.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "catalog/pg_aggregate.h"
#include "common/keywords.h"
#include "commands/defrem.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#if PG_VERSION_NUM < 120000
#include "optimizer/var.h"
#else
#include "optimizer/optimizer.h"
#endif
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "optimizer/tlist.h"
/*
* Global context for jdbc_foreign_expr_walker's search of an expression
* tree.
*/
typedef struct foreign_glob_cxt
{
PlannerInfo *root; /* global planner state */
RelOptInfo *foreignrel; /* the foreign relation we are planning for */
Relids relids; /* relids of base relations in the underlying
* scan */
} foreign_glob_cxt;
/*
* Local (per-tree-level) context for jdbc_foreign_expr_walker's search. This
* is concerned with identifying collations used in the expression.
*/
typedef enum
{
FDW_COLLATE_NONE, /* expression is of a noncollatable type */
FDW_COLLATE_SAFE, /* collation derives from a foreign Var */
FDW_COLLATE_UNSAFE /* collation derives from something else */
} FDWCollateState;
typedef struct foreign_loc_cxt
{
Oid collation; /* OID of current collation, if any */
FDWCollateState state; /* state of current collation choice */
} foreign_loc_cxt;
/*
* Context for jdbc_deparse_expr
*/
typedef struct deparse_expr_cxt
{
PlannerInfo *root; /* global planner state */
RelOptInfo *foreignrel; /* the foreign relation we are planning for */
RelOptInfo *scanrel; /* the underlying scan relation. Same as
* foreignrel, when that represents a join or
* a base relation. */
StringInfo buf; /* output buffer to append to */
List **params_list; /* exprs that will become remote Params */
jdbcAggref *aggref;
char *q_char; /* Default identifier quote char */
} deparse_expr_cxt;
/*
* Functions to determine whether an expression can be evaluated safely on
* remote server.
*/
static bool jdbc_foreign_expr_walker(Node *node,
foreign_glob_cxt *glob_cxt,
foreign_loc_cxt *outer_cxt);
static bool jdbc_is_builtin(Oid procid);
/*
* Functions to construct string representation of a node tree.
*/
static void jdbc_deparse_target_list(StringInfo buf,
PlannerInfo *root,
Index rtindex,
Relation rel,
Bitmapset *attrs_used,
bool qualify_col,
List **retrieved_attrs,
char *q_char);
static void jdbc_deparse_column_ref(StringInfo buf, int varno, int varattno,
PlannerInfo *root, bool qualify_col, char *q_char);
static void jdbc_deparse_aggref(Aggref *node, deparse_expr_cxt *context);
static void jdbc_deparse_relation(StringInfo buf, Relation rel, char *q_char);
static void jdbc_deparse_string_literal(StringInfo buf, const char *val);
static void jdbc_deparse_expr(Expr *expr, deparse_expr_cxt *context);
static void jdbc_deparse_var(Var *node, deparse_expr_cxt *context);
static void jdbc_deparse_const(Const *node, deparse_expr_cxt *context);
#if PG_VERSION_NUM < 120000
static void jdbc_deparse_array_ref(ArrayRef * node, deparse_expr_cxt *context);
#else
static void jdbc_deparse_array_ref(SubscriptingRef *node, deparse_expr_cxt *context);
#endif
static void jdbc_deparse_func_expr(FuncExpr *node, deparse_expr_cxt *context);
static void jdbc_deparse_op_expr(OpExpr *node, deparse_expr_cxt *context);
static void jdbc_deparse_operator_name(StringInfo buf, Form_pg_operator opform);
static void jdbc_deparse_distinct_expr(DistinctExpr *node, deparse_expr_cxt *context);
static void jdbc_deparse_scalar_array_op_expr(ScalarArrayOpExpr *node,
deparse_expr_cxt *context);
static void jdbc_deparse_relabel_type(RelabelType *node, deparse_expr_cxt *context);
static void jdbc_deparse_bool_expr(BoolExpr *node, deparse_expr_cxt *context);
static void jdbc_deparse_null_test(NullTest *node, deparse_expr_cxt *context);
static void jdbc_append_limit_clause(deparse_expr_cxt *context);
static void jdbc_deparse_array_expr(ArrayExpr *node, deparse_expr_cxt *context);
static void jdbc_append_function_name(Oid funcid, deparse_expr_cxt *context);
static const char *jdbc_quote_identifier(const char *ident,
char *q_char,
bool quote_all_identifiers);
/*
* Deparse given targetlist and append it to context->buf.
*
* tlist is list of TargetEntry's which in turn contain Var nodes.
*
* retrieved_attrs is the list of continuously increasing integers starting
* from 1. It has same number of entries as tlist.
*
*/
static void
deparseExplicitTargetList(List *tlist,
bool is_returning,
List **retrieved_attrs,
deparse_expr_cxt *context)
{
ListCell *lc;
StringInfo buf = context->buf;
int i = 0;
*retrieved_attrs = NIL;
foreach(lc, tlist)
{
TargetEntry *tle = lfirst_node(TargetEntry, lc);
if (i > 0)
appendStringInfoString(buf, ", ");
jdbc_deparse_expr((Expr *) tle->expr, context);
*retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
i++;
}
if (i == 0 && !is_returning)
appendStringInfoString(buf, "NULL");
}
/*
* Examine each qual clause in input_conds, and classify them into two
* groups, which are returned as two lists: - remote_conds contains
* expressions that can be evaluated remotely - local_conds contains
* expressions that can't be evaluated remotely
*/
void
jdbc_classify_conditions(PlannerInfo *root,
RelOptInfo *baserel,
List *input_conds,
List **remote_conds,
List **local_conds)
{
ListCell *lc;
*remote_conds = NIL;
*local_conds = NIL;
foreach(lc, input_conds)
{
RestrictInfo *ri = (RestrictInfo *) lfirst(lc);
if (jdbc_is_foreign_expr(root, baserel, ri->clause))
*remote_conds = lappend(*remote_conds, ri);
else
*local_conds = lappend(*local_conds, ri);
}
}
/*
* Deparse LIMIT/OFFSET clause.
*/
static void
jdbc_append_limit_clause(deparse_expr_cxt *context)
{
PlannerInfo *root = context->root;
StringInfo buf = context->buf;
int nestlevel;
/* Make sure any constants in the exprs are printed portably */
nestlevel = jdbc_set_transmission_modes();
if (root->parse->limitCount)
{
appendStringInfoString(buf, " LIMIT ");
jdbc_deparse_expr((Expr *) root->parse->limitCount, context);
}
if (root->parse->limitOffset)
{
appendStringInfoString(buf, " OFFSET ");
jdbc_deparse_expr((Expr *) root->parse->limitOffset, context);
}
jdbc_reset_transmission_modes(nestlevel);
}
/*
* Returns true if given expr is safe to evaluate on the foreign server.
*/
bool
jdbc_is_foreign_expr(PlannerInfo *root,
RelOptInfo *baserel,
Expr *expr)
{
foreign_glob_cxt glob_cxt;
foreign_loc_cxt loc_cxt;
/*
* Check that the expression consists of nodes that are safe to execute
* remotely.
*/
glob_cxt.root = root;
glob_cxt.foreignrel = baserel;
loc_cxt.collation = InvalidOid;
loc_cxt.state = FDW_COLLATE_NONE;
if (!jdbc_foreign_expr_walker((Node *) expr, &glob_cxt, &loc_cxt))
return false;
/* Expressions examined here should be boolean, ie noncollatable */
Assert(loc_cxt.collation == InvalidOid);
Assert(loc_cxt.state == FDW_COLLATE_NONE);
/*
* An expression which includes any mutable functions can't be sent over
* because its result is not stable. For example, sending now() remote
* side could cause confusion from clock offsets. Future versions might
* be able to make this choice with more granularity. (We check this last
* because it requires a lot of expensive catalog lookups.)
*/
if (contain_mutable_functions((Node *) expr))
return false;
/* OK to evaluate on the remote server */
return true;
}
/*
* Returns true if given expr is something we'd have to send the value of to
* the foreign server.
*
* This should return true when the expression is a shippable node that
* jdbc_deparse_expr would add to context->params_list. Note that we don't
* care if the expression *contains* such a node, only whether one appears at
* top level. We need this to detect cases where setrefs.c would recognize a
* false match between an fdw_exprs item (which came from the params_list)
* and an entry in fdw_scan_tlist (which we're considering putting the given
* expression into).
*/
bool
jdbc_is_foreign_param(PlannerInfo *root,
RelOptInfo *baserel,
Expr *expr)
{
if (expr == NULL)
return false;
switch (nodeTag(expr))
{
case T_Var:
{
/* It would have to be sent unless it's a foreign Var */
Var *var = (Var *) expr;
jdbcFdwRelationInfo *fpinfo = (jdbcFdwRelationInfo *) (baserel->fdw_private);
Relids relids;
if (IS_UPPER_REL(baserel))
relids = fpinfo->outerrel->relids;
else
relids = baserel->relids;
if (bms_is_member(var->varno, relids) && var->varlevelsup == 0)
return false; /* foreign Var, so not a param */
else
return true; /* it'd have to be a param */
break;
}
case T_Param:
/* Params always have to be sent to the foreign server */
return true;
default:
break;
}
return false;
}
/*
* Check if expression is safe to execute remotely, and return true if so.
*
* In addition, *outer_cxt is updated with collation information.
*
* We must check that the expression contains only node types we can deparse,
* that all types/functions/operators are safe to send (which we approximate
* as being built-in), and that all collations used in the expression derive
* from Vars of the foreign table. Because of the latter, the logic is
* pretty close to assign_collations_walker() in parse_collate.c, though we
* can assume here that the given expression is valid.
*/
static bool
jdbc_foreign_expr_walker(Node *node,
foreign_glob_cxt *glob_cxt,
foreign_loc_cxt *outer_cxt)
{
bool check_type = true;
foreign_loc_cxt inner_cxt;
Oid collation;
FDWCollateState state;
/* Need do nothing for empty subexpressions */
if (node == NULL)
return true;
/* Set up inner_cxt for possible recursion to child nodes */
inner_cxt.collation = InvalidOid;
inner_cxt.state = FDW_COLLATE_NONE;
switch (nodeTag(node))
{
case T_Var:
{
Var *var = (Var *) node;
/*
* If the Var is from the foreign table, we consider its
* collation (if any) safe to use. If it is from another
* table, we treat its collation the same way as we would a
* Param's collation, ie it's not safe for it to have a
* non-default collation.
*/
if (var->varno == glob_cxt->foreignrel->relid &&
var->varlevelsup == 0)
{
/* Var belongs to foreign table */
/*
* System columns other than ctid should not be sent to
* the remote, since we don't make any effort to ensure
* that local and remote values match (tableoid, in
* particular, almost certainly doesn't match).
*/
if (var->varattno < 0 &&
var->varattno != SelfItemPointerAttributeNumber)
return false;
/* Else check the collation */
collation = var->varcollid;
state = OidIsValid(collation) ? FDW_COLLATE_SAFE : FDW_COLLATE_NONE;
}
else
{
/* Var belongs to some other table */
if (var->varcollid != InvalidOid &&
var->varcollid != DEFAULT_COLLATION_OID)
return false;
/*
* We can consider that it doesn't set collation
*/
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
}
break;
case T_Const:
{
Const *c = (Const *) node;
/*
* If the constant has nondefault collation, either it's of a
* non-builtin type, or it reflects folding of a CollateExpr;
* either way, it's unsafe to send to the remote.
*/
if (c->constcollid != InvalidOid &&
c->constcollid != DEFAULT_COLLATION_OID)
return false;
/*
* Otherwise, we can consider that it doesn't set collation
*/
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
break;
case T_Param:
{
/* Parameter is unsupported */
return false;
}
break;
#if PG_VERSION_NUM < 120000
case T_ArrayRef:
{
ArrayRef *ar = (ArrayRef *) node;;
#else
case T_SubscriptingRef:
{
SubscriptingRef *ar = (SubscriptingRef *) node;
#endif
/* Assignment should not be in restrictions. */
if (ar->refassgnexpr != NULL)
return false;
/*
* Recurse into the remaining subexpressions. The container
* subscripts will not affect collation of the SubscriptingRef
* result, so do those first and reset inner_cxt afterwards.
*/
if (!jdbc_foreign_expr_walker((Node *) ar->refupperindexpr,
glob_cxt, &inner_cxt))
return false;
inner_cxt.collation = InvalidOid;
inner_cxt.state = FDW_COLLATE_NONE;
if (!jdbc_foreign_expr_walker((Node *) ar->reflowerindexpr,
glob_cxt, &inner_cxt))
return false;
inner_cxt.collation = InvalidOid;
inner_cxt.state = FDW_COLLATE_NONE;
if (!jdbc_foreign_expr_walker((Node *) ar->refexpr,
glob_cxt, &inner_cxt))
return false;
/*
* Array subscripting should yield same collation as input,
* but for safety use same logic as for function nodes.
*/
collation = ar->refcollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_FuncExpr:
{
FuncExpr *fe = (FuncExpr *) node;
/*
* If function used by the expression is not built-in, it
* can't be sent to remote because it might have incompatible
* semantics on remote side.
*/
if (!jdbc_is_builtin(fe->funcid))
return false;
/*
* Recurse to input subexpressions.
*/
if (!jdbc_foreign_expr_walker((Node *) fe->args,
glob_cxt, &inner_cxt))
return false;
/*
* If function's input collation is not derived from a foreign
* Var, it can't be sent to remote.
*/
if (fe->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
fe->inputcollid != inner_cxt.collation)
return false;
/*
* Detect whether node is introducing a collation not derived
* from a foreign Var. (If so, we just mark it unsafe for now
* rather than immediately returning false, since the parent
* node might not care.)
*/
collation = fe->funccollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_OpExpr:
case T_DistinctExpr: /* struct-equivalent to OpExpr */
{
OpExpr *oe = (OpExpr *) node;
/*
* Similarly, only built-in operators can be sent to remote.
* (If the operator is, surely its underlying function is
* too.)
*/
if (!jdbc_is_builtin(oe->opno))
return false;
/*
* Recurse to input subexpressions.
*/
if (!jdbc_foreign_expr_walker((Node *) oe->args,
glob_cxt, &inner_cxt))
return false;
/*
* If operator's input collation is not derived from a foreign
* Var, it can't be sent to remote.
*/
if (oe->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
oe->inputcollid != inner_cxt.collation)
return false;
/* Result-collation handling is same as for functions */
collation = oe->opcollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_ScalarArrayOpExpr:
{
ScalarArrayOpExpr *oe = (ScalarArrayOpExpr *) node;
/*
* Again, only built-in operators can be sent to remote.
*/
if (!jdbc_is_builtin(oe->opno))
return false;
/*
* Recurse to input subexpressions.
*/
if (!jdbc_foreign_expr_walker((Node *) oe->args,
glob_cxt, &inner_cxt))
return false;
/*
* If operator's input collation is not derived from a foreign
* Var, it can't be sent to remote.
*/
if (oe->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
oe->inputcollid != inner_cxt.collation)
return false;
/* Output is always boolean and so noncollatable. */
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
break;
case T_RelabelType:
{
RelabelType *r = (RelabelType *) node;
/*
* Recurse to input subexpression.
*/
if (!jdbc_foreign_expr_walker((Node *) r->arg,
glob_cxt, &inner_cxt))
return false;
/*
* RelabelType must not introduce a collation not derived from
* an input foreign Var.
*/
collation = r->resultcollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_BoolExpr:
{
BoolExpr *b = (BoolExpr *) node;
/*
* Recurse to input subexpressions.
*/
if (!jdbc_foreign_expr_walker((Node *) b->args,
glob_cxt, &inner_cxt))
return false;
/* Output is always boolean and so noncollatable. */
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
break;
case T_NullTest:
{
NullTest *nt = (NullTest *) node;
/*
* Recurse to input subexpressions.
*/
if (!jdbc_foreign_expr_walker((Node *) nt->arg,
glob_cxt, &inner_cxt))
return false;
/* Output is always boolean and so noncollatable. */
collation = InvalidOid;
state = FDW_COLLATE_NONE;
}
break;
case T_ArrayExpr:
{
ArrayExpr *a = (ArrayExpr *) node;
/*
* Recurse to input subexpressions.
*/
if (!jdbc_foreign_expr_walker((Node *) a->elements,
glob_cxt, &inner_cxt))
return false;
/*
* ArrayExpr must not introduce a collation not derived from
* an input foreign Var.
*/
collation = a->array_collid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
case T_List:
{
List *l = (List *) node;
ListCell *lc;
/*
* Recurse to component subexpressions.
*/
foreach(lc, l)
{
if (!jdbc_foreign_expr_walker((Node *) lfirst(lc),
glob_cxt, &inner_cxt))
return false;
}
/*
* When processing a list, collation state just bubbles up
* from the list elements.
*/
collation = inner_cxt.collation;
state = inner_cxt.state;
/* Don't apply exprType() to the list. */
check_type = false;
}
break;
case T_Aggref:
{
Aggref *agg = (Aggref *) node;
ListCell *lc;
char *opername = NULL;
bool is_math_func = false;
bool is_selector_func = false;
bool is_count_func = false;
HeapTuple tuple;
/* get function name */
tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(agg->aggfnoid));
if (!HeapTupleIsValid(tuple))
{
elog(ERROR, "cache lookup failed for function %u", agg->aggfnoid);
}
opername = pstrdup(((Form_pg_proc) GETSTRUCT(tuple))->proname.data);
ReleaseSysCache(tuple);
/* these function can be passed to JDBC */
if (strcmp(opername, "sum") == 0 ||
strcmp(opername, "avg") == 0 ||
strcmp(opername, "stddev") == 0 ||
strcmp(opername, "variance") == 0)
is_math_func = true;
if (strcmp(opername, "max") == 0 ||
strcmp(opername, "min") == 0)
is_selector_func = true;
if (strcmp(opername, "count") == 0)
is_count_func = true;
if (!(is_math_func || is_selector_func || is_count_func))
return false;
/* Not safe to pushdown when not in grouping context */
if (glob_cxt->foreignrel->reloptkind != RELOPT_UPPER_REL)
return false;
/* Only non-split aggregates are pushable. */
if (agg->aggsplit != AGGSPLIT_SIMPLE)
return false;
/*
* Recurse to input args. aggdirectargs, aggorder and
* aggdistinct are all present in args, so no need to check
* their shippability explicitly.
*/
foreach(lc, agg->args)
{
Node *n = (Node *) lfirst(lc);
/*
* If TargetEntry, extract the expression from it
*/
if (IsA(n, TargetEntry))
{
TargetEntry *tle = (TargetEntry *) n;
Var *tmp_var;
n = (Node *) tle->expr;
tmp_var = (Var *) n;
switch (tmp_var->vartype)
{
case INT2OID:
case INT4OID:
case INT8OID:
case OIDOID:
case FLOAT4OID:
case FLOAT8OID:
case NUMERICOID:
{
if (!(is_math_func || is_selector_func))
{
return false;
}
break;
}
case TIMESTAMPOID:
case TIMESTAMPTZOID:
{
if (!is_selector_func)
{
return false;
}
break;
}
default:
return false;
}
}
else if (!(agg->aggstar == true && is_count_func))
return false;
if (!jdbc_foreign_expr_walker(n, glob_cxt, &inner_cxt))
return false;
}
if (agg->aggorder || agg->aggfilter)
{
return false;
}
/*
* If aggregate's input collation is not derived from a
* foreign Var, it can't be sent to remote.
*/
if (agg->inputcollid == InvalidOid)
/* OK, inputs are all noncollatable */ ;
else if (inner_cxt.state != FDW_COLLATE_SAFE ||
agg->inputcollid != inner_cxt.collation)
return false;
/*
* Detect whether node is introducing a collation not derived
* from a foreign Var. (If so, we just mark it unsafe for now
* rather than immediately returning false, since the parent
* node might not care.)
*/
collation = agg->aggcollid;
if (collation == InvalidOid)
state = FDW_COLLATE_NONE;
else if (inner_cxt.state == FDW_COLLATE_SAFE &&
collation == inner_cxt.collation)
state = FDW_COLLATE_SAFE;
else if (collation == DEFAULT_COLLATION_OID)
state = FDW_COLLATE_NONE;
else
state = FDW_COLLATE_UNSAFE;
}
break;
default:
/*
* If it's anything else, assume it's unsafe. This list can be
* expanded later, but don't forget to add deparse support below.
*/
return false;
}
/*
* If result type of given expression is not built-in, it can't be sent to
* remote because it might have incompatible semantics on remote side.
*/
if (check_type && !jdbc_is_builtin(exprType(node)))
return false;
/*
* Now, merge my collation information into my parent's state.
*/
if (state > outer_cxt->state)
{
/* Override previous parent state */
outer_cxt->collation = collation;
outer_cxt->state = state;
}
else if (state == outer_cxt->state)
{
/* Merge, or detect error if there's a collation conflict */
switch (state)
{
case FDW_COLLATE_NONE:
/* Nothing + nothing is still nothing */
break;
case FDW_COLLATE_SAFE:
if (collation != outer_cxt->collation)
{
/*
* Non-default collation always beats default.
*/
if (outer_cxt->collation == DEFAULT_COLLATION_OID)
{
/* Override previous parent state */
outer_cxt->collation = collation;
}
else if (collation != DEFAULT_COLLATION_OID)
{
/*
* Conflict; show state as indeterminate. We don't
* want to "return false" right away, since parent
* node might not care about collation.
*/
outer_cxt->state = FDW_COLLATE_UNSAFE;
}
}
break;
case FDW_COLLATE_UNSAFE:
/* We're still conflicted ... */
break;
}
}
/* It looks OK */
return true;
}
/*
* Deparse SELECT statement for given relation into buf.
*/
void
jdbc_deparse_select_stmt_for_rel(StringInfo buf,
PlannerInfo *root,
RelOptInfo *baserel,
List *remote_conds,
List *pathkeys,
List **retrieved_attrs,
List **params_list,
List *tlist,
bool has_limit,
bool use_remote_estimate,
List *fpinfo_remote_conds,
List *remote_join_conds,
char *q_char)
{
jdbcFdwRelationInfo *fpinfo = (jdbcFdwRelationInfo *) baserel->fdw_private;
List *quals;
deparse_expr_cxt context;
/* Fill portions of context common to join and base relation */
context.buf = buf;
context.root = root;
context.foreignrel = baserel;
context.params_list = params_list;
context.scanrel = IS_UPPER_REL(baserel) ? fpinfo->outerrel : baserel;
jdbc_deparse_select_sql(buf, root, baserel, remote_conds,
pathkeys, retrieved_attrs, params_list,
tlist, has_limit, q_char);
/*
* For upper relations, the WHERE clause is built from the remote
* conditions of the underlying scan relation; otherwise, we can use the
* supplied list of remote conditions directly.
*/
if (IS_UPPER_REL(baserel))
{
jdbcFdwRelationInfo *ofpinfo;
ofpinfo = (jdbcFdwRelationInfo *) fpinfo->outerrel->fdw_private;
quals = ofpinfo->remote_conds;
}
else
quals = remote_conds;
/*
* Construct WHERE clause
*/
if (use_remote_estimate)
{
if (fpinfo_remote_conds)
jdbc_append_where_clause(buf, root, baserel, fpinfo_remote_conds,
true, NULL, q_char);
if (remote_join_conds)
jdbc_append_where_clause(buf, root, baserel, remote_join_conds,
(fpinfo_remote_conds == NIL), NULL, q_char);
}
else
{
if (quals)
{
jdbc_append_where_clause(buf, root, baserel, quals,
true, params_list, q_char);
}
}
/* Add LIMIT clause if necessary */
if (has_limit)
jdbc_append_limit_clause(&context);
}
/*
* Return true if given object is one of PostgreSQL's built-in objects.
*
* We use FirstBootstrapObjectId as the cutoff, so that we only consider
* objects with hand-assigned OIDs to be "built in", not for instance any
* function or type defined in the information_schema.
*
* Our constraints for dealing with types are tighter than they are for
* functions or operators: we want to accept only types that are in
* pg_catalog, else format_type might incorrectly fail to schema-qualify
* their names. (This could be fixed with some changes to format_type, but
* for now there's no need.) Thus we must exclude information_schema types.
*
* XXX there is a problem with this, which is that the set of built-in
* objects expands over time. Something that is built-in to us might not be
* known to the remote server, if it's of an older version. But keeping
* track of that would be a huge exercise.
*/
static bool
jdbc_is_builtin(Oid oid)
{
return (oid < FirstBootstrapObjectId);
}
/*
* Construct a simple SELECT statement that retrieves desired columns of the
* specified foreign table, and append it to "buf". The output contains just
* "SELECT ... FROM tablename".
*
* We also create an integer List of the columns being retrieved, which is
* returned to *retrieved_attrs.
*/
void
jdbc_deparse_select_sql(StringInfo buf,
PlannerInfo *root,
RelOptInfo *baserel,
List *remote_conds,
List *pathkeys,
List **retrieved_attrs,
List **params_list,
List *tlist,
bool has_limit,
char *q_char)
{
RangeTblEntry *rte;
Relation rel;
jdbcFdwRelationInfo *fpinfo = (jdbcFdwRelationInfo *) baserel->fdw_private;
deparse_expr_cxt context;
/* Fill portions of context common to join and base relation */
context.buf = buf;
context.root = root;
context.foreignrel = baserel;
context.params_list = params_list;
context.scanrel = IS_UPPER_REL(baserel) ? fpinfo->outerrel : baserel;
context.q_char = q_char;
rte = planner_rt_fetch(context.scanrel->relid, root);
/*
* Core code already has some lock on each rel being planned, so we can
* use NoLock here.
*/
#if PG_VERSION_NUM < 130000
rel = heap_open(rte->relid, NoLock);
#else
rel = table_open(rte->relid, NoLock);
#endif
/*
* Construct SELECT list
*/
appendStringInfoString(buf, "SELECT ");
if (IS_UPPER_REL(baserel) || fpinfo->is_tlist_func_pushdown == true)
{
deparseExplicitTargetList(tlist, false, retrieved_attrs, &context);
}
else
{
jdbc_deparse_target_list(buf, root, baserel->relid, rel, fpinfo->attrs_used,
false, retrieved_attrs, q_char);
}
/*
* Construct FROM clause
*/
appendStringInfoString(buf, " FROM ");
jdbc_deparse_relation(buf, rel, q_char);
#if PG_VERSION_NUM < 130000
heap_close(rel, NoLock);
#else
table_close(rel, NoLock);
#endif
}
/*
* Emit a target list that retrieves the columns specified in attrs_used.
* This is used for both SELECT and RETURNING targetlists.
*
* The tlist text is appended to buf, and we also create an integer List of
* the columns being retrieved, which is returned to *retrieved_attrs.
*
* If qualify_col is true, add relation alias before the column name.
*/
static void
jdbc_deparse_target_list(StringInfo buf,
PlannerInfo *root,
Index rtindex,
Relation rel,
Bitmapset *attrs_used,
bool qualify_col,
List **retrieved_attrs,
char *q_char)
{
TupleDesc tupdesc = RelationGetDescr(rel);
bool have_wholerow;
bool first;
int i;
*retrieved_attrs = NIL;
/* If there's a whole-row reference, we'll need all the columns. */
have_wholerow = bms_is_member(0 - FirstLowInvalidHeapAttributeNumber,
attrs_used);
first = true;
for (i = 1; i <= tupdesc->natts; i++)
{
Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
/* Ignore dropped attributes. */
if (attr->attisdropped)
continue;
if (have_wholerow ||
bms_is_member(i - FirstLowInvalidHeapAttributeNumber,
attrs_used))
{
if (!first)
appendStringInfoString(buf, ", ");
first = false;
jdbc_deparse_column_ref(buf, rtindex, i, root, qualify_col, q_char);
*retrieved_attrs = lappend_int(*retrieved_attrs, i);
}
}
/* Don't generate bad syntax if no undropped columns */
if (first)
appendStringInfoString(buf, "NULL");
}
/*
* Deparse WHERE clauses in given list of RestrictInfos and append them to
* buf.
*
* baserel is the foreign table we're planning for.
*
* If no WHERE clause already exists in the buffer, is_first should be true.
*
* If params is not NULL, it receives a list of Params and other-relation
* Vars used in the clauses; these values must be transmitted to the remote
* server as parameter values.
*
* If params is NULL, we're generating the query for EXPLAIN purposes, so
* Params and other-relation Vars should be replaced by dummy values.
*/
void
jdbc_append_where_clause(StringInfo buf,
PlannerInfo *root,
RelOptInfo *baserel,
List *exprs,
bool is_first,
List **params,
char *q_char)
{
deparse_expr_cxt context;
int nestlevel;
ListCell *lc;
jdbcFdwRelationInfo *fpinfo = (jdbcFdwRelationInfo *) baserel->fdw_private;
if (params)
*params = NIL; /* initialize result list to empty */
/* Set up context struct for recursion */
context.root = root;
context.foreignrel = baserel;
context.buf = buf;
context.params_list = params;
context.scanrel = IS_UPPER_REL(baserel) ? fpinfo->outerrel : baserel;
context.q_char = q_char;
/* Make sure any constants in the exprs are printed portably */
nestlevel = jdbc_set_transmission_modes();
foreach(lc, exprs)
{
RestrictInfo *ri = (RestrictInfo *) lfirst(lc);
/*
* Connect expressions with "AND" and parenthesize each condition.
*/
if (is_first)
appendStringInfoString(buf, " WHERE ");
else
appendStringInfoString(buf, " AND ");
appendStringInfoChar(buf, '(');
jdbc_deparse_expr(ri->clause, &context);
appendStringInfoChar(buf, ')');
is_first = false;
}
jdbc_reset_transmission_modes(nestlevel);
}
/*
* deparse remote INSERT statement
*
* The statement text is appended to buf, and we also create an integer List
* of the columns being retrieved by RETURNING (if any), which is returned to
* *retrieved_attrs.
*/
void
jdbc_deparse_insert_sql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
List *targetAttrs, List *returningList,
List **retrieved_attrs, char *q_char)
{
AttrNumber pindex;
bool first;
ListCell *lc;
appendStringInfoString(buf, "INSERT INTO ");
jdbc_deparse_relation(buf, rel, q_char);
if (targetAttrs)
{
appendStringInfoChar(buf, '(');
first = true;
foreach(lc, targetAttrs)
{
int attnum = lfirst_int(lc);
if (!first)
appendStringInfoString(buf, ", ");
first = false;
jdbc_deparse_column_ref(buf, rtindex, attnum, root, false, q_char);
}
appendStringInfoString(buf, ") VALUES (");
pindex = 1;
first = true;
foreach(lc, targetAttrs)
{
if (!first)
appendStringInfoString(buf, ", ");
first = false;
appendStringInfo(buf, "?");
pindex++;
}
appendStringInfoChar(buf, ')');
}
else
appendStringInfoString(buf, " DEFAULT VALUES");
}
/*
* deparse remote UPDATE statement
*
* The statement text is appended to buf, and we also create an integer List
* of the columns being retrieved by RETURNING (if any), which is returned to
* *retrieved_attrs.
*/
void
jdbc_deparse_update_sql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
List *targetAttrs, List *attnums,
char *q_char)
{
bool first;
ListCell *lc;
int i;
appendStringInfoString(buf, "UPDATE ");
jdbc_deparse_relation(buf, rel, q_char);
appendStringInfoString(buf, " SET ");
first = true;
foreach(lc, targetAttrs)
{
int attnum = lfirst_int(lc);
if (!first)
appendStringInfoString(buf, ", ");
first = false;
jdbc_deparse_column_ref(buf, rtindex, attnum, root, false, q_char);
appendStringInfo(buf, " = ?");
}
i = 0;
foreach(lc, attnums)
{
int attnum = lfirst_int(lc);
appendStringInfo(buf, i == 0 ? " WHERE " : " AND ");
jdbc_deparse_column_ref(buf, rtindex, attnum, root, false, q_char);
appendStringInfo(buf, "=?");
i++;
}
}
/*
* deparse remote DELETE statement
*
* The statement text is appended to buf, and we also create an integer List
* of the columns being retrieved by RETURNING (if any), which is returned to
* *retrieved_attrs.
*/
void
jdbc_deparse_delete_sql(StringInfo buf, PlannerInfo *root,
Index rtindex, Relation rel,
List *attname, char *q_char)
{
int i = 0;
ListCell *lc;
appendStringInfoString(buf, "DELETE FROM ");
jdbc_deparse_relation(buf, rel, q_char);
foreach(lc, attname)
{
int attnum = lfirst_int(lc);
appendStringInfo(buf, i == 0 ? " WHERE " : " AND ");
jdbc_deparse_column_ref(buf, rtindex, attnum, root, false, q_char);
appendStringInfo(buf, "=?");
i++;
}
}
/*
* Construct SELECT statement to acquire sample rows of given relation.
*
* SELECT command is appended to buf, and list of columns retrieved is
* returned to *retrieved_attrs.
*/
void
jdbc_deparse_analyze_sql(StringInfo buf, Relation rel, List **retrieved_attrs, char *q_char)
{
Oid relid = RelationGetRelid(rel);
TupleDesc tupdesc = RelationGetDescr(rel);
int i;
char *colname;
List *options;
ListCell *lc;
bool first = true;
*retrieved_attrs = NIL;
appendStringInfoString(buf, "SELECT ");
for (i = 0; i < tupdesc->natts; i++)
{
Form_pg_attribute attr = TupleDescAttr(tupdesc, i - 1);
/* Ignore dropped columns. */
if (attr->attisdropped)
continue;
if (!first)
appendStringInfoString(buf, ", ");
first = false;
/* Use attribute name or column_name option. */
colname = NameStr(TupleDescAttr(tupdesc, i)->attname);
options = GetForeignColumnOptions(relid, i + 1);
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "column_name") == 0)
{
colname = defGetString(def);
break;
}
}
appendStringInfoString(buf, jdbc_quote_identifier(colname, q_char, false));
*retrieved_attrs = lappend_int(*retrieved_attrs, i + 1);
}
/* Don't generate bad syntax for zero-column relation. */
if (first)
appendStringInfoString(buf, "NULL");
/*
* Construct FROM clause
*/
appendStringInfoString(buf, " FROM ");
jdbc_deparse_relation(buf, rel, q_char);
}
/*
* Construct name to use for given column, and emit it into buf. If it has a
* column_name FDW option, use that instead of attribute name.
*/
static void
jdbc_deparse_column_ref(StringInfo buf, int varno, int varattno, PlannerInfo *root,
bool qualify_col, char *q_char)
{
RangeTblEntry *rte;
char *colname = NULL;
List *options;
ListCell *lc;
/* varno must not be any of OUTER_VAR, INNER_VAR and INDEX_VAR. */
Assert(!IS_SPECIAL_VARNO(varno));
/* Get RangeTblEntry from array in PlannerInfo. */
rte = planner_rt_fetch(varno, root);
/*
* If it's a column of a foreign table, and it has the column_name FDW
* option, use that value.
*/
options = GetForeignColumnOptions(rte->relid, varattno);
foreach(lc, options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "column_name") == 0)
{
colname = defGetString(def);
break;
}
}
/*
* If it's a column of a regular table or it doesn't have column_name FDW
* option, use attribute name.
*/
if (colname == NULL)
#if PG_VERSION_NUM >= 110000
colname = get_attname(rte->relid, varattno, false);
#else
colname = get_relid_attribute_name(rte->relid, varattno);
#endif
appendStringInfoString(buf, jdbc_quote_identifier(colname, q_char, false));
}
/*
* Build the targetlist for given relation to be deparsed as SELECT clause.
*
* The output targetlist contains the columns that need to be fetched from
* the foreign server for the given relation. If foreignrel is an upper
* relation, then the output targetlist can also contain expressions to be
* evaluated on foreign server.
*/
List *
jdbc_build_tlist_to_deparse(RelOptInfo *foreignrel)
{
List *tlist = NIL;
jdbcFdwRelationInfo *fpinfo = (jdbcFdwRelationInfo *) foreignrel->fdw_private;
ListCell *lc;
/*
* For an upper relation, we have already built the target list while
* checking shippability, so just return that.
*/
if (IS_UPPER_REL(foreignrel))
return fpinfo->grouped_tlist;
/*
* We require columns specified in foreignrel->reltarget->exprs and those
* required for evaluating the local conditions.
*/
tlist = add_to_flat_tlist(tlist,
pull_var_clause((Node *) foreignrel->reltarget->exprs,
PVC_RECURSE_PLACEHOLDERS));
foreach(lc, fpinfo->local_conds)
{
RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
tlist = add_to_flat_tlist(tlist,
pull_var_clause((Node *) rinfo->clause,
PVC_RECURSE_PLACEHOLDERS));
}
return tlist;
}
/*
* Deparse an Aggref node.
*/
static void
jdbc_deparse_aggref(Aggref *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
bool use_variadic;
/* Only basic, non-split aggregation accepted. */
Assert(node->aggsplit == AGGSPLIT_SIMPLE);
/* Check if need to print VARIADIC (cf. ruleutils.c) */
use_variadic = node->aggvariadic;
/* Find aggregate name from aggfnoid which is a pg_proc entry */
jdbc_append_function_name(node->aggfnoid, context);
appendStringInfoChar(buf, '(');
/* Add DISTINCT */
appendStringInfoString(buf, (node->aggdistinct != NIL) ? "DISTINCT " : "");
/* aggstar can be set only in zero-argument aggregates */
if (node->aggstar)
{
appendStringInfoChar(buf, '*');
}
else
{
ListCell *arg;
bool first = true;
/* Add all the arguments */
foreach(arg, node->args)
{
TargetEntry *tle = (TargetEntry *) lfirst(arg);
Node *n = (Node *) tle->expr;
if (tle->resjunk)
continue;
if (!first)
appendStringInfoString(buf, ", ");
first = false;
/* Add VARIADIC */
#if PG_VERSION_NUM < 130000
if (use_variadic && lnext(arg) == NULL)
#else
if (use_variadic && lnext(node->args, arg) == NULL)
#endif
appendStringInfoString(buf, "VARIADIC ");
jdbc_deparse_expr((Expr *) n, context);
}
}
/* Add FILTER (WHERE ..) */
if (node->aggfilter != NULL)
{
appendStringInfoString(buf, ") FILTER (WHERE ");
jdbc_deparse_expr((Expr *) node->aggfilter, context);
}
appendStringInfoChar(buf, ')');
}
/*
* Append remote name of specified foreign table to buf. Use value of
* table_name FDW option (if any) instead of relation's name. Similarly,
* schema_name FDW option overrides schema name.
*/
static void
jdbc_deparse_relation(StringInfo buf, Relation rel, char *q_char)
{
ForeignTable *table;
const char *nspname = NULL;
const char *relname = NULL;
ListCell *lc;
/* obtain additional catalog information. */
table = GetForeignTable(RelationGetRelid(rel));
/*
* Use value of FDW options if any, instead of the name of object itself.
*/
foreach(lc, table->options)
{
DefElem *def = (DefElem *) lfirst(lc);
if (strcmp(def->defname, "schema_name") == 0)
nspname = defGetString(def);
else if (strcmp(def->defname, "table_name") == 0)
relname = defGetString(def);
}
/*
* Note: we could skip printing the schema name if it's pg_catalog, but
* that doesn't seem worth the trouble.
*/
if (relname == NULL)
{
relname = RelationGetRelationName(rel);
}
if (nspname == NULL)
{
appendStringInfo(buf, "%s", jdbc_quote_identifier(relname, q_char, false));
}
else if (strlen(nspname) == 0)
{
appendStringInfo(buf, "%s", jdbc_quote_identifier(relname, q_char, false));
}
else
{
appendStringInfo(buf, "%s.%s", jdbc_quote_identifier(nspname, q_char, false),
jdbc_quote_identifier(relname, q_char, false));
}
}
/*
* Append a SQL string literal representing "val" to buf.
*/
static void
jdbc_deparse_string_literal(StringInfo buf, const char *val)
{
const char *valptr;
/*
* Rather than making assumptions about the remote server's value of
* standard_conforming_strings, always use E'foo' syntax if there are any
* backslashes. This will fail on remote servers before 8.1, but those
* are long out of support.
*/
if (strchr(val, '\\') != NULL)
appendStringInfoChar(buf, ESCAPE_STRING_SYNTAX);
appendStringInfoChar(buf, '\'');
for (valptr = val; *valptr; valptr++)
{
char ch = *valptr;
if (SQL_STR_DOUBLE(ch, true))
appendStringInfoChar(buf, ch);
appendStringInfoChar(buf, ch);
}
appendStringInfoChar(buf, '\'');
}
/*
* Deparse given expression into context->buf.
*
* This function must support all the same node types that
* jdbc_foreign_expr_walker accepts.
*
* Note: unlike ruleutils.c, we just use a simple hard-wired parenthesization
* scheme: anything more complex than a Var, Const, function call or cast
* should be self-parenthesized.
*/
static void
jdbc_deparse_expr(Expr *node, deparse_expr_cxt *context)
{
if (node == NULL)
return;
switch (nodeTag(node))
{
case T_Var:
jdbc_deparse_var((Var *) node, context);
break;
case T_Const:
jdbc_deparse_const((Const *) node, context);
break;
case T_Param:
/*
* Does not reach here because foreign_expr_walker returns false.
*/
elog(ERROR, "Parameter is unsupported");
Assert(false);
break;
#if PG_VERSION_NUM < 120000
case T_ArrayRef:
jdbc_deparse_array_ref((ArrayRef *) node, context);
break;
#else
case T_SubscriptingRef:
jdbc_deparse_array_ref((SubscriptingRef *) node, context);
break;
#endif
case T_FuncExpr:
jdbc_deparse_func_expr((FuncExpr *) node, context);
break;
case T_OpExpr:
jdbc_deparse_op_expr((OpExpr *) node, context);
break;
case T_DistinctExpr:
jdbc_deparse_distinct_expr((DistinctExpr *) node, context);
break;
case T_ScalarArrayOpExpr:
jdbc_deparse_scalar_array_op_expr((ScalarArrayOpExpr *) node, context);
break;
case T_RelabelType:
jdbc_deparse_relabel_type((RelabelType *) node, context);
break;
case T_BoolExpr:
jdbc_deparse_bool_expr((BoolExpr *) node, context);
break;
case T_NullTest:
jdbc_deparse_null_test((NullTest *) node, context);
break;
case T_ArrayExpr:
jdbc_deparse_array_expr((ArrayExpr *) node, context);
break;
case T_Aggref:
jdbc_deparse_aggref((Aggref *) node, context);
break;
default:
elog(ERROR, "unsupported expression type for deparse: %d",
(int) nodeTag(node));
break;
}
}
/*
* Deparse given Var node into context->buf.
*
* If the Var belongs to the foreign relation, just print its remote name.
* Otherwise, it's effectively a Param (and will in fact be a Param at run
* time).
*/
static void
jdbc_deparse_var(Var *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
Relids relids = context->scanrel->relids;
/* Qualify columns when multiple relations are involved. */
bool qualify_col = (bms_membership(relids) == BMS_MULTIPLE);
if (bms_is_member(node->varno, relids) && node->varlevelsup == 0)
{
/* Var belongs to foreign table */
jdbc_deparse_column_ref(buf, node->varno, node->varattno, context->root, qualify_col, context->q_char);
}
else
{
/* Does not reach here. */
elog(ERROR, "Parameter is unsupported");
Assert(false);
}
}
/*
* Deparse given constant value into context->buf.
*
* This function has to be kept in sync with ruleutils.c's get_const_expr.
*/
static void
jdbc_deparse_const(Const *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
Oid typoutput;
bool typIsVarlena;
char *extval;
if (node->constisnull)
{
appendStringInfoString(buf, "NULL");
return;
}
getTypeOutputInfo(node->consttype,
&typoutput, &typIsVarlena);
extval = OidOutputFunctionCall(typoutput, node->constvalue);
switch (node->consttype)
{
case INT2OID:
case INT4OID:
case INT8OID:
case OIDOID:
case FLOAT4OID:
case FLOAT8OID:
case NUMERICOID:
{
/*
* No need to quote unless it's a special value such as 'NaN'.
* See comments in get_const_expr().
*/
if (strspn(extval, "0123456789+-eE.") == strlen(extval))
{
if (extval[0] == '+' || extval[0] == '-')
appendStringInfo(buf, "(%s)", extval);
else
appendStringInfoString(buf, extval);
}
else
appendStringInfo(buf, "'%s'", extval);
}
break;
case BITOID:
case VARBITOID:
appendStringInfo(buf, "B'%s'", extval);
break;
case BOOLOID:
if (strcmp(extval, "t") == 0)
appendStringInfoString(buf, "true");
else
appendStringInfoString(buf, "false");
break;
default:
jdbc_deparse_string_literal(buf, extval);
break;
}
/*
* Append ::typename unless the constant will be implicitly typed as the
* right type when it is read in.
*
* XXX this code has to be kept in sync with the behavior of the parser,
* especially make_const.
*/
/*
* switch (node->consttype) { case BOOLOID: case INT4OID: case UNKNOWNOID:
* needlabel = false; break; case NUMERICOID: needlabel = !isfloat ||
* (node->consttypmod >= 0); break; default: needlabel = true; break; }
*/
/*
* if (needlabel) appendStringInfo(buf, "::%s",
* format_type_with_typemod(node->consttype, node->consttypmod));
*/
}
/*
* Deparse an array subscript expression.
*/
static void
#if PG_VERSION_NUM < 120000
jdbc_deparse_array_ref(ArrayRef * node, deparse_expr_cxt *context)
#else
jdbc_deparse_array_ref(SubscriptingRef *node, deparse_expr_cxt *context)
#endif
{
StringInfo buf = context->buf;
ListCell *lowlist_item;
ListCell *uplist_item;
/* Always parenthesize the expression. */
appendStringInfoChar(buf, '(');
/*
* Deparse referenced array expression first. If that expression includes
* a cast, we have to parenthesize to prevent the array subscript from
* being taken as typename decoration. We can avoid that in the typical
* case of subscripting a Var, but otherwise do it.
*/
if (IsA(node->refexpr, Var))
jdbc_deparse_expr(node->refexpr, context);
else
{
appendStringInfoChar(buf, '(');
jdbc_deparse_expr(node->refexpr, context);
appendStringInfoChar(buf, ')');
}
/* Deparse subscript expressions. */
lowlist_item = list_head(node->reflowerindexpr); /* could be NULL */
foreach(uplist_item, node->refupperindexpr)
{
appendStringInfoChar(buf, '[');
if (lowlist_item)
{
jdbc_deparse_expr(lfirst(lowlist_item), context);
appendStringInfoChar(buf, ':');
#if PG_VERSION_NUM < 130000
lowlist_item = lnext(lowlist_item);
#else
lowlist_item = lnext(node->reflowerindexpr, lowlist_item);
#endif
}
jdbc_deparse_expr(lfirst(uplist_item), context);
appendStringInfoChar(buf, ']');
}
appendStringInfoChar(buf, ')');
}
/*
* Deparse a function call.
*/
static void
jdbc_deparse_func_expr(FuncExpr *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
HeapTuple proctup;
Form_pg_proc procform;
const char *proname;
bool use_variadic;
bool first;
ListCell *arg;
char *q_char = context->q_char;
/*
* If the function call came from an implicit coercion, then just show the
* first argument.
*/
if (node->funcformat == COERCE_IMPLICIT_CAST)
{
jdbc_deparse_expr((Expr *) linitial(node->args), context);
return;
}
/*
* Normal function: display as proname(args).
*/
proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(node->funcid));
if (!HeapTupleIsValid(proctup))
elog(ERROR, "cache lookup failed for function %u", node->funcid);
procform = (Form_pg_proc) GETSTRUCT(proctup);
/* Check if need to print VARIADIC (cf. ruleutils.c) */
use_variadic = node->funcvariadic;
/* Print schema name only if it's not pg_catalog */
if (procform->pronamespace != PG_CATALOG_NAMESPACE)
{
const char *schemaname;
schemaname = get_namespace_name(procform->pronamespace);
appendStringInfo(buf, "%s.", jdbc_quote_identifier(schemaname, q_char, false));
}
/* Deparse the function name ... */
proname = NameStr(procform->proname);
appendStringInfo(buf, "%s(", jdbc_quote_identifier(proname, q_char, false));
/* ... and all the arguments */
first = true;
foreach(arg, node->args)
{
if (!first)
appendStringInfoString(buf, ", ");
#if PG_VERSION_NUM < 130000
if (use_variadic && lnext(arg) == NULL)
appendStringInfoString(buf, "VARIADIC ");
#else
if (use_variadic && lnext(node->args, arg) == NULL)
appendStringInfoString(buf, "VARIADIC ");
#endif
jdbc_deparse_expr((Expr *) lfirst(arg), context);
first = false;
}
appendStringInfoChar(buf, ')');
ReleaseSysCache(proctup);
}
/*
* Deparse given operator expression. To avoid problems around priority of
* operations, we always parenthesize the arguments.
*/
static void
jdbc_deparse_op_expr(OpExpr *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
HeapTuple tuple;
Form_pg_operator form;
char oprkind;
/* Retrieve information about the operator from system catalog. */
tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for operator %u", node->opno);
form = (Form_pg_operator) GETSTRUCT(tuple);
oprkind = form->oprkind;
/* Sanity check. */
#if PG_VERSION_NUM < 140000
Assert((oprkind == 'r' && list_length(node->args) == 1) ||
(oprkind == 'l' && list_length(node->args) == 1) ||
(oprkind == 'b' && list_length(node->args) == 2));
#else
Assert((oprkind == 'l' && list_length(node->args) == 1) ||
(oprkind == 'b' && list_length(node->args) == 2));
#endif
/* Always parenthesize the expression. */
appendStringInfoChar(buf, '(');
/* Deparse left operand. */
#if PG_VERSION_NUM < 140000
if (oprkind == 'r' || oprkind == 'b')
#else
if (oprkind == 'b')
#endif
{
jdbc_deparse_expr(linitial(node->args), context);
appendStringInfoChar(buf, ' ');
}
/* Deparse operator name. */
jdbc_deparse_operator_name(buf, form);
/* Deparse right operand. */
#if PG_VERSION_NUM < 140000
if (oprkind == 'l' || oprkind == 'b')
{
#endif
appendStringInfoChar(buf, ' ');
jdbc_deparse_expr(llast(node->args), context);
#if PG_VERSION_NUM < 140000
}
#endif
appendStringInfoChar(buf, ')');
ReleaseSysCache(tuple);
}
/*
* Print the name of an operator.
*/
static void
jdbc_deparse_operator_name(StringInfo buf, Form_pg_operator opform)
{
char *cur_opname;
/* opname is not a SQL identifier, so we should not quote it. */
cur_opname = NameStr(opform->oprname);
/* Print schema name only if it's not pg_catalog */
if (opform->oprnamespace != PG_CATALOG_NAMESPACE)
{
elog(ERROR, "OPERATOR is not supported");
}
else
{
if (strcmp(cur_opname, "~~") == 0)
{
appendStringInfoString(buf, "LIKE");
}
else if (strcmp(cur_opname, "!~~") == 0)
{
appendStringInfoString(buf, "NOT LIKE");
}
else if (strcmp(cur_opname, "~~*") == 0 ||
strcmp(cur_opname, "!~~*") == 0 ||
strcmp(cur_opname, "~") == 0 ||
strcmp(cur_opname, "!~") == 0 ||
strcmp(cur_opname, "~*") == 0 ||
strcmp(cur_opname, "!~*") == 0)
{
elog(ERROR, "OPERATOR is not supported");
}
else
{
appendStringInfoString(buf, cur_opname);
}
}
}
/*
* Deparse IS DISTINCT FROM.
*/
static void
jdbc_deparse_distinct_expr(DistinctExpr *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
Assert(list_length(node->args) == 2);
appendStringInfoChar(buf, '(');
jdbc_deparse_expr(linitial(node->args), context);
appendStringInfoString(buf, " IS DISTINCT FROM ");
jdbc_deparse_expr(lsecond(node->args), context);
appendStringInfoChar(buf, ')');
}
/*
* Deparse given ScalarArrayOpExpr expression. To avoid problems around
* priority of operations, we always parenthesize the arguments.
*/
static void
jdbc_deparse_scalar_array_op_expr(ScalarArrayOpExpr *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
HeapTuple tuple;
Expr *arg1;
Expr *arg2;
Form_pg_operator form;
char *opname = NULL;
Oid typoutput;
bool typIsVarlena;
char *extval;
bool useIn = false;
/* Retrieve information about the operator from system catalog. */
tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(node->opno));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for operator %u", node->opno);
form = (Form_pg_operator) GETSTRUCT(tuple);
/* Sanity check. */
Assert(list_length(node->args) == 2);
opname = pstrdup(NameStr(form->oprname));
ReleaseSysCache(tuple);
/* Using IN clause for '= ANY' and NOT IN clause for '<> ALL' */
if ((strcmp(opname, "=") == 0 && node->useOr == true) ||
(strcmp(opname, "<>") == 0 && node->useOr == false))
useIn = true;
/* Get left and right argument for deparsing */
arg1 = linitial(node->args);
arg2 = lsecond(node->args);
if (useIn)
{
/* Deparse left operand. */
jdbc_deparse_expr(arg1, context);
appendStringInfoChar(buf, ' ');
/* Add IN clause */
if (strcmp(opname, "<>") == 0)
{
appendStringInfoString(buf, "NOT IN (");
}
else if (strcmp(opname, "=") == 0)
{
appendStringInfoString(buf, "IN (");
}
}
switch (nodeTag((Node *) arg2))
{
case T_Const:
{
Const *c = (Const *) arg2;
bool isstr = false;
const char *valptr;
int i = -1;
bool deparseLeft = true;
if (!c->constisnull)
{
getTypeOutputInfo(c->consttype,
&typoutput, &typIsVarlena);
extval = OidOutputFunctionCall(typoutput, c->constvalue);
/* Determine array type */
switch (c->consttype)
{
case INT4ARRAYOID:
case OIDARRAYOID:
isstr = false;
break;
default:
isstr = true;
break;
}
for (valptr = extval; *valptr; valptr++)
{
char ch = *valptr;
i++;
if (useIn)
{
if (i == 0 && isstr)
appendStringInfoChar(buf, '\'');
}
else if (deparseLeft)
{
/* Deparse left operand. */
jdbc_deparse_expr(arg1, context);
/* Append operator */
appendStringInfo(buf, " %s ", opname);
if (isstr)
appendStringInfoChar(buf, '\'');
deparseLeft = false;
}
/*
* Remove '{', '}' and \" character from the string.
* Because this syntax is not recognize by the remote
* Sqlite server.
*/
if ((ch == '{' && i == 0) || (ch == '}' && (i == (strlen(extval) - 1))) || ch == '\"')
continue;
if (ch == ',')
{
if (useIn)
{
if (isstr)
appendStringInfoChar(buf, '\'');
appendStringInfoChar(buf, ch);
appendStringInfoChar(buf, ' ');
if (isstr)
appendStringInfoChar(buf, '\'');
}
else
{
if (isstr)
appendStringInfoChar(buf, '\'');
if (node->useOr)
appendStringInfoString(buf, " OR ");
else
appendStringInfoString(buf, " AND ");
deparseLeft = true;
}
continue;
}
appendStringInfoChar(buf, ch);
}
if (isstr)
appendStringInfoChar(buf, '\'');
}
else
{
appendStringInfoString(buf, " NULL");
return;
}
}
break;
case T_ArrayExpr:
{
bool first = true;
ListCell *lc;
foreach(lc, ((ArrayExpr *) arg2)->elements)
{
if (!first)
{
if (useIn)
{
appendStringInfoString(buf, ", ");
}
else
{
if (node->useOr)
appendStringInfoString(buf, " OR ");
else
appendStringInfoString(buf, " AND ");
}
}
if (useIn)
{
jdbc_deparse_expr(lfirst(lc), context);
}
else
{
/* Deparse left argument */
appendStringInfoChar(buf, '(');
jdbc_deparse_expr(arg1, context);
appendStringInfo(buf, " %s ", opname);
/*
* Deparse each element in right argument
*/
jdbc_deparse_expr(lfirst(lc), context);
appendStringInfoChar(buf, ')');
}
first = false;
}
break;
}
default:
elog(ERROR, "unsupported expression type for deparse: %d", (int) nodeTag(node));
break;
}
/* Close IN clause */
if (useIn)
appendStringInfoChar(buf, ')');
}
/*
* Deparse a RelabelType (binary-compatible cast) node.
*/
static void
jdbc_deparse_relabel_type(RelabelType *node, deparse_expr_cxt *context)
{
jdbc_deparse_expr(node->arg, context);
}
/*
* Deparse a BoolExpr node.
*
* Note: by the time we get here, AND and OR expressions have been flattened
* into N-argument form, so we'd better be prepared to deal with that.
*/
static void
jdbc_deparse_bool_expr(BoolExpr *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
const char *op = NULL; /* keep compiler quiet */
bool first;
ListCell *lc;
switch (node->boolop)
{
case AND_EXPR:
op = "AND";
break;
case OR_EXPR:
op = "OR";
break;
case NOT_EXPR:
appendStringInfoString(buf, "(NOT ");
jdbc_deparse_expr(linitial(node->args), context);
appendStringInfoChar(buf, ')');
return;
}
appendStringInfoChar(buf, '(');
first = true;
foreach(lc, node->args)
{
if (!first)
appendStringInfo(buf, " %s ", op);
jdbc_deparse_expr((Expr *) lfirst(lc), context);
first = false;
}
appendStringInfoChar(buf, ')');
}
/*
* Deparse IS [NOT] NULL expression.
*/
static void
jdbc_deparse_null_test(NullTest *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
appendStringInfoChar(buf, '(');
jdbc_deparse_expr(node->arg, context);
if (node->nulltesttype == IS_NULL)
appendStringInfoString(buf, " IS NULL)");
else
appendStringInfoString(buf, " IS NOT NULL)");
}
/*
* Deparse ARRAY[...] construct.
*/
static void
jdbc_deparse_array_expr(ArrayExpr *node, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
bool first = true;
ListCell *lc;
appendStringInfoString(buf, "ARRAY[");
foreach(lc, node->elements)
{
if (!first)
appendStringInfoString(buf, ", ");
jdbc_deparse_expr(lfirst(lc), context);
first = false;
}
appendStringInfoChar(buf, ']');
}
/*
* jdbc_append_function_name Deparses function name from given function oid.
*/
static void
jdbc_append_function_name(Oid funcid, deparse_expr_cxt *context)
{
StringInfo buf = context->buf;
HeapTuple proctup;
Form_pg_proc procform;
const char *proname;
char *q_char = context->q_char;
proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
if (!HeapTupleIsValid(proctup))
elog(ERROR, "cache lookup failed for function %u", funcid);
procform = (Form_pg_proc) GETSTRUCT(proctup);
/* Always print the function name */
proname = NameStr(procform->proname);
appendStringInfoString(buf, jdbc_quote_identifier(proname, q_char, false));
ReleaseSysCache(proctup);
}
/*
* jdbc_quote_identifier - Quote an identifier only if needed
*
* When quotes are needed, we palloc the required space; slightly
* space-wasteful but well worth it for notational simplicity.
* refer: PostgreSQL 13.0 src/backend/utils/adt/ruleutils.c L10730
*/
static const char *
jdbc_quote_identifier(const char *ident, char *q_char, bool quote_all_identifiers)
{
/*
* Can avoid quoting if ident starts with a lowercase letter or underscore
* and contains only lowercase letters, digits, and underscores, *and* is
* not any SQL keyword. Otherwise, supply quotes.
*/
int nquotes = 0;
bool safe;
const char *ptr;
char *result;
char *optr;
/*
* Verify q_char get from remote server
*/
if (strlen(q_char) == 1)
{
/* q_char is a char value */
if (strcmp(q_char, " ") == 0)
{
/* remote server not support identifier quote string */
return ident; /* no change needed */
}
}
else
{
/*
* q_char is a string value. Currently, we do not handle this case.
*/
elog(ERROR, "jdbc_fdw: Not support quote string \"%s\".", q_char);
}
/*
* would like to use <ctype.h> macros here, but they might yield unwanted
* locale-specific results...
*/
safe = ((ident[0] >= 'a' && ident[0] <= 'z') || ident[0] == '_');
for (ptr = ident; *ptr; ptr++)
{
char ch = *ptr;
if ((ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9') ||
(ch == '_'))
{
/* okay */
}
else
{
safe = false;
if (ch == *q_char)
nquotes++;
}
}
if (quote_all_identifiers)
safe = false;
if (safe)
{
/*
* Check for keyword. We quote keywords except for unreserved ones.
* (In some cases we could avoid quoting a col_name or type_func_name
* keyword, but it seems much harder than it's worth to tell that.)
*
* Note: ScanKeywordLookup() does case-insensitive comparison, but
* that's fine, since we already know we have all-lower-case.
*/
int kwnum = ScanKeywordLookup(ident, &ScanKeywords);
if (kwnum >= 0 && ScanKeywordCategories[kwnum] != UNRESERVED_KEYWORD)
safe = false;
}
if (safe)
return ident; /* no change needed */
/* -----
* Create new ident:
* - Enclose by q_char arg
* - Add escape for quotes char
*
* Note:
* - nquote: number of quote char need to escape
* - 2: number of outer quote.
* - 1: null terminator.
* -----
*/
result = (char *) palloc0(strlen(ident) + nquotes + 2 + 1);
optr = result;
*optr++ = *q_char;
for (ptr = ident; *ptr; ptr++)
{
char ch = *ptr;
if (ch == *q_char)
*optr++ = *q_char;
*optr++ = ch;
}
*optr++ = *q_char;
*optr = '\0';
return result;
}
| 26.082902 | 105 | 0.667629 |
08c5fa2bbc0f73fa3b989518282aaa9f2f645ce5 | 676 | h | C | arch/mips/kvm/commpage.h | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | arch/mips/kvm/commpage.h | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 13 | 2021-07-10T04:36:17.000Z | 2022-03-03T10:50:05.000Z | arch/mips/kvm/commpage.h | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 30 | 2018-05-02T08:43:27.000Z | 2022-01-23T03:25:54.000Z | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* KVM/MIPS: commpage: mapped into get kernel space
*
* Copyright (C) 2012 MIPS Technologies, Inc. All rights reserved.
* Authors: Sanjay Lal <sanjayl@kymasys.com>
*/
#ifndef __KVM_MIPS_COMMPAGE_H__
#define __KVM_MIPS_COMMPAGE_H__
struct kvm_mips_commpage {
/* COP0 state is mapped into Guest kernel via commpage */
struct mips_coproc cop0;
};
#define KVM_MIPS_COMM_EIDI_OFFSET 0x0
extern void kvm_mips_commpage_init(struct kvm_vcpu *vcpu);
#endif /* __KVM_MIPS_COMMPAGE_H__ */
| 27.04 | 77 | 0.752959 |
26006124d06298f321025ddb0db24391dca5c586 | 3,050 | h | C | Geometry/Geomlib_PolylineIntersection.h | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 28 | 2017-03-01T04:09:18.000Z | 2022-02-01T13:33:50.000Z | Geometry/Geomlib_PolylineIntersection.h | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 3 | 2017-03-09T05:22:49.000Z | 2017-08-02T18:38:05.000Z | Geometry/Geomlib_PolylineIntersection.h | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 17 | 2017-03-01T14:00:01.000Z | 2022-02-08T06:36:54.000Z | //
// Copyright (c) 2016 - 2017 Mesh Consultants Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 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 <Urho3D/Core/Variant.h>
#include <Urho3D/Container/Vector.h>
namespace Geomlib {
// [t1, t2] interval of real number line; no promise that t1 <= t2
// [s1, s2] interval of real number line; no promise that s1 <= s2
// Returns:
// 1 if [t1, t2] and [s1, s2] have non-empty intersection
// 0 otherwise
int IntervalIntervalIntersection(
double t1,
double t2,
double s1,
double s2);
// 1 if (A,B) and (C,D) have non-empty intersection
// 0 otherwise
int SegmentSegmentIntersection2D(
Urho3D::Vector2& A,
Urho3D::Vector2& B,
Urho3D::Vector2& C,
Urho3D::Vector2& D);
int SegmentSegmentIntersection3D(
Urho3D::Vector3& A,
Urho3D::Vector3& B,
Urho3D::Vector3& C,
Urho3D::Vector3& D,
Urho3D::Vector3& normal);
// ONLY FOR PLANAR POLYLINES
// returns true if the polyline has a self-intersection
// does not count a closed polyline as self-intersecting
bool HasSelfIntersection(const Urho3D::Variant polyline);
// returns a list of self intersections of the polyline
int GetSelfIntersections(
const Urho3D::Variant polyline,
Urho3D::Vector<Urho3D::Vector3>& intersections,
Urho3D::Variant& revised_polyline
);
// inserts the point into the vertex list between A, B and C, D
int InsertSelfIntersectionsAsPoint(
const Urho3D::Vector3& A,
const Urho3D::Vector3& B,
const Urho3D::Vector3& C,
const Urho3D::Vector3& D,
const Urho3D::Vector3& point,
Urho3D::Vector<Urho3D::Vector3>& verts);
int GetPointOfIntersection(
const Urho3D::Vector3& A,
const Urho3D::Vector3& B,
const Urho3D::Vector3& C,
const Urho3D::Vector3& D,
Urho3D::Vector3& point);
bool ShortestDistance(
const Urho3D::Vector3& A,
const Urho3D::Vector3& B,
const Urho3D::Vector3& C,
const Urho3D::Vector3& D,
double& ta, double& tb);
Urho3D::Variant Polyline_Make_With_Intersections(const Urho3D::Vector<Urho3D::Vector3>& vertexList);
} | 32.105263 | 101 | 0.731475 |
26168577e495b59f14c6acb176da91f2f346d234 | 266 | h | C | Coffee/include/Coffee/Renderer/GraphicsContext.h | SentientCoffee/HazelnutEngine | b1e9e29d50119a2882d840c47078363db71b266b | [
"Apache-2.0"
] | 1 | 2020-07-19T20:07:25.000Z | 2020-07-19T20:07:25.000Z | Coffee/include/Coffee/Renderer/GraphicsContext.h | SentientCoffee/CoffeeEngine | b1e9e29d50119a2882d840c47078363db71b266b | [
"Apache-2.0"
] | null | null | null | Coffee/include/Coffee/Renderer/GraphicsContext.h | SentientCoffee/CoffeeEngine | b1e9e29d50119a2882d840c47078363db71b266b | [
"Apache-2.0"
] | null | null | null | #pragma once
namespace Coffee {
class GraphicsContext {
public:
GraphicsContext() = default;
virtual ~GraphicsContext() = default;
virtual void init() = 0;
virtual void swapBuffers() = 0;
static Scope<GraphicsContext> create(void* window);
};
} | 15.647059 | 53 | 0.68797 |
b7e3fb1ea5d26de4728baa11c8ff46c442162722 | 4,932 | c | C | renesas/YRDKRL78G14/applilet3_src/r_cg_it_user.c | anne18a/scanner_2lemetry | 9b0f5fe5476d3a633fce7bb0affbfba10e41fbe4 | [
"Unlicense"
] | 1 | 2015-06-29T01:26:37.000Z | 2015-06-29T01:26:37.000Z | renesas/YRDKRL78G14/applilet3_src/r_cg_it_user.c | anne18a/scanner_2lemetry | 9b0f5fe5476d3a633fce7bb0affbfba10e41fbe4 | [
"Unlicense"
] | null | null | null | renesas/YRDKRL78G14/applilet3_src/r_cg_it_user.c | anne18a/scanner_2lemetry | 9b0f5fe5476d3a633fce7bb0affbfba10e41fbe4 | [
"Unlicense"
] | null | null | null | /***********************************************************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only
* intended for use with Renesas products. No other uses are authorized. This
* software is owned by Renesas Electronics Corporation and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software
* and to discontinue the availability of this software. By using this software,
* you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2011 Renesas Electronics Corporation. All rights reserved.
***********************************************************************************************************************/
/***********************************************************************************************************************
* File Name : r_cg_it_user.c
* Version : Applilet3 for RL78/G14 V1.01.01 [11 Oct 2011]
* Device(s) : R5F104PJ
* Tool-Chain : IAR Systems iccrl78
* Description : This file implements device driver for IT module.
* Creation Date: 7/3/2012
***********************************************************************************************************************/
/***********************************************************************************************************************
Includes
***********************************************************************************************************************/
#include "r_cg_macrodriver.h"
#include "r_cg_it.h"
/* Start user code for include. Do not edit comment generated here */
volatile int G_100usTimer = 0; // 100 microseconds counter
volatile int G_msTimer = 0; // millisecond counter
/* End user code. Do not edit comment generated here */
#include "r_cg_userdefine.h"
/***********************************************************************************************************************
Global variables and functions
***********************************************************************************************************************/
/* Start user code for global. Do not edit comment generated here */
/* End user code. Do not edit comment generated here */
/***********************************************************************************************************************
* Function Name: r_it_interrupt
* Description : This function is INTIT interrupt service routine.
* Arguments : None
* Return Value : None
***********************************************************************************************************************/
#pragma vector = INTIT_vect
__interrupt static void r_it_interrupt(void)
{
/* Start user code. Do not edit comment generated here */
G_100usTimer++;
if((G_100usTimer % 10) == 0)
G_msTimer++;
/* End user code. Do not edit comment generated here */
}
/* Start user code for adding. Do not edit comment generated here */
/*---------------------------------------------------------------------------*
* delay_ms
*---------------------------------------------------------------------------
* Description:
* Uses the interval timer to delay so many milliseconds
* Inputs:
* aCount - number of 100us intervals to delay
*---------------------------------------------------------------------------*/
void delay_100us(int aCount)
{
G_100usTimer = 0;
R_IT_Start();
while(G_100usTimer < aCount);
R_IT_Stop();
}
/*---------------------------------------------------------------------------*
* delay_ms
*---------------------------------------------------------------------------
* Description:
* Uses the interval timer to delay so many milliseconds
* Inputs:
* aTimeMS - milliseconds to delay
*---------------------------------------------------------------------------*/
void delay_ms(int aTimeMS)
{
G_msTimer = 0;
R_IT_Start();
while(G_msTimer < aTimeMS);
R_IT_Stop();
}
/* End user code. Do not edit comment generated here */
| 48.352941 | 121 | 0.471006 |
b7f7e533dd18c0b3924b4faab9efa1b67fdc595d | 12,637 | c | C | src/third_party/wiredtiger/test/format/util.c | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/format/util.c | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/format/util.c | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /*-
* Public Domain 2014-present MongoDB, Inc.
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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 "format.h"
/*
* track_ts_diff --
* Return a one character descriptor of relative timestamp values.
*/
static const char *
track_ts_diff(uint64_t left_ts, uint64_t right_ts)
{
if (left_ts < right_ts)
return "+";
else if (left_ts == right_ts)
return "=";
else
return "-";
}
/*
* track_ts_dots --
* Return an entry in the time stamp progress indicator.
*/
static const char *
track_ts_dots(u_int dot_count)
{
static const char *dots[] = {" ", ". ", ".. ", "..."};
return (dots[dot_count % WT_ELEMENTS(dots)]);
}
/*
* track_write --
* Write out a tracking message.
*/
static void
track_write(char *msg, size_t len)
{
static size_t last_len; /* callers must be single-threaded */
if (last_len > len) {
memset(msg + len, ' ', (size_t)(last_len - len));
msg[last_len] = '\0';
}
last_len = len;
if (printf("%s\r", msg) < 0)
testutil_die(EIO, "printf");
if (fflush(stdout) == EOF)
testutil_die(errno, "fflush");
}
/*
* track_ops --
* Show a status line of operations and time stamp progress.
*/
void
track_ops(TINFO *tinfo)
{
static uint64_t last_cur, last_old, last_stable;
static u_int cur_dot_cnt, old_dot_cnt, stable_dot_cnt;
size_t len;
uint64_t cur_ts, old_ts, stable_ts;
char msg[128], ts_msg[64];
if (GV(QUIET))
return;
ts_msg[0] = '\0';
if (g.transaction_timestamps_config) {
/*
* Don't worry about having a completely consistent set of timestamps.
*/
old_ts = g.oldest_timestamp;
stable_ts = g.stable_timestamp;
cur_ts = g.timestamp;
if (old_ts != last_old) {
++old_dot_cnt;
last_old = old_ts;
}
if (stable_ts != last_stable) {
++stable_dot_cnt;
last_stable = stable_ts;
}
if (cur_ts != last_cur) {
++cur_dot_cnt;
last_cur = cur_ts;
}
testutil_check(__wt_snprintf(ts_msg, sizeof(ts_msg),
" old%s"
"stb%s%s"
"ts%s%s",
track_ts_dots(old_dot_cnt), track_ts_diff(old_ts, stable_ts),
track_ts_dots(stable_dot_cnt), track_ts_diff(stable_ts, cur_ts),
track_ts_dots(cur_dot_cnt)));
}
testutil_check(__wt_snprintf_len_set(msg, sizeof(msg), &len,
"ops: "
"S %" PRIu64
"%s, "
"I %" PRIu64
"%s, "
"U %" PRIu64
"%s, "
"R %" PRIu64 "%s%s",
tinfo->search > M(9) ? tinfo->search / M(1) : tinfo->search, tinfo->search > M(9) ? "M" : "",
tinfo->insert > M(9) ? tinfo->insert / M(1) : tinfo->insert, tinfo->insert > M(9) ? "M" : "",
tinfo->update > M(9) ? tinfo->update / M(1) : tinfo->update, tinfo->update > M(9) ? "M" : "",
tinfo->remove > M(9) ? tinfo->remove / M(1) : tinfo->remove, tinfo->remove > M(9) ? "M" : "",
ts_msg));
track_write(msg, len);
}
/*
* track --
* Show general operation progress.
*/
void
track(const char *tag, uint64_t cnt)
{
size_t len;
char msg[128];
if (GV(QUIET))
return;
if (cnt == 0)
testutil_check(__wt_snprintf_len_set(msg, sizeof(msg), &len, "%s", tag));
else
testutil_check(__wt_snprintf_len_set(msg, sizeof(msg), &len, "%s: %" PRIu64, tag, cnt));
track_write(msg, len);
}
/*
* path_setup --
* Build the standard paths and shell commands we use.
*/
void
path_setup(const char *home)
{
size_t len;
const char *name;
/* Home directory. */
g.home = dstrdup(home == NULL ? "RUNDIR" : home);
/* Configuration file. */
name = "CONFIG";
len = strlen(g.home) + strlen(name) + 2;
g.home_config = dmalloc(len);
testutil_check(__wt_snprintf(g.home_config, len, "%s/%s", g.home, name));
/* Key length configuration file. */
name = "CONFIG.keylen";
len = strlen(g.home) + strlen(name) + 2;
g.home_key = dmalloc(len);
testutil_check(__wt_snprintf(g.home_key, len, "%s/%s", g.home, name));
/* History store dump file. */
name = "FAIL.HSdump";
len = strlen(g.home) + strlen(name) + 2;
g.home_hsdump = dmalloc(len);
testutil_check(__wt_snprintf(g.home_hsdump, len, "%s/%s", g.home, name));
/* Page dump file. */
name = "FAIL.pagedump";
len = strlen(g.home) + strlen(name) + 2;
g.home_pagedump = dmalloc(len);
testutil_check(__wt_snprintf(g.home_pagedump, len, "%s/%s", g.home, name));
/* Statistics file. */
name = "OPERATIONS.stats";
len = strlen(g.home) + strlen(name) + 2;
g.home_stats = dmalloc(len);
testutil_check(__wt_snprintf(g.home_stats, len, "%s/%s", g.home, name));
}
/*
* fp_readv --
* Read and return a value from a file.
*/
bool
fp_readv(FILE *fp, char *name, uint32_t *vp)
{
u_long ulv;
char *endptr, buf[64];
if (fgets(buf, sizeof(buf), fp) == NULL)
testutil_die(errno, "%s: read-value error", name);
errno = 0;
ulv = strtoul(buf, &endptr, 10);
testutil_assert(errno == 0 && endptr[0] == '\n');
testutil_assert(ulv <= UINT32_MAX);
*vp = (uint32_t)ulv;
return (false);
}
/*
* fclose_and_clear --
* Close a file and clear the handle so we don't close twice.
*/
void
fclose_and_clear(FILE **fpp)
{
FILE *fp;
if ((fp = *fpp) == NULL)
return;
*fpp = NULL;
if (fclose(fp) != 0)
testutil_die(errno, "fclose");
}
/*
* timestamp_parse --
* Parse a timestamp to an integral value.
*/
static void
timestamp_parse(const char *p, uint64_t *tsp)
{
char *endptr;
errno = 0;
*tsp = __wt_strtouq(p, &endptr, 16);
testutil_assert(errno == 0 && endptr[0] == '\0');
}
/*
* timestamp_init --
* Set the stable timestamp on open.
*/
void
timestamp_init(void)
{
WT_CONNECTION *conn;
char timestamp_buf[2 * sizeof(uint64_t) + 1];
conn = g.wts_conn;
testutil_check(conn->query_timestamp(conn, timestamp_buf, "get=recovery"));
timestamp_parse(timestamp_buf, &g.timestamp);
}
/*
* timestamp_once --
* Update the timestamp once.
*/
void
timestamp_once(WT_SESSION *session, bool allow_lag, bool final)
{
static const char *oldest_timestamp_str = "oldest_timestamp=";
static const char *stable_timestamp_str = "stable_timestamp=";
WT_CONNECTION *conn;
WT_DECL_RET;
uint64_t all_durable;
char buf[WT_TS_HEX_STRING_SIZE * 2 + 64];
conn = g.wts_conn;
/* Lock out transaction timestamp operations. */
lock_writelock(session, &g.ts_lock);
if (final)
g.oldest_timestamp = g.stable_timestamp = ++g.timestamp;
else {
if ((ret = conn->query_timestamp(conn, buf, "get=all_durable")) == 0)
all_durable = testutil_timestamp_parse(buf);
else {
testutil_assert(ret == WT_NOTFOUND);
lock_writeunlock(session, &g.ts_lock);
return;
}
/*
* If a lag is permitted, move the oldest timestamp half the way to the current
* "all_durable" timestamp. Move the stable timestamp to "all_durable".
*/
if (allow_lag)
g.oldest_timestamp = (all_durable + g.oldest_timestamp) / 2;
else
g.oldest_timestamp = all_durable;
g.stable_timestamp = all_durable;
}
lock_writeunlock(session, &g.ts_lock);
testutil_check(__wt_snprintf(buf, sizeof(buf), "%s%" PRIx64 ",%s%" PRIx64, oldest_timestamp_str,
g.oldest_timestamp, stable_timestamp_str, g.stable_timestamp));
lock_writelock(session, &g.prepare_commit_lock);
testutil_check(conn->set_timestamp(conn, buf));
lock_writeunlock(session, &g.prepare_commit_lock);
trace_msg(
"%-10s oldest=%" PRIu64 ", stable=%" PRIu64, "setts", g.oldest_timestamp, g.stable_timestamp);
}
/*
* timestamp --
* Periodically update the oldest timestamp.
*/
WT_THREAD_RET
timestamp(void *arg)
{
WT_CONNECTION *conn;
WT_SESSION *session;
(void)arg; /* Unused argument */
conn = g.wts_conn;
/* Locks need session */
testutil_check(conn->open_session(conn, NULL, NULL, &session));
/* Update the oldest and stable timestamps at least once every 15 seconds. */
while (!g.workers_finished) {
random_sleep(&g.rnd, 15);
timestamp_once(session, true, false);
}
testutil_check(session->close(session, NULL));
return (WT_THREAD_RET_VALUE);
}
/*
* timestamp_teardown --
* Wrap up timestamp operations.
*/
void
timestamp_teardown(WT_SESSION *session)
{
/*
* Do a final bump of the oldest and stable timestamps, otherwise recent operations can prevent
* verify from running.
*/
timestamp_once(session, false, true);
}
/*
* set_oldest_timestamp --
* Query the oldest timestamp from wiredtiger and set it as our global oldest timestamp. This
* should only be called on runs for pre existing databases.
*/
void
set_oldest_timestamp(void)
{
static const char *oldest_timestamp_str = "oldest_timestamp=";
WT_CONNECTION *conn;
WT_DECL_RET;
uint64_t oldest_ts;
char buf[WT_TS_HEX_STRING_SIZE * 2 + 64], tsbuf[WT_TS_HEX_STRING_SIZE];
conn = g.wts_conn;
if ((ret = conn->query_timestamp(conn, tsbuf, "get=oldest_timestamp")) == 0) {
oldest_ts = testutil_timestamp_parse(tsbuf);
g.timestamp = oldest_ts;
testutil_check(
__wt_snprintf(buf, sizeof(buf), "%s%" PRIx64, oldest_timestamp_str, g.oldest_timestamp));
} else if (ret != WT_NOTFOUND)
/*
* Its possible there may not be an oldest timestamp as such we could get not found. This
* should be okay assuming timestamps are not configured if they are, it's still okay as we
* could have configured timestamps after not running with timestamps. As such only error if
* we get a non not found error. If we were supposed to fail with not found we'll see an
* error later on anyway.
*/
testutil_die(ret, "unable to query oldest timestamp");
}
/*
* maximum_read_ts --
* Return the largest safe read timestamp.
*/
uint64_t
maximum_read_ts(void)
{
TINFO **tlp;
uint64_t ts;
/*
* We can't use a read timestamp that's ahead of a commit timestamp. Find the maximum safe read
* timestamp.
*/
for (ts = g.timestamp, tlp = tinfo_list; *tlp != NULL; ++tlp)
ts = WT_MIN(ts, (*tlp)->commit_ts);
if (ts != 0)
--ts;
return (ts);
}
/*
* lock_init --
* Initialize abstract lock that can use either pthread of wt reader-writer locks.
*/
void
lock_init(WT_SESSION *session, RWLOCK *lock)
{
testutil_assert(lock->lock_type == LOCK_NONE);
if (GV(WIREDTIGER_RWLOCK)) {
testutil_check(__wt_rwlock_init((WT_SESSION_IMPL *)session, &lock->l.wt));
lock->lock_type = LOCK_WT;
} else {
testutil_check(pthread_rwlock_init(&lock->l.pthread, NULL));
lock->lock_type = LOCK_PTHREAD;
}
}
/*
* lock_destroy --
* Destroy abstract lock.
*/
void
lock_destroy(WT_SESSION *session, RWLOCK *lock)
{
testutil_assert(LOCK_INITIALIZED(lock));
if (lock->lock_type == LOCK_WT)
__wt_rwlock_destroy((WT_SESSION_IMPL *)session, &lock->l.wt);
else
testutil_check(pthread_rwlock_destroy(&lock->l.pthread));
lock->lock_type = LOCK_NONE;
}
| 27.652079 | 100 | 0.630529 |
d6dc43996676603672050b14f13661e35a40dcda | 2,539 | h | C | orca/gporca/libgpopt/include/gpopt/operators/CScalarArrayRefIndexList.h | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 3 | 2017-12-10T16:41:21.000Z | 2020-07-08T12:59:12.000Z | orca/gporca/libgpopt/include/gpopt/operators/CScalarArrayRefIndexList.h | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | orca/gporca/libgpopt/include/gpopt/operators/CScalarArrayRefIndexList.h | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 4 | 2017-12-10T16:41:35.000Z | 2020-11-28T12:20:30.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2014 Pivotal, Inc.
//
// @filename:
// CScalarArrayRefIndexList.h
//
// @doc:
// Class for scalar arrayref index list
//
// @owner:
//
//
// @test:
//
//
//---------------------------------------------------------------------------
#ifndef GPOPT_CScalarArrayRefIndexList_H
#define GPOPT_CScalarArrayRefIndexList_H
#include "gpos/base.h"
#include "naucrates/md/IMDId.h"
#include "gpopt/operators/CScalar.h"
namespace gpopt
{
using namespace gpos;
using namespace gpmd;
//---------------------------------------------------------------------------
// @class:
// CScalarArrayRefIndexList
//
// @doc:
// Scalar arrayref index list
//
//---------------------------------------------------------------------------
class CScalarArrayRefIndexList : public CScalar
{
public:
enum EIndexListType
{
EiltLower, // lower index
EiltUpper, // upper index
EiltSentinel
};
private:
// index list type
EIndexListType m_eilt;
// private copy ctor
CScalarArrayRefIndexList(const CScalarArrayRefIndexList &);
public:
// ctor
CScalarArrayRefIndexList(IMemoryPool *pmp, EIndexListType eilt);
// ident accessors
virtual
EOperatorId Eopid() const
{
return EopScalarArrayRefIndexList;
}
// operator name
virtual
const CHAR *SzId() const
{
return "CScalarArrayRefIndexList";
}
// index list type
EIndexListType Eilt() const
{
return m_eilt;
}
// match function
virtual
BOOL FMatch(COperator *pop) const;
// sensitivity to order of inputs
virtual
BOOL FInputOrderSensitive() const
{
return true;
}
// return a copy of the operator with remapped columns
virtual
COperator *PopCopyWithRemappedColumns
(
IMemoryPool *, //pmp,
HMUlCr *, //phmulcr,
BOOL //fMustExist
)
{
return PopCopyDefault();
}
// type of expression's result
virtual
IMDId *PmdidType() const
{
GPOS_ASSERT(!"Invalid function call: CScalarArrayRefIndexList::PmdidType()");
return NULL;
}
// conversion function
static
CScalarArrayRefIndexList *PopConvert
(
COperator *pop
)
{
GPOS_ASSERT(NULL != pop);
GPOS_ASSERT(EopScalarArrayRefIndexList == pop->Eopid());
return dynamic_cast<CScalarArrayRefIndexList*>(pop);
}
}; // class CScalarArrayRefIndexList
}
#endif // !GPOPT_CScalarArrayRefIndexList_H
// EOF
| 18.947761 | 81 | 0.582907 |
8605f59e50acce85129c900972b7f3a55b31ffac | 4,548 | h | C | src/butil/recordio.h | wu-hanqing/incubator-brpc | 7de0d7eaf6fca2b73b9f6018eb1b9128ce0a8f21 | [
"Apache-2.0"
] | 5,379 | 2019-03-02T14:35:09.000Z | 2022-03-31T14:19:19.000Z | src/butil/recordio.h | RichPure/incubator-brpc | 846f7998799dd3c9103ef743fecc3c75d6dcb7ef | [
"BSL-1.0",
"Apache-2.0"
] | 921 | 2019-03-02T00:57:34.000Z | 2022-03-30T08:58:23.000Z | src/butil/recordio.h | RichPure/incubator-brpc | 846f7998799dd3c9103ef743fecc3c75d6dcb7ef | [
"BSL-1.0",
"Apache-2.0"
] | 1,641 | 2019-03-02T06:53:17.000Z | 2022-03-31T11:35:07.000Z | // recordio - A binary format to transport data from end to end.
//
// 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.
// Date: Thu Nov 22 13:57:56 CST 2012
#ifndef BUTIL_RECORDIO_H
#define BUTIL_RECORDIO_H
#include "butil/iobuf.h"
#include <memory>
namespace butil {
// 0-or-1 Payload + 0-or-multiple Metas.
// Payload and metas are often serialized form of protobuf messages. As a
// correspondence, the implementation is not optimized for very small blobs,
// which should be batched properly before inserting(e.g. using repeated
// field in pb)
class Record {
public:
struct NamedMeta {
std::string name;
std::shared_ptr<butil::IOBuf> data;
};
// Number of metas. Could be 0.
size_t MetaCount() const { return _metas.size(); }
// Get i-th Meta, out-of-range accesses may crash.
// This method is mainly for iterating all metas.
const NamedMeta& MetaAt(size_t i) const { return _metas[i]; }
// Get meta by |name|. NULL on not found.
const butil::IOBuf* Meta(const char* name) const;
// Returns a mutable pointer to the meta with |name|. If the meta does
// not exist, add it first.
// If |null_on_found| is true and meta with |name| is present, NULL is
// returned. This is useful for detecting uniqueness of meta names in some
// scenarios.
// NOTE: With the assumption that there won't be many metas, the impl.
// tests presence by scaning all fields, which may perform badly when metas
// are a lot.
butil::IOBuf* MutableMeta(const char* name, bool null_on_found = false);
butil::IOBuf* MutableMeta(const std::string& name, bool null_on_found = false);
// Remove meta with the name. The impl. may scan all fields.
// Returns true on erased, false on absent.
bool RemoveMeta(const butil::StringPiece& name);
// Get the payload. Empty by default.
const butil::IOBuf& Payload() const { return _payload; }
// Get a mutable pointer to the payload.
butil::IOBuf* MutablePayload() { return &_payload; }
// Clear payload and remove all meta.
void Clear();
// Serialized size of this record.
size_t ByteSize() const;
private:
butil::IOBuf _payload;
std::vector<NamedMeta> _metas;
};
// Parse records from the IReader, corrupted records will be skipped.
// Example:
// RecordReader rd(...);
// Record rec;
// while (rd.ReadNext(&rec)) {
// // Handle the rec
// }
// if (rd.last_error() != RecordReader::END_OF_READER) {
// LOG(FATAL) << "Critical error occurred";
// }
class RecordReader {
public:
// A special error code to mark end of input data.
static const int END_OF_READER = -1;
explicit RecordReader(IReader* reader);
// Returns true on success and |out| is overwritten by the record.
// False otherwise and last_error() is the error which is treated as permanent.
bool ReadNext(Record* out);
// 0 means no error.
// END_OF_READER means all data in the IReader are successfully consumed.
int last_error() const { return _last_error; }
// Total bytes consumed.
// NOTE: this value may not equal to read bytes from the IReader even if
// the reader runs out, due to parsing errors.
size_t offset() const { return _ncut; }
private:
bool CutUntilNextRecordCandidate();
int CutRecord(Record* rec);
private:
IReader* _reader;
IOPortal _portal;
IOBufCutter _cutter;
size_t _ncut;
int _last_error;
};
// Write records into the IWriter.
class RecordWriter {
public:
explicit RecordWriter(IWriter* writer);
// Serialize |record| into internal buffer and NOT flush into the IWriter.
int WriteWithoutFlush(const Record& record);
// Serialize |record| into internal buffer and flush into the IWriter.
int Write(const Record& record);
// Flush internal buffer into the IWriter.
// Returns 0 on success, error code otherwise.
int Flush();
private:
IOBuf _buf;
IWriter* _writer;
};
} // namespace butil
#endif // BUTIL_RECORDIO_H
| 31.583333 | 83 | 0.687555 |
ea9070f0c70dbf464137412712f712c0a1428e72 | 1,021 | h | C | FileEntry.h | wutipong/ZipPicViewWx | 1663ff327f6dba85cd661068133bcfdbae43a83e | [
"MIT"
] | 10 | 2015-11-29T11:10:06.000Z | 2020-03-07T10:17:19.000Z | FileEntry.h | wutipong/ZipPicViewWx | 1663ff327f6dba85cd661068133bcfdbae43a83e | [
"MIT"
] | null | null | null | FileEntry.h | wutipong/ZipPicViewWx | 1663ff327f6dba85cd661068133bcfdbae43a83e | [
"MIT"
] | 4 | 2015-11-29T13:43:36.000Z | 2018-11-19T05:31:33.000Z | #ifndef ZIPPICVIEW_FILEENTRY_H
#define ZIPPICVIEW_FILEENTRY_H
#include <wx/dir.h>
#include <wx/filename.h>
#include <wx/thread.h>
#include "Entry.h"
#include <functional>
#include <map>
class FileEntry : public Entry {
public:
typedef std::map<wxFileName, FileEntry *,
std::function<bool(const wxFileName &, const wxFileName &)>>
EntryMap;
FileEntry() = delete;
FileEntry(const FileEntry &) = delete;
virtual ~FileEntry();
static FileEntry *Create(const wxFileName &filename,
std::function<bool()> updateFnc);
virtual bool IsRoot() const override { return isRoot; }
private:
FileEntry(const wxFileName &filename, const bool &isRoot = false);
wxFileName filename;
wxMutex *mutex;
bool isRoot{false};
static FileEntry *AddChildrenFromPath(EntryMap &entryMap,
const wxFileName &filename);
protected:
virtual wxInputStream *GetInputStream() override;
};
#endif
| 25.525 | 80 | 0.648384 |
eaacb25195f44d841dd4faa5c8885f6a47bcfc7a | 344 | h | C | lib/PrintStatement.h | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | lib/PrintStatement.h | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | lib/PrintStatement.h | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | #ifndef PRINT_STATEMENT_INCLUDED
#define PRINT_STATEMENT_INCLUDED
#include "Statement.h"
#include <iostream>
#include "ProgramState.h"
class PrintStatement: public Statement
{
public:
PrintStatement(std::string variableName);
virtual void execute(ProgramState * state, std::ostream &outf);
private:
std::string m_variableName;
};
#endif
| 18.105263 | 64 | 0.787791 |
d854b7ec2d0e1f2095720e9c4c49e07736e6bcc7 | 1,928 | h | C | src/prod/src/Reliability/Failover/ra/Query.ReplicaDetailQueryHandler.h | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Reliability/Failover/ra/Query.ReplicaDetailQueryHandler.h | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Reliability/Failover/ra/Query.ReplicaDetailQueryHandler.h | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Reliability
{
namespace ReconfigurationAgentComponent
{
namespace Query
{
class ReplicaDetailQueryHandler : public IQueryHandler
{
public:
ReplicaDetailQueryHandler(
ReconfigurationAgent & ra,
QueryUtility queryUtility,
DeployedServiceReplicaUtility deployedServiceReplicaUtility);
ReplicaDetailQueryHandler(const ReplicaDetailQueryHandler & handler);
void ProcessQuery(
Federation::RequestReceiverContextUPtr && context,
ServiceModel::QueryArgumentMap const & queryArgs,
std::wstring const & activityId) override;
private:
static Common::ErrorCode ValidateAndGetParameters(
ServiceModel::QueryArgumentMap const & queryArgs,
__out std::wstring & serviceManifestName,
__out FailoverUnitId & failoverUnitId,
__out int64 & replicaId);
void OnCompleteSendResponse(
std::wstring const & activityId,
Federation::RequestReceiverContext & context,
Common::AsyncOperationSPtr const& operation,
ServiceModel::DeployedServiceReplicaQueryResult & replicaQueryResult);
private:
ReconfigurationAgent & ra_;
QueryUtility queryUtility_;
DeployedServiceReplicaUtility deployedServiceReplicaUtility_;
};
}
}
}
| 37.803922 | 98 | 0.554979 |
96941eda0008e33f93a19800e044c2cffe2dfb8b | 362 | c | C | ppidtest.c | HosseinMohammadii/operatingSystemProject | 7b5d18385d49ae3f7021f33df536de9dcdbc260a | [
"MIT-0"
] | 1 | 2020-04-03T13:08:12.000Z | 2020-04-03T13:08:12.000Z | ppidtest.c | HosseinMohammadii/operatingSystemProject | 7b5d18385d49ae3f7021f33df536de9dcdbc260a | [
"MIT-0"
] | null | null | null | ppidtest.c | HosseinMohammadii/operatingSystemProject | 7b5d18385d49ae3f7021f33df536de9dcdbc260a | [
"MIT-0"
] | null | null | null | #include "types.h"
#include "user.h"
int main(void){
int parent = getpid();
int child = fork();
if(child == 0){
printf(1, "child: parent=%d child=%d getpid()=%d getppid()=%d\n" , parent, child, getpid(), getppid());
}else{
wait();
printf(1, "parennt: parent=%d child=%d getpid()=%d getppid()=%d\n" , parent, child, getpid(), getppid());
}
exit();
}
| 24.133333 | 107 | 0.593923 |
96f897984b334d071a231c878618aa17c01d1f15 | 493 | c | C | case/test6.c | adavis10006/2012-Compiler | e7409280a34e7e409e8007c66a52590ab0c16a6e | [
"MIT"
] | null | null | null | case/test6.c | adavis10006/2012-Compiler | e7409280a34e7e409e8007c66a52590ab0c16a6e | [
"MIT"
] | null | null | null | case/test6.c | adavis10006/2012-Compiler | e7409280a34e7e409e8007c66a52590ab0c16a6e | [
"MIT"
] | null | null | null | int is_prime(int n)
{
int k, limit;
if (n == 2)
return 1;
if (n-(n/2 * 2)== 0)
return 0;
limit = n / 2;
for ( k = 3; k <= limit; k = k + 2)
{
if ((n - (n/k * k)) == 0)
return 0;
}
return 1;
}
int main()
{
int i, num1, num2;
write("enter a range, for example, 5<ENTER> 23<ENTER>:");
num1 = read();
num2 = read();
for (i =num1; i < num2; i = i + 1)
{
if (is_prime(i)) {
write (i);
write ("\n");
}
}
return 1;
}
| 13.324324 | 59 | 0.427992 |
f012b44ab42ce80dd2325b89da0fb1b55b1a7506 | 2,087 | h | C | library/libfunky/extra/ActionDownload.h | HaikuArchives/BePodder | 5df834d4408251ec73d5f3e994bd903637124a35 | [
"MIT"
] | 3 | 2018-06-21T03:58:59.000Z | 2022-03-27T10:11:25.000Z | library/libfunky/extra/ActionDownload.h | HaikuArchives/BePodder | 5df834d4408251ec73d5f3e994bd903637124a35 | [
"MIT"
] | 77 | 2015-04-29T02:40:04.000Z | 2021-12-18T00:34:46.000Z | library/libfunky/extra/ActionDownload.h | HaikuArchives/BePodder | 5df834d4408251ec73d5f3e994bd903637124a35 | [
"MIT"
] | 10 | 2015-02-23T18:12:25.000Z | 2022-03-11T06:28:02.000Z | #ifndef _ActionDownload_h_
#define _ActionDownload_h_
#include "ActionAsync.h"
#include <Entry.h>
#include <Looper.h>
#include "curl/curl.h"
class ActionDownload : public ActionAsync
{
public:
ActionDownload(BString URL, entry_ref dest,bool allowResume,BLooper *target = NULL ,uint32 msg = 0);
~ActionDownload(){};
status_t Perform(BMessage* errors);
BString GetDescription();
BString GetLocalPath();
//void SetLooper(BLooper *loop,uint32 msg){ fTarget=loop; fMsg=msg;};
//for compaatibility:
void SetExtraData(BString extra){
extraInfo.AddString("extra",extra);
}
void SetKey(BString key, BString data){
extraInfo.AddString(key.String(),data);
}
void SetRef(BString key, entry_ref *ref){
extraInfo.AddRef(key.String(),ref);
}
status_t GetRef(BString key, entry_ref* ref){
return extraInfo.FindRef(key.String(),ref);
}
BString GetKey(BString key){
BString data;
extraInfo.FindString(key.String(),&data);
return data;
}
void SetShouldStop(bool stop){ fShouldStop=stop;}
bool ShouldStop(){ return fShouldStop; }
enum Status {
ERROR_OPENFILE, // 0
ERROR_CURL_INIT, // 1
ERROR_PERFORMING, // 2
OK_CONNECTING, // 3
OK_PROGRESS, // 4
OK_DOWNLOADED // 5
};
private:
status_t openFile(BMessage*);
static void fillMessage(ActionDownload*,BMessage*);
static void sendProgressX(ActionDownload*,double max,double current);
//curl callbacks:
static size_t save_file ( void *ptr, size_t size, size_t nmemb, void *stream);
static int callback (void *clientp,double dltotal,double dlnow,double , double);
static int passwd (void *clientp, const char *prompt, char *buffer, int buflen);
CURL* curl;
BString fUrl; //from.
entry_ref fDest;
//BLooper* fTarget; //target progess
//uint32 fMsg;
BMessage extraInfo;
bool fShouldStop;
BFile* file;
double resuming;
bool fAllowResume;
BString fFileType;
};
#endif
| 23.988506 | 104 | 0.655966 |
6cf156307ff4268cfebdbdc6f5f51c80f3f08b1e | 1,894 | h | C | Engine/script/executingscript.h | scottchiefbaker/ags | de5201c1ae541f84168eb365ff61ca013d1d62f3 | [
"Artistic-2.0"
] | null | null | null | Engine/script/executingscript.h | scottchiefbaker/ags | de5201c1ae541f84168eb365ff61ca013d1d62f3 | [
"Artistic-2.0"
] | null | null | null | Engine/script/executingscript.h | scottchiefbaker/ags | de5201c1ae541f84168eb365ff61ca013d1d62f3 | [
"Artistic-2.0"
] | null | null | null | //=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
//
//
//=============================================================================
#ifndef __AGS_EE_SCRIPT__EXECUTINGSCRIPT_H
#define __AGS_EE_SCRIPT__EXECUTINGSCRIPT_H
#include "script/cc_instance.h"
enum PostScriptAction {
ePSANewRoom,
ePSAInvScreen,
ePSARestoreGame,
ePSARestoreGameDialog,
ePSARunAGSGame,
ePSARunDialog,
ePSARestartGame,
ePSASaveGame,
ePSASaveGameDialog
};
#define MAX_QUEUED_SCRIPTS 4
#define MAX_QUEUED_ACTIONS 5
#define MAX_FUNCTION_NAME_LEN 60
struct ExecutingScript {
ccInstance *inst;
PostScriptAction postScriptActions[MAX_QUEUED_ACTIONS];
const char *postScriptActionNames[MAX_QUEUED_ACTIONS];
char postScriptSaveSlotDescription[MAX_QUEUED_ACTIONS][100];
int postScriptActionData[MAX_QUEUED_ACTIONS];
int numPostScriptActions;
char script_run_another[MAX_QUEUED_SCRIPTS][MAX_FUNCTION_NAME_LEN+1];
RuntimeScriptValue run_another_p1[MAX_QUEUED_SCRIPTS];
RuntimeScriptValue run_another_p2[MAX_QUEUED_SCRIPTS];
int numanother;
char forked;
int queue_action(PostScriptAction act, int data, const char *aname);
void run_another (char *namm, RuntimeScriptValue &p1, RuntimeScriptValue &p2);
void init();
ExecutingScript();
};
#endif // __AGS_EE_SCRIPT__EXECUTINGSCRIPT_H
| 32.655172 | 82 | 0.670539 |
9b499d54e1d1a9280b5e89abae70c6cea43434f9 | 21,235 | h | C | src/RadiusAttribute.h | webfolderio/ace-radius | f5cdd51df046c9bedd3f073121922eb3c0e59f8c | [
"BSD-2-Clause"
] | null | null | null | src/RadiusAttribute.h | webfolderio/ace-radius | f5cdd51df046c9bedd3f073121922eb3c0e59f8c | [
"BSD-2-Clause"
] | null | null | null | src/RadiusAttribute.h | webfolderio/ace-radius | f5cdd51df046c9bedd3f073121922eb3c0e59f8c | [
"BSD-2-Clause"
] | null | null | null | /*
* This source file is part of the ace-radius library. This code was
* written by Alex Agranov in 2004-2009, and is covered by the BSD open source
* license. Refer to the accompanying documentation for details on usage and
* license.
*/
#ifndef _RADIUSATTRIBUTE_H__
#define _RADIUSATTRIBUTE_H__
#include "Radius.h"
// definition of Attribute Types from RFC2865
#define D_ATTR_USER_NAME 1
#define D_ATTR_USER_PASSWORD 2
#define D_ATTR_CHAP_PASSWORD 3
#define D_ATTR_NAS_IP_ADDRESS 4
#define D_ATTR_NAS_PORT 5
#define D_ATTR_SERVICE_TYPE 6
#define D_ATTR_FRAMED_PROTOCOL 7
#define D_ATTR_FRAMED_IP_ADDRESS 8
#define D_ATTR_FRAMED_IP_NETMASK 9
#define D_ATTR_FRAMED_ROUTING 10
#define D_ATTR_FILTER_ID 11
#define D_ATTR_FRAMED_MTU 12
#define D_ATTR_FRAMED_COMPRESSION 13
#define D_ATTR_LOGIN_IP_HOST 14
#define D_ATTR_LOGIN_SERVICE 15
#define D_ATTR_LOGIN_TCP_PORT 16
#define D_ATTR_OLD_PASSWORD 17
#define D_ATTR_REPLY_MESSAGE 18
#define D_ATTR_CALLBACK_NUMBER 19
#define D_ATTR_CALLBACK_ID 20
#define D_ATTR_FRAMED_ROUTE 22
#define D_ATTR_FRAMED_IPX_NETWORK 23
#define D_ATTR_STATE 24
#define D_ATTR_CLASS 25
#define D_ATTR_VENDOR_SPECIFIC 26
#define D_ATTR_SESSION_TIMEOUT 27
#define D_ATTR_IDLE_TIMEOUT 28
#define D_ATTR_TERMINATION_ACTION 29
#define D_ATTR_CALLED_STATION_ID 30
#define D_ATTR_CALLING_STATION_ID 31
#define D_ATTR_NAS_IDENTIFIER 32
#define D_ATTR_PROXY_STATE 33
#define D_ATTR_LOGIN_LAT_SERVICE 34
#define D_ATTR_LOGIN_LAT_NODE 35
#define D_ATTR_LOGIN_LAT_GROUP 36
#define D_ATTR_FRAMED_APPLETALK_LINK 37
#define D_ATTR_FRAMED_APPLETALK_NETWORK 38
#define D_ATTR_FRAMED_APPLETALK_ZONE 39
// types 40-59 are reserved for accounting - RFC2866
#define D_ATTR_CHAP_CHALLENGE 60
#define D_ATTR_NAS_PORT_TYPE 61
#define D_ATTR_PORT_LIMIT 62
#define D_ATTR_LOGIN_LAT_PROMPT 63
// definition of Attribute Types from RFC2866
#define D_ATTR_ACCT_STATUS_TYPE 40
#define D_ATTR_ACCT_DELAY_TIME 41
#define D_ATTR_ACCT_INPUT_OCTETS 42
#define D_ATTR_ACCT_OUTPUT_OCTETS 43
#define D_ATTR_ACCT_SESSION_ID 44
#define D_ATTR_ACCT_AUTHENTIC 45
#define D_ATTR_ACCT_SESSION_TIME 46
#define D_ATTR_ACCT_INPUT_PACKETS 47
#define D_ATTR_ACCT_OUTPUT_PACKETS 48
#define D_ATTR_ACCT_TERMINATE_CAUSE 49
#define D_ATTR_ACCT_MULTI_SESSION_ID 50
#define D_ATTR_ACCT_LINK_COUNT 51
#define D_ATTR_MAX_KNOWN_TYPE 63
// definition of Acct-Status-Type attribute values from RFC2866
#define D_ACCT_STATUS_START 1
#define D_ACCT_STATUS_STOP 2
#define D_ACCT_STATUS_INTERIM_UPDATE 3
#define D_ACCT_STATUS_ON 7
#define D_ACCT_STATUS_OFF 8
// max length of User-Password attribute
#define D_USER_PASSWORD_MAX_LENGTH 128
class RadiusPacket;
class RadiusSecret;
/**
* @class RadiusAttribute
*
* @brief Implementation of RADIUS attribute
*
* This class does not keep any data - instead it provides methods to
* properly access and encode data at specific offset inside the RADIUS
* packet raw data buffer.
*
* This implementation minimizes the footprint of RADIUS stack and
* does not require dynamic memory allocations. It's also very fast
* (at least in the typical RADIUS applications) since the data is
* immediately encoded inside the packet.
*
*/
class RadiusAttribute
{
public:
/// Constructor
RadiusAttribute();
/// Destructor
~RadiusAttribute();
/// Dump attribute in readable text format to the STDOUT
void dump();
/// Init attribute
/**
* Set associated RADIUS packet and offset in it - this will effectively
* init the attribute. A special usage is to pass zero p_offset - this
* will mark attribute "invalid".
*
* @param[in] p_packet - RADIUS packet
* @param[in] p_offset - offset inside the packet's raw data
*/
void init(RadiusPacket * p_packet, uint16_t p_offset);
/// Get packet that this attribute belongs to
RadiusPacket * getPacket(void);
/// Get attribute's offset inside the packet
uint16_t getOffset(void);
///////////////////////////////////////////////////////////////////////
/// Get attribute type
/**
* @return attribute type
*/
unsigned char getType(void);
/// Set attribute type
/**
* Set attribute type
*
* @param[in] p_code - attribute code
* @return RC_SUCCESS or RC_FAIL
*/
int setType(unsigned char p_type);
/// Get textual description of attribute type
const char * getTypeDescription(void);
/// Get attribute length
/**
* Note that returned value is length of the attribute data block
* as encoded in raw RADIUS packet (in other words it's simply
* a value of Length octet in attribute data).
* You must take into account specific attribute type in order to
* calculate the "real data" length.
*
* @return attribute's length
*/
unsigned char getLength(void);
/// Set attribute length
/**
* Set attribute's length - refer to getLength() description for details.
*
* @param[in] p_length - attribute's length
* @return RC_SUCCESS or RC_FAIL
*/
int setLength(unsigned char p_length);
/// Attribute is valid?
/**
* @return TRUE or FALSE
*/
int isValid(void);
// ------------------------------------------------------------
// get- and set- methods - access data stored in the attribute
// ===========================
// Regular attributes
// ===========================
/// Get value of the numeric attribute
/**
* @return value of numeric attribute in host order format
*/
uint32_t getNumber(void);
/// Set value of the numeric attribute
/**
* @param[in] p_value - numeric value in host order format
* @return RC_SUCCESS if attribute is successfully encode; RC_FAIL otherwise
*/
int setNumber(uint32_t p_value);
/// Get value of the IP address attribute
/**
* @return value of IP address attribute
*/
struct in_addr getIPAddress(void);
/// Set value of the IP address attribute
/**
* @param[in] p_value - IP address
* @return RC_SUCCESS if attribute is successfully encode; RC_FAIL otherwise
*/
int setIPAddress(struct in_addr p_value);
/// Get value of the string attribute
/**
* Note that string data may contain both readable characters
* and non-readable binary data. In any case string will not be
* null-terminated, hence you should use returned p_length value
* to properly operate on it.
*
* @param[out] p_data - pointer to the beginning of string data
* @param[out] p_length - string length
* @return RC_SUCCESS or RC_FAIL
*/
int getString(const char * & p_data, uint16_t & p_length);
/// Set value of the string attribute
/**
* Note that string data may contain both readable characters
* and non-readable binary data and in any case encoded string
* should not be null-terminated.
*
* You have two options:
* - provide a "raw" buffer and its length
* - provide NULL-terminated string and leave the p_length
* parameter unspecified (in this case strlen() will be
* used to determine encoded string length)
*
* @param[in] p_data - pointer to the beginning of string data
* @param[in] p_length - string length (optional)
* @return RC_SUCCESS or RC_FAIL
*/
int setString(const char * p_data, uint16_t p_length = 0);
// ===========================
// Vendor-Specific attribute
// ===========================
/// Get vendor ID of Vendor-Specific attribute
/**
* @return vendor ID numeric value in host order format
*/
uint32_t getVendorId(void);
/// Set vendor ID of Vendor-Specific attribute
/**
* @param[in] p_vendorId - vendor ID numeric value in host order format
* @return RC_SUCCESS or RC_FAIL
*/
int setVendorId(uint32_t p_vendorId);
/// Get "raw" string data of Vendor-Specific attribute
/**
* "Raw" string data of Vendor-Specific attribute typically
* contains Vendor Type, Vendor Length and Attribute-specific
* data. Therefore in most cases you should use getVendorType(),
* getVendorLength() and getVendorNumber() instead of this
* method.
*
* Note that string data may contain both readable characters and non-readable
* binary data. In any case string will not be null-terminated,
* hence yous should use returned p_length value to properly
* operate on it.
*
* @param[out] p_data - pointer to the beginning of string data
* @param[out] p_length - string length
* @return RC_SUCCESS or RC_FAIL
*/
int getVendorRawString(const char * & p_data, uint16_t & p_length);
/// Set "raw" string data of Vendor-Specific attribute
/**
* "Raw" string data of Vendor-Specific attribute typically
* contains Vendor Type, Vendor Length and Attribute-specific
* data. Therefore in most cases you should use setVendorType(),
* setVendorLength() and setVendorNumber() instead of this
* method.
*
* Note that string data may contain both readable characters
* and non-readable binary data and in any case encoded string
* should not be null-terminated.
*
* You have two options:
* - provide a "raw" buffer and its length
* - provide NULL-terminated string and leave the p_length
* parameter unspecified (in this case strlen() will be
* used to determine encoded string length)
*
* @param[in] p_data - pointer to the beginning of string data
* @param[in] p_length - string length (optional)
* @return RC_SUCCESS or RC_FAIL
*/
int setVendorRawString(const char * p_data, uint16_t p_length = 0);
/// Get vendor type of Vendor-Specific attribute
/**
* @return vendor type
*/
unsigned char getVendorType();
/// Set vendor type of Vendor-Specific attribute
/**
* @param[in] p_value - vendor type value
* @return RC_SUCCESS or RC_FAIL
*/
int setVendorType(unsigned char p_value);
/// Get vendor length of Vendor-Specific attribute
/**
* @return vendor length
*/
unsigned char getVendorLength();
/// Set vendor length of Vendor-Specific attribute
/**
* @param[in] p_length - vendor length value
* @return RC_SUCCESS or RC_FAIL
*/
int setVendorLength(unsigned char p_length);
/// Get value of the numeric Vendor-Specific attribute
/**
* @return value of numeric attribute in host order format
*/
uint32_t getVendorNumber();
/// Set value of the numeric Vendor-Specific attribute
/**
* @param[in] p_value - numeric value in host order format
* @return RC_SUCCESS if attribute is successfully encode; RC_FAIL otherwise
*/
int setVendorNumber(uint32_t p_value);
/// Get value of the IP address Vendor-Specific attribute
/**
* @return value of IP address attribute
*/
struct in_addr getVendorIPAddress();
/// Set value of the IP address Vendor-Specific attribute
/**
* @param[in] p_value - IP address
* @return RC_SUCCESS if attribute is successfully encode; RC_FAIL otherwise
*/
int setVendorIPAddress(struct in_addr p_address);
/// Get value of the string Vendor-Specific attribute
/**
* Note that string data may contain both readable characters
* and non-readable binary data. In any case string will not be
* null-terminated, hence you should use returned p_length value
* to properly operate on it.
*
* @param[out] p_data - pointer to the beginning of string data
* @param[out] p_length - string length
* @return RC_SUCCESS or RC_FAIL
*/
int getVendorString(const char * & p_data, uint16_t & p_length);
/// Set value of the string Vendor-Specific attribute
/**
* Note that string data may contain both readable characters and non-readable
* binary data. In any case string should not be null-terminated.
*
* Note that string data may contain both readable characters
* and non-readable binary data and in any case encoded string
* should not be null-terminated.
*
* You have two options:
* - provide a "raw" buffer and its length
* - provide NULL-terminated string and leave the p_length
* parameter unspecified (in this case strlen() will be
* used to determine encoded string length)
*
* @param[in] p_data - pointer to the beginning of string data
* @param[in] p_length - string length (optional)
* @return RC_SUCCESS or RC_FAIL
*/
int setVendorString(const char * p_data, uint16_t p_length = 0);
// ===========================
// User-Password attribute
// ===========================
/// Get string data of User-Password attribute
/**
* Password is decoded from the packet using secret key and presented in
* it's "original" form.
*
* Note that password may contain both readable characters and
* non-readable binary data. In any case string will not be
* null-terminated, hence you should use returned p_length value
* to properly operate on it.
*
* @param[in] p_data - pointer to local buffer allocated by application
* where the decoded password will be stored
* @param[out] p_length - string length
* @param[in] p_secret - secret key (if NULL, stack's secret key is taken)
* @return RC_SUCCESS or RC_FAIL
*
* IMPORTANT: allocate the buffer of size D_USER_PASSWORD_MAX_LENGTH
* for storing decoded password data and pass it as
* p_data
*/
int getUserPassword(char * p_data, uint16_t & p_length,
RadiusSecret * p_secret = NULL);
/// Set string data of User-Password attribute
/**
* Password is encoded into the packet using secret key.
* The actual encoding is performed when packet is transmitted
* to the network (using the secret key of current connection) -
* therefore if you "dump" packet beforehand you won't see
* any data encoded.
*
* Note that the password may contain both readable characters
* and non-readable binary data. In any case encoded string
* should not be null-terminated.
*
* You have two options:
* - provide a "raw" buffer and its length
* - provide NULL-terminated string and leave the p_length
* parameter unspecified (in this case strlen() will be
* used to determine encoded password length)
*
* @param[in] p_data - pointer to the beginning of string data
* @param[in] p_length - string length
* @return RC_SUCCESS or RC_FAIL
*/
int setUserPassword(const char * p_data, uint16_t p_length = 0);
// Encode raw data of User-Password attribute
/*
* We need this function in order to re-encode User-Password attribute with new secret key
* when packet is retransmitted through new connection; application should not use this API.
*/
int encodeUserPassword(const unsigned char * p_data, uint16_t p_length);
// ===========================
// Old-Password attribute
// ===========================
/// Get string data of Old-Password attribute
/**
* Password is decoded from the packet using secret key and presented in
* it's "original" form.
*
* Note that string data may contain both readable characters
* and non-readable binary data. In any case string will not be
* null-terminated, hence you should use returned p_length value
* to properly operate on it.
*
* @param[in] p_data - pointer to local buffer allocated by application
* where the decoded password will be stored
* @param[out] p_length - string length
* @param[in] p_secret - secret key (if NULL, stack's secret key is taken)
* @return RC_SUCCESS or RC_FAIL
*
* IMPORTANT: allocate the buffer of size D_USER_PASSWORD_MAX_LENGTH
* for storing decoded password data and pass it as
* p_data
*/
int getOldPassword(char * p_data, uint16_t & p_length,
RadiusSecret * p_secret = NULL);
/// Set string data of Old-Password attribute
/**
* Password is encoded into the packet using secret key.
* The actual encoding is performed when packet is transmitted
* to the network (using the secret key of current connection) -
* therefore if you "dump" packet beforehand you won't see
* any data encoded.
*
* The application must add User-Password attribute prior to
* adding Old-Password, since encrypted User-Password data is
* used instead of shared authenticator for encoding
*
* Note that the password may contain both readable characters
* and non-readable binary data. In any case encoded string
* should not be null-terminated.
*
* You have two options:
* - provide a "raw" buffer and its length
* - provide NULL-terminated string and leave the p_length
* parameter unspecified (in this case strlen() will be
* used to determine encoded password length)
*
* @param[in] p_data - pointer to the beginning of string data
* @param[in] p_length - string length
* @return RC_SUCCESS or RC_FAIL
*/
int setOldPassword(const char * p_data, uint16_t p_length = 0);
// Encode raw data of Old-Password attribute
/*
* We need this function in order to re-encode User-Password attribute with new secret key
* when packet is retransmitted through new connection; application should not use this API.
*/
int encodeOldPassword(const unsigned char * p_data, uint16_t p_length);
// ===========================
// CHAP-Password attribute
// ===========================
/// Get CHAP identifier of CHAP-Password attribute
/**
* @return CHAP identifier
*/
unsigned char getChapIdentifier(void);
/// Set vendor ID of CHAP-Password attribute
/**
* @param[in] p_chapIdentifier - CHAP identifier value
* @return RC_SUCCESS or RC_FAIL
*/
int setChapIdentifier(unsigned char p_chapId);
/// Get string data of CHAP-Password attribute
/**
* Note that string data may contain both readable characters
* and non-readable binary data. In any case string will not be
* null-terminated, hence you should use returned p_length value
* to properly operate on it.
*
* @param[out] p_data - pointer to the beginning of string data
* @param[out] p_length - string length
* @return RC_SUCCESS or RC_FAIL
*/
int getChapString(const char * & p_data, uint16_t & p_length);
/// Set string data of CHAP-Password attribute
/**
* Note that string data may contain both readable characters and non-readable
* binary data. In any case string should not be null-terminated.
*
* You have two options:
* - provide a "raw" buffer and its length
* - provide NULL-terminated string and leave the p_length
* parameter unspecified (in this case strlen() will be
* used to determine encoded password length)
*
* @param[in] p_data - pointer to the beginning of string data
* @param[in] p_length - string length
* @return RC_SUCCESS or RC_FAIL
*/
int setChapString(const char * p_data, uint16_t p_length = 0);
private:
// Get pointer to the attribute raw data
unsigned char * getRawData(void);
// Types of attribute data
enum AttributeFormat_e
{
E_ATTR_FORMAT_INTEGER,
E_ATTR_FORMAT_IP_ADDRESS,
E_ATTR_FORMAT_STRING,
E_ATTR_FORMAT_VENDOR_SPECIFIC,
E_ATTR_FORMAT_USER_PASSWORD,
E_ATTR_FORMAT_CHAP_PASSWORD
};
// Dump attribute in readable text format to the STDOUT
/**
* @param[in] p_format - attribute format;
*/
void dump(AttributeFormat_e p_format);
//////////////////////////////////////////////////////////////////////
// Pointer to the RADIUS packet that this attribute belongs to
RadiusPacket * m_packet;
// Offset of the attribute inside the RADIUS packet
uint16_t m_offset;
};
#endif // _RADIUSATTRIBUTE_H__
| 34.472403 | 96 | 0.6421 |
7aecb40149962bdaa2a38bc2bb34def2e99f8f5c | 1,087 | h | C | lst1-amiga/sources/process.h | LambdaCalculus37/little-smalltalk | d7157339e23a3e75ee3763dccf6d8d1b5c32e42d | [
"MIT"
] | 2 | 2021-07-07T11:59:23.000Z | 2022-01-17T22:18:14.000Z | lst1-amiga/sources/process.h | LambdaCalculus37/little-smalltalk | d7157339e23a3e75ee3763dccf6d8d1b5c32e42d | [
"MIT"
] | null | null | null | lst1-amiga/sources/process.h | LambdaCalculus37/little-smalltalk | d7157339e23a3e75ee3763dccf6d8d1b5c32e42d | [
"MIT"
] | null | null | null | /*
Little Smalltalk
process definitions
dennis a. vadner and michael t. benhase, 11/84
*/
/*
the process
interp = pointer to the head of the process'
interpreter chain
p_state = current state of the process
next = link to the next process in the active list
prev = link to the previous process in the active list
*/
struct process_struct {
int p_ref_count;
int p_size;
interpreter *interp;
int p_state;
struct process_struct *next;
struct process_struct *prev;
} ;
typedef struct process_struct process;
extern int atomcnt; /* atomic action flag */
extern process *runningProcess; /* currently running process */
extern process *cr_process(); /* create a new process */
extern int set_state(); /* set the state on a process */
/* process states */
# define ACTIVE 0
# define SUSPENDED 1
# define READY ~SUSPENDED
# define BLOCKED 2
# define UNBLOCKED ~BLOCKED
# define TERMINATED 4
# define CUR_STATE 10
# define terminate_process(aProcess) {set_state(aProcess, TERMINATED); if (aProcess == runningProcess) atomcnt = 0;}
| 21.74 | 118 | 0.713891 |
bb7906f572da4a8d913faf2fa98f9007ea2033b8 | 1,673 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/InitCodeLoginReqPbPB.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/InitCodeLoginReqPbPB.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/InitCodeLoginReqPbPB.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 "APDPBGeneratedMessage.h"
@class NSArray, NSString;
@interface InitCodeLoginReqPbPB : APDPBGeneratedMessage
{
}
+ (CDStruct_af61540b *)_fieldInfos;
// Remaining properties
@property(retain, nonatomic) NSString *devKeySet; // @dynamic devKeySet;
@property(retain, nonatomic) NSString *envJson; // @dynamic envJson;
@property(retain, nonatomic) NSArray *externParams; // @dynamic externParams;
@property(readonly) _Bool hasDevKeySet; // @dynamic hasDevKeySet;
@property(readonly) _Bool hasEnvJson; // @dynamic hasEnvJson;
@property(readonly) _Bool hasLoginId; // @dynamic hasLoginId;
@property(readonly) _Bool hasProductId; // @dynamic hasProductId;
@property(readonly) _Bool hasProductVersion; // @dynamic hasProductVersion;
@property(readonly) _Bool hasSdkVersion; // @dynamic hasSdkVersion;
@property(readonly) _Bool hasTid; // @dynamic hasTid;
@property(readonly) _Bool hasUmidToken; // @dynamic hasUmidToken;
@property(readonly) _Bool hasUtdid; // @dynamic hasUtdid;
@property(retain, nonatomic) NSString *loginId; // @dynamic loginId;
@property(retain, nonatomic) NSString *productId; // @dynamic productId;
@property(retain, nonatomic) NSString *productVersion; // @dynamic productVersion;
@property(retain, nonatomic) NSString *sdkVersion; // @dynamic sdkVersion;
@property(retain, nonatomic) NSString *tid; // @dynamic tid;
@property(retain, nonatomic) NSString *umidToken; // @dynamic umidToken;
@property(retain, nonatomic) NSString *utdid; // @dynamic utdid;
@end
| 41.825 | 90 | 0.758518 |
635ad14a9a495e93e0b735f16cccd1aad0398de6 | 4,590 | h | C | source/multiplayer/prGameSession.h | pmac1965/proteus | 53f366be90739f456c64f09cbec565a0e97b2629 | [
"Apache-2.0"
] | 1 | 2019-01-27T14:47:10.000Z | 2019-01-27T14:47:10.000Z | source/multiplayer/prGameSession.h | pmac1965/proteus | 53f366be90739f456c64f09cbec565a0e97b2629 | [
"Apache-2.0"
] | null | null | null | source/multiplayer/prGameSession.h | pmac1965/proteus | 53f366be90739f456c64f09cbec565a0e97b2629 | [
"Apache-2.0"
] | null | null | null | // File: prGameSession.h
/**
* Copyright 2014 Paul Michael McNab
*
* 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 "../core/prTypes.h"
#include "prGameSessionProvider.h"
// Game Pession Providers
enum
{
GSP_ANDROID_BT, // Android bluetooth
GSP_IOS_GAMESESSION, // IOS game session
};
// Game Session Status
enum
{
GSS_CONNECT_BEGIN = 0x64210001, // Connecting has begun
GSS_CONNECT_FAILED = 0x64210002, // Connecting failed
GSS_CONNECT_OK = 0x64210003, // Connecting succeeded
GSS_TURNED_ON = 0x64210004, // Bluetooth needs to be turned on. You must restart connect
GSS_DISCOVERY = 0x64210005, // Bluetooth is discovering devices. You must restart connect
GSS_PEER_ID = 0x64210006, // Send the peer ID. Allows you to decide things, like who goes first
};
// Class: prGameSessionPacket
// This class is incomplete as yet - TO BE COMPLETED
class prGameSessionPacket
{
public:
u32 size;
u32 hash;
u32 type;
u32 index;
};
// Class: prGameSessionReceiver
// This class should be derived by any class wishing to know the status
// of the current game session
class prGameSessionReceiver
{
public:
// Method: GameSessionStatus
// Receives the current status of a game session
virtual void GameSessionStatus(u32 status) = 0;
// Method: PacketReceiver
// Receive a data packet from the other device
virtual void PacketReceiver(prGameSessionPacket &packet) = 0;
};
// Class: prGameSession
// Cross platform interface for multiplayer connectivity using bluetooth, or
// other types of close range communication
class prGameSession
{
public:
// Method: prGameSession
// Ctor
prGameSession();
// Method: ~prGameSession
// Dtor
~prGameSession();
// Method: Initialise
// Initialises the game session
//
// Parameters:
// pProvider - A pointer to the provider
//
// Notes:
// This determines if the technology is available, etc
//
// Call when required as this may bring up a dialog dependant on the platform
//
// This class will clean up the provider
void Initialise(prGameSessionReceiver *pReceiver, prGameSessionProvider *pProvider);
// Method: Update
// Updates the game session
bool Update();
// Method: IsAvailable
// Is the technology available? For example does a device have bluetooth
PRBOOL IsAvailable() const { return mIsAvailable; }
// Method: IsEnabled
// Is the technology turned on?
PRBOOL IsEnabled() const { return mIsEnabled; }
// Method: ReceiveMessage
// Used by the OS to pass messages back to the game
//
// Notes:
// The messages are of type. Game Session Status
//
// Some of which are platform specific
void ReceiveMessage(s32 msg);
// Method: SendPacket
// Send a data packet to the other device
void SendPacket(prGameSessionPacket &packet);
// Method: ReceivePacket
// Receive a data packet from the other device
void ReceivePacket(prGameSessionPacket &packet);
// Method: IsServer
// Determine if we are the client or the server
PRBOOL IsServer();
// Method: GetProvider
// Gets the current provider
prGameSessionProvider *GetProvider() const { return mpProvider; }
// Method: Disconnect
// Disconnects a game session
void Disconnect();
private:
prGameSessionProvider *mpProvider; // The provider
prGameSessionReceiver *mpGameSessionReceiver; // Notification class.
PRBOOL mInitialised; // Has game session been initialised.
PRBOOL mIsAvailable; // Is the technology available? For example does a device have bluetooth
PRBOOL mIsEnabled; // Is the technology turned on?
};
| 30.197368 | 124 | 0.653159 |
5b70388be60bd3562c4fdcfe7519da8205aeadfd | 537 | h | C | BSBDJ/BSBDJ/Classes/Other/Category/UIBarButtonItem+Item.h | NickChenHao/BSBDJ | c020d5eaa354dad3d16368798a53fea6daae0ef7 | [
"Apache-2.0"
] | null | null | null | BSBDJ/BSBDJ/Classes/Other/Category/UIBarButtonItem+Item.h | NickChenHao/BSBDJ | c020d5eaa354dad3d16368798a53fea6daae0ef7 | [
"Apache-2.0"
] | null | null | null | BSBDJ/BSBDJ/Classes/Other/Category/UIBarButtonItem+Item.h | NickChenHao/BSBDJ | c020d5eaa354dad3d16368798a53fea6daae0ef7 | [
"Apache-2.0"
] | null | null | null | //
// UIBarButtonItem+Item.h
// BuDeJie
//
// Copyright © 2016年 小码哥. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIBarButtonItem (Item)
/**
* 设置导航条左右Item的View 为按钮时 可设置选中/高亮状态
*
* @param image 正常状态下
* @param selImage 选中状态下
* @param highImage 高亮状态下
* @param target 监听者
* @param action 监听方法
*
* @return 返回一个UIBarButtonItem
*/
+ (UIBarButtonItem *)itemWithImage:(UIImage *)image selImage:(UIImage *)selImage highImage:(UIImage *)highImage target:(id)target action:(SEL)action;
@end
| 21.48 | 149 | 0.672253 |
5b7c207d27be034c582858dea4b6acfd59d0997a | 11,393 | h | C | System/Library/PrivateFrameworks/SearchFoundation.framework/SearchFoundation.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | 4 | 2019-08-27T18:03:47.000Z | 2021-09-18T06:29:00.000Z | System/Library/PrivateFrameworks/SearchFoundation.framework/SearchFoundation.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/SearchFoundation.framework/SearchFoundation.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | #import <SearchFoundation/SFUserReportFeedback.h>
#import <SearchFoundation/SFDescriptionCardSection.h>
#import <SearchFoundation/SFUserReportRequest.h>
#import <SearchFoundation/SFLocalImage.h>
#import <SearchFoundation/SFFormattedText.h>
#import <SearchFoundation/SFCardSectionValue.h>
#import <SearchFoundation/SFAppLink.h>
#import <SearchFoundation/SFRichText.h>
#import <SearchFoundation/SFCardSection.h>
#import <SearchFoundation/SFImageOption.h>
#import <SearchFoundation/SFKeyValueDataCardSection.h>
#import <SearchFoundation/SFMediaInfoCardSection.h>
#import <SearchFoundation/SFMapsDetailedRowCardSection.h>
#import <SearchFoundation/SFActivityIndicatorCardSection.h>
#import <SearchFoundation/SFNowPlayingCardSection.h>
#import <SearchFoundation/SFURLImage.h>
#import <SearchFoundation/SFKeyValueTuple.h>
#import <SearchFoundation/SFMediaItem.h>
#import <SearchFoundation/SFUserActivityInfo.h>
#import <SearchFoundation/SFTitleCardSection.h>
#import <SearchFoundation/SFMapCardSectionEngagementFeedback.h>
#import <SearchFoundation/SFLookupHintRelevancyFeedback.h>
#import <SearchFoundation/SFWatchListCardSection.h>
#import <SearchFoundation/SFMediaPlayerCardSection.h>
#import <SearchFoundation/SFHorizontalButtonCardSection.h>
#import <SearchFoundation/SFText.h>
#import <SearchFoundation/SFSearchSuggestion.h>
#import <SearchFoundation/SFMediaDetail.h>
#import <SearchFoundation/SFAppIconImage.h>
#import <SearchFoundation/SFResultsReceivedAfterTimeoutFeedback.h>
#import <SearchFoundation/SFTableRowCardSection.h>
#import <SearchFoundation/SFButtonCardSection.h>
#import <SearchFoundation/SFWatchListItem.h>
#import <SearchFoundation/SFContactImage.h>
#import <SearchFoundation/SFDynamicURLImageResource.h>
#import <SearchFoundation/SFRowCardSection.h>
#import <SearchFoundation/SFAppLinkCardSection.h>
#import <SearchFoundation/_SFPBAbstractCommand.h>
#import <SearchFoundation/_SFPBActionItem.h>
#import <SearchFoundation/_SFPBActivityIndicatorCardSection.h>
#import <SearchFoundation/_SFPBAirport.h>
#import <SearchFoundation/_SFPBApiResults.h>
#import <SearchFoundation/_SFPBAppIconImage.h>
#import <SearchFoundation/_SFPBAppLink.h>
#import <SearchFoundation/_SFPBAppLinkCardSection.h>
#import <SearchFoundation/_SFPBAudioPlaybackCardSection.h>
#import <SearchFoundation/_SFPBButton.h>
#import <SearchFoundation/_SFPBButtonCardSection.h>
#import <SearchFoundation/_SFPBCard.h>
#import <SearchFoundation/_SFPBCardSection.h>
#import <SearchFoundation/_SFPBCardSectionValue.h>
#import <SearchFoundation/_SFPBColor.h>
#import <SearchFoundation/_SFPBCommandValue.h>
#import <SearchFoundation/_SFPBContactImage.h>
#import <SearchFoundation/_SFPBDate.h>
#import <SearchFoundation/_SFPBDescriptionCardSection.h>
#import <SearchFoundation/_SFPBDetailedRowCardSection.h>
#import <SearchFoundation/_SFPBDynamicURLImageResource.h>
#import <SearchFoundation/_SFPBFlight.h>
#import <SearchFoundation/_SFPBFlightCardSection.h>
#import <SearchFoundation/_SFPBFlightLeg.h>
#import <SearchFoundation/_SFPBFormattedText.h>
#import <SearchFoundation/_SFPBGraphicalFloat.h>
#import <SearchFoundation/_SFPBHorizontalButtonCardSection.h>
#import <SearchFoundation/_SFPBHorizontalScrollCardSection.h>
#import <SearchFoundation/_SFPBImage.h>
#import <SearchFoundation/_SFPBImageOption.h>
#import <SearchFoundation/_SFPBImagesCardSection.h>
#import <SearchFoundation/_SFPBKeyValueDataCardSection.h>
#import <SearchFoundation/_SFPBKeyValueTuple.h>
#import <SearchFoundation/_SFPBLatLng.h>
#import <SearchFoundation/_SFPBLocalImage.h>
#import <SearchFoundation/_SFPBMapCardSection.h>
#import <SearchFoundation/_SFPBMapRegion.h>
#import <SearchFoundation/_SFPBMapsDetailedRowCardSection.h>
#import <SearchFoundation/_SFPBMediaArtworkImage.h>
#import <SearchFoundation/_SFPBMediaDetail.h>
#import <SearchFoundation/_SFPBMediaInfoCardSection.h>
#import <SearchFoundation/_SFPBMediaItem.h>
#import <SearchFoundation/_SFPBMediaOffer.h>
#import <SearchFoundation/_SFPBMediaPlayerCardSection.h>
#import <SearchFoundation/_SFPBMediaRemoteControlCardSection.h>
#import <SearchFoundation/_SFPBMessageCardSection.h>
#import <SearchFoundation/_SFPBMetaInfoCardSection.h>
#import <SearchFoundation/_SFPBMonogramImage.h>
#import <SearchFoundation/_SFPBMoreResults.h>
#import <SearchFoundation/_SFPBNamedProtobufMessage.h>
#import <SearchFoundation/_SFPBNowPlayingCardSection.h>
#import <SearchFoundation/_SFPBPin.h>
#import <SearchFoundation/_SFPBPointSize.h>
#import <SearchFoundation/_SFPBProduct.h>
#import <SearchFoundation/_SFPBProductAvailability.h>
#import <SearchFoundation/_SFPBProductCardSection.h>
#import <SearchFoundation/_SFPBProductInventory.h>
#import <SearchFoundation/_SFPBProductInventoryResult.h>
#import <SearchFoundation/_SFPBPunchout.h>
#import <SearchFoundation/_SFPBReferentialCommand.h>
#import <SearchFoundation/_SFPBRichText.h>
#import <SearchFoundation/_SFPBRichTitleCardSection.h>
#import <SearchFoundation/_SFPBRowCardSection.h>
#import <SearchFoundation/_SFPBScoreboardCardSection.h>
#import <SearchFoundation/_SFPBSearchSuggestion.h>
#import <SearchFoundation/_SFPBSectionHeaderCardSection.h>
#import <SearchFoundation/_SFPBSelectableGridCardSection.h>
#import <SearchFoundation/_SFPBSocialMediaPostCardSection.h>
#import <SearchFoundation/_SFPBSportsTeam.h>
#import <SearchFoundation/_SFPBStockChartCardSection.h>
#import <SearchFoundation/_SFPBStringDictionary.h>
#import <SearchFoundation/_SFPBSuggestionCardSection.h>
#import <SearchFoundation/_SFPBTableAlignmentSchema.h>
#import <SearchFoundation/_SFPBTableColumnAlignment.h>
#import <SearchFoundation/_SFPBTableHeaderRowCardSection.h>
#import <SearchFoundation/_SFPBTableRowCardSection.h>
#import <SearchFoundation/_SFPBText.h>
#import <SearchFoundation/_SFPBTextColumn.h>
#import <SearchFoundation/_SFPBTextColumnSection.h>
#import <SearchFoundation/_SFPBTextColumnsCardSection.h>
#import <SearchFoundation/_SFPBTimeZone.h>
#import <SearchFoundation/_SFPBTitleCardSection.h>
#import <SearchFoundation/_SFPBTitleSubtitleTuple.h>
#import <SearchFoundation/_SFPBTrack.h>
#import <SearchFoundation/_SFPBTrackListCardSection.h>
#import <SearchFoundation/_SFPBURL.h>
#import <SearchFoundation/_SFPBURLImage.h>
#import <SearchFoundation/_SFPBUserActivityData.h>
#import <SearchFoundation/_SFPBUserActivityInfo.h>
#import <SearchFoundation/_SFPBUserReportRequest.h>
#import <SearchFoundation/_SFPBVerticalLayoutCardSection.h>
#import <SearchFoundation/_SFPBWatchListCardSection.h>
#import <SearchFoundation/_SFPBWatchListItem.h>
#import <SearchFoundation/_SFPBWebCardSection.h>
#import <SearchFoundation/SFSectionRankingFeedback.h>
#import <SearchFoundation/SFClearInputFeedback.h>
#import <SearchFoundation/SFCard.h>
#import <SearchFoundation/SFCustomFeedback.h>
#import <SearchFoundation/SFProductInventory.h>
#import <SearchFoundation/SFProductAvailability.h>
#import <SearchFoundation/SFMediaOffer.h>
#import <SearchFoundation/SFReferentialCommand.h>
#import <SearchFoundation/SFAbstractCommand.h>
#import <SearchFoundation/SFTrackListCardSection.h>
#import <SearchFoundation/SFScoreboardCardSection.h>
#import <SearchFoundation/SFRichTitleCardSection.h>
#import <SearchFoundation/SFDetailedRowCardSection.h>
#import <SearchFoundation/SFTableHeaderRowCardSection.h>
#import <SearchFoundation/SFSearchViewAppearFeedback.h>
#import <SearchFoundation/SFSearchViewDisappearFeedback.h>
#import <SearchFoundation/SFMediaRemoteControlCardSection.h>
#import <SearchFoundation/SFResultFeedback.h>
#import <SearchFoundation/SFResultEngagementFeedback.h>
#import <SearchFoundation/SFResultGradingFeedback.h>
#import <SearchFoundation/SFPunchout.h>
#import <SearchFoundation/SFActionItem.h>
#import <SearchFoundation/SFSuggestionEngagementFeedback.h>
#import <SearchFoundation/WeakListener.h>
#import <SearchFoundation/SFResultSection.h>
#import <SearchFoundation/SFMessageCardSection.h>
#import <SearchFoundation/SFWebCardSection.h>
#import <SearchFoundation/SFPBCardSectionValueTranslator.h>
#import <SearchFoundation/SFCardViewDisappearFeedback.h>
#import <SearchFoundation/SFCardViewAppearFeedback.h>
#import <SearchFoundation/SFMediaArtworkImage.h>
#import <SearchFoundation/SFColor.h>
#import <SearchFoundation/SFResultRankingFeedback.h>
#import <SearchFoundation/SFMonogramImage.h>
#import <SearchFoundation/SFTableColumnAlignment.h>
#import <SearchFoundation/SFMapCardSection.h>
#import <SearchFoundation/SFVisibleSuggestionsFeedback.h>
#import <SearchFoundation/SFProduct.h>
#import <SearchFoundation/SFVisibleResultsFeedback.h>
#import <SearchFoundation/SFSectionEngagementFeedback.h>
#import <SearchFoundation/WeakLoader.h>
#import <SearchFoundation/ImageFileLoader.h>
#import <SearchFoundation/SFVisibleSectionHeaderFeedback.h>
#import <SearchFoundation/SFImagesCardSection.h>
#import <SearchFoundation/SFTitleSubtitleTuple.h>
#import <SearchFoundation/SFRankingFeedback.h>
#import <SearchFoundation/SFLatLng.h>
#import <SearchFoundation/SFAirport.h>
#import <SearchFoundation/SFClientTimingFeedback.h>
#import <SearchFoundation/SFCommandValue.h>
#import <SearchFoundation/SFApiResults.h>
#import <SearchFoundation/SFDidGoToSearchFeedback.h>
#import <SearchFoundation/SFCardSectionFeedback.h>
#import <SearchFoundation/SFCardSectionEngagementFeedback.h>
#import <SearchFoundation/SFMapsCardSectionEngagementFeedback.h>
#import <SearchFoundation/SFStoreCardSectionEngagementFeedback.h>
#import <SearchFoundation/SFTextColumn.h>
#import <SearchFoundation/SFSuggestionCardSection.h>
#import <SearchFoundation/SFTableAlignmentSchema.h>
#import <SearchFoundation/SFMetaInfoCardSection.h>
#import <SearchFoundation/SFStockChartCardSection.h>
#import <SearchFoundation/SFProductInventoryResult.h>
#import <SearchFoundation/SFSearchResult.h>
#import <SearchFoundation/SFImage.h>
#import <SearchFoundation/SFLateSectionsAppendedFeedback.h>
#import <SearchFoundation/SFFlight.h>
#import <SearchFoundation/SFMoreResults.h>
#import <SearchFoundation/SFSocialMediaPostCardSection.h>
#import <SearchFoundation/SFTextColumnsCardSection.h>
#import <SearchFoundation/SFFeedback.h>
#import <SearchFoundation/SFNullCardSection.h>
#import <SearchFoundation/SFErrorFeedback.h>
#import <SearchFoundation/SFPin.h>
#import <SearchFoundation/SFStartSearchFeedback.h>
#import <SearchFoundation/SFEndSearchFeedback.h>
#import <SearchFoundation/SFStartNetworkSearchFeedback.h>
#import <SearchFoundation/SFEndNetworkSearchFeedback.h>
#import <SearchFoundation/SFStartLocalSearchFeedback.h>
#import <SearchFoundation/SFEndLocalSearchFeedback.h>
#import <SearchFoundation/SFSelectableGridCardSection.h>
#import <SearchFoundation/SFNamedProtobufMessage.h>
#import <SearchFoundation/SFProductCardSection.h>
#import <SearchFoundation/SFButton.h>
#import <SearchFoundation/SFCalendarImage.h>
#import <SearchFoundation/SFFlightLeg.h>
#import <SearchFoundation/SFTrack.h>
#import <SearchFoundation/SFHorizontalScrollCardSection.h>
#import <SearchFoundation/SFMapRegion.h>
#import <SearchFoundation/SFDidGoToSiteFeedback.h>
#import <SearchFoundation/SFFlightCardSection.h>
#import <SearchFoundation/SFTextColumnSection.h>
#import <SearchFoundation/SFPBSerialization.h>
#import <SearchFoundation/SFSectionHeaderCardSection.h>
#import <SearchFoundation/SFCustom.h>
#import <SearchFoundation/SFSportsTeam.h>
#import <SearchFoundation/SFAudioPlaybackCardSection.h>
#import <SearchFoundation/SFUserActivityData.h>
#import <SearchFoundation/SFVerticalLayoutCardSection.h>
| 49.534783 | 66 | 0.8593 |
8d4014eae89c941f45b4f41907bcf188fd8a7405 | 17,956 | c | C | MPlayer-1.3.0/ffmpeg/libavfilter/vaf_spectrumsynth.c | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 41 | 2015-04-06T09:15:47.000Z | 2022-02-06T19:02:09.000Z | MPlayer-1.3.0/ffmpeg/libavfilter/vaf_spectrumsynth.c | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 15 | 2016-08-26T15:13:03.000Z | 2022-01-05T22:55:11.000Z | MPlayer-1.3.0/ffmpeg/libavfilter/vaf_spectrumsynth.c | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 24 | 2015-08-08T10:15:19.000Z | 2021-07-15T22:04:51.000Z | /*
* Copyright (c) 2016 Paul B Mahol
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* SpectrumSynth filter
* @todo support float pixel format
*/
#include "libavcodec/avfft.h"
#include "libavutil/avassert.h"
#include "libavutil/channel_layout.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "avfilter.h"
#include "formats.h"
#include "audio.h"
#include "video.h"
#include "internal.h"
#include "window_func.h"
enum MagnitudeScale { LINEAR, LOG, NB_SCALES };
enum SlideMode { REPLACE, SCROLL, FULLFRAME, RSCROLL, NB_SLIDES };
enum Orientation { VERTICAL, HORIZONTAL, NB_ORIENTATIONS };
typedef struct SpectrumSynthContext {
const AVClass *class;
int sample_rate;
int channels;
int scale;
int sliding;
int win_func;
float overlap;
int orientation;
AVFrame *magnitude, *phase;
FFTContext *fft; ///< Fast Fourier Transform context
int fft_bits; ///< number of bits (FFT window size = 1<<fft_bits)
FFTComplex **fft_data; ///< bins holder for each (displayed) channels
int win_size;
int size;
int nb_freq;
int hop_size;
int start, end;
int xpos;
int xend;
int64_t pts;
float factor;
AVFrame *buffer;
float *window_func_lut; ///< Window function LUT
} SpectrumSynthContext;
#define OFFSET(x) offsetof(SpectrumSynthContext, x)
#define A AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
#define V AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
static const AVOption spectrumsynth_options[] = {
{ "sample_rate", "set sample rate", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 44100}, 15, INT_MAX, A },
{ "channels", "set channels", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 1}, 1, 8, A },
{ "scale", "set input amplitude scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64 = LOG}, 0, NB_SCALES-1, V, "scale" },
{ "lin", "linear", 0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, V, "scale" },
{ "log", "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG}, 0, 0, V, "scale" },
{ "slide", "set input sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = FULLFRAME}, 0, NB_SLIDES-1, V, "slide" },
{ "replace", "consume old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, V, "slide" },
{ "scroll", "consume only most right column", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, V, "slide" },
{ "fullframe", "consume full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, V, "slide" },
{ "rscroll", "consume only most left column", 0, AV_OPT_TYPE_CONST, {.i64=RSCROLL}, 0, 0, V, "slide" },
{ "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_WFUNC-1, A, "win_func" },
{ "rect", "Rectangular", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT}, 0, 0, A, "win_func" },
{ "bartlett", "Bartlett", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, A, "win_func" },
{ "hann", "Hann", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING}, 0, 0, A, "win_func" },
{ "hanning", "Hanning", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING}, 0, 0, A, "win_func" },
{ "hamming", "Hamming", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING}, 0, 0, A, "win_func" },
{ "sine", "Sine", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE}, 0, 0, A, "win_func" },
{ "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 1, A },
{ "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, V, "orientation" },
{ "vertical", NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL}, 0, 0, V, "orientation" },
{ "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, V, "orientation" },
{ NULL }
};
AVFILTER_DEFINE_CLASS(spectrumsynth);
static int query_formats(AVFilterContext *ctx)
{
SpectrumSynthContext *s = ctx->priv;
AVFilterFormats *formats = NULL;
AVFilterChannelLayouts *layout = NULL;
AVFilterLink *magnitude = ctx->inputs[0];
AVFilterLink *phase = ctx->inputs[1];
AVFilterLink *outlink = ctx->outputs[0];
static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE };
static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P,
AV_PIX_FMT_YUV444P16, AV_PIX_FMT_NONE };
int ret, sample_rates[] = { 48000, -1 };
formats = ff_make_format_list(sample_fmts);
if ((ret = ff_formats_ref (formats, &outlink->in_formats )) < 0 ||
(ret = ff_add_channel_layout (&layout, FF_COUNT2LAYOUT(s->channels))) < 0 ||
(ret = ff_channel_layouts_ref (layout , &outlink->in_channel_layouts)) < 0)
return ret;
sample_rates[0] = s->sample_rate;
formats = ff_make_format_list(sample_rates);
if (!formats)
return AVERROR(ENOMEM);
if ((ret = ff_formats_ref(formats, &outlink->in_samplerates)) < 0)
return ret;
formats = ff_make_format_list(pix_fmts);
if (!formats)
return AVERROR(ENOMEM);
if ((ret = ff_formats_ref(formats, &magnitude->out_formats)) < 0)
return ret;
formats = ff_make_format_list(pix_fmts);
if (!formats)
return AVERROR(ENOMEM);
if ((ret = ff_formats_ref(formats, &phase->out_formats)) < 0)
return ret;
return 0;
}
static int config_output(AVFilterLink *outlink)
{
AVFilterContext *ctx = outlink->src;
SpectrumSynthContext *s = ctx->priv;
int width = ctx->inputs[0]->w;
int height = ctx->inputs[0]->h;
AVRational time_base = ctx->inputs[0]->time_base;
AVRational frame_rate = ctx->inputs[0]->frame_rate;
int i, ch, fft_bits;
float factor, overlap;
outlink->sample_rate = s->sample_rate;
outlink->time_base = (AVRational){1, s->sample_rate};
if (width != ctx->inputs[1]->w ||
height != ctx->inputs[1]->h) {
av_log(ctx, AV_LOG_ERROR,
"Magnitude and Phase sizes differ (%dx%d vs %dx%d).\n",
width, height,
ctx->inputs[1]->w, ctx->inputs[1]->h);
return AVERROR_INVALIDDATA;
} else if (av_cmp_q(time_base, ctx->inputs[1]->time_base) != 0) {
av_log(ctx, AV_LOG_ERROR,
"Magnitude and Phase time bases differ (%d/%d vs %d/%d).\n",
time_base.num, time_base.den,
ctx->inputs[1]->time_base.num,
ctx->inputs[1]->time_base.den);
return AVERROR_INVALIDDATA;
} else if (av_cmp_q(frame_rate, ctx->inputs[1]->frame_rate) != 0) {
av_log(ctx, AV_LOG_ERROR,
"Magnitude and Phase framerates differ (%d/%d vs %d/%d).\n",
frame_rate.num, frame_rate.den,
ctx->inputs[1]->frame_rate.num,
ctx->inputs[1]->frame_rate.den);
return AVERROR_INVALIDDATA;
}
s->size = s->orientation == VERTICAL ? height / s->channels : width / s->channels;
s->xend = s->orientation == VERTICAL ? width : height;
for (fft_bits = 1; 1 << fft_bits < 2 * s->size; fft_bits++);
s->win_size = 1 << fft_bits;
s->nb_freq = 1 << (fft_bits - 1);
s->fft = av_fft_init(fft_bits, 1);
if (!s->fft) {
av_log(ctx, AV_LOG_ERROR, "Unable to create FFT context. "
"The window size might be too high.\n");
return AVERROR(EINVAL);
}
s->fft_data = av_calloc(s->channels, sizeof(*s->fft_data));
if (!s->fft_data)
return AVERROR(ENOMEM);
for (ch = 0; ch < s->channels; ch++) {
s->fft_data[ch] = av_calloc(s->win_size, sizeof(**s->fft_data));
if (!s->fft_data[ch])
return AVERROR(ENOMEM);
}
s->buffer = ff_get_audio_buffer(outlink, s->win_size * 2);
if (!s->buffer)
return AVERROR(ENOMEM);
/* pre-calc windowing function */
s->window_func_lut = av_realloc_f(s->window_func_lut, s->win_size,
sizeof(*s->window_func_lut));
if (!s->window_func_lut)
return AVERROR(ENOMEM);
ff_generate_window_func(s->window_func_lut, s->win_size, s->win_func, &overlap);
if (s->overlap == 1)
s->overlap = overlap;
s->hop_size = (1 - s->overlap) * s->win_size;
for (factor = 0, i = 0; i < s->win_size; i++) {
factor += s->window_func_lut[i] * s->window_func_lut[i];
}
s->factor = (factor / s->win_size) / FFMAX(1 / (1 - s->overlap) - 1, 1);
return 0;
}
static int request_frame(AVFilterLink *outlink)
{
AVFilterContext *ctx = outlink->src;
SpectrumSynthContext *s = ctx->priv;
int ret;
if (!s->magnitude) {
ret = ff_request_frame(ctx->inputs[0]);
if (ret < 0)
return ret;
}
if (!s->phase) {
ret = ff_request_frame(ctx->inputs[1]);
if (ret < 0)
return ret;
}
return 0;
}
static void read16_fft_bin(SpectrumSynthContext *s,
int x, int y, int f, int ch)
{
const int m_linesize = s->magnitude->linesize[0];
const int p_linesize = s->phase->linesize[0];
const uint16_t *m = (uint16_t *)(s->magnitude->data[0] + y * m_linesize);
const uint16_t *p = (uint16_t *)(s->phase->data[0] + y * p_linesize);
float magnitude, phase;
switch (s->scale) {
case LINEAR:
magnitude = m[x] / (double)UINT16_MAX;
break;
case LOG:
magnitude = ff_exp10(((m[x] / (double)UINT16_MAX) - 1.) * 6.);
break;
default:
av_assert0(0);
}
phase = ((p[x] / (double)UINT16_MAX) * 2. - 1.) * M_PI;
s->fft_data[ch][f].re = magnitude * cos(phase);
s->fft_data[ch][f].im = magnitude * sin(phase);
}
static void read8_fft_bin(SpectrumSynthContext *s,
int x, int y, int f, int ch)
{
const int m_linesize = s->magnitude->linesize[0];
const int p_linesize = s->phase->linesize[0];
const uint8_t *m = (uint8_t *)(s->magnitude->data[0] + y * m_linesize);
const uint8_t *p = (uint8_t *)(s->phase->data[0] + y * p_linesize);
float magnitude, phase;
switch (s->scale) {
case LINEAR:
magnitude = m[x] / (double)UINT8_MAX;
break;
case LOG:
magnitude = ff_exp10(((m[x] / (double)UINT8_MAX) - 1.) * 6.);
break;
default:
av_assert0(0);
}
phase = ((p[x] / (double)UINT8_MAX) * 2. - 1.) * M_PI;
s->fft_data[ch][f].re = magnitude * cos(phase);
s->fft_data[ch][f].im = magnitude * sin(phase);
}
static void read_fft_data(AVFilterContext *ctx, int x, int h, int ch)
{
SpectrumSynthContext *s = ctx->priv;
AVFilterLink *inlink = ctx->inputs[0];
int start = h * (s->channels - ch) - 1;
int end = h * (s->channels - ch - 1);
int y, f;
switch (s->orientation) {
case VERTICAL:
switch (inlink->format) {
case AV_PIX_FMT_YUV444P16:
case AV_PIX_FMT_GRAY16:
for (y = start, f = 0; y >= end; y--, f++) {
read16_fft_bin(s, x, y, f, ch);
}
break;
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_GRAY8:
for (y = start, f = 0; y >= end; y--, f++) {
read8_fft_bin(s, x, y, f, ch);
}
break;
}
break;
case HORIZONTAL:
switch (inlink->format) {
case AV_PIX_FMT_YUV444P16:
case AV_PIX_FMT_GRAY16:
for (y = end, f = 0; y <= start; y++, f++) {
read16_fft_bin(s, y, x, f, ch);
}
break;
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_GRAY8:
for (y = end, f = 0; y <= start; y++, f++) {
read8_fft_bin(s, y, x, f, ch);
}
break;
}
break;
}
}
static void synth_window(AVFilterContext *ctx, int x)
{
SpectrumSynthContext *s = ctx->priv;
const int h = s->size;
int nb = s->win_size;
int y, f, ch;
for (ch = 0; ch < s->channels; ch++) {
read_fft_data(ctx, x, h, ch);
for (y = h; y <= s->nb_freq; y++) {
s->fft_data[ch][y].re = 0;
s->fft_data[ch][y].im = 0;
}
for (y = s->nb_freq + 1, f = s->nb_freq - 1; y < nb; y++, f--) {
s->fft_data[ch][y].re = s->fft_data[ch][f].re;
s->fft_data[ch][y].im = -s->fft_data[ch][f].im;
}
av_fft_permute(s->fft, s->fft_data[ch]);
av_fft_calc(s->fft, s->fft_data[ch]);
}
}
static int try_push_frame(AVFilterContext *ctx, int x)
{
SpectrumSynthContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
const float factor = s->factor;
int ch, n, i, ret;
int start, end;
AVFrame *out;
synth_window(ctx, x);
for (ch = 0; ch < s->channels; ch++) {
float *buf = (float *)s->buffer->extended_data[ch];
int j, k;
start = s->start;
end = s->end;
k = end;
for (i = 0, j = start; j < k && i < s->win_size; i++, j++) {
buf[j] += s->fft_data[ch][i].re;
}
for (; i < s->win_size; i++, j++) {
buf[j] = s->fft_data[ch][i].re;
}
start += s->hop_size;
end = j;
if (start >= s->win_size) {
start -= s->win_size;
end -= s->win_size;
if (ch == s->channels - 1) {
float *dst;
int c;
out = ff_get_audio_buffer(outlink, s->win_size);
if (!out) {
av_frame_free(&s->magnitude);
av_frame_free(&s->phase);
return AVERROR(ENOMEM);
}
out->pts = s->pts;
s->pts += s->win_size;
for (c = 0; c < s->channels; c++) {
dst = (float *)out->extended_data[c];
buf = (float *)s->buffer->extended_data[c];
for (n = 0; n < s->win_size; n++) {
dst[n] = buf[n] * factor;
}
memmove(buf, buf + s->win_size, s->win_size * 4);
}
ret = ff_filter_frame(outlink, out);
}
}
}
s->start = start;
s->end = end;
return 0;
}
static int try_push_frames(AVFilterContext *ctx)
{
SpectrumSynthContext *s = ctx->priv;
int ret, x;
if (!(s->magnitude && s->phase))
return 0;
switch (s->sliding) {
case REPLACE:
ret = try_push_frame(ctx, s->xpos);
s->xpos++;
if (s->xpos >= s->xend)
s->xpos = 0;
break;
case SCROLL:
s->xpos = s->xend - 1;
ret = try_push_frame(ctx, s->xpos);
break;
case RSCROLL:
s->xpos = 0;
ret = try_push_frame(ctx, s->xpos);
break;
case FULLFRAME:
for (x = 0; x < s->xend; x++) {
ret = try_push_frame(ctx, x);
if (ret < 0)
break;
}
break;
default:
av_assert0(0);
}
av_frame_free(&s->magnitude);
av_frame_free(&s->phase);
return ret;
}
static int filter_frame_magnitude(AVFilterLink *inlink, AVFrame *magnitude)
{
AVFilterContext *ctx = inlink->dst;
SpectrumSynthContext *s = ctx->priv;
s->magnitude = magnitude;
return try_push_frames(ctx);
}
static int filter_frame_phase(AVFilterLink *inlink, AVFrame *phase)
{
AVFilterContext *ctx = inlink->dst;
SpectrumSynthContext *s = ctx->priv;
s->phase = phase;
return try_push_frames(ctx);
}
static av_cold void uninit(AVFilterContext *ctx)
{
SpectrumSynthContext *s = ctx->priv;
int i;
av_frame_free(&s->magnitude);
av_frame_free(&s->phase);
av_frame_free(&s->buffer);
av_fft_end(s->fft);
if (s->fft_data) {
for (i = 0; i < s->channels; i++)
av_freep(&s->fft_data[i]);
}
av_freep(&s->fft_data);
av_freep(&s->window_func_lut);
}
static const AVFilterPad spectrumsynth_inputs[] = {
{
.name = "magnitude",
.type = AVMEDIA_TYPE_VIDEO,
.filter_frame = filter_frame_magnitude,
.needs_fifo = 1,
},
{
.name = "phase",
.type = AVMEDIA_TYPE_VIDEO,
.filter_frame = filter_frame_phase,
.needs_fifo = 1,
},
{ NULL }
};
static const AVFilterPad spectrumsynth_outputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_AUDIO,
.config_props = config_output,
.request_frame = request_frame,
},
{ NULL }
};
AVFilter ff_vaf_spectrumsynth = {
.name = "spectrumsynth",
.description = NULL_IF_CONFIG_SMALL("Convert input spectrum videos to audio output."),
.uninit = uninit,
.query_formats = query_formats,
.priv_size = sizeof(SpectrumSynthContext),
.inputs = spectrumsynth_inputs,
.outputs = spectrumsynth_outputs,
.priv_class = &spectrumsynth_class,
};
| 33.190388 | 136 | 0.565716 |
e4b5c70eb8266f3c3b17cdef1c2f89eae814cadd | 4,871 | c | C | angrylion-rdp-plus/src/core/n64video/vi/video.c | dmrlawson/parallel-rdp | f18e00728bb45e3a769ab7ad3b9064359ef82209 | [
"MIT"
] | 7 | 2020-07-25T11:44:39.000Z | 2021-01-29T13:21:31.000Z | angrylion-rdp-plus/src/core/n64video/vi/video.c | dmrlawson/parallel-rdp | f18e00728bb45e3a769ab7ad3b9064359ef82209 | [
"MIT"
] | null | null | null | angrylion-rdp-plus/src/core/n64video/vi/video.c | dmrlawson/parallel-rdp | f18e00728bb45e3a769ab7ad3b9064359ef82209 | [
"MIT"
] | 1 | 2021-03-22T16:15:30.000Z | 2021-03-22T16:15:30.000Z | #ifdef N64VIDEO_C
static STRICTINLINE void video_max_optimized(uint32_t* pixels, uint32_t* penumin, uint32_t* penumax, int numofels)
{
int i;
int posmax = 0, posmin = 0;
uint32_t curpenmax = pixels[0], curpenmin = pixels[0];
uint32_t max, min;
for (i = 1; i < numofels; i++)
{
if (pixels[i] > pixels[posmax])
{
curpenmax = pixels[posmax];
posmax = i;
}
else if (pixels[i] < pixels[posmin])
{
curpenmin = pixels[posmin];
posmin = i;
}
}
max = pixels[posmax];
min = pixels[posmin];
if (curpenmax != max)
{
for (i = posmax + 1; i < numofels; i++)
{
if (pixels[i] > curpenmax)
curpenmax = pixels[i];
}
}
if (curpenmin != min)
{
for (i = posmin + 1; i < numofels; i++)
{
if (pixels[i] < curpenmin)
curpenmin = pixels[i];
}
}
*penumax = curpenmax;
*penumin = curpenmin;
}
static STRICTINLINE void video_filter16(int* endr, int* endg, int* endb, uint32_t fboffset, uint32_t num, uint32_t hres, uint32_t centercvg, uint32_t fetchbugstate)
{
int i;
uint32_t penumaxr, penumaxg, penumaxb, penuminr, penuming, penuminb;
uint16_t pix;
uint32_t numoffull = 1;
uint8_t hidval;
uint32_t r, g, b;
uint32_t backr[7], backg[7], backb[7];
r = *endr;
g = *endg;
b = *endb;
backr[0] = r;
backg[0] = g;
backb[0] = b;
uint32_t idx = (fboffset >> 1) + num;
uint32_t toleft = idx - 2;
uint32_t toright = idx + 2;
uint32_t leftup, rightup, leftdown, rightdown;
leftup = idx - hres - 1;
rightup = idx - hres + 1;
if (fetchbugstate != 1)
{
leftdown = idx + hres - 1;
rightdown = idx + hres + 1;
}
else
{
leftdown = toleft;
rightdown = toright;
}
const uint32_t dirs[] = {leftup, rightup, toleft, toright, leftdown, rightdown};
for (i = 0; i < 6; i++)
{
rdram_read_pair16(&pix, &hidval, dirs[i]);
if (hidval == 3 && (pix & 1))
{
backr[numoffull] = RGBA16_R(pix);
backg[numoffull] = RGBA16_G(pix);
backb[numoffull] = RGBA16_B(pix);
numoffull++;
}
}
uint32_t colr, colg, colb;
video_max_optimized(backr, &penuminr, &penumaxr, numoffull);
video_max_optimized(backg, &penuming, &penumaxg, numoffull);
video_max_optimized(backb, &penuminb, &penumaxb, numoffull);
uint32_t coeff = 7 - centercvg;
colr = penuminr + penumaxr - (r << 1);
colg = penuming + penumaxg - (g << 1);
colb = penuminb + penumaxb - (b << 1);
colr = (((colr * coeff) + 4) >> 3) + r;
colg = (((colg * coeff) + 4) >> 3) + g;
colb = (((colb * coeff) + 4) >> 3) + b;
*endr = colr & 0xff;
*endg = colg & 0xff;
*endb = colb & 0xff;
}
static STRICTINLINE void video_filter32(int* endr, int* endg, int* endb, uint32_t fboffset, uint32_t num, uint32_t hres, uint32_t centercvg, uint32_t fetchbugstate)
{
int i;
uint32_t penumaxr, penumaxg, penumaxb, penuminr, penuming, penuminb;
uint32_t numoffull = 1;
uint32_t pix = 0, pixcvg = 0;
uint32_t r, g, b;
uint32_t backr[7], backg[7], backb[7];
r = *endr;
g = *endg;
b = *endb;
backr[0] = r;
backg[0] = g;
backb[0] = b;
uint32_t idx = (fboffset >> 2) + num;
uint32_t toleft = idx - 2;
uint32_t toright = idx + 2;
uint32_t leftup, rightup, leftdown, rightdown;
leftup = idx - hres - 1;
rightup = idx - hres + 1;
if (fetchbugstate != 1)
{
leftdown = idx + hres - 1;
rightdown = idx + hres + 1;
}
else
{
leftdown = toleft;
rightdown = toright;
}
const uint32_t dirs[] = {leftup, rightup, toleft, toright, leftdown, rightdown};
for (i = 0; i < 6; i++)
{
pix = rdram_read_idx32(dirs[i]);
pixcvg = (pix >> 5) & 7;
if (pixcvg == 7)
{
backr[numoffull] = (pix >> 24) & 0xff;
backg[numoffull] = (pix >> 16) & 0xff;
backb[numoffull] = (pix >> 8) & 0xff;
numoffull++;
}
}
uint32_t colr, colg, colb;
video_max_optimized(backr, &penuminr, &penumaxr, numoffull);
video_max_optimized(backg, &penuming, &penumaxg, numoffull);
video_max_optimized(backb, &penuminb, &penumaxb, numoffull);
uint32_t coeff = 7 - centercvg;
colr = penuminr + penumaxr - (r << 1);
colg = penuming + penumaxg - (g << 1);
colb = penuminb + penumaxb - (b << 1);
colr = (((colr * coeff) + 4) >> 3) + r;
colg = (((colg * coeff) + 4) >> 3) + g;
colb = (((colb * coeff) + 4) >> 3) + b;
*endr = colr & 0xff;
*endg = colg & 0xff;
*endb = colb & 0xff;
}
#endif // N64VIDEO_C
| 25.238342 | 164 | 0.537056 |
e28289d9ffd6a69611fd88e38c7a0d9767fa5614 | 1,280 | h | C | PGDatePicker/PGEnumeration.h | h912545437/PGDatePicker | 5a348f73a6b2fc90c7c9e7c44c9e511527db2e04 | [
"MIT"
] | null | null | null | PGDatePicker/PGEnumeration.h | h912545437/PGDatePicker | 5a348f73a6b2fc90c7c9e7c44c9e511527db2e04 | [
"MIT"
] | null | null | null | PGDatePicker/PGEnumeration.h | h912545437/PGDatePicker | 5a348f73a6b2fc90c7c9e7c44c9e511527db2e04 | [
"MIT"
] | null | null | null | //
// PGEnumeration.h
//
// Created by piggybear on 2018/1/7.
// Copyright © 2018年 piggybear. All rights reserved.
//
#ifndef PGEnumeration_h
#define PGEnumeration_h
typedef NS_ENUM(NSInteger, PGDatePickerMode) {
PGDatePickerModeYear, //年
PGDatePickerModeYearAndMonth, //年月
PGDatePickerModeDate, //年月日
PGDatePickerModeDateHour, //年月日时
PGDatePickerModeDateHourMinute, //年月日时分
PGDatePickerModeDateHourMinuteSecond, //年月日时分秒
PGDatePickerModeMonthDay, //月日
PGDatePickerModeMonthDayHour, //月日时
PGDatePickerModeMonthDayHourMinute, //月日时分
PGDatePickerModeMonthDayHourMinuteSecond, //月日时分秒
PGDatePickerModeTime, //时分
PGDatePickerModeTimeAndSecond, //时分秒
PGDatePickerModeMinuteAndSecond, //分秒
PGDatePickerModeDateAndTime, //月日周 时分
PGDatePickerModeDate2,
};
typedef NS_ENUM(NSUInteger, PGDatePickerType) {
PGDatePickerTypeLine,
PGDatePickerTypeSegment,
PGDatePickerTypeVertical,
};
typedef NS_ENUM(NSUInteger, PGShowUnitType) {
PGShowUnitTypeAll,
PGShowUnitTypeCenter,
PGShowUnitTypeNone,
};
typedef NS_ENUM(NSUInteger, PGDatePickManagerStyle) {
PGDatePickManagerStyleSheet,
PGDatePickManagerStyleAlertTopButton,
PGDatePickManagerStyleAlertBottomButton
};
#endif /* PGEnumeration_h */
| 26.666667 | 53 | 0.771875 |
12972afe926652a0f892f80bf38aa8127a9ed83b | 743 | h | C | RoboRoboPi/GpioPi.h | vanklompf/RoboRoboPi | 344d025ae374720a88c761d97ed3010c5c577602 | [
"Beerware"
] | null | null | null | RoboRoboPi/GpioPi.h | vanklompf/RoboRoboPi | 344d025ae374720a88c761d97ed3010c5c577602 | [
"Beerware"
] | null | null | null | RoboRoboPi/GpioPi.h | vanklompf/RoboRoboPi | 344d025ae374720a88c761d97ed3010c5c577602 | [
"Beerware"
] | null | null | null | #ifndef GPIO_PI_H
#define GPIO_PI_H
#include <cstdint>
#include "IGpio.h"
namespace robo
{
class GpioPi : public IGpio
{
public:
~GpioPi();
void Init() const;
void LedOn(led_t pin) const;
void LedOff(led_t pin) const;
void SetLed(led_t led, led_mode_t mode) const;
void SetAsOutput(uint8_t pin) const;
void SetAsInput(uint8_t pin) const;
void SetServo(uint8_t pin, uint32_t pos) const;
void SetPwmFrequency(uint8_t pin, uint32_t freq) const;
void SetPwmRange(uint8_t pin, uint32_t range) const;
void SetPwmDutyCycle(uint8_t pin, uint32_t dutycycle) const;
private:
void SetPinHigh(unsigned int pin) const;
void SetPinLow(unsigned int pin) const;
};
}
#endif /* GPIO_PI_H */ | 23.967742 | 65 | 0.702557 |
3e8eb687260a99853b66d9d3d8b023d3a631cb3a | 414 | h | C | DataStructures/LinkedList/singleLinkedList.h | ComplicatedPhenomenon/C_practice | 03838005638a3dd9d3deef86c5944b58db278d98 | [
"MIT"
] | null | null | null | DataStructures/LinkedList/singleLinkedList.h | ComplicatedPhenomenon/C_practice | 03838005638a3dd9d3deef86c5944b58db278d98 | [
"MIT"
] | null | null | null | DataStructures/LinkedList/singleLinkedList.h | ComplicatedPhenomenon/C_practice | 03838005638a3dd9d3deef86c5944b58db278d98 | [
"MIT"
] | null | null | null | typedef struct Cell {
int data;
struct Cell * next;
} listNode;
listNode * newNode(int val);
int lengthOfSLL(listNode *head);
void printSLL(listNode *head);
void freeSLL(listNode *head);
listNode * reverseSLL(listNode *head);
listNode * reversePartOfSLL(listNode *head, int m, int n);
listNode * insertToSLL(listNode *head, int postion, int val);
listNode * removeElementsOfSLL(listNode* head, int val); | 31.846154 | 62 | 0.73913 |
c49e217bbf2502a0d999ef6b5b7f5e98b7f9a7e5 | 1,570 | h | C | src/xcode/mobbl-core-framework/Services/DataManagerImpl/Handlers/Helpers/MBHTTPConnectionDelegate.h | sven-m/itude-mobile-ios-mobbl-framework | f5b3b8cc22274933f9f7f60e2939bbde26425ce2 | [
"Apache-2.0"
] | null | null | null | src/xcode/mobbl-core-framework/Services/DataManagerImpl/Handlers/Helpers/MBHTTPConnectionDelegate.h | sven-m/itude-mobile-ios-mobbl-framework | f5b3b8cc22274933f9f7f60e2939bbde26425ce2 | [
"Apache-2.0"
] | null | null | null | src/xcode/mobbl-core-framework/Services/DataManagerImpl/Handlers/Helpers/MBHTTPConnectionDelegate.h | sven-m/itude-mobile-ios-mobbl-framework | f5b3b8cc22274933f9f7f60e2939bbde26425ce2 | [
"Apache-2.0"
] | null | null | null | /*
* (C) Copyright Itude Mobile B.V., The Netherlands.
*
* 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.
*/
//
// MBHTTPConnectionDelegate.h
// mobbl-core-framework
//
// Created by Sven Meyer on 16/07/14.
#import <Foundation/Foundation.h>
@protocol MBHTTPConnection;
@protocol MBHTTPConnectionDelegate <NSObject>
@optional
- (void)connection:(id<MBHTTPConnection>)connection didFailWithError:(NSError *)error;
- (void)connection:(id<MBHTTPConnection>)connection didReceiveData:(NSData *)data;
- (void)connection:(id<MBHTTPConnection>)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connectionDidFinishLoading:(id<MBHTTPConnection>)connection;
- (NSCachedURLResponse *)connection:(id<MBHTTPConnection>)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse;
- (BOOL)connection:(id<MBHTTPConnection>)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
- (void)connection:(id<MBHTTPConnection>)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
@end
| 39.25 | 130 | 0.784713 |
8bab9f69cc39df27313cb7b21dc8c6cfb0ecf904 | 3,360 | h | C | usr.bin/tip/tip/tipconf.h | ivadasz/DragonFlyBSD | 460227f342554313be3c7728ff679dd4a556cce9 | [
"BSD-3-Clause"
] | null | null | null | usr.bin/tip/tip/tipconf.h | ivadasz/DragonFlyBSD | 460227f342554313be3c7728ff679dd4a556cce9 | [
"BSD-3-Clause"
] | null | null | null | usr.bin/tip/tip/tipconf.h | ivadasz/DragonFlyBSD | 460227f342554313be3c7728ff679dd4a556cce9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)tipconf.h 8.1 (Berkeley) 3/25/95
*/
#ifndef tipconf_h_included
#define tipconf_h_included
/*
Define constness
*/
#define CONST const
/*
Specify default bit rate for connections
*/
#define DEFBR 1200
/*
Default frame size for file transfer buffering of writes
on local side
*/
#ifndef BUFSIZ
#define DEFFS 1024
#else
#define DEFFS BUFSIZ
#endif
/*
Enable logging of ACU use
*/
#define ACULOG 1
/*
Strip phone #s from ACU log file
*/
#define PRISTINE 1
/*
Enable command to "connect" remote with local process
*/
#define CONNECT 1
/*
Specify style of UUCP lock files
*/
#define HAVE_V2_LOCKFILES 0
#define HAVE_HDB_LOCKFILES 1
/*
System has a millisecond based sleep function
*/
#define HAVE_USLEEP 0
/*
System has select
*/
#define HAVE_SELECT 1
/*
System has termios tty interface
*/
#define HAVE_TERMIOS 1
/*
Include configurable modem driver
*/
#define UNIDIALER 1
/*
Specify builtin modem drivers to include
*/
#define BIZ1031 0
#define BIZ1022 0
#define COURIER 0
#define DF02 0
#define DF03 0
#define DN11 0
#define HAYES 0
#define MULTITECH 0
#define T3000 0
#define V3451 0
#define V831 0
#define VENTEL 0
/*
Include cu interface so that, when tip is linked to cu and then
invoked as cu, it behaves like cu.
*/
#define INCLUDE_CU_INTERFACE 1
#endif
/* end of tipconf.h */
| 26.88 | 77 | 0.705357 |
ac631551549c997934978901d6a6a61f64f4b362 | 376 | h | C | projectionSceneManager/src/MovingRectSource.h | c-c-c/gold-creative-coding | d7ccb5d5f706caafed27050a4c3a514c56a8230e | [
"MIT"
] | 1 | 2020-04-25T06:34:59.000Z | 2020-04-25T06:34:59.000Z | projectionSceneManager/src/MovingRectSource.h | c-c-c/gold-creative-coding-1 | d7ccb5d5f706caafed27050a4c3a514c56a8230e | [
"MIT"
] | null | null | null | projectionSceneManager/src/MovingRectSource.h | c-c-c/gold-creative-coding-1 | d7ccb5d5f706caafed27050a4c3a514c56a8230e | [
"MIT"
] | null | null | null | #pragma once
#include "ofMain.h"
#include "FboSource.h"
class MovingRectSource : public ofx::piMapper::FboSource {
public:
void setup();
void update();
void draw();
void reset();
void drawMovingRect(int, int, int, int, float);
void setName(string _name);
void setColor(ofColor);
ofColor rectColor;
float time;
};
| 20.888889 | 58 | 0.614362 |
3acc93c715e213c10e3fad95285a2d6aaa190f6f | 2,947 | h | C | iVS3D/src/iVS3D-core/model/delayedcopyreader.h | iVS3D/iVS3D | a1553a8d6ac5c5d3205a0ab2e2e340a109d2d8c9 | [
"MIT"
] | 10 | 2021-08-05T09:47:11.000Z | 2022-03-18T12:47:39.000Z | iVS3D/src/iVS3D-core/model/delayedcopyreader.h | iVS3D/iVS3D | a1553a8d6ac5c5d3205a0ab2e2e340a109d2d8c9 | [
"MIT"
] | null | null | null | iVS3D/src/iVS3D-core/model/delayedcopyreader.h | iVS3D/iVS3D | a1553a8d6ac5c5d3205a0ab2e2e340a109d2d8c9 | [
"MIT"
] | null | null | null | #ifndef DELAYEDCOPYREADER_H
#define DELAYEDCOPYREADER_H
#include "reader.h"
/**
* @class DelayedCopyReader
*
* @ingroup Model
*
* @brief The DelayedCopyReader class is a proxy for a Reader and copies this Reader if Reader::getPic() is called.
*
* This implementation allows to perform time consuming copying of Reader objects only if they are used.
*
* @author Dominik Wüst
*
* @date 2021/02/26
*/
class DelayedCopyReader : public Reader
{
public:
/**
* @brief Create a DelayedCopyReader instance which performs Reader::copy() operation on given Reader on first call of Reader::getPic().
* @param reader the Reader to copy
*/
explicit DelayedCopyReader(Reader *reader);
/**
* @brief getPic calls Reader::getPic() on copy of given Reader [COPIES THE READER IF NOT DONE YET].
* @param index Index of the frame to be returned
* @param useMultipleAccess optinal paramter, if multipleAccess should be used (set to false by default)
* @return cv::Mat of the selected frame
*/
cv::Mat getPic(unsigned int idx, bool = false) override;
/**
* @brief getPicCount Returns the number of pictures to access on this Reader [DOES NOT COPY THE READER].
* @return the number of pictures
*/
unsigned int getPicCount() override;
/**
* @brief getInputPath Returns the input path of the pictures [DOES NOT COPY THE READER].
* @return the input path
*/
QString getInputPath() override;
/**
* @brief Returns the video FPS
*
* @return double with the FPS, -1 if input isn't a video
*/
double getFPS() override;
/**
* @brief Returns the video duration
*
* @return double with the video duration, -1 if input isn't a video
*/
double getVideoDuration() override;
/**
* @brief isDir Checks if the given Reader operates on a video or directory [DOES NOT COPY THE READER].
* @return @a true if reading from directory
*/
bool isDir() override;
/**
* @brief copy Create a copy of this DelayedCopyReader.
* @return the copy
*/
Reader *copy() override;
/**
* @brief Returns a vector with filepaths (only valid, if the reader is a imagereader)
*
* @return Vector with filepaths
*/
std::vector<std::string> getFileVector() override;
/**
* @brief enableMultithreading This method has to be called once in the plugins to use the reader while multithreading
*/
void enableMultithreading() override;
/**
* @brief initMultipleAccess Enables the reader to make ordered access to the input, which will result in a faster access time
* @param frames Vector containing the indices of the images which will be used in ascending order
*/
void initMultipleAccess(const std::vector<uint> &frames) override;
private:
Reader *m_realReader;
Reader *m_copyReader;
};
#endif // DELAYEDCOPYREADER_H
| 31.021053 | 140 | 0.672888 |
6b96959035227f0278987f56c2832ecb73011022 | 1,242 | h | C | evs/include/huaweicloud/evs/v2/model/OsExtend.h | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | evs/include/huaweicloud/evs/v2/model/OsExtend.h | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | evs/include/huaweicloud/evs/v2/model/OsExtend.h | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null |
#ifndef HUAWEICLOUD_SDK_EVS_V2_MODEL_OsExtend_H_
#define HUAWEICLOUD_SDK_EVS_V2_MODEL_OsExtend_H_
#include <huaweicloud/evs/v2/EvsExport.h>
#include <huaweicloud/core/utils/ModelBase.h>
#include <huaweicloud/core/http/HttpResponse.h>
namespace HuaweiCloud {
namespace Sdk {
namespace Evs {
namespace V2 {
namespace Model {
using namespace HuaweiCloud::Sdk::Core::Utils;
using namespace HuaweiCloud::Sdk::Core::Http;
/// <summary>
///
/// </summary>
class HUAWEICLOUD_EVS_V2_EXPORT OsExtend
: public ModelBase
{
public:
OsExtend();
virtual ~OsExtend();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
bool fromJson(const web::json::value& json) override;
/////////////////////////////////////////////
/// OsExtend members
/// <summary>
/// 扩容后的云硬盘大小,单位为GB。扩容的大小必须大于原有云硬盘容量且小于云硬盘最大容量。 云硬盘最大容量: * 数据盘:32768GB * 系统盘:1024GB
/// </summary>
int32_t getNewSize() const;
bool newSizeIsSet() const;
void unsetnewSize();
void setNewSize(int32_t value);
protected:
int32_t newSize_;
bool newSizeIsSet_;
};
}
}
}
}
}
#endif // HUAWEICLOUD_SDK_EVS_V2_MODEL_OsExtend_H_
| 19.107692 | 87 | 0.6562 |
b166b931204dc55c0510c47b50328c3c2a1ce923 | 477 | h | C | QQApiObjectCoderImpl.h | yihongmingfeng/Fruitday | 981f6ecdb03a42d95210b249590505db18195dfd | [
"MIT"
] | null | null | null | QQApiObjectCoderImpl.h | yihongmingfeng/Fruitday | 981f6ecdb03a42d95210b249590505db18195dfd | [
"MIT"
] | null | null | null | QQApiObjectCoderImpl.h | yihongmingfeng/Fruitday | 981f6ecdb03a42d95210b249590505db18195dfd | [
"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 "NSObject.h"
#import "NSCoding.h"
@class QQApiObject;
@interface QQApiObjectCoderImpl : NSObject <NSCoding>
{
QQApiObject *_obj;
}
@property(retain, nonatomic) QQApiObject *obj; // @synthesize obj=_obj;
- (id)initWithCoder:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
- (void)dealloc;
- (id)initWithObject:(id)arg1;
@end
| 18.346154 | 83 | 0.685535 |
58062573057b133d39791fae14a0807588564739 | 1,114 | h | C | include/il2cpp/Dpr/Battle/Logic/Section_CalcActionPriority.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/Dpr/Battle/Logic/Section_CalcActionPriority.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/Dpr/Battle/Logic/Section_CalcActionPriority.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void Dpr_Battle_Logic_Section_CalcActionPriority___ctor (Dpr_Battle_Logic_Section_CalcActionPriority_o* __this, Dpr_Battle_Logic_Section_CommonParam_o** commonParam, const MethodInfo* method_info);
void Dpr_Battle_Logic_Section_CalcActionPriority__Execute (Dpr_Battle_Logic_Section_CalcActionPriority_o* __this, Dpr_Battle_Logic_Section_CalcActionPriority_Result_o* pResult, Dpr_Battle_Logic_Section_CalcActionPriority_Description_o** description, const MethodInfo* method_info);
uint8_t Dpr_Battle_Logic_Section_CalcActionPriority__calcOperationPriority (Dpr_Battle_Logic_Section_CalcActionPriority_o* __this, Dpr_Battle_Logic_PokeAction_o* pAction, const MethodInfo* method_info);
uint16_t Dpr_Battle_Logic_Section_CalcActionPriority__calcAgility (Dpr_Battle_Logic_Section_CalcActionPriority_o* __this, Dpr_Battle_Logic_BTL_POKEPARAM_o* poke, const MethodInfo* method_info);
uint8_t Dpr_Battle_Logic_Section_CalcActionPriority__calcWazaPriority (Dpr_Battle_Logic_Section_CalcActionPriority_o* __this, Dpr_Battle_Logic_PokeAction_o** pokeAction, const MethodInfo* method_info);
| 111.4 | 281 | 0.90754 |
0dc287914338b3000d1652d04e0f9d62a9ac4598 | 31,445 | c | C | contrib/gnu/gettext/dist/gettext-tools/libgettextpo/gettext-po.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | 3 | 2021-05-04T17:09:06.000Z | 2021-10-04T07:19:26.000Z | contrib/gnu/gettext/dist/gettext-tools/libgettextpo/gettext-po.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | contrib/gnu/gettext/dist/gettext-tools/libgettextpo/gettext-po.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | /* Public API for GNU gettext PO files.
Copyright (C) 2003-2006 Free Software Foundation, Inc.
Written by Bruno Haible <bruno@clisp.org>, 2003.
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, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
/* Specification. */
#include "gettext-po.h"
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "message.h"
#include "xalloc.h"
#include "read-catalog.h"
#include "read-po.h"
#include "write-catalog.h"
#include "write-po.h"
#include "error.h"
#include "xerror.h"
#include "po-error.h"
#include "po-xerror.h"
#include "vasprintf.h"
#include "format.h"
#include "msgl-check.h"
#include "gettext.h"
#define _(str) gettext(str)
struct po_file
{
msgdomain_list_ty *mdlp;
const char *real_filename;
const char *logical_filename;
const char **domains;
};
struct po_message_iterator
{
po_file_t file;
char *domain;
message_list_ty *mlp;
size_t index;
};
/* A po_message_t is actually a 'struct message_ty *'. */
/* A po_filepos_t is actually a 'lex_pos_ty *'. */
/* Version number: (major<<16) + (minor<<8) + subminor */
int libgettextpo_version = LIBGETTEXTPO_VERSION;
/* Create an empty PO file representation in memory. */
po_file_t
po_file_create (void)
{
po_file_t file;
file = (struct po_file *) xmalloc (sizeof (struct po_file));
file->mdlp = msgdomain_list_alloc (false);
file->real_filename = _("<unnamed>");
file->logical_filename = file->real_filename;
file->domains = NULL;
return file;
}
/* Read a PO file into memory.
Return its contents. Upon failure, return NULL and set errno. */
po_file_t
po_file_read (const char *filename, po_xerror_handler_t handler)
{
FILE *fp;
po_file_t file;
if (strcmp (filename, "-") == 0 || strcmp (filename, "/dev/stdin") == 0)
{
filename = _("<stdin>");
fp = stdin;
}
else
{
fp = fopen (filename, "r");
if (fp == NULL)
return NULL;
}
/* Establish error handler around read_catalog_stream(). */
po_xerror =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror;
po_xerror2 =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror2;
gram_max_allowed_errors = UINT_MAX;
file = (struct po_file *) xmalloc (sizeof (struct po_file));
file->real_filename = filename;
file->logical_filename = filename;
file->mdlp = read_catalog_stream (fp, file->real_filename,
file->logical_filename, &input_format_po);
file->domains = NULL;
/* Restore error handler. */
po_xerror = textmode_xerror;
po_xerror2 = textmode_xerror2;
gram_max_allowed_errors = 20;
if (fp != stdin)
fclose (fp);
return file;
}
#undef po_file_read
po_file_t
po_file_read_v2 (const char *filename, po_error_handler_t handler)
{
FILE *fp;
po_file_t file;
if (strcmp (filename, "-") == 0 || strcmp (filename, "/dev/stdin") == 0)
{
filename = _("<stdin>");
fp = stdin;
}
else
{
fp = fopen (filename, "r");
if (fp == NULL)
return NULL;
}
/* Establish error handler around read_catalog_stream(). */
po_error = handler->error;
po_error_at_line = handler->error_at_line;
po_multiline_warning = handler->multiline_warning;
po_multiline_error = handler->multiline_error;
gram_max_allowed_errors = UINT_MAX;
file = (struct po_file *) xmalloc (sizeof (struct po_file));
file->real_filename = filename;
file->logical_filename = filename;
file->mdlp = read_catalog_stream (fp, file->real_filename,
file->logical_filename, &input_format_po);
file->domains = NULL;
/* Restore error handler. */
po_error = error;
po_error_at_line = error_at_line;
po_multiline_warning = multiline_warning;
po_multiline_error = multiline_error;
gram_max_allowed_errors = 20;
if (fp != stdin)
fclose (fp);
return file;
}
/* Older version for binary backward compatibility. */
po_file_t
po_file_read (const char *filename)
{
FILE *fp;
po_file_t file;
if (strcmp (filename, "-") == 0 || strcmp (filename, "/dev/stdin") == 0)
{
filename = _("<stdin>");
fp = stdin;
}
else
{
fp = fopen (filename, "r");
if (fp == NULL)
return NULL;
}
file = (struct po_file *) xmalloc (sizeof (struct po_file));
file->real_filename = filename;
file->logical_filename = filename;
file->mdlp = read_catalog_stream (fp, file->real_filename,
file->logical_filename, &input_format_po);
file->domains = NULL;
if (fp != stdin)
fclose (fp);
return file;
}
/* Write an in-memory PO file to a file.
Upon failure, return NULL and set errno. */
po_file_t
po_file_write (po_file_t file, const char *filename, po_xerror_handler_t handler)
{
/* Establish error handler around msgdomain_list_print(). */
po_xerror =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror;
po_xerror2 =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror2;
msgdomain_list_print (file->mdlp, filename, &output_format_po, true, false);
/* Restore error handler. */
po_xerror = textmode_xerror;
po_xerror2 = textmode_xerror2;
return file;
}
#undef po_file_write
/* Older version for binary backward compatibility. */
po_file_t
po_file_write (po_file_t file, const char *filename, po_error_handler_t handler)
{
/* Establish error handler around msgdomain_list_print(). */
po_error = handler->error;
po_error_at_line = handler->error_at_line;
po_multiline_warning = handler->multiline_warning;
po_multiline_error = handler->multiline_error;
msgdomain_list_print (file->mdlp, filename, &output_format_po, true, false);
/* Restore error handler. */
po_error = error;
po_error_at_line = error_at_line;
po_multiline_warning = multiline_warning;
po_multiline_error = multiline_error;
return file;
}
/* Free a PO file from memory. */
void
po_file_free (po_file_t file)
{
msgdomain_list_free (file->mdlp);
if (file->domains != NULL)
free (file->domains);
free (file);
}
/* Return the names of the domains covered by a PO file in memory. */
const char * const *
po_file_domains (po_file_t file)
{
if (file->domains == NULL)
{
size_t n = file->mdlp->nitems;
const char **domains =
(const char **) xmalloc ((n + 1) * sizeof (const char *));
size_t j;
for (j = 0; j < n; j++)
domains[j] = file->mdlp->item[j]->domain;
domains[n] = NULL;
file->domains = domains;
}
return file->domains;
}
/* Return the header entry of a domain of a PO file in memory.
The domain NULL denotes the default domain.
Return NULL if there is no header entry. */
const char *
po_file_domain_header (po_file_t file, const char *domain)
{
message_list_ty *mlp;
size_t j;
if (domain == NULL)
domain = MESSAGE_DOMAIN_DEFAULT;
mlp = msgdomain_list_sublist (file->mdlp, domain, false);
if (mlp != NULL)
for (j = 0; j < mlp->nitems; j++)
if (is_header (mlp->item[j]) && !mlp->item[j]->obsolete)
{
const char *header = mlp->item[j]->msgstr;
if (header != NULL)
return xstrdup (header);
else
return NULL;
}
return NULL;
}
/* Return the value of a field in a header entry.
The return value is either a freshly allocated string, to be freed by the
caller, or NULL. */
char *
po_header_field (const char *header, const char *field)
{
size_t field_len = strlen (field);
const char *line;
for (line = header;;)
{
if (strncmp (line, field, field_len) == 0
&& line[field_len] == ':' && line[field_len + 1] == ' ')
{
const char *value_start;
const char *value_end;
char *value;
value_start = line + field_len + 2;
value_end = strchr (value_start, '\n');
if (value_end == NULL)
value_end = value_start + strlen (value_start);
value = (char *) xmalloc (value_end - value_start + 1);
memcpy (value, value_start, value_end - value_start);
value[value_end - value_start] = '\0';
return value;
}
line = strchr (line, '\n');
if (line != NULL)
line++;
else
break;
}
return NULL;
}
/* Return the header entry with a given field set to a given value. The field
is added if necessary.
The return value is a freshly allocated string. */
char *
po_header_set_field (const char *header, const char *field, const char *value)
{
size_t header_len = strlen (header);
size_t field_len = strlen (field);
size_t value_len = strlen (value);
{
const char *line;
for (line = header;;)
{
if (strncmp (line, field, field_len) == 0
&& line[field_len] == ':' && line[field_len + 1] == ' ')
{
const char *oldvalue_start;
const char *oldvalue_end;
size_t oldvalue_len;
size_t header_part1_len;
size_t header_part3_len;
size_t result_len;
char *result;
oldvalue_start = line + field_len + 2;
oldvalue_end = strchr (oldvalue_start, '\n');
if (oldvalue_end == NULL)
oldvalue_end = oldvalue_start + strlen (oldvalue_start);
oldvalue_len = oldvalue_end - oldvalue_start;
header_part1_len = oldvalue_start - header;
header_part3_len = header + header_len - oldvalue_end;
result_len = header_part1_len + value_len + header_part3_len;
/* = header_len - oldvalue_len + value_len */
result = (char *) xmalloc (result_len + 1);
memcpy (result, header, header_part1_len);
memcpy (result + header_part1_len, value, value_len);
memcpy (result + header_part1_len + value_len, oldvalue_end,
header_part3_len);
*(result + result_len) = '\0';
return result;
}
line = strchr (line, '\n');
if (line != NULL)
line++;
else
break;
}
}
{
size_t newline;
size_t result_len;
char *result;
newline = (header_len > 0 && header[header_len - 1] != '\n' ? 1 : 0);
result_len = header_len + newline + field_len + 2 + value_len + 1;
result = (char *) xmalloc (result_len + 1);
memcpy (result, header, header_len);
if (newline)
*(result + header_len) = '\n';
memcpy (result + header_len + newline, field, field_len);
*(result + header_len + newline + field_len) = ':';
*(result + header_len + newline + field_len + 1) = ' ';
memcpy (result + header_len + newline + field_len + 2, value, value_len);
*(result + header_len + newline + field_len + 2 + value_len) = '\n';
*(result + result_len) = '\0';
return result;
}
}
/* Create an iterator for traversing a domain of a PO file in memory.
The domain NULL denotes the default domain. */
po_message_iterator_t
po_message_iterator (po_file_t file, const char *domain)
{
po_message_iterator_t iterator;
if (domain == NULL)
domain = MESSAGE_DOMAIN_DEFAULT;
iterator =
(struct po_message_iterator *)
xmalloc (sizeof (struct po_message_iterator));
iterator->file = file;
iterator->domain = xstrdup (domain);
iterator->mlp = msgdomain_list_sublist (file->mdlp, domain, false);
iterator->index = 0;
return iterator;
}
/* Free an iterator. */
void
po_message_iterator_free (po_message_iterator_t iterator)
{
free (iterator->domain);
free (iterator);
}
/* Return the next message, and advance the iterator.
Return NULL at the end of the message list. */
po_message_t
po_next_message (po_message_iterator_t iterator)
{
if (iterator->mlp != NULL && iterator->index < iterator->mlp->nitems)
return (po_message_t) iterator->mlp->item[iterator->index++];
else
return NULL;
}
/* Insert a message in a PO file in memory, in the domain and at the position
indicated by the iterator. The iterator thereby advances past the freshly
inserted message. */
void
po_message_insert (po_message_iterator_t iterator, po_message_t message)
{
message_ty *mp = (message_ty *) message;
if (iterator->mlp == NULL)
/* Now we need to allocate a sublist corresponding to the iterator. */
iterator->mlp =
msgdomain_list_sublist (iterator->file->mdlp, iterator->domain, true);
/* Insert the message. */
message_list_insert_at (iterator->mlp, iterator->index, mp);
/* Advance the iterator. */
iterator->index++;
}
/* Return a freshly constructed message.
To finish initializing the message, you must set the msgid and msgstr. */
po_message_t
po_message_create (void)
{
lex_pos_ty pos = { NULL, 0 };
return (po_message_t) message_alloc (NULL, NULL, NULL, NULL, 0, &pos);
}
/* Return the context of a message, or NULL for a message not restricted to a
context. */
const char *
po_message_msgctxt (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return mp->msgctxt;
}
/* Change the context of a message. NULL means a message not restricted to a
context. */
void
po_message_set_msgctxt (po_message_t message, const char *msgctxt)
{
message_ty *mp = (message_ty *) message;
if (msgctxt != mp->msgctxt)
{
char *old_msgctxt = (char *) mp->msgctxt;
mp->msgctxt = (msgctxt != NULL ? xstrdup (msgctxt) : NULL);
if (old_msgctxt != NULL)
free (old_msgctxt);
}
}
/* Return the msgid (untranslated English string) of a message. */
const char *
po_message_msgid (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return mp->msgid;
}
/* Change the msgid (untranslated English string) of a message. */
void
po_message_set_msgid (po_message_t message, const char *msgid)
{
message_ty *mp = (message_ty *) message;
if (msgid != mp->msgid)
{
char *old_msgid = (char *) mp->msgid;
mp->msgid = xstrdup (msgid);
if (old_msgid != NULL)
free (old_msgid);
}
}
/* Return the msgid_plural (untranslated English plural string) of a message,
or NULL for a message without plural. */
const char *
po_message_msgid_plural (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return mp->msgid_plural;
}
/* Change the msgid_plural (untranslated English plural string) of a message.
NULL means a message without plural. */
void
po_message_set_msgid_plural (po_message_t message, const char *msgid_plural)
{
message_ty *mp = (message_ty *) message;
if (msgid_plural != mp->msgid_plural)
{
char *old_msgid_plural = (char *) mp->msgid_plural;
mp->msgid_plural = (msgid_plural != NULL ? xstrdup (msgid_plural) : NULL);
if (old_msgid_plural != NULL)
free (old_msgid_plural);
}
}
/* Return the msgstr (translation) of a message.
Return the empty string for an untranslated message. */
const char *
po_message_msgstr (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return mp->msgstr;
}
/* Change the msgstr (translation) of a message.
Use an empty string to denote an untranslated message. */
void
po_message_set_msgstr (po_message_t message, const char *msgstr)
{
message_ty *mp = (message_ty *) message;
if (msgstr != mp->msgstr)
{
char *old_msgstr = (char *) mp->msgstr;
mp->msgstr = xstrdup (msgstr);
mp->msgstr_len = strlen (mp->msgstr) + 1;
if (old_msgstr != NULL)
free (old_msgstr);
}
}
/* Return the msgstr[index] for a message with plural handling, or
NULL when the index is out of range or for a message without plural. */
const char *
po_message_msgstr_plural (po_message_t message, int index)
{
message_ty *mp = (message_ty *) message;
if (mp->msgid_plural != NULL && index >= 0)
{
const char *p;
const char *p_end = mp->msgstr + mp->msgstr_len;
for (p = mp->msgstr; ; p += strlen (p) + 1, index--)
{
if (p >= p_end)
return NULL;
if (index == 0)
break;
}
return p;
}
else
return NULL;
}
/* Change the msgstr[index] for a message with plural handling.
Use a NULL value at the end to reduce the number of plural forms. */
void
po_message_set_msgstr_plural (po_message_t message, int index, const char *msgstr)
{
message_ty *mp = (message_ty *) message;
if (mp->msgid_plural != NULL && index >= 0)
{
char *p = (char *) mp->msgstr;
char *p_end = (char *) mp->msgstr + mp->msgstr_len;
char *copied_msgstr;
/* Special care must be taken of the case that msgstr points into the
mp->msgstr string list, because mp->msgstr may be relocated before we
are done with msgstr. */
if (msgstr >= p && msgstr < p_end)
msgstr = copied_msgstr = xstrdup (msgstr);
else
copied_msgstr = NULL;
for (; ; p += strlen (p) + 1, index--)
{
if (p >= p_end)
{
/* Append at the end. */
if (msgstr != NULL)
{
size_t new_msgstr_len = mp->msgstr_len + index + strlen (msgstr) + 1;
mp->msgstr =
(char *) xrealloc ((char *) mp->msgstr, new_msgstr_len);
p = (char *) mp->msgstr + mp->msgstr_len;
for (; index > 0; index--)
*p++ = '\0';
memcpy (p, msgstr, strlen (msgstr) + 1);
mp->msgstr_len = new_msgstr_len;
}
if (copied_msgstr != NULL)
free (copied_msgstr);
return;
}
if (index == 0)
break;
}
if (msgstr == NULL)
{
if (p + strlen (p) + 1 >= p_end)
{
/* Remove the string that starts at p. */
mp->msgstr_len = p - mp->msgstr;
return;
}
/* It is not possible to remove an element of the string list
except the last one. So just replace it with the empty string.
That's the best we can do here. */
msgstr = "";
}
{
/* Replace the string that starts at p. */
size_t i1 = p - mp->msgstr;
size_t i2before = i1 + strlen (p);
size_t i2after = i1 + strlen (msgstr);
size_t new_msgstr_len = mp->msgstr_len - i2before + i2after;
if (i2after > i2before)
mp->msgstr = (char *) xrealloc ((char *) mp->msgstr, new_msgstr_len);
memmove ((char *) mp->msgstr + i2after, mp->msgstr + i2before,
mp->msgstr_len - i2before);
memcpy ((char *) mp->msgstr + i1, msgstr, i2after - i1);
mp->msgstr_len = new_msgstr_len;
}
if (copied_msgstr != NULL)
free (copied_msgstr);
}
}
/* Return the comments for a message. */
const char *
po_message_comments (po_message_t message)
{
/* FIXME: memory leak. */
message_ty *mp = (message_ty *) message;
if (mp->comment == NULL || mp->comment->nitems == 0)
return "";
else
return string_list_join (mp->comment, '\n', '\n', true);
}
/* Change the comments for a message.
comments should be a multiline string, ending in a newline, or empty. */
void
po_message_set_comments (po_message_t message, const char *comments)
{
message_ty *mp = (message_ty *) message;
string_list_ty *slp = string_list_alloc ();
{
char *copy = xstrdup (comments);
char *rest;
rest = copy;
while (*rest != '\0')
{
char *newline = strchr (rest, '\n');
if (newline != NULL)
{
*newline = '\0';
string_list_append (slp, rest);
rest = newline + 1;
}
else
{
string_list_append (slp, rest);
break;
}
}
free (copy);
}
if (mp->comment != NULL)
string_list_free (mp->comment);
mp->comment = slp;
}
/* Return the extracted comments for a message. */
const char *
po_message_extracted_comments (po_message_t message)
{
/* FIXME: memory leak. */
message_ty *mp = (message_ty *) message;
if (mp->comment_dot == NULL || mp->comment_dot->nitems == 0)
return "";
else
return string_list_join (mp->comment_dot, '\n', '\n', true);
}
/* Change the extracted comments for a message.
comments should be a multiline string, ending in a newline, or empty. */
void
po_message_set_extracted_comments (po_message_t message, const char *comments)
{
message_ty *mp = (message_ty *) message;
string_list_ty *slp = string_list_alloc ();
{
char *copy = xstrdup (comments);
char *rest;
rest = copy;
while (*rest != '\0')
{
char *newline = strchr (rest, '\n');
if (newline != NULL)
{
*newline = '\0';
string_list_append (slp, rest);
rest = newline + 1;
}
else
{
string_list_append (slp, rest);
break;
}
}
free (copy);
}
if (mp->comment_dot != NULL)
string_list_free (mp->comment_dot);
mp->comment_dot = slp;
}
/* Return the i-th file position for a message, or NULL if i is out of
range. */
po_filepos_t
po_message_filepos (po_message_t message, int i)
{
message_ty *mp = (message_ty *) message;
if (i >= 0 && (size_t)i < mp->filepos_count)
return (po_filepos_t) &mp->filepos[i];
else
return NULL;
}
/* Remove the i-th file position from a message.
The indices of all following file positions for the message are decremented
by one. */
void
po_message_remove_filepos (po_message_t message, int i)
{
message_ty *mp = (message_ty *) message;
if (i >= 0)
{
size_t j = (size_t)i;
size_t n = mp->filepos_count;
if (j < n)
{
mp->filepos_count = n = n - 1;
free ((char *) mp->filepos[j].file_name);
for (; j < n; j++)
mp->filepos[j] = mp->filepos[j + 1];
}
}
}
/* Add a file position to a message, if it is not already present for the
message.
file is the file name.
start_line is the line number where the string starts, or (size_t)(-1) if no
line number is available. */
void
po_message_add_filepos (po_message_t message, const char *file, size_t start_line)
{
message_ty *mp = (message_ty *) message;
message_comment_filepos (mp, file, start_line);
}
/* Return the previous context of a message, or NULL for none. */
const char *
po_message_prev_msgctxt (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return mp->prev_msgctxt;
}
/* Change the previous context of a message. NULL is allowed. */
void
po_message_set_prev_msgctxt (po_message_t message, const char *prev_msgctxt)
{
message_ty *mp = (message_ty *) message;
if (prev_msgctxt != mp->prev_msgctxt)
{
char *old_prev_msgctxt = (char *) mp->prev_msgctxt;
mp->prev_msgctxt = (prev_msgctxt != NULL ? xstrdup (prev_msgctxt) : NULL);
if (old_prev_msgctxt != NULL)
free (old_prev_msgctxt);
}
}
/* Return the previous msgid (untranslated English string) of a message, or
NULL for none. */
const char *
po_message_prev_msgid (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return mp->prev_msgid;
}
/* Change the previous msgid (untranslated English string) of a message.
NULL is allowed. */
void
po_message_set_prev_msgid (po_message_t message, const char *prev_msgid)
{
message_ty *mp = (message_ty *) message;
if (prev_msgid != mp->prev_msgid)
{
char *old_prev_msgid = (char *) mp->prev_msgid;
mp->prev_msgid = (prev_msgid != NULL ? xstrdup (prev_msgid) : NULL);
if (old_prev_msgid != NULL)
free (old_prev_msgid);
}
}
/* Return the previous msgid_plural (untranslated English plural string) of a
message, or NULL for none. */
const char *
po_message_prev_msgid_plural (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return mp->prev_msgid_plural;
}
/* Change the previous msgid_plural (untranslated English plural string) of a
message. NULL is allowed. */
void
po_message_set_prev_msgid_plural (po_message_t message, const char *prev_msgid_plural)
{
message_ty *mp = (message_ty *) message;
if (prev_msgid_plural != mp->prev_msgid_plural)
{
char *old_prev_msgid_plural = (char *) mp->prev_msgid_plural;
mp->prev_msgid_plural =
(prev_msgid_plural != NULL ? xstrdup (prev_msgid_plural) : NULL);
if (old_prev_msgid_plural != NULL)
free (old_prev_msgid_plural);
}
}
/* Return true if the message is marked obsolete. */
int
po_message_is_obsolete (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return (mp->obsolete ? 1 : 0);
}
/* Change the obsolete mark of a message. */
void
po_message_set_obsolete (po_message_t message, int obsolete)
{
message_ty *mp = (message_ty *) message;
mp->obsolete = obsolete;
}
/* Return true if the message is marked fuzzy. */
int
po_message_is_fuzzy (po_message_t message)
{
message_ty *mp = (message_ty *) message;
return (mp->is_fuzzy ? 1 : 0);
}
/* Change the fuzzy mark of a message. */
void
po_message_set_fuzzy (po_message_t message, int fuzzy)
{
message_ty *mp = (message_ty *) message;
mp->is_fuzzy = fuzzy;
}
/* Return true if the message is marked as being a format string of the given
type (e.g. "c-format"). */
int
po_message_is_format (po_message_t message, const char *format_type)
{
message_ty *mp = (message_ty *) message;
size_t len = strlen (format_type);
size_t i;
if (len >= 7 && memcmp (format_type + len - 7, "-format", 7) == 0)
for (i = 0; i < NFORMATS; i++)
if (strlen (format_language[i]) == len - 7
&& memcmp (format_language[i], format_type, len - 7) == 0)
/* The given format_type corresponds to (enum format_type) i. */
return (possible_format_p (mp->is_format[i]) ? 1 : 0);
return 0;
}
/* Change the format string mark for a given type of a message. */
void
po_message_set_format (po_message_t message, const char *format_type, /*bool*/int value)
{
message_ty *mp = (message_ty *) message;
size_t len = strlen (format_type);
size_t i;
if (len >= 7 && memcmp (format_type + len - 7, "-format", 7) == 0)
for (i = 0; i < NFORMATS; i++)
if (strlen (format_language[i]) == len - 7
&& memcmp (format_language[i], format_type, len - 7) == 0)
/* The given format_type corresponds to (enum format_type) i. */
mp->is_format[i] = (value ? yes : no);
}
/* Return the file name. */
const char *
po_filepos_file (po_filepos_t filepos)
{
lex_pos_ty *pp = (lex_pos_ty *) filepos;
return pp->file_name;
}
/* Return the line number where the string starts, or (size_t)(-1) if no line
number is available. */
size_t
po_filepos_start_line (po_filepos_t filepos)
{
lex_pos_ty *pp = (lex_pos_ty *) filepos;
return pp->line_number;
}
/* Test whether an entire file PO file is valid, like msgfmt does it.
If it is invalid, pass the reasons to the handler. */
void
po_file_check_all (po_file_t file, po_xerror_handler_t handler)
{
msgdomain_list_ty *mdlp;
size_t k;
/* Establish error handler. */
po_xerror =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror;
po_xerror2 =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror2;
mdlp = file->mdlp;
for (k = 0; k < mdlp->nitems; k++)
check_message_list (mdlp->item[k]->messages, 1, 1, 1, 0, 0, 0);
/* Restore error handler. */
po_xerror = textmode_xerror;
po_xerror2 = textmode_xerror2;
}
/* Test a single message, to be inserted in a PO file in memory, like msgfmt
does it. If it is invalid, pass the reasons to the handler. The iterator
is not modified by this call; it only specifies the file and the domain. */
void
po_message_check_all (po_message_t message, po_message_iterator_t iterator,
po_xerror_handler_t handler)
{
message_ty *mp = (message_ty *) message;
/* Establish error handler. */
po_xerror =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror;
po_xerror2 =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror2;
/* For plural checking, combine the message and its header into a small,
two-element message list. */
{
message_ty *header;
/* Find the header. */
{
message_list_ty *mlp;
size_t j;
header = NULL;
mlp =
msgdomain_list_sublist (iterator->file->mdlp, iterator->domain, false);
if (mlp != NULL)
for (j = 0; j < mlp->nitems; j++)
if (is_header (mlp->item[j]) && !mlp->item[j]->obsolete)
{
header = mlp->item[j];
break;
}
}
{
message_ty *items[2];
struct message_list_ty ml;
ml.item = items;
ml.nitems = 0;
ml.nitems_max = 2;
ml.use_hashtable = false;
if (header != NULL)
message_list_append (&ml, header);
if (mp != header)
message_list_append (&ml, mp);
check_message_list (&ml, 1, 1, 1, 0, 0, 0);
}
}
/* Restore error handler. */
po_xerror = textmode_xerror;
po_xerror2 = textmode_xerror2;
}
/* Test whether the message translation is a valid format string if the message
is marked as being a format string. If it is invalid, pass the reasons to
the handler. */
void
po_message_check_format (po_message_t message, po_xerror_handler_t handler)
{
message_ty *mp = (message_ty *) message;
/* Establish error handler. */
po_xerror =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror;
po_xerror2 =
(void (*) (int, const message_ty *, const char *, size_t, size_t, int, const char *, const message_ty *, const char *, size_t, size_t, int, const char *))
handler->xerror2;
if (!mp->obsolete)
check_message (mp, &mp->pos, 0, 1, NULL, 0, 0, 0, 0);
/* Restore error handler. */
po_xerror = textmode_xerror;
po_xerror2 = textmode_xerror2;
}
#undef po_message_check_format
/* Older version for binary backward compatibility. */
/* An error logger based on the po_error function pointer. */
static void
po_error_logger (const char *format, ...)
__attribute__ ((__format__ (__printf__, 1, 2)));
static void
po_error_logger (const char *format, ...)
{
va_list args;
char *error_message;
va_start (args, format);
if (vasprintf (&error_message, format, args) < 0)
error (EXIT_FAILURE, 0, _("memory exhausted"));
va_end (args);
po_error (0, 0, "%s", error_message);
free (error_message);
}
/* Test whether the message translation is a valid format string if the message
is marked as being a format string. If it is invalid, pass the reasons to
the handler. */
void
po_message_check_format (po_message_t message, po_error_handler_t handler)
{
message_ty *mp = (message_ty *) message;
/* Establish error handler for po_error_logger(). */
po_error = handler->error;
check_msgid_msgstr_format (mp->msgid, mp->msgid_plural,
mp->msgstr, mp->msgstr_len,
mp->is_format, NULL, po_error_logger);
/* Restore error handler. */
po_error = error;
}
| 24.877373 | 158 | 0.657434 |
0dfb6660d5817d10c07c76046d21f4930cd2e6de | 156 | h | C | src/mrbmacs-dialog.h | masahino/mruby-bin-mrbmacs-gtk | bbde5d956827ef7cbd7168b2a21b32a1777c098a | [
"MIT"
] | null | null | null | src/mrbmacs-dialog.h | masahino/mruby-bin-mrbmacs-gtk | bbde5d956827ef7cbd7168b2a21b32a1777c098a | [
"MIT"
] | null | null | null | src/mrbmacs-dialog.h | masahino/mruby-bin-mrbmacs-gtk | bbde5d956827ef7cbd7168b2a21b32a1777c098a | [
"MIT"
] | 1 | 2020-09-28T16:27:35.000Z | 2020-09-28T16:27:35.000Z | #ifndef MRBMACS_FRAME_DIALOG_H
#define MRBMACS_FRAME_DIALOG_H
void mrb_mrbmacs_gtk_frame_dialog_init(mrb_state *mrb);
#endif /* MRBMACS_FRAME_DIALOG_H */
| 22.285714 | 55 | 0.846154 |
ce64df1530217c82c8b535f84b696a263b45c0ec | 23,620 | h | C | wled00/audio_reactive.h | southseaboy/WLED | 6cf2352121655ea2df6bf8d3df19ae80ef918efb | [
"MIT"
] | null | null | null | wled00/audio_reactive.h | southseaboy/WLED | 6cf2352121655ea2df6bf8d3df19ae80ef918efb | [
"MIT"
] | null | null | null | wled00/audio_reactive.h | southseaboy/WLED | 6cf2352121655ea2df6bf8d3df19ae80ef918efb | [
"MIT"
] | null | null | null | /*
* This file allows you to add own functionality to WLED more easily
* See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality
* EEPROM bytes 2750+ are reserved for your custom use case. (if you extend #define EEPSIZE in const.h)
* bytes 2400+ are currently ununsed, but might be used for future wled features
*/
// WARNING Sound reactive variables that are used by the animations or other asynchronous routines must NOT
// have interim values, but only updated in a single calculation. These are:
//
// sample sampleAvg sampleAgc samplePeak myVals[]
//
// fftBin[] fftResult[] FFT_MajorPeak FFT_Magnitude
//
// Otherwise, the animations may asynchronously read interim values of these variables.
//
#include "wled.h"
#include <driver/i2s.h>
#include "audio_source.h"
AudioSource *audioSource;
// ALL AUDIO INPUT PINS DEFINED IN wled.h AND CONFIGURABLE VIA UI
// Comment/Uncomment to toggle usb serial debugging
// #define SR_DEBUG
#ifdef SR_DEBUG
#define DEBUGSR_PRINT(x) Serial.print(x)
#define DEBUGSR_PRINTLN(x) Serial.println(x)
#define DEBUGSR_PRINTF(x...) Serial.printf(x)
#else
#define DEBUGSR_PRINT(x)
#define DEBUGSR_PRINTLN(x)
#define DEBUGSR_PRINTF(x...)
#endif
// #define MIC_LOGGER
// #define MIC_SAMPLING_LOG
// #define FFT_SAMPLING_LOG
//#define MAJORPEAK_SUPPRESS_NOISE // define to activate a dirty hack that ignores the lowest + hightest FFT bins
const i2s_port_t I2S_PORT = I2S_NUM_0;
const int BLOCK_SIZE = 128;
const int SAMPLE_RATE = 10240; // Base sample rate in Hz
//Use userVar0 and userVar1 (API calls &U0=,&U1=, uint16_t)
#ifndef LED_BUILTIN // Set LED_BUILTIN if it is not defined by Arduino framework
#define LED_BUILTIN 3
#endif
#define UDP_SYNC_HEADER "00001"
uint8_t maxVol = 10; // Reasonable value for constant volume for 'peak detector', as it won't always trigger
uint8_t binNum; // Used to select the bin for FFT based beat detection.
uint8_t targetAgc = 60; // This is our setPoint at 20% of max for the adjusted output
uint8_t myVals[32]; // Used to store a pile of samples because WLED frame rate and WLED sample rate are not synchronized. Frame rate is too low.
bool samplePeak = 0; // Boolean flag for peak. Responding routine must reset this flag
bool udpSamplePeak = 0; // Boolean flag for peak. Set at the same tiem as samplePeak, but reset by transmitAudioData
int delayMs = 10; // I don't want to sample too often and overload WLED
int micIn; // Current sample starts with negative values and large values, which is why it's 16 bit signed
int sample; // Current sample. Must only be updated ONCE!!!
int tmpSample; // An interim sample variable used for calculatioins.
int sampleAdj; // Gain adjusted sample value
int sampleAgc; // Our AGC sample
uint16_t micData; // Analog input for FFT
uint16_t micDataSm; // Smoothed mic data, as it's a bit twitchy
long timeOfPeak = 0;
long lastTime = 0;
float micLev = 0; // Used to convert returned value to have '0' as minimum. A leveller
float multAgc; // sample * multAgc = sampleAgc. Our multiplier
float sampleAvg = 0; // Smoothed Average
double beat = 0; // beat Detection
float expAdjF; // Used for exponential filter.
float weighting = 0.2; // Exponential filter weighting. Will be adjustable in a future release.
// FFT Variables
const uint16_t samples = 512; // This value MUST ALWAYS be a power of 2
unsigned int sampling_period_us;
unsigned long microseconds;
double FFT_MajorPeak = 0;
double FFT_Magnitude = 0;
uint16_t mAvg = 0;
// These are the input and output vectors. Input vectors receive computed results from FFT.
double vReal[samples];
double vImag[samples];
double fftBin[samples];
// Try and normalize fftBin values to a max of 4096, so that 4096/16 = 256.
// Oh, and bins 0,1,2 are no good, so we'll zero them out.
double fftCalc[16];
int fftResult[16]; // Our calculated result table, which we feed to the animations.
double fftResultMax[16]; // A table used for testing to determine how our post-processing is working.
float fftAvg[16];
// Table of linearNoise results to be multiplied by soundSquelch in order to reduce squelch across fftResult bins.
int linearNoise[16] = { 34, 28, 26, 25, 20, 12, 9, 6, 4, 4, 3, 2, 2, 2, 2, 2 };
// Table of multiplication factors so that we can even out the frequency response.
double fftResultPink[16] = {1.70,1.71,1.73,1.78,1.68,1.56,1.55,1.63,1.79,1.62,1.80,2.06,2.47,3.35,6.83,9.55};
struct audioSyncPacket {
char header[6] = UDP_SYNC_HEADER;
uint8_t myVals[32]; // 32 Bytes
int sampleAgc; // 04 Bytes
int sample; // 04 Bytes
float sampleAvg; // 04 Bytes
bool samplePeak; // 01 Bytes
uint8_t fftResult[16]; // 16 Bytes
double FFT_Magnitude; // 08 Bytes
double FFT_MajorPeak; // 08 Bytes
};
double mapf(double x, double in_min, double in_max, double out_min, double out_max);
bool isValidUdpSyncVersion(char header[6]) {
if (strncmp(header, UDP_SYNC_HEADER, 6) == 0) {
return true;
} else {
return false;
}
}
void getSample() {
static long peakTime;
//extern double FFT_Magnitude; // Optional inclusion for our volume routines // COMMENTED OUT - UNUSED VARIABLE COMPILER WARNINGS
//extern double FFT_MajorPeak; // Same here. Not currently used though // COMMENTED OUT - UNUSED VARIABLE COMPILER WARNINGS
#ifdef WLED_DISABLE_SOUND
micIn = inoise8(millis(), millis()); // Simulated analog read
#else
micIn = micDataSm; // micDataSm = ((micData * 3) + micData)/4;
/*---------DEBUG---------*/
DEBUGSR_PRINT("micIn:\tmicData:\tmicIn>>2:\tmic_In_abs:\tsample:\tsampleAdj:\tsampleAvg:\n");
DEBUGSR_PRINT(micIn); DEBUGSR_PRINT("\t"); DEBUGSR_PRINT(micData);
/*-------END DEBUG-------*/
// We're still using 10 bit, but changing the analog read resolution in usermod.cpp
// if (digitalMic == false) micIn = micIn >> 2; // ESP32 has 2 more bits of A/D than ESP8266, so we need to normalize to 10 bit.
/*---------DEBUG---------*/
DEBUGSR_PRINT("\t\t"); DEBUGSR_PRINT(micIn);
/*-------END DEBUG-------*/
#endif
micLev = ((micLev * 31) + micIn) / 32; // Smooth it out over the last 32 samples for automatic centering
micIn -= micLev; // Let's center it to 0 now
/*---------DEBUG---------*/
DEBUGSR_PRINT("\t\t"); DEBUGSR_PRINT(micIn);
/*-------END DEBUG-------*/
// Using an exponential filter to smooth out the signal. We'll add controls for this in a future release.
expAdjF = (weighting * micIn + (1.0-weighting) * expAdjF);
expAdjF = (expAdjF <= soundSquelch) ? 0: expAdjF;
expAdjF = fabs(expAdjF); // Now (!) take the absolute value
tmpSample = (int)expAdjF;
/*---------DEBUG---------*/
DEBUGSR_PRINT("\t\t"); DEBUGSR_PRINT(sample);
/*-------END DEBUG-------*/
micIn = abs(micIn); // And get the absolute value of each sample
sampleAdj = tmpSample * sampleGain / 40 + tmpSample / 16; // Adjust the gain.
sampleAdj = min(sampleAdj, 255); // Question: why are we limiting the value to 8 bits ???
sample = sampleAdj; // ONLY update sample ONCE!!!!
sampleAvg = ((sampleAvg * 15) + sample) / 16; // Smooth it out over the last 16 samples.
/*---------DEBUG---------*/
DEBUGSR_PRINT("\t"); DEBUGSR_PRINT(sample);
DEBUGSR_PRINT("\t\t"); DEBUGSR_PRINT(sampleAvg); DEBUGSR_PRINT("\n\n");
/*-------END DEBUG-------*/
// Fixes private class variable compiler error. Unsure if this is the correct way of fixing the root problem. -THATDONFC
uint16_t MinShowDelay = strip.getMinShowDelay();
if (millis() - timeOfPeak > MinShowDelay) { // Auto-reset of samplePeak after a complete frame has passed.
samplePeak = 0;
udpSamplePeak = 0;
}
if (userVar1 == 0) samplePeak = 0;
// Poor man's beat detection by seeing if sample > Average + some value.
// Serial.print(binNum); Serial.print("\t"); Serial.print(fftBin[binNum]); Serial.print("\t"); Serial.print(fftAvg[binNum/16]); Serial.print("\t"); Serial.print(maxVol); Serial.print("\t"); Serial.println(samplePeak);
if ((fftBin[binNum] > maxVol) && (millis() > (peakTime + 100))) { // This goe through ALL of the 255 bins
// if (sample > (sampleAvg + maxVol) && millis() > (peakTime + 200)) {
// Then we got a peak, else we don't. The peak has to time out on its own in order to support UDP sound sync.
samplePeak = 1;
timeOfPeak = millis();
udpSamplePeak = 1;
userVar1 = samplePeak;
peakTime=millis();
}
} // getSample()
/*
* A simple averaging multiplier to automatically adjust sound sensitivity.
*/
/*
* A simple, but hairy, averaging multiplier to automatically adjust sound sensitivity.
* not sure if not sure "sample" or "sampleAvg" is the correct input signal for AGC
*/
void agcAvg() {
float lastMultAgc = multAgc;
float tmpAgc;
if(fabs(sampleAvg) < 2.0) {
tmpAgc = sampleAvg; // signal below squelch -> deliver silence
multAgc = multAgc * 0.95; // slightly decrease gain multiplier
} else {
multAgc = (sampleAvg < 1) ? targetAgc : targetAgc / sampleAvg; // Make the multiplier so that sampleAvg * multiplier = setpoint
}
if (multAgc < 0.5) multAgc = 0.5; // signal higher than 2*setpoint -> don't reduce it further
multAgc = (lastMultAgc*127.0 +multAgc) / 128.0; //apply some filtering to gain multiplier -> smoother transitions
tmpAgc = (float)sample * multAgc; // apply gain to signal
if (tmpAgc <= (soundSquelch*1.2)) tmpAgc = sample; // check against squelch threshold - increased by 20% to avoid artefacts (ripples)
if (tmpAgc > 255) tmpAgc = 255;
sampleAgc = tmpAgc; // ONLY update sampleAgc ONCE because it's used elsewhere asynchronously!!!!
userVar0 = sampleAvg * 4;
if (userVar0 > 255) userVar0 = 255;
} // agcAvg()
////////////////////
// Begin FFT Code //
////////////////////
#include "arduinoFFT.h"
void transmitAudioData() {
if (!udpSyncConnected) return;
extern uint8_t myVals[];
extern int sampleAgc;
extern int sample;
extern float sampleAvg;
extern bool udpSamplePeak;
extern int fftResult[];
extern double FFT_Magnitude;
extern double FFT_MajorPeak;
audioSyncPacket transmitData;
for (int i = 0; i < 32; i++) {
transmitData.myVals[i] = myVals[i];
}
transmitData.sampleAgc = sampleAgc;
transmitData.sample = sample;
transmitData.sampleAvg = sampleAvg;
transmitData.samplePeak = udpSamplePeak;
udpSamplePeak = 0; // Reset udpSamplePeak after we've transmitted it
for (int i = 0; i < 16; i++) {
transmitData.fftResult[i] = (uint8_t)constrain(fftResult[i], 0, 254);
}
transmitData.FFT_Magnitude = FFT_Magnitude;
transmitData.FFT_MajorPeak = FFT_MajorPeak;
fftUdp.beginMulticastPacket();
fftUdp.write(reinterpret_cast<uint8_t *>(&transmitData), sizeof(transmitData));
fftUdp.endPacket();
return;
} // transmitAudioData()
// Create FFT object
arduinoFFT FFT = arduinoFFT( vReal, vImag, samples, SAMPLE_RATE );
double fftAdd( int from, int to) {
int i = from;
double result = 0;
while ( i <= to) {
result += fftBin[i++];
}
return result;
}
// FFT main code
void FFTcode( void * parameter) {
DEBUG_PRINT("FFT running on core: "); DEBUG_PRINTLN(xPortGetCoreID());
#ifdef MAJORPEAK_SUPPRESS_NOISE
static double xtemp[24] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
#endif
for(;;) {
delay(1); // DO NOT DELETE THIS LINE! It is needed to give the IDLE(0) task enough time and to keep the watchdog happy.
// taskYIELD(), yield(), vTaskDelay() and esp_task_wdt_feed() didn't seem to work.
// Only run the FFT computing code if we're not in Receive mode
if (audioSyncEnabled & (1 << 1))
continue;
audioSource->getSamples(vReal, samples);
// old code - Last sample in vReal is our current mic sample
//micDataSm = (uint16_t)vReal[samples - 1]; // will do a this a bit later
// micDataSm = ((micData * 3) + micData)/4;
double maxSample = 0.0;
for (int i=0; i < samples; i++)
{
// set imaginary parts to 0
vImag[i] = 0;
// pick our our current mic sample - we take the max value from all samples that go into FFT
if ((vReal[i] <= (INT16_MAX - 1024)) && (vReal[i] >= (INT16_MIN + 1024))) //skip extreme values - normally these are artefacts
{
if (fabs(vReal[i]) > maxSample) maxSample = fabs(vReal[i]);
}
}
micDataSm = (uint16_t)maxSample;
FFT.DCRemoval(); // let FFT lib remove DC component, so we don't need to care about this in getSamples()
//FFT.Windowing( FFT_WIN_TYP_HAMMING, FFT_FORWARD ); // Weigh data - standard Hamming window
//FFT.Windowing( FFT_WIN_TYP_BLACKMAN, FFT_FORWARD ); // Blackman window - better side freq rejection
//FFT.Windowing( FFT_WIN_TYP_BLACKMAN_HARRIS, FFT_FORWARD );// Blackman-Harris - excellent sideband rejection
FFT.Windowing( FFT_WIN_TYP_FLT_TOP, FFT_FORWARD ); // Flat Top Window - better amplitude accuracy
FFT.Compute( FFT_FORWARD ); // Compute FFT
FFT.ComplexToMagnitude(); // Compute magnitudes
//
// vReal[3 .. 255] contain useful data, each a 20Hz interval (60Hz - 5120Hz).
// There could be interesting data at bins 0 to 2, but there are too many artifacts.
//
#ifdef MAJORPEAK_SUPPRESS_NOISE
// teporarily reduce signal strength in the highest + lowest bins
xtemp[0] = vReal[0]; vReal[0] *= 0.005;
xtemp[1] = vReal[1]; vReal[1] *= 0.005;
xtemp[2] = vReal[2]; vReal[2] *= 0.005;
xtemp[3] = vReal[3]; vReal[3] *= 0.02;
xtemp[4] = vReal[4]; vReal[4] *= 0.02;
xtemp[5] = vReal[5]; vReal[5] *= 0.02;
xtemp[6] = vReal[6]; vReal[6] *= 0.05;
xtemp[7] = vReal[7]; vReal[7] *= 0.08;
xtemp[8] = vReal[8]; vReal[8] *= 0.1;
xtemp[9] = vReal[9]; vReal[9] *= 0.2;
xtemp[10] = vReal[10]; vReal[10] *= 0.2;
xtemp[11] = vReal[11]; vReal[11] *= 0.25;
xtemp[12] = vReal[12]; vReal[12] *= 0.3;
xtemp[13] = vReal[13]; vReal[13] *= 0.3;
xtemp[14] = vReal[14]; vReal[14] *= 0.4;
xtemp[15] = vReal[15]; vReal[15] *= 0.4;
xtemp[16] = vReal[16]; vReal[16] *= 0.4;
xtemp[17] = vReal[17]; vReal[17] *= 0.5;
xtemp[18] = vReal[18]; vReal[18] *= 0.5;
xtemp[19] = vReal[19]; vReal[19] *= 0.6;
xtemp[20] = vReal[20]; vReal[20] *= 0.7;
xtemp[21] = vReal[21]; vReal[21] *= 0.8;
xtemp[22] = vReal[samples-2]; vReal[samples-2] =0.0;
xtemp[23] = vReal[samples-1]; vReal[samples-1] =0.0;
#endif
FFT.MajorPeak(&FFT_MajorPeak, &FFT_Magnitude); // let the effects know which freq was most dominant
#ifdef MAJORPEAK_SUPPRESS_NOISE
// dirty hack: limit suppressed channel intensities to FFT_Magnitude
for (int k=0; k < 24; k++) if(xtemp[k] > FFT_Magnitude) xtemp[k] = FFT_Magnitude;
// restore bins
vReal[0] = xtemp[0];
vReal[1] = xtemp[1];
vReal[2] = xtemp[2];
vReal[3] = xtemp[3];
vReal[4] = xtemp[4];
vReal[5] = xtemp[5];
vReal[6] = xtemp[6];
vReal[7] = xtemp[7];
vReal[8] = xtemp[8];
vReal[9] = xtemp[9];
vReal[10] = xtemp[10];
vReal[11] = xtemp[11];
vReal[12] = xtemp[12];
vReal[13] = xtemp[13];
vReal[14] = xtemp[14];
vReal[15] = xtemp[15];
vReal[16] = xtemp[16];
vReal[17] = xtemp[17];
vReal[18] = xtemp[18];
vReal[19] = xtemp[19];
vReal[20] = xtemp[20];
vReal[21] = xtemp[21];
vReal[samples-2] = xtemp[22];
vReal[samples-1] = xtemp[23];
#endif
for (int i = 0; i < samples; i++) { // Values for bins 0 and 1 are WAY too large. Might as well start at 3.
double t = 0.0;
t = fabs(vReal[i]); // just to be sure - values in fft bins should be positive any way
t = t / 16.0; // Reduce magnitude. Want end result to be linear and ~4096 max.
fftBin[i] = t;
} // for()
/* This FFT post processing is a DIY endeavour. What we really need is someone with sound engineering expertise to do a great job here AND most importantly, that the animations look GREAT as a result.
*
*
* Andrew's updated mapping of 256 bins down to the 16 result bins with Sample Freq = 10240, samples = 512 and some overlap.
* Based on testing, the lowest/Start frequency is 60 Hz (with bin 3) and a highest/End frequency of 5120 Hz in bin 255.
* Now, Take the 60Hz and multiply by 1.320367784 to get the next frequency and so on until the end. Then detetermine the bins.
* End frequency = Start frequency * multiplier ^ 16
* Multiplier = (End frequency/ Start frequency) ^ 1/16
* Multiplier = 1.320367784
*/
// Range
fftCalc[0] = (fftAdd(3,4)) /2; // 60 - 100
fftCalc[1] = (fftAdd(4,5)) /2; // 80 - 120
fftCalc[2] = (fftAdd(5,7)) /3; // 100 - 160
fftCalc[3] = (fftAdd(7,9)) /3; // 140 - 200
fftCalc[4] = (fftAdd(9,12)) /4; // 180 - 260
fftCalc[5] = (fftAdd(12,16)) /5; // 240 - 340
fftCalc[6] = (fftAdd(16,21)) /6; // 320 - 440
fftCalc[7] = (fftAdd(21,28)) /8; // 420 - 600
fftCalc[8] = (fftAdd(29,37)) /10; // 580 - 760
fftCalc[9] = (fftAdd(37,48)) /12; // 740 - 980
fftCalc[10] = (fftAdd(48,64)) /17; // 960 - 1300
fftCalc[11] = (fftAdd(64,84)) /21; // 1280 - 1700
fftCalc[12] = (fftAdd(84,111)) /28; // 1680 - 2240
fftCalc[13] = (fftAdd(111,147)) /37; // 2220 - 2960
fftCalc[14] = (fftAdd(147,194)) /48; // 2940 - 3900
fftCalc[15] = (fftAdd(194, 255)) /62; // 3880 - 5120
// Noise supression of fftCalc bins using soundSquelch adjustment for different input types.
for (int i=0; i < 16; i++) {
fftCalc[i] = fftCalc[i]-(float)soundSquelch*(float)linearNoise[i]/4.0 <= 0? 0 : fftCalc[i];
}
// Adjustment for frequency curves.
for (int i=0; i < 16; i++) {
fftCalc[i] = fftCalc[i] * fftResultPink[i];
}
// Manual linear adjustment of gain using sampleGain adjustment for different input types.
for (int i=0; i < 16; i++) {
fftCalc[i] = fftCalc[i] * sampleGain / 40 + fftCalc[i]/16.0;
}
// Now, let's dump it all into fftResult. Need to do this, otherwise other routines might grab fftResult values prematurely.
for (int i=0; i < 16; i++) {
// fftResult[i] = (int)fftCalc[i];
fftResult[i] = constrain((int)fftCalc[i],0,254); // question: why do we constrain values to 8bit here ???
fftAvg[i] = (float)fftResult[i]*.05 + (1-.05)*fftAvg[i];
}
// Looking for fftResultMax for each bin using Pink Noise
// for (int i=0; i<16; i++) {
// fftResultMax[i] = ((fftResultMax[i] * 63.0) + fftResult[i]) / 64.0;
// Serial.print(fftResultMax[i]*fftResultPink[i]); Serial.print("\t");
// }
// Serial.println(" ");
} // for(;;)
} // FFTcode()
void logAudio() {
#ifdef MIC_LOGGER
//Serial.print("micData:"); Serial.print(micData); Serial.print("\t");
//Serial.print("micDataSm:"); Serial.print(micDataSm); Serial.print("\t");
//Serial.print("micIn:"); Serial.print(micIn); Serial.print("\t");
//Serial.print("micLev:"); Serial.print(micLev); Serial.print("\t");
Serial.print("sample:"); Serial.print(sample); Serial.print("\t");
//Serial.print("sampleAvg:"); Serial.print(sampleAvg); Serial.print("\t");
//Serial.print("multAgc:"); Serial.print(multAgc); Serial.print("\t");
Serial.print("sampleAgc:"); Serial.print(sampleAgc); Serial.print("\t");
Serial.println(" ");
#endif
#ifdef MIC_SAMPLING_LOG
//------------ Oscilloscope output ---------------------------
Serial.print(targetAgc); Serial.print(" ");
Serial.print(multAgc); Serial.print(" ");
Serial.print(sampleAgc); Serial.print(" ");
Serial.print(sample); Serial.print(" ");
Serial.print(sampleAvg); Serial.print(" ");
Serial.print(micLev); Serial.print(" ");
Serial.print(samplePeak); Serial.print(" "); //samplePeak = 0;
Serial.print(micIn); Serial.print(" ");
Serial.print(100); Serial.print(" ");
Serial.print(0); Serial.print(" ");
Serial.println(" ");
#endif
#ifdef FFT_SAMPLING_LOG
#if 0
for(int i=0; i<16; i++) {
Serial.print(fftResult[i]);
Serial.print("\t");
}
Serial.println("");
#endif
// OPTIONS are in the following format: Description \n Option
//
// Set true if wanting to see all the bands in their own vertical space on the Serial Plotter, false if wanting to see values in Serial Monitor
const bool mapValuesToPlotterSpace = false;
// Set true to apply an auto-gain like setting to to the data (this hasn't been tested recently)
const bool scaleValuesFromCurrentMaxVal = false;
// prints the max value seen in the current data
const bool printMaxVal = false;
// prints the min value seen in the current data
const bool printMinVal = false;
// if !scaleValuesFromCurrentMaxVal, we scale values from [0..defaultScalingFromHighValue] to [0..scalingToHighValue], lower this if you want to see smaller values easier
const int defaultScalingFromHighValue = 256;
// Print values to terminal in range of [0..scalingToHighValue] if !mapValuesToPlotterSpace, or [(i)*scalingToHighValue..(i+1)*scalingToHighValue] if mapValuesToPlotterSpace
const int scalingToHighValue = 256;
// set higher if using scaleValuesFromCurrentMaxVal and you want a small value that's also the current maxVal to look small on the plotter (can't be 0 to avoid divide by zero error)
const int minimumMaxVal = 1;
int maxVal = minimumMaxVal;
int minVal = 0;
for(int i = 0; i < 16; i++) {
if(fftResult[i] > maxVal) maxVal = fftResult[i];
if(fftResult[i] < minVal) minVal = fftResult[i];
}
for(int i = 0; i < 16; i++) {
Serial.print(i); Serial.print(":");
Serial.printf("%04d ", map(fftResult[i], 0, (scaleValuesFromCurrentMaxVal ? maxVal : defaultScalingFromHighValue), (mapValuesToPlotterSpace*i*scalingToHighValue)+0, (mapValuesToPlotterSpace*i*scalingToHighValue)+scalingToHighValue-1));
}
if(printMaxVal) {
Serial.printf("maxVal:%04d ", maxVal + (mapValuesToPlotterSpace ? 16*256 : 0));
}
if(printMinVal) {
Serial.printf("%04d:minVal ", minVal); // printed with value first, then label, so negative values can be seen in Serial Monitor but don't throw off y axis in Serial Plotter
}
if(mapValuesToPlotterSpace)
Serial.printf("max:%04d ", (printMaxVal ? 17 : 16)*256); // print line above the maximum value we expect to see on the plotter to avoid autoscaling y axis
else
Serial.printf("max:%04d ", 256);
Serial.println();
#endif // FFT_SAMPLING_LOG
} // logAudio()
| 42.789855 | 239 | 0.624217 |
e1b45585841b7959ad9c44a7acd5273102ab4c1b | 2,671 | h | C | ietf/rtp3640.h | larixsoft/bitstream | e9408996e7557e4a6b9f8e2e7ea1b1cb959bf837 | [
"MIT"
] | 48 | 2018-02-02T04:33:06.000Z | 2022-03-13T03:26:35.000Z | ietf/rtp3640.h | larixsoft/bitstream | e9408996e7557e4a6b9f8e2e7ea1b1cb959bf837 | [
"MIT"
] | 8 | 2018-03-14T21:44:26.000Z | 2021-11-15T17:56:42.000Z | ietf/rtp3640.h | larixsoft/bitstream | e9408996e7557e4a6b9f8e2e7ea1b1cb959bf837 | [
"MIT"
] | 36 | 2018-03-14T16:04:26.000Z | 2022-03-07T10:27:47.000Z | /*****************************************************************************
* rtp3640.h: RTP Payload Format for Transport of MPEG-4 Elementary Streams
*****************************************************************************
* Copyright (C) 2017 VideoLAN
*
* Authors: Christophe Massiot
*
* 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.
*****************************************************************************/
/*
* Normative references:
* - IETF RFC 3640 RTP Payload Format for Transport of MPEG-4 ES
*/
#ifndef __BITSTREAM_IETF_RTP3640_H__
# define __BITSTREAM_IETF_RTP3640_H__
#include <stdint.h>
#ifdef __cplusplus
extern "C"
{
#endif
#define RTP3640_AU_HEADERS_LENGTH_SIZE 2
#define RTP3640_AU_HEADER_AAC_HBR_SIZE 2
static inline void rtp3640_set_au_headers_length(uint8_t *header, uint16_t size)
{
header[0] = size >> 8;
header[1] = size & 0xff;
}
static inline uint16_t rtp3640_get_au_headers_length(const uint8_t *header)
{
return (header[0] << 8) | header[1];
}
static inline void rtp3640_set_aac_hbr_au_size(uint8_t *header, uint16_t size)
{
header[0] = (size >> 5) & 0xff;
header[1] &= ~0xf8;
header[1] |= (size << 3) & 0xf8;
}
static inline uint16_t rtp3640_get_aac_hbr_au_size(const uint8_t *header)
{
return (header[0] << 5) | (header[1] >> 3);
}
static inline void rtp3640_set_aac_hbr_au_index(uint8_t *header, uint8_t index)
{
header[1] &= ~0x7;
header[1] |= index & 0x7;
}
static inline uint8_t rtp3640_get_aac_hbr_au_index(const uint8_t *header)
{
return (header[1] & 0x7);
}
#ifdef __cplusplus
}
#endif
#endif /* !__BITSTREAM_IETF_RTP3640_H__ */
| 31.05814 | 80 | 0.672033 |
e1d65fb1ecd883e9abf159258e611d3119fef4a4 | 259 | c | C | structure/struct6_nest.c | 1432junaid/c-classes | af2546123db0ce07fdcf2f19e1ee6eeae373b079 | [
"MIT"
] | null | null | null | structure/struct6_nest.c | 1432junaid/c-classes | af2546123db0ce07fdcf2f19e1ee6eeae373b079 | [
"MIT"
] | null | null | null | structure/struct6_nest.c | 1432junaid/c-classes | af2546123db0ce07fdcf2f19e1ee6eeae373b079 | [
"MIT"
] | null | null | null | #include<stdio.h>
int main(){
struct student{
char *name;
int age;
struct lcation{
char *city;
char *country;
}loc;
}st;
st.name="sariya";
st.age=12;
st.loc.city="lucknow";
st.loc.country="India";
printf("%s\n",st.loc.country);
return 0;
}
| 12.333333 | 30 | 0.629344 |
6d82c17767b8be9fc0ae8956517131bc19477671 | 7,960 | h | C | C++/scope/math/SO3.h | fantaosha/SCOPE | 30519b52822d04fb7b5bf6f45e73227ad4260738 | [
"MIT"
] | 26 | 2021-10-10T18:34:38.000Z | 2022-03-03T03:00:40.000Z | C++/scope/math/SO3.h | fantaosha/SCOPE | 30519b52822d04fb7b5bf6f45e73227ad4260738 | [
"MIT"
] | 3 | 2021-12-24T07:28:11.000Z | 2022-02-02T21:26:55.000Z | C++/scope/math/SO3.h | fantaosha/SCOPE | 30519b52822d04fb7b5bf6f45e73227ad4260738 | [
"MIT"
] | 7 | 2021-11-06T15:23:08.000Z | 2022-02-28T03:40:03.000Z | #pragma once
#include <scope/base/Types.h>
#include <Eigen/Dense>
namespace scope {
namespace math {
struct SO3 {
typedef Matrix3 LieGroup;
typedef Vector3 LieAlgebra;
template <typename T1, typename T2>
static void exp(Eigen::MatrixBase<T1> const &w, Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T1, 3)
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T2, 3, 3)
Scalar const th = w.stableNorm();
LieAlgebra s = w;
if (th < 5e-2) {
Scalar c, d, th2, th4, th6, d2, thd2;
th2 = th * th;
th4 = th2 * th2;
th6 = th4 * th2;
d = 1 + th2 / 12 + th4 / 120 + th6 / 1185.88235294117647058823529412;
d2 = d * d;
thd2 = th2 * d2;
c = 2 / (4 + thd2);
s *= c * d2;
res.noalias() = s * w.transpose();
res.diagonal().array() += 1 - c * thd2;
s *= 2 / d;
} else {
// use exponential map
Scalar sth, cth;
fsincos(th, &sth, &cth);
s /= th;
res.noalias() = (1 - cth) * s * s.transpose();
res.diagonal().array() += cth;
s *= sth;
}
res(0, 1) -= s[2];
res(1, 0) += s[2];
res(0, 2) += s[1];
res(2, 0) -= s[1];
res(1, 2) -= s[0];
res(2, 1) += s[0];
}
template <typename T1, typename T2>
static void log(Eigen::MatrixBase<T1> const &R, Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T1, 3, 3)
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T2, 3)
Scalar const tr = R.trace() + 1;
if (fabs(tr) < 1e-9) {
// theta = pi and use eigenvalue decomposition
if (R(0, 0) > R(1, 1)) {
if (R(0, 0) > R(2, 2)) {
res[0] = std::sqrt((R(0, 0) + 1));
res[1] = R(1, 0) / res[0];
res[2] = R(2, 0) / res[0];
} else {
res[2] = std::sqrt((R(2, 2) + 1));
res[0] = R(0, 2) / res[2];
res[1] = R(1, 2) / res[2];
}
} else {
if (R(1, 1) > R(2, 2)) {
res[1] = std::sqrt((R(1, 1) + 1));
res[0] = R(0, 1) / res[1];
res[2] = R(2, 1) / res[1];
} else {
res[2] = std::sqrt((R(2, 2) + 1));
res[0] = R(0, 2) / res[2];
res[1] = R(1, 2) / res[2];
}
}
res *= 2.221441469079183; // multiplied by pi/sqrt(2)
} else {
res(0) = R(2, 1) - R(1, 2);
res(1) = R(0, 2) - R(2, 0);
res(2) = R(1, 0) - R(0, 1);
if (tr > INVERSE_OF_RETRACT_TOL) {
// use cayley map when th is small for fast approximation
// res *= 2 / (1.0 + tr);
res *= (3.0666666666666669 * tr - 5.8666666666666663 +
6.4000000000000004 / tr) /
(tr * tr);
} else {
// use exponential map
Scalar const th = acos((tr - 2) / 2);
res *= 0.5 * th / sin(th);
}
}
}
template <typename T1, typename T2>
static void dexp(Eigen::MatrixBase<T1> const &w, Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T1, 3)
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T2, 3, 3)
Scalar const th = w.stableNorm();
LieAlgebra s = w;
if (th < 5e-2) {
// use second-order taylor expansion when th is small for fast
// approximation relative approx. error <= 1e-6 for DRETRACT_TOL = 0.1 rad
Scalar th2 = th * th;
Scalar c = 0.166666666666667 - th2 / 120;
res.noalias() = c * w * w.transpose();
res.diagonal().array() += 1 - c * th2;
s *= 0.5 - th2 / 24.0;
} else {
// use exponential map
Scalar sth, cth, th2, th3;
fsincos(th, &sth, &cth);
th2 = th * th;
th3 = th2 * th;
res.noalias() = (th - sth) / th3 * s *
s.transpose(); // (th-sth)/th^3 -> 1/6 as th -> 0
res.diagonal().array() += sth / th;
s *= (1 - cth) / th2; // (1-cth)/th^2 -> 1/2 as th -> 0
}
res(0, 1) -= s[2];
res(1, 0) += s[2];
res(0, 2) += s[1];
res(2, 0) -= s[1];
res(1, 2) -= s[0];
res(2, 1) += s[0];
}
template <typename T1, typename T2>
static void dexpinv(Eigen::MatrixBase<T1> const &w,
Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T1, 3)
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T2, 3, 3)
Scalar const th = w.stableNorm();
LieAlgebra s = w;
if (th < 5e-2) {
// use cayley map when th is small for fast approximation
Scalar th2 = th * th;
Scalar c = 0.333333333333333 + th2 / 180;
s *= -0.5;
res.noalias() = c * s * s.transpose();
res.diagonal().array() += 1 - 0.25 * c * th2;
} else {
// use exponential map
Scalar sth, cth;
fsincos(th, &sth, &cth);
sth *= th;
cth = 2 * cth - 2;
res.noalias() = (sth + cth) / (th * th * cth) * s * s.transpose();
res.diagonal().array() -= sth / cth;
s *= -0.5;
}
res(0, 1) -= s[2];
res(1, 0) += s[2];
res(0, 2) += s[1];
res(2, 0) -= s[1];
res(1, 2) -= s[0];
res(2, 1) += s[0];
}
template <typename T1, typename T2>
static void cay(Eigen::MatrixBase<T1> const &w, Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T1, 3)
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T2, 3, 3)
Scalar const th = w.stableNorm();
LieAlgebra s = w;
// using cayley map
s *= 2 / (4 + th * th);
res.noalias() = s * w.transpose();
res.diagonal().array() += 1 - s.dot(w);
s *= 2;
res(0, 1) -= s[2];
res(1, 0) += s[2];
res(0, 2) += s[1];
res(2, 0) -= s[1];
res(1, 2) -= s[0];
res(2, 1) += s[0];
}
template <typename T1, typename T2>
static void cayinv(Eigen::MatrixBase<T1> const &R,
Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T1, 3, 3)
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T2, 3)
Scalar const tr = R.trace();
res(0) = R(2, 1) - R(1, 2);
res(1) = R(0, 2) - R(2, 0);
res(2) = R(1, 0) - R(0, 1);
res /= 2 / (1.0 + tr);
}
template <typename T1, typename T2>
static void dcay(Eigen::MatrixBase<T1> const &w, Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T1, 3)
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T2, 3, 3)
Scalar const th = w.stableNorm();
LieAlgebra s = w;
Scalar c = 2 / (4 + th * th);
s *= c;
res.diagonal().array() = 2 * c;
res(0, 1) = -s[2];
res(1, 0) = s[2];
res(0, 2) = s[1];
res(2, 0) = -s[1];
res(1, 2) = -s[0];
res(2, 1) = s[0];
}
template <typename T1, typename T2>
static void dcayinv(Eigen::MatrixBase<T1> const &w,
Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T1, 3)
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T2, 3, 3)
Scalar const th = w.stableNorm();
LieAlgebra s = w;
s *= -0.5;
res.noalias() = s * s.transpose();
res.diagonal().array() += 1 - 0.25 * th;
res(0, 1) -= s[2];
res(1, 0) += s[2];
res(0, 2) += s[1];
res(2, 0) -= s[1];
res(1, 2) -= s[0];
res(2, 1) += s[0];
}
template <typename T1, typename T2>
static void Rot2XYZ(Eigen::MatrixBase<T1> const &R,
Eigen::MatrixBase<T2> &res) {
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(T1, 3, 3)
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(T2, 3)
if (1 - fabs(R(0, 2)) >= 5e-11) {
res[0] = atan2(-R(1, 2), R(2, 2));
res[1] = asin(R(0, 2));
res[2] = atan2(-R(0, 1), R(0, 0));
} else {
res[0] = atan2(R(1,0), R(1,1));
res[1] = R(0, 2) > 0 ? 0.5 * M_PI : -0.5 * M_PI;
res[2] = 0;
}
}
static void fsincos(double x, double *sin, double *cos) {
sincos(x, sin, cos);
}
static void fsincos(float x, float *sin, float *cos) { sincosf(x, sin, cos); }
static void fsincos(long double x, long double *sin, long double *cos) {
sincosl(x, sin, cos);
}
};
} // namespace math
} // namespace scope
| 25.11041 | 80 | 0.511432 |
07266660c58f6ff32e426bc546bf1b0235e7bd88 | 641 | h | C | C++/PositionArrangement/PositionArrangement/PositionManager.h | blAs1N/C-programming | 3ab83a00dab6e3d9cfe97c514115308ad2333387 | [
"MIT"
] | 4 | 2018-06-17T11:47:16.000Z | 2018-10-01T14:01:55.000Z | C++/PositionArrangement/PositionArrangement/PositionManager.h | blAs1N/TIL | 3ab83a00dab6e3d9cfe97c514115308ad2333387 | [
"MIT"
] | null | null | null | C++/PositionArrangement/PositionArrangement/PositionManager.h | blAs1N/TIL | 3ab83a00dab6e3d9cfe97c514115308ad2333387 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <array>
#include <string>
class PositionManager {
public:
constexpr const static int MAX_STUDENT = 20;
private:
constexpr const static char* FILE_PATH = "Postion.txt";
constexpr static int INIT_NUMS[MAX_STUDENT] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
};
public:
PositionManager();
void MixPosition();
void AddStudent(const std::string& name);
void DelStudent(const std::string& name);
std::array<std::string, MAX_STUDENT> EnumPosition() const;
private:
void SavePosition();
void LoadPosition();
private:
std::map<std::string, int> students;
};
| 18.314286 | 71 | 0.691108 |
e4bc76246bea7ce7893b1f5a9661693f122549c1 | 369 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/BEEDirectPreviewPickerDelegate-Protocol.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/BEEDirectPreviewPickerDelegate-Protocol.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/BEEDirectPreviewPickerDelegate-Protocol.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 "NSObject-Protocol.h"
@class BEEDirectPreviewPicker;
@protocol BEEDirectPreviewPickerDelegate <NSObject>
- (void)didDismissDirectPicker:(BEEDirectPreviewPicker *)arg1;
@end
| 24.6 | 90 | 0.734417 |
32e67cdab00ca0e75b43ee374093004b710b50d0 | 217 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/pr52134.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/pr52134.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/pr52134.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* { dg-do compile } */
/* { dg-options "-fdump-tree-original" } */
unsigned f(unsigned t)
{
return (t*4)&-4;
}
int f1(int t)
{
return (t*4)&-4;
}
/* { dg-final { scan-tree-dump-not "\\\&" "original" } } */
| 15.5 | 59 | 0.516129 |
25ba097e8d847857a3eb98005bcbef4eca158504 | 1,921 | h | C | capture/ximea-usb3/CamTool/xvpSample/include/xiCore/VideoCodecManager.h | ruedijc/jetson-cam-utils | 29fb26892cc150f9679ad7d5c3220e38f733ab04 | [
"MIT"
] | 3 | 2021-02-28T10:09:54.000Z | 2022-02-24T09:21:18.000Z | capture/ximea-usb3/CamTool/xvpSample/include/xiCore/VideoCodecManager.h | ruedijc/jetson-cam-utils | 29fb26892cc150f9679ad7d5c3220e38f733ab04 | [
"MIT"
] | null | null | null | capture/ximea-usb3/CamTool/xvpSample/include/xiCore/VideoCodecManager.h | ruedijc/jetson-cam-utils | 29fb26892cc150f9679ad7d5c3220e38f733ab04 | [
"MIT"
] | null | null | null | #ifndef VIDEOCODECMANAGER_H
#define VIDEOCODECMANAGER_H
#include <QPair>
#include <QString>
#include <QList>
#include <xiCoreGlobal.h>
#include <VideoEncoder.h>
#include <VideoDecoder.h>
#include <xiRtti.h>
/*!
* \brief The class that manages video codecs used by video loaders and savers.
*/
class XICORE_API CxVideoCodecManager : public QObject
{
Q_OBJECT
public:
static CxVideoCodecManager* instance(); //!< Singleton class, this is the way to obtain the pointer
private:
CxVideoCodecManager();
public:
IxVideoEncoder* encoderForFourCC(TxFourCC fcc);
IxVideoDecoder* decoderForFourCC(TxFourCC fcc);
QList<QPair<TxFourCC, QString> > encoders(); //!< Returns a list of encoders with their FourCCs and names.
QList<QPair<TxFourCC, QString> > decoders(); //!< Returns a list of decoders with their FourCCs and names.
void setCodecOptions(TxFourCC fccCodec, const TxImageFormatOptions &aOpt); //!< set defaults codec
void saveSettings(QSettings *pSettings); //!< store format options to app settings
void loadSettings(QSettings *pSettings); //!< load format options from app settings
private slots:
void onRttiItemEnableStateChanged(TxRttiItem hItem, bool bEnabled); //!< Handle the CxRTTI changes.
private:
struct SxCodecItem
{
QString m_sRttiClass;
QString m_sName; //!< Localized name of the codec.
TxFourCC m_fcc;
};
private:
void resetEncoders();
void resetDecoders();
void loadAvailableEncoders();
void loadAvailableDecoders();
static QString findClassForFourCC(const QList<SxCodecItem>& lstCodecs, TxFourCC fourCC);
private:
bool m_bEncodersLoaded;
bool m_bDecodersLoaded;
QList<SxCodecItem> m_lstEncoders;
QList<SxCodecItem> m_lstDecoders;
QMap<TxFourCC, TxImageFormatOptions> m_mapCodecOptions; //!< maps FourCC of a codec to its options
};
#endif // VIDEOCODECMANAGER_H
| 30.015625 | 110 | 0.732431 |
d302b1550d188eb77f4ab5dd04b20c428798db0d | 586 | h | C | Classes/Networking/TMNetworkActivityIndicatorManager.h | turlodales/TMTumblrSDK | af5fa629a088ead0064f28ec5d611a59c25ca353 | [
"Apache-2.0"
] | 259 | 2015-01-05T08:30:59.000Z | 2022-03-21T06:39:52.000Z | Classes/Networking/TMNetworkActivityIndicatorManager.h | turlodales/TMTumblrSDK | af5fa629a088ead0064f28ec5d611a59c25ca353 | [
"Apache-2.0"
] | 74 | 2015-01-07T18:39:25.000Z | 2021-11-17T08:53:02.000Z | Classes/Networking/TMNetworkActivityIndicatorManager.h | turlodales/TMTumblrSDK | af5fa629a088ead0064f28ec5d611a59c25ca353 | [
"Apache-2.0"
] | 92 | 2015-02-01T07:44:29.000Z | 2021-12-09T05:56:02.000Z | //
// TMNetworkActivityIndicatorManager.h
// TMTumblrSDK
//
// Created by Kenny Ackerson on 1/7/16.
//
//
/**
* A protocol for types to conform to for updates on when the SDK determines if the network activity indicator should be visible.
*/
@protocol TMNetworkActivityIndicatorManager
/**
* Called when the SDK determines the network activity indicator should be visible.
*
* @param networkActivityIndicatorVisible Whether or not the network activity indicator should be visible.
*/
- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible;
@end
| 26.636364 | 130 | 0.771331 |
ea55445639f9b88a61c24b69ded5d14d0262ac73 | 991 | h | C | Instagram/PostCell.h | nevcam/Instagram | 53f977496ad243fbdc0ace23387843f0520327ed | [
"Apache-2.0"
] | null | null | null | Instagram/PostCell.h | nevcam/Instagram | 53f977496ad243fbdc0ace23387843f0520327ed | [
"Apache-2.0"
] | 1 | 2019-07-13T04:21:49.000Z | 2019-07-13T04:21:49.000Z | Instagram/PostCell.h | nevcam/Instagram | 53f977496ad243fbdc0ace23387843f0520327ed | [
"Apache-2.0"
] | null | null | null | //
// PostCell.h
// Instagram
//
// Created by nev on 7/9/19.
// Copyright © 2019 nev. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Post.h"
#import "Parse/Parse.h"
NS_ASSUME_NONNULL_BEGIN
@protocol PostCellDelegate;
@interface PostCell : UITableViewCell
@property (weak, nonatomic) Post *post;
@property (weak, nonatomic) IBOutlet UILabel *usernameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@property (weak, nonatomic) IBOutlet UILabel *captionLabel;
@property (weak, nonatomic) IBOutlet UILabel *likeCountLabel;
@property (weak, nonatomic) IBOutlet UIImageView *profilePhotoView;
@property (weak, nonatomic) IBOutlet UIButton *likeButton;
@property (weak, nonatomic) IBOutlet UIButton *commentButton;
@property (weak, nonatomic) IBOutlet UILabel *timestampLabel;
@property (nonatomic, weak) id<PostCellDelegate> delegate;
@end
@protocol PostCellDelegate
- (void)postCell:(PostCell *) postCell didTap: (PFUser *)user;
@end
NS_ASSUME_NONNULL_END
| 29.147059 | 67 | 0.769929 |
5a600f231ee98e96a243bcd04af5172490586bef | 18,391 | h | C | include/lmctfy.h | vmarmol/lmctfy | 59d5837099c7d231efdd6c7ffd41b83ce6feaf5c | [
"Apache-2.0"
] | 1 | 2017-01-19T22:35:06.000Z | 2017-01-19T22:35:06.000Z | include/lmctfy.h | vmarmol/lmctfy | 59d5837099c7d231efdd6c7ffd41b83ce6feaf5c | [
"Apache-2.0"
] | null | null | null | include/lmctfy.h | vmarmol/lmctfy | 59d5837099c7d231efdd6c7ffd41b83ce6feaf5c | [
"Apache-2.0"
] | 1 | 2020-12-28T16:07:20.000Z | 2020-12-28T16:07:20.000Z | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef INCLUDE_LMCTFY_H_
#define INCLUDE_LMCTFY_H_
#include <time.h>
#include <string>
using ::std::string;
#include <vector>
#include "base/callback.h"
#include "base/macros.h"
#include "include/lmctfy.pb.h"
#include "strings/stringpiece.h"
#include "util/task/statusor.h"
#include "util/task/status.h"
namespace containers {
namespace lmctfy {
class Container;
// lmctfy: Base Containers Library.
//
// Facilitates the creation, management, monitoring, and interaction with
// containers.
//
// The container specifications can be found in:
// //include/lmctfy.proto
//
// Container Naming Format:
//
// Container names mimic filesystem paths closely since they express a hierarchy
// of containers (i.e.: containers can be inside other containers, these are
// called subcontainers or children containers).
//
// Allowable characters for container names are:
// - Alpha numeric ([a-zA-Z]+, [0-9]+)
// - Underscores (_)
// - Dashes (-)
// - Periods (.)
//
// An absolute path is one that is defined from the root (/) container
// (i.e.: /sys/subcont). Container names can also be relative (i.e.: subcont).
// In general and unless otherwise specified, regular filesystem path rules
// apply.
//
// Examples:
// / : Root container
// /sys : the "sys" top level container
// /sys/sub : the "sub" container inside the "sys" top level container
// . : the current container
// ./ : the current container
// .. : the parent of the current container
// sub : the "sub" subcontainer (child container) of the current
// container
// ./sub : the "sub" subcontainer (child container) of the current
// container
// /sub : the "sub" top level container
// ../sibling : the "sibling" child container of the parent container
//
// Containers exist on the whole machine and thus can be accessed from multiple
// processes and multiple threads in each process. At any given time, there may
// be Container objects for container /foo in different processes, and in
// different threads of the same process. Administrative operations on a single
// container must be synchronized. This synchronizations is typically done by
// the "container owner". Administrative operations are: Create(), Update(),
// Destroy(), KillAll(), Pause(), and Resume().
//
// Note that since there are multiple Container objects in multiple processes, a
// container may be "deleted under you." Once a container is deleted, all of the
// operations on all Container objects that reference it will fail with
// NOT_FOUND.
//
// Visitor Threads:
// There may exist threads that are inside a container, but their thread-group
// leader (the thread whose TID is the same as the PID) is not inside the
// container. These threads shall be referred to as "visitor threads." This use
// is in general discouraged as it can lead to hard to manage edge cases. Some
// of these edge cases are described in the documentation below.
//
// Class is thread-safe.
class ContainerApi {
public:
// TODO(vishnuk): Empty Spec should trigger default initialization.
// Initializes the machine to start being able to create containers. All
// creations of ContainerApi objects will fail before this initialization is
// complete. This should be called once during machine boot.
//
// Regular users do NOT need to call this.
static ::util::Status InitMachine(const InitSpec &spec);
// Returns a new instance of ContainerApi iff the status is OK. The returned
// instance is thread-safe and the caller takes ownership.
static ::util::StatusOr<ContainerApi *> New();
virtual ~ContainerApi() {}
// Attach to an existing container. Get an object through which we can
// interact with that container. If the container does not exist, an error is
// returned.
//
// Multiple Get() operations on the same container (or a Create() and a Get())
// return different Container object instances pointing to the same underlying
// container. Any of these instances can be used to interact with the
// container and certain interactions are synchronized (those that specify
// it).
//
// Arguments:
// container_name: The name of the existing container. The container name
// format is outlined near the top of this file.
// Return:
// StatusOr: OK iff the operation was successful. On success we populate an
// object for container interactions and the caller takes ownership.
virtual ::util::StatusOr<Container *> Get(
StringPiece container_name) const = 0;
// Create a new container from the provided specification. Get an object
// through which we can interact with that container. If the container name
// already exists, an error is returned.
//
// Arguments:
// container_name: The desired name for the new container. The container
// name format is outlined near the top of this file.
// spec: Container specification. Only resources that are specified will be
// included in the container. All those resources not specified will
// share their parent's limits.
// Return:
// StatusOr: OK iff the operation was successful. On success we populate an
// object for container interactions and the caller takes ownership.
virtual ::util::StatusOr<Container *> Create(
StringPiece container_name,
const ContainerSpec &spec) const = 0;
// Destroys the container and all subcontainers (recursive). Also kills any
// processes inside the containers being destroyed.
//
// Arguments:
// container: The container to destroy. Takes ownership (and deletes) the
// pointer on success.
// Return:
// Status: OK iff the container was destroyed (and deleted). Otherwise, the
// container is not destroyed (or deleted) and the caller retains
// ownership.
virtual ::util::Status Destroy(Container *container) const = 0;
// Detect what container the specified thread is in.
//
// Arguments:
// tid: The thread ID to check. 0 refers to self.
// Return:
// StatusOr: OK iff the container exists. On success we populate the name of
// the container in which the thread lives. The name is a full and
// absolute name as described by the container name format near the top
// of this file.
virtual ::util::StatusOr<string> Detect(pid_t tid) const = 0;
inline ::util::StatusOr<string> Detect() const { return Detect(0); }
protected:
ContainerApi() {}
private:
DISALLOW_COPY_AND_ASSIGN(ContainerApi);
};
// A lmctfy Container.
//
// Allows direct interactions with the container and its properties. Containers
// are created and destroyed by the lmctfy library above.
//
// TODO(vmarmol): Make this thread-safe for calls on the same container object.
// Class is thread-compatible. It is not inherently thread-safe, but can be made
// as such by synchronizing non-const invocations. It is safe to call const
// methods without synchronization.
class Container {
public:
// Destructor does not destroy the underlying container. For that, use
// ContainerApi's Destroy().
virtual ~Container() {}
// TODO(vmarmol): Change to "enum class" when that is supported. Here and
// elsewhere.
enum UpdatePolicy {
// Update only the specified fields.
UPDATE_DIFF,
// Replace the existing container with the new specification.
UPDATE_REPLACE
};
// Updates the container according to the specification. The set of resource
// types being isolated cannot change during an Update. This means that an
// UPDATE_REPLACE must specify all the resources being isolated and an
// UPDATE_DIFF cannot specify any resource that is not already being isolated.
//
// Arguments:
// spec: The specification of the desired updates.
// policy: If UPDATE_REPLACE updates the container to EXACTLY match the
// specification. If UPDATE_DIFF, only makes the specified changes.
// i.e.: if only memory limit is specified, only that is updated.
// Return:
// Status: Status of the operation. OK iff successful.
virtual ::util::Status Update(const ContainerSpec &spec,
UpdatePolicy policy) = 0;
// Moves the specified threads into this container. Enter is atomic.
//
// If Enter fails, the system may be left in an inconsistent state as the TIDs
// may have been partially moved into the container.
//
// Arguments:
// tids: The Thread IDs to move into the container.
// tid: The Thread ID to move into the container.
// Return:
// Status: Status of the operation. OK iff successful.
virtual ::util::Status Enter(const ::std::vector<pid_t> &tids) = 0;
inline ::util::Status Enter(pid_t tid) {
return Enter(::std::vector<pid_t>(1, tid));
}
// Run the specified command inside the container. Multiple instances of run
// can be active simultaneously. Processes MUST be reaped by the caller.
//
// Arguments:
// command: The command to execute with its arguments. The first element is
// the binary that will be executed and must be an absolute path. The
// remaining elements are provided as arguments to the binary. Unlike
// execv, you do not need to repeat the first argument.
// spec: The specification of the runtime environment to use for the
// execution of the command.
// Return:
// StatusOr: Status of the operation. OK iff successful. On success, the
// PID of the command is returned.
virtual ::util::StatusOr<pid_t> Run(const ::std::vector<string> &command,
const RunSpec &spec) = 0;
// Execute the specified command inside the container. This replaces the
// current process image with the specified command. The PATH environment
// variable is used, and the existing environment is passed to the new
// process image unchanged.
//
// Arguments:
// command: The program to execute, with one argument per element. The
// first argument must be the command to run, findable either by
// standard resolution from the current directory (e.g. /dir/prog or
// ./dir/prog or dir/prog), or by the PATH environment variable.
// Return:
// Status: Status of the operation, iff failure. If this call succeeds,
// it never returns.
virtual ::util::Status Exec(const ::std::vector<string> &command) = 0;
// Returns the resource isolation specification (ContainerSpec) of this
// container.
//
// Return:
// StatusOr: Status of the operation. OK iff successfull. On success, the
// ContainerSpec is populated.
virtual ::util::StatusOr<ContainerSpec> Spec() const = 0;
// Policies on listing output
enum ListPolicy {
// Only output the information of this container.
LIST_SELF,
// Output the information of this container and all of its subcontainers and
// their subcontainers.
LIST_RECURSIVE
};
// Get all subcontainers in this container.
//
// Recursive operation is not atomic so results may be stale or inconsistent
// depending on other container operations in the system. i.e.: if someone
// creates a subcontainer after all subcontainers were examined.
//
// Arguments:
// policy: If LIST_SELF, only list this container's subcontainers. If
// LIST_RECURSIVE, recursively lists all subcontainers of the
// subcontainers as well.
// Return:
// StatusOr: Status of the operation. OK iff successful. On success
// populates a list of subcontainers sorted by container names. The
// caller takes ownership of all pointers.
virtual ::util::StatusOr< ::std::vector<Container *>> ListSubcontainers(
ListPolicy policy) const = 0;
// Get all TIDs in this container.
//
// Recursive operation is not atomic so results may be stale or inconsistent
// depending on other container operations in the system. i.e.: if someone
// adds a process after the container was examined.
//
// Arguments:
// recursive: Whether to recursively list the TIDs of the subcontainer's
// subcontainers.
// Return:
// StatusOr: Status of the operation. OK iff successful. On success
// populates a list of TIDs.
virtual ::util::StatusOr< ::std::vector<pid_t>> ListThreads(
ListPolicy policy) const = 0;
// Get all PIDs in this container.
//
// Recursive operation is not atomic so results may be stale or inconsistent
// depending on other container operations in the system. i.e.: if someone
// adds a process after the container was examined.
//
// Arguments:
// recursive: Whether to recursively list the PIDs of the subcontainer's
// subcontainers.
// Return:
// StatusOr: Status of the operation. OK iff successful. On success
// populates a list of PIDs.
virtual ::util::StatusOr< ::std::vector<pid_t>> ListProcesses(
ListPolicy policy) const = 0;
// Atomically stops the execution of all threads inside the container and all
// subcontainers (recursively). All threads moved to a paused container will
// be paused as well (regardless of whether the PID is in the container). This
// guarantees to get all threads.
//
// Return:
// Status: Status of the operation. OK iff successful.
virtual ::util::Status Pause() = 0;
// Atomically resumes the execution of all threads inside the container and
// all subcontainers (recursively). All paused threads moved to a non-paused
// container will be resumed.
//
// Return:
// Status: Status of the operation. OK iff successful.
virtual ::util::Status Resume() = 0;
// Type of stats to output
enum StatsType {
// A summary of the statistics (see each resource's definition of summary).
STATS_SUMMARY,
// All available statistics.
STATS_FULL
};
// Gets usage and state information for the container. Note that the snapshot
// is not atomic.
//
// Arguments:
// type: The type of statistics to output.
// output: A snapshot of the container's statistics.
// Return:
// StatusOr: Status of the operation. On success we populate the container
// statistics.
virtual ::util::StatusOr<ContainerStats> Stats(StatsType type) const = 0;
// Unique IDs for registered notifications.
typedef uint64 NotificationId;
// Callback used on an event notification.
// container: The container that received the notification. It is an error
// to delete it.
// status: The status of the notification. If OK, then the event registered
// occured. Otherwise, an error is reported in the status. Errors may
// be caused by container deletion or unexpected registration errors.
typedef Callback2<Container *, ::util::Status> EventCallback;
// Register a notification for a specified container event. All notifications
// are unregistered when the container is destroyed.
//
// Arguments:
// spec: The specification for the event for which to register
// notifications.
// callback: The callback to run when the event is triggered. The callee
// takes ownership of the callback which MUST be a repeatable callback.
// Return:
// StatusOr: Status of the operation. OK iff successful and a unique ID for
// the notification is provided. The ID is unique within the current
// ContainerApi instance.
virtual ::util::StatusOr<NotificationId> RegisterNotification(
const EventSpec &spec, EventCallback *callback) = 0;
// Unregister (stop) the specified notification from being received.
//
// Arguments:
// notification_id: The unique notification ID for the container
// notification.
// Return:
// Status: Status of the operation. OK iff successful.
virtual ::util::Status UnregisterNotification(NotificationId event_id) = 0;
// Kills all processes running in the container. This operation is atomic and
// is synchronized with any mutable operations on this container.
//
// The operation sends a SIGKILL to all processes in the containers. Visitor
// threads are killed via SIGKILL after all processes have exited.
//
// Note that this operation can potentially take a long time (O(seconds)) if
// the processes in the container do not finish quickly. This operation also
// blocks all mutable container operations while it is in progress.
//
// Return:
// Status: Status of the operation. OK iff successful.
virtual ::util::Status KillAll() = 0;
// Gets the PID of the init process for this container.
//
// In containers with VirtualHost enabled, this will be the init in that
// virtual host. For all other containers, it will be the system's init
// (typically 1).
//
// Return
// StatusOr<pid_t>: Status of the operation. OK iff successful and the PID
// of init is populated..
virtual ::util::StatusOr<pid_t> GetInitPid() const = 0;
// Gets the name of the container.
//
// Return:
// string: The resolved absolute name of this container as outlined in the
// container name format near the top of this file.
const string &name() const { return name_; }
protected:
explicit Container(const string &container_name) : name_(container_name) {}
// Destroy the Container. This is for internal use only. Users should use
// ContainerApi::Destroy() instead.
//
// Return:
// Status: Status of the operation. OK iff successful.
virtual ::util::Status Destroy() = 0;
// The name of the container
string name_;
private:
friend class ContainerApiImpl;
DISALLOW_COPY_AND_ASSIGN(Container);
};
} // namespace lmctfy
} // namespace containers
#endif // INCLUDE_LMCTFY_H_
| 40.33114 | 80 | 0.700179 |
f6cdc0f5ac24382568185b28508c3d092ae05978 | 3,824 | c | C | qmta/libqmta/domain.c | bschau/Attic | 639d2e1f9b735944f9523b280e70c1bdabb0115c | [
"MIT"
] | null | null | null | qmta/libqmta/domain.c | bschau/Attic | 639d2e1f9b735944f9523b280e70c1bdabb0115c | [
"MIT"
] | null | null | null | qmta/libqmta/domain.c | bschau/Attic | 639d2e1f9b735944f9523b280e70c1bdabb0115c | [
"MIT"
] | 1 | 2020-03-28T18:25:41.000Z | 2020-03-28T18:25:41.000Z | #include "private.h"
/* protos */
static int skipname(u_char *, u_char *, u_char *);
static int skipdata(u_char *, u_char *, u_char *, u_short *, u_short *);
/*******************************************************************************
*
* mxlookup
*
* Lookup MX-rr for given domain.
*
* Input:
* ch - child object.
* domain - domain.
* response - where to store response string.
* Output:
* s: mxnodes.
* f: NULL.
*/
mxnode *
mxlookup(char *domain)
{
mxnode *mxl=NULL, *m;
int resplen;
u_char *cp, *eom, *tcp;
int cnt, err;
u_short type, dlen, weight;
u_char namebuf[MAXDNAME+1];
union {
HEADER hdr;
u_char buf[PACKETSZ];
} pkg;
resplen=res_query(domain, C_IN, T_MX, (u_char *)&pkg, sizeof(pkg));
if (resplen<0)
return NULL;
if (resplen>sizeof(pkg))
resplen=sizeof(pkg);
eom=pkg.buf+resplen;
cp=pkg.buf+sizeof(HEADER);
err=skipname(pkg.buf, eom, cp);
if (err<0)
return NULL;
cp+=(err+QFIXEDSZ);
cnt=ntohs(pkg.hdr.ancount);
while (cnt) {
if (cp>=eom)
break;
err=skipdata(pkg.buf, eom, cp, &type, &dlen);
if (err<0) { /* don't know how to continue from here */
mxdestroylist(&mxl);
return NULL;
}
cp+=err;
if (type==T_MX) {
tcp=cp;
GETSHORT(weight, tcp);
memset(namebuf, 0, MAXDNAME+1);
err=dn_expand(pkg.buf, eom, tcp, namebuf, MAXDNAME);
if (err>=0) {
m=mxalloc(weight, namebuf);
if (m)
mxl=mxinsert(mxl, m);
else
qlog(QWARN, "(mxlookup) mxalloc failed");
} else
qlog(QWARN, "(mxlookup) dn_expand failed");
}
cp+=dlen;
cnt--;
}
return mxl;
}
/*******************************************************************************
*
* skipname
*
* Pseudo expands name - this is a fast forward function :)
*
* Input:
* som - start of message.
* eom - end of message.
* cp - char pointer.
* Output:
* s: >=0.
* f: -1.
*/
static int
skipname(u_char *som,
u_char *eom,
u_char *cp)
{
char buf[MAXDNAME+1];
int cnt;
cnt=dn_expand(som, eom, cp, buf, MAXDNAME);
if (cnt<0) {
qlog(QWARN, "(skipname) dn_expand failed");
return -1;
}
return cnt;
}
/*******************************************************************************
*
* skipdata
*
* Parse a rdata block.
*
* Input:
* som - start of message.
* eom - end of message.
* cp - char pointer.
* type - where to store rdata type.
* dlen - where to store rdata length.
* Output:
* s: >0.
* f: -1.
*/
static int
skipdata(u_char *som,
u_char *eom,
u_char *cp,
u_short *type,
u_short *dlen)
{
u_char *tcp=cp;
int err;
u_short class;
u_int32_t ttl;
err=skipname(som, eom, tcp);
if (err<0) {
qlog(QWARN, "(skipdata) skipname failed");
return -1;
}
tcp+=err;
GETSHORT(*type, tcp);
GETSHORT(class, tcp);
GETLONG(ttl, tcp);
GETSHORT(*dlen, tcp);
return (tcp-cp);
}
/*******************************************************************************
*
* getdomain
*
* Return domain part of mailbox.
*
* Input:
* m - mailbox.
* Output:
* s: domain.
* f: NULL.
*/
char *
getdomain(char *m)
{
for (; *m && *m!='@'; m++);
if (*m=='@') {
m++;
return m;
}
return NULL;
}
/*******************************************************************************
*
* islocal
*
* Is host/domain local? A local host/domain is a host/domain we know of.
*
* Input:
* db - database.
* hd - host/domain.
* Output:
* host/domain is local: *ptr.
* host/domain is not local: NULL.
*/
char *
islocal(database *db,
char *hd)
{
int err;
if (!db->f) /* no database, not local */
return NULL;
if (!hd) /* no host/domain, not local */
return NULL;
err=qdbfetch(db, hd);
if (err) { /* database error, not local */
qlog(QWARN, "(islocal) database error");
return NULL;
}
if (db->dptr) /* found it */
return db->dptr;
/* not in db, not local */
return NULL;
}
| 17.381818 | 80 | 0.534519 |
c6fc320ef0c01c28af852f5c5afa8f0e9868c4b9 | 731 | h | C | SandBox/src/RenderCellLayer.h | Dalvent/GoblinEngine | 83836f08995aebf064c01a69ac6ba316d0e1921b | [
"Apache-2.0"
] | null | null | null | SandBox/src/RenderCellLayer.h | Dalvent/GoblinEngine | 83836f08995aebf064c01a69ac6ba316d0e1921b | [
"Apache-2.0"
] | null | null | null | SandBox/src/RenderCellLayer.h | Dalvent/GoblinEngine | 83836f08995aebf064c01a69ac6ba316d0e1921b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <IronCat.h>
#include <memory>
#include "ColorChooseLayer.h"
class RenderCellLayer : public IronCat::Layer
{
public:
RenderCellLayer(IronCat::Ref<IronCat::OrthogriphicCamera> camera,
ColorChooseLayer& colorChoose) : IronCat::Layer("RenderTriangleLayer"),
s_camera(camera), _colorChoose(colorChoose)
{
}
void OnAttach() override;
void OnUpdate() override;
void OnDetach() override;
private:
IronCat::Transform* CreateTransforms();
private:
IronCat::Ref<IronCat::Shader> s_shader;
IronCat::Ref<IronCat::VertexArray> s_vertexArray;
IronCat::Ref<IronCat::OrthogriphicCamera> s_camera;
IronCat::Ref<IronCat::Texture> s_texture;
IronCat::Transform* _transforms;
ColorChooseLayer& _colorChoose;
}; | 27.074074 | 73 | 0.774282 |
11ecffa5d2f7955c019e105b7b0b78a97de1e8f3 | 19,778 | h | C | src/oneD/decomposition/swept.h | Niemeyer-Research-Group/HeterogeneousSwept1D | 17000c86e6c1c2ef39821767660f23f32e1e83ff | [
"MIT"
] | null | null | null | src/oneD/decomposition/swept.h | Niemeyer-Research-Group/HeterogeneousSwept1D | 17000c86e6c1c2ef39821767660f23f32e1e83ff | [
"MIT"
] | 1 | 2020-07-15T21:01:33.000Z | 2020-07-15T21:28:17.000Z | src/oneD/decomposition/swept.h | Niemeyer-Research-Group/HeterogeneousSwept1D | 17000c86e6c1c2ef39821767660f23f32e1e83ff | [
"MIT"
] | 1 | 2020-03-01T17:55:30.000Z | 2020-03-01T17:55:30.000Z |
/*
---------------------------
SWEPT CORE
---------------------------
*/
using namespace std;
typedef std::vector<int> ivec;
#include "cudaUtils.h"
states ssLeft[3];
states ssRight[3];
__global__ void upTriangle(states *state, const int tstep)
{
extern __shared__ states sharedstate[];
int gid = blockDim.x * blockIdx.x + threadIdx.x; //Global Thread ID
int tidx = threadIdx.x; //Block Thread ID
int mid = blockDim.x >> 1;
// Using tidx as tid is kind of confusing for reader but looks valid.
sharedstate[tidx] = state[gid + 1];
__syncthreads();
for (int k=1; k<mid; k++)
{
if (tidx < (blockDim.x-k) && tidx >= k)
{
stepUpdate(sharedstate, tidx, tstep + k);
}
__syncthreads();
}
state[gid + 1] = sharedstate[tidx];
}
/**
Builds an inverted triangle using the swept rule.
Inverted triangle using the swept rule. downTriangle is only called at the end when data is passed left. It's never split. Sides have already been passed between nodes, but will be swapped and parsed by readIn function.
@param IC Full solution at some timestep.
@param inRight Array of right edges seeding solution vector.
*/
__global__
void
downTriangle(states *state, const int tstep, const int offset)
{
extern __shared__ states sharedstate[];
int tid = threadIdx.x; // Thread index
int mid = blockDim.x >> 1; // Half of block size
int base = blockDim.x + 2;
int gid = blockDim.x * blockIdx.x + tid + offset;
int tidx = tid + 1;
int tnow = tstep; // read tstep into register.
if (tid<2) sharedstate[tid] = state[gid];
__syncthreads();
sharedstate[tid+2] = state[gid+2];
__syncthreads();
for (int k=mid; k>0; k--)
{
if (tidx < (base-k) && tidx >= k)
{
stepUpdate(sharedstate, tidx, tnow);
}
tnow++;
__syncthreads();
}
state[gid] = sharedstate[tidx];
}
// __global__
// void
// printgpu(states *state, int n, int on)
// {
// printf("%i\n", on);
// for (int k=0; k<n; k++) printf("%i %.2f\n", k, state[k].T[on]);
// }
/**
Builds an diamond using the swept rule after a left pass.
Unsplit diamond using the swept rule. wholeDiamond must apply boundary conditions only at it's center.
@param state The working array of structures states.
@param tstep The count of the first timestep.
*/
__global__
void
wholeDiamond(states *state, const int tstep, const int offset)
{
extern __shared__ states sharedstate[];
int tidx = threadIdx.x + 1; // Thread index
int mid = (blockDim.x >> 1); // Half of block size
int base = blockDim.x + 2;
int gid = blockDim.x * blockIdx.x + threadIdx.x + offset;
int tnow = tstep;
int k;
if (threadIdx.x<2) sharedstate[threadIdx.x] = state[gid];
__syncthreads();
sharedstate[tidx+1] = state[gid + 2];
__syncthreads();
for (k=mid; k>0; k--)
{
if (tidx < (base-k) && tidx >= k)
{
stepUpdate(sharedstate, tidx, tnow);
}
tnow++;
__syncthreads();
}
for (k=2; k<=mid; k++)
{
if (tidx < (base-k) && tidx >= k)
{
stepUpdate(sharedstate, tidx, tnow);
}
tnow++;
__syncthreads();
}
state[gid + 1] = sharedstate[tidx];
}
/*
MARK : HOST SWEPT ROUTINES
*/
void upTriangleCPU(states *state, int tstep)
{
int tnow=tstep;
for (int k=2; k<cGlob.htp; k++)
{
for (int n=k; n<(cGlob.base-k); n++)
{
stepUpdate(state, n, tnow);
}
tnow++;
}
}
void downTriangleCPU(states *state, int tstep)
{
int tnow=tstep;
for (int k=cGlob.ht; k>0; k--)
{
for (int n=k; n<(cGlob.base-k); n++)
{
stepUpdate(state, n, tnow);
}
tnow++;
}
}
void wholeDiamondCPU(states *state, int tnow)
{
for (int k=cGlob.ht; k>0; k--)
{
for (int n=k; n<(cGlob.base-k); n++)
{
stepUpdate(state, n, tnow);
}
tnow++;
}
for (int k=2; k<cGlob.htp; k++)
{
for (int n=k; n<(cGlob.base-k); n++)
{
stepUpdate(state, n, tnow);
}
tnow++;
}
}
void splitDiamondCPU(states *state, int tnow)
{
ssLeft[2] = bound[1];
ssRight[0] = bound[0];
for (int k=cGlob.ht; k>0; k--)
{
for (int n=k; n<(cGlob.base-k); n++)
{
if (n == cGlob.ht)
{
ssLeft[0] = state[n-1], ssLeft[1] = state[n];
stepUpdate(&ssLeft[0], 1, tnow);
state[n] = ssLeft[1];
}
else if (n == cGlob.htp)
{
ssRight[1] = state[n], ssRight[2] = state[n+1];
stepUpdate(&ssRight[0], 1, tnow);
state[n] = ssRight[1];
}
else
{
stepUpdate(state, n, tnow);
}
}
tnow++;
}
for (int k=2; k<cGlob.htp; k++)
{
for (int n=k; n<(cGlob.base-k); n++)
{
if (n == cGlob.ht)
{
ssLeft[0] = state[n-1], ssLeft[1] = state[n];
stepUpdate(&ssLeft[0], 1, tnow);
state[n] = ssLeft[1];
}
else if (n == cGlob.htp)
{
ssRight[1] = state[n], ssRight[2] = state[n+1];
stepUpdate(&ssRight[0], 1, tnow);
state[n] = ssRight[1];
}
else
{
stepUpdate(state, n, tnow);
}
}
tnow++;
}
}
void passSwept(states *passer, states *getter, int tstep, int turn)
{
int rx = turn^1;
MPI_Isend(passer, cGlob.htp, struct_type, ranks[2*turn], TAGS(tstep),
MPI_COMM_WORLD, &req[0]);
MPI_Recv(getter, cGlob.htp, struct_type, ranks[2*rx], TAGS(tstep),
MPI_COMM_WORLD, &stat[0]);
MPI_Wait(&req[0], &stat[0]);
}
// void applyBC(states *state, int ty, int pt)
// {
// // Like if-dirichilet
// // Works for whole
// state[ty*pt] = sBound[ty];
// // If reflective
// // state[ty*pt] = state[pt-2] or state[pt+2]
// }
// Now we need to put the last value in a bucket, and append that to the start of the next array.
double sweptWrapper(states **state, int *tstep)
{
// FILE *diagDump;
// std::string fname = "edge/edgeWrite_" + std::to_string(ranks[1]) + ".csv";
// diagDump = fopen(fname.c_str(), "w+")
if (!ranks[1]) cout << "SWEPT Decomposition " << cGlob.tpb << endl;
const int bkL = cGlob.cBks - 1;
double t_eq = 0.0;
double twrite = cGlob.freq - QUARTER*cGlob.dt;
int tmine = *tstep;
// Must be declared global in equation specific header.
int tou = 2000;
if (cGlob.hasGpu) // If there's no gpu assigned to the process this is 0.
{
const int xc = cGlob.xcpu/2, xcp=xc+1;
const int xgp = cGlob.xg+1, xgpp = cGlob.xg+2;
const int cmid = cGlob.cBks/2;
int bx, ix;
const size_t gpusize = cGlob.szState * (xgpp + cGlob.ht);
const size_t ptsize = cGlob.szState * xgpp;
const size_t passsize = cGlob.szState * cGlob.htp;
const size_t smem = cGlob.szState * cGlob.base;
int gpupts = gpusize/cGlob.szState;
cudaStream_t st1, st2;
cudaStreamCreate(&st1);
cudaStreamCreate(&st2);
states *dState;
cudaMalloc((void **) &dState, gpusize);
cudaMemcpy(dState, state[1], ptsize, cudaMemcpyHostToDevice);
/* RULES
-- DOWN MUST FOLLOW A SPLIT
-- UP CANNOT BE IN WHILE LOOP
-||- ACTION: DO UP AND FIRST SPLIT OUTSIDE OF LOOP
-||- THEN LOOP CAN BEGIN WITH WHOLE DIAMOND.
*/
// ------------ Step Forward ------------ //
// ------------ UP ------------ //
upTriangle <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine);
int bchk=cudaKernelCheck(1, ranks[1]);
for (int k=0; k<cGlob.cBks; k++)
{
bx = (k/cmid);
ix = 2*bx;
upTriangleCPU(state[ix] + (k - bx * cmid)*cGlob.tpb, tmine);
}
// ------------ Pass Edges ------------ //
// -- FRONT TO BACK -- //
cudaMemcpy(state[0] + xcp, dState + 1, passsize, cudaMemcpyDeviceToHost);
cudaMemcpy(dState + xgp, state[2] + 1, passsize, cudaMemcpyHostToDevice);
passSwept(state[0] + 1, state[2] + xcp, tmine, 0);
// ------------ Step Forward ------------ //
// ------------ SPLIT ------------ //
wholeDiamond <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine, cGlob.ht);
for (int k=0; k<(cGlob.cBks); k++)
{
bx = (k/cmid);
ix = 2*bx;
if ((ranks[1] == lastproc) && (k == bkL))
{
splitDiamondCPU(state[ix] + (k - bx * cmid)*cGlob.tpb + cGlob.ht, tmine);
}
else
{
wholeDiamondCPU(state[ix] + (k - bx * cmid)*cGlob.tpb + cGlob.ht, tmine);
}
}
// ------------ Pass Edges ------------ //
// -- BACK TO FRONT -- //
cudaMemcpy(state[2], dState+cGlob.xg, passsize, cudaMemcpyDeviceToHost);
cudaMemcpy(dState, state[0] + xc, passsize, cudaMemcpyHostToDevice);
passSwept(state[2] + xc, state[0], tmine+1, 1);
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
if (!ranks[1]) state[0][0] = bound[0];
if (ranks[1]==lastproc) state[2][xcp] = bound[1];
while(t_eq < cGlob.tf)
{
// ------------ Step Forward ------------ //
// ------------ WHOLE ------------ //
wholeDiamond <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine, 0);
for (int k=0; k<cGlob.cBks; k++)
{
bx = (k/cmid);
ix = 2*(k/cmid);
wholeDiamondCPU(state[ix] + (k - bx * cmid)*cGlob.tpb, tmine);
}
// ------------ Pass Edges ------------ //
cudaMemcpy(state[0] + xcp, dState + 1, passsize, cudaMemcpyDeviceToHost);
cudaMemcpy(dState + xgp, state[2] + 1, passsize, cudaMemcpyHostToDevice);
passSwept(state[0] + 1, state[2] + xcp, tmine, 0);
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
// ------------ Step Forward ------------ //
// ------------ SPLIT ------------ //
wholeDiamond <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine, cGlob.ht);
for (int k=0; k<(cGlob.cBks); k++)
{
bx = (k/cmid);
ix = 2*bx;
if ((ranks[1] == lastproc) && (k == bkL))
{
splitDiamondCPU(state[ix] + (k - bx * cmid)*cGlob.tpb + cGlob.ht, tmine);
}
else
{
wholeDiamondCPU(state[ix] + (k - bx * cmid)*cGlob.tpb + cGlob.ht, tmine);
}
}
// ------------ Pass Edges ------------ //
// -- BACK TO FRONT -- //
cudaMemcpy(state[2], dState+cGlob.xg, passsize, cudaMemcpyDeviceToHost);
cudaMemcpy(dState, state[0] + xc, passsize, cudaMemcpyHostToDevice);
passSwept(state[2] + xc, state[0], tmine, 1);
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
if (!ranks[1]) state[0][0] = bound[0];
if (ranks[1]==lastproc) state[2][xcp] = bound[1];
if (t_eq > twrite)
{
downTriangle <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine, 0);
for (int k=0; k<cGlob.cBks; k++)
{
bx = (k/cmid);
ix = 2*bx;
downTriangleCPU(state[ix] + (k - bx * cmid)*cGlob.tpb, tmine);
}
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
cudaMemcpy(state[1], dState, ptsize, cudaMemcpyDeviceToHost);
writeOut(state, t_eq);
upTriangle <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine);
for (int k=0; k<cGlob.cBks; k++)
{
bx = (k/cmid);
ix = 2*bx;
upTriangleCPU(state[ix] + (k - bx * cmid)*cGlob.tpb, tmine);
}
cudaMemcpy(state[0] + xcp, dState + 1, passsize, cudaMemcpyDeviceToHost);
cudaMemcpy(dState + xgp, state[2] + 1, passsize, cudaMemcpyHostToDevice);
passSwept(state[0] + 1, state[2] + xcp, tmine, 0);
// ------------ Step Forward ------------ //
// ------------ SPLIT ------------ //
wholeDiamond <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine, cGlob.ht);
for (int k=0; k<(cGlob.cBks); k++)
{
bx = (k/cmid);
ix = 2*bx;
if ((ranks[1] == lastproc) && (k ==bkL))
{
splitDiamondCPU(state[ix] + (k - bx * cmid)*cGlob.tpb + cGlob.ht, tmine);
}
else
{
wholeDiamondCPU(state[ix] + (k - bx * cmid)*cGlob.tpb + cGlob.ht, tmine);
}
}
// ------------ Pass Edges ------------ //
// -- BACK TO FRONT -- //
cudaMemcpy(state[2], dState+cGlob.xg, passsize, cudaMemcpyDeviceToHost);
cudaMemcpy(dState, state[0] + xc, passsize, cudaMemcpyHostToDevice);
passSwept(state[2] + xc, state[0], tmine+1, 1);
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
twrite += cGlob.freq;
if (!ranks[1]) state[0][0] = bound[0];
if (ranks[1]==lastproc) state[2][xcp] = bound[1];
}
}
downTriangle <<<cGlob.gBks, cGlob.tpb, smem>>> (dState, tmine, 0);
for (int k=0; k<cGlob.cBks; k++)
{
bx = (k/cmid);
ix = 2*bx;
downTriangleCPU(state[ix] + (k - bx * cmid)*cGlob.tpb, tmine);
}
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
cudaMemcpy(state[1], dState, ptsize, cudaMemcpyDeviceToHost);
cudaFree(dState);
cudaStreamDestroy(st1);
cudaStreamDestroy(st2);
}
else
{
const int xc = cGlob.xcpu, xcp = xc+1;
for (int k=0; k<cGlob.cBks; k++)
{
upTriangleCPU(state[0] + k*cGlob.tpb, tmine);
}
// for (int i=0; i<xcp; i++) fprintf(diagDump,"%.5f:%.5f,", state[0][i].T[0], state[0][i].T[1]);
// fprintf(diagDump, "\n");
passSwept(state[0] + 1, state[0] + xcp, tmine, 0);
//Split
for (int k=0; k<cGlob.cBks; k++)
{
if ((ranks[1] == lastproc) && (k == bkL))
{
splitDiamondCPU(state[0] + cGlob.ht + k*cGlob.tpb, tmine);
}
else
{
wholeDiamondCPU(state[0] + cGlob.ht + k*cGlob.tpb, tmine);
}
}
// for (int i=cGlob.ht; i<xcp+cGlob.ht; i++) fprintf(diagDump,"%.5f:%.5f,", state[0][i].T[0], state[0][i].T[1]);
// fprintf(diagDump, "\n");
// -- BACK TO FRONT -- //
passSwept(state[0] + xc, state[0], tmine+1, 1);
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
if (!ranks[1]) state[0][0] = bound[0];
if (ranks[1]==lastproc) state[0][xcp] = bound[1];
while (t_eq < cGlob.tf)
{
for (int k=0; k<cGlob.cBks; k++)
{
wholeDiamondCPU(state[0] + k*cGlob.tpb, tmine);
}
// for (int i=1; i<xcp; i++) fprintf(diagDump,"%.5f:%.5f,", state[0][i].T[0], state[0][i].T[1]);
// fprintf(diagDump, "\n");
passSwept(state[0] + 1, state[0] + xcp, tmine, 0);
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
for (int k=0; k<(cGlob.cBks); k++)
{
if ((ranks[1] == lastproc) && (k == bkL))
{
splitDiamondCPU(state[0] + cGlob.ht + k*cGlob.tpb, tmine);
}
else
{
wholeDiamondCPU(state[0] + cGlob.ht + k*cGlob.tpb, tmine);
}
}
// for (int i=cGlob.ht; i<xcp+cGlob.ht; i++) fprintf(diagDump,"%.5f:%.5f,", state[0][i].T[0], state[0][i].T[1]);
// fprintf(diagDump, "\n");
passSwept(state[0] + xc, state[0], tmine, 1);
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
if (!ranks[1]) state[0][0] = bound[0];
if (ranks[1]==lastproc) state[0][xcp] = bound[1];
if (t_eq > twrite)
{
for (int k=0; k<cGlob.cBks; k++)
{
downTriangleCPU(state[0] + k*cGlob.tpb, tmine);
}
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
writeOut(state, t_eq);
for (int k=0; k<cGlob.cBks; k++)
{
upTriangleCPU(state[0] + k*cGlob.tpb, tmine);
}
passSwept(state[0] + 1, state[0] + xcp, tmine, 0);
// ------------ Step Forward ------------ //
// ------------ SPLIT ------------ //
for (int k=0; k<(cGlob.cBks); k++)
{
if ((ranks[1] == lastproc) && (k == bkL))
{
splitDiamondCPU(state[0] + cGlob.ht + k*cGlob.tpb, tmine);
}
else
{
wholeDiamondCPU(state[0] + cGlob.ht + k*cGlob.tpb, tmine);
}
}
// passSwept(&putRe[0], &getRe[0], tmine+1, 1);
passSwept(state[0] + xc, state[0], tmine+1, 1);
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
twrite += cGlob.freq;
if (!ranks[1]) state[0][0] = bound[0];
if (ranks[1]==lastproc) state[0][xcp] = bound[1];
}
}
for (int k=0; k<cGlob.cBks; k++)
{
downTriangleCPU(state[0] + k*cGlob.tpb, tmine);
}
// Increment Counter and timestep
tmine += cGlob.ht;
t_eq = cGlob.dt * (tmine/NSTEPS);
}
// if (!ranks[1]){
// FILE *metaFile;
// metaFile = fopen("edge/RunDetails.txt", "w+");
// fprintf(metaFile, "%d,%.5f,%.5f,%.5f\n", cGlob.tpb, cGlob.lx, cGlob.dx, cGlob.dt);
// fclose(metaFile);
// }
// fclose(diagDump);
*tstep = tmine;
//atomicWrite(timeit.typ, timeit.times);
return t_eq;
}
| 30.14939 | 227 | 0.455152 |
91bc13302921a33cc835ac4328b792ce597b48f2 | 1,345 | h | C | DankEngine/src/DankEngine/Renderer/PerspectiveCamera.h | masonentrican/DankEngine | b6033aa491cc35fa6af4a465803c5e129d131e03 | [
"Apache-2.0"
] | 3 | 2020-12-04T00:30:10.000Z | 2021-07-14T03:59:02.000Z | DankEngine/src/DankEngine/Renderer/PerspectiveCamera.h | masonentrican/DankEngine | b6033aa491cc35fa6af4a465803c5e129d131e03 | [
"Apache-2.0"
] | null | null | null | DankEngine/src/DankEngine/Renderer/PerspectiveCamera.h | masonentrican/DankEngine | b6033aa491cc35fa6af4a465803c5e129d131e03 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
namespace Dank {
class PerspectiveCamera
{
public:
PerspectiveCamera(float FOV, float aspectRatio);
const glm::vec3& getPosition() const { return _position; }
float GetRotation() const { return _rotation; }
void SetPosition(const glm::vec3& position) { _position = position; RecalculateViewMatrix(); }
void SetRotation(const glm::vec3& newFront) { _front = newFront; RecalculateViewMatrix(); }
void SetProjection(float aspectRatio);
const glm::mat4& GetProjectionMatrix() const { return _projectionMatrix; }
const glm::mat4& GetViewMatrix() const { return _viewMatrix; }
const glm::mat4& GetViewProjectionMatrix() const { return _viewProjectionMatrix; }
private:
void RecalculateViewMatrix();
private:
glm::mat4 _projectionMatrix;
glm::mat4 _viewMatrix = glm::mat4(1.0f);
glm::mat4 _viewProjectionMatrix;
float _FOV;
glm::vec3 _position = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 _up = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 _front = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 _camTarget = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 _camDirection = glm::normalize(_position - _camTarget);
glm::vec3 _camRight = glm::normalize(glm::cross(_up, _camDirection));
glm::vec3 _camUp = glm::cross(_camDirection, _camRight);
float _rotation = 0.0f;
};
}
| 31.27907 | 96 | 0.704089 |
4c01c9910b72882b4c39feb03350e2bb96aef5a8 | 1,377 | c | C | atmega8/aes/aes-min/aes-sbox-inv-small.c | kavka1983/key | 9185c156fd40a1cab358b2464af4b27cacf71935 | [
"MIT"
] | 226 | 2017-08-14T16:11:36.000Z | 2022-03-13T00:58:13.000Z | atmega8/aes/aes-min/aes-sbox-inv-small.c | kavka1983/key | 9185c156fd40a1cab358b2464af4b27cacf71935 | [
"MIT"
] | 90 | 2017-09-12T02:07:39.000Z | 2022-01-27T20:58:19.000Z | atmega8/aes/aes-min/aes-sbox-inv-small.c | kavka1983/key | 9185c156fd40a1cab358b2464af4b27cacf71935 | [
"MIT"
] | 44 | 2017-09-17T17:31:25.000Z | 2022-02-27T08:19:46.000Z | /*****************************************************************************
* aes-sbox-inv-small.c
*
* AES inverse S-box implemented as a code calculation using Galois inverse.
*
* However it is doubtful whether this saves much over table look-up, due to
* the size of the implementation of aes_inv() and aes_mul() which it uses,
* as well as the size of aes_rotate_left_uint8() if it's not optimised.
* Check the size of the generated code on the target platform.
****************************************************************************/
/*****************************************************************************
* Includes
****************************************************************************/
#include "aes-sbox.h"
#include "aes-rotate.h"
#include "aes-inv.h"
/*****************************************************************************
* Functions
****************************************************************************/
uint8_t aes_sbox_inv(uint8_t a)
{
uint8_t x;
x = aes_rotate_left_uint8(a, 1u);
a = aes_rotate_left_uint8(x, 2u);
x ^= a;
a = aes_rotate_left_uint8(a, 3u);
return aes_inv(a ^ x ^ 0x05u);
}
void aes_sbox_inv_apply_block(uint8_t p_block[AES_BLOCK_SIZE])
{
uint_fast8_t i;
for (i = 0; i < AES_BLOCK_SIZE; ++i)
{
p_block[i] = aes_sbox_inv(p_block[i]);
}
}
| 30.6 | 78 | 0.442266 |
4c0b499b98f482426d3ade1de989b4c52e1672bb | 5,251 | h | C | semantics/includes/cuda_datatypes.h | chathhorn/cuda-semantics | 83e55fe63a3bbf49cbbba2a5d5778591c25a433a | [
"MIT"
] | 5 | 2015-02-04T11:45:56.000Z | 2020-10-04T10:46:40.000Z | semantics/includes/cuda_datatypes.h | chathhorn/cuda-semantics | 83e55fe63a3bbf49cbbba2a5d5778591c25a433a | [
"MIT"
] | null | null | null | semantics/includes/cuda_datatypes.h | chathhorn/cuda-semantics | 83e55fe63a3bbf49cbbba2a5d5778591c25a433a | [
"MIT"
] | 2 | 2018-02-01T13:55:58.000Z | 2020-03-09T19:46:14.000Z | #ifndef _KCC_CUDA_VECTOR_TYPES_H
#define _KCC_CUDA_VECTOR_TYPES_H
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef long long longlong;
typedef unsigned long long ulonglong;
enum cudaMemoryType {
cudaMemoryTypeHost = 1,
cudaMemoryTypeDevice = 2,
};
struct cudaPointerAttributes {
enum cudaMemoryType memoryType;
int device;
void* devicePointer;
void* hostPointer;
};
enum cudaMemcpyKind {
cudaMemcpyHostToDevice = 1,
cudaMemcpyDeviceToHost = 2,
};
typedef enum cudaError {
cudaSuccess = 0,
cudaErrorInvalidDevice = 10,
cudaErrorInvalidResourceHandle = 33,
cudaErrorNotReady = 34,
cudaErrorUnsupportedLimit = 42,
cudaErrorPeerAccessAlready = 50,
cudaErrorPeerAccessNotEnabled = 51,
} cudaError_t;
enum cudaFuncCache {
cudaFuncCachePreferNone = 0,
cudaFuncCachePreferShared = 1,
cudaFuncCachePreferL1 = 2,
};
typedef struct dim3 {
unsigned x, y, z;
} dim3;
struct cudaDeviceProp {
char name[256];
size_t totalGlobalMem;
size_t sharedMemPerBlock;
int regsPerBlock;
int warpSize;
size_t memPitch;
int maxThreadsPerBlock;
int maxThreadsDim[3];
int maxGridSize[3];
int clockRate;
size_t totalConstMem;
int major;
int minor;
size_t textureAlignment;
int deviceOverlap;
int multiProcessorCount;
int kernelExecTimeoutEnabled;
int integrated;
int canMapHostMemory;
int computeMode;
int maxTexture1D;
int maxTexture2D[2];
int maxTexture3D[3];
int maxTexture1DLayered[2];
int maxTexture2DLayered[3];
size_t surfaceAlignment;
int concurrentKernels;
int ECCEnabled;
int pciBusID;
int pciDeviceID;
int pciDomainID;
int tccDriver;
int asyncEngineCount;
int unifiedAddressing;
int memoryClockRate;
int memoryBusWidth;
int l2CacheSize;
int maxThreadsPerMultiProcessor;
};
enum cudaLimit {
cudaLimitStackSize = 0,
cudaLimitPrintfFifoSize = 1,
cudaLimitMallocHeapSize = 2,
};
typedef int cudaStream_t;
typedef int cudaEvent_t;
extern dim3 threadIdx;
extern dim3 blockIdx;
extern dim3 gridDim;
extern dim3 blockDim;
extern int warpSize;
struct cudaPitchedPtr {
void* ptr;
size_t pitch;
size_t xsize;
size_t ysize;
};
struct cudaExtent {
size_t width;
size_t height;
size_t depth;
};
struct cudaPos {
size_t x;
size_t y;
size_t z;
};
__device__ __host__ struct cudaExtent make_cudaExtent(size_t w, size_t h, size_t d);
__device__ __host__ struct cudaPitchedPtr make_cudaPitchedPtr(void* d, size_t p, size_t xsz, size_t ysz);
__device__ __host__ struct cudaPos make_cudaPos(size_t x, size_t y, size_t z);
/* Built-in Vector Types */
#define DECL_VEC1(T) \
typedef struct T ## 1 { T x; } T ## 1;
#define DECL_VEC2(T) \
typedef struct T ## 2 { T x, y; } T ## 2;
#define DECL_VEC3(T) \
typedef struct T ## 3 { T x, y, z; } T ## 3;
#define DECL_VEC4(T) \
typedef struct T ## 4 { T x, y, z, w; } T ## 4;
#define DECL_VEC_MAKE1(T) \
__host__ __device__ T ## 1 make_ ## T ## 1 (T x);
#define DECL_VEC_MAKE2(T) \
__host__ __device__ T ## 2 make_ ## T ## 2 (T x, T y);
#define DECL_VEC_MAKE3(T) \
__host__ __device__ T ## 3 make_ ## T ## 3 (T x, T y, T z);
#define DECL_VEC_MAKE4(T) \
__host__ __device__ T ## 4 make_ ## T ## 4 (T x, T y, T z, T w);
DECL_VEC1(char) DECL_VEC1(uchar)
DECL_VEC2(char) DECL_VEC2(uchar)
DECL_VEC3(char) DECL_VEC3(uchar)
DECL_VEC4(char) DECL_VEC4(uchar)
DECL_VEC1(short) DECL_VEC1(ushort)
DECL_VEC2(short) DECL_VEC2(ushort)
DECL_VEC3(short) DECL_VEC3(ushort)
DECL_VEC4(short) DECL_VEC4(ushort)
DECL_VEC1(int) DECL_VEC1(uint)
DECL_VEC2(int) DECL_VEC2(uint)
DECL_VEC3(int) DECL_VEC3(uint)
DECL_VEC4(int) DECL_VEC4(uint)
DECL_VEC1(long) DECL_VEC1(ulong)
DECL_VEC2(long) DECL_VEC2(ulong)
DECL_VEC3(long) DECL_VEC3(ulong)
DECL_VEC4(long) DECL_VEC4(ulong)
DECL_VEC1(longlong) DECL_VEC1(ulonglong)
DECL_VEC2(longlong) DECL_VEC2(ulonglong)
DECL_VEC1(float)
DECL_VEC2(float)
DECL_VEC3(float)
DECL_VEC4(float)
DECL_VEC1(double)
DECL_VEC2(double)
DECL_VEC_MAKE1(char) DECL_VEC_MAKE1(uchar)
DECL_VEC_MAKE2(char) DECL_VEC_MAKE2(uchar)
DECL_VEC_MAKE3(char) DECL_VEC_MAKE3(uchar)
DECL_VEC_MAKE4(char) DECL_VEC_MAKE4(uchar)
DECL_VEC_MAKE1(short) DECL_VEC_MAKE1(ushort)
DECL_VEC_MAKE2(short) DECL_VEC_MAKE2(ushort)
DECL_VEC_MAKE3(short) DECL_VEC_MAKE3(ushort)
DECL_VEC_MAKE4(short) DECL_VEC_MAKE4(ushort)
DECL_VEC_MAKE1(int) DECL_VEC_MAKE1(uint)
DECL_VEC_MAKE2(int) DECL_VEC_MAKE2(uint)
DECL_VEC_MAKE3(int) DECL_VEC_MAKE3(uint)
DECL_VEC_MAKE4(int) DECL_VEC_MAKE4(uint)
DECL_VEC_MAKE1(long) DECL_VEC_MAKE1(ulong)
DECL_VEC_MAKE2(long) DECL_VEC_MAKE2(ulong)
DECL_VEC_MAKE3(long) DECL_VEC_MAKE3(ulong)
DECL_VEC_MAKE4(long) DECL_VEC_MAKE4(ulong)
DECL_VEC_MAKE1(longlong) DECL_VEC_MAKE1(ulonglong)
DECL_VEC_MAKE2(longlong) DECL_VEC_MAKE2(ulonglong)
DECL_VEC_MAKE1(float)
DECL_VEC_MAKE2(float)
DECL_VEC_MAKE3(float)
DECL_VEC_MAKE4(float)
DECL_VEC_MAKE1(double)
DECL_VEC_MAKE2(double)
#endif
| 25.004762 | 105 | 0.716435 |
1ba425d95e9f73142eb7523a72873a22094ec48c | 6,292 | c | C | src/thirdparty/harfbuzz/test/api/test-ot-ligature-carets.c | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | src/thirdparty/harfbuzz/test/api/test-ot-ligature-carets.c | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | src/thirdparty/harfbuzz/test/api/test-ot-ligature-carets.c | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright © 2018 Ebrahim Byagowi
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
*/
#include "hb-test.h"
#include <hb-ot.h>
static void
test_ot_layout_get_ligature_carets_ot_gdef (void) {
hb_face_t * face = hb_test_open_font_file ("fonts/NotoNastaliqUrdu-Regular.ttf");
hb_font_t* font = hb_font_create (face);
hb_font_set_scale (font, hb_face_get_upem (face) * 2, hb_face_get_upem (face) * 4);
hb_position_t caret_array[16];
/* call with no result */
{
unsigned caret_count = 16;
g_assert_cmpuint (0, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
188, 0, &caret_count,
caret_array));
g_assert_cmpuint (0, == , caret_count);
}
/* call with no result and some offset */
{
unsigned caret_count = 16;
g_assert_cmpuint (0, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
188, 10, &caret_count,
caret_array));
g_assert_cmpuint (0, == , caret_count);
}
/* a glyph with 3 ligature carets */
{
unsigned caret_count = 16;
g_assert_cmpuint (3, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
1020, 0, &caret_count,
caret_array));
g_assert_cmpuint (3, == , caret_count);
g_assert_cmpuint (2718, == , caret_array[0]);
g_assert_cmpuint (5438, == , caret_array[1]);
g_assert_cmpuint (8156, == , caret_array[2]);
}
/* the same glyph as above but with offset */
{
caret_array[2] = 123;
unsigned caret_count = 16;
g_assert_cmpuint (3, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
1020, 1, &caret_count,
caret_array));
g_assert_cmpuint (2, == , caret_count);
g_assert_cmpuint (5438, == , caret_array[0]);
g_assert_cmpuint (8156, == , caret_array[1]);
g_assert_cmpuint (123, == , caret_array[2]);
}
/* the same glyph as above but with another offset */
{
unsigned caret_count = 16;
g_assert_cmpuint (3, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
1020, 2, &caret_count,
caret_array));
g_assert_cmpuint (1, == , caret_count);
g_assert_cmpuint (8156, == , caret_array[0]);
}
/* call with no result */
{
unsigned caret_count = 16;
g_assert_cmpuint (0, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
1021, 0, &caret_count,
caret_array));
g_assert_cmpuint (0, == , caret_count);
}
/* a glyph with 1 ligature caret */
{
unsigned caret_count = 16;
g_assert_cmpuint (1, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
1022, 0, &caret_count,
caret_array));
g_assert_cmpuint (1, == , caret_count);
g_assert_cmpuint (3530, == , caret_array[0]);
}
/* the same glyph as above but with offset */
{
unsigned caret_count = 16;
g_assert_cmpuint (1, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
1022, 1, &caret_count,
caret_array));
g_assert_cmpuint (0, == , caret_count);
}
/* a glyph with 2 ligature carets */
{
unsigned caret_count = 16;
g_assert_cmpuint (2, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_LTR,
1023, 0, &caret_count,
caret_array));
g_assert_cmpuint (2, == , caret_count);
g_assert_cmpuint (2352, == , caret_array[0]);
g_assert_cmpuint (4706, == , caret_array[1]);
}
hb_font_destroy (font);
hb_face_destroy (face);
}
static void
test_ot_layout_get_ligature_carets_empty (void) {
hb_face_t * face = hb_face_get_empty ();
hb_font_t* font = hb_font_create (face);
hb_font_set_scale (font, hb_face_get_upem (face) * 2, hb_face_get_upem (face) * 4);
hb_position_t caret_array[3];
unsigned int caret_count = 3;
g_assert_cmpuint (0, == , hb_ot_layout_get_ligature_carets (font, HB_DIRECTION_RTL,
1024, 0, &caret_count,
caret_array));
g_assert_cmpuint (0, == , caret_count);
hb_font_destroy (font);
hb_face_destroy (face);
}
int
main (int argc, char** argv) {
g_test_init (&argc, &argv, NULL);
hb_test_add (test_ot_layout_get_ligature_carets_ot_gdef);
hb_test_add (test_ot_layout_get_ligature_carets_empty);
return hb_test_run ();
}
| 36.581395 | 87 | 0.564685 |
f499b2f98657cc08b80e73c404d5d95562eb40dc | 3,532 | c | C | tests/timer/timer.c | pulp-platform/pulp-freertos | 351a088e704ec065aa877f73eef982e14fcbc60f | [
"Apache-2.0"
] | 4 | 2021-07-04T07:59:11.000Z | 2022-02-24T13:15:54.000Z | tests/timer/timer.c | pulp-platform/pulp-freertos | 351a088e704ec065aa877f73eef982e14fcbc60f | [
"Apache-2.0"
] | 2 | 2021-01-04T05:53:23.000Z | 2021-05-10T14:39:11.000Z | tests/timer/timer.c | pulp-platform/pulp-freertos | 351a088e704ec065aa877f73eef982e14fcbc60f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 ETH Zurich
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* Author: Robert Balas (balasr@iis.ee.ethz.ch)
*/
/*
* A minimal pmsis example. Mainly used to test if we can link against pmsis.
*/
/* FreeRTOS kernel includes. */
#include <FreeRTOS.h>
#include <task.h>
/* c stdlib */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <inttypes.h>
/* system includes */
#include "system.h"
#include "timer.h"
#include "timer_irq.h"
#include "fll.h"
#include "irq.h"
#include "gpio.h"
/* pmsis */
#include "target.h"
#include "os.h"
void vApplicationMallocFailedHook(void);
void vApplicationIdleHook(void);
void vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName);
void vApplicationTickHook(void);
static int blink_times;
void timer1_handler(void)
{
printf("blink\n");
/* terminate after a few blinks */
blink_times++;
if (blink_times > 4)
exit(0);
}
/* some busy freertos task that doesn't do anything */
void some_busy_task(void)
{
for (;;)
;
}
/* Program Entry. */
int main(void)
{
/* Init board hardware. */
system_init();
/* create a dummy task */
BaseType_t xTask;
xTask = xTaskCreate(some_busy_task, "dummy",
((unsigned short)configMINIMAL_STACK_SIZE), NULL,
tskIDLE_PRIORITY + 1, NULL);
if (xTask != pdPASS) {
printf("failed to create task\n");
exit(1);
}
/* hook up timer1 interrupt */
irq_set_handler(FC_TIMER1_IRQN, timer1_handler);
/* reset timer (not really necessary in this case) */
writew(1, (uintptr_t)(PULP_FC_TIMER_ADDR + TIMER_RESET_HI_OFFSET));
/* set interrupt frequency to TIMER1_TICK_RATE_HZ */
#define TIMER1_TICK_RATE_HZ ((TickType_t)2000)
writew(ARCHI_REF_CLOCK / TIMER1_TICK_RATE_HZ,
(uintptr_t)(PULP_FC_TIMER_ADDR + TIMER_CMP_HI_OFFSET));
/* Enable timer (TIMER_CFG_HI_ENABLE_MASK), use 32khz ref clock as
* source (TIMER_CFG_HI_CLKCFG_MASK). Timer will reset automatically
* (TIMER_CFG_HI_MODE_MASK) to zero after causing an interrupt
* (TIMER_CFG_HI_IRQEN_MASK). Also reset timer to start from a clean
* slate (TIMER_CFG_HI_RESET_MASK).
*/
writew(TIMER_CFG_HI_ENABLE_MASK | TIMER_CFG_HI_RESET_MASK |
TIMER_CFG_HI_CLKCFG_MASK | TIMER_CFG_HI_MODE_MASK |
TIMER_CFG_HI_IRQEN_MASK,
(uintptr_t)(PULP_FC_TIMER_ADDR + TIMER_CFG_HI_OFFSET));
/* Enable timer1 interrupt. Need to enable this in the CV32E40P and the
* apb_interrupt controller. In RI5CY we didn't need to touch the clint
* since it was in a kind of "passthrough" mode. */
irq_enable(IRQ_FC_EVT_TIMER0_HI);
irq_clint_enable(IRQ_FC_EVT_TIMER0_HI);
/* start test */
printf("Starting timer test\n");
/* start scheduling */
vTaskStartScheduler();
/* should never happen */
for (;;)
;
}
void vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName)
{
(void)pcTaskName;
(void)pxTask;
taskDISABLE_INTERRUPTS();
printf("error: stack overflow\n");
__asm volatile("ebreak");
for (;;)
;
}
| 25.594203 | 77 | 0.72282 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.