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
e172a5f36c0f745d84dc4b371abdd4b2f3d72fc2
62
c
C
tests/preproc/errmac4.c
MatthewCLane/unicon
29f68fb05ae1ca33050adf1bd6890d03c6ff26ad
[ "BSD-2-Clause" ]
35
2019-11-29T13:19:55.000Z
2022-03-01T06:00:40.000Z
tests/preproc/errmac4.c
MatthewCLane/unicon
29f68fb05ae1ca33050adf1bd6890d03c6ff26ad
[ "BSD-2-Clause" ]
83
2019-11-03T20:07:12.000Z
2022-03-22T11:32:35.000Z
tests/preproc/errmac4.c
jschnet/unicon
df79234dc1b8a4972f3908f601329591c06bd141
[ "BSD-2-Clause" ]
16
2019-10-14T04:32:36.000Z
2022-03-01T06:01:00.000Z
/* test error message: no #enddef */ #begdef m line 1 line 2
10.333333
36
0.66129
f6eb58efd90e9bc30b6bd02e0967ba74ac52a76a
898
h
C
ImportantExample/JQTools/library/JQLibrary/include/JQQRCodeWriter/JQQRCodeWriter.h
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/JQTools/library/JQLibrary/include/JQQRCodeWriter/JQQRCodeWriter.h
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/JQTools/library/JQLibrary/include/JQQRCodeWriter/JQQRCodeWriter.h
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
/* This file is part of JQLibrary Copyright: Jason Contact email: 188080501@qq.com GNU Lesser General Public License Usage Alternatively, this file may be used under the terms of the GNU Lesser General Public License version 2.1 or version 3 as published by the Free Software Foundation and appearing in the file LICENSE.LGPLv21 and LICENSE.LGPLv3 included in the packaging of this file. Please review the following information to ensure the GNU Lesser General Public License requirements will be met: https://www.gnu.org/licenses/lgpl.html and http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. */ #ifndef JQQRCODEWRITER_H_ #define JQQRCODEWRITER_H_ // Qt lib import #include <QString> #include <QImage> namespace JQQRCodeWriter { QImage makeQRcode(const QString &data, const QSize &size = QSize( 512, 512 )); } #endif//JQQRCODEWRITER_H_
27.212121
78
0.749443
052158d1d4344f5576d2f3533c01a3cba594db26
5,443
c
C
src/uifc/uifctest.c
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
1
2017-07-18T03:56:48.000Z
2017-07-18T03:56:48.000Z
src/uifc/uifctest.c
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
null
null
null
src/uifc/uifctest.c
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
null
null
null
/* uedit.c */ /* Synchronet for *nix user editor */ /* $Id: uifctest.c,v 1.7 2005/06/04 01:54:48 deuce Exp $ */ /**************************************************************************** * @format.tab-size 4 (Plain Text/Source Code File Header) * * @format.use-tabs true (see http://www.synchro.net/ptsc_hdr.html) * * * * Copyright 2003 Rob Swindell - http://www.synchro.net/copyright.html * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * See the GNU General Public License for more details: gpl.txt or * * http://www.fsf.org/copyleft/gpl.html * * * * Anonymous FTP access to the most recent released source is available at * * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net * * * * Anonymous CVS access to the development source and modification history * * is available at cvs.synchro.net:/cvsroot/sbbs, example: * * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login * * (just hit return, no password is necessary) * * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src * * * * For Synchronet coding style and modification guidelines, see * * http://www.synchro.net/source.html * * * * You are encouraged to submit any modifications (preferably in Unix diff * * format) via e-mail to mods@synchro.net * * * * Note: If this box doesn't appear square, then you need to fix your tabs. * ****************************************************************************/ #include <signal.h> #include <stdio.h> /* #include "curs_fix.h" */ #include "filepick.h" #include "uifc.h" /********************/ /* Global Variables */ /********************/ uifcapi_t uifc; /* User Interface (UIFC) Library API */ char YesStr[]="Yes"; char NoStr[]="No"; char *ok[2]={"OK",""}; int main(int argc, char** argv) { char** opt; char** mopt; int main_dflt=0; int main_bar=0; char revision[16]; char str[256],ctrl_dir[41],*p; char title[256]; int i,j; int done; int last; int edtuser=0; char longtitle[1024]; struct file_pick fper; /******************/ /* Ini file stuff */ /******************/ char ini_file[MAX_PATH+1]; FILE* fp; sscanf("$Revision: 1.7 $", "%*s %s", revision); printf("\nSynchronet UIFC Test Suite Copyright 2004 " "Rob Swindell\n"); memset(&uifc,0,sizeof(uifc)); uifc.esc_delay=500; for(i=1;i<argc;i++) { if(argv[i][0]=='-') switch(toupper(argv[i][1])) { case 'C': uifc.mode|=UIFC_COLOR; break; case 'L': uifc.scrn_len=atoi(argv[i]+2); break; case 'E': uifc.esc_delay=atoi(argv[i]+2); break; case 'I': /* Set up ex-ascii codes */ uifc.mode|=UIFC_IBM; break; default: printf("\nusage: %s [ctrl_dir] [options]" "\n\noptions:\n\n" "-c = force color mode\n" "-e# = set escape delay to #msec\n" "-i = force IBM charset\n" "-l# = set screen lines to #\n" ,argv[0] ); exit(0); } if(atoi(argv[i])) edtuser=atoi(argv[i]); } #ifdef __unix__ signal(SIGPIPE, SIG_IGN); #endif uifc.size=sizeof(uifc); #ifdef USE_CURSES i=uifcinic(&uifc); /* curses */ #else i=uifcini32(&uifc); /* curses */ #endif if(i!=0) { printf("uifc library init returned error %d\n",i); exit(1); } opt=(char **)malloc(sizeof(char *)*(MAX_OPTS+1)); for(i=0;i<(MAX_OPTS+1);i++) opt[i]=(char *)malloc(MAX_OPLN); mopt=(char **)malloc(sizeof(char *)*MAX_OPTS); for(i=0;i<MAX_OPTS;i++) mopt[i]=(char *)malloc(MAX_OPLN); sprintf(title,"Synchronet Test Suite"); if(uifc.scrn(title)) { printf(" USCRN (len=%d) failed!\n",uifc.scrn_len+1); return(1); } strcpy(mopt[0],"Long Title"); strcpy(mopt[1],"String Input"); strcpy(mopt[2],"File picker"); mopt[3][0]=0; uifc.helpbuf= "`Test Suite:`\n" "\nToDo: Add Help"; while(1) { j=uifc.list(WIN_L2R|WIN_ESC|WIN_ACT|WIN_DYN|WIN_ORG,0,5,70,&main_dflt,&main_bar ,title,mopt); if(j <= -2) continue; if(j==-1) { uifc.bail(); return(0); } if(j==0) { /* Long Title */ strcpy(longtitle,"This is a long title..."); for(p=strchr(longtitle,0);p<longtitle+sizeof(longtitle)-1;p++) *p='.'; *p=0; done=0; uifc.list(WIN_ORG|WIN_MID|WIN_ACT,0,0,0,&i,0,longtitle,ok); } if(j==1) { /* String input */ strcpy(longtitle,"This is a test if string input... enter/edit this field"); uifc.input(WIN_MID|WIN_NOBRDR,0,0,"Input",longtitle,sizeof(longtitle),K_EDIT); uifc.showbuf(WIN_MID, 0, 0, uifc.scrn_width-4, uifc.scrn_len-4, "Result:", longtitle, NULL, NULL); } if(j==2) { /* File picker */ if(filepick(&uifc, "Bob", &fper, NULL, NULL, UIFC_FP_ALLOWENTRY)!=-1) { if(fper.files==1) { sprintf(str,"File selected: %-.200s",fper.selected[0]); uifc.msg(str); } filepick_free(&fper); } } } }
28.952128
101
0.548043
40a961d112730cece1cdf50ecceeeaf90b434143
860
h
C
include/lfc/utils/panic.h
a-lafrance/lfc
86fb0f1e48d14a76c1a374c012052d8d807ffbe8
[ "MIT" ]
2
2021-09-02T20:37:45.000Z
2021-09-04T01:03:58.000Z
include/lfc/utils/panic.h
a-lafrance/lfc
86fb0f1e48d14a76c1a374c012052d8d807ffbe8
[ "MIT" ]
2
2021-09-07T06:54:49.000Z
2021-09-12T22:46:06.000Z
include/lfc/utils/panic.h
a-lafrance/lfc
86fb0f1e48d14a76c1a374c012052d8d807ffbe8
[ "MIT" ]
null
null
null
#ifndef LFC_PANIC_HEADER #define LFC_PANIC_HEADER #include <stdio.h> #include <stdlib.h> /// A simple error-handling system. Although there is no stack-unwinding, this system is just a simple /// way to print an error message to the user before exiting. It prints a message to stderr, along with /// some basic debug data that specifies where the error occurred. #define panic(estatus, fmt_str, ...) fprintf(stderr, "[%s:%d @ %s] program panicked due to error:\n\t" fmt_str "\n", \ __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \ exit(estatus); #define guard(estatus, condition) if (!(condition)) { panic(estatus, "guard failed: %s", #condition) } // "panic if false" #define unwrap(estatus, ptr) if (ptr == NULL) { panic(estatus, "failed to unwrap '%s'", #ptr) } #endif
45.263158
122
0.647674
673aeabdb5886e0d78fd9c67a18c10e3711ed03f
350
h
C
src/is_palindrome.h
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
src/is_palindrome.h
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
src/is_palindrome.h
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
/** * @file is_palindrome.h * @author lipingan (lipingan.dev@outlook.com) * @brief * @version 0.1 * @date 2022-01-13 * * @copyright Copyright (c) 2022 * */ #ifndef __LEETCODE_IS_PALINDROME_H__ #define __LEETCODE_IS_PALINDROME_H__ #include "list_node.h" namespace leetcode { bool isPalindrome(ListNode *head); } // namespace leetcode #endif
18.421053
46
0.725714
9147d9bce6b19f857c94807542fc9a00cf4a90e3
1,701
c
C
logistic.c
ikirker/logistic-map-sanity-checks
3f4b940d6a163191a4ee219a1a03bc4640838542
[ "MIT" ]
null
null
null
logistic.c
ikirker/logistic-map-sanity-checks
3f4b940d6a163191a4ee219a1a03bc4640838542
[ "MIT" ]
null
null
null
logistic.c
ikirker/logistic-map-sanity-checks
3f4b940d6a163191a4ee219a1a03bc4640838542
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <mpi.h> #include "vec_type.h" #include "vector_functions.h" const double starting_value = 0.2; void logistic(Vec_Type starting_val, Vec_Type *buffer, int iterations) { int i; Vec_Type x = starting_val; for (i = 0; i < iterations; i++) { x = 4*x*(1-x); buffer[i] = x; } } Vec_Type v_type_add(Vec_Type a, Vec_Type b) { return a + b; } int main(int argc, char **argv) { int ierr; ierr = MPI_Init(&argc, &argv); int my_rank; ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); int ranks; ierr = MPI_Comm_size(MPI_COMM_WORLD, &ranks); const int store_size = 128; Vec_Type map_store[store_size]; Vec_Type root_map[store_size]; Vec_Type residual[store_size]; Vec_Type residual_sum; logistic(starting_value, map_store, store_size); if (my_rank == 0) { memcpy(root_map, map_store, store_size * sizeof(Vec_Type)); } ierr = MPI_Bcast(root_map, store_size, MY_MPI_VEC_TYPE, 0, MPI_COMM_WORLD); vector_subtract(residual, map_store, root_map, store_size); vector_abs(residual, store_size); residual_sum = vector_reduce(0.0, residual, &v_type_add, store_size); if (residual_sum != 0.0) { printf("Rank %d differed from rank 0: residual sum = %.24g\n", my_rank, residual_sum); } MPI_Finalize(); return 0; } int serial_main(int argc, char **argv) { int i; const int store_size = 100; Vec_Type map_store[store_size]; logistic(starting_value, map_store, store_size); for (i=0; i<store_size; i++) { printf("%.12g \n", map_store[i]); } return 0; }
23.625
94
0.642563
c6a3d9397721b3682e2408a620dc81ce138f985c
5,429
h
C
libcryptotemplate/include/cryptotemplate/NtlLib.h
alinush/libcryptotemplate
c13a9ad5f14bacdbf7c47080890a24f1fe9d8feb
[ "MIT" ]
1
2021-05-16T13:43:52.000Z
2021-05-16T13:43:52.000Z
libcryptotemplate/include/cryptotemplate/NtlLib.h
alinush/libcryptotemplate
c13a9ad5f14bacdbf7c47080890a24f1fe9d8feb
[ "MIT" ]
null
null
null
libcryptotemplate/include/cryptotemplate/NtlLib.h
alinush/libcryptotemplate
c13a9ad5f14bacdbf7c47080890a24f1fe9d8feb
[ "MIT" ]
1
2021-07-21T11:52:36.000Z
2021-07-21T11:52:36.000Z
#pragma once #include <iostream> #include <ctime> #include <vector> #include <sstream> #include <NTL/ZZ.h> #include <NTL/ZZ_p.h> #include <NTL/ZZ_pX.h> #include <NTL/vec_ZZ_p.h> #include <NTL/vector.h> #include <NTL/BasicThreadPool.h> #include <xutils/AutoBuf.h> #include <xutils/NotImplementedException.h> #include <cryptotemplate/PolyCrypto.h> using NTL::ZZ_p; using NTL::ZZ_pX; using NTL::ZZ; using NTL::vec_ZZ_p; using namespace std; namespace libcryptotemplate { /** * Some useful NTL functions to know (see https://www.shoup.net/ntl/doc/ZZ_pX.cpp.html) * NOTE: Unfortunately, as far as I can tell, there's no way to compute f(w_i) fast using FFT in libntl. * It seems that NTL uses a complicated representation for the f(w_i) values and doesn't expose them as ZZ_p's. * * ZZ_pX(INIT_SIZE, n) -> initializes to zero, but space is pre-allocated * * const ZZ_pX& ZZ_pX::zero() -> returns const reference to 0 polynomial * * void ZZ_pX::SetMaxLength(long n) -> f.SetMaxLength(n) pre-allocate spaces for n coefficients. The polynomial that f represents is unchanged. * * clear(ZZ_pX& x) -> x = 0 * set(ZZ_pX& x) -> x = 1 * random(ZZ_pX& x, long degBound) -> picks random poly of degree = degBound - 1 (documentation is confusing; it says < degBound, which is not precise; but code generates exactly degBound - 1) * * rem(r, a, b) -> r = a%b * DivRem(q, r, a, b) -> q = a/b, r = a%b * div(q, a, b) -> q = a/b * diff(d, f) -> d = derivative of f */ template<typename FieldT> void conv_single_fr_zp(const FieldT& a, ZZ_p& b, mpz_t& rop, ZZ& mid) { (a.as_bigint()).to_mpz(rop); char *s = mpz_get_str(NULL, 10, rop); mid = NTL::conv<ZZ>(s); b = NTL::conv<ZZ_p>(mid); void (*freefunc)(void *, size_t); mp_get_memory_functions(NULL, NULL, &freefunc); freefunc(s, strlen(s) + 1); } template<typename FieldT> void convLibffToNtl(const vector<FieldT> &a, ZZ_pX &pa) { (void)a; (void)pa; throw libxutils::NotImplementedException(); } /* * DEPRECATED: This uses strings and is slower than the implementation above. */ template<typename FieldT> void convLibffToNtl_slow(const vector<FieldT> &a, ZZ_pX &pa) { pa = ZZ_pX(NTL::INIT_MONO, (long)(a.size() - 1)); mpz_t rop; mpz_init(rop); ZZ mid; for (size_t i = 0; i < a.size(); i++) { conv_single_fr_zp(a[i], pa[static_cast<long>(i)], rop, mid); } mpz_clear(rop); } /** * Converts an NTL vec_ZZ_p vector of field elements to a vector of libff field elements. */ template<typename FieldT> void convNtlToLibff(const ZZ_p& zzp, FieldT& ff) { long numBytes = NumBytes(ZZ_p::modulus()); AutoBuf<unsigned char> buf(static_cast<int>(numBytes)); buf.zeroize(); mpz_t interm; mpz_init(interm); const ZZ& rep = NTL::rep(zzp); // NOTE: Puts the least significant byte in buf[0] NTL::BytesFromZZ(buf, rep, numBytes); // convert byte array to mpz_t mpz_import(interm, /*count =*/static_cast<size_t>(numBytes), /*order =*/-1, /*size =*/1, /*endian=*/0, /*nails =*/0, buf); ff = libff::bigint<FieldT::num_limbs>(interm); mpz_clear(interm); } template<typename FieldT> void convNtlToLibff(const vec_ZZ_p& pn, vector<FieldT>& pf) { // allocate enough space for libff polynomial pf.resize(static_cast<size_t>(pn.length())); mpz_t interm; mpz_init(interm); long numBytes = NumBytes(ZZ_p::modulus()); AutoBuf<unsigned char> buf(static_cast<int>(numBytes)); buf.zeroize(); for (size_t i = 0; i < pf.size(); i++) { const ZZ_p& coeff = pn[static_cast<long>(i)]; const ZZ& coeffRep = NTL::rep(coeff); // NOTE: Puts the least significant byte in buf[0] NTL::BytesFromZZ(buf, coeffRep, numBytes); // convert byte array to mpz_t mpz_import(interm, /*count =*/static_cast<size_t>(numBytes), /*order =*/-1, /*size =*/1, /*endian=*/0, /*nails =*/0, buf); pf[i] = libff::bigint<FieldT::num_limbs>(interm); } mpz_clear(interm); } /** * Converts an NTL ZZ_pX polynomial to libff polynomial. */ template<typename FieldT> void convNtlToLibff(const ZZ_pX& pn, vector<FieldT>& pf) { convNtlToLibff(pn.rep, pf); } /** * DEPRECATED: Converts an NTL ZZ_pX polynomial to libff polynomial. * This uses string streams and is slower than the implementation above. */ template<typename FieldT> void convNtlToLibff_slow(const ZZ_pX &pa, vector<FieldT> &a) { a.resize((size_t)(NTL::deg(pa)+1)); stringstream ss; for (size_t i = 0; i < a.size(); i++) { ss << pa[(long)i]; a[i] = libff::bigint<FieldT::num_limbs>(ss.str().c_str()); ss.str(""); } } template<class Group, class FieldT> Group multiExp( const std::vector<Group>& bases, const vec_ZZ_p& exps) { std::vector<FieldT> expsff; convNtlToLibff(exps, expsff); long minSize = static_cast<long>(bases.size()); if(exps.length() < minSize) minSize = exps.length(); return multiExp<Group>(bases.cbegin(), bases.cbegin() + minSize, expsff.cbegin(), expsff.cbegin() + minSize); } template<class Group, class FieldT> Group multiExp( const std::vector<Group>& bases, const ZZ_pX& exps) { return multiExp<Group, FieldT>(bases, exps.rep); } } // end of namespace libcryptotemplate
26.482927
192
0.639897
42d5e0ade576ca63d4b9414ed40f3aed5d9d5323
237
h
C
baisibudejie/baisibudejie/Classes/Other/View/LJPublishView.h
LJApple/baisibudeqijie
051aff04823c17709ab2762c2bc1328585822d97
[ "Apache-2.0" ]
null
null
null
baisibudejie/baisibudejie/Classes/Other/View/LJPublishView.h
LJApple/baisibudeqijie
051aff04823c17709ab2762c2bc1328585822d97
[ "Apache-2.0" ]
null
null
null
baisibudejie/baisibudejie/Classes/Other/View/LJPublishView.h
LJApple/baisibudeqijie
051aff04823c17709ab2762c2bc1328585822d97
[ "Apache-2.0" ]
null
null
null
// // LJPublishView.h // baisibudejie // // Created by 吕俊 on 16/2/23. // Copyright © 2016年 吕俊. All rights reserved. // #import <UIKit/UIKit.h> @interface LJPublishView : UIView // + (instancetype)publishView; + (void)show; @end
13.166667
46
0.658228
6e10f4206ebdd45002a1106e6d075229cee14667
25,095
c
C
vlc_linux/vlc-3.0.16/modules/access/http/message.c
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/access/http/message.c
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/access/http/message.c
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
/***************************************************************************** * message.c: HTTP request/response ***************************************************************************** * Copyright (C) 2015 Rémi Denis-Courmont * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 #include <assert.h> #include <errno.h> #include <stdalign.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <vlc_common.h> #include <vlc_http.h> #include <vlc_strings.h> #include <vlc_memstream.h> #include "message.h" #include "h2frame.h" struct vlc_http_msg { short status; char *method; char *scheme; char *authority; char *path; char *(*headers)[2]; unsigned count; struct vlc_http_stream *payload; }; /* Maximum alignment for safe conversion to/from any specific pointer type */ static const char alignas (max_align_t) vlc_http_error_loc; void *const vlc_http_error = (char *)&vlc_http_error_loc; static bool vlc_http_is_token(const char *); static ssize_t vlc_http_msg_find_header(const struct vlc_http_msg *m, const char *name) { for (unsigned i = 0; i < m->count; i++) if (!strcasecmp(m->headers[i][0], name)) return i; return -1; } static int vlc_http_msg_vadd_header(struct vlc_http_msg *m, const char *name, const char *fmt, va_list ap) { if (!vlc_http_is_token(name)) { /* Not a valid field name, i.e. not an HTTP token */ errno = EINVAL; return -1; } char *value; int len = vasprintf(&value, fmt, ap); if (unlikely(len < 0)) return -1; /* IETF RFC7230 §3.2.4 */ for (char *p = value; *p; p++) if (*p == '\r' || *p == '\n') *p = ' '; /* Discard leading OWS */ size_t crop = strspn(value, "\t "); if (crop > 0) { assert((unsigned)len >= crop); memmove(value, value + crop, len - crop + 1); len -= crop; } /* Discard trailing OWS */ while (len > 0 && (value[len - 1] == '\t' || value[len - 1] == ' ')) value[--len] = '\0'; /* Fold identically named header field values. This is unfortunately not * possible for Set-Cookie, while Cookie requires a special separator. */ ssize_t idx = vlc_http_msg_find_header(m, name); if (idx >= 0 && strcasecmp(name, "Set-Cookie")) { char *merged; char sep = strcasecmp(name, "Cookie") ? ',' : ';'; int val = asprintf(&merged, "%s%c %s", m->headers[idx][1], sep, value); free(value); if (unlikely(val == -1)) return -1; free(m->headers[idx][1]); m->headers[idx][1] = merged; return 0; } char *(*h)[2] = realloc(m->headers, sizeof (char *[2]) * (m->count + 1)); if (unlikely(h == NULL)) { free(value); return -1; } m->headers = h; h += m->count; h[0][0] = strdup(name); if (unlikely(h[0][0] == NULL)) { free(value); return -1; } h[0][1] = value; m->count++; return 0; } int vlc_http_msg_add_header(struct vlc_http_msg *m, const char *name, const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = vlc_http_msg_vadd_header(m, name, fmt, ap); va_end(ap); return ret; } const char *vlc_http_msg_get_header(const struct vlc_http_msg *m, const char *name) { ssize_t idx = vlc_http_msg_find_header(m, name); if (idx < 0) { errno = ENOENT; return NULL; } return m->headers[idx][1]; } int vlc_http_msg_get_status(const struct vlc_http_msg *m) { return m->status; } const char *vlc_http_msg_get_method(const struct vlc_http_msg *m) { return m->method; } const char *vlc_http_msg_get_scheme(const struct vlc_http_msg *m) { return m->scheme; } const char *vlc_http_msg_get_authority(const struct vlc_http_msg *m) { return m->authority; } const char *vlc_http_msg_get_path(const struct vlc_http_msg *m) { return m->path; } void vlc_http_msg_destroy(struct vlc_http_msg *m) { if (m->payload != NULL) vlc_http_stream_close(m->payload, false); for (unsigned i = 0; i < m->count; i++) { free(m->headers[i][0]); free(m->headers[i][1]); } free(m->headers); free(m->path); free(m->authority); free(m->scheme); free(m->method); free(m); } struct vlc_http_msg * vlc_http_req_create(const char *method, const char *scheme, const char *authority, const char *path) { struct vlc_http_msg *m = malloc(sizeof (*m)); if (unlikely(m == NULL)) return NULL; assert(method != NULL); m->status = -1; m->method = strdup(method); m->scheme = (scheme != NULL) ? strdup(scheme) : NULL; m->authority = (authority != NULL) ? strdup(authority) : NULL; m->path = (path != NULL) ? strdup(path) : NULL; m->count = 0; m->headers = NULL; m->payload = NULL; if (unlikely(m->method == NULL || (scheme != NULL && m->scheme == NULL) || (authority != NULL && m->authority == NULL) || (path != NULL && m->path == NULL))) { vlc_http_msg_destroy(m); m = NULL; } return m; } struct vlc_http_msg *vlc_http_resp_create(unsigned status) { struct vlc_http_msg *m = malloc(sizeof (*m)); if (unlikely(m == NULL)) return NULL; assert(status < 1000); m->status = status; m->method = NULL; m->scheme = NULL; m->authority = NULL; m->path = NULL; m->count = 0; m->headers = NULL; m->payload = NULL; return m; } void vlc_http_msg_attach(struct vlc_http_msg *m, struct vlc_http_stream *s) { assert(m->payload == NULL); m->payload = s; } struct vlc_http_msg *vlc_http_msg_iterate(struct vlc_http_msg *m) { struct vlc_http_msg *next = vlc_http_stream_read_headers(m->payload); if (next != NULL) m->payload = NULL; vlc_http_msg_destroy(m); return next; } struct vlc_http_msg *vlc_http_msg_get_initial(struct vlc_http_stream *s) { struct vlc_http_msg *m = vlc_http_stream_read_headers(s); if (m == NULL) vlc_http_stream_close(s, false); return m; } struct vlc_http_msg *vlc_http_msg_get_final(struct vlc_http_msg *m) { while (m != NULL && (vlc_http_msg_get_status(m) / 100) == 1) m = vlc_http_msg_iterate(m); return m; } block_t *vlc_http_msg_read(struct vlc_http_msg *m) { if (m->payload == NULL) return NULL; return vlc_http_stream_read(m->payload); } /* Serialization and deserialization */ char *vlc_http_msg_format(const struct vlc_http_msg *m, size_t *restrict lenp, bool proxied) { struct vlc_memstream stream; vlc_memstream_open(&stream); if (m->status < 0) { vlc_memstream_printf(&stream, "%s ", m->method); if (proxied) vlc_memstream_printf(&stream, "%s://%s", m->scheme, m->authority); vlc_memstream_printf(&stream, "%s HTTP/1.1\r\nHost: %s\r\n", m->path ? m->path : m->authority, m->authority); } else vlc_memstream_printf(&stream, "HTTP/1.1 %03hd .\r\n", m->status); for (unsigned i = 0; i < m->count; i++) vlc_memstream_printf(&stream, "%s: %s\r\n", m->headers[i][0], m->headers[i][1]); vlc_memstream_puts(&stream, "\r\n"); if (vlc_memstream_close(&stream)) return NULL; if (lenp != NULL) *lenp = stream.length; return stream.ptr; } struct vlc_http_msg *vlc_http_msg_headers(const char *msg) { struct vlc_http_msg *m; unsigned short code; if (sscanf(msg, "HTTP/1.%*1u %3hu %*s", &code) == 1) { m = vlc_http_resp_create(code); if (unlikely(m == NULL)) return NULL; } else return NULL; /* TODO: request support */ msg = strstr(msg, "\r\n"); if (msg == NULL) goto error; while (strcmp(msg + 2, "\r\n")) { const char *eol = msg; do { eol = strstr(eol + 2, "\r\n"); if (eol == NULL) goto error; } /* Deal with legacy obs-fold (i.e. multi-line header) */ while (eol[2] == ' ' || eol[2] == '\t'); msg += 2; /* skip CRLF */ const char *colon = memchr(msg, ':', eol - msg); if (colon == NULL || colon == msg) goto error; char *name = strndup(msg, colon - msg); if (unlikely(name == NULL)) goto error; colon++; colon += strspn(colon, " \t"); if (unlikely(vlc_http_msg_add_header(m, name, "%.*s", (int)(eol - colon), colon))) { free(name); goto error; } free(name); msg = eol; } return m; error: vlc_http_msg_destroy(m); return NULL; } struct vlc_h2_frame *vlc_http_msg_h2_frame(const struct vlc_http_msg *m, uint_fast32_t stream_id, bool eos) { for (unsigned j = 0; j < m->count; j++) { /* No HTTP 1 specific headers */ assert(strcasecmp(m->headers[j][0], "Connection")); assert(strcasecmp(m->headers[j][0], "Upgrade")); assert(strcasecmp(m->headers[j][0], "HTTP2-Settings")); } const char *(*headers)[2] = vlc_alloc(m->count + 5, sizeof (char *[2])); if (unlikely(headers == NULL)) return NULL; struct vlc_h2_frame *f; unsigned i = 0; char status[4]; if (m->status >= 0) { assert(m->status < 1000); sprintf(status, "%hd", m->status); headers[i][0] = ":status"; headers[i][1] = status; i++; } if (m->method != NULL) { headers[i][0] = ":method"; headers[i][1] = m->method; i++; } if (m->scheme != NULL) { headers[i][0] = ":scheme"; headers[i][1] = m->scheme; i++; } if (m->authority != NULL) { headers[i][0] = ":authority"; headers[i][1] = m->authority; i++; } if (m->path != NULL) { headers[i][0] = ":path"; headers[i][1] = m->path; i++; } if (m->count > 0) { memcpy(headers + i, m->headers, m->count * sizeof (*headers)); i += m->count; } f = vlc_h2_frame_headers(stream_id, VLC_H2_DEFAULT_MAX_FRAME, eos, i, headers); free(headers); return f; } struct vlc_http_msg *vlc_http_msg_h2_headers(unsigned n, const char *const hdrs[][2]) { struct vlc_http_msg *m = vlc_http_resp_create(0); if (unlikely(m == NULL)) return NULL; for (unsigned i = 0; i < n; i++) { const char *name = hdrs[i][0]; const char *value = hdrs[i][1]; /* NOTE: HPACK always returns lower-case names, so strcmp() is fine. */ if (!strcmp(name, ":status")) { char *end; unsigned long status = strtoul(value, &end, 10); if (m->status != 0 || status > 999 || *end != '\0') goto error; /* Not a three decimal digits status! */ m->status = status; continue; } if (!strcmp(name, ":method")) { if (m->method != NULL) goto error; m->method = strdup(value); if (unlikely(m->method == NULL)) goto error; m->status = -1; /* this is a request */ continue; } if (!strcmp(name, ":scheme")) { if (m->scheme != NULL) goto error; m->scheme = strdup(value); if (unlikely(m->scheme == NULL)) goto error; continue; } if (!strcmp(name, ":authority")) { if (m->authority != NULL) goto error; m->authority = strdup(value); if (unlikely(m->authority == NULL)) goto error; continue; } if (!strcmp(name, ":path")) { if (m->path != NULL) goto error; m->path = strdup(value); if (unlikely(m->path == NULL)) goto error; continue; } if (vlc_http_msg_add_header(m, name, "%s", value)) goto error; } if ((m->status < 0) == (m->method == NULL)) { /* Must be either a request or response. Not both, not neither. */ error: vlc_http_msg_destroy(m); m = NULL; } return m; } /* Header helpers */ static int vlc_http_istoken(int c) { /* IETF RFC7230 §3.2.6 */ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c && strchr("!#$%&'*+-.^_`|~", c) != NULL); } static int vlc_http_isctext(int c) { /* IETF RFC7230 §3.2.6 */ return (c == '\t') || (c == ' ') || (c >= 0x21 && c <= 0x27) || (c >= 0x2A && c <= 0x5B) || (c >= 0x5D && c <= 0x7E) || (c >= 0x80); } static size_t vlc_http_token_length(const char *str) { size_t i = 0; while (vlc_http_istoken(str[i])) i++; return i; } static size_t vlc_http_quoted_length(const char *str) { size_t i = 0; unsigned char c; if (str[i++] != '"') return 0; do { c = str[i++]; if (c == '\0') return 0; if (c == '\\') /* Quoted pair */ { unsigned char q = str[i++]; if (q < 32 && q != '\t') return 0; } } while (c != '"'); return i; } static bool vlc_http_is_token(const char *str) { size_t len = vlc_http_token_length(str); return len > 0 && str[len] == '\0'; } const char *vlc_http_next_token(const char *value) { /* We handle either token or token = token / quoted-string */ value += strcspn(value, ",\""); if (!*value) return NULL; value += vlc_http_quoted_length(value); return value + strspn(value, "\t ,"); } static const char *vlc_http_get_token(const char *value, const char *token) { const size_t length = strlen(token); while (value != NULL) { if (vlc_http_token_length(value) == length && !strncasecmp(token, value, length)) return value; value = vlc_http_next_token(value); } return NULL; } static char *vlc_http_get_token_value(const char *value, const char *token) { value = vlc_http_get_token(value, token); if (value == NULL) return NULL; value += vlc_http_token_length(value); value += strspn(value, " \t"); /* BWS */ if (*value != '=') return NULL; value++; value += strspn(value, " \t"); /* BWS */ size_t len = vlc_http_quoted_length(value); if (len == 0) return NULL; assert(len >= 2); value++; len -= 2; char *out = malloc(len + 1), *p; if (unlikely(out == NULL)) return NULL; for (p = out; len > 0; len--) { char c = *(value++); if (c == '\\') /* Quoted pair */ { c = *(value++); len--; } *(p++) = c; } *p = '\0'; return out; } const char *vlc_http_msg_get_token(const struct vlc_http_msg *msg, const char *field, const char *token) { return vlc_http_get_token(vlc_http_msg_get_header(msg, field), token); } static size_t vlc_http_comment_length(const char *str) { /* IETF RFC7230 §3.2.6 */ if (*str != '(') return 0; size_t i = 1; for (size_t nested = 1; nested > 0; i++) { unsigned char c = str[i]; if (c == ')') nested--; else if (c == '(') /* Nested comment */ nested++; else if (c == '\\') /* Quoted pair */ { i++; if (str[i] < 32) return 0; } else if (!vlc_http_isctext(c)) return 0; } return i; } static bool vlc_http_is_agent(const char *s) { /* IETF RFC7231 §5.5.3 and §7.4.2 */ if (!vlc_http_istoken(*s)) return false; for (;;) { size_t l = vlc_http_token_length(s); if (l != 0) /* product */ { if (s[l] == '/') /* product version */ { s += l + 1; l = vlc_http_token_length(s); } } else l = vlc_http_comment_length(s); if (l == 0) break; s += l; if (*s == '\0') return true; l = strspn(s, "\t "); /* RWS */ if (l == 0) break; s += l; } return false; } int vlc_http_msg_add_agent(struct vlc_http_msg *m, const char *str) { const char *hname = (m->status < 0) ? "User-Agent" : "Server"; if (!vlc_http_is_agent(str)) { errno = EINVAL; return -1; } return vlc_http_msg_add_header(m, hname, "%s", str); } const char *vlc_http_msg_get_agent(const struct vlc_http_msg *m) { const char *hname = (m->status < 0) ? "User-Agent" : "Server"; const char *str = vlc_http_msg_get_header(m, hname); return (str != NULL && vlc_http_is_agent(str)) ? str : NULL; } static const char vlc_http_days[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char vlc_http_months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; int vlc_http_msg_add_time(struct vlc_http_msg *m, const char *hname, const time_t *t) { struct tm tm; if (gmtime_r(t, &tm) == NULL) return -1; return vlc_http_msg_add_header(m, hname, "%s, %02d %s %04d %02d:%02d:%02d GMT", vlc_http_days[tm.tm_wday], tm.tm_mday, vlc_http_months[tm.tm_mon], 1900 + tm.tm_year, tm.tm_hour, tm.tm_min, tm.tm_sec); } int vlc_http_msg_add_atime(struct vlc_http_msg *m) { time_t now; time(&now); return vlc_http_msg_add_time(m, "Date", &now); } static time_t vlc_http_mktime(const char *str) { /* IETF RFC7231 §7.1.1.1 */ struct tm tm; char mon[4]; /* Internet Message Format date */ if (sscanf(str, "%*c%*c%*c, %2d %3s %4d %2d:%2d:%2d", &tm.tm_mday, mon, &tm.tm_year, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6 /* ANSI C format */ || sscanf(str, "%*3s %3s %2d %2d:%2d:%2d %4d", mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &tm.tm_year) == 6) tm.tm_year -= 1900; /* RFC850 date */ else if (sscanf(str, "%*[^,], %2d-%3s-%2d %2d:%2d:%2d", &tm.tm_mday, mon, &tm.tm_year, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) { if (tm.tm_year <= 75) tm.tm_year += 100; /* Y2K compat, sort of */ } else /* Unknown format */ goto error; for (tm.tm_mon = 0; tm.tm_mon < 12; tm.tm_mon++) if (!strcmp(mon, vlc_http_months[tm.tm_mon])) /* found month */ return timegm(&tm); error: errno = EINVAL; return -1; /* invalid month */ } time_t vlc_http_msg_get_time(const struct vlc_http_msg *m, const char *name) { const char *str = vlc_http_msg_get_header(m, name); if (str == NULL) return -1; return vlc_http_mktime(str); } time_t vlc_http_msg_get_atime(const struct vlc_http_msg *m) { return vlc_http_msg_get_time(m, "Date"); } time_t vlc_http_msg_get_mtime(const struct vlc_http_msg *m) { return vlc_http_msg_get_time(m, "Last-Modified"); } unsigned vlc_http_msg_get_retry_after(const struct vlc_http_msg *m) { const char *str = vlc_http_msg_get_header(m, "Retry-After"); if (str == NULL) return 0; char *end; unsigned long delay = strtoul(str, &end, 10); if (end != str && *end == '\0') return delay; time_t t = vlc_http_mktime(str); if (t != (time_t)-1) { time_t now; time(&now); if (t >= now) return t - now; } return 0; } uintmax_t vlc_http_msg_get_size(const struct vlc_http_msg *m) { /* IETF RFC7230 §3.3.3 */ if ((m->status / 100) == 1 /* Informational 1xx (implicitly void) */ || m->status == 204 /* No Content (implicitly void) */ || m->status == 205 /* Reset Content (must be explicitly void) */ || m->status == 304 /* Not Modified */) return 0; const char *str = vlc_http_msg_get_header(m, "Transfer-Encoding"); if (str != NULL) /* Transfer-Encoding preempts Content-Length */ return -1; str = vlc_http_msg_get_header(m, "Content-Length"); if (str == NULL) { if (m->status < 0) return 0; /* Requests are void by default */ return -1; /* Response of unknown size (e.g. chunked) */ } uintmax_t length; if (sscanf(str, "%ju", &length) == 1) return length; errno = EINVAL; return -1; } void vlc_http_msg_get_cookies(const struct vlc_http_msg *m, vlc_http_cookie_jar_t *jar, const char *host, const char *path) { if (jar == NULL) return; for (unsigned i = 0; i < m->count; i++) if (!strcasecmp(m->headers[i][0], "Set-Cookie")) vlc_http_cookies_store(jar, m->headers[i][1], host, path); } int vlc_http_msg_add_cookies(struct vlc_http_msg *m, vlc_http_cookie_jar_t *jar) { char *host, *cookies; int val = 0; bool secure; if (m->scheme == NULL || m->authority == NULL || m->path == NULL) { errno = EINVAL; return -1; } if (!strcasecmp(m->scheme, "https")) secure = true; else if (!strcasecmp(m->scheme, "http")) secure = false; else return 0; if (jar == NULL) return 0; if (m->authority[0] == '[') host = strndup(m->authority + 1, strcspn(m->authority + 1, "]")); else host = strndup(m->authority, strcspn(m->authority, ":")); if (unlikely(host == NULL)) return -1; cookies = vlc_http_cookies_fetch(jar, secure, host, m->path); free(host); if (cookies != NULL) { val = vlc_http_msg_add_header(m, "Cookie", "%s", cookies); free(cookies); } return val; } char *vlc_http_msg_get_basic_realm(const struct vlc_http_msg *m) { const char *auth; /* TODO: Support other authentication schemes. */ /* NOTE: In principles, RFC7235 allows for multiple authentication schemes, * including multiple times Basic with a different realm each. There are no * UI paradigms though. */ auth = vlc_http_msg_get_token(m, "WWW-Authenticate", "Basic"); if (auth == NULL) return NULL; auth += 5; auth += strspn(auth, " "); /* 1*SP */ return vlc_http_get_token_value(auth, "realm"); } int vlc_http_msg_add_creds_basic(struct vlc_http_msg *m, bool proxy, const char *username, const char *password) { char *str, *token; int ret; unsigned char c; /* CTL characters and colons not permitted in username */ for (size_t len = 0; (c = username[len]) != '\0'; len++) if (c < 32 || c == 127 || c == ':') { errno = EINVAL; return -1; } /* CTL characters not permitted in password */ for (size_t len = 0; (c = password[len]) != '\0'; len++) if (c < 32 || c == 127) { errno = EINVAL; return -1; } ret = asprintf(&str, "%s:%s", username, password); if (unlikely(ret < 0)) return -1; token = vlc_b64_encode_binary((unsigned char *)str, ret); free(str); if (unlikely(token == NULL)) return -1; ret = vlc_http_msg_add_header(m, proxy ? "Proxy-Authorization" : "Authorization", "Basic %s", token); free(token); return ret; }
25.195783
79
0.526798
5d483ca5d67d7426e93f74cb13fa5655900e9197
1,351
h
C
Ym2Mym/sources/infos.h
nekoniaow/OSDK
ba6692caba3da0afde67e5709de21aacab8b03b7
[ "WTFPL", "Zlib" ]
5
2018-10-31T10:33:44.000Z
2022-02-28T14:33:52.000Z
Ym2Mym/sources/infos.h
nekoniaow/OSDK
ba6692caba3da0afde67e5709de21aacab8b03b7
[ "WTFPL", "Zlib" ]
2
2018-05-15T06:06:14.000Z
2018-05-17T05:52:59.000Z
Ym2Mym/sources/infos.h
nekoniaow/OSDK
ba6692caba3da0afde67e5709de21aacab8b03b7
[ "WTFPL", "Zlib" ]
1
2018-10-31T10:35:20.000Z
2018-10-31T10:35:20.000Z
/* Change history for the Ym2Mym 0.1 - 30.1.2000 - Marq/Lieves!Tuore & Fit (marq@iki.fi) 0.2 - 3.2.2000 - Added a rude YM5 loader. Skips most of the header. 1.0 - 2013/12/18 - Added support for retuning (Atari ST songs are at 2mhz, Amstrad ones at 1mhz) - Added rude support for YM6 format (also skips most of the header) 1.1 - 2014/01/12 - The tool is now able to extract LHA compressed YM files directly, should make the process much easier :) 1.2 - 2014/01/13 [Broken do not use] - Added a -v flag to enable/disable verbosity - Added a -h flag to add a tape compatible header 1.3 - 2014/01/13 [Broken do not use] - Added a -m flag to check if the exported file fits a maximum size 1.4 - 2014/01/14 - Fixed a stupid bug of signed data added in version 1.2 1.5 - 2014/12/06 - The verbose mode (-v1) now displays the embedded informations such as author name, song name, and extra comments - Interleave register format is now also supported 1.6 - 2015/05/29 - Added a -d flag that can be used to shorten a music. "-dt" truncates the music, "-df" fades it out. (example: -dt50 will cut the music after 1 second - 50 frames - ) 1.7 - 2015/05/29 - Added a -f flag that can be used to export the music to WAV format instead of MYM */ #define TOOL_VERSION_MAJOR 1 #define TOOL_VERSION_MINOR 7
30.022222
168
0.695041
56e1d70f0f5e315a516c178f73a605d366a17a7f
297
h
C
nen/Classes/IM/ChatUI/Class/Call/Conference/UserTableViewController.h
heshaohao/nen
36035e038efcd8f4ef849a67559018f89e010871
[ "Apache-2.0" ]
null
null
null
nen/Classes/IM/ChatUI/Class/Call/Conference/UserTableViewController.h
heshaohao/nen
36035e038efcd8f4ef849a67559018f89e010871
[ "Apache-2.0" ]
null
null
null
nen/Classes/IM/ChatUI/Class/Call/Conference/UserTableViewController.h
heshaohao/nen
36035e038efcd8f4ef849a67559018f89e010871
[ "Apache-2.0" ]
null
null
null
// // UserTableViewController.h // ChatDemo-UI3.0 // // Created by XieYajie on 8/31/16. // Copyright © 2016 XieYajie. All rights reserved. // #import <UIKit/UIKit.h> @interface UserTableViewController : UITableViewController - (instancetype)initWithDataSource:(NSArray *)aDataSource; @end
18.5625
58
0.737374
5172fd234e48f6a5fbaed44b5564a7df5660f821
3,340
h
C
MSCMoreOptionTableViewCell-master/MSCMoreOptionTableViewCell/MSCMoreOptionTableViewCellDelegate.h
kobunketsu/PrototypeMaker
b62e348729b8121555276009f053e9c6027d37ce
[ "MIT" ]
null
null
null
MSCMoreOptionTableViewCell-master/MSCMoreOptionTableViewCell/MSCMoreOptionTableViewCellDelegate.h
kobunketsu/PrototypeMaker
b62e348729b8121555276009f053e9c6027d37ce
[ "MIT" ]
null
null
null
MSCMoreOptionTableViewCell-master/MSCMoreOptionTableViewCell/MSCMoreOptionTableViewCellDelegate.h
kobunketsu/PrototypeMaker
b62e348729b8121555276009f053e9c6027d37ce
[ "MIT" ]
null
null
null
// // MSCMoreOptionTableViewCellDelegate.h // MSCMoreOptionTableViewCell // // Created by Manfred Scheiner (@scheinem) on 20.08.13. // Copyright (c) 2013 Manfred Scheiner (@scheinem). All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @protocol MSCMoreOptionTableViewCellDelegate<NSObject> @optional // 'more' button /* * Tells the delegate that the 'more' button for specified row was pressed. */ - (void)tableView:(UITableView *)tableView moreOptionButtonPressedInRowAtIndexPath:(NSIndexPath *)indexPath; /* * When property 'configurationBlock' is nil: * ========================================== * If not implemented or returning nil the 'More' button will neither be created * nor displayed, the cell will act like a common UITableViewCell and the only * two delegate methods which will have an impact will be: * * - tableView:backgroundColorForDeleteConfirmationButtonForRowAtIndexPath: * - tableView:titleColorForDeleteConfirmationButtonForRowAtIndexPath: * * This behaviour is needed to ensure compatiblity of code from developers * that was written for usage of MSCMoreOptionTableViewCell 1.x * * When property 'configurationBlock' is set (NOT nil): * ==================================================== * The 'more' button will be created then customized using the delegate methods, * passed to the configuration block and added to the view hierarchy afterwards. * * NOTE: * ===== * The 'more' button also supports multiline titles. * */ - (NSString *)tableView:(UITableView *)tableView titleForMoreOptionButtonForRowAtIndexPath:(NSIndexPath *)indexPath; /* * If not implemented or returning nil the 'more' button will have [UIColor whiteColor] * as titleColor. * */ - (UIColor *)tableView:(UITableView *)tableView titleColorForMoreOptionButtonForRowAtIndexPath:(NSIndexPath *)indexPath; /* * If not implemented or returning nil the 'more' button will have [UIColor lightGrayColor] * as backgroundColor. * */ - (UIColor *)tableView:(UITableView *)tableView backgroundColorForMoreOptionButtonForRowAtIndexPath:(NSIndexPath *)indexPath; /* * If not implemented or returning a lower value than the 'more' button's 'fitting' value, * the 'More' button width will not be changed. * */ - (CGFloat)tableView:(UITableView *)tableView minimumWidthForMoreOptionButtonForRowAtIndexPath:(NSIndexPath *)indexPath; /* * If not implemented the 'more' button will have (0, 15, 0, 15) as 'edgeInsets'. * */ - (UIEdgeInsets)tableView:(UITableView *)tableView edgeInsetsForMoreOptionButtonForRowAtIndexPath:(NSIndexPath *)indexPath; // 'delete' button /* * If not implemented or returning nil the 'delete' button will have it's default backgroundColor. * */ - (UIColor *)tableView:(UITableView *)tableView backgroundColorForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath; /* * If not implemented or returning nil the 'delete' button will have it's default titleColor. * */ - (UIColor *)tableView:(UITableView *)tableView titleColorForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath; /* * If not implemented the 'delete' button will have (0, 15, 0, 15) as 'edgeInsets'. * */ - (UIEdgeInsets)tableView:(UITableView *)tableView edgeInsetsForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath; @end
35.531915
133
0.744311
b6c1d4d92dd4b170d8aac3c5d9c43f30d351f2f8
1,164
h
C
packages/path_provider/path_provider_ios/ios/Classes/messages.g.h
cglol/plugins
41722ee5594aac1b4048036f840a98e0369bb7c5
[ "BSD-3-Clause" ]
null
null
null
packages/path_provider/path_provider_ios/ios/Classes/messages.g.h
cglol/plugins
41722ee5594aac1b4048036f840a98e0369bb7c5
[ "BSD-3-Clause" ]
null
null
null
packages/path_provider/path_provider_ios/ios/Classes/messages.g.h
cglol/plugins
41722ee5594aac1b4048036f840a98e0369bb7c5
[ "BSD-3-Clause" ]
1
2022-03-29T02:58:33.000Z
2022-03-29T02:58:33.000Z
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v3.1.5), do not edit directly. // See also: https://pub.dev/packages/pigeon #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN /// The codec used by FLTPathProviderApi. NSObject<FlutterMessageCodec> *FLTPathProviderApiGetCodec(void); @protocol FLTPathProviderApi - (nullable NSString *)getTemporaryPathWithError:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)getApplicationSupportPathWithError:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)getLibraryPathWithError:(FlutterError *_Nullable *_Nonnull)error; - (nullable NSString *)getApplicationDocumentsPathWithError: (FlutterError *_Nullable *_Nonnull)error; @end extern void FLTPathProviderApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLTPathProviderApi> *_Nullable api); NS_ASSUME_NONNULL_END
40.137931
99
0.790378
99c6f089d131dddc9ca3458ce21fdef26f2b13f2
1,324
h
C
cocos2dx_playground/Classes/algorithm_practice_floodfill_Grid4TileMap.h
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
9
2020-06-11T17:09:44.000Z
2021-12-25T00:34:33.000Z
cocos2dx_playground/Classes/algorithm_practice_floodfill_Grid4TileMap.h
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
9
2019-12-21T15:01:01.000Z
2020-12-05T15:42:43.000Z
cocos2dx_playground/Classes/algorithm_practice_floodfill_Grid4TileMap.h
R2Road/cocos2dx_playground
6e6f349b5c9fc702558fe8720ba9253a8ba00164
[ "Apache-2.0" ]
1
2020-09-07T01:32:16.000Z
2020-09-07T01:32:16.000Z
#pragma once #include <string> #include "algorithm_practice_floodfill_Constant.h" #include "cpg_Grid.h" #include "cpg_Point.h" namespace algorithm_practice_floodfill { class Grid4TileMap { public: using GridT = cpg::Grid<eCellType>; explicit Grid4TileMap(); void Reset( const std::size_t new_width, const std::size_t new_height ); // // Iteration // GridT::ConstIteratorT begin() const { return mGrid.begin(); } GridT::ConstIteratorT end() const { return mGrid.end(); } GridT::IteratorT begin() { return mGrid.begin(); } GridT::IteratorT end() { return mGrid.end(); } // // Getter // std::size_t GetWidth() const { return mGrid.GetWidth(); } std::size_t GetHeight() const { return mGrid.GetHeight(); } const cpg::Point& GetEntryPoint() const { return mEntryPoint; } eCellType GetCellType( const std::size_t x, const std::size_t y ); eCellType GetCellType( const std::size_t x, const std::size_t y ) const; // // Setter // void SetEntryPoint( const cpg::Point& new_entry_point ); void SetCellType( const std::size_t x, const std::size_t y, const eCellType cell_type ); // // File // void ExportJsonString( std::string& out_json_string ) const; bool LoadJsonString( const std::string& json_string ); private: cpg::Point mEntryPoint; GridT mGrid; }; }
24.518519
90
0.693353
fbfec7f50476aa7e2e01fa00bde05c0b73a46fb5
175
h
C
chapter1.h
forgot2015/ForgotCppLearning
9679a47aeee88b460128477342a0457ce8e0fa12
[ "MIT" ]
null
null
null
chapter1.h
forgot2015/ForgotCppLearning
9679a47aeee88b460128477342a0457ce8e0fa12
[ "MIT" ]
null
null
null
chapter1.h
forgot2015/ForgotCppLearning
9679a47aeee88b460128477342a0457ce8e0fa12
[ "MIT" ]
null
null
null
// // Created by forgot on 2017/7/21. // #ifndef FORGOTCPPLEARNING_SAMPLE2_H #define FORGOTCPPLEARNING_SAMPLE2_H class sample2 { }; #endif //FORGOTCPPLEARNING_SAMPLE2_H
11.666667
36
0.765714
b2ed2ae75d44111a49f912ee16e46350c1ffc2e4
15,454
c
C
backend/wayland/pointer.c
git-bruh/wlroots-eglstreams
e9bccfeee7a82db1e89c750a37cb98400e118761
[ "MIT" ]
2
2022-03-14T15:33:03.000Z
2022-03-27T09:40:31.000Z
backend/wayland/pointer.c
git-bruh/wlroots-eglstreams
e9bccfeee7a82db1e89c750a37cb98400e118761
[ "MIT" ]
null
null
null
backend/wayland/pointer.c
git-bruh/wlroots-eglstreams
e9bccfeee7a82db1e89c750a37cb98400e118761
[ "MIT" ]
null
null
null
#define _POSIX_C_SOURCE 200809L #include <assert.h> #include <stdlib.h> #include <wayland-client.h> #include <wlr/interfaces/wlr_pointer.h> #include <wlr/util/log.h> #include "backend/wayland.h" #include "util/signal.h" #include "pointer-gestures-unstable-v1-client-protocol.h" #include "relative-pointer-unstable-v1-client-protocol.h" static struct wlr_wl_pointer *output_get_pointer(struct wlr_wl_output *output, const struct wl_pointer *wl_pointer) { struct wlr_wl_seat *seat; wl_list_for_each(seat, &output->backend->seats, link) { if (seat->wl_pointer != wl_pointer) { continue; } struct wlr_wl_pointer *pointer; wl_list_for_each(pointer, &seat->pointers, link) { if (pointer->output == output) { return pointer; } } } return NULL; } static void pointer_handle_enter(void *data, struct wl_pointer *wl_pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx, wl_fixed_t sy) { struct wlr_wl_seat *seat = data; if (surface == NULL) { return; } struct wlr_wl_output *output = wl_surface_get_user_data(surface); assert(output); struct wlr_wl_pointer *pointer = output_get_pointer(output, wl_pointer); seat->active_pointer = pointer; // Manage cursor icon/rendering on output struct wlr_wl_pointer *current = output->cursor.pointer; if (current && current != pointer) { wlr_log(WLR_INFO, "Ignoring seat '%s' pointer in favor of seat '%s'", seat->name, current->seat->name); return; } output->enter_serial = serial; output->cursor.pointer = pointer; update_wl_output_cursor(output); } static void pointer_handle_leave(void *data, struct wl_pointer *wl_pointer, uint32_t serial, struct wl_surface *surface) { struct wlr_wl_seat *seat = data; if (surface == NULL) { return; } struct wlr_wl_output *output = wl_surface_get_user_data(surface); assert(output); if (seat->active_pointer != NULL && seat->active_pointer->output == output) { seat->active_pointer = NULL; } if (output->cursor.pointer == seat->active_pointer) { output->enter_serial = 0; output->cursor.pointer = NULL; } } static void pointer_handle_motion(void *data, struct wl_pointer *wl_pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_output *wlr_output = &pointer->output->wlr_output; struct wlr_pointer_motion_absolute_event event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .x = wl_fixed_to_double(sx) / wlr_output->width, .y = wl_fixed_to_double(sy) / wlr_output->height, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.motion_absolute, &event); } static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_button_event event = { .pointer = &pointer->wlr_pointer, .button = button, .state = state, .time_msec = time, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.button, &event); } static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_axis_event event = { .pointer = &pointer->wlr_pointer, .delta = wl_fixed_to_double(value), .delta_discrete = pointer->axis_discrete, .orientation = axis, .time_msec = time, .source = pointer->axis_source, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.axis, &event); pointer->axis_discrete = 0; } static void pointer_handle_frame(void *data, struct wl_pointer *wl_pointer) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } wlr_signal_emit_safe(&pointer->wlr_pointer.events.frame, &pointer->wlr_pointer); } static void pointer_handle_axis_source(void *data, struct wl_pointer *wl_pointer, uint32_t axis_source) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } pointer->axis_source = axis_source; } static void pointer_handle_axis_stop(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_axis_event event = { .pointer = &pointer->wlr_pointer, .delta = 0, .delta_discrete = 0, .orientation = axis, .time_msec = time, .source = pointer->axis_source, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.axis, &event); } static void pointer_handle_axis_discrete(void *data, struct wl_pointer *wl_pointer, uint32_t axis, int32_t discrete) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } pointer->axis_discrete = discrete; } static const struct wl_pointer_listener pointer_listener = { .enter = pointer_handle_enter, .leave = pointer_handle_leave, .motion = pointer_handle_motion, .button = pointer_handle_button, .axis = pointer_handle_axis, .frame = pointer_handle_frame, .axis_source = pointer_handle_axis_source, .axis_stop = pointer_handle_axis_stop, .axis_discrete = pointer_handle_axis_discrete, }; static void gesture_swipe_begin(void *data, struct zwp_pointer_gesture_swipe_v1 *zwp_pointer_gesture_swipe_v1, uint32_t serial, uint32_t time, struct wl_surface *surface, uint32_t fingers) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } pointer->fingers = fingers; struct wlr_pointer_swipe_begin_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .fingers = fingers, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.swipe_begin, &wlr_event); } static void gesture_swipe_update(void *data, struct zwp_pointer_gesture_swipe_v1 *zwp_pointer_gesture_swipe_v1, uint32_t time, wl_fixed_t dx, wl_fixed_t dy) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_swipe_update_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .fingers = pointer->fingers, .dx = wl_fixed_to_double(dx), .dy = wl_fixed_to_double(dy), }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.swipe_update, &wlr_event); } static void gesture_swipe_end(void *data, struct zwp_pointer_gesture_swipe_v1 *zwp_pointer_gesture_swipe_v1, uint32_t serial, uint32_t time, int32_t cancelled) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_swipe_end_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .cancelled = cancelled, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.swipe_end, &wlr_event); } static const struct zwp_pointer_gesture_swipe_v1_listener gesture_swipe_impl = { .begin = gesture_swipe_begin, .update = gesture_swipe_update, .end = gesture_swipe_end, }; static void gesture_pinch_begin(void *data, struct zwp_pointer_gesture_pinch_v1 *zwp_pointer_gesture_pinch_v1, uint32_t serial, uint32_t time, struct wl_surface *surface, uint32_t fingers) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } pointer->fingers = fingers; struct wlr_pointer_pinch_begin_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .fingers = pointer->fingers, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.pinch_begin, &wlr_event); } static void gesture_pinch_update(void *data, struct zwp_pointer_gesture_pinch_v1 *zwp_pointer_gesture_pinch_v1, uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, wl_fixed_t rotation) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_pinch_update_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .fingers = pointer->fingers, .dx = wl_fixed_to_double(dx), .dy = wl_fixed_to_double(dy), .scale = wl_fixed_to_double(scale), .rotation = wl_fixed_to_double(rotation), }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.pinch_update, &wlr_event); } static void gesture_pinch_end(void *data, struct zwp_pointer_gesture_pinch_v1 *zwp_pointer_gesture_pinch_v1, uint32_t serial, uint32_t time, int32_t cancelled) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_pinch_end_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .cancelled = cancelled, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.pinch_end, &wlr_event); } static const struct zwp_pointer_gesture_pinch_v1_listener gesture_pinch_impl = { .begin = gesture_pinch_begin, .update = gesture_pinch_update, .end = gesture_pinch_end, }; static void gesture_hold_begin(void *data, struct zwp_pointer_gesture_hold_v1 *zwp_pointer_gesture_hold_v1, uint32_t serial, uint32_t time, struct wl_surface *surface, uint32_t fingers) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } pointer->fingers = fingers; struct wlr_pointer_hold_begin_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .fingers = fingers, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.hold_begin, &wlr_event); } static void gesture_hold_end(void *data, struct zwp_pointer_gesture_hold_v1 *zwp_pointer_gesture_hold_v1, uint32_t serial, uint32_t time, int32_t cancelled) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } struct wlr_pointer_hold_end_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = time, .cancelled = cancelled, }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.hold_end, &wlr_event); } static const struct zwp_pointer_gesture_hold_v1_listener gesture_hold_impl = { .begin = gesture_hold_begin, .end = gesture_hold_end, }; static void relative_pointer_handle_relative_motion(void *data, struct zwp_relative_pointer_v1 *relative_pointer, uint32_t utime_hi, uint32_t utime_lo, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t dx_unaccel, wl_fixed_t dy_unaccel) { struct wlr_wl_seat *seat = data; struct wlr_wl_pointer *pointer = seat->active_pointer; if (pointer == NULL) { return; } uint64_t time_usec = (uint64_t)utime_hi << 32 | utime_lo; struct wlr_pointer_motion_event wlr_event = { .pointer = &pointer->wlr_pointer, .time_msec = (uint32_t)(time_usec / 1000), .delta_x = wl_fixed_to_double(dx), .delta_y = wl_fixed_to_double(dy), .unaccel_dx = wl_fixed_to_double(dx_unaccel), .unaccel_dy = wl_fixed_to_double(dy_unaccel), }; wlr_signal_emit_safe(&pointer->wlr_pointer.events.motion, &wlr_event); } static const struct zwp_relative_pointer_v1_listener relative_pointer_listener = { .relative_motion = relative_pointer_handle_relative_motion, }; const struct wlr_pointer_impl wl_pointer_impl = { .name = "wl-pointer", }; static void destroy_pointer(struct wlr_wl_pointer *pointer) { if (pointer->output->cursor.pointer == pointer) { pointer->output->cursor.pointer = NULL; } wlr_pointer_finish(&pointer->wlr_pointer); wl_list_remove(&pointer->output_destroy.link); wl_list_remove(&pointer->link); free(pointer); } static void pointer_output_destroy(struct wl_listener *listener, void *data) { struct wlr_wl_pointer *pointer = wl_container_of(listener, pointer, output_destroy); destroy_pointer(pointer); } void create_pointer(struct wlr_wl_seat *seat, struct wlr_wl_output *output) { assert(seat->wl_pointer); if (output_get_pointer(output, seat->wl_pointer)) { wlr_log(WLR_DEBUG, "pointer for output '%s' from seat '%s' already exists", output->wlr_output.name, seat->name); return; } wlr_log(WLR_DEBUG, "creating pointer for output '%s' from seat '%s'", output->wlr_output.name, seat->name); struct wlr_wl_pointer *pointer = calloc(1, sizeof(struct wlr_wl_pointer)); if (pointer == NULL) { wlr_log(WLR_ERROR, "failed to allocate wlr_wl_pointer"); return; } char name[64] = {0}; snprintf(name, sizeof(name), "wayland-pointer-%s", seat->name); wlr_pointer_init(&pointer->wlr_pointer, &wl_pointer_impl, name); pointer->wlr_pointer.output_name = strdup(output->wlr_output.name); pointer->seat = seat; pointer->output = output; wl_signal_add(&output->wlr_output.events.destroy, &pointer->output_destroy); pointer->output_destroy.notify = pointer_output_destroy; wlr_signal_emit_safe(&seat->backend->backend.events.new_input, &pointer->wlr_pointer.base); wl_list_insert(&seat->pointers, &pointer->link); } void init_seat_pointer(struct wlr_wl_seat *seat) { assert(seat->wl_pointer); struct wlr_wl_backend *backend = seat->backend; wl_list_init(&seat->pointers); struct wlr_wl_output *output; wl_list_for_each(output, &backend->outputs, link) { create_pointer(seat, output); } if (backend->zwp_pointer_gestures_v1) { uint32_t version = zwp_pointer_gestures_v1_get_version( backend->zwp_pointer_gestures_v1); seat->gesture_swipe = zwp_pointer_gestures_v1_get_swipe_gesture( backend->zwp_pointer_gestures_v1, seat->wl_pointer); zwp_pointer_gesture_swipe_v1_add_listener(seat->gesture_swipe, &gesture_swipe_impl, seat); seat->gesture_pinch = zwp_pointer_gestures_v1_get_pinch_gesture( backend->zwp_pointer_gestures_v1, seat->wl_pointer); zwp_pointer_gesture_pinch_v1_add_listener(seat->gesture_pinch, &gesture_pinch_impl, seat); if (version >= ZWP_POINTER_GESTURES_V1_GET_HOLD_GESTURE) { seat->gesture_hold = zwp_pointer_gestures_v1_get_hold_gesture( backend->zwp_pointer_gestures_v1, seat->wl_pointer); zwp_pointer_gesture_hold_v1_add_listener(seat->gesture_hold, &gesture_hold_impl, seat); } } if (backend->zwp_relative_pointer_manager_v1) { seat->relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer( backend->zwp_relative_pointer_manager_v1, seat->wl_pointer); zwp_relative_pointer_v1_add_listener(seat->relative_pointer, &relative_pointer_listener, seat); } wl_pointer_add_listener(seat->wl_pointer, &pointer_listener, seat); } void finish_seat_pointer(struct wlr_wl_seat *seat) { assert(seat->wl_pointer); wl_pointer_release(seat->wl_pointer); struct wlr_wl_pointer *pointer, *tmp; wl_list_for_each_safe(pointer, tmp, &seat->pointers, link) { destroy_pointer(pointer); } if (seat->gesture_swipe != NULL) { zwp_pointer_gesture_swipe_v1_destroy(seat->gesture_swipe); } if (seat->gesture_pinch != NULL) { zwp_pointer_gesture_pinch_v1_destroy(seat->gesture_pinch); } if (seat->gesture_hold != NULL) { zwp_pointer_gesture_hold_v1_destroy(seat->gesture_hold); } if (seat->relative_pointer != NULL) { zwp_relative_pointer_v1_destroy(seat->relative_pointer); } seat->wl_pointer = NULL; seat->active_pointer = NULL; }
29.268939
82
0.757086
258204a07c0fdbe3c15cb165d738b5a05f18db5e
422
h
C
muenergia/SHT21Module.h
samindaa/uEnergia
6c822019862aa723302a61e035c95b1abb0cc3d0
[ "Apache-1.1" ]
null
null
null
muenergia/SHT21Module.h
samindaa/uEnergia
6c822019862aa723302a61e035c95b1abb0cc3d0
[ "Apache-1.1" ]
null
null
null
muenergia/SHT21Module.h
samindaa/uEnergia
6c822019862aa723302a61e035c95b1abb0cc3d0
[ "Apache-1.1" ]
null
null
null
/* * SHT21Module.h * * Created on: Sep 12, 2014 * Author: sam */ #include "framework/Template.h" #include "SHT21Representation.h" #include "SensorAccessRepresentation.h" MODULE(SHT21Module) PROVIDES(SHT21Representation) // USES(SensorAccessRepresentation) END_MODULE class SHT21Module: public SHT21ModuleBase { public: void init(); void update(SHT21Representation& theSHT21Representation); };
17.583333
61
0.736967
669533f34370154b866b355d9c946dce72b852f1
3,816
h
C
msys64/mingw64/x86_64-w64-mingw32/include/newdev.h
Bhuvanesh1208/ruby2.6.1
17642e3f37233f6d0e0523af68d7600a91ece1c7
[ "Ruby" ]
12,718
2018-05-25T02:00:44.000Z
2022-03-31T23:03:51.000Z
msys64/mingw64/x86_64-w64-mingw32/include/newdev.h
Bhuvanesh1208/ruby2.6.1
17642e3f37233f6d0e0523af68d7600a91ece1c7
[ "Ruby" ]
8,483
2018-05-23T16:22:39.000Z
2022-03-31T22:18:16.000Z
msys64/mingw64/x86_64-w64-mingw32/include/newdev.h
Bhuvanesh1208/ruby2.6.1
17642e3f37233f6d0e0523af68d7600a91ece1c7
[ "Ruby" ]
1,400
2018-05-24T22:35:25.000Z
2022-03-31T21:32:48.000Z
/* * newdev.h * * Driver installation DLL interface * * This file is part of the w32api package. * * Contributors: * Created by Casper S. Hornstrup <chorns@users.sourceforge.net> * * THIS SOFTWARE IS NOT COPYRIGHTED * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #pragma once #include <setupapi.h> #ifdef __cplusplus extern "C" { #endif #include <pshpack1.h> /* UpdateDriverForPlugAndPlayDevices.InstallFlags constants */ #define INSTALLFLAG_FORCE 0x00000001 #define INSTALLFLAG_READONLY 0x00000002 #define INSTALLFLAG_NONINTERACTIVE 0x00000004 #define INSTALLFLAG_BITS 0x00000007 #if (WINVER >= _WIN32_WINNT_WIN2K) WINBOOL WINAPI UpdateDriverForPlugAndPlayDevicesA( HWND hwndParent, LPCSTR HardwareId, LPCSTR FullInfPath, DWORD InstallFlags, PBOOL bRebootRequired OPTIONAL); WINBOOL WINAPI UpdateDriverForPlugAndPlayDevicesW( HWND hwndParent, LPCWSTR HardwareId, LPCWSTR FullInfPath, DWORD InstallFlags, PBOOL bRebootRequired OPTIONAL); #ifdef UNICODE #define UpdateDriverForPlugAndPlayDevices UpdateDriverForPlugAndPlayDevicesW #else #define UpdateDriverForPlugAndPlayDevices UpdateDriverForPlugAndPlayDevicesA #endif /* UNICODE */ #endif /* (WINVER >= _WIN32_WINNT_WIN2K) */ #if (WINVER >= _WIN32_WINNT_VISTA) #define DIIDFLAG_SHOWSEARCHUI 0x00000001 #define DIIDFLAG_NOFINISHINSTALLUI 0x00000002 #define DIIDFLAG_INSTALLNULLDRIVER 0x00000004 #define DIIDFLAG_BITS 0x00000007 #define DIIRFLAG_INF_ALREADY_COPIED 0x00000001 #define DIIRFLAG_FORCE_INF 0x00000002 #define DIIRFLAG_HW_USING_THE_INF 0x00000004 #define DIIRFLAG_HOTPATCH 0x00000008 #define DIIRFLAG_NOBACKUP 0x00000010 #define DIIRFLAG_BITS ( DIIRFLAG_FORCE_INF | DIIRFLAG_HOTPATCH) #define DIIRFLAG_SYSTEM_BITS ( DIIRFLAG_INF_ALREADY_COPIED |\ DIIRFLAG_FORCE_INF |\ DIIRFLAG_HW_USING_THE_INF |\ DIIRFLAG_HOTPATCH |\ DIIRFLAG_NOBACKUP ) #define ROLLBACK_FLAG_NO_UI 0x00000001 #define ROLLBACK_BITS 0x00000001 WINBOOL WINAPI DiInstallDevice( HWND hwndParent OPTIONAL, HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, PSP_DRVINFO_DATA DriverInfoData OPTIONAL, DWORD Flags, PBOOL NeedReboot OPTIONAL); WINBOOL WINAPI DiShowUpdateDevice( HWND hwndParent OPTIONAL, HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Flags, PBOOL NeedReboot OPTIONAL); WINBOOL WINAPI DiRollbackDriver( HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, HWND hwndParent OPTIONAL, DWORD Flags, PBOOL NeedReboot OPTIONAL); WINBOOL WINAPI DiInstallDriverW( HWND hwndParent OPTIONAL, LPCWSTR InfPath, DWORD Flags, PBOOL NeedReboot OPTIONAL); WINBOOL WINAPI DiInstallDriverA( HWND hwndParent OPTIONAL, LPCSTR InfPath, DWORD Flags, PBOOL NeedReboot OPTIONAL); #ifdef UNICODE #define DiInstallDriver DiInstallDriverW #else #define DiInstallDriver DiInstallDriverA #endif #endif /* (WINVER >= _WIN32_WINNT_VISTA) */ #if (WINVER >= _WIN32_WINNT_WIN7) WINBOOL WINAPI DiUninstallDevice( HWND hwndParent, HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Flags, PBOOL NeedReboot OPTIONAL); #endif /* (WINVER >= _WIN32_WINNT_WIN7) */ #include <poppack.h> #ifdef __cplusplus } #endif
24.151899
76
0.735587
baa856f2907f541bcfd08c06215343dc8a7f5bdd
649
h
C
cocos2dx/platform/third_party/blackberry/include/grskia/SkDrawProcs.h
zhouguoshan/cocos2d-xv4
cc77865aed07a14a2fe09101b0d3682519cb3ff5
[ "Zlib", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
45
2015-01-06T02:28:11.000Z
2021-09-01T02:08:52.000Z
cocos2d-2.1beta3-x-2.1.0/cocos2dx/platform/third_party/blackberry/include/grskia/SkDrawProcs.h
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
null
null
null
cocos2d-2.1beta3-x-2.1.0/cocos2dx/platform/third_party/blackberry/include/grskia/SkDrawProcs.h
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
22
2015-02-25T02:24:50.000Z
2022-03-22T02:03:39.000Z
#ifndef SkDrawProcs_DEFINED #define SkDrawProcs_DEFINED #include "SkDraw.h" class SkBlitter; struct SkDraw1Glyph { const SkDraw* fDraw; SkBounder* fBounder; const SkRegion* fClip; SkBlitter* fBlitter; SkGlyphCache* fCache; SkIRect fClipBounds; // The fixed x,y have been pre-rounded (i.e. 1/2 has already been added), // so the impls need just trunc down to an int typedef void (*Proc)(const SkDraw1Glyph&, SkFixed x, SkFixed y, const SkGlyph&); Proc init(const SkDraw* draw, SkBlitter* blitter, SkGlyphCache* cache); }; struct SkDrawProcs { SkDraw1Glyph::Proc fD1GProc; }; #endif
22.37931
82
0.688752
c9660247c1d05c20f37c7e10b3a9584afd60633c
278
h
C
OpenLDAP/contrib/gtk-tool/gtk.h
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
1
2021-02-24T13:01:00.000Z
2021-02-24T13:01:00.000Z
OpenLDAP/contrib/gtk-tool/gtk.h
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
null
null
null
OpenLDAP/contrib/gtk-tool/gtk.h
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
null
null
null
#ifndef MY_GTK_INCLUDES #define MY_GTK_INCLUDES #include <gtk--.h> #include <gtk/gtk.h> #include <gtk--/widget.h> #include <gtk--/button.h> #include <gtk--/window.h> #include <gtk--/list.h> #include <gtk--/main.h> /*#include <gtk--sig.h>*/ #include <gtk--/container.h> #endif
18.533333
28
0.672662
a788ee9a9183456f3b8c6fe1ceb363a8d15e546c
2,286
c
C
src/backend/callback/callback_new_game.c
Ravf95/12h
467f8340a034443539a616a7fd9fc58e64ff4aa5
[ "MIT" ]
1
2019-12-10T21:23:29.000Z
2019-12-10T21:23:29.000Z
src/backend/callback/callback_new_game.c
Ravf95/12h
467f8340a034443539a616a7fd9fc58e64ff4aa5
[ "MIT" ]
null
null
null
src/backend/callback/callback_new_game.c
Ravf95/12h
467f8340a034443539a616a7fd9fc58e64ff4aa5
[ "MIT" ]
1
2019-12-10T21:23:50.000Z
2019-12-10T21:23:50.000Z
/* The MIT License (MIT) Copyright (c) 2017 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. Author: Rodrigo <Ravf> Villalba */ #include <gtk/gtk.h> #include "w_board.h" #include "w_new_game.h" #include "w_status_bar.h" #include "w_vtable_white.h" #include "w_vtable_black.h" #include "f_game.h" #include "ia.h" #include "headers/callback_new_game.h" #define ADV(X) ((X == 0) ? 1 : 0) // @SUB-RUTINA : callback_new_game_ok(GtkWidget *, GdkEvent *, gpointer ) // @UTILIDAD : establecer el inicio del juego. // @PARAMETROS : widget > elemento de la gui asociado. // event > evento por el cual es llamado. // data > apuntador a un tipo de dato externo asociado al widget. // @RETORNO : TRUE > no hay operaciones pendientes. gboolean callback_new_game_ok(GtkWidget *widget, GdkEvent *event, gpointer data) { guint8 mode; mode = w_new_game_get_mode(); ia_set_turno(ADV(mode)); f_game_set_turno(mode); w_status_bar_show(); w_table_white_show(); w_vtable_black_show(); w_statusbar_change_value(); w_board_signal_connect(); w_vtable_white_widget_signal_connect(); w_vtable_black_widget_signal_connect(); f_game_set_config(TRUE); w_new_game_quick_exit(); if (mode == 1) ia(); return TRUE; } #undef ADV
32.657143
81
0.737095
db212b33628dc8a1acce93c184de43c0d61d512d
383
h
C
wwwww/wwwww/tools/Category/UIButton+btn.h
Lantianboy/xcode9-
fb9b0ae3a67809281f392a68636c6c73aa534fdb
[ "MIT" ]
null
null
null
wwwww/wwwww/tools/Category/UIButton+btn.h
Lantianboy/xcode9-
fb9b0ae3a67809281f392a68636c6c73aa534fdb
[ "MIT" ]
null
null
null
wwwww/wwwww/tools/Category/UIButton+btn.h
Lantianboy/xcode9-
fb9b0ae3a67809281f392a68636c6c73aa534fdb
[ "MIT" ]
null
null
null
// // UIButton+btn.h // wwwww // // Created by 最爱是深蓝 on 2017/10/31. // Copyright © 2017年 ProductTest. All rights reserved. // #import <UIKit/UIKit.h> @interface UIButton (btn) //自定义方法 - (instancetype)initWithFrame:(CGRect)frame borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth ; - (void)Hook_setTitle:(NSString *)str forState:(UIControlState *)sta; @end
19.15
113
0.718016
84850446e45e3abb1a752879c97cd6fcbb247895
445
h
C
examples/iosclient/openrvclient/RemoteView.h
monumentsoftware/openrv
4fa5a8b2cb3178041e94afd332571e3064fd5cd2
[ "Apache-2.0" ]
2
2018-04-10T00:43:45.000Z
2018-06-07T06:35:45.000Z
examples/iosclient/openrvclient/RemoteView.h
monumentsoftware/openrv
4fa5a8b2cb3178041e94afd332571e3064fd5cd2
[ "Apache-2.0" ]
null
null
null
examples/iosclient/openrvclient/RemoteView.h
monumentsoftware/openrv
4fa5a8b2cb3178041e94afd332571e3064fd5cd2
[ "Apache-2.0" ]
null
null
null
// // RemoteView.h // opervclient // // Created by christoph on 03.04.18. // Copyright © 2018 Christoph Möde. All rights reserved. // @import UIKit; @import GLKit; #include "RemoteViewController.h" @interface RemoteView : GLKView -(instancetype) initWithFrame:(CGRect)frame; -(void) setRemoteBufferSize:(CGSize)size; -(void) fillRemoteBuffer:(const uint8_t*)data frame:(CGRect)frame; @property RemoteViewController* viewController; @end
21.190476
66
0.748315
84d75a0700aa2106aee0340a04f4e1caed88f311
1,874
c
C
src/callbacks/irc_callbacks.c
slingamn/toxirc
4b709bc1d355ec53a74aba52f11a185215700405
[ "MIT" ]
null
null
null
src/callbacks/irc_callbacks.c
slingamn/toxirc
4b709bc1d355ec53a74aba52f11a185215700405
[ "MIT" ]
null
null
null
src/callbacks/irc_callbacks.c
slingamn/toxirc
4b709bc1d355ec53a74aba52f11a185215700405
[ "MIT" ]
null
null
null
#include "irc_callbacks.h" #include "../irc.h" #include "../settings.h" #include "../tox.h" #include "../commands/irc_commands.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <tox/tox.h> static void message_callback(IRC *irc, char *buffer, void *arg) { Tox *tox = arg; char nick[32], user[32], server[100], channel[IRC_MAX_CHANNEL_LENGTH], msg[256]; int matches = sscanf(buffer, ":%31[^!]!%31[^@]@%99s PRIVMSG %49s :%255[^\r\n]", nick, user, server, channel, msg); if (matches != 5) { return; } // clang-format off char *nosync_prefix = settings_get_prefix(CHAR_NO_SYNC_PREFIX); if (command_prefix_cmp(msg, nosync_prefix)) { // dont sync messages that begin with ~ return; } // clang-format on char *cmd_prefix = settings_get_prefix(CHAR_CMD_PREFIX); if (command_prefix_cmp(msg, cmd_prefix)) { size_t msg_length = strlen(msg); size_t cmd_length; char * cmd = command_parse(msg, msg_length, &cmd_length); if (!cmd) { return; } size_t arg_length; char * arg = command_parse_arg(msg, msg_length, cmd_length, &arg_length); for (int i = 0; irc_commands[i].cmd; i++) { if (strncmp(cmd, irc_commands[i].cmd, strlen(irc_commands[i].cmd)) == 0) { const uint32_t channel_index = irc_get_channel_index(irc, channel); irc_commands[i].func(tox, irc, channel_index, NULL); } } free(cmd); if (arg) { free(arg); } return; // dont sync commands } uint32_t group = irc_get_channel_group(irc, channel); if (group == UINT32_MAX) { return; } tox_group_send_msg(tox, group, nick, msg); } void irc_callbacks_setup(IRC *irc) { irc_set_message_callback(irc, message_callback); }
26.771429
119
0.604055
3b6ab27198354a76e6b58b24995f660ab481a773
926
h
C
User__wpr/User__wpr/User__wpr.h
nolivaldeziii/advanced_csharp-movie-search-engine
b89a202898b9b081d9c30e9aa19088c8f1466bfb
[ "MIT" ]
null
null
null
User__wpr/User__wpr/User__wpr.h
nolivaldeziii/advanced_csharp-movie-search-engine
b89a202898b9b081d9c30e9aa19088c8f1466bfb
[ "MIT" ]
null
null
null
User__wpr/User__wpr/User__wpr.h
nolivaldeziii/advanced_csharp-movie-search-engine
b89a202898b9b081d9c30e9aa19088c8f1466bfb
[ "MIT" ]
null
null
null
// User__wpr.h #pragma once #include "C:\\Users\\Noli\\Dropbox\\Programming\\Projects\\Movie Search Engine\\UserClass_Unmanaged\\User.h" //#include "C:\\Users\\Noli\\Dropbox\\Programming\\Projects\\Movie Search Engine\\UserClass_Unmanaged\\FilestreamMP.cpp" #include "C:\\Users\\Noli\\Dropbox\\Programming\\Projects\\Movie Search Engine\\Database\\Database\\Database.h" #include "C:\\Users\\Noli\\Dropbox\\Programming\\Projects\\Movie Search Engine\\Database\\Database\\Database.cpp" using namespace System; namespace User__wpr { public ref class User_wpr { public: char* username; char* fullname; char* password; char* email; char* verification; char* verified; public: User_wpr(); void GetUsername(char*); void GetFullname(char*); void GetPassword(char*); void GetEmail(char*); void GetVerification(char*); bool checkPassword(char*); void GetUser(char*); void SaveUser(); }; }
22.585366
120
0.720302
5f2aec98db2936a26efcf8343207744f994a091a
1,198
c
C
esp8266_gen2/test_system/test_system.c
cnlohr/esptracker
d466c3e558f3e9b7f55fa650f08b5b3c8c6f7193
[ "MIT" ]
49
2018-04-11T12:31:33.000Z
2022-01-06T07:58:44.000Z
esp8266_gen2/test_system/test_system.c
cnlohr/esptracker
d466c3e558f3e9b7f55fa650f08b5b3c8c6f7193
[ "MIT" ]
4
2018-07-22T06:05:49.000Z
2020-04-27T20:35:13.000Z
esp8266_gen2/test_system/test_system.c
cnlohr/esptracker
d466c3e558f3e9b7f55fa650f08b5b3c8c6f7193
[ "MIT" ]
10
2018-11-19T03:02:10.000Z
2021-12-28T13:55:15.000Z
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <lighthouse_decode.h> int main() { int rs = 0; lighthouse_setup(); for( ; ; rs++ ) { int i; int srlen = (rand()%100)+2; uint32_t buffer[srlen]; int offset = rand()%32; int freq = rand()%20; int first_off = rand()%32; for( i = 0; i < srlen; i++ ) { buffer[i] = rand(); } buffer[i-1] = 0; buffer[0] = 0; buffer[1] &= (1<<offset)-1; printf( "%08x\n", buffer[1] ); //printf( "%d / %d\n", rs, srlen ); lighthouse_decode( buffer, srlen ); } } int SendPacket( struct LightEvent * le ) { /* uint8_t gotlock; //Is nonzero when data is good ( uint8_t freq_denominator; uint16_t freq_numerator; uint16_t full_length; uint16_t strength; //in total ticks the signal was asserted. uint32_t average_numerator; //Compressed average. Divide by strength to get real average. uint32_t firsttransition; //In ticks uint8_t t1mark; uint8_t t2mark; uint8_t t3mark; uint8_t t4mark; */ printf( "%d %d %d / %d %d / %d %d %08x\n", le->gotlock, le->freq_denominator, le->freq_numerator, le->full_length, le->strength, le->average_numerator, le->firsttransition, LHSM.timebase ); }
21.392857
148
0.641068
9a1d38b2030e00531b95ef0e18a0ec37693db1b8
55,652
c
C
pTk/mTk/generic/tkPack.c
bekuno/perl-tk
ab69338e7a7d052d31b25fa54f920b1826b3b5af
[ "TCL" ]
28
2015-01-02T00:31:12.000Z
2021-12-21T09:03:05.000Z
pTk/mTk/generic/tkPack.c
bekuno/perl-tk
ab69338e7a7d052d31b25fa54f920b1826b3b5af
[ "TCL" ]
44
2015-01-07T22:25:25.000Z
2022-03-28T13:34:44.000Z
pTk/mTk/generic/tkPack.c
bekuno/perl-tk
ab69338e7a7d052d31b25fa54f920b1826b3b5af
[ "TCL" ]
18
2015-01-02T00:32:47.000Z
2022-03-24T12:57:40.000Z
/* * tkPack.c -- * * This file contains code to implement the "packer" * geometry manager for Tk. * * Copyright (c) 1990-1994 The Regents of the University of California. * Copyright (c) 1994-1997 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tkPack.c,v 1.16.2.1 2003/07/17 03:17:08 dgp Exp $ */ #include "tkPort.h" #include "tkInt.h" typedef enum {TOP, BOTTOM, LEFT, RIGHT} Side; static CONST char *sideNames[] = { "top", "bottom", "left", "right", (char *) NULL }; /* For each window that the packer cares about (either because * the window is managed by the packer or because the window * has slaves that are managed by the packer), there is a * structure of the following type: */ typedef struct Packer { Tk_Window tkwin; /* Tk token for window. NULL means that * the window has been deleted, but the * packet hasn't had a chance to clean up * yet because the structure is still in * use. */ struct Packer *masterPtr; /* Master window within which this window * is packed (NULL means this window * isn't managed by the packer). */ struct Packer *nextPtr; /* Next window packed within same * parent. List is priority-ordered: * first on list gets packed first. */ struct Packer *slavePtr; /* First in list of slaves packed * inside this window (NULL means * no packed slaves). */ Side side; /* Side of parent against which * this window is packed. */ Tk_Anchor anchor; /* If frame allocated for window is larger * than window needs, this indicates how * where to position window in frame. */ int padX, padY; /* Total additional pixels to leave around the * window. Some is of this space is on each * side. This is space *outside* the window: * we'll allocate extra space in frame but * won't enlarge window). */ int padLeft, padTop; /* The part of padX or padY to use on the * left or top of the widget, respectively. * By default, this is half of padX or padY. */ int iPadX, iPadY; /* Total extra pixels to allocate inside the * window (half of this amount will appear on * each side). */ int doubleBw; /* Twice the window's last known border * width. If this changes, the window * must be repacked within its parent. */ int *abortPtr; /* If non-NULL, it means that there is a nested * call to ArrangePacking already working on * this window. *abortPtr may be set to 1 to * abort that nested call. This happens, for * example, if tkwin or any of its slaves * is deleted. */ int flags; /* Miscellaneous flags; see below * for definitions. */ } Packer; /* * Flag values for Packer structures: * * REQUESTED_REPACK: 1 means a Tcl_DoWhenIdle request * has already been made to repack * all the slaves of this window. * FILLX: 1 means if frame allocated for window * is wider than window needs, expand window * to fill frame. 0 means don't make window * any larger than needed. * FILLY: Same as FILLX, except for height. * EXPAND: 1 means this window's frame will absorb any * extra space in the parent window. * OLD_STYLE: 1 means this window is being managed with * the old-style packer algorithms (before * Tk version 3.3). The main difference is * that padding and filling are done differently. * DONT_PROPAGATE: 1 means don't set this window's requested * size. 0 means if this window is a master * then Tk will set its requested size to fit * the needs of its slaves. */ #define REQUESTED_REPACK 1 #define FILLX 2 #define FILLY 4 #define EXPAND 8 #define OLD_STYLE 16 #define DONT_PROPAGATE 32 /* * The following structure is the official type record for the * packer: */ static void PackReqProc _ANSI_ARGS_((ClientData clientData, Tk_Window tkwin)); static void PackLostSlaveProc _ANSI_ARGS_((ClientData clientData, Tk_Window tkwin)); static Tk_GeomMgr packerType = { "pack", /* name */ PackReqProc, /* requestProc */ PackLostSlaveProc, /* lostSlaveProc */ }; /* * Forward declarations for procedures defined later in this file: */ static void ArrangePacking _ANSI_ARGS_((ClientData clientData)); static int ConfigureSlaves _ANSI_ARGS_((Tcl_Interp *interp, Tk_Window tkwin, int objc, Tcl_Obj *CONST objv[])); static void DestroyPacker _ANSI_ARGS_((char *memPtr)); static Packer * GetPacker _ANSI_ARGS_((Tk_Window tkwin)); static int PackAfter _ANSI_ARGS_((Tcl_Interp *interp, Packer *prevPtr, Packer *masterPtr, int objc, Tcl_Obj *CONST objv[])); static void PackReqProc _ANSI_ARGS_((ClientData clientData, Tk_Window tkwin)); static void PackStructureProc _ANSI_ARGS_((ClientData clientData, XEvent *eventPtr)); static void Unlink _ANSI_ARGS_((Packer *packPtr)); static int XExpansion _ANSI_ARGS_((Packer *slavePtr, int cavityWidth)); static int YExpansion _ANSI_ARGS_((Packer *slavePtr, int cavityHeight)); /* *-------------------------------------------------------------- * * TkPrintPadAmount -- * * This procedure generates a text value that describes one * of the -padx, -pady, -ipadx, or -ipady configuration options. * The text value generated is appended to the interpreter * result. * * Results: * None. * * Side effects: * None. * *-------------------------------------------------------------- */ void TkPrintPadAmount(interp, switchName, halfSpace, allSpace) Tcl_Interp *interp; /* The interpreter into which the result * is written. */ char *switchName; /* One of "padx", "pady", "ipadx" or "ipady" */ int halfSpace; /* The left or top padding amount */ int allSpace; /* The total amount of padding */ { char buffer[60 + 2*TCL_INTEGER_SPACE]; sprintf(buffer, "-%.10s", switchName); Tcl_AppendElement(interp, buffer); if (halfSpace*2 == allSpace) { Tcl_IntResults(interp, 1, 1, halfSpace); } else { Tcl_Obj *list = Tcl_NewListObj(0,NULL); Tcl_ListObjAppendElement(interp, list, Tcl_NewIntObj(halfSpace)); Tcl_ListObjAppendElement(interp, list, Tcl_NewIntObj(allSpace - halfSpace)); Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp), list); } } /* *-------------------------------------------------------------- * * Tk_PackCmd -- * * This procedure is invoked to process the "pack" Tcl command. * See the user documentation for details on what it does. * * Results: * A standard Tcl result. * * Side effects: * See the user documentation. * *-------------------------------------------------------------- */ int Tk_PackObjCmd(clientData, interp, objc, objv) ClientData clientData; /* Main window associated with * interpreter. */ Tcl_Interp *interp; /* Current interpreter. */ int objc; /* Number of arguments. */ Tcl_Obj *CONST objv[]; /* Argument objects. */ { Tk_Window tkwin = (Tk_Window) clientData; char *argv2; static CONST char *optionStrings[] = { /* after, append, before and unpack are deprecated */ "after", "append", "before", "unpack", "configure", "forget", "info", "propagate", "slaves", (char *) NULL }; enum options { PACK_AFTER, PACK_APPEND, PACK_BEFORE, PACK_UNPACK, PACK_CONFIGURE, PACK_FORGET, PACK_INFO, PACK_PROPAGATE, PACK_SLAVES }; int index; if (objc >= 2) { char *string = Tcl_GetString(objv[1]); if (string[0] == '.') { return ConfigureSlaves(interp, tkwin, objc-1, objv+1); } } if (objc < 3) { Tcl_WrongNumArgs(interp, 1, objv, "option arg ?arg ...?"); return TCL_ERROR; } if (Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0, &index) != TCL_OK) { /* * Call it again without the deprecated ones to get a proper * error message. * This works well since there can't be any ambiguity between * deprecated and new options. */ Tcl_ResetResult(interp); Tcl_GetIndexFromObj(interp, objv[1], &optionStrings[4], "option", 0, &index); return TCL_ERROR; } argv2 = Tcl_GetString(objv[2]); if (index == PACK_AFTER) { Packer *prevPtr; Tk_Window tkwin2; if (TkGetWindowFromObj(interp, tkwin, objv[2], &tkwin2) != TCL_OK) { return TCL_ERROR; } prevPtr = GetPacker(tkwin2); if (prevPtr->masterPtr == NULL) { Tcl_AppendResult(interp, "window \"", argv2, "\" isn't packed", (char *) NULL); return TCL_ERROR; } return PackAfter(interp, prevPtr, prevPtr->masterPtr, objc-3, objv+3); } else if (index == PACK_APPEND) { Packer *masterPtr; register Packer *prevPtr; Tk_Window tkwin2; if (TkGetWindowFromObj(interp, tkwin, objv[2], &tkwin2) != TCL_OK) { return TCL_ERROR; } masterPtr = GetPacker(tkwin2); prevPtr = masterPtr->slavePtr; if (prevPtr != NULL) { while (prevPtr->nextPtr != NULL) { prevPtr = prevPtr->nextPtr; } } return PackAfter(interp, prevPtr, masterPtr, objc-3, objv+3); } else if (index == PACK_BEFORE) { Packer *packPtr, *masterPtr; register Packer *prevPtr; Tk_Window tkwin2; if (TkGetWindowFromObj(interp, tkwin, objv[2], &tkwin2) != TCL_OK) { return TCL_ERROR; } packPtr = GetPacker(tkwin2); if (packPtr->masterPtr == NULL) { Tcl_AppendResult(interp, "window \"", argv2, "\" isn't packed", (char *) NULL); return TCL_ERROR; } masterPtr = packPtr->masterPtr; prevPtr = masterPtr->slavePtr; if (prevPtr == packPtr) { prevPtr = NULL; } else { for ( ; ; prevPtr = prevPtr->nextPtr) { if (prevPtr == NULL) { panic("\"pack before\" couldn't find predecessor"); } if (prevPtr->nextPtr == packPtr) { break; } } } return PackAfter(interp, prevPtr, masterPtr, objc-3, objv+3); } else if (index == PACK_CONFIGURE) { if (argv2[0] != '.') { Tcl_AppendResult(interp, "bad argument \"", argv2, "\": must be name of window", (char *) NULL); return TCL_ERROR; } return ConfigureSlaves(interp, tkwin, objc-2, objv+2); } else if (index == PACK_FORGET) { Tk_Window slave; Packer *slavePtr; int i; for (i = 2; i < objc; i++) { if (TkGetWindowFromObj(interp, tkwin, objv[i], &slave) != TCL_OK) { continue; } slavePtr = GetPacker(slave); if ((slavePtr != NULL) && (slavePtr->masterPtr != NULL)) { Tk_ManageGeometry(slave, (Tk_GeomMgr *) NULL, (ClientData) NULL); if (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin)) { Tk_UnmaintainGeometry(slavePtr->tkwin, slavePtr->masterPtr->tkwin); } Unlink(slavePtr); Tk_UnmapWindow(slavePtr->tkwin); } } } else if (index == PACK_INFO) { register Packer *slavePtr; Tk_Window slave; if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "window"); return TCL_ERROR; } if (TkGetWindowFromObj(interp, tkwin, objv[2], &slave) != TCL_OK) { return TCL_ERROR; } slavePtr = GetPacker(slave); if (slavePtr->masterPtr == NULL) { Tcl_AppendResult(interp, "window \"", argv2, "\" isn't packed", (char *) NULL); return TCL_ERROR; } Tcl_AppendElement(interp, "-in"); Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp), LangWidgetObj(interp,slavePtr->masterPtr->tkwin)); Tcl_AppendElement(interp, "-anchor"); Tcl_AppendElement(interp, Tk_NameOfAnchor(slavePtr->anchor)); Tcl_AppendElement(interp, "-expand"); Tcl_IntResults(interp, 1, 1, (slavePtr->flags & EXPAND) != 0); Tcl_AppendElement(interp, "-fill"); switch (slavePtr->flags & (FILLX|FILLY)) { case 0: Tcl_AppendElement(interp, "none"); break; case FILLX: Tcl_AppendElement(interp, "x"); break; case FILLY: Tcl_AppendElement(interp, "y"); break; case FILLX|FILLY: Tcl_AppendElement(interp, "both"); break; } TkPrintPadAmount(interp, "ipadx", slavePtr->iPadX/2, slavePtr->iPadX); TkPrintPadAmount(interp, "ipady", slavePtr->iPadY/2, slavePtr->iPadY); TkPrintPadAmount(interp, "padx", slavePtr->padLeft, slavePtr->padX); TkPrintPadAmount(interp, "pady", slavePtr->padTop, slavePtr->padY); Tcl_AppendElement(interp, "-side"); Tcl_AppendElement(interp, sideNames[slavePtr->side]); } else if (index == PACK_PROPAGATE) { Tk_Window master; Packer *masterPtr; int propagate; if (objc > 4) { Tcl_WrongNumArgs(interp, 2, objv, "window ?boolean?"); return TCL_ERROR; } if (TkGetWindowFromObj(interp, tkwin, objv[2], &master) != TCL_OK) { return TCL_ERROR; } masterPtr = GetPacker(master); if (objc == 3) { Tcl_SetObjResult(interp, Tcl_NewBooleanObj(!(masterPtr->flags & DONT_PROPAGATE))); return TCL_OK; } if (Tcl_GetBooleanFromObj(interp, objv[3], &propagate) != TCL_OK) { return TCL_ERROR; } if (propagate) { masterPtr->flags &= ~DONT_PROPAGATE; /* * Repack the master to allow new geometry information to * propagate upwards to the master's master. */ if (masterPtr->abortPtr != NULL) { *masterPtr->abortPtr = 1; } if (!(masterPtr->flags & REQUESTED_REPACK)) { masterPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); } } else { masterPtr->flags |= DONT_PROPAGATE; } } else if (index == PACK_SLAVES) { Tk_Window master; Packer *masterPtr, *slavePtr; if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "window"); return TCL_ERROR; } if (TkGetWindowFromObj(interp, tkwin, objv[2], &master) != TCL_OK) { return TCL_ERROR; } masterPtr = GetPacker(master); for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; slavePtr = slavePtr->nextPtr) { Tcl_ListObjAppendElement(interp,Tcl_GetObjResult(interp), LangWidgetObj(interp,slavePtr->tkwin)); } } else if (index == PACK_UNPACK) { Tk_Window tkwin2; Packer *packPtr; if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "window"); return TCL_ERROR; } if (TkGetWindowFromObj(interp, tkwin, objv[2], &tkwin2) != TCL_OK) { return TCL_ERROR; } packPtr = GetPacker(tkwin2); if ((packPtr != NULL) && (packPtr->masterPtr != NULL)) { Tk_ManageGeometry(tkwin2, (Tk_GeomMgr *) NULL, (ClientData) NULL); if (packPtr->masterPtr->tkwin != Tk_Parent(packPtr->tkwin)) { Tk_UnmaintainGeometry(packPtr->tkwin, packPtr->masterPtr->tkwin); } Unlink(packPtr); Tk_UnmapWindow(packPtr->tkwin); } } return TCL_OK; } /* *-------------------------------------------------------------- * * PackReqProc -- * * This procedure is invoked by Tk_GeometryRequest for * windows managed by the packer. * * Results: * None. * * Side effects: * Arranges for tkwin, and all its managed siblings, to * be re-packed at the next idle point. * *-------------------------------------------------------------- */ /* ARGSUSED */ static void PackReqProc(clientData, tkwin) ClientData clientData; /* Packer's information about * window that got new preferred * geometry. */ Tk_Window tkwin; /* Other Tk-related information * about the window. */ { register Packer *packPtr = (Packer *) clientData; packPtr = packPtr->masterPtr; if (!(packPtr->flags & REQUESTED_REPACK)) { packPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr); } } /* *-------------------------------------------------------------- * * PackLostSlaveProc -- * * This procedure is invoked by Tk whenever some other geometry * claims control over a slave that used to be managed by us. * * Results: * None. * * Side effects: * Forgets all packer-related information about the slave. * *-------------------------------------------------------------- */ /* ARGSUSED */ static void PackLostSlaveProc(clientData, tkwin) ClientData clientData; /* Packer structure for slave window that * was stolen away. */ Tk_Window tkwin; /* Tk's handle for the slave window. */ { register Packer *slavePtr = (Packer *) clientData; if (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin)) { Tk_UnmaintainGeometry(slavePtr->tkwin, slavePtr->masterPtr->tkwin); } Unlink(slavePtr); Tk_UnmapWindow(slavePtr->tkwin); } /* *-------------------------------------------------------------- * * ArrangePacking -- * * This procedure is invoked (using the Tcl_DoWhenIdle * mechanism) to re-layout a set of windows managed by * the packer. It is invoked at idle time so that a * series of packer requests can be merged into a single * layout operation. * * Results: * None. * * Side effects: * The packed slaves of masterPtr may get resized or * moved. * *-------------------------------------------------------------- */ static void ArrangePacking(clientData) ClientData clientData; /* Structure describing parent whose slaves * are to be re-layed out. */ { register Packer *masterPtr = (Packer *) clientData; register Packer *slavePtr; int cavityX, cavityY, cavityWidth, cavityHeight; /* These variables keep track of the * as-yet-unallocated space remaining in * the middle of the parent window. */ int frameX, frameY, frameWidth, frameHeight; /* These variables keep track of the frame * allocated to the current window. */ int x, y, width, height; /* These variables are used to hold the * actual geometry of the current window. */ int abort; /* May get set to non-zero to abort this * repacking operation. */ int borderX, borderY; int borderTop, borderBtm; int borderLeft, borderRight; int maxWidth, maxHeight, tmp; masterPtr->flags &= ~REQUESTED_REPACK; /* * If the parent has no slaves anymore, then don't do anything * at all: just leave the parent's size as-is. */ if (masterPtr->slavePtr == NULL) { return; } /* * Abort any nested call to ArrangePacking for this window, since * we'll do everything necessary here, and set up so this call * can be aborted if necessary. */ if (masterPtr->abortPtr != NULL) { *masterPtr->abortPtr = 1; } masterPtr->abortPtr = &abort; abort = 0; Tcl_Preserve((ClientData) masterPtr); /* * Pass #1: scan all the slaves to figure out the total amount * of space needed. Two separate width and height values are * computed: * * width - Holds the sum of the widths (plus padding) of * all the slaves seen so far that were packed LEFT * or RIGHT. * height - Holds the sum of the heights (plus padding) of * all the slaves seen so far that were packed TOP * or BOTTOM. * * maxWidth - Gradually builds up the width needed by the master * to just barely satisfy all the slave's needs. For * each slave, the code computes the width needed for * all the slaves so far and updates maxWidth if the * new value is greater. * maxHeight - Same as maxWidth, except keeps height info. */ width = maxWidth = Tk_InternalBorderLeft(masterPtr->tkwin) + Tk_InternalBorderRight(masterPtr->tkwin); height = maxHeight = Tk_InternalBorderTop(masterPtr->tkwin) + Tk_InternalBorderBottom(masterPtr->tkwin); for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; slavePtr = slavePtr->nextPtr) { if ((slavePtr->side == TOP) || (slavePtr->side == BOTTOM)) { tmp = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padX + slavePtr->iPadX + width; if (tmp > maxWidth) { maxWidth = tmp; } height += Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padY + slavePtr->iPadY; } else { tmp = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padY + slavePtr->iPadY + height; if (tmp > maxHeight) { maxHeight = tmp; } width += Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padX + slavePtr->iPadX; } } if (width > maxWidth) { maxWidth = width; } if (height > maxHeight) { maxHeight = height; } if (maxWidth < Tk_MinReqWidth(masterPtr->tkwin)) { maxWidth = Tk_MinReqWidth(masterPtr->tkwin); } if (maxHeight < Tk_MinReqHeight(masterPtr->tkwin)) { maxHeight = Tk_MinReqHeight(masterPtr->tkwin); } /* * If the total amount of space needed in the parent window has * changed, and if we're propagating geometry information, then * notify the next geometry manager up and requeue ourselves to * start again after the parent has had a chance to * resize us. */ if (((maxWidth != Tk_ReqWidth(masterPtr->tkwin)) || (maxHeight != Tk_ReqHeight(masterPtr->tkwin))) && !(masterPtr->flags & DONT_PROPAGATE)) { Tk_GeometryRequest(masterPtr->tkwin, maxWidth, maxHeight); masterPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); goto done; } /* * Pass #2: scan the slaves a second time assigning * new sizes. The "cavity" variables keep track of the * unclaimed space in the cavity of the window; this * shrinks inward as we allocate windows around the * edges. The "frame" variables keep track of the space * allocated to the current window and its frame. The * current window is then placed somewhere inside the * frame, depending on anchor. */ cavityX = x = Tk_InternalBorderLeft(masterPtr->tkwin); cavityY = y = Tk_InternalBorderTop(masterPtr->tkwin); cavityWidth = Tk_Width(masterPtr->tkwin) - Tk_InternalBorderLeft(masterPtr->tkwin) - Tk_InternalBorderRight(masterPtr->tkwin); cavityHeight = Tk_Height(masterPtr->tkwin) - Tk_InternalBorderTop(masterPtr->tkwin) - Tk_InternalBorderBottom(masterPtr->tkwin); for (slavePtr = masterPtr->slavePtr; slavePtr != NULL; slavePtr = slavePtr->nextPtr) { if ((slavePtr->side == TOP) || (slavePtr->side == BOTTOM)) { frameWidth = cavityWidth; frameHeight = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padY + slavePtr->iPadY; if (slavePtr->flags & EXPAND) { frameHeight += YExpansion(slavePtr, cavityHeight); } cavityHeight -= frameHeight; if (cavityHeight < 0) { frameHeight += cavityHeight; cavityHeight = 0; } frameX = cavityX; if (slavePtr->side == TOP) { frameY = cavityY; cavityY += frameHeight; } else { frameY = cavityY + cavityHeight; } } else { frameHeight = cavityHeight; frameWidth = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padX + slavePtr->iPadX; if (slavePtr->flags & EXPAND) { frameWidth += XExpansion(slavePtr, cavityWidth); } cavityWidth -= frameWidth; if (cavityWidth < 0) { frameWidth += cavityWidth; cavityWidth = 0; } frameY = cavityY; if (slavePtr->side == LEFT) { frameX = cavityX; cavityX += frameWidth; } else { frameX = cavityX + cavityWidth; } } /* * Now that we've got the size of the frame for the window, * compute the window's actual size and location using the * fill, padding, and frame factors. The variables "borderX" * and "borderY" are used to handle the differences between * old-style packing and the new style (in old-style, iPadX * and iPadY are always zero and padding is completely ignored * except when computing frame size). */ if (slavePtr->flags & OLD_STYLE) { borderX = borderY = 0; borderTop = borderBtm = 0; borderLeft = borderRight = 0; } else { borderX = slavePtr->padX; borderY = slavePtr->padY; borderLeft = slavePtr->padLeft; borderRight = borderX - borderLeft; borderTop = slavePtr->padTop; borderBtm = borderY - borderTop; } width = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->iPadX; if ((slavePtr->flags & FILLX) || (width > (frameWidth - borderX))) { width = frameWidth - borderX; } height = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->iPadY; if ((slavePtr->flags & FILLY) || (height > (frameHeight - borderY))) { height = frameHeight - borderY; } switch (slavePtr->anchor) { case TK_ANCHOR_N: x = frameX + (borderLeft + frameWidth - width - borderRight)/2; y = frameY + borderTop; break; case TK_ANCHOR_NE: x = frameX + frameWidth - width - borderRight; y = frameY + borderTop; break; case TK_ANCHOR_E: x = frameX + frameWidth - width - borderRight; y = frameY + (borderTop + frameHeight - height - borderBtm)/2; break; case TK_ANCHOR_SE: x = frameX + frameWidth - width - borderRight; y = frameY + frameHeight - height - borderBtm; break; case TK_ANCHOR_S: x = frameX + (borderLeft + frameWidth - width - borderRight)/2; y = frameY + frameHeight - height - borderBtm; break; case TK_ANCHOR_SW: x = frameX + borderLeft; y = frameY + frameHeight - height - borderBtm; break; case TK_ANCHOR_W: x = frameX + borderLeft; y = frameY + (borderTop + frameHeight - height - borderBtm)/2; break; case TK_ANCHOR_NW: x = frameX + borderLeft; y = frameY + borderTop; break; case TK_ANCHOR_CENTER: x = frameX + (borderLeft + frameWidth - width - borderRight)/2; y = frameY + (borderTop + frameHeight - height - borderBtm)/2; break; default: panic("bad frame factor in ArrangePacking"); } width -= slavePtr->doubleBw; height -= slavePtr->doubleBw; /* * The final step is to set the position, size, and mapped/unmapped * state of the slave. If the slave is a child of the master, then * do this here. Otherwise let Tk_MaintainGeometry do the work. */ if (masterPtr->tkwin == Tk_Parent(slavePtr->tkwin)) { if ((width <= 0) || (height <= 0)) { Tk_UnmapWindow(slavePtr->tkwin); } else { if ((x != Tk_X(slavePtr->tkwin)) || (y != Tk_Y(slavePtr->tkwin)) || (width != Tk_Width(slavePtr->tkwin)) || (height != Tk_Height(slavePtr->tkwin))) { Tk_MoveResizeWindow(slavePtr->tkwin, x, y, width, height); } if (abort) { goto done; } /* * Don't map the slave if the master isn't mapped: wait * until the master gets mapped later. */ if (Tk_IsMapped(masterPtr->tkwin)) { Tk_MapWindow(slavePtr->tkwin); } } } else { if ((width <= 0) || (height <= 0)) { Tk_UnmaintainGeometry(slavePtr->tkwin, masterPtr->tkwin); Tk_UnmapWindow(slavePtr->tkwin); } else { Tk_MaintainGeometry(slavePtr->tkwin, masterPtr->tkwin, x, y, width, height); } } /* * Changes to the window's structure could cause almost anything * to happen, including deleting the parent or child. If this * happens, we'll be told to abort. */ if (abort) { goto done; } } done: masterPtr->abortPtr = NULL; Tcl_Release((ClientData) masterPtr); } /* *---------------------------------------------------------------------- * * XExpansion -- * * Given a list of packed slaves, the first of which is packed * on the left or right and is expandable, compute how much to * expand the child. * * Results: * The return value is the number of additional pixels to give to * the child. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int XExpansion(slavePtr, cavityWidth) register Packer *slavePtr; /* First in list of remaining * slaves. */ int cavityWidth; /* Horizontal space left for all * remaining slaves. */ { int numExpand, minExpand, curExpand; int childWidth; /* * This procedure is tricky because windows packed top or bottom can * be interspersed among expandable windows packed left or right. * Scan through the list, keeping a running sum of the widths of * all left and right windows (actually, count the cavity space not * allocated) and a running count of all expandable left and right * windows. At each top or bottom window, and at the end of the * list, compute the expansion factor that seems reasonable at that * point. Return the smallest factor seen at any of these points. */ minExpand = cavityWidth; numExpand = 0; for ( ; slavePtr != NULL; slavePtr = slavePtr->nextPtr) { childWidth = Tk_ReqWidth(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padX + slavePtr->iPadX; if ((slavePtr->side == TOP) || (slavePtr->side == BOTTOM)) { curExpand = (cavityWidth - childWidth)/numExpand; if (curExpand < minExpand) { minExpand = curExpand; } } else { cavityWidth -= childWidth; if (slavePtr->flags & EXPAND) { numExpand++; } } } curExpand = cavityWidth/numExpand; if (curExpand < minExpand) { minExpand = curExpand; } return (minExpand < 0) ? 0 : minExpand; } /* *---------------------------------------------------------------------- * * YExpansion -- * * Given a list of packed slaves, the first of which is packed * on the top or bottom and is expandable, compute how much to * expand the child. * * Results: * The return value is the number of additional pixels to give to * the child. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int YExpansion(slavePtr, cavityHeight) register Packer *slavePtr; /* First in list of remaining * slaves. */ int cavityHeight; /* Vertical space left for all * remaining slaves. */ { int numExpand, minExpand, curExpand; int childHeight; /* * See comments for XExpansion. */ minExpand = cavityHeight; numExpand = 0; for ( ; slavePtr != NULL; slavePtr = slavePtr->nextPtr) { childHeight = Tk_ReqHeight(slavePtr->tkwin) + slavePtr->doubleBw + slavePtr->padY + slavePtr->iPadY; if ((slavePtr->side == LEFT) || (slavePtr->side == RIGHT)) { curExpand = (cavityHeight - childHeight)/numExpand; if (curExpand < minExpand) { minExpand = curExpand; } } else { cavityHeight -= childHeight; if (slavePtr->flags & EXPAND) { numExpand++; } } } curExpand = cavityHeight/numExpand; if (curExpand < minExpand) { minExpand = curExpand; } return (minExpand < 0) ? 0 : minExpand; } /* *-------------------------------------------------------------- * * GetPacker -- * * This internal procedure is used to locate a Packer * structure for a given window, creating one if one * doesn't exist already. * * Results: * The return value is a pointer to the Packer structure * corresponding to tkwin. * * Side effects: * A new packer structure may be created. If so, then * a callback is set up to clean things up when the * window is deleted. * *-------------------------------------------------------------- */ static Packer * GetPacker(tkwin) Tk_Window tkwin; /* Token for window for which * packer structure is desired. */ { register Packer *packPtr; Tcl_HashEntry *hPtr; int new; TkDisplay *dispPtr = ((TkWindow *) tkwin)->dispPtr; if (!dispPtr->packInit) { dispPtr->packInit = 1; Tcl_InitHashTable(&dispPtr->packerHashTable, TCL_ONE_WORD_KEYS); } /* * See if there's already packer for this window. If not, * then create a new one. */ hPtr = Tcl_CreateHashEntry(&dispPtr->packerHashTable, (char *) tkwin, &new); if (!new) { return (Packer *) Tcl_GetHashValue(hPtr); } packPtr = (Packer *) ckalloc(sizeof(Packer)); packPtr->tkwin = tkwin; packPtr->masterPtr = NULL; packPtr->nextPtr = NULL; packPtr->slavePtr = NULL; packPtr->side = TOP; packPtr->anchor = TK_ANCHOR_CENTER; packPtr->padX = packPtr->padY = 0; packPtr->padLeft = packPtr->padTop = 0; packPtr->iPadX = packPtr->iPadY = 0; packPtr->doubleBw = 2*Tk_Changes(tkwin)->border_width; packPtr->abortPtr = NULL; packPtr->flags = 0; Tcl_SetHashValue(hPtr, packPtr); Tk_CreateEventHandler(tkwin, StructureNotifyMask, PackStructureProc, (ClientData) packPtr); return packPtr; } /* *-------------------------------------------------------------- * * TkParsePadAmount -- * * This procedure parses a padding specification and returns * the appropriate padding values. A padding specification can * be either a single pixel width, or a list of two pixel widths. * If a single pixel width, the amount specified is used for * padding on both sides. If two amounts are specified, then * they specify the left/right or top/bottom padding. * * Results: * A standard Tcl return value. * * Side effects: * An error message is written to the interpreter is something * is not right. * *-------------------------------------------------------------- */ int TkParsePadAmount(interp, tkwin, specObj, halfPtr, allPtr) Tcl_Interp *interp; /* Interpreter for error reporting. */ Tk_Window tkwin; /* A window. Needed by Tk_GetPixels() */ Tcl_Obj *specObj; /* The argument to "-padx", "-pady", "-ipadx", * or "-ipady". The thing to be parsed. */ int *halfPtr; /* Write the left/top part of padding here */ int *allPtr; /* Write the total padding here */ { char *secondPart; /* The second pixel amount of the list */ char *separator = 0; /* Separator between 1st and 2nd pixel widths */ int sepChar = 0; /* Character used as the separator */ int firstInt, secondInt; /* The two components of the padding */ char *padSpec = Tcl_GetString(specObj); for (secondPart=padSpec; (*secondPart != '\0') && !isspace(UCHAR(*secondPart)); secondPart++) { /* Do nothing */ } if (*secondPart != '\0') { separator = secondPart; sepChar = *secondPart; *secondPart = '\0'; secondPart++; while ( isspace(UCHAR(*secondPart)) ) { secondPart++; } if (*secondPart == '\0'){ secondPart = 0; *separator = sepChar; } } else { secondPart = 0; } if ((Tk_GetPixels(interp, tkwin, padSpec, &firstInt) != TCL_OK) || (firstInt < 0)) { Tcl_ResetResult(interp); Tcl_AppendResult(interp, "bad pad value \"", padSpec, "\": must be positive screen distance", (char *) NULL); return TCL_ERROR; } if (secondPart) { if ((Tk_GetPixels(interp, tkwin, secondPart, &secondInt) != TCL_OK) || (secondInt < 0)) { Tcl_ResetResult(interp); Tcl_AppendResult(interp, "bad 2nd pad value \"", secondPart, "\": must be positive screen distance", (char *) NULL); return TCL_ERROR; } *separator = sepChar; } else { secondInt = firstInt; } if (halfPtr != 0) *halfPtr = firstInt; *allPtr = firstInt + secondInt; return TCL_OK; } /* *-------------------------------------------------------------- * * PackAfter -- * * This procedure does most of the real work of adding * one or more windows into the packing order for its parent. * * Results: * A standard Tcl return value. * * Side effects: * The geometry of the specified windows may change, both now and * again in the future. * *-------------------------------------------------------------- */ static int PackAfter(interp, prevPtr, masterPtr, objc, objv) Tcl_Interp *interp; /* Interpreter for error reporting. */ Packer *prevPtr; /* Pack windows in argv just after this * window; NULL means pack as first * child of masterPtr. */ Packer *masterPtr; /* Master in which to pack windows. */ int objc; /* Number of elements in objv. */ Tcl_Obj *CONST objv[]; /* Array of lists, each containing 2 * elements: window name and side * against which to pack. */ { register Packer *packPtr; Tk_Window tkwin, ancestor, parent; int length; Tcl_Obj **options; int index, optionCount, c; /* * Iterate over all of the window specifiers, each consisting of * two arguments. The first argument contains the window name and * the additional arguments contain options such as "top" or * "padx 20". */ for ( ; objc > 0; objc -= 2, objv += 2, prevPtr = packPtr) { if (objc < 2) { Tcl_AppendResult(interp, "wrong # args: window \"", Tcl_GetString(objv[0]), "\" should be followed by options", (char *) NULL); return TCL_ERROR; } /* * Find the packer for the window to be packed, and make sure * that the window in which it will be packed is either its * or a descendant of its parent. */ if (TkGetWindowFromObj(interp, masterPtr->tkwin, objv[0], &tkwin) != TCL_OK) { return TCL_ERROR; } parent = Tk_Parent(tkwin); for (ancestor = masterPtr->tkwin; ; ancestor = Tk_Parent(ancestor)) { if (ancestor == parent) { break; } if (((Tk_FakeWin *) (ancestor))->flags & TK_TOP_HIERARCHY) { badWindow: Tcl_AppendResult(interp, "can't pack ", Tcl_GetString(objv[0]), " inside ", Tk_PathName(masterPtr->tkwin), (char *) NULL); return TCL_ERROR; } } if (((Tk_FakeWin *) (tkwin))->flags & TK_TOP_HIERARCHY) { goto badWindow; } if (tkwin == masterPtr->tkwin) { goto badWindow; } packPtr = GetPacker(tkwin); /* * Process options for this window. */ if (Tcl_ListObjGetElements(interp, objv[1], &optionCount, &options) != TCL_OK) { return TCL_ERROR; } packPtr->side = TOP; packPtr->anchor = TK_ANCHOR_CENTER; packPtr->padX = packPtr->padY = 0; packPtr->padLeft = packPtr->padTop = 0; packPtr->iPadX = packPtr->iPadY = 0; packPtr->flags &= ~(FILLX|FILLY|EXPAND); packPtr->flags |= OLD_STYLE; for (index = 0 ; index < optionCount; index++) { Tcl_Obj *curOptPtr = options[index]; char *curOpt = Tcl_GetStringFromObj(curOptPtr, (int *) &length); c = curOpt[0]; if ((c == 't') && (strncmp(curOpt, "top", (size_t) length)) == 0) { packPtr->side = TOP; } else if ((c == 'b') && (strncmp(curOpt, "bottom", (size_t) length)) == 0) { packPtr->side = BOTTOM; } else if ((c == 'l') && (strncmp(curOpt, "left", (size_t) length)) == 0) { packPtr->side = LEFT; } else if ((c == 'r') && (strncmp(curOpt, "right", (size_t) length)) == 0) { packPtr->side = RIGHT; } else if ((c == 'e') && (strncmp(curOpt, "expand", (size_t) length)) == 0) { packPtr->flags |= EXPAND; } else if ((c == 'f') && (strcmp(curOpt, "fill")) == 0) { packPtr->flags |= FILLX|FILLY; } else if ((length == 5) && (strcmp(curOpt, "fillx")) == 0) { packPtr->flags |= FILLX; } else if ((length == 5) && (strcmp(curOpt, "filly")) == 0) { packPtr->flags |= FILLY; } else if ((c == 'p') && (strcmp(curOpt, "padx")) == 0) { if (optionCount < (index+2)) { missingPad: Tcl_AppendResult(interp, "wrong # args: \"", curOpt, "\" option must be followed by screen distance", (char *) NULL); return TCL_ERROR; } if (TkParsePadAmount(interp, tkwin, options[index+1], &packPtr->padLeft, &packPtr->padX) != TCL_OK) { return TCL_ERROR; } packPtr->padX /= 2; packPtr->padLeft /= 2; packPtr->iPadX = 0; index++; } else if ((c == 'p') && (strcmp(curOpt, "pady")) == 0) { if (optionCount < (index+2)) { goto missingPad; } if (TkParsePadAmount(interp, tkwin, options[index+1], &packPtr->padTop, &packPtr->padY) != TCL_OK) { return TCL_ERROR; } packPtr->padY /= 2; packPtr->padTop /= 2; packPtr->iPadY = 0; index++; } else if ((c == 'f') && (length > 1) && (strncmp(curOpt, "frame", (size_t) length) == 0)) { if (optionCount < (index+2)) { Tcl_AppendResult(interp, "wrong # args: \"frame\" ", "option must be followed by anchor point", (char *) NULL); return TCL_ERROR; } if (Tk_GetAnchorFromObj(interp, options[index+1], &packPtr->anchor) != TCL_OK) { return TCL_ERROR; } index++; } else { Tcl_AppendResult(interp, "bad option \"", curOpt, "\": should be top, bottom, left, right, ", "expand, fill, fillx, filly, padx, pady, or frame", (char *) NULL); return TCL_ERROR; } } if (packPtr != prevPtr) { /* * Unpack this window if it's currently packed. */ if (packPtr->masterPtr != NULL) { if ((packPtr->masterPtr != masterPtr) && (packPtr->masterPtr->tkwin != Tk_Parent(packPtr->tkwin))) { Tk_UnmaintainGeometry(packPtr->tkwin, packPtr->masterPtr->tkwin); } Unlink(packPtr); } /* * Add the window in the correct place in its parent's * packing order, then make sure that the window is * managed by us. */ packPtr->masterPtr = masterPtr; if (prevPtr == NULL) { packPtr->nextPtr = masterPtr->slavePtr; masterPtr->slavePtr = packPtr; } else { packPtr->nextPtr = prevPtr->nextPtr; prevPtr->nextPtr = packPtr; } Tk_ManageGeometry(tkwin, &packerType, (ClientData) packPtr); } } /* * Arrange for the parent to be re-packed at the first * idle moment. */ if (masterPtr->abortPtr != NULL) { *masterPtr->abortPtr = 1; } if (!(masterPtr->flags & REQUESTED_REPACK)) { masterPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); } return TCL_OK; } /* *---------------------------------------------------------------------- * * Unlink -- * * Remove a packer from its parent's list of slaves. * * Results: * None. * * Side effects: * The parent will be scheduled for repacking. * *---------------------------------------------------------------------- */ static void Unlink(packPtr) register Packer *packPtr; /* Window to unlink. */ { register Packer *masterPtr, *packPtr2; masterPtr = packPtr->masterPtr; if (masterPtr == NULL) { return; } if (masterPtr->slavePtr == packPtr) { masterPtr->slavePtr = packPtr->nextPtr; } else { for (packPtr2 = masterPtr->slavePtr; ; packPtr2 = packPtr2->nextPtr) { if (packPtr2 == NULL) { panic("Unlink couldn't find previous window"); } if (packPtr2->nextPtr == packPtr) { packPtr2->nextPtr = packPtr->nextPtr; break; } } } if (!(masterPtr->flags & REQUESTED_REPACK)) { masterPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); } if (masterPtr->abortPtr != NULL) { *masterPtr->abortPtr = 1; } packPtr->masterPtr = NULL; } /* *---------------------------------------------------------------------- * * DestroyPacker -- * * This procedure is invoked by Tcl_EventuallyFree or Tcl_Release * to clean up the internal structure of a packer at a safe time * (when no-one is using it anymore). * * Results: * None. * * Side effects: * Everything associated with the packer is freed up. * *---------------------------------------------------------------------- */ static void DestroyPacker(memPtr) char *memPtr; /* Info about packed window that * is now dead. */ { register Packer *packPtr = (Packer *) memPtr; ckfree((char *) packPtr); } /* *---------------------------------------------------------------------- * * PackStructureProc -- * * This procedure is invoked by the Tk event dispatcher in response * to StructureNotify events. * * Results: * None. * * Side effects: * If a window was just deleted, clean up all its packer-related * information. If it was just resized, repack its slaves, if * any. * *---------------------------------------------------------------------- */ static void PackStructureProc(clientData, eventPtr) ClientData clientData; /* Our information about window * referred to by eventPtr. */ XEvent *eventPtr; /* Describes what just happened. */ { register Packer *packPtr = (Packer *) clientData; if (eventPtr->type == ConfigureNotify) { if ((packPtr->slavePtr != NULL) && !(packPtr->flags & REQUESTED_REPACK)) { packPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr); } if (packPtr->doubleBw != 2*Tk_Changes(packPtr->tkwin)->border_width) { if ((packPtr->masterPtr != NULL) && !(packPtr->masterPtr->flags & REQUESTED_REPACK)) { packPtr->doubleBw = 2*Tk_Changes(packPtr->tkwin)->border_width; packPtr->masterPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr->masterPtr); } } } else if (eventPtr->type == DestroyNotify) { register Packer *slavePtr, *nextPtr; if (packPtr->masterPtr != NULL) { Unlink(packPtr); } for (slavePtr = packPtr->slavePtr; slavePtr != NULL; slavePtr = nextPtr) { Tk_ManageGeometry(slavePtr->tkwin, (Tk_GeomMgr *) NULL, (ClientData) NULL); Tk_UnmapWindow(slavePtr->tkwin); slavePtr->masterPtr = NULL; nextPtr = slavePtr->nextPtr; slavePtr->nextPtr = NULL; } if (packPtr->tkwin != NULL) { TkDisplay *dispPtr = ((TkWindow *) packPtr->tkwin)->dispPtr; Tcl_DeleteHashEntry(Tcl_FindHashEntry(&dispPtr->packerHashTable, (char *) packPtr->tkwin)); } if (packPtr->flags & REQUESTED_REPACK) { Tcl_CancelIdleCall(ArrangePacking, (ClientData) packPtr); } packPtr->tkwin = NULL; Tcl_EventuallyFree((ClientData) packPtr, DestroyPacker); } else if (eventPtr->type == MapNotify) { /* * When a master gets mapped, must redo the geometry computation * so that all of its slaves get remapped. */ if ((packPtr->slavePtr != NULL) && !(packPtr->flags & REQUESTED_REPACK)) { packPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) packPtr); } } else if (eventPtr->type == UnmapNotify) { register Packer *packPtr2; /* * Unmap all of the slaves when the master gets unmapped, * so that they don't bother to keep redisplaying * themselves. */ for (packPtr2 = packPtr->slavePtr; packPtr2 != NULL; packPtr2 = packPtr2->nextPtr) { Tk_UnmapWindow(packPtr2->tkwin); } } } /* *---------------------------------------------------------------------- * * ConfigureSlaves -- * * This implements the guts of the "pack configure" command. Given * a list of slaves and configuration options, it arranges for the * packer to manage the slaves and sets the specified options. * * Results: * TCL_OK is returned if all went well. Otherwise, TCL_ERROR is * returned and the interp's result is set to contain an error message. * * Side effects: * Slave windows get taken over by the packer. * *---------------------------------------------------------------------- */ static int ConfigureSlaves(interp, tkwin, objc, objv) Tcl_Interp *interp; /* Interpreter for error reporting. */ Tk_Window tkwin; /* Any window in application containing * slaves. Used to look up slave names. */ int objc; /* Number of elements in argv. */ Tcl_Obj *CONST objv[]; /* Argument objects: contains one or more * window names followed by any number * of "option value" pairs. Caller must * make sure that there is at least one * window name. */ { Packer *masterPtr, *slavePtr, *prevPtr, *otherPtr; Tk_Window other, slave, parent, ancestor; int i, j, numWindows, tmp, positionGiven; char *string; static CONST char *optionStrings[] = { "-after", "-anchor", "-before", "-expand", "-fill", "-in", "-ipadx", "-ipady", "-padx", "-pady", "-side", (char *) NULL }; enum options { CONF_AFTER, CONF_ANCHOR, CONF_BEFORE, CONF_EXPAND, CONF_FILL, CONF_IN, CONF_IPADX, CONF_IPADY, CONF_PADX, CONF_PADY, CONF_SIDE }; int index, side; /* * Find out how many windows are specified. */ for (numWindows = 0; numWindows < objc; numWindows++) { string = Tcl_GetString(objv[numWindows]); if (string[0] != '.') { break; } } /* * Iterate over all of the slave windows, parsing the configuration * options for each slave. It's a bit wasteful to re-parse the * options for each slave, but things get too messy if we try to * parse the arguments just once at the beginning. For example, * if a slave already is packed we want to just change a few * existing values without resetting everything. If there are * multiple windows, the -after, -before, and -in options only * get processed for the first window. */ masterPtr = NULL; prevPtr = NULL; positionGiven = 0; for (j = 0; j < numWindows; j++) { if (TkGetWindowFromObj(interp, tkwin, objv[j], &slave) != TCL_OK) { return TCL_ERROR; } if (Tk_TopWinHierarchy(slave)) { Tcl_AppendResult(interp, "can't pack \"", Tcl_GetString(objv[j]), "\": it's a top-level window", (char *) NULL); return TCL_ERROR; } slavePtr = GetPacker(slave); slavePtr->flags &= ~OLD_STYLE; /* * If the slave isn't currently packed, reset all of its * configuration information to default values (there could * be old values left from a previous packing). */ if (slavePtr->masterPtr == NULL) { slavePtr->side = TOP; slavePtr->anchor = TK_ANCHOR_CENTER; slavePtr->padX = slavePtr->padY = 0; slavePtr->padLeft = slavePtr->padTop = 0; slavePtr->iPadX = slavePtr->iPadY = 0; slavePtr->flags &= ~(FILLX|FILLY|EXPAND); } for (i = numWindows; i < objc; i+=2) { if ((i+2) > objc) { Tcl_AppendResult(interp, "extra option \"", Tcl_GetString(objv[i]), "\" (option with no value?)", (char *) NULL); return TCL_ERROR; } if (Tcl_GetIndexFromObj(interp, objv[i], optionStrings, "option", 0, &index) != TCL_OK) { return TCL_ERROR; } if (index == CONF_AFTER) { if (j == 0) { if (TkGetWindowFromObj(interp, tkwin, objv[i+1], &other) != TCL_OK) { return TCL_ERROR; } prevPtr = GetPacker(other); if (prevPtr->masterPtr == NULL) { notPacked: Tcl_AppendResult(interp, "window \"", Tcl_GetString(objv[i+1]), "\" isn't packed", (char *) NULL); return TCL_ERROR; } masterPtr = prevPtr->masterPtr; positionGiven = 1; } } else if (index == CONF_ANCHOR) { if (Tk_GetAnchorFromObj(interp, objv[i+1], &slavePtr->anchor) != TCL_OK) { return TCL_ERROR; } } else if (index == CONF_BEFORE) { if (j == 0) { if (TkGetWindowFromObj(interp, tkwin, objv[i+1], &other) != TCL_OK) { return TCL_ERROR; } otherPtr = GetPacker(other); if (otherPtr->masterPtr == NULL) { goto notPacked; } masterPtr = otherPtr->masterPtr; prevPtr = masterPtr->slavePtr; if (prevPtr == otherPtr) { prevPtr = NULL; } else { while (prevPtr->nextPtr != otherPtr) { prevPtr = prevPtr->nextPtr; } } positionGiven = 1; } } else if (index == CONF_EXPAND) { if (Tcl_GetBooleanFromObj(interp, objv[i+1], &tmp) != TCL_OK) { return TCL_ERROR; } slavePtr->flags &= ~EXPAND; if (tmp) { slavePtr->flags |= EXPAND; } } else if (index == CONF_FILL) { string = Tcl_GetString(objv[i+1]); if (strcmp(string, "none") == 0) { slavePtr->flags &= ~(FILLX|FILLY); } else if (strcmp(string, "x") == 0) { slavePtr->flags = (slavePtr->flags & ~FILLY) | FILLX; } else if (strcmp(string, "y") == 0) { slavePtr->flags = (slavePtr->flags & ~FILLX) | FILLY; } else if (strcmp(string, "both") == 0) { slavePtr->flags |= FILLX|FILLY; } else { Tcl_AppendResult(interp, "bad fill style \"", string, "\": must be none, x, y, or both", (char *) NULL); return TCL_ERROR; } } else if (index == CONF_IN) { if (j == 0) { if (TkGetWindowFromObj(interp, tkwin, objv[i+1], &other) != TCL_OK) { return TCL_ERROR; } masterPtr = GetPacker(other); prevPtr = masterPtr->slavePtr; if (prevPtr != NULL) { while (prevPtr->nextPtr != NULL) { prevPtr = prevPtr->nextPtr; } } positionGiven = 1; } } else if (index == CONF_IPADX) { if ((Tk_GetPixelsFromObj(interp, slave, objv[i+1], &tmp) != TCL_OK) || (tmp < 0)) { Tcl_ResetResult(interp); Tcl_AppendResult(interp, "bad ipadx value \"", Tcl_GetString(objv[i+1]), "\": must be positive screen distance", (char *) NULL); return TCL_ERROR; } slavePtr->iPadX = tmp * 2; } else if (index == CONF_IPADY) { if ((Tk_GetPixelsFromObj(interp, slave, objv[i+1], &tmp) != TCL_OK) || (tmp < 0)) { Tcl_ResetResult(interp); Tcl_AppendResult(interp, "bad ipady value \"", Tcl_GetString(objv[i+1]), "\": must be positive screen distance", (char *) NULL); return TCL_ERROR; } slavePtr->iPadY = tmp * 2; } else if (index == CONF_PADX) { if (TkParsePadAmount(interp, slave, objv[i+1], &slavePtr->padLeft, &slavePtr->padX) != TCL_OK) { return TCL_ERROR; } } else if (index == CONF_PADY) { if (TkParsePadAmount(interp, slave, objv[i+1], &slavePtr->padTop, &slavePtr->padY) != TCL_OK) { return TCL_ERROR; } } else if (index == CONF_SIDE) { if (Tcl_GetIndexFromObj(interp, objv[i+1], sideNames, "side", TCL_EXACT, &side) != TCL_OK) { return TCL_ERROR; } slavePtr->side = (Side) side; } } /* * If no position in a packing list was specified and the slave * is already packed, then leave it in its current location in * its current packing list. */ if (!positionGiven && (slavePtr->masterPtr != NULL)) { masterPtr = slavePtr->masterPtr; goto scheduleLayout; } /* * If the slave is going to be put back after itself then * skip the whole operation, since it won't work anyway. */ if (prevPtr == slavePtr) { masterPtr = slavePtr->masterPtr; goto scheduleLayout; } /* * If none of the "-in", "-before", or "-after" options has * been specified, arrange for the slave to go at the end of * the order for its parent. */ if (!positionGiven) { masterPtr = GetPacker(Tk_Parent(slave)); prevPtr = masterPtr->slavePtr; if (prevPtr != NULL) { while (prevPtr->nextPtr != NULL) { prevPtr = prevPtr->nextPtr; } } } /* * Make sure that the slave's parent is either the master or * an ancestor of the master, and that the master and slave * aren't the same. */ parent = Tk_Parent(slave); for (ancestor = masterPtr->tkwin; ; ancestor = Tk_Parent(ancestor)) { if (ancestor == parent) { break; } if (Tk_TopWinHierarchy(ancestor)) { Tcl_AppendResult(interp, "can't pack ", Tcl_GetString(objv[j]), " inside ", Tk_PathName(masterPtr->tkwin), (char *) NULL); return TCL_ERROR; } } if (slave == masterPtr->tkwin) { Tcl_AppendResult(interp, "can't pack ", Tcl_GetString(objv[j]), " inside itself", (char *) NULL); return TCL_ERROR; } /* * Unpack the slave if it's currently packed, then position it * after prevPtr. */ if (slavePtr->masterPtr != NULL) { if ((slavePtr->masterPtr != masterPtr) && (slavePtr->masterPtr->tkwin != Tk_Parent(slavePtr->tkwin))) { Tk_UnmaintainGeometry(slavePtr->tkwin, slavePtr->masterPtr->tkwin); } Unlink(slavePtr); } slavePtr->masterPtr = masterPtr; if (prevPtr == NULL) { slavePtr->nextPtr = masterPtr->slavePtr; masterPtr->slavePtr = slavePtr; } else { slavePtr->nextPtr = prevPtr->nextPtr; prevPtr->nextPtr = slavePtr; } Tk_ManageGeometry(slave, &packerType, (ClientData) slavePtr); prevPtr = slavePtr; /* * Arrange for the parent to be re-packed at the first * idle moment. */ scheduleLayout: if (masterPtr->abortPtr != NULL) { *masterPtr->abortPtr = 1; } if (!(masterPtr->flags & REQUESTED_REPACK)) { masterPtr->flags |= REQUESTED_REPACK; Tcl_DoWhenIdle(ArrangePacking, (ClientData) masterPtr); } } return TCL_OK; }
29.92043
84
0.620858
621d4f9a773967429618887bdf34823a76c5362e
4,542
h
C
Samples/Win7Samples/netds/wlan/WirelessHostedNetwork/HostedNetwork/HostedNetworkDlg.h
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/netds/wlan/WirelessHostedNetwork/HostedNetwork/HostedNetworkDlg.h
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/netds/wlan/WirelessHostedNetwork/HostedNetwork/HostedNetworkDlg.h
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // HostedNetworkDlg.h : header file // #pragma once #include "afxwin.h" #include "afxcmn.h" // CHostedNetworkDlg dialog class CHostedNetworkDlg : public CDialog { // Construction public: CHostedNetworkDlg(CWnd* pParent = NULL); // standard constructor ~CHostedNetworkDlg(); // standard descructor // Dialog Data enum { IDD = IDD_HOSTEDNETWORK_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support private: // private data members // ICS manager CIcsManager * m_IcsMgr; // Wlan manager CWlanManager m_WlanMgr; // Hosted network notification sink CNotificationSink * m_NotificationSink; bool m_fProcessNotifications; // List of WLAN devices CRefObjList<CWlanDevice *> m_WlanDeviceList; // List of connections (adapters) CRefObjList<CIcsConnectionInfo *> m_ConnectionList; // whether softAP will be started with full ICS bool m_IcsNeeded; // ICS enabled bool m_IcsEnabled; // Hosted network started bool m_HostedNetworkStarted; // GUID of hosted network adapter GUID m_HostedNetworkGuid; // messages for start/stop hosted network WCHAR m_strStartHostedNetwork[256]; WCHAR m_strStopHostedNetwork[256]; // Current name and key for the hosted network CAtlString m_CurrentName; CAtlString m_CurrentKey; // whether the app is running with admin privilege BOOL m_bIsAdmin; // whether ICS is allowed bool m_bIsICSAllowed; // private methods HRESULT InitWlan(); HRESULT InitIcs(); void DeinitIcs(); void ProcessNotifications(); HRESULT StartHostedNetwork(); HRESULT StopHostedNetwork(); HRESULT EnableIcs(); HRESULT DisableIcs(); void OnOK() {}; void OnDeviceAdd(CWlanDevice *); void OnDeviceRemove(CWlanDevice *); void OnDeviceUpdate(CWlanDevice *); void OnHostedNetworkStarted(); void OnHostedNetworkStopped(); void OnHostedNetworkNotAvailable(); void OnHostedNetworkAvailable(); void GetHostedNetworkInfo(); void GetIcsInfo(); void UpdateIcsConnectionList(); HRESULT StartIcsIfNeeded(); bool StopIcsIfNeeded(); void GetWlanDeviceInfo(); void PostNotification(LPCWSTR msg); void PostDeviceNotification(CWlanDevice *, int); void ClearNotifications() {m_NotificationOutputList.ResetContent();}; void PostErrorMessage(LPCWSTR msg) {::MessageBox(m_hWnd, msg, NULL, MB_ICONERROR|MB_OK);}; BOOL IsUserAdmin(); bool IsICSAllowed(); bool CheckValidSSIDKeyLen(); // The following three functions update the device list void AddWlanDevice(CWlanDevice *); void RemoveWlanDevice(CWlanDevice *); void UpdateWlanDevice(CWlanDevice *); void DisableAllControls(); void EnableAllControls(); // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg void OnClose(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedCheckEnableIcs(); afx_msg void OnBnClickedButtonHostednetwork(); afx_msg void OnBnClickedButtonClearNotifications(); afx_msg void OnEnKillfocusEditName(); LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); private: // Edit box for hosted network name CEdit m_NameEdit; // Edit box for host network security key CEdit m_KeyEdit; // Checkbox for enabling/disabling ICS CButton m_EnableIcsCheck; // Button to start/stop hosted network CButton m_HostedNetworkButton; // ComboBox for the list of connections that support ICS CComboBox m_ConnectionComboBox; // List box of notification output CListBox m_NotificationOutputList; // ListCtrl for WLAN devices CListCtrl m_DeviceListCtrl; public: afx_msg void OnEnKillfocusEditKey(); CStatic m_HostedNetworkStatusTxt; };
24.684783
95
0.682959
289c53fc21609781a47d01c2a5fc6faa082274cf
300
h
C
TaoShenFang/UpLoadIDCardCell.h
rentianhua/tsf_ios
5e3840119def49861effcdfe55382a09ae33de98
[ "MIT" ]
null
null
null
TaoShenFang/UpLoadIDCardCell.h
rentianhua/tsf_ios
5e3840119def49861effcdfe55382a09ae33de98
[ "MIT" ]
null
null
null
TaoShenFang/UpLoadIDCardCell.h
rentianhua/tsf_ios
5e3840119def49861effcdfe55382a09ae33de98
[ "MIT" ]
null
null
null
// // UpLoadIDCardCell.h // TaoShenFang // // Created by YXM on 16/9/1. // Copyright © 2016年 RA. All rights reserved. // #import <UIKit/UIKit.h> @interface UpLoadIDCardCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIButton *uploadBtn; - (IBAction)upload:(UIButton *)sender; @end
18.75
57
0.71
f39644f0f64e1610e8345b3f947e1b28aa0a2d5f
1,208
h
C
bluelock/bluelockservice.h
tclass/bluelock
fb342f4d773262bcad4616b25c7f802d1d01bab9
[ "MIT" ]
7
2015-01-16T21:13:58.000Z
2021-11-21T08:35:50.000Z
bluelock/bluelockservice.h
tclass/bluelock
fb342f4d773262bcad4616b25c7f802d1d01bab9
[ "MIT" ]
1
2015-01-16T23:33:57.000Z
2015-01-16T23:33:57.000Z
bluelock/bluelockservice.h
tclass/bluelock
fb342f4d773262bcad4616b25c7f802d1d01bab9
[ "MIT" ]
1
2015-01-16T22:50:13.000Z
2015-01-16T22:50:13.000Z
#ifndef BLUELOCKSERVICE_H #define BLUELOCKSERVICE_H #include <QObject> #include <QBluetoothServer> #include <qdebug.h> #include <QBluetoothLocalDevice> #include <bluelocklinux.h> #include <memory> class BluelockService : public QObject { Q_OBJECT public: explicit BluelockService(QObject *parent = 0); ~BluelockService(); void startService(); void stopService(); std::unique_ptr<QBluetoothServer> server = NULL; QString getLocalAddress(); QString getPeerName(); QString getUuid(); signals: void notify(int,int); void disconnect(); public slots: void acceptConnection(); void readNextData(); void socketDisconnected(); private: std::unique_ptr<QBluetoothSocket> socket = NULL; std::unique_ptr<QBluetoothLocalDevice> localDevice = NULL; BluelockLinux ll; QBluetoothServiceInfo service; QString localAddress; QString peerName; QString uuidStr; bool running = false; const QBluetoothUuid uuid = QBluetoothUuid(QBluetoothUuid::HumanInterfaceDeviceService); const QString serviceName = QStringLiteral("BLUELOCK"); signals: void newConnection(); void readyRead(); }; #endif // BLUELOCKSERVICE_H
20.133333
92
0.721854
13864f018690197c7591f79c65268b5e2bc8dc21
89
h
C
HomebrewLauncher/include/jailbreak.h
ZeraTron/PS4-Homebrew-Sample
25083cc29e8e48ea19240ece04867d2e2e8f2c06
[ "MIT" ]
11
2017-11-09T12:52:22.000Z
2021-03-31T16:49:25.000Z
HomebrewLauncher/include/jailbreak.h
ZeraTron/PS4-Homebrew-Sample
25083cc29e8e48ea19240ece04867d2e2e8f2c06
[ "MIT" ]
null
null
null
HomebrewLauncher/include/jailbreak.h
ZeraTron/PS4-Homebrew-Sample
25083cc29e8e48ea19240ece04867d2e2e8f2c06
[ "MIT" ]
5
2018-02-14T02:14:43.000Z
2021-08-03T19:31:43.000Z
#ifndef JAILBREAKH #define JAILBREAKH int jailbreak(struct thread *td, void *uap); #endif
22.25
44
0.786517
2c78ff1681caa8f22ba6eaa0b5abc275863813ef
668
h
C
include/dcl/Driver/Driver.h
dcl-project/dcl
a4cc1c1f5f78f39012ab4d317c31f99106ec595b
[ "Apache-2.0" ]
null
null
null
include/dcl/Driver/Driver.h
dcl-project/dcl
a4cc1c1f5f78f39012ab4d317c31f99106ec595b
[ "Apache-2.0" ]
null
null
null
include/dcl/Driver/Driver.h
dcl-project/dcl
a4cc1c1f5f78f39012ab4d317c31f99106ec595b
[ "Apache-2.0" ]
null
null
null
//===--- Driver.h - Compilers Driver ----------------------------*- C++ -*-===// // // This source file is part of the DCL open source project // // Copyright (c) 2022 Li Yu-Long and the DCL project authors // Licensed under Apache 2.0 License // // See https://github.com/dcl-project/dcl/LICENSE.txt for license information // See https://github.com/dcl-project/dcl/graphs/contributors for the list of // DCL project authors // //===----------------------------------------------------------------------===// #ifndef DCL_DRIVER_DRIVER_H #define DCL_DRIVER_DRIVER_H namespace dcl::Driver { class Suite {}; } // namespace dcl::Driver #endif // DCL_DRIVER_DRIVER_H
27.833333
80
0.597305
82cb0adc4a20417e14a8c0ef6193ff3ab43d3380
3,834
c
C
core/tee/se/channel.c
NexellCorp/secure_optee_optee-os
523e3c9b41b36c6625761d5c0948999da630b82c
[ "BSD-2-Clause" ]
3
2015-05-29T13:45:16.000Z
2018-07-30T21:16:42.000Z
core/tee/se/channel.c
NexellCorp/secure_optee_optee-os
523e3c9b41b36c6625761d5c0948999da630b82c
[ "BSD-2-Clause" ]
null
null
null
core/tee/se/channel.c
NexellCorp/secure_optee_optee-os
523e3c9b41b36c6625761d5c0948999da630b82c
[ "BSD-2-Clause" ]
7
2015-03-19T08:26:55.000Z
2018-04-14T08:11:55.000Z
/* * Copyright (c) 2014, Linaro Limited * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tee_api_types.h> #include <trace.h> #include <kernel/tee_common_unpg.h> #include <tee/se/session.h> #include <tee/se/channel.h> #include <tee/se/iso7816.h> #include <tee/se/aid.h> #include <tee/se/apdu.h> #include <stdlib.h> #include <string.h> #include "aid_priv.h" #include "channel_priv.h" struct tee_se_channel *tee_se_channel_alloc(struct tee_se_session *s, int channel_id) { struct tee_se_channel *c; c = malloc(sizeof(struct tee_se_channel)); if (c) { c->session = s; c->channel_id = channel_id; c->aid = NULL; c->select_resp = NULL; } return c; } void tee_se_channel_free(struct tee_se_channel *c) { TEE_ASSERT(c != NULL); if (c->aid) tee_se_aid_release(c->aid); if (c->select_resp) apdu_release(to_apdu_base(c->select_resp)); } struct tee_se_session *tee_se_channel_get_session(struct tee_se_channel *c) { TEE_ASSERT(c != NULL); return c->session; } int tee_se_channel_get_id(struct tee_se_channel *c) { TEE_ASSERT(c != NULL); return c->channel_id; } void tee_se_channel_set_select_response(struct tee_se_channel *c, struct resp_apdu *resp) { TEE_ASSERT(c != NULL); if (c->select_resp) apdu_release(to_apdu_base(c->select_resp)); apdu_acquire(to_apdu_base(resp)); c->select_resp = resp; } TEE_Result tee_se_channel_get_select_response(struct tee_se_channel *c, struct resp_apdu **resp) { TEE_ASSERT(c != NULL && resp != NULL); if (c->select_resp) { *resp = c->select_resp; return TEE_SUCCESS; } else { return TEE_ERROR_NO_DATA; } } void tee_se_channel_set_aid(struct tee_se_channel *c, struct tee_se_aid *aid) { TEE_ASSERT(c != NULL); if (c->aid) tee_se_aid_release(c->aid); tee_se_aid_acquire(aid); c->aid = aid; } TEE_Result tee_se_channel_select(struct tee_se_channel *c, struct tee_se_aid *aid) { TEE_ASSERT(c != NULL); return iso7816_select(c, aid); } TEE_Result tee_se_channel_select_next(struct tee_se_channel *c) { TEE_ASSERT(c != NULL); return iso7816_select_next(c); } TEE_Result tee_se_channel_transmit(struct tee_se_channel *c, struct cmd_apdu *cmd_apdu, struct resp_apdu *resp_apdu) { struct tee_se_session *s; uint8_t *cmd_buf; int cla_channel; TEE_ASSERT(c != NULL && cmd_apdu != NULL && resp_apdu != NULL); s = c->session; cla_channel = iso7816_get_cla_channel(c->channel_id); cmd_buf = apdu_get_data(to_apdu_base(cmd_apdu)); cmd_buf[ISO7816_CLA_OFFSET] = ISO7816_CLA | cla_channel; return tee_se_session_transmit(s, cmd_apdu, resp_apdu); }
27
79
0.748044
d635cabcde707adc7359ca1a718ffdba00c55724
246
h
C
avr/net/util.h
allenporter/thebends
5e35c7e654e5260b37218e59b02fb0b1a5cb2eca
[ "Apache-2.0" ]
4
2015-07-27T04:05:50.000Z
2021-01-28T21:56:09.000Z
avr/net/util.h
allenporter/thebends
5e35c7e654e5260b37218e59b02fb0b1a5cb2eca
[ "Apache-2.0" ]
null
null
null
avr/net/util.h
allenporter/thebends
5e35c7e654e5260b37218e59b02fb0b1a5cb2eca
[ "Apache-2.0" ]
null
null
null
// util.h // Author: Allen Porter <allen@thebends.org> #ifndef __UTIL_H__ #define __UTIL_H__ #include <inttypes.h> void ntohs(uint16_t* value); void ntohl(uint32_t* value); int inet_aton(const char* cp, uint32_t* ip); #endif // __UTIL_H__
15.375
44
0.723577
965a3b3da7ae73741bd4fe965ec0d185ea578920
25,031
c
C
stm32303c_eval_eeprom.c
STMicroelectronics/stm32303c-eval
76f16888a4287b9cf3cdcc1b05ee64643ecd54cc
[ "BSD-3-Clause" ]
null
null
null
stm32303c_eval_eeprom.c
STMicroelectronics/stm32303c-eval
76f16888a4287b9cf3cdcc1b05ee64643ecd54cc
[ "BSD-3-Clause" ]
null
null
null
stm32303c_eval_eeprom.c
STMicroelectronics/stm32303c-eval
76f16888a4287b9cf3cdcc1b05ee64643ecd54cc
[ "BSD-3-Clause" ]
null
null
null
/** ****************************************************************************** * @file stm32303c_eval_eeprom.c * @author MCD Application Team * @brief This file provides a set of functions needed to manage a M24LR64 * or M24M01 I2C EEPROM memory, or a M95M01 SPI EEPROM memory. * * =================================================================== * Notes: * - This driver is intended for STM32F30x families devices only. * - The I2C EEPROM memory (M24LR64) is available on separate daughter * board ANT7-M24LR-A, which is provided with the STM32F303C * EVAL board. * To use this driver with M24LR64, you have to connect * the ANT7-M24LR-A to CN1 connector of STM32F303C EVAL board. * Jumper JP5 and JP6 needs to be set in I2C2 position. * Jumper JP8 (E2P WC) needs to be set. * * - The I2C EEPROM memory (M24M01) is mounted on the STM32F303C * EVAL board. * Jumper JP5 and JP6 needs to be set in I2C2_F position. * Jumper JP8 (E2P WC) needs to be set. * * - The SPI EEPROM memory (M95M01) is available directly * on STM32F303C EVAL board. * =================================================================== * * It implements a high level communication layer for read and write * from/to this memory. The needed STM32F30x hardware resources (I2C, * SPI and GPIO) are defined in stm32303c_eval.h file, * and the initialization is performed depending of EEPROMs * in EEPROM_I2C_IO_Init() or EEPROM_SPI_IO_Init() functions * declared in stm32303c_eval.c file. * You can easily tailor this driver to any other development board, * by just adapting the defines for hardware resources and * EEPROM_I2C_IO_Init() or EEPROM_SPI_IO_Init() functions. * * @note In this driver, basic read and write functions * (BSP_EEPROM_ReadBuffer() and BSP_EEPROM_WriteBuffer()) * use Polling mode to perform the data transfer to/from EEPROM memories. * +-----------------------------------------------------------------+ * | Pin assignment for M24M01 EEPROM | * +---------------------------------------+-----------+-------------+ * | STM32F30x I2C Pins | EEPROM | Pin | * +---------------------------------------+-----------+-------------+ * | . | NC | 1 | * | . | E1(VDD) | 2 (3.3V) | * | . | E2(GND) | 3 (0V) | * | . | VSS | 4 (0V) | * | EEPROM_I2C_SDA_PIN/ SDA | SDA | 5 | * | EEPROM_I2C_SCL_PIN/ SCL | SCL | 6 | * | . | /WC(VSS)| 7 (0V) | * | . | VDD | 8 (3.3V) | * +---------------------------------------+-----------+-------------+ * +-----------------------------------------------------------------+ * | Pin assignment for M24LR64 EEPROM | * +---------------------------------------+-----------+-------------+ * | STM32F30x I2C Pins | EEPROM | Pin | * +---------------------------------------+-----------+-------------+ * | . | E0(GND) | 1 (0V) | * | . | AC0 | 2 | * | . | AC1 | 3 | * | . | VSS | 4 (0V) | * | EEPROM_I2C_SDA_PIN/ SDA | SDA | 5 | * | EEPROM_I2C_SCL_PIN/ SCL | SCL | 6 | * | . | E1(GND) | 7 (0V) | * | . | VDD | 8 (3.3V) | * +---------------------------------------+-----------+-------------+ * * +-----------------------------------------------------------------+ * | Pin assignment for M95M01 EEPROM | * +---------------------------------------+-----------+-------------+ * | STM32F30x SPI Pins | EEPROM | Pin | * +---------------------------------------+-----------+-------------+ * | EEPROM_CS_PIN | ChipSelect| 1 (/S) | * | EEPROM_SPI_MISO_PIN/ MISO | DataOut | 2 (Q) | * | EEPROM_SPI_WP_PIN | WR Protect| 3 (/W) | * | . | GND | 4 (0 V) | * | EEPROM_SPI_MOSI_PIN/ MOSI | DataIn | 5 (D) | * | EEPROM_SPI_SCK_PIN/ SCLK | Clock | 6 (C) | * | . | Hold | 7 (/HOLD)| * | . | VCC | 8 (3.3 V)| * +---------------------------------------+-----------+-------------+ ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32303c_eval_eeprom.h" /** @addtogroup BSP * @{ */ /** @addtogroup STM32303C_EVAL * @{ */ /** @addtogroup STM32303C_EVAL_EEPROM * @brief This file includes the I2C EEPROM and SPI EEPROM driver * of STM32303C-EVAL board. * @{ */ /** @addtogroup STM32303C_EVAL_EEPROM_Private_Variables * @{ */ __IO uint16_t EEPROMAddress = 0; __IO uint16_t EEPROMPageSize = 0; __IO uint16_t EEPROMDataRead; __IO uint8_t EEPROMDataWrite; static EEPROM_DrvTypeDef *EEPROM_SelectedDevice = 0; /** * @} */ /** @addtogroup STM32303C_EVAL_EEPROM_Private_Functions * @{ */ static uint32_t EEPROM_I2C_Init(void); static uint32_t EEPROM_I2C_ReadBuffer(uint8_t* pBuffer, uint16_t ReadAddr, uint32_t* NumByteToRead); static uint32_t EEPROM_I2C_WritePage(uint8_t* pBuffer, uint16_t WriteAddr, uint32_t* NumByteToWrite); static uint32_t EEPROM_I2C_WaitEepromStandbyState(void); static uint32_t EEPROM_SPI_Init(void); static uint32_t EEPROM_SPI_ReadBuffer(uint8_t* pBuffer, uint16_t ReadAddr, uint32_t* NumByteToRead); static uint32_t EEPROM_SPI_WritePage(uint8_t* pBuffer, uint16_t WriteAddr, uint32_t* NumByteToWrite); static uint32_t EEPROM_SPI_WaitEepromStandbyState(void); /** * @} */ /** @defgroup STM32303C_EVAL_EEPROM_Private_Types Private Types * @{ */ /* EEPROM I2C driver typedef */ EEPROM_DrvTypeDef EEPROM_I2C_Drv = { EEPROM_I2C_Init, EEPROM_I2C_ReadBuffer, EEPROM_I2C_WritePage }; /* EEPROM SPI driver typedef */ EEPROM_DrvTypeDef EEPROM_SPI_Drv = { EEPROM_SPI_Init, EEPROM_SPI_ReadBuffer, EEPROM_SPI_WritePage }; /** * @} */ /** @addtogroup STM32303C_EVAL_EEPROM_Exported_Functions * @{ */ /** * @brief Initializes peripherals used by the EEPROM device selected. * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) */ uint32_t BSP_EEPROM_Init(void) { if(EEPROM_SelectedDevice->Init != 0) { return (EEPROM_SelectedDevice->Init()); } else { return EEPROM_FAIL; } } /** * @brief Select the EEPROM device to communicate. * @param DeviceID Specifies the EEPROM device to be selected. * This parameter can be one of following parameters: * @arg BSP_EEPROM_M24LR64 * @arg BSP_EEPROM_M24M01 * @arg BSP_EEPROM_M95M01 * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) */ void BSP_EEPROM_SelectDevice(uint8_t DeviceID) { switch(DeviceID) { case BSP_EEPROM_M24LR64 : EEPROM_SelectedDevice = &EEPROM_I2C_Drv; break; case BSP_EEPROM_M24M01 : EEPROM_SelectedDevice = &EEPROM_I2C_Drv; break; case BSP_EEPROM_M95M01 : EEPROM_SelectedDevice = &EEPROM_SPI_Drv; break; default: break; } } /** * @brief Reads a block of data from the EEPROM device selected. * @param pBuffer pointer to the buffer that receives the data read from * the EEPROM. * @param ReadAddr EEPROM's internal address to start reading from. * @param NumByteToRead pointer to the variable holding number of bytes to * be read from the EEPROM. * * @note The variable pointed by NumByteToRead is reset to 0 when all the * data are read from the EEPROM. Application should monitor this * variable in order know when the transfer is complete. * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ uint32_t BSP_EEPROM_ReadBuffer(uint8_t* pBuffer, uint16_t ReadAddr, uint32_t* NumByteToRead) { if(EEPROM_SelectedDevice->ReadBuffer != 0) { return (EEPROM_SelectedDevice->ReadBuffer(pBuffer, ReadAddr, NumByteToRead)); } else { return EEPROM_FAIL; } } /** * @brief Writes buffer of data to the EEPROM device selected. * @param pBuffer pointer to the buffer containing the data to be written * to the EEPROM. * @param WriteAddr EEPROM's internal address to write to. * @param NumByteToWrite number of bytes to write to the EEPROM. * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ uint32_t BSP_EEPROM_WriteBuffer(uint8_t* pBuffer, uint16_t WriteAddr, uint32_t NumByteToWrite) { uint16_t numofpage = 0, numofsingle = 0, count = 0; uint16_t addr = 0; uint32_t dataindex = 0; uint32_t status = EEPROM_OK; addr = WriteAddr % EEPROMPageSize; count = EEPROMPageSize - addr; numofpage = NumByteToWrite / EEPROMPageSize; numofsingle = NumByteToWrite % EEPROMPageSize; if(EEPROM_SelectedDevice->WritePage == 0) { return EEPROM_FAIL; } /*!< If WriteAddr is EEPROM_PAGESIZE aligned */ if(addr == 0) { /*!< If NumByteToWrite < EEPROM_PAGESIZE */ if(numofpage == 0) { /* Store the number of data to be written */ dataindex = numofsingle; /* Start writing data */ status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } } /*!< If NumByteToWrite > EEPROM_PAGESIZE */ else { while(numofpage--) { /* Store the number of data to be written */ dataindex = EEPROMPageSize; status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } WriteAddr += EEPROMPageSize; pBuffer += EEPROMPageSize; } if(numofsingle!=0) { /* Store the number of data to be written */ dataindex = numofsingle; status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } } } } /*!< If WriteAddr is not EEPROM_PAGESIZE aligned */ else { /*!< If NumByteToWrite < EEPROM_PAGESIZE */ if(numofpage== 0) { /*!< If the number of data to be written is more than the remaining space in the current page: */ if (NumByteToWrite > count) { /* Store the number of data to be written */ dataindex = count; /*!< Write the data contained in same page */ status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } /* Store the number of data to be written */ dataindex = (NumByteToWrite - count); /*!< Write the remaining data in the following page */ status = EEPROM_SelectedDevice->WritePage((uint8_t*)(pBuffer + count), (WriteAddr + count), (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } } else { /* Store the number of data to be written */ dataindex = numofsingle; status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } } } /*!< If NumByteToWrite > EEPROM_PAGESIZE */ else { NumByteToWrite -= count; numofpage = NumByteToWrite / EEPROMPageSize; numofsingle = NumByteToWrite % EEPROMPageSize; if(count != 0) { /* Store the number of data to be written */ dataindex = count; status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } WriteAddr += count; pBuffer += count; } while(numofpage--) { /* Store the number of data to be written */ dataindex = EEPROMPageSize; status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } WriteAddr += EEPROMPageSize; pBuffer += EEPROMPageSize; } if(numofsingle != 0) { /* Store the number of data to be written */ dataindex = numofsingle; status = EEPROM_SelectedDevice->WritePage(pBuffer, WriteAddr, (uint32_t*)(&dataindex)); if (status != EEPROM_OK) { return status; } } } } /* If all operations OK, return EEPROM_OK (0) */ return EEPROM_OK; } /** * @brief Basic management of the timeout situation. * @retval None. */ __weak void BSP_EEPROM_TIMEOUT_UserCallback(void) { } /** * @} */ /** @addtogroup STM32303C_EVAL_EEPROM_Private_Functions * @{ */ /** * @brief Initializes peripherals used by the I2C EEPROM driver. * @note There are 2 different versions of M24LR64 (A01 & A02). * Then try to connect on 1st one (EEPROM_I2C_ADDRESS_A01) * and if problem, check the 2nd one (EEPROM_I2C_ADDRESS_A02) * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) */ static uint32_t EEPROM_I2C_Init(void) { EEPROM_I2C_IO_Init(); /*Select the EEPROM address for M24LR64 A02 and check if OK*/ EEPROMAddress = EEPROM_ADDRESS_M24LR64_A01; EEPROMPageSize = EEPROM_PAGESIZE_M24LR64; if (EEPROM_I2C_IO_IsDeviceReady(EEPROMAddress, EEPROM_MAX_TRIALS) != HAL_OK) { /*Select the EEPROM address for M24LR64 A01 and check if OK*/ EEPROMAddress = EEPROM_ADDRESS_M24LR64_A02; EEPROMPageSize = EEPROM_PAGESIZE_M24LR64; if (EEPROM_I2C_IO_IsDeviceReady(EEPROMAddress, EEPROM_MAX_TRIALS) != HAL_OK) { /*Select the EEPROM address for M24M01 and check if OK*/ EEPROMAddress = EEPROM_ADDRESS_M24M01; EEPROMPageSize = EEPROM_PAGESIZE_M24M01; if (EEPROM_I2C_IO_IsDeviceReady(EEPROMAddress, EEPROM_MAX_TRIALS) != HAL_OK) { return EEPROM_FAIL; } } } return EEPROM_OK; } /** * @brief Reads a block of data from the I2C EEPROM. * @param pBuffer pointer to the buffer that receives the data read from * the EEPROM. * @param ReadAddr EEPROM's internal address to start reading from. * @param NumByteToRead pointer to the variable holding number of bytes to * be read from the EEPROM. * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ static uint32_t EEPROM_I2C_ReadBuffer(uint8_t* pBuffer, uint16_t ReadAddr, uint32_t* NumByteToRead) { uint32_t buffersize = *NumByteToRead; if (EEPROM_I2C_IO_ReadData(EEPROMAddress, ReadAddr, pBuffer, buffersize) != HAL_OK) { return EEPROM_FAIL; } /* If all operations OK, return EEPROM_OK (0) */ return EEPROM_OK; } /** * @brief Writes more than one byte to the EEPROM with a single WRITE cycle. * * @note The number of bytes (combined to write start address) must not * cross the EEPROM page boundary. This function can only write into * the boundaries of an EEPROM page. * This function doesn't check on boundaries condition (in this driver * the function BSP_EEPROM_WriteBuffer() which calls EEPROM_WritePage() is * responsible of checking on Page boundaries). * * @param pBuffer pointer to the buffer containing the data to be written to * the EEPROM. * @param WriteAddr EEPROM's internal address to write to. * @param NumByteToWrite pointer to the variable holding number of bytes to * be written into the EEPROM. * * @note The variable pointed by NumByteToWrite is reset to 0 when all the * data are written to the EEPROM. Application should monitor this * variable in order know when the transfer is complete. * * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ static uint32_t EEPROM_I2C_WritePage(uint8_t* pBuffer, uint16_t WriteAddr, uint32_t* NumByteToWrite) { uint32_t buffersize = *NumByteToWrite; if (EEPROM_I2C_IO_WriteData(EEPROMAddress, WriteAddr, pBuffer, buffersize) != HAL_OK) { return EEPROM_FAIL; } /* Wait for EEPROM Standby state */ if (EEPROM_I2C_WaitEepromStandbyState() != EEPROM_OK) { return EEPROM_FAIL; } return EEPROM_OK; } /** * @brief Wait for EEPROM I2C Standby state. * * @note This function allows to wait and check that EEPROM has finished the * last operation. It is mostly used after Write operation: after receiving * the buffer to be written, the EEPROM may need additional time to actually * perform the write operation. During this time, it doesn't answer to * I2C packets addressed to it. Once the write operation is complete * the EEPROM responds to its address. * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ static uint32_t EEPROM_I2C_WaitEepromStandbyState(void) { /* Check if the maximum allowed number of trials has bee reached */ if (EEPROM_I2C_IO_IsDeviceReady(EEPROMAddress, EEPROM_MAX_TRIALS) != HAL_OK) { /* If the maximum number of trials has been reached, exit the function */ BSP_EEPROM_TIMEOUT_UserCallback(); return EEPROM_TIMEOUT; } return EEPROM_OK; } /** * @brief Initializes peripherals used by the SPI EEPROM driver. * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) */ static uint32_t EEPROM_SPI_Init(void) { EEPROM_SPI_IO_Init(); /* Check if EEPROM SPI is ready to use */ EEPROMPageSize = EEPROM_PAGESIZE_M95M01; if(EEPROM_SPI_WaitEepromStandbyState() != HAL_OK) { return EEPROM_FAIL; } return EEPROM_OK; } /** * @brief Reads a block of data from the SPI EEPROM. * @param pBuffer pointer to the buffer that receives the data read from * the EEPROM. * @param ReadAddr EEPROM's internal address to start reading from. * @param NumByteToRead pointer to the variable holding number of bytes to * be read from the EEPROM. * * @note The variable pointed by NumByteToRead is reset to 0 when all the * data are read from the EEPROM. Application should monitor this * variable in order know when the transfer is complete. * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ static uint32_t EEPROM_SPI_ReadBuffer(uint8_t* pBuffer, uint16_t ReadAddr, uint32_t* NumByteToRead) { uint32_t buffersize = *NumByteToRead; EEPROM_SPI_IO_ReadData(ReadAddr, pBuffer, buffersize); /* Wait for EEPROM Standby state */ if (EEPROM_SPI_WaitEepromStandbyState() != EEPROM_OK) { return EEPROM_FAIL; } return EEPROM_OK; } /** * @brief Writes more than one byte to the EEPROM with a single WRITE cycle. * * @note The number of bytes (combined to write start address) must not * cross the EEPROM page boundary. This function can only write into * the boundaries of an EEPROM page. * This function doesn't check on boundaries condition (in this driver * the function BSP_EEPROM_WriteBuffer() which calls EEPROM_WritePage() is * responsible of checking on Page boundaries). * * @param pBuffer pointer to the buffer containing the data to be written to * the EEPROM. * @param WriteAddr EEPROM's internal address to write to. * @param NumByteToWrite pointer to the variable holding number of bytes to * be written into the EEPROM. * * @note The variable pointed by NumByteToWrite is reset to 0 when all the * data are written to the EEPROM. Application should monitor this * variable in order know when the transfer is complete. * * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ static uint32_t EEPROM_SPI_WritePage(uint8_t* pBuffer, uint16_t WriteAddr, uint32_t* NumByteToWrite) { uint32_t buffersize = *NumByteToWrite; if (EEPROM_SPI_IO_WriteData(WriteAddr, pBuffer, buffersize) != HAL_OK) { return EEPROM_FAIL; } /* Wait for EEPROM Standby state */ if (EEPROM_SPI_WaitEepromStandbyState() != EEPROM_OK) { return EEPROM_FAIL; } return EEPROM_OK; } /** * @brief Wait for EEPROM SPI Standby state. * * @note This function allows to wait and check that EEPROM has finished the * last operation. It is mostly used after Write operation. * * @retval EEPROM_OK (0) if operation is correctly performed, else return value * different from EEPROM_OK (0) or the timeout user callback. */ static uint32_t EEPROM_SPI_WaitEepromStandbyState(void) { if(EEPROM_SPI_IO_WaitEepromStandbyState() != HAL_OK) { BSP_EEPROM_TIMEOUT_UserCallback(); return EEPROM_TIMEOUT; } return EEPROM_OK; } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
36.382267
125
0.584995
3020676f0c3122fc559c7a906c59f8ca43b5b8c3
5,004
h
C
src/apps/haikudepot/server/WebAppInterface.h
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/haikudepot/server/WebAppInterface.h
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/haikudepot/server/WebAppInterface.h
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2014, Stephan Aßmus <superstippi@gmx.de>. * Copyright 2016-2021, Andrew Lindesay <apl@lindesay.co.nz>. * All rights reserved. Distributed under the terms of the MIT License. */ #ifndef WEB_APP_INTERFACE_H #define WEB_APP_INTERFACE_H #include <Application.h> #include <JsonWriter.h> #include <String.h> #include <package/PackageVersion.h> #include "PackageInfo.h" #include "UserCredentials.h" #include "UserDetail.h" #include "UserUsageConditions.h" class BDataIO; class BMessage; using BPackageKit::BPackageVersion; /*! These are error codes that are sent back to the client from the server */ #define ERROR_CODE_NONE 0 #define ERROR_CODE_VALIDATION -32800 #define ERROR_CODE_OBJECTNOTFOUND -32801 #define ERROR_CODE_CAPTCHABADRESPONSE -32802 #define ERROR_CODE_AUTHORIZATIONFAILURE -32803 #define ERROR_CODE_BADPKGICON -32804 #define ERROR_CODE_LIMITEXCEEDED -32805 #define ERROR_CODE_AUTHORIZATIONRULECONFLICT -32806 /*! This constant can be used to indicate the lack of a rating. */ #define RATING_NONE -1 class WebAppInterface { public: WebAppInterface(); WebAppInterface(const WebAppInterface& other); virtual ~WebAppInterface(); WebAppInterface& operator=(const WebAppInterface& other); void SetAuthorization(const UserCredentials& value); const BString& Nickname() const; status_t GetChangelog( const BString& packageName, BMessage& message); status_t RetreiveUserRatingsForPackageForDisplay( const BString& packageName, const BString& webAppRepositoryCode, int resultOffset, int maxResults, BMessage& message); status_t RetreiveUserRatingForPackageAndVersionByUser( const BString& packageName, const BPackageVersion& version, const BString& architecture, const BString& repositoryCode, const BString& userNickname, BMessage& message); status_t CreateUserRating( const BString& packageName, const BPackageVersion& version, const BString& architecture, const BString& repositoryCode, const BString& languageCode, const BString& comment, const BString& stability, int rating, BMessage& message); status_t UpdateUserRating( const BString& ratingID, const BString& languageCode, const BString& comment, const BString& stability, int rating, bool active, BMessage& message); status_t RetrieveUserDetailForCredentials( const UserCredentials& credentials, BMessage& message); status_t RetrieveCurrentUserDetail( BMessage& message); status_t RetrieveUserUsageConditions( const BString& code, UserUsageConditions& conditions); status_t AgreeUserUsageConditions(const BString& code, BMessage& responsePayload); status_t RetrieveScreenshot( const BString& code, int32 width, int32 height, BDataIO* stream); status_t RequestCaptcha(BMessage& message); status_t CreateUser(const BString& nickName, const BString& passwordClear, const BString& email, const BString& captchaToken, const BString& captchaResponse, const BString& languageCode, const BString& userUsageConditionsCode, BMessage& message); status_t AuthenticateUser(const BString& nickName, const BString& passwordClear, BMessage& message); status_t IncrementViewCounter( const PackageInfoRef package, const DepotInfoRef depot, BMessage& message); static int32 ErrorCodeFromResponse( BMessage& responseEnvelopeMessage); static status_t UnpackUserDetail( BMessage& responseEnvelopeMessage, UserDetail& userDetail); private: status_t _RetrieveUserUsageConditionsMeta( const BString& code, BMessage& message); status_t _RetrieveUserUsageConditionsCopy( const BString& code, BDataIO* stream); status_t _SendJsonRequest(const char* urlPathComponents, const BString& jsonString, uint32 flags, BMessage& reply) const; status_t _SendJsonRequest(const char* urlPathComponents, UserCredentials credentials, BPositionIO* requestData, size_t requestDataSize, uint32 flags, BMessage& reply) const; status_t _SendJsonRequest(const char* urlPathComponents, BPositionIO* requestData, size_t requestDataSize, uint32 flags, BMessage& reply) const; status_t _SendRawGetRequest( const BString urlPathComponents, BDataIO* stream); static void _LogPayload(BPositionIO* requestData, size_t size); static off_t _LengthAndSeekToZero(BPositionIO* data); private: UserCredentials fCredentials; static int fRequestIndex; }; #endif // WEB_APP_INTERFACE_H
29.435294
77
0.695444
309c0e8cc5be580f8b5dac20398b0480fe6c7a37
3,262
c
C
src/main.c
sasairc/hogesay
1d16dcc6d0bb0c5c8e8b15d2ef52792d36ece8de
[ "WTFPL" ]
null
null
null
src/main.c
sasairc/hogesay
1d16dcc6d0bb0c5c8e8b15d2ef52792d36ece8de
[ "WTFPL" ]
null
null
null
src/main.c
sasairc/hogesay
1d16dcc6d0bb0c5c8e8b15d2ef52792d36ece8de
[ "WTFPL" ]
null
null
null
/* * * * main.c * * Copyright (c) {year} {name} * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar.HocevarHocevar See the COPYING file or http://www.wtfpl.net/ * for more details. */ #include "./config.h" #include "./defs.h" #include "./info.h" #include "./subset.h" #include "./polyaness.h" #include <stdio.h> #include <stdlib.h> #include <getopt.h> int main(int argc, char* argv[]) { int res = 0, index = 0; FILE* fp = NULL; /* dict file */ char* path = NULL, /* dict file path */ * quote = NULL; polyaness_t* pt = NULL; /* flag and args */ flags_t flags = { 0, 0, 0, 0 ,NULL, }; struct option opts[] = { {"file", required_argument, NULL, 'f'}, {"number", required_argument, NULL, 'n'}, {"list", no_argument, NULL, 'l'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {0, 0, 0, 0} }; /* processing of arguments */ while ((res = getopt_long(argc, argv, "f:n:lvh", opts, &index)) != -1) { switch (res) { case 'f': flags.farg = optarg; flags.fflag = 1; break; case 'n': if (strisdigit(optarg) < 0) return -1; flags.narg = atoi(optarg); flags.nflag = 1; break; case 'l': flags.lflag = 1; break; case 'v': print_version(); case 'h': print_usage(); case '?': return -1; } } /* concat file path */ if ((path = concat_file_path(&flags)) == NULL) return 1; /* open flags-quotes */ if (open_dict_file(path, &fp) < 0) { release(NULL, path, NULL); return 2; } /* read dict file */ if (read_dict_file(fp, &pt) < 0) { release(NULL, path, NULL); return 3; } /* do parse polyaness */ if (parse_dict_file(fp, &pt) < 0) { release(fp, path, pt); return 4; } /* * print all quotes list and exit */ if (flags.lflag == 1) { print_all_quotes(pt); release(fp, path, pt); return 0; } /* * generate output quote */ if (flags.nflag == 0) { quote = get_polyaness("quote", create_rand(pt->recs - 1), &pt); } else { if (flags.narg < pt->recs) quote = get_polyaness("quote", flags.narg, &pt); else quote = get_polyaness("quote", 0, &pt); } /* print of string */ fprintf(stdout, "%s\n", quote); /* release memory */ release(fp, path, pt); return 0; } void release(FILE* fp, char* path, polyaness_t* pt) { if (fp != NULL) { fclose(fp); fp = NULL; } if (path != NULL) { free(path); path = NULL; } if (pt != NULL) release_polyaness(pt); return; }
22.342466
91
0.458921
cf50110d679adc2b008d34f64120ecc31635b726
609
h
C
OpenPEARL/openpearl-code/runtime/cortexM/LPCOpen/software/lwip/contrib/ports/win32/pcapif.h
BenniN/OpenPEARLThesis
d7db83b0ea15b7ba0f6244d918432c830ddcd697
[ "Apache-2.0" ]
1
2020-09-15T07:26:00.000Z
2020-09-15T07:26:00.000Z
OpenPEARL/openpearl-code/runtime/cortexM/LPCOpen/software/lwip/contrib/ports/win32/pcapif.h
BenniN/OpenPEARLThesis
d7db83b0ea15b7ba0f6244d918432c830ddcd697
[ "Apache-2.0" ]
null
null
null
OpenPEARL/openpearl-code/runtime/cortexM/LPCOpen/software/lwip/contrib/ports/win32/pcapif.h
BenniN/OpenPEARLThesis
d7db83b0ea15b7ba0f6244d918432c830ddcd697
[ "Apache-2.0" ]
null
null
null
#ifndef __PCAPIF_H__ #define __PCAPIF_H__ #include "lwip/err.h" /** Set to 1 to let rx use an own thread (only for NO_SYS==0). * If set to 0, ethernetif_poll is used to poll for packets. */ #ifndef PCAPIF_RX_USE_THREAD #define PCAPIF_RX_USE_THREAD !NO_SYS #endif #if PCAPIF_RX_USE_THREAD && NO_SYS #error "Can't create a dedicated RX thread with NO_SYS==1" #endif struct netif; err_t pcapif_init (struct netif *netif); void pcapif_shutdown(struct netif *netif); #if !PCAPIF_RX_USE_THREAD void pcapif_poll (struct netif *netif); #endif /* !PCAPIF_RX_USE_THREAD */ #endif
24.36
63
0.719212
cf560b07565fcba4c655fde5b367638daef6af4c
2,418
h
C
include/reaver/vapor/parser/typeclass.h
reaver-project/vapor
17ddb5c60b483bd17a288319bfd3e8a43656859e
[ "Zlib" ]
4
2017-07-22T23:12:36.000Z
2022-01-13T23:57:06.000Z
include/reaver/vapor/parser/typeclass.h
reaver-project/vapor
17ddb5c60b483bd17a288319bfd3e8a43656859e
[ "Zlib" ]
36
2016-11-26T17:46:16.000Z
2019-05-21T16:27:13.000Z
include/reaver/vapor/parser/typeclass.h
reaver-project/vapor
17ddb5c60b483bd17a288319bfd3e8a43656859e
[ "Zlib" ]
3
2016-10-01T21:04:32.000Z
2021-03-20T06:57:53.000Z
/** * Vapor Compiler Licence * * Copyright © 2017, 2019 Michał "Griwes" Dominiak * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation is required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * **/ #pragma once #include "declaration.h" #include "function.h" #include "helpers.h" #include "id_expression.h" #include "parameter_list.h" namespace reaver::vapor::parser { inline namespace _v1 { struct typeclass_literal { range_type range; parameter_list parameters; std::vector<std::variant<function_declaration, function_definition>> members; }; struct instance_literal { range_type range; id_expression typeclass_name; expression_list arguments; std::vector<std::variant<function_definition>> definitions; }; struct default_instance_definition { range_type range; instance_literal literal; }; bool operator==(const typeclass_literal & lhs, const typeclass_literal & rhs); bool operator==(const instance_literal & lhs, const instance_literal & rhs); bool operator==(const default_instance_definition & lhs, const default_instance_definition & rhs); typeclass_literal parse_typeclass_literal(context & ctx); declaration parse_typeclass_definition(context & ctx); instance_literal parse_instance_literal(context & ctx); default_instance_definition parse_default_instance(context & ctx); void print(const typeclass_literal & lit, std::ostream & os, print_context ctx); void print(const instance_literal & def, std::ostream & os, print_context ctx); void print(const default_instance_definition & def, std::ostream & os, print_context ctx); } }
34.542857
102
0.73201
a93deb729d4a62b3c804a028f65a81ecbfc16c0a
624
h
C
LFPhotoBrowserDEMO/LFPhotoBrowserDEMO/class/type/PhotoViewType.h
lincf0912/LFPhotoBrowser
e7c16d2e99169fa616652ee864a81948aa051557
[ "MIT" ]
12
2017-03-27T07:39:08.000Z
2022-01-27T10:47:54.000Z
LFPhotoBrowserDEMO/LFPhotoBrowserDEMO/class/type/PhotoViewType.h
lincf0912/LFPhotoBrowser
e7c16d2e99169fa616652ee864a81948aa051557
[ "MIT" ]
null
null
null
LFPhotoBrowserDEMO/LFPhotoBrowserDEMO/class/type/PhotoViewType.h
lincf0912/LFPhotoBrowser
e7c16d2e99169fa616652ee864a81948aa051557
[ "MIT" ]
5
2017-03-27T07:39:09.000Z
2022-01-06T00:58:38.000Z
// // PhotoViewType.h // MEMobile // // Created by LamTsanFeng on 2016/9/28. // Copyright © 2016年 GZMiracle. All rights reserved. // #ifndef PhotoViewType_h #define PhotoViewType_h typedef NS_ENUM(NSInteger, downLoadType) { // 加载类型 downLoadTypeUnknown, // 未知 downLoadTypeLocale, // 本地 downLoadTypeNetWork, // 网络 downLoadTypeImage, // 显示单张图片 downLoadTypeFail = 9, // 下载失败 }; typedef NS_ENUM(NSInteger, MaskPosition) {//遮罩位置 MaskPosition_None, //遮罩与图层一样大 MaskPosition_LeftOrUp, //左边或者上边 MaskPosition_Middle, //中间位置 MaskPosition_RightOrDown,//右边或者下边 }; #endif /* PhotoViewType_h */
21.517241
53
0.708333
65601df003b87e122f9195b9fe10b3bbbc1bdd9f
17,759
h
C
moveit_core/collision_distance_field/include/moveit/collision_distance_field/collision_distance_field_types.h
Tobias-Fischer/moveit
1d8d51e295cd74d3b37ceab8c012ff0fe73003c1
[ "BSD-3-Clause" ]
null
null
null
moveit_core/collision_distance_field/include/moveit/collision_distance_field/collision_distance_field_types.h
Tobias-Fischer/moveit
1d8d51e295cd74d3b37ceab8c012ff0fe73003c1
[ "BSD-3-Clause" ]
null
null
null
moveit_core/collision_distance_field/include/moveit/collision_distance_field/collision_distance_field_types.h
Tobias-Fischer/moveit
1d8d51e295cd74d3b37ceab8c012ff0fe73003c1
[ "BSD-3-Clause" ]
2
2020-10-12T07:48:51.000Z
2020-10-19T15:28:28.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage 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. *********************************************************************/ /* Author: E. Gil Jones */ #pragma once #include <vector> #include <string> #include <algorithm> #include <memory> #include <float.h> #include <geometric_shapes/shapes.h> #include <geometric_shapes/bodies.h> #include <moveit/macros/diagnostics.h> DIAGNOSTIC_PUSH SILENT_UNUSED_PARAM #include <octomap/OcTree.h> DIAGNOSTIC_POP #include <moveit/macros/class_forward.h> #include <moveit/distance_field/distance_field.h> #include <moveit/distance_field/propagation_distance_field.h> #include <visualization_msgs/MarkerArray.h> #include <ros/console.h> namespace collision_detection { enum CollisionType { NONE = 0, SELF = 1, INTRA = 2, ENVIRONMENT = 3, }; struct CollisionSphere { CollisionSphere(const Eigen::Vector3d& rel, double radius) { relative_vec_ = rel; radius_ = radius; } EIGEN_MAKE_ALIGNED_OPERATOR_NEW Eigen::Vector3d relative_vec_; double radius_; }; struct GradientInfo { GradientInfo() : closest_distance(DBL_MAX), collision(false) { } EIGEN_MAKE_ALIGNED_OPERATOR_NEW double closest_distance; bool collision; EigenSTL::vector_Vector3d sphere_locations; std::vector<double> distances; EigenSTL::vector_Vector3d gradients; std::vector<CollisionType> types; std::vector<double> sphere_radii; std::string joint_name; void clear() { closest_distance = DBL_MAX; collision = false; sphere_locations.clear(); distances.clear(); gradients.clear(); sphere_radii.clear(); joint_name.clear(); } }; MOVEIT_CLASS_FORWARD(PosedDistanceField) MOVEIT_CLASS_FORWARD(BodyDecomposition); // Defines BodyDecompositionPtr, ConstPtr, WeakPtr... etc MOVEIT_CLASS_FORWARD(PosedBodySphereDecomposition) MOVEIT_CLASS_FORWARD(PosedBodyPointDecomposition) MOVEIT_CLASS_FORWARD(PosedBodySphereDecompositionVector) MOVEIT_CLASS_FORWARD(PosedBodyPointDecompositionVector) class PosedDistanceField : public distance_field::PropagationDistanceField { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW PosedDistanceField(const Eigen::Vector3d& size, const Eigen::Vector3d& origin, double resolution, double max_distance, bool propagate_negative_distances = false) : distance_field::PropagationDistanceField(size.x(), size.y(), size.z(), resolution, origin.x(), origin.y(), origin.z(), max_distance, propagate_negative_distances) , pose_(Eigen::Isometry3d::Identity()) { } void updatePose(const Eigen::Isometry3d& transform) { pose_ = transform; } const Eigen::Isometry3d& getPose() const { return pose_; } /** * @brief Gets not only the distance to the nearest cell but the gradient * direction. The point * defined by the x, y and z values is transform into the local distance field * coordinate system using * the current pose. * The gradient is computed as a function of the distances of near-by cells. * An uninitialized * distance is returned if the cell is not valid for gradient production * purposes. * @param x input x value of the query point * @param y input y value of the query point * @param z input z value of the query point * @param gradient_x output argument with the x value of the gradient * @param gradient_y output argument with the y value of the gradient * @param gradient_z output argument with the z value of the gradient * @param in_bounds true if the point is within the bounds of the distance * field, false otherwise */ double getDistanceGradient(double x, double y, double z, double& gradient_x, double& gradient_y, double& gradient_z, bool& in_bounds) const { Eigen::Vector3d rel_pos = pose_.inverse() * Eigen::Vector3d(x, y, z); double gx, gy, gz; double res = distance_field::PropagationDistanceField::getDistanceGradient(rel_pos.x(), rel_pos.y(), rel_pos.z(), gx, gy, gz, in_bounds); Eigen::Vector3d grad = pose_ * Eigen::Vector3d(gx, gy, gz); gradient_x = grad.x(); gradient_y = grad.y(); gradient_z = grad.z(); return res; } /* * @brief determines a set of gradients of the given collision spheres in the * distance field * @param sphere_list vector of the spheres that approximate a links geometry * @param sphere_centers vector of points which indicate the center of each * sphere in sphere_list * @param gradient output argument to be populated with the resulting gradient * calculation * @param tolerance * @param subtract_radii distance to the sphere centers will be computed by * substracting the sphere radius from the nearest point * @param maximum_value * @param stop_at_first_collision when true the computation is terminated when * the first collision is found */ bool getCollisionSphereGradients(const std::vector<CollisionSphere>& sphere_list, const EigenSTL::vector_Vector3d& sphere_centers, GradientInfo& gradient, const CollisionType& type, double tolerance, bool subtract_radii, double maximum_value, bool stop_at_first_collision); protected: Eigen::Isometry3d pose_; }; // determines set of collision spheres given a posed body; this is BAD! // Allocation erorrs will happen; change this function so it does not return // that vector by value std::vector<CollisionSphere> determineCollisionSpheres(const bodies::Body* body, Eigen::Isometry3d& relativeTransform); // determines a set of gradients of the given collision spheres in the distance // field bool getCollisionSphereGradients(const distance_field::DistanceField* distance_field, const std::vector<CollisionSphere>& sphere_list, const EigenSTL::vector_Vector3d& sphere_centers, GradientInfo& gradient, const CollisionType& type, double tolerance, bool subtract_radii, double maximum_value, bool stop_at_first_collision); bool getCollisionSphereCollision(const distance_field::DistanceField* distance_field, const std::vector<CollisionSphere>& sphere_list, const EigenSTL::vector_Vector3d& sphere_centers, double maximum_value, double tolerance); bool getCollisionSphereCollision(const distance_field::DistanceField* distance_field, const std::vector<CollisionSphere>& sphere_list, const EigenSTL::vector_Vector3d& sphere_centers, double maximum_value, double tolerance, unsigned int num_coll, std::vector<unsigned int>& colls); // forward declaration required for friending apparently class BodyDecompositionVector; class BodyDecomposition { friend class BodyDecompositionVector; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW BodyDecomposition(const shapes::ShapeConstPtr& shape, double resolution, double padding = 0.01); BodyDecomposition(const std::vector<shapes::ShapeConstPtr>& shapes, const EigenSTL::vector_Isometry3d& poses, double resolution, double padding); ~BodyDecomposition(); Eigen::Isometry3d relative_cylinder_pose_; void replaceCollisionSpheres(const std::vector<CollisionSphere>& new_collision_spheres, const Eigen::Isometry3d& new_relative_cylinder_pose) { // std::cerr << "Replacing " << collision_spheres_.size() << " with " << // new_collision_spheres.size() << std::endl; collision_spheres_ = new_collision_spheres; relative_cylinder_pose_ = new_relative_cylinder_pose; } const std::vector<CollisionSphere>& getCollisionSpheres() const { return collision_spheres_; } const std::vector<double>& getSphereRadii() const { return sphere_radii_; } const EigenSTL::vector_Vector3d& getCollisionPoints() const { return relative_collision_points_; } const bodies::Body* getBody(unsigned int i) const { return bodies_.getBody(i); } unsigned int getBodiesCount() { return bodies_.getCount(); } Eigen::Isometry3d getRelativeCylinderPose() const { return relative_cylinder_pose_; } const bodies::BoundingSphere& getRelativeBoundingSphere() const { return relative_bounding_sphere_; } protected: void init(const std::vector<shapes::ShapeConstPtr>& shapes, const EigenSTL::vector_Isometry3d& poses, double resolution, double padding); protected: bodies::BodyVector bodies_; bodies::BoundingSphere relative_bounding_sphere_; std::vector<double> sphere_radii_; std::vector<CollisionSphere> collision_spheres_; EigenSTL::vector_Vector3d relative_collision_points_; }; class PosedBodySphereDecomposition { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW PosedBodySphereDecomposition(const BodyDecompositionConstPtr& body_decomposition); const std::vector<CollisionSphere>& getCollisionSpheres() const { return body_decomposition_->getCollisionSpheres(); } const EigenSTL::vector_Vector3d& getSphereCenters() const { return sphere_centers_; } const EigenSTL::vector_Vector3d& getCollisionPoints() const { return posed_collision_points_; } const std::vector<double>& getSphereRadii() const { return body_decomposition_->getSphereRadii(); } const Eigen::Vector3d& getBoundingSphereCenter() const { return posed_bounding_sphere_center_; } double getBoundingSphereRadius() const { return body_decomposition_->getRelativeBoundingSphere().radius; } // assumed to be in reference frame, updates the pose of the body, // the collision spheres, and the posed collision points void updatePose(const Eigen::Isometry3d& linkTransform); protected: BodyDecompositionConstPtr body_decomposition_; Eigen::Vector3d posed_bounding_sphere_center_; EigenSTL::vector_Vector3d posed_collision_points_; EigenSTL::vector_Vector3d sphere_centers_; }; class PosedBodyPointDecomposition { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW PosedBodyPointDecomposition(const BodyDecompositionConstPtr& body_decomposition); PosedBodyPointDecomposition(const BodyDecompositionConstPtr& body_decomposition, const Eigen::Isometry3d& pose); PosedBodyPointDecomposition(const std::shared_ptr<const octomap::OcTree>& octree); const EigenSTL::vector_Vector3d& getCollisionPoints() const { return posed_collision_points_; } // the collision spheres, and the posed collision points void updatePose(const Eigen::Isometry3d& linkTransform); protected: BodyDecompositionConstPtr body_decomposition_; EigenSTL::vector_Vector3d posed_collision_points_; }; class PosedBodySphereDecompositionVector { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW PosedBodySphereDecompositionVector() { } const std::vector<CollisionSphere>& getCollisionSpheres() const { return collision_spheres_; } const EigenSTL::vector_Vector3d& getSphereCenters() const { return posed_collision_spheres_; } const std::vector<double>& getSphereRadii() const { return sphere_radii_; } void addToVector(PosedBodySphereDecompositionPtr& bd) { sphere_index_map_[decomp_vector_.size()] = collision_spheres_.size(); decomp_vector_.push_back(bd); collision_spheres_.insert(collision_spheres_.end(), bd->getCollisionSpheres().begin(), bd->getCollisionSpheres().end()); posed_collision_spheres_.insert(posed_collision_spheres_.end(), bd->getSphereCenters().begin(), bd->getSphereCenters().end()); sphere_radii_.insert(sphere_radii_.end(), bd->getSphereRadii().begin(), bd->getSphereRadii().end()); } unsigned int getSize() const { return decomp_vector_.size(); } PosedBodySphereDecompositionConstPtr getPosedBodySphereDecomposition(unsigned int i) const { if (i >= decomp_vector_.size()) { ROS_INFO_NAMED("collision_distance_field", "No body decomposition"); return empty_ptr_; } return decomp_vector_[i]; } void updatePose(unsigned int ind, const Eigen::Isometry3d& pose) { if (ind >= decomp_vector_.size()) { ROS_WARN_NAMED("collision_distance_field", "Can't update pose"); return; } decomp_vector_[ind]->updatePose(pose); for (unsigned int i = 0; i < decomp_vector_[ind]->getSphereCenters().size(); i++) { posed_collision_spheres_[sphere_index_map_[ind] + i] = decomp_vector_[ind]->getSphereCenters()[i]; } } private: PosedBodySphereDecompositionConstPtr empty_ptr_; std::vector<PosedBodySphereDecompositionPtr> decomp_vector_; std::vector<CollisionSphere> collision_spheres_; EigenSTL::vector_Vector3d posed_collision_spheres_; std::vector<double> sphere_radii_; std::map<unsigned int, unsigned int> sphere_index_map_; }; class PosedBodyPointDecompositionVector { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW PosedBodyPointDecompositionVector() { } EigenSTL::vector_Vector3d getCollisionPoints() const { EigenSTL::vector_Vector3d ret_points; for (const PosedBodyPointDecompositionPtr& decomp : decomp_vector_) { ret_points.insert(ret_points.end(), decomp->getCollisionPoints().begin(), decomp->getCollisionPoints().end()); } return ret_points; } void addToVector(PosedBodyPointDecompositionPtr& bd) { decomp_vector_.push_back(bd); } unsigned int getSize() const { return decomp_vector_.size(); } PosedBodyPointDecompositionConstPtr getPosedBodyDecomposition(unsigned int i) const { if (i >= decomp_vector_.size()) { ROS_INFO_NAMED("collision_distance_field", "No body decomposition"); return empty_ptr_; } return decomp_vector_[i]; } void updatePose(unsigned int ind, const Eigen::Isometry3d& pose) { if (ind < decomp_vector_.size()) { decomp_vector_[ind]->updatePose(pose); } else { ROS_WARN_NAMED("collision_distance_field", "Can't update pose"); return; } } private: PosedBodyPointDecompositionPtr empty_ptr_; std::vector<PosedBodyPointDecompositionPtr> decomp_vector_; }; struct ProximityInfo { EIGEN_MAKE_ALIGNED_OPERATOR_NEW std::string link_name; std::string attached_object_name; double proximity; unsigned int sphere_index; unsigned int att_index; Eigen::Vector3d closest_point; Eigen::Vector3d closest_gradient; }; bool doBoundingSpheresIntersect(const PosedBodySphereDecompositionConstPtr& p1, const PosedBodySphereDecompositionConstPtr& p2); void getCollisionSphereMarkers(const std_msgs::ColorRGBA& color, const std::string& frame_id, const std::string& ns, const ros::Duration& dur, const std::vector<PosedBodySphereDecompositionPtr>& posed_decompositions, visualization_msgs::MarkerArray& arr); void getProximityGradientMarkers(const std::string& frame_id, const std::string& ns, const ros::Duration& dur, const std::vector<PosedBodySphereDecompositionPtr>& posed_decompositions, const std::vector<PosedBodySphereDecompositionVectorPtr>& posed_vector_decompositions, const std::vector<GradientInfo>& gradients, visualization_msgs::MarkerArray& arr); void getCollisionMarkers(const std::string& frame_id, const std::string& ns, const ros::Duration& dur, const std::vector<PosedBodySphereDecompositionPtr>& posed_decompositions, const std::vector<PosedBodySphereDecompositionVectorPtr>& posed_vector_decompositions, const std::vector<GradientInfo>& gradients, visualization_msgs::MarkerArray& arr); } // namespace collision_detection
33.63447
120
0.711921
459a11d1d5ebe50f98d29b3bd3a3feca820152f5
3,098
c
C
bin/operation/readline.c
Melchizedek6809/Nujel
e213ac44c705a6dd123f078005afcc218f616b1f
[ "MIT" ]
9
2021-09-02T22:02:34.000Z
2022-03-23T00:00:08.000Z
bin/operation/readline.c
Melchizedek6809/Nujel
e213ac44c705a6dd123f078005afcc218f616b1f
[ "MIT" ]
3
2021-09-03T14:43:29.000Z
2021-09-14T21:55:57.000Z
bin/operation/readline.c
Melchizedek6809/Nujel
e213ac44c705a6dd123f078005afcc218f616b1f
[ "MIT" ]
null
null
null
/* * Nujel - Copyright (C) 2020-2021 - Benjamin Vincent Schulenburg * * This project uses the MIT license, a copy should be included under /LICENSE */ #include "readline.h" #include "../misc.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #if defined(__MINGW32__) || defined(__MSYS__) #include <windows.h> #include <shlobj.h> #include "../../vendor/getline/getline.h" /* Since bestline does not support windows, * these serve as a simple replacement. */ #define BUF_SIZE (1 << 14) static void bestlineHistoryLoad(const char *path){(void)path;} static void bestlineHistorySave(const char *path){(void)path;} static void bestlineHistoryAdd (const char *line){(void)line;} static char *bestline(const char *prompt){ char *buf = NULL; size_t bufsize = 0; fputs(prompt, stdout); const ssize_t ret = getline(&buf,&bufsize,stdin); if(ret >= 0){ buf[MIN(bufsize-1,(size_t)ret)] = 0; return buf; }else{ return NULL; } } #else #include "../../vendor/bestline/bestline.h" #endif const char *getHistoryPath(){ static char buf[512]; #ifdef __MINGW32__ char home[512]; HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, home); if(result != S_OK){ return NULL; } #else const char* home = getenv("HOME"); if(!home){ return NULL; } #endif spf(buf,&buf[sizeof(buf)],"%s/.nujel_history",home); return buf; } static lVal *lnfReadline(lClosure *c, lVal *v){ (void) c; const char *prompt = castToString(lCar(v),"> "); char *line = bestline(prompt); lVal *ret = lValString(line); free(line); return ret; } static lVal *lnfReadlineHistoryPath(lClosure *c, lVal *v){ (void) c; (void) v; return lValString(getHistoryPath()); } static lVal *lnfReadlineHistoryAdd(lClosure *c, lVal *v){ (void) c; const char *line = castToString(lCar(v),NULL); if(line == NULL){return NULL;} bestlineHistoryAdd(line); return lCar(v); } static lVal *lnfReadlineHistoryLoad(lClosure *c, lVal *v){ (void) c; const char *path = castToString(lCar(v),NULL); if(path == NULL){return NULL;} bestlineHistoryLoad(path); return lValBool(true); } static lVal *lnfReadlineHistorySave(lClosure *c, lVal *v){ (void) c; const char *path = castToString(lCar(v),NULL); if(path == NULL){return NULL;} bestlineHistorySave(path); return lValBool(true); } void lOperationsReadline(lClosure *c){ lAddNativeFunc(c,"readline", "[prompt]", "Read a line of input in a user friendly way after writing PROMPT", lnfReadline); lAddNativeFunc(c,"readline/history/path", "[]", "Return the default path to the command history", lnfReadlineHistoryPath); lAddNativeFunc(c,"readline/history/load", "[path]", "Load command history from PATH", lnfReadlineHistoryLoad); lAddNativeFunc(c,"readline/history/save", "[path]", "Save command history into PATH", lnfReadlineHistorySave); lAddNativeFunc(c,"readline/history/add", "[line]", "Add an entry into the command history without saving", lnfReadlineHistoryAdd); }
28.685185
147
0.677211
10d25abafd99341301453dfc4c2c3eba1a9b6f6d
5,390
h
C
Sources/CAudioKit/Devoloop/include/FFTReal/FFTRealPassDirect.h
kylestew/AudioKit
4ce9bb325f6576ac2a4141d6e72428dd13d8239d
[ "MIT" ]
7
2021-06-07T16:37:38.000Z
2022-03-20T06:15:15.000Z
Sources/CAudioKit/Devoloop/include/FFTReal/FFTRealPassDirect.h
kylestew/AudioKit
4ce9bb325f6576ac2a4141d6e72428dd13d8239d
[ "MIT" ]
null
null
null
Sources/CAudioKit/Devoloop/include/FFTReal/FFTRealPassDirect.h
kylestew/AudioKit
4ce9bb325f6576ac2a4141d6e72428dd13d8239d
[ "MIT" ]
2
2021-08-07T00:36:50.000Z
2021-12-28T01:18:08.000Z
/***************************************************************************** FFTRealPassDirect.h By Laurent de Soras --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined(ffft_FFTRealPassDirect_CURRENT_CODEHEADER) #error Recursive inclusion of FFTRealPassDirect code header. #endif #define ffft_FFTRealPassDirect_CURRENT_CODEHEADER #if !defined(ffft_FFTRealPassDirect_CODEHEADER_INCLUDED) #define ffft_FFTRealPassDirect_CODEHEADER_INCLUDED #include "ffft/FFTRealUseTrigo.h" namespace ffft { template <> inline void FFTRealPassDirect<1>::process(long len, DataType dest_ptr[], DataType src_ptr[], const DataType x_ptr[], const DataType cos_ptr[], long cos_len, const long br_ptr[], OscType osc_list[]) { // First and second pass at once const long qlen = len >> 2; long coef_index = 0; do { // To do: unroll the loop (2x). const long ri_0 = br_ptr[coef_index >> 2]; const long ri_1 = ri_0 + 2 * qlen; // bit_rev_lut_ptr [coef_index + 1]; const long ri_2 = ri_0 + 1 * qlen; // bit_rev_lut_ptr [coef_index + 2]; const long ri_3 = ri_0 + 3 * qlen; // bit_rev_lut_ptr [coef_index + 3]; DataType *const df2 = dest_ptr + coef_index; df2[1] = x_ptr[ri_0] - x_ptr[ri_1]; df2[3] = x_ptr[ri_2] - x_ptr[ri_3]; const DataType sf_0 = x_ptr[ri_0] + x_ptr[ri_1]; const DataType sf_2 = x_ptr[ri_2] + x_ptr[ri_3]; df2[0] = sf_0 + sf_2; df2[2] = sf_0 - sf_2; coef_index += 4; } while (coef_index < len); } template <> inline void FFTRealPassDirect<2>::process(long len, DataType dest_ptr[], DataType src_ptr[], const DataType x_ptr[], const DataType cos_ptr[], long cos_len, const long br_ptr[], OscType osc_list[]) { // Executes "previous" passes first. Inverts source and destination buffers FFTRealPassDirect<1>::process(len, src_ptr, dest_ptr, x_ptr, cos_ptr, cos_len, br_ptr, osc_list); // Third pass const DataType sqrt2_2 = DataType(SQRT2 * 0.5); long coef_index = 0; do { dest_ptr[coef_index] = src_ptr[coef_index] + src_ptr[coef_index + 4]; dest_ptr[coef_index + 4] = src_ptr[coef_index] - src_ptr[coef_index + 4]; dest_ptr[coef_index + 2] = src_ptr[coef_index + 2]; dest_ptr[coef_index + 6] = src_ptr[coef_index + 6]; DataType v; v = (src_ptr[coef_index + 5] - src_ptr[coef_index + 7]) * sqrt2_2; dest_ptr[coef_index + 1] = src_ptr[coef_index + 1] + v; dest_ptr[coef_index + 3] = src_ptr[coef_index + 1] - v; v = (src_ptr[coef_index + 5] + src_ptr[coef_index + 7]) * sqrt2_2; dest_ptr[coef_index + 5] = v + src_ptr[coef_index + 3]; dest_ptr[coef_index + 7] = v - src_ptr[coef_index + 3]; coef_index += 8; } while (coef_index < len); } template <int PASS> void FFTRealPassDirect<PASS>::process(long len, DataType dest_ptr[], DataType src_ptr[], const DataType x_ptr[], const DataType cos_ptr[], long cos_len, const long br_ptr[], OscType osc_list[]) { // Executes "previous" passes first. Inverts source and destination buffers FFTRealPassDirect<PASS - 1>::process(len, src_ptr, dest_ptr, x_ptr, cos_ptr, cos_len, br_ptr, osc_list); const long dist = 1L << (PASS - 1); const long c1_r = 0; const long c1_i = dist; const long c2_r = dist * 2; const long c2_i = dist * 3; const long cend = dist * 4; const long table_step = cos_len >> (PASS - 1); enum { TRIGO_OSC = PASS - FFTRealFixLenParam::TRIGO_BD_LIMIT }; enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 }; long coef_index = 0; do { const DataType *const sf = src_ptr + coef_index; DataType *const df = dest_ptr + coef_index; // Extreme coefficients are always real df[c1_r] = sf[c1_r] + sf[c2_r]; df[c2_r] = sf[c1_r] - sf[c2_r]; df[c1_i] = sf[c1_i]; df[c2_i] = sf[c2_i]; FFTRealUseTrigo<TRIGO_DIRECT>::prepare(osc_list[TRIGO_OSC]); // Others are conjugate complex numbers for (long i = 1; i < dist; ++i) { DataType c; DataType s; FFTRealUseTrigo<TRIGO_DIRECT>::iterate(osc_list[TRIGO_OSC], c, s, cos_ptr, i * table_step, (dist - i) * table_step); const DataType sf_r_i = sf[c1_r + i]; const DataType sf_i_i = sf[c1_i + i]; const DataType v1 = sf[c2_r + i] * c - sf[c2_i + i] * s; df[c1_r + i] = sf_r_i + v1; df[c2_r - i] = sf_r_i - v1; const DataType v2 = sf[c2_r + i] * s + sf[c2_i + i] * c; df[c2_r + i] = v2 + sf_i_i; df[cend - i] = v2 - sf_i_i; } coef_index += cend; } while (coef_index < len); } } #endif #undef ffft_FFTRealPassDirect_CURRENT_CODEHEADER
32.46988
80
0.588126
803529fd50f8a32f0cbf98e5a0ec05d10948e337
51,585
c
C
xen/xen-4.2.2-hv/xen/arch/x86/domctl.c
zhiming-shen/Xen-Blanket-NG
47e59d9bb92e8fdc60942df526790ddb983a5496
[ "Apache-2.0" ]
1
2018-02-02T00:15:26.000Z
2018-02-02T00:15:26.000Z
xen/xen-4.2.2-hv/xen/arch/x86/domctl.c
zhiming-shen/Xen-Blanket-NG
47e59d9bb92e8fdc60942df526790ddb983a5496
[ "Apache-2.0" ]
null
null
null
xen/xen-4.2.2-hv/xen/arch/x86/domctl.c
zhiming-shen/Xen-Blanket-NG
47e59d9bb92e8fdc60942df526790ddb983a5496
[ "Apache-2.0" ]
1
2019-05-27T09:47:18.000Z
2019-05-27T09:47:18.000Z
/****************************************************************************** * Arch-specific domctl.c * * Copyright (c) 2002-2006, K A Fraser */ #include <xen/config.h> #include <xen/types.h> #include <xen/lib.h> #include <xen/mm.h> #include <xen/guest_access.h> #include <xen/compat.h> #include <xen/pci.h> #include <public/domctl.h> #include <xen/sched.h> #include <xen/domain.h> #include <xen/event.h> #include <xen/domain_page.h> #include <asm/msr.h> #include <xen/trace.h> #include <xen/console.h> #include <xen/iocap.h> #include <xen/paging.h> #include <asm/irq.h> #include <asm/hvm/hvm.h> #include <asm/hvm/support.h> #include <asm/hvm/cacheattr.h> #include <asm/processor.h> #include <asm/acpi.h> /* for hvm_acpi_power_button */ #include <xen/hypercall.h> /* for arch_do_domctl */ #include <xsm/xsm.h> #include <xen/iommu.h> #include <asm/mem_event.h> #include <public/mem_event.h> #include <asm/mem_sharing.h> #include <asm/xstate.h> #include <asm/debugger.h> #include "cpu/cpu.h" static int gdbsx_guest_mem_io( domid_t domid, struct xen_domctl_gdbsx_memio *iop) { ulong l_uva = (ulong)iop->uva; iop->remain = dbg_rw_mem( (dbgva_t)iop->gva, (dbgbyte_t *)l_uva, iop->len, domid, iop->gwr, iop->pgd3val); return (iop->remain ? -EFAULT : 0); } long arch_do_domctl( struct xen_domctl *domctl, XEN_GUEST_HANDLE(xen_domctl_t) u_domctl) { long ret = 0; switch ( domctl->cmd ) { case XEN_DOMCTL_shadow_op: { struct domain *d; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d != NULL ) { ret = paging_domctl(d, &domctl->u.shadow_op, guest_handle_cast(u_domctl, void)); rcu_unlock_domain(d); copy_to_guest(u_domctl, domctl, 1); } } break; case XEN_DOMCTL_ioport_permission: { struct domain *d; unsigned int fp = domctl->u.ioport_permission.first_port; unsigned int np = domctl->u.ioport_permission.nr_ports; int allow = domctl->u.ioport_permission.allow_access; ret = -EINVAL; if ( (fp + np) > 65536 ) break; ret = -ESRCH; if ( unlikely((d = rcu_lock_domain_by_id(domctl->domain)) == NULL) ) break; if ( np == 0 ) ret = 0; else if ( xsm_ioport_permission(d, fp, fp + np - 1, allow) ) ret = -EPERM; else if ( allow ) ret = ioports_permit_access(d, fp, fp + np - 1); else ret = ioports_deny_access(d, fp, fp + np - 1); rcu_unlock_domain(d); } break; case XEN_DOMCTL_getpageframeinfo: { struct page_info *page; unsigned long mfn = domctl->u.getpageframeinfo.gmfn; domid_t dom = domctl->domain; struct domain *d; ret = -EINVAL; if ( unlikely(!mfn_valid(mfn)) || unlikely((d = rcu_lock_domain_by_id(dom)) == NULL) ) break; page = mfn_to_page(mfn); ret = xsm_getpageframeinfo(d); if ( ret ) { rcu_unlock_domain(d); break; } if ( likely(get_page(page, d)) ) { ret = 0; domctl->u.getpageframeinfo.type = XEN_DOMCTL_PFINFO_NOTAB; if ( (page->u.inuse.type_info & PGT_count_mask) != 0 ) { switch ( page->u.inuse.type_info & PGT_type_mask ) { case PGT_l1_page_table: domctl->u.getpageframeinfo.type = XEN_DOMCTL_PFINFO_L1TAB; break; case PGT_l2_page_table: domctl->u.getpageframeinfo.type = XEN_DOMCTL_PFINFO_L2TAB; break; case PGT_l3_page_table: domctl->u.getpageframeinfo.type = XEN_DOMCTL_PFINFO_L3TAB; break; case PGT_l4_page_table: domctl->u.getpageframeinfo.type = XEN_DOMCTL_PFINFO_L4TAB; break; } } put_page(page); } rcu_unlock_domain(d); copy_to_guest(u_domctl, domctl, 1); } break; case XEN_DOMCTL_getpageframeinfo3: #ifdef __x86_64__ if (!has_32bit_shinfo(current->domain)) { unsigned int n, j; unsigned int num = domctl->u.getpageframeinfo3.num; domid_t dom = domctl->domain; struct domain *d; struct page_info *page; xen_pfn_t *arr; ret = -ESRCH; if ( unlikely((d = rcu_lock_domain_by_id(dom)) == NULL) ) break; ret = xsm_getpageframeinfo(d); if ( ret ) { rcu_unlock_domain(d); break; } if ( unlikely(num > 1024) || unlikely(num != domctl->u.getpageframeinfo3.num) ) { ret = -E2BIG; rcu_unlock_domain(d); break; } page = alloc_domheap_page(NULL, 0); if ( !page ) { ret = -ENOMEM; rcu_unlock_domain(d); break; } arr = page_to_virt(page); for ( n = ret = 0; n < num; ) { unsigned int k = min_t(unsigned int, num - n, PAGE_SIZE / sizeof(*arr)); if ( copy_from_guest_offset(arr, domctl->u.getpageframeinfo3.array, n, k) ) { ret = -EFAULT; break; } for ( j = 0; j < k; j++ ) { unsigned long type = 0; page = get_page_from_gfn(d, arr[j], NULL, P2M_ALLOC); if ( unlikely(!page) || unlikely(is_xen_heap_page(page)) ) type = XEN_DOMCTL_PFINFO_XTAB; else { switch( page->u.inuse.type_info & PGT_type_mask ) { case PGT_l1_page_table: type = XEN_DOMCTL_PFINFO_L1TAB; break; case PGT_l2_page_table: type = XEN_DOMCTL_PFINFO_L2TAB; break; case PGT_l3_page_table: type = XEN_DOMCTL_PFINFO_L3TAB; break; case PGT_l4_page_table: type = XEN_DOMCTL_PFINFO_L4TAB; break; } if ( page->u.inuse.type_info & PGT_pinned ) type |= XEN_DOMCTL_PFINFO_LPINTAB; } if ( page ) put_page(page); arr[j] = type; } if ( copy_to_guest_offset(domctl->u.getpageframeinfo3.array, n, arr, k) ) { ret = -EFAULT; break; } n += k; } free_domheap_page(virt_to_page(arr)); rcu_unlock_domain(d); break; } #endif /* fall thru */ case XEN_DOMCTL_getpageframeinfo2: { int n,j; int num = domctl->u.getpageframeinfo2.num; domid_t dom = domctl->domain; struct domain *d; uint32_t *arr32; ret = -ESRCH; if ( unlikely((d = rcu_lock_domain_by_id(dom)) == NULL) ) break; ret = xsm_getpageframeinfo(d); if ( ret ) { rcu_unlock_domain(d); break; } if ( unlikely(num > 1024) ) { ret = -E2BIG; rcu_unlock_domain(d); break; } arr32 = alloc_xenheap_page(); if ( !arr32 ) { ret = -ENOMEM; rcu_unlock_domain(d); break; } ret = 0; for ( n = 0; n < num; ) { int k = PAGE_SIZE / 4; if ( (num - n) < k ) k = num - n; if ( copy_from_guest_offset(arr32, domctl->u.getpageframeinfo2.array, n, k) ) { ret = -EFAULT; break; } for ( j = 0; j < k; j++ ) { struct page_info *page; unsigned long gfn = arr32[j]; page = get_page_from_gfn(d, gfn, NULL, P2M_ALLOC); if ( domctl->cmd == XEN_DOMCTL_getpageframeinfo3) arr32[j] = 0; if ( unlikely(!page) || unlikely(is_xen_heap_page(page)) ) arr32[j] |= XEN_DOMCTL_PFINFO_XTAB; else { unsigned long type = 0; switch( page->u.inuse.type_info & PGT_type_mask ) { case PGT_l1_page_table: type = XEN_DOMCTL_PFINFO_L1TAB; break; case PGT_l2_page_table: type = XEN_DOMCTL_PFINFO_L2TAB; break; case PGT_l3_page_table: type = XEN_DOMCTL_PFINFO_L3TAB; break; case PGT_l4_page_table: type = XEN_DOMCTL_PFINFO_L4TAB; break; } if ( page->u.inuse.type_info & PGT_pinned ) type |= XEN_DOMCTL_PFINFO_LPINTAB; arr32[j] |= type; } if ( page ) put_page(page); } if ( copy_to_guest_offset(domctl->u.getpageframeinfo2.array, n, arr32, k) ) { ret = -EFAULT; break; } n += k; } free_xenheap_page(arr32); rcu_unlock_domain(d); } break; case XEN_DOMCTL_getmemlist: { int i; struct domain *d = rcu_lock_domain_by_id(domctl->domain); unsigned long max_pfns = domctl->u.getmemlist.max_pfns; uint64_t mfn; struct page_info *page; ret = -EINVAL; if ( d != NULL ) { ret = xsm_getmemlist(d); if ( ret ) { rcu_unlock_domain(d); break; } spin_lock(&d->page_alloc_lock); if ( unlikely(d->is_dying) ) { spin_unlock(&d->page_alloc_lock); goto getmemlist_out; } ret = i = 0; page_list_for_each(page, &d->page_list) { if ( i >= max_pfns ) break; mfn = page_to_mfn(page); if ( copy_to_guest_offset(domctl->u.getmemlist.buffer, i, &mfn, 1) ) { ret = -EFAULT; break; } ++i; } spin_unlock(&d->page_alloc_lock); domctl->u.getmemlist.num_pfns = i; copy_to_guest(u_domctl, domctl, 1); getmemlist_out: rcu_unlock_domain(d); } } break; case XEN_DOMCTL_hypercall_init: { struct domain *d = rcu_lock_domain_by_id(domctl->domain); unsigned long gmfn = domctl->u.hypercall_init.gmfn; struct page_info *page; void *hypercall_page; ret = -ESRCH; if ( unlikely(d == NULL) ) break; ret = xsm_hypercall_init(d); if ( ret ) { rcu_unlock_domain(d); break; } page = get_page_from_gfn(d, gmfn, NULL, P2M_ALLOC); ret = -EACCES; if ( !page || !get_page_type(page, PGT_writable_page) ) { if ( page ) put_page(page); rcu_unlock_domain(d); break; } ret = 0; hypercall_page = __map_domain_page(page); hypercall_page_initialise(d, hypercall_page); unmap_domain_page(hypercall_page); put_page_and_type(page); rcu_unlock_domain(d); } break; case XEN_DOMCTL_sethvmcontext: { struct hvm_domain_context c = { .size = domctl->u.hvmcontext.size }; struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_hvmcontext(d, domctl->cmd); if ( ret ) goto sethvmcontext_out; ret = -EINVAL; if ( !is_hvm_domain(d) ) goto sethvmcontext_out; ret = -ENOMEM; if ( (c.data = xmalloc_bytes(c.size)) == NULL ) goto sethvmcontext_out; ret = -EFAULT; if ( copy_from_guest(c.data, domctl->u.hvmcontext.buffer, c.size) != 0) goto sethvmcontext_out; domain_pause(d); ret = hvm_load(d, &c); domain_unpause(d); sethvmcontext_out: if ( c.data != NULL ) xfree(c.data); rcu_unlock_domain(d); } break; case XEN_DOMCTL_gethvmcontext: { struct hvm_domain_context c = { 0 }; struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_hvmcontext(d, domctl->cmd); if ( ret ) goto gethvmcontext_out; ret = -EINVAL; if ( !is_hvm_domain(d) ) goto gethvmcontext_out; c.size = hvm_save_size(d); if ( guest_handle_is_null(domctl->u.hvmcontext.buffer) ) { /* Client is querying for the correct buffer size */ domctl->u.hvmcontext.size = c.size; ret = 0; goto gethvmcontext_out; } /* Check that the client has a big enough buffer */ ret = -ENOSPC; if ( domctl->u.hvmcontext.size < c.size ) goto gethvmcontext_out; /* Allocate our own marshalling buffer */ ret = -ENOMEM; if ( (c.data = xmalloc_bytes(c.size)) == NULL ) goto gethvmcontext_out; domain_pause(d); ret = hvm_save(d, &c); domain_unpause(d); domctl->u.hvmcontext.size = c.cur; if ( copy_to_guest(domctl->u.hvmcontext.buffer, c.data, c.size) != 0 ) ret = -EFAULT; gethvmcontext_out: if ( copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; if ( c.data != NULL ) xfree(c.data); rcu_unlock_domain(d); } break; case XEN_DOMCTL_gethvmcontext_partial: { struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_hvmcontext(d, domctl->cmd); if ( ret ) goto gethvmcontext_partial_out; ret = -EINVAL; if ( !is_hvm_domain(d) ) goto gethvmcontext_partial_out; domain_pause(d); ret = hvm_save_one(d, domctl->u.hvmcontext_partial.type, domctl->u.hvmcontext_partial.instance, domctl->u.hvmcontext_partial.buffer); domain_unpause(d); gethvmcontext_partial_out: rcu_unlock_domain(d); } break; case XEN_DOMCTL_set_address_size: { struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_address_size(d, domctl->cmd); if ( ret ) { rcu_unlock_domain(d); break; } switch ( domctl->u.address_size.size ) { #ifdef CONFIG_COMPAT case 32: ret = switch_compat(d); break; case 64: ret = switch_native(d); break; #endif default: ret = (domctl->u.address_size.size == BITS_PER_LONG) ? 0 : -EINVAL; break; } rcu_unlock_domain(d); } break; case XEN_DOMCTL_get_address_size: { struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_address_size(d, domctl->cmd); if ( ret ) { rcu_unlock_domain(d); break; } domctl->u.address_size.size = is_pv_32on64_domain(d) ? 32 : BITS_PER_LONG; ret = 0; rcu_unlock_domain(d); if ( copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; } break; case XEN_DOMCTL_set_machine_address_size: { struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_machine_address_size(d, domctl->cmd); if ( ret ) goto set_machine_address_size_out; ret = -EBUSY; if ( d->tot_pages > 0 ) goto set_machine_address_size_out; d->arch.physaddr_bitsize = domctl->u.address_size.size; ret = 0; set_machine_address_size_out: rcu_unlock_domain(d); } break; case XEN_DOMCTL_get_machine_address_size: { struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_machine_address_size(d, domctl->cmd); if ( ret ) { rcu_unlock_domain(d); break; } domctl->u.address_size.size = d->arch.physaddr_bitsize; ret = 0; rcu_unlock_domain(d); if ( copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; } break; case XEN_DOMCTL_sendtrigger: { struct domain *d; struct vcpu *v; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = xsm_sendtrigger(d); if ( ret ) goto sendtrigger_out; ret = -EINVAL; if ( domctl->u.sendtrigger.vcpu >= MAX_VIRT_CPUS ) goto sendtrigger_out; ret = -ESRCH; if ( domctl->u.sendtrigger.vcpu >= d->max_vcpus || (v = d->vcpu[domctl->u.sendtrigger.vcpu]) == NULL ) goto sendtrigger_out; switch ( domctl->u.sendtrigger.trigger ) { case XEN_DOMCTL_SENDTRIGGER_NMI: { ret = 0; if ( !test_and_set_bool(v->nmi_pending) ) vcpu_kick(v); } break; case XEN_DOMCTL_SENDTRIGGER_POWER: { ret = -EINVAL; if ( is_hvm_domain(d) ) { ret = 0; hvm_acpi_power_button(d); } } break; case XEN_DOMCTL_SENDTRIGGER_SLEEP: { ret = -EINVAL; if ( is_hvm_domain(d) ) { ret = 0; hvm_acpi_sleep_button(d); } } break; default: ret = -ENOSYS; } sendtrigger_out: rcu_unlock_domain(d); } break; case XEN_DOMCTL_bind_pt_irq: { struct domain * d; xen_domctl_bind_pt_irq_t * bind; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; bind = &(domctl->u.bind_pt_irq); ret = -EINVAL; if ( !is_hvm_domain(d) ) goto bind_out; ret = xsm_bind_pt_irq(d, bind); if ( ret ) goto bind_out; ret = -EPERM; if ( !IS_PRIV(current->domain) ) { int irq = domain_pirq_to_irq(d, bind->machine_irq); if ( irq <= 0 || !irq_access_permitted(current->domain, irq) ) goto bind_out; } ret = -ESRCH; if ( iommu_enabled ) { spin_lock(&pcidevs_lock); ret = pt_irq_create_bind_vtd(d, bind); spin_unlock(&pcidevs_lock); } if ( ret < 0 ) printk(XENLOG_G_ERR "pt_irq_create_bind failed (%ld) for dom%d\n", ret, d->domain_id); bind_out: rcu_unlock_domain(d); } break; case XEN_DOMCTL_unbind_pt_irq: { struct domain * d; xen_domctl_bind_pt_irq_t * bind; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; bind = &(domctl->u.bind_pt_irq); ret = -EPERM; if ( !IS_PRIV(current->domain) ) { int irq = domain_pirq_to_irq(d, bind->machine_irq); if ( irq <= 0 || !irq_access_permitted(current->domain, irq) ) goto unbind_out; } if ( iommu_enabled ) { spin_lock(&pcidevs_lock); ret = pt_irq_destroy_bind_vtd(d, bind); spin_unlock(&pcidevs_lock); } if ( ret < 0 ) printk(XENLOG_G_ERR "pt_irq_destroy_bind failed (%ld) for dom%d\n", ret, d->domain_id); unbind_out: rcu_unlock_domain(d); } break; case XEN_DOMCTL_memory_mapping: { struct domain *d; unsigned long gfn = domctl->u.memory_mapping.first_gfn; unsigned long mfn = domctl->u.memory_mapping.first_mfn; unsigned long nr_mfns = domctl->u.memory_mapping.nr_mfns; int add = domctl->u.memory_mapping.add_mapping; unsigned long i; ret = -EINVAL; if ( (mfn + nr_mfns - 1) < mfn || /* wrap? */ ((mfn | (mfn + nr_mfns - 1)) >> (paddr_bits - PAGE_SHIFT)) || (gfn + nr_mfns - 1) < gfn ) /* wrap? */ break; ret = -EPERM; if ( !IS_PRIV(current->domain) && !iomem_access_permitted(current->domain, mfn, mfn + nr_mfns - 1) ) break; ret = -ESRCH; if ( unlikely((d = rcu_lock_domain_by_id(domctl->domain)) == NULL) ) break; ret = xsm_iomem_permission(d, mfn, mfn + nr_mfns - 1, add); if ( ret ) { rcu_unlock_domain(d); break; } if ( add ) { printk(XENLOG_G_INFO "memory_map:add: dom%d gfn=%lx mfn=%lx nr=%lx\n", d->domain_id, gfn, mfn, nr_mfns); ret = iomem_permit_access(d, mfn, mfn + nr_mfns - 1); if ( !ret && paging_mode_translate(d) ) { for ( i = 0; !ret && i < nr_mfns; i++ ) if ( !set_mmio_p2m_entry(d, gfn + i, _mfn(mfn + i)) ) ret = -EIO; if ( ret ) { printk(XENLOG_G_WARNING "memory_map:fail: dom%d gfn=%lx mfn=%lx\n", d->domain_id, gfn + i, mfn + i); while ( i-- ) clear_mmio_p2m_entry(d, gfn + i); if ( iomem_deny_access(d, mfn, mfn + nr_mfns - 1) && IS_PRIV(current->domain) ) printk(XENLOG_ERR "memory_map: failed to deny dom%d access to [%lx,%lx]\n", d->domain_id, mfn, mfn + nr_mfns - 1); } } } else { printk(XENLOG_G_INFO "memory_map:remove: dom%d gfn=%lx mfn=%lx nr=%lx\n", d->domain_id, gfn, mfn, nr_mfns); if ( paging_mode_translate(d) ) for ( i = 0; i < nr_mfns; i++ ) add |= !clear_mmio_p2m_entry(d, gfn + i); ret = iomem_deny_access(d, mfn, mfn + nr_mfns - 1); if ( !ret && add ) ret = -EIO; if ( ret && IS_PRIV(current->domain) ) printk(XENLOG_ERR "memory_map: error %ld %s dom%d access to [%lx,%lx]\n", ret, add ? "removing" : "denying", d->domain_id, mfn, mfn + nr_mfns - 1); } rcu_unlock_domain(d); } break; case XEN_DOMCTL_ioport_mapping: { #define MAX_IOPORTS 0x10000 struct domain *d; struct hvm_iommu *hd; unsigned int fgp = domctl->u.ioport_mapping.first_gport; unsigned int fmp = domctl->u.ioport_mapping.first_mport; unsigned int np = domctl->u.ioport_mapping.nr_ports; unsigned int add = domctl->u.ioport_mapping.add_mapping; struct g2m_ioport *g2m_ioport; int found = 0; ret = -EINVAL; if ( ((fgp | fmp | (np - 1)) >= MAX_IOPORTS) || ((fgp + np) > MAX_IOPORTS) || ((fmp + np) > MAX_IOPORTS) ) { printk(XENLOG_G_ERR "ioport_map:invalid:dom%d gport=%x mport=%x nr=%x\n", domctl->domain, fgp, fmp, np); break; } ret = -EPERM; if ( !IS_PRIV(current->domain) && !ioports_access_permitted(current->domain, fmp, fmp + np - 1) ) break; ret = -ESRCH; if ( unlikely((d = rcu_lock_domain_by_id(domctl->domain)) == NULL) ) break; ret = xsm_ioport_permission(d, fmp, fmp + np - 1, add); if ( ret ) { rcu_unlock_domain(d); break; } hd = domain_hvm_iommu(d); if ( add ) { printk(XENLOG_G_INFO "ioport_map:add: dom%d gport=%x mport=%x nr=%x\n", d->domain_id, fgp, fmp, np); list_for_each_entry(g2m_ioport, &hd->g2m_ioport_list, list) if (g2m_ioport->mport == fmp ) { g2m_ioport->gport = fgp; g2m_ioport->np = np; found = 1; break; } if ( !found ) { g2m_ioport = xmalloc(struct g2m_ioport); if ( !g2m_ioport ) ret = -ENOMEM; } if ( !found && !ret ) { g2m_ioport->gport = fgp; g2m_ioport->mport = fmp; g2m_ioport->np = np; list_add_tail(&g2m_ioport->list, &hd->g2m_ioport_list); } if ( !ret ) ret = ioports_permit_access(d, fmp, fmp + np - 1); if ( ret && !found && g2m_ioport ) { list_del(&g2m_ioport->list); xfree(g2m_ioport); } } else { printk(XENLOG_G_INFO "ioport_map:remove: dom%d gport=%x mport=%x nr=%x\n", d->domain_id, fgp, fmp, np); list_for_each_entry(g2m_ioport, &hd->g2m_ioport_list, list) if ( g2m_ioport->mport == fmp ) { list_del(&g2m_ioport->list); xfree(g2m_ioport); break; } ret = ioports_deny_access(d, fmp, fmp + np - 1); if ( ret && IS_PRIV(current->domain) ) printk(XENLOG_ERR "ioport_map: error %ld denying dom%d access to [%x,%x]\n", ret, d->domain_id, fmp, fmp + np - 1); } rcu_unlock_domain(d); } break; case XEN_DOMCTL_pin_mem_cacheattr: { struct domain *d; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d == NULL ) break; ret = xsm_pin_mem_cacheattr(d); if ( ret ) goto pin_out; ret = hvm_set_mem_pinned_cacheattr( d, domctl->u.pin_mem_cacheattr.start, domctl->u.pin_mem_cacheattr.end, domctl->u.pin_mem_cacheattr.type); pin_out: rcu_unlock_domain(d); } break; case XEN_DOMCTL_set_ext_vcpucontext: case XEN_DOMCTL_get_ext_vcpucontext: { struct xen_domctl_ext_vcpucontext *evc; struct domain *d; struct vcpu *v; evc = &domctl->u.ext_vcpucontext; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d == NULL ) break; ret = xsm_ext_vcpucontext(d, domctl->cmd); if ( ret ) goto ext_vcpucontext_out; ret = -ESRCH; if ( (evc->vcpu >= d->max_vcpus) || ((v = d->vcpu[evc->vcpu]) == NULL) ) goto ext_vcpucontext_out; if ( domctl->cmd == XEN_DOMCTL_get_ext_vcpucontext ) { evc->size = sizeof(*evc); #ifdef __x86_64__ if ( !is_hvm_domain(d) ) { evc->sysenter_callback_cs = v->arch.pv_vcpu.sysenter_callback_cs; evc->sysenter_callback_eip = v->arch.pv_vcpu.sysenter_callback_eip; evc->sysenter_disables_events = v->arch.pv_vcpu.sysenter_disables_events; evc->syscall32_callback_cs = v->arch.pv_vcpu.syscall32_callback_cs; evc->syscall32_callback_eip = v->arch.pv_vcpu.syscall32_callback_eip; evc->syscall32_disables_events = v->arch.pv_vcpu.syscall32_disables_events; } else #endif { evc->sysenter_callback_cs = 0; evc->sysenter_callback_eip = 0; evc->sysenter_disables_events = 0; evc->syscall32_callback_cs = 0; evc->syscall32_callback_eip = 0; evc->syscall32_disables_events = 0; } evc->mcg_cap = v->arch.mcg_cap; } else { ret = -EINVAL; if ( evc->size < offsetof(typeof(*evc), mcg_cap) ) goto ext_vcpucontext_out; #ifdef __x86_64__ if ( !is_hvm_domain(d) ) { if ( !is_canonical_address(evc->sysenter_callback_eip) || !is_canonical_address(evc->syscall32_callback_eip) ) goto ext_vcpucontext_out; fixup_guest_code_selector(d, evc->sysenter_callback_cs); v->arch.pv_vcpu.sysenter_callback_cs = evc->sysenter_callback_cs; v->arch.pv_vcpu.sysenter_callback_eip = evc->sysenter_callback_eip; v->arch.pv_vcpu.sysenter_disables_events = evc->sysenter_disables_events; fixup_guest_code_selector(d, evc->syscall32_callback_cs); v->arch.pv_vcpu.syscall32_callback_cs = evc->syscall32_callback_cs; v->arch.pv_vcpu.syscall32_callback_eip = evc->syscall32_callback_eip; v->arch.pv_vcpu.syscall32_disables_events = evc->syscall32_disables_events; } else #endif /* We do not support syscall/syscall32/sysenter on 32-bit Xen. */ if ( (evc->sysenter_callback_cs & ~3) || evc->sysenter_callback_eip || (evc->syscall32_callback_cs & ~3) || evc->syscall32_callback_eip ) goto ext_vcpucontext_out; if ( evc->size >= offsetof(typeof(*evc), mcg_cap) + sizeof(evc->mcg_cap) ) ret = vmce_restore_vcpu(v, evc->mcg_cap); } ret = 0; ext_vcpucontext_out: rcu_unlock_domain(d); if ( (domctl->cmd == XEN_DOMCTL_get_ext_vcpucontext) && copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; } break; case XEN_DOMCTL_set_cpuid: { struct domain *d; xen_domctl_cpuid_t *ctl = &domctl->u.cpuid; cpuid_input_t *cpuid = NULL; int i; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d == NULL ) break; for ( i = 0; i < MAX_CPUID_INPUT; i++ ) { cpuid = &d->arch.cpuids[i]; if ( cpuid->input[0] == XEN_CPUID_INPUT_UNUSED ) break; if ( (cpuid->input[0] == ctl->input[0]) && ((cpuid->input[1] == XEN_CPUID_INPUT_UNUSED) || (cpuid->input[1] == ctl->input[1])) ) break; } if ( i == MAX_CPUID_INPUT ) { ret = -ENOENT; } else { //if(ctl->input[0] == 0x1 || ctl->input[0] == 0x80000001 || ctl->input[0] == 0xd || ctl->input[0] == 0x7) printk("=====XEN-BLANKET=====DOMCTL_set_cpuid input:leaf=0x%x, sub_leaf=0x%x, eax=0x%x, ebx=0x%x, ecx=0x%x, edx=0x%x\n", ctl->input[0], cpuid->input[1], ctl->eax, ctl->ebx, ctl->ecx, ctl->edx); if ( ctl->input[0] == 1 ) { ctl->ecx &= opt_cpuid_mask_ecx; ctl->edx &= opt_cpuid_mask_edx; } else if ( ctl->input[0] == 0x80000001 ) { ctl->ecx &= opt_cpuid_mask_ext_ecx; ctl->edx &= opt_cpuid_mask_ext_edx; } else if ( ctl->input[0] == 0xd && cpuid->input[1] == 0x1 ) ctl->eax &= opt_cpuid_mask_xsave_eax; else if (ctl->input[0] == 0xd || ctl->input[0] == 0x7) { ctl->eax = 0; ctl->ebx = 0; ctl->ecx = 0; ctl->edx = 0; } //if(ctl->input[0] == 0x1 || ctl->input[0] == 0x80000001 || ctl->input[0] == 0xd || ctl->input[0] == 0x7) printk("=====XEN-BLANKET=====DOMCTL_set_cpuid output:leaf=0x%x, sub_leaf=0x%x, eax=0x%x, ebx=0x%x, ecx=0x%x, edx=0x%x\n", ctl->input[0], cpuid->input[1], ctl->eax, ctl->ebx, ctl->ecx, ctl->edx); memcpy(cpuid, ctl, sizeof(cpuid_input_t)); ret = 0; } rcu_unlock_domain(d); } break; case XEN_DOMCTL_gettscinfo: { struct domain *d; xen_guest_tsc_info_t info; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d == NULL ) break; domain_pause(d); tsc_get_info(d, &info.tsc_mode, &info.elapsed_nsec, &info.gtsc_khz, &info.incarnation); if ( copy_to_guest(domctl->u.tsc_info.out_info, &info, 1) ) ret = -EFAULT; else ret = 0; domain_unpause(d); rcu_unlock_domain(d); } break; case XEN_DOMCTL_settscinfo: { struct domain *d; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d == NULL ) break; domain_pause(d); tsc_set_info(d, domctl->u.tsc_info.info.tsc_mode, domctl->u.tsc_info.info.elapsed_nsec, domctl->u.tsc_info.info.gtsc_khz, domctl->u.tsc_info.info.incarnation); domain_unpause(d); rcu_unlock_domain(d); ret = 0; } break; case XEN_DOMCTL_suppress_spurious_page_faults: { struct domain *d; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d != NULL ) { d->arch.suppress_spurious_page_faults = 1; rcu_unlock_domain(d); ret = 0; } } break; case XEN_DOMCTL_debug_op: { struct domain *d; struct vcpu *v; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d == NULL ) break; ret = -EINVAL; if ( (domctl->u.debug_op.vcpu >= d->max_vcpus) || ((v = d->vcpu[domctl->u.debug_op.vcpu]) == NULL) ) goto debug_op_out; ret = -EINVAL; if ( !is_hvm_domain(d)) goto debug_op_out; ret = hvm_debug_op(v, domctl->u.debug_op.op); debug_op_out: rcu_unlock_domain(d); } break; case XEN_DOMCTL_gdbsx_guestmemio: { struct domain *d; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; domctl->u.gdbsx_guest_memio.remain = domctl->u.gdbsx_guest_memio.len; ret = gdbsx_guest_mem_io(domctl->domain, &domctl->u.gdbsx_guest_memio); if ( !ret && copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; rcu_unlock_domain(d); } break; case XEN_DOMCTL_gdbsx_pausevcpu: { struct domain *d; struct vcpu *v; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = -EBUSY; if ( !d->is_paused_by_controller ) { rcu_unlock_domain(d); break; } ret = -EINVAL; if ( domctl->u.gdbsx_pauseunp_vcpu.vcpu >= MAX_VIRT_CPUS || (v = d->vcpu[domctl->u.gdbsx_pauseunp_vcpu.vcpu]) == NULL ) { rcu_unlock_domain(d); break; } vcpu_pause(v); ret = 0; rcu_unlock_domain(d); } break; case XEN_DOMCTL_gdbsx_unpausevcpu: { struct domain *d; struct vcpu *v; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; ret = -EBUSY; if ( !d->is_paused_by_controller ) { rcu_unlock_domain(d); break; } ret = -EINVAL; if ( domctl->u.gdbsx_pauseunp_vcpu.vcpu >= MAX_VIRT_CPUS || (v = d->vcpu[domctl->u.gdbsx_pauseunp_vcpu.vcpu]) == NULL ) { rcu_unlock_domain(d); break; } if ( !atomic_read(&v->pause_count) ) printk("WARN: Unpausing vcpu:%d which is not paused\n", v->vcpu_id); vcpu_unpause(v); ret = 0; rcu_unlock_domain(d); } break; case XEN_DOMCTL_gdbsx_domstatus: { struct domain *d; struct vcpu *v; ret = -ESRCH; if ( (d = rcu_lock_domain_by_id(domctl->domain)) == NULL ) break; domctl->u.gdbsx_domstatus.vcpu_id = -1; domctl->u.gdbsx_domstatus.paused = d->is_paused_by_controller; if ( domctl->u.gdbsx_domstatus.paused ) { for_each_vcpu ( d, v ) { if ( v->arch.gdbsx_vcpu_event ) { domctl->u.gdbsx_domstatus.vcpu_id = v->vcpu_id; domctl->u.gdbsx_domstatus.vcpu_ev = v->arch.gdbsx_vcpu_event; v->arch.gdbsx_vcpu_event = 0; break; } } } ret = 0; if ( copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; rcu_unlock_domain(d); } break; case XEN_DOMCTL_setvcpuextstate: case XEN_DOMCTL_getvcpuextstate: { struct xen_domctl_vcpuextstate *evc; struct domain *d; struct vcpu *v; uint32_t offset = 0; uint64_t _xfeature_mask = 0; uint64_t _xcr0, _xcr0_accum; void *receive_buf = NULL, *_xsave_area; #define PV_XSAVE_SIZE (2 * sizeof(uint64_t) + xsave_cntxt_size) evc = &domctl->u.vcpuextstate; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d == NULL ) break; ret = xsm_vcpuextstate(d, domctl->cmd); if ( ret ) goto vcpuextstate_out; ret = -ESRCH; if ( (evc->vcpu >= d->max_vcpus) || ((v = d->vcpu[evc->vcpu]) == NULL) ) goto vcpuextstate_out; if ( domctl->cmd == XEN_DOMCTL_getvcpuextstate ) { if ( !evc->size && !evc->xfeature_mask ) { //evc->xfeature_mask = xfeature_mask; //XEN-BLANKET if(d->domain_id == 0) evc->xfeature_mask = xfeature_mask; else evc->xfeature_mask = 0; evc->size = PV_XSAVE_SIZE; ret = 0; goto vcpuextstate_out; } if ( evc->size != PV_XSAVE_SIZE || evc->xfeature_mask != xfeature_mask ) { ret = -EINVAL; goto vcpuextstate_out; } if ( copy_to_guest_offset(domctl->u.vcpuextstate.buffer, offset, (void *)&v->arch.xcr0, sizeof(v->arch.xcr0)) ) { ret = -EFAULT; goto vcpuextstate_out; } offset += sizeof(v->arch.xcr0); if ( copy_to_guest_offset(domctl->u.vcpuextstate.buffer, offset, (void *)&v->arch.xcr0_accum, sizeof(v->arch.xcr0_accum)) ) { ret = -EFAULT; goto vcpuextstate_out; } offset += sizeof(v->arch.xcr0_accum); if ( copy_to_guest_offset(domctl->u.vcpuextstate.buffer, offset, (void *)v->arch.xsave_area, xsave_cntxt_size) ) { ret = -EFAULT; goto vcpuextstate_out; } } else { ret = -EINVAL; _xfeature_mask = evc->xfeature_mask; /* xsave context must be restored on compatible target CPUs */ if ( (_xfeature_mask & xfeature_mask) != _xfeature_mask ) goto vcpuextstate_out; if ( evc->size > PV_XSAVE_SIZE || evc->size < 2 * sizeof(uint64_t) ) goto vcpuextstate_out; receive_buf = xmalloc_bytes(evc->size); if ( !receive_buf ) { ret = -ENOMEM; goto vcpuextstate_out; } if ( copy_from_guest_offset(receive_buf, domctl->u.vcpuextstate.buffer, offset, evc->size) ) { ret = -EFAULT; xfree(receive_buf); goto vcpuextstate_out; } _xcr0 = *(uint64_t *)receive_buf; _xcr0_accum = *(uint64_t *)(receive_buf + sizeof(uint64_t)); _xsave_area = receive_buf + 2 * sizeof(uint64_t); if ( !(_xcr0 & XSTATE_FP) || _xcr0 & ~xfeature_mask ) { xfree(receive_buf); goto vcpuextstate_out; } if ( (_xcr0 & _xcr0_accum) != _xcr0 ) { xfree(receive_buf); goto vcpuextstate_out; } v->arch.xcr0 = _xcr0; v->arch.xcr0_accum = _xcr0_accum; memcpy(v->arch.xsave_area, _xsave_area, evc->size - 2 * sizeof(uint64_t) ); xfree(receive_buf); } ret = 0; vcpuextstate_out: rcu_unlock_domain(d); if ( (domctl->cmd == XEN_DOMCTL_getvcpuextstate) && copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; } break; #ifdef __x86_64__ case XEN_DOMCTL_mem_event_op: { struct domain *d; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d != NULL ) { ret = xsm_mem_event(d); if ( !ret ) ret = mem_event_domctl(d, &domctl->u.mem_event_op, guest_handle_cast(u_domctl, void)); rcu_unlock_domain(d); copy_to_guest(u_domctl, domctl, 1); } } break; case XEN_DOMCTL_mem_sharing_op: { struct domain *d; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d != NULL ) { ret = xsm_mem_sharing(d); if ( !ret ) ret = mem_sharing_domctl(d, &domctl->u.mem_sharing_op); rcu_unlock_domain(d); } } break; #endif /* __x86_64__ */ #if P2M_AUDIT case XEN_DOMCTL_audit_p2m: { struct domain *d; ret = rcu_lock_remote_target_domain_by_id(domctl->domain, &d); if ( ret != 0 ) break; audit_p2m(d, &domctl->u.audit_p2m.orphans, &domctl->u.audit_p2m.m2p_bad, &domctl->u.audit_p2m.p2m_bad); rcu_unlock_domain(d); if ( copy_to_guest(u_domctl, domctl, 1) ) ret = -EFAULT; } break; #endif /* P2M_AUDIT */ case XEN_DOMCTL_set_access_required: { struct domain *d; struct p2m_domain* p2m; ret = -EPERM; if ( current->domain->domain_id == domctl->domain ) break; ret = -ESRCH; d = rcu_lock_domain_by_id(domctl->domain); if ( d != NULL ) { ret = xsm_mem_event(d); if ( !ret ) { p2m = p2m_get_hostp2m(d); p2m->access_required = domctl->u.access_required.access_required; } rcu_unlock_domain(d); } } break; default: ret = iommu_do_domctl(domctl, u_domctl); break; } return ret; } #ifdef CONFIG_COMPAT #define xen_vcpu_guest_context vcpu_guest_context #define fpu_ctxt fpu_ctxt.x CHECK_FIELD_(struct, vcpu_guest_context, fpu_ctxt); #undef fpu_ctxt #undef xen_vcpu_guest_context #endif void arch_get_info_guest(struct vcpu *v, vcpu_guest_context_u c) { unsigned int i; bool_t compat = is_pv_32on64_domain(v->domain); #ifdef CONFIG_COMPAT #define c(fld) (!compat ? (c.nat->fld) : (c.cmp->fld)) #else #define c(fld) (c.nat->fld) #endif if ( is_hvm_vcpu(v) ) memset(c.nat, 0, sizeof(*c.nat)); memcpy(&c.nat->fpu_ctxt, v->arch.fpu_ctxt, sizeof(c.nat->fpu_ctxt)); c(flags = v->arch.vgc_flags & ~(VGCF_i387_valid|VGCF_in_kernel)); if ( v->fpu_initialised ) c(flags |= VGCF_i387_valid); if ( !test_bit(_VPF_down, &v->pause_flags) ) c(flags |= VGCF_online); if ( !compat ) { memcpy(&c.nat->user_regs, &v->arch.user_regs, sizeof(c.nat->user_regs)); if ( !is_hvm_vcpu(v) ) memcpy(c.nat->trap_ctxt, v->arch.pv_vcpu.trap_ctxt, sizeof(c.nat->trap_ctxt)); } #ifdef CONFIG_COMPAT else { XLAT_cpu_user_regs(&c.cmp->user_regs, &v->arch.user_regs); for ( i = 0; i < ARRAY_SIZE(c.cmp->trap_ctxt); ++i ) XLAT_trap_info(c.cmp->trap_ctxt + i, v->arch.pv_vcpu.trap_ctxt + i); } #endif for ( i = 0; i < ARRAY_SIZE(v->arch.debugreg); ++i ) c(debugreg[i] = v->arch.debugreg[i]); if ( is_hvm_vcpu(v) ) { struct segment_register sreg; c.nat->ctrlreg[0] = v->arch.hvm_vcpu.guest_cr[0]; c.nat->ctrlreg[2] = v->arch.hvm_vcpu.guest_cr[2]; c.nat->ctrlreg[3] = v->arch.hvm_vcpu.guest_cr[3]; c.nat->ctrlreg[4] = v->arch.hvm_vcpu.guest_cr[4]; hvm_get_segment_register(v, x86_seg_cs, &sreg); c.nat->user_regs.cs = sreg.sel; hvm_get_segment_register(v, x86_seg_ss, &sreg); c.nat->user_regs.ss = sreg.sel; hvm_get_segment_register(v, x86_seg_ds, &sreg); c.nat->user_regs.ds = sreg.sel; hvm_get_segment_register(v, x86_seg_es, &sreg); c.nat->user_regs.es = sreg.sel; hvm_get_segment_register(v, x86_seg_fs, &sreg); c.nat->user_regs.fs = sreg.sel; #ifdef __x86_64__ c.nat->fs_base = sreg.base; #endif hvm_get_segment_register(v, x86_seg_gs, &sreg); c.nat->user_regs.gs = sreg.sel; #ifdef __x86_64__ if ( ring_0(&c.nat->user_regs) ) { c.nat->gs_base_kernel = sreg.base; c.nat->gs_base_user = hvm_get_shadow_gs_base(v); } else { c.nat->gs_base_user = sreg.base; c.nat->gs_base_kernel = hvm_get_shadow_gs_base(v); } #endif } else { c(ldt_base = v->arch.pv_vcpu.ldt_base); c(ldt_ents = v->arch.pv_vcpu.ldt_ents); for ( i = 0; i < ARRAY_SIZE(v->arch.pv_vcpu.gdt_frames); ++i ) c(gdt_frames[i] = v->arch.pv_vcpu.gdt_frames[i]); #ifdef CONFIG_COMPAT BUILD_BUG_ON(ARRAY_SIZE(c.nat->gdt_frames) != ARRAY_SIZE(c.cmp->gdt_frames)); #endif for ( ; i < ARRAY_SIZE(c.nat->gdt_frames); ++i ) c(gdt_frames[i] = 0); c(gdt_ents = v->arch.pv_vcpu.gdt_ents); c(kernel_ss = v->arch.pv_vcpu.kernel_ss); c(kernel_sp = v->arch.pv_vcpu.kernel_sp); for ( i = 0; i < ARRAY_SIZE(v->arch.pv_vcpu.ctrlreg); ++i ) c(ctrlreg[i] = v->arch.pv_vcpu.ctrlreg[i]); c(event_callback_eip = v->arch.pv_vcpu.event_callback_eip); c(failsafe_callback_eip = v->arch.pv_vcpu.failsafe_callback_eip); #ifdef CONFIG_X86_64 if ( !compat ) { c.nat->syscall_callback_eip = v->arch.pv_vcpu.syscall_callback_eip; c.nat->fs_base = v->arch.pv_vcpu.fs_base; c.nat->gs_base_kernel = v->arch.pv_vcpu.gs_base_kernel; c.nat->gs_base_user = v->arch.pv_vcpu.gs_base_user; } else #endif { c(event_callback_cs = v->arch.pv_vcpu.event_callback_cs); c(failsafe_callback_cs = v->arch.pv_vcpu.failsafe_callback_cs); } c(vm_assist = v->arch.pv_vcpu.vm_assist); /* IOPL privileges are virtualised: merge back into returned eflags. */ BUG_ON((c(user_regs.eflags) & X86_EFLAGS_IOPL) != 0); c(user_regs.eflags |= v->arch.pv_vcpu.iopl << 12); if ( !is_pv_32on64_domain(v->domain) ) { c.nat->ctrlreg[3] = xen_pfn_to_cr3( pagetable_get_pfn(v->arch.guest_table)); #ifdef __x86_64__ c.nat->ctrlreg[1] = pagetable_is_null(v->arch.guest_table_user) ? 0 : xen_pfn_to_cr3(pagetable_get_pfn(v->arch.guest_table_user)); #endif /* Merge shadow DR7 bits into real DR7. */ c.nat->debugreg[7] |= c.nat->debugreg[5]; c.nat->debugreg[5] = 0; } #ifdef CONFIG_COMPAT else { l4_pgentry_t *l4e = __va(pagetable_get_paddr(v->arch.guest_table)); c.cmp->ctrlreg[3] = compat_pfn_to_cr3(l4e_get_pfn(*l4e)); /* Merge shadow DR7 bits into real DR7. */ c.cmp->debugreg[7] |= c.cmp->debugreg[5]; c.cmp->debugreg[5] = 0; } #endif if ( guest_kernel_mode(v, &v->arch.user_regs) ) c(flags |= VGCF_in_kernel); } c(vm_assist = v->domain->vm_assist); #undef c } /* * Local variables: * mode: C * c-set-style: "BSD" * c-basic-offset: 4 * tab-width: 4 * indent-tabs-mode: nil * End: */
29.061972
211
0.488495
e74c6914de7097dc15b3357fedf4c82de2a64165
1,149
h
C
libacars/asn1/FANSAltitudeQFEMeters.h
srcejon/libacars
3ee9e54275ea7c32c133ca936b9f96d1e452b74a
[ "MIT" ]
63
2018-11-29T18:44:03.000Z
2022-03-26T01:32:37.000Z
libacars/asn1/FANSAltitudeQFEMeters.h
srcejon/libacars
3ee9e54275ea7c32c133ca936b9f96d1e452b74a
[ "MIT" ]
15
2018-11-29T18:55:40.000Z
2022-01-06T13:33:44.000Z
libacars/asn1/FANSAltitudeQFEMeters.h
srcejon/libacars
3ee9e54275ea7c32c133ca936b9f96d1e452b74a
[ "MIT" ]
8
2018-12-02T16:04:38.000Z
2021-10-12T15:09:24.000Z
/* * Generated by asn1c-0.9.28 (http://lionet.info/asn1c) * From ASN.1 module "FANSACTwoWayDataLinkCommunications" * found in "../../../libacars.asn1/fans-cpdlc.asn1" * `asn1c -fcompound-names -fincludes-quoted -gen-PER` */ #ifndef _FANSAltitudeQFEMeters_H_ #define _FANSAltitudeQFEMeters_H_ #include "asn_application.h" /* Including external dependencies */ #include "NativeInteger.h" #ifdef __cplusplus extern "C" { #endif /* FANSAltitudeQFEMeters */ typedef long FANSAltitudeQFEMeters_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_FANSAltitudeQFEMeters; asn_struct_free_f FANSAltitudeQFEMeters_free; asn_struct_print_f FANSAltitudeQFEMeters_print; asn_constr_check_f FANSAltitudeQFEMeters_constraint; ber_type_decoder_f FANSAltitudeQFEMeters_decode_ber; der_type_encoder_f FANSAltitudeQFEMeters_encode_der; xer_type_decoder_f FANSAltitudeQFEMeters_decode_xer; xer_type_encoder_f FANSAltitudeQFEMeters_encode_xer; per_type_decoder_f FANSAltitudeQFEMeters_decode_uper; per_type_encoder_f FANSAltitudeQFEMeters_encode_uper; #ifdef __cplusplus } #endif #endif /* _FANSAltitudeQFEMeters_H_ */ #include "asn_internal.h"
27.357143
59
0.833768
2e721d01934824fb976a36a2a15434366d6c61e0
254
h
C
source/measurementMethods/measurementMethods.h
hhucn/rmf
aca9e05ed5c62179bfa0e0e74ff1ea76c52f94a2
[ "MIT" ]
null
null
null
source/measurementMethods/measurementMethods.h
hhucn/rmf
aca9e05ed5c62179bfa0e0e74ff1ea76c52f94a2
[ "MIT" ]
null
null
null
source/measurementMethods/measurementMethods.h
hhucn/rmf
aca9e05ed5c62179bfa0e0e74ff1ea76c52f94a2
[ "MIT" ]
null
null
null
/* * File: measurementMethods.h * Author: goebel * * Created on 26. März 2015, 11:05 */ #ifndef MEASUREMENTMETHODS_H #define MEASUREMENTMETHODS_H #include "measurementMethodClass.h" #include "measureTBUS.h" #endif /* MEASUREMENTMETHODS_H */
14.941176
35
0.724409
2ea65743665e71b96377334b58a64c599e1e196c
11,801
h
C
tools/clang/unittests/HLSL/HlslTestUtils.h
python3kgae/DirectXShaderCompiler
6df7438d70be97669f13f584227401ef46d224bf
[ "NCSA" ]
null
null
null
tools/clang/unittests/HLSL/HlslTestUtils.h
python3kgae/DirectXShaderCompiler
6df7438d70be97669f13f584227401ef46d224bf
[ "NCSA" ]
null
null
null
tools/clang/unittests/HLSL/HlslTestUtils.h
python3kgae/DirectXShaderCompiler
6df7438d70be97669f13f584227401ef46d224bf
[ "NCSA" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // // HlslTestUtils.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Provides utility functions for HLSL tests. // // // /////////////////////////////////////////////////////////////////////////////// #include <string> #include <sstream> #include <fstream> #include "dxc/Support/Unicode.h" #include <dxgiformat.h> // If TAEF verify macros are available, use them to alias other legacy // comparison macros that don't have a direct translation. // // Other common replacements are as follows. // // EXPECT_EQ -> VERIFY_ARE_EQUAL // ASSERT_EQ -> VERIFY_ARE_EQUAL // // Note that whether verification throws or continues depends on // preprocessor settings. #ifdef VERIFY_ARE_EQUAL #define EXPECT_STREQ(a, b) VERIFY_ARE_EQUAL(0, strcmp(a, b)) #define EXPECT_STREQW(a, b) VERIFY_ARE_EQUAL(0, wcscmp(a, b)) #define VERIFY_ARE_EQUAL_CMP(a, b, ...) VERIFY_IS_TRUE(a == b, __VA_ARGS__) #define VERIFY_ARE_EQUAL_STR(a, b, ...) { \ const char *pTmpA = (a);\ const char *pTmpB = (b);\ if (0 != strcmp(pTmpA, pTmpB)) {\ CA2W conv(pTmpB, CP_UTF8); WEX::Logging::Log::Comment(conv);\ const char *pA = pTmpA; const char *pB = pTmpB; \ while(*pA == *pB) { pA++; pB++; } \ wchar_t diffMsg[32]; swprintf_s(diffMsg, _countof(diffMsg), L"diff at %u", (unsigned)(pA-pTmpA)); \ WEX::Logging::Log::Comment(diffMsg); \ } \ VERIFY_ARE_EQUAL(0, strcmp(pTmpA, pTmpB), __VA_ARGS__); \ } #define VERIFY_ARE_EQUAL_WSTR(a, b, ...) { \ if (0 != wcscmp(a, b)) { WEX::Logging::Log::Comment(b);} \ VERIFY_ARE_EQUAL(0, wcscmp(a, b), __VA_ARGS__); \ } #define ASSERT_EQ(expected, actual) VERIFY_ARE_EQUAL(expected, actual) #define ASSERT_NE(expected, actual) VERIFY_ARE_NOT_EQUAL(expected, actual) #define TEST_F(typeName, functionName) void typeName::functionName() #define ASSERT_HRESULT_SUCCEEDED VERIFY_SUCCEEDED #define EXPECT_EQ(expected, actual) VERIFY_ARE_EQUAL(expected, actual) #endif namespace hlsl_test { inline std::wstring vFormatToWString(_In_z_ _Printf_format_string_ const wchar_t *fmt, va_list argptr) { std::wstring result; int len = _vscwprintf(fmt, argptr); result.resize(len + 1); vswprintf_s((wchar_t *)result.data(), len + 1, fmt, argptr); return result; } inline std::wstring FormatToWString(_In_z_ _Printf_format_string_ const wchar_t *fmt, ...) { va_list args; va_start(args, fmt); std::wstring result(vFormatToWString(fmt, args)); va_end(args); return result; } inline void LogCommentFmt(_In_z_ _Printf_format_string_ const wchar_t *fmt, ...) { va_list args; va_start(args, fmt); std::wstring buf(vFormatToWString(fmt, args)); va_end(args); WEX::Logging::Log::Comment(buf.data()); } inline void LogErrorFmt(_In_z_ _Printf_format_string_ const wchar_t *fmt, ...) { va_list args; va_start(args, fmt); std::wstring buf(vFormatToWString(fmt, args)); va_end(args); WEX::Logging::Log::Error(buf.data()); } inline std::wstring GetPathToHlslDataFile(const wchar_t* relative) { WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures); WEX::Common::String HlslDataDirValue; ASSERT_HRESULT_SUCCEEDED(WEX::TestExecution::RuntimeParameters::TryGetValue(L"HlslDataDir", HlslDataDirValue)); wchar_t envPath[MAX_PATH]; wchar_t expanded[MAX_PATH]; swprintf_s(envPath, _countof(envPath), L"%s\\%s", reinterpret_cast<wchar_t*>(HlslDataDirValue.GetBuffer()), relative); VERIFY_WIN32_BOOL_SUCCEEDED(ExpandEnvironmentStringsW(envPath, expanded, _countof(expanded))); return std::wstring(expanded); } inline bool PathLooksAbsolute(LPCWSTR name) { // Very simplified, only for the cases we care about in the test suite. return name && *name && ((*name == L'\\') || (name[1] == L':')); } inline std::string GetFirstLine(LPCWSTR name) { char firstLine[300]; memset(firstLine, 0, sizeof(firstLine)); const std::wstring path = PathLooksAbsolute(name) ? std::wstring(name) : hlsl_test::GetPathToHlslDataFile(name); std::ifstream infile(path); if (infile.bad()) { std::wstring errMsg(L"Unable to read file "); errMsg += path; WEX::Logging::Log::Error(errMsg.c_str()); VERIFY_FAIL(); } infile.getline(firstLine, _countof(firstLine)); return firstLine; } inline HANDLE CreateFileForReading(LPCWSTR path) { HANDLE sourceHandle = CreateFileW(path, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (sourceHandle == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); std::wstring errorMessage(FormatToWString(L"Unable to open file '%s', err=%u", path, err).c_str()); VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(err), errorMessage.c_str()); } return sourceHandle; } inline HANDLE CreateNewFileForReadWrite(LPCWSTR path) { HANDLE sourceHandle = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); if (sourceHandle == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); std::wstring errorMessage(FormatToWString(L"Unable to create file '%s', err=%u", path, err).c_str()); VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(err), errorMessage.c_str()); } return sourceHandle; } inline bool GetTestParamBool(LPCWSTR name) { WEX::Common::String ParamValue; WEX::Common::String NameValue; if (FAILED(WEX::TestExecution::RuntimeParameters::TryGetValue(name, ParamValue))) { return false; } if (ParamValue.IsEmpty()) { return false; } if (0 == wcscmp(ParamValue, L"*")) { return true; } VERIFY_SUCCEEDED(WEX::TestExecution::RuntimeParameters::TryGetValue( L"TestName", NameValue)); if (NameValue.IsEmpty()) { return false; } return Unicode::IsStarMatchUTF16(ParamValue, ParamValue.GetLength(), NameValue, NameValue.GetLength()); } inline bool GetTestParamUseWARP(bool defaultVal) { WEX::Common::String AdapterValue; if (FAILED(WEX::TestExecution::RuntimeParameters::TryGetValue( L"Adapter", AdapterValue))) { return defaultVal; } if (defaultVal && AdapterValue.IsEmpty() || AdapterValue.CompareNoCase(L"WARP") == 0) { return true; } return false; } } inline bool CompareFloatULP(const float &fsrc, const float &fref, int ULPTolerance) { if (isnan(fsrc)) { return isnan(fref); } if (fsrc == fref) { return true; } int diff = *((DWORD *)&fsrc) - *((DWORD *)&fref); unsigned int uDiff = diff < 0 ? -diff : diff; return uDiff <= (unsigned int)ULPTolerance; } inline bool CompareFloatEpsilon(const float &fsrc, const float &fref, float epsilon) { if (isnan(fsrc)) { return isnan(fref); } return fsrc == fref || fabsf(fsrc - fref) < epsilon; } // Compare using relative error (relative error < 2^{nRelativeExp}) inline bool CompareFloatRelativeEpsilon(const float &fsrc, const float &fref, int nRelativeExp) { return CompareFloatULP(fsrc, fref, 23 - nRelativeExp); } // returns the number of bytes per pixel for a given dxgi format // add more cases if different format needed to copy back resources inline UINT GetByteSizeForFormat(DXGI_FORMAT value) { switch (value) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return 16; case DXGI_FORMAT_R32G32B32A32_FLOAT: return 16; case DXGI_FORMAT_R32G32B32A32_UINT: return 16; case DXGI_FORMAT_R32G32B32A32_SINT: return 16; case DXGI_FORMAT_R32G32B32_TYPELESS: return 12; case DXGI_FORMAT_R32G32B32_FLOAT: return 12; case DXGI_FORMAT_R32G32B32_UINT: return 12; case DXGI_FORMAT_R32G32B32_SINT: return 12; case DXGI_FORMAT_R16G16B16A16_TYPELESS: return 8; case DXGI_FORMAT_R16G16B16A16_FLOAT: return 8; case DXGI_FORMAT_R16G16B16A16_UNORM: return 8; case DXGI_FORMAT_R16G16B16A16_UINT: return 8; case DXGI_FORMAT_R16G16B16A16_SNORM: return 8; case DXGI_FORMAT_R16G16B16A16_SINT: return 8; case DXGI_FORMAT_R32G32_TYPELESS: return 8; case DXGI_FORMAT_R32G32_FLOAT: return 8; case DXGI_FORMAT_R32G32_UINT: return 8; case DXGI_FORMAT_R32G32_SINT: return 8; case DXGI_FORMAT_R32G8X24_TYPELESS: return 8; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return 4; case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: return 4; case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: return 4; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return 4; case DXGI_FORMAT_R10G10B10A2_UNORM: return 4; case DXGI_FORMAT_R10G10B10A2_UINT: return 4; case DXGI_FORMAT_R11G11B10_FLOAT: return 4; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return 4; case DXGI_FORMAT_R8G8B8A8_UNORM: return 4; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return 4; case DXGI_FORMAT_R8G8B8A8_UINT: return 4; case DXGI_FORMAT_R8G8B8A8_SNORM: return 4; case DXGI_FORMAT_R8G8B8A8_SINT: return 4; case DXGI_FORMAT_R16G16_TYPELESS: return 4; case DXGI_FORMAT_R16G16_FLOAT: return 4; case DXGI_FORMAT_R16G16_UNORM: return 4; case DXGI_FORMAT_R16G16_UINT: return 4; case DXGI_FORMAT_R16G16_SNORM: return 4; case DXGI_FORMAT_R16G16_SINT: return 4; case DXGI_FORMAT_R32_TYPELESS: return 4; case DXGI_FORMAT_D32_FLOAT: return 4; case DXGI_FORMAT_R32_FLOAT: return 4; case DXGI_FORMAT_R32_UINT: return 4; case DXGI_FORMAT_R32_SINT: return 4; case DXGI_FORMAT_R24G8_TYPELESS: return 4; case DXGI_FORMAT_D24_UNORM_S8_UINT: return 4; case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return 4; case DXGI_FORMAT_X24_TYPELESS_G8_UINT: return 4; case DXGI_FORMAT_R8G8_TYPELESS: return 2; case DXGI_FORMAT_R8G8_UNORM: return 2; case DXGI_FORMAT_R8G8_UINT: return 2; case DXGI_FORMAT_R8G8_SNORM: return 2; case DXGI_FORMAT_R8G8_SINT: return 2; case DXGI_FORMAT_R16_TYPELESS: return 2; case DXGI_FORMAT_R16_FLOAT: return 2; case DXGI_FORMAT_D16_UNORM: return 2; case DXGI_FORMAT_R16_UNORM: return 2; case DXGI_FORMAT_R16_UINT: return 2; case DXGI_FORMAT_R16_SNORM: return 2; case DXGI_FORMAT_R16_SINT: return 2; case DXGI_FORMAT_R8_TYPELESS: return 1; case DXGI_FORMAT_R8_UNORM: return 1; case DXGI_FORMAT_R8_UINT: return 1; case DXGI_FORMAT_R8_SNORM: return 1; case DXGI_FORMAT_R8_SINT: return 1; case DXGI_FORMAT_A8_UNORM: return 1; case DXGI_FORMAT_R1_UNORM: return 1; default: VERIFY_FAILED(E_INVALIDARG); return 0; } } #define SIMPLE_IUNKNOWN_IMPL1(_IFACE_) \ private: volatile ULONG m_dwRef; \ public:\ ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&m_dwRef); } \ ULONG STDMETHODCALLTYPE Release() { \ ULONG result = InterlockedDecrement(&m_dwRef); \ if (result == 0) delete this; \ return result; \ } \ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** ppvObject) { \ if (ppvObject == nullptr) return E_POINTER; \ if (IsEqualIID(iid, __uuidof(IUnknown)) || \ IsEqualIID(iid, __uuidof(INoMarshal)) || \ IsEqualIID(iid, __uuidof(_IFACE_))) { \ *ppvObject = reinterpret_cast<_IFACE_*>(this); \ reinterpret_cast<_IFACE_*>(this)->AddRef(); \ return S_OK; \ } \ return E_NOINTERFACE; \ }
38.439739
120
0.677061
2ee000382d653118ea5cbf43db852e8dbedded24
700
h
C
RRRMethod/FooterView/UICollectionView+FooterView.h
RRRenJ/RRRMethod
2f7df3d126a418edf3a3a615e95fea25d1be8590
[ "MIT" ]
null
null
null
RRRMethod/FooterView/UICollectionView+FooterView.h
RRRenJ/RRRMethod
2f7df3d126a418edf3a3a615e95fea25d1be8590
[ "MIT" ]
null
null
null
RRRMethod/FooterView/UICollectionView+FooterView.h
RRRenJ/RRRMethod
2f7df3d126a418edf3a3a615e95fea25d1be8590
[ "MIT" ]
null
null
null
// // UICollectionView+FooterView.h // RRRMethodDemo // // Created by 任敬 on 2019/8/2. // Copyright © 2019 任敬. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UICollectionView (FooterView) - (void)footerViewWithEmptyView; - (void)footerViewWithImageName:(NSString *)imageName andFrame:(CGRect)frame andY:(CGFloat)y; - (void)footerViewWithString:(NSString *)string andFrame:(CGRect)frame andY:(CGFloat)y; - (void)footerViewWithImageName:(NSString *)imageName andImageFrame:(CGRect)imageFrame andString:(NSString *)string andStringFrame:(CGRect)stringFrame andY:(CGFloat)y; - (void)footerViewWithCustomView:(UIView *)customView; @end NS_ASSUME_NONNULL_END
26.923077
167
0.777143
c899d9f83c9e64868a15c04e043dc5770b904ae4
51,747
c
C
code/libbluray/player_wrappers/xine/input_bluray.c
timkingh/FFmpeg_VS
993b14dc146731d782cf4b5fffc6a0f4b9aeea0c
[ "MIT" ]
2
2019-11-17T14:01:21.000Z
2019-12-24T14:29:45.000Z
code/libbluray/player_wrappers/xine/input_bluray.c
timkingh/FFmpeg_VS
993b14dc146731d782cf4b5fffc6a0f4b9aeea0c
[ "MIT" ]
null
null
null
code/libbluray/player_wrappers/xine/input_bluray.c
timkingh/FFmpeg_VS
993b14dc146731d782cf4b5fffc6a0f4b9aeea0c
[ "MIT" ]
3
2019-08-28T14:37:01.000Z
2020-06-17T16:46:32.000Z
/* * Copyright (C) 2000-2005 the xine project * * Copyright (C) 2009-2013 Petri Hintukainen <phintuka@users.sourceforge.net> * * This file is part of xine, a free video player. * * xine is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * xine 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, USA * * Input plugin for BluRay discs / images * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <pthread.h> /* libbluray */ #include <libbluray/bluray.h> #include <libbluray/bluray-version.h> #include <libbluray/keys.h> #include <libbluray/overlay.h> #include <libbluray/meta_data.h> /* xine */ #define LOG_MODULE "input_bluray" #define LOG_VERBOSE #define LOG #define LOGMSG(x...) xine_log (this->stream->xine, XINE_LOG_MSG, "input_bluray: " x); #define XINE_ENGINE_INTERNAL // stream->demux_plugin #ifdef HAVE_CONFIG_H # include "xine_internal.h" # include "input_plugin.h" #else # include <xine/xine_internal.h> # include <xine/input_plugin.h> #endif #ifndef XINE_VERSION_CODE # error XINE_VERSION_CODE undefined ! #endif #ifndef EXPORTED # define EXPORTED __attribute__((visibility("default"))) #endif #ifndef MIN # define MIN(a,b) ((a)<(b)?(a):(b)) #endif #ifndef MAX # define MAX(a,b) ((a)>(b)?(a):(b)) #endif #define ALIGNED_UNIT_SIZE 6144 #define PKT_SIZE 192 #define TICKS_IN_MS 45 #define MIN_TITLE_LENGTH 180 typedef struct { input_class_t input_class; xine_t *xine; /* config */ char *mountpoint; char *language; char *country; int region; int parental; } bluray_input_class_t; typedef struct { BD_ARGB_BUFFER buf; pthread_mutex_t buf_lock; } XINE_BD_ARGB_BUFFER; static void osd_buf_lock(BD_ARGB_BUFFER *buf_gen) { XINE_BD_ARGB_BUFFER *buf = (XINE_BD_ARGB_BUFFER*)buf_gen; pthread_mutex_lock(&buf->buf_lock); } static void osd_buf_unlock(BD_ARGB_BUFFER *buf_gen) { XINE_BD_ARGB_BUFFER *buf = (XINE_BD_ARGB_BUFFER*)buf_gen; pthread_mutex_unlock(&buf->buf_lock); } static void osd_buf_init(XINE_BD_ARGB_BUFFER *buf) { buf->buf.lock = osd_buf_lock; buf->buf.unlock = osd_buf_unlock; pthread_mutex_init(&buf->buf_lock, NULL); } static void osd_buf_destroy(XINE_BD_ARGB_BUFFER *buf) { if (buf->buf.lock) { buf->buf.lock = NULL; buf->buf.unlock = NULL; pthread_mutex_destroy(&buf->buf_lock); } } typedef struct { input_plugin_t input_plugin; xine_stream_t *stream; xine_event_queue_t *event_queue; xine_osd_t *osd[2]; XINE_BD_ARGB_BUFFER osd_buf; bluray_input_class_t *class; char *mrl; char *disc_root; char *disc_name; BLURAY *bdh; const BLURAY_DISC_INFO *disc_info; const META_DL *meta_dl; /* disc library meta data */ int num_title_idx; /* number of relevant playlists */ int current_title_idx; int num_titles; /* navigation mode, number of titles in disc index */ int current_title; /* navigation mode, title from disc index */ BLURAY_TITLE_INFO *title_info; pthread_mutex_t title_info_mutex; /* lock this when accessing title_info outside of input/demux thread */ unsigned int current_clip; time_t still_end_time; int pg_stream; uint8_t nav_mode : 1; uint8_t error : 1; uint8_t menu_open : 1; uint8_t stream_flushed : 1; uint8_t demux_action_req : 1; uint8_t end_of_title : 1; uint8_t pg_enable : 1; uint8_t has_video : 1; int mouse_inside_button; } bluray_input_plugin_t; /* * overlay */ #define PALETTE_INDEX_BACKGROUND 0xff static void send_num_buttons(bluray_input_plugin_t *this, int n) { xine_event_t event; xine_ui_data_t data; event.type = XINE_EVENT_UI_NUM_BUTTONS; event.data = &data; event.data_length = sizeof(data); data.num_buttons = n; xine_event_send(this->stream, &event); } static void clear_overlay(xine_osd_t *osd) { /* palette entry 0xff is background --> can't use xine_osd_clear(). */ memset(osd->osd.area, PALETTE_INDEX_BACKGROUND, osd->osd.width * osd->osd.height); osd->osd.x1 = osd->osd.width; osd->osd.y1 = osd->osd.height; osd->osd.x2 = 0; osd->osd.y2 = 0; osd->osd.area_touched = 0; } static void close_overlay(bluray_input_plugin_t *this, int plane) { if (plane < 0) { close_overlay(this, 0); close_overlay(this, 1); return; } if (plane < 2 && this->osd[plane]) { xine_osd_free(this->osd[plane]); this->osd[plane] = NULL; free(this->osd_buf.buf.buf[plane]); this->osd_buf.buf.buf[plane] = NULL; } } static void open_overlay(bluray_input_plugin_t *this, int plane, uint16_t x, uint16_t y, uint16_t w, uint16_t h) { if (this->osd[plane]) { close_overlay(this, plane); } this->osd[plane] = xine_osd_new(this->stream, x, y, w, h); if (xine_osd_get_capabilities(this->osd[plane]) & XINE_OSD_CAP_ARGB_LAYER) { this->osd_buf.buf.width = w; this->osd_buf.buf.height = h; this->osd_buf.buf.buf[plane] = calloc(sizeof(uint32_t), w * h); } clear_overlay(this->osd[plane]); } static xine_osd_t *get_overlay(bluray_input_plugin_t *this, int plane) { if (!this->osd[plane]) { open_overlay(this, plane, 0, 0, 1920, 1080); } if (!this->pg_enable) { _x_select_spu_channel(this->stream, -1); } this->stream->video_out->enable_ovl(this->stream->video_out, 1); return this->osd[plane]; } static void draw_bitmap(xine_osd_t *osd, const BD_OVERLAY * const ov) { unsigned i; /* convert and set palette */ if (ov->palette) { uint32_t color[256]; uint8_t trans[256]; for(i = 0; i < 256; i++) { trans[i] = ov->palette[i].T; color[i] = (ov->palette[i].Y << 16) | (ov->palette[i].Cr << 8) | ov->palette[i].Cb; } xine_osd_set_palette(osd, color, trans); } /* uncompress and draw bitmap */ if (ov->img) { const BD_PG_RLE_ELEM *rlep = ov->img; uint8_t *img = malloc(ov->w * ov->h); unsigned pixels = ov->w * ov->h; for (i = 0; i < pixels; i += rlep->len, rlep++) { memset(img + i, rlep->color, rlep->len); } xine_osd_draw_bitmap(osd, img, ov->x, ov->y, ov->w, ov->h, NULL); free(img); } } static void overlay_proc(void *this_gen, const BD_OVERLAY * const ov) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; xine_osd_t *osd; int64_t vpts; if (!this) { return; } if (!ov) { /* hide OSD */ close_overlay(this, -1); return; } if (ov->plane > 1) { return; } switch (ov->cmd) { case BD_OVERLAY_INIT: /* init overlay plane. Size of full plane in x,y,w,h */ open_overlay(this, ov->plane, ov->x, ov->y, ov->w, ov->h); return; case BD_OVERLAY_CLOSE: /* close overlay */ close_overlay(this, ov->plane); return; } osd = get_overlay(this, ov->plane); vpts = 0; if (ov->pts > 0) { vpts = this->stream->metronom->got_spu_packet (this->stream->metronom, ov->pts); } switch (ov->cmd) { case BD_OVERLAY_DRAW: /* draw bitmap (x,y,w,h,img,palette) */ draw_bitmap(osd, ov); return; case BD_OVERLAY_WIPE: /* clear area (x,y,w,h) */ xine_osd_draw_rect(osd, ov->x, ov->y, ov->x + ov->w - 1, ov->y + ov->h - 1, PALETTE_INDEX_BACKGROUND, 1); return; case BD_OVERLAY_CLEAR: /* clear plane */ clear_overlay(osd); return; case BD_OVERLAY_HIDE: osd->osd.area_touched = 0; /* will be hiden at next commit time */ break; case BD_OVERLAY_FLUSH: /* all changes have been done, flush overlay to display at given pts */ if (!osd->osd.area_touched) { xine_osd_hide(osd, vpts); } else { xine_osd_show(osd, vpts); } return; default: LOGMSG("unknown overlay command %d", ov->cmd); return; } } static void argb_overlay_proc(void *this_gen, const BD_ARGB_OVERLAY * const ov) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; xine_osd_t *osd; int64_t vpts; if (!this) { return; } if (!ov) { /* hide OSD */ close_overlay(this, -1); return; } vpts = 0; if (ov->pts > 0) { vpts = this->stream->metronom->got_spu_packet (this->stream->metronom, ov->pts); } switch (ov->cmd) { case BD_ARGB_OVERLAY_INIT: open_overlay(this, ov->plane, 0, 0, ov->w, ov->h); return; case BD_ARGB_OVERLAY_CLOSE: close_overlay(this, ov->plane); return; case BD_ARGB_OVERLAY_DRAW: /* nothing to do */ return; case BD_ARGB_OVERLAY_FLUSH: osd = get_overlay(this, ov->plane); xine_osd_set_argb_buffer(osd, this->osd_buf.buf.buf[ov->plane], this->osd_buf.buf.dirty[ov->plane].x0, this->osd_buf.buf.dirty[ov->plane].y0, this->osd_buf.buf.dirty[ov->plane].x1 - this->osd_buf.buf.dirty[ov->plane].x0 + 1, this->osd_buf.buf.dirty[ov->plane].y1 - this->osd_buf.buf.dirty[ov->plane].y0 + 1); xine_osd_show(osd, vpts); return; default: lprintf("unknown ARGB overlay command %d\n", ov->cmd); return; } } /* * stream info */ static void update_stream_info(bluray_input_plugin_t *this) { if (this->title_info) { /* set stream info */ _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_ANGLE_COUNT, this->title_info->angle_count); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_ANGLE_NUMBER, bd_get_current_angle(this->bdh)); _x_stream_info_set(this->stream, XINE_STREAM_INFO_HAS_CHAPTERS, this->title_info->chapter_count > 0); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_CHAPTER_COUNT, this->title_info->chapter_count); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_CHAPTER_NUMBER, bd_get_current_chapter(this->bdh) + 1); } } static void update_title_name(bluray_input_plugin_t *this) { char title_name[64] = ""; xine_ui_data_t udata; xine_event_t uevent = { .type = XINE_EVENT_UI_SET_TITLE, .stream = this->stream, .data = &udata, .data_length = sizeof(udata) }; /* check disc library metadata */ if (this->meta_dl) { unsigned i; for (i = 0; i < this->meta_dl->toc_count; i++) if (this->meta_dl->toc_entries[i].title_number == (unsigned)this->current_title) if (this->meta_dl->toc_entries[i].title_name) if (strlen(this->meta_dl->toc_entries[i].title_name) > 2) strncpy(title_name, this->meta_dl->toc_entries[i].title_name, sizeof(title_name)); } /* title name */ if (title_name[0]) { } else if (this->current_title == BLURAY_TITLE_TOP_MENU) { strcpy(title_name, "Top Menu"); } else if (this->current_title == BLURAY_TITLE_FIRST_PLAY) { strcpy(title_name, "First Play"); } else if (this->nav_mode) { snprintf(title_name, sizeof(title_name), "Title %d/%d (PL %d/%d)", this->current_title, this->num_titles, this->current_title_idx + 1, this->num_title_idx); } else { snprintf(title_name, sizeof(title_name), "Title %d/%d", this->current_title_idx + 1, this->num_title_idx); } /* disc name */ if (this->disc_name && this->disc_name[0]) { udata.str_len = snprintf(udata.str, sizeof(udata.str), "%s, %s", this->disc_name, title_name); } else { udata.str_len = snprintf(udata.str, sizeof(udata.str), "%s", title_name); } _x_meta_info_set(this->stream, XINE_META_INFO_TITLE, udata.str); xine_event_send(this->stream, &uevent); } static void update_title_info(bluray_input_plugin_t *this, int playlist_id) { /* update title_info */ pthread_mutex_lock(&this->title_info_mutex); if (this->title_info) bd_free_title_info(this->title_info); if (playlist_id < 0) this->title_info = bd_get_title_info(this->bdh, this->current_title_idx, 0); else this->title_info = bd_get_playlist_info(this->bdh, playlist_id, 0); pthread_mutex_unlock(&this->title_info_mutex); if (!this->title_info) { LOGMSG("bd_get_title_info(%d) failed\n", this->current_title_idx); return; } /* calculate and set stream rate */ uint64_t rate = bd_get_title_size(this->bdh) * UINT64_C(8) // bits * INT64_C(90000) / (uint64_t)(this->title_info->duration); _x_stream_info_set(this->stream, XINE_STREAM_INFO_BITRATE, rate); /* set stream info */ if (this->nav_mode) { _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_TITLE_COUNT, this->num_titles); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_TITLE_NUMBER, this->current_title); } else { _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_TITLE_COUNT, this->num_title_idx); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_TITLE_NUMBER, this->current_title_idx + 1); } update_stream_info(this); /* set title name */ update_title_name(this); } /* * libbluray event handling */ static void stream_flush(bluray_input_plugin_t *this) { if (this->stream_flushed || !this->stream) return; lprintf("Stream flush\n"); this->stream_flushed = 1; xine_event_t event = { .type = XINE_EVENT_END_OF_CLIP, .stream = this->stream, .data = NULL, .data_length = 0, }; xine_event_send (this->stream, &event); this->demux_action_req = 1; } static void stream_reset(bluray_input_plugin_t *this) { if (!this || !this->stream) return; lprintf("Stream reset\n"); xine_event_t event = { .type = XINE_EVENT_PIDS_CHANGE, .stream = this->stream, .data = NULL, .data_length = 0, }; if (!this->end_of_title) { _x_demux_flush_engine(this->stream); } xine_event_send (this->stream, &event); this->demux_action_req = 1; } static void wait_secs(bluray_input_plugin_t *this, unsigned seconds) { stream_flush(this); if (this->still_end_time) { if (time(NULL) >= this->still_end_time) { lprintf("pause end\n"); this->still_end_time = 0; bd_read_skip_still(this->bdh); stream_reset(this); return; } } else if (seconds) { if (seconds > 300) { seconds = 300; } lprintf("still image, pause for %d seconds\n", seconds); this->still_end_time = time(NULL) + seconds; } xine_usec_sleep(40*1000); } static void update_spu_channel(bluray_input_plugin_t *this, int channel) { if (this->stream->video_fifo) { buf_element_t *buf = this->stream->video_fifo->buffer_pool_alloc(this->stream->video_fifo); buf->type = BUF_CONTROL_SPU_CHANNEL; buf->decoder_info[0] = channel; buf->decoder_info[1] = channel; buf->decoder_info[2] = channel; this->stream->video_fifo->put(this->stream->video_fifo, buf); } } static void update_audio_channel(bluray_input_plugin_t *this, int channel) { if (this->stream->audio_fifo) { buf_element_t *buf = this->stream->audio_fifo->buffer_pool_alloc(this->stream->audio_fifo); buf->type = BUF_CONTROL_AUDIO_CHANNEL; buf->decoder_info[0] = channel; this->stream->audio_fifo->put(this->stream->audio_fifo, buf); } } static void handle_libbluray_event(bluray_input_plugin_t *this, BD_EVENT ev) { switch ((bd_event_e)ev.event) { case BD_EVENT_ERROR: lprintf("BD_EVENT_ERROR\n"); _x_message (this->stream, XINE_MSG_GENERAL_WARNING, "Error playing BluRay disc", NULL); this->error = 1; return; case BD_EVENT_READ_ERROR: LOGMSG("m2ts file read error"); /*stream_flush(this); leave error detection and handling for upper layer */ return; case BD_EVENT_ENCRYPTED: lprintf("BD_EVENT_ENCRYPTED\n"); _x_message (this->stream, XINE_MSG_ENCRYPTED_SOURCE, "Media stream scrambled/encrypted", NULL); this->error = 1; return; /* playback control */ case BD_EVENT_SEEK: lprintf("BD_EVENT_SEEK\n"); this->still_end_time = 0; stream_reset(this); break; case BD_EVENT_STILL_TIME: lprintf("BD_EVENT_STILL_TIME %d\n", ev.param); wait_secs(this, ev.param); break; case BD_EVENT_STILL: lprintf("BD_EVENT_STILL %d\n", ev.param); int paused = _x_get_fine_speed(this->stream) == XINE_SPEED_PAUSE; if (paused != ev.param) { _x_set_fine_speed(this->stream, ev.param ? XINE_SPEED_PAUSE : XINE_SPEED_NORMAL); } break; case BD_EVENT_IDLE: xine_usec_sleep(10000); break; /* playback position */ case BD_EVENT_ANGLE: lprintf("BD_EVENT_ANGLE_NUMBER %d\n", ev.param); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_ANGLE_NUMBER, ev.param); break; case BD_EVENT_END_OF_TITLE: lprintf("BD_EVENT_END_OF_TITLE\n"); stream_flush(this); this->end_of_title = 1; break; case BD_EVENT_TITLE: this->current_title = ev.param; break; case BD_EVENT_PLAYLIST: lprintf("BD_EVENT_PLAYLIST %d\n", ev.param); this->current_title_idx = bd_get_current_title(this->bdh); this->current_clip = 0; update_title_info(this, ev.param); stream_reset(this); this->end_of_title = 0; break; case BD_EVENT_PLAYITEM: lprintf("BD_EVENT_PLAYITEM %d\n", ev.param); this->current_clip = ev.param; this->still_end_time = 0; break; case BD_EVENT_CHAPTER: lprintf("BD_EVENT_CHAPTER %d\n", ev.param); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_CHAPTER_NUMBER, ev.param); break; /* stream selection */ case BD_EVENT_AUDIO_STREAM: lprintf("BD_EVENT_AUDIO_STREAM %d\n", ev.param); if (ev.param < 32) { update_audio_channel(this, ev.param - 1); } else { update_audio_channel(this, 0); } break; case BD_EVENT_PG_TEXTST: lprintf("BD_EVENT_PG_TEXTST %s\n", ev.param ? "ON" : "OFF"); this->pg_enable = !!ev.param; update_spu_channel(this, this->pg_enable ? this->pg_stream : -1); break; case BD_EVENT_PG_TEXTST_STREAM: lprintf("BD_EVENT_PG_TEXTST_STREAM %d\n", ev.param); if (ev.param < 64) { this->pg_stream = ev.param - 1; } else { this->pg_stream = -1; } if (this->pg_enable) { update_spu_channel(this, this->pg_stream); } break; case BD_EVENT_MENU: this->menu_open = !!ev.param; send_num_buttons(this, ev.param); break; case BD_EVENT_IG_STREAM: case BD_EVENT_SECONDARY_AUDIO: case BD_EVENT_SECONDARY_AUDIO_STREAM: case BD_EVENT_SECONDARY_VIDEO: case BD_EVENT_SECONDARY_VIDEO_SIZE: case BD_EVENT_SECONDARY_VIDEO_STREAM: case BD_EVENT_NONE: break; default: LOGMSG("unhandled libbluray event %d [param %d]\n", ev.event, ev.param); break; } } static void handle_libbluray_events(bluray_input_plugin_t *this) { BD_EVENT ev; while (bd_get_event(this->bdh, &ev)) { handle_libbluray_event(this, ev); if (this->error || ev.event == BD_EVENT_NONE || ev.event == BD_EVENT_ERROR) break; } } /* * xine event handling */ static int open_title (bluray_input_plugin_t *this, int title_idx) { if (bd_select_title(this->bdh, title_idx) <= 0) { LOGMSG("bd_select_title(%d) failed\n", title_idx); return 0; } this->current_title_idx = title_idx; update_title_info(this, -1); return 1; } static void send_mouse_enter_leave_event(bluray_input_plugin_t *this, int direction) { if (direction != this->mouse_inside_button) { xine_event_t event; xine_spu_button_t spu_event; spu_event.direction = direction; spu_event.button = 1; event.type = XINE_EVENT_SPU_BUTTON; event.stream = this->stream; event.data = &spu_event; event.data_length = sizeof(spu_event); xine_event_send(this->stream, &event); this->mouse_inside_button = direction; } } static void handle_events(bluray_input_plugin_t *this) { xine_event_t *event; if (!this->event_queue) return; while (NULL != (event = xine_event_get(this->event_queue))) { if (!this->bdh || !this->title_info) { xine_event_free(event); return; } int64_t pts = xine_get_current_vpts(this->stream) - this->stream->metronom->get_option(this->stream->metronom, METRONOM_VPTS_OFFSET); if (this->menu_open) { switch (event->type) { case XINE_EVENT_INPUT_LEFT: bd_user_input(this->bdh, pts, BD_VK_LEFT); break; case XINE_EVENT_INPUT_RIGHT: bd_user_input(this->bdh, pts, BD_VK_RIGHT); break; } } else { switch (event->type) { case XINE_EVENT_INPUT_LEFT: lprintf("XINE_EVENT_INPUT_LEFT: previous title\n"); if (!this->nav_mode) { open_title(this, MAX(0, this->current_title_idx - 1)); } else { bd_play_title(this->bdh, MAX(1, this->current_title - 1)); } stream_reset(this); break; case XINE_EVENT_INPUT_RIGHT: lprintf("XINE_EVENT_INPUT_RIGHT: next title\n"); if (!this->nav_mode) { open_title(this, MIN(this->num_title_idx - 1, this->current_title_idx + 1)); } else { bd_play_title(this->bdh, MIN(this->num_titles, this->current_title + 1)); } stream_reset(this); break; } } switch (event->type) { case XINE_EVENT_INPUT_MOUSE_BUTTON: { xine_input_data_t *input = event->data; lprintf("mouse click: button %d at (%d,%d)\n", input->button, input->x, input->y); if (input->button == 1) { bd_mouse_select(this->bdh, pts, input->x, input->y); bd_user_input(this->bdh, pts, BD_VK_MOUSE_ACTIVATE); send_mouse_enter_leave_event(this, 0); } break; } case XINE_EVENT_INPUT_MOUSE_MOVE: { xine_input_data_t *input = event->data; if (bd_mouse_select(this->bdh, pts, input->x, input->y) > 0) { send_mouse_enter_leave_event(this, 1); } else { send_mouse_enter_leave_event(this, 0); } break; } case XINE_EVENT_INPUT_MENU1: if (!this->disc_info->top_menu_supported) { _x_message (this->stream, XINE_MSG_GENERAL_WARNING, "Can't open Top Menu", "Top Menu title not supported", NULL); } bd_menu_call(this->bdh, pts); break; case XINE_EVENT_INPUT_MENU2: bd_user_input(this->bdh, pts, BD_VK_POPUP); break; case XINE_EVENT_INPUT_UP: bd_user_input(this->bdh, pts, BD_VK_UP); break; case XINE_EVENT_INPUT_DOWN: bd_user_input(this->bdh, pts, BD_VK_DOWN); break; case XINE_EVENT_INPUT_SELECT: bd_user_input(this->bdh, pts, BD_VK_ENTER); break; case XINE_EVENT_INPUT_NUMBER_0: bd_user_input(this->bdh, pts, BD_VK_0); break; case XINE_EVENT_INPUT_NUMBER_1: bd_user_input(this->bdh, pts, BD_VK_1); break; case XINE_EVENT_INPUT_NUMBER_2: bd_user_input(this->bdh, pts, BD_VK_2); break; case XINE_EVENT_INPUT_NUMBER_3: bd_user_input(this->bdh, pts, BD_VK_3); break; case XINE_EVENT_INPUT_NUMBER_4: bd_user_input(this->bdh, pts, BD_VK_4); break; case XINE_EVENT_INPUT_NUMBER_5: bd_user_input(this->bdh, pts, BD_VK_5); break; case XINE_EVENT_INPUT_NUMBER_6: bd_user_input(this->bdh, pts, BD_VK_6); break; case XINE_EVENT_INPUT_NUMBER_7: bd_user_input(this->bdh, pts, BD_VK_7); break; case XINE_EVENT_INPUT_NUMBER_8: bd_user_input(this->bdh, pts, BD_VK_8); break; case XINE_EVENT_INPUT_NUMBER_9: bd_user_input(this->bdh, pts, BD_VK_9); break; case XINE_EVENT_INPUT_NEXT: { cfg_entry_t* entry = this->class->xine->config->lookup_entry(this->class->xine->config, "media.bluray.skip_behaviour"); switch (entry->num_value) { case 0: /* skip by chapter */ bd_seek_chapter(this->bdh, bd_get_current_chapter(this->bdh) + 1); update_stream_info(this); break; case 1: /* skip by title */ if (!this->nav_mode) { open_title(this, MIN(this->num_title_idx - 1, this->current_title_idx + 1)); } else { bd_play_title(this->bdh, MIN(this->num_titles, this->current_title + 1)); } break; } stream_reset(this); break; } case XINE_EVENT_INPUT_PREVIOUS: { cfg_entry_t* entry = this->class->xine->config->lookup_entry(this->class->xine->config, "media.bluray.skip_behaviour"); switch (entry->num_value) { case 0: /* skip by chapter */ bd_seek_chapter(this->bdh, MAX(0, ((int)bd_get_current_chapter(this->bdh)) - 1)); update_stream_info(this); break; case 1: /* skip by title */ if (!this->nav_mode) { open_title(this, MAX(0, this->current_title_idx - 1)); } else { bd_play_title(this->bdh, MAX(1, this->current_title - 1)); } break; } stream_reset(this); break; } case XINE_EVENT_INPUT_ANGLE_NEXT: { unsigned curr_angle = bd_get_current_angle(this->bdh); unsigned angle = MIN(8, curr_angle + 1); lprintf("XINE_EVENT_INPUT_ANGLE_NEXT: set angle %d --> %d\n", curr_angle, angle); bd_seamless_angle_change(this->bdh, angle); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_ANGLE_NUMBER, bd_get_current_angle(this->bdh)); break; } case XINE_EVENT_INPUT_ANGLE_PREVIOUS: { unsigned curr_angle = bd_get_current_angle(this->bdh); unsigned angle = curr_angle ? curr_angle - 1 : 0; lprintf("XINE_EVENT_INPUT_ANGLE_PREVIOUS: set angle %d --> %d\n", curr_angle, angle); bd_seamless_angle_change(this->bdh, angle); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_ANGLE_NUMBER, bd_get_current_angle(this->bdh)); break; } } xine_event_free(event); } } /* * xine plugin interface */ static uint32_t bluray_plugin_get_capabilities (input_plugin_t *this_gen) { return INPUT_CAP_SEEKABLE | INPUT_CAP_BLOCK | INPUT_CAP_AUDIOLANG | INPUT_CAP_SPULANG | INPUT_CAP_CHAPTERS; } #define CHECK_READ_INTERRUPT \ do { \ if (this->demux_action_req) { \ this->demux_action_req = 0; \ errno = EAGAIN; \ return -1; \ } \ if (_x_action_pending(this->stream)) { \ errno = EINTR; \ return -1; \ } \ } while (0) static off_t bluray_plugin_read (input_plugin_t *this_gen, void *buf, off_t len) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; off_t result; if (!this || !this->bdh || len < 0 || this->error) return -1; if (!this->has_video) { vo_frame_t *img = NULL; this->class->xine->port_ticket->acquire (this->class->xine->port_ticket, 1); img = this->stream->video_out->get_frame (this->stream->video_out, 1920, 1080, 16.0/9.0, XINE_IMGFMT_YV12, VO_BOTH_FIELDS); this->class->xine->port_ticket->release (this->class->xine->port_ticket, 1); if (img) { if (img->format == XINE_IMGFMT_YV12 && img->base[0] && img->base[1] && img->base[2]) { memset(img->base[0], 0x00, img->pitches[0] * img->height); memset(img->base[1], 0x80, img->pitches[1] * img->height / 2); memset(img->base[2], 0x80, img->pitches[2] * img->height / 2); img->duration = 0; img->pts = 0; img->bad_frame = 0; img->draw(img, this->stream); } img->free(img); } this->has_video = 1; } handle_events(this); CHECK_READ_INTERRUPT; if (this->nav_mode) { do { BD_EVENT ev; result = bd_read_ext (this->bdh, (unsigned char *)buf, len, &ev); handle_libbluray_event(this, ev); CHECK_READ_INTERRUPT; if (result == 0) { handle_events(this); CHECK_READ_INTERRUPT; } } while (!this->error && result == 0); } else { result = bd_read (this->bdh, (unsigned char *)buf, len); handle_libbluray_events(this); } if (result < 0) { LOGMSG("bd_read() failed: %s (%d of %d)\n", strerror(errno), (int)result, (int)len); } if (result > 0) { this->stream_flushed = 0; } return result; } static buf_element_t *bluray_plugin_read_block (input_plugin_t *this_gen, fifo_buffer_t *fifo, off_t todo) { buf_element_t *buf = fifo->buffer_pool_alloc (fifo); if (todo > (off_t)buf->max_size) todo = buf->max_size; if (todo > ALIGNED_UNIT_SIZE) todo = ALIGNED_UNIT_SIZE; if (todo > 0) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; buf->size = bluray_plugin_read(this_gen, (char*)buf->mem, todo); buf->type = BUF_DEMUX_BLOCK; if (buf->size > 0) { buf->extra_info->input_time = 0; buf->extra_info->total_time = this->title_info->duration / 90000; return buf; } } buf->free_buffer (buf); return NULL; } static off_t bluray_plugin_seek (input_plugin_t *this_gen, off_t offset, int origin) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; if (!this || !this->bdh) return -1; if (this->still_end_time) return offset; /* convert relative seeks to absolute */ if (origin == SEEK_CUR) { offset = bd_tell(this->bdh) + offset; } else if (origin == SEEK_END) { if (offset < (off_t)bd_get_title_size(this->bdh)) offset = bd_get_title_size(this->bdh) - offset; else offset = 0; } lprintf("bluray_plugin_seek() seeking to %lld\n", (long long)offset); return bd_seek (this->bdh, offset); } static off_t bluray_plugin_seek_time (input_plugin_t *this_gen, int time_offset, int origin) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; if (!this || !this->bdh) return -1; if (this->still_end_time) return bd_tell(this->bdh); /* convert relative seeks to absolute */ if (origin == SEEK_CUR) { time_offset += this_gen->get_current_time(this_gen); } else if (origin == SEEK_END) { pthread_mutex_lock(&this->title_info_mutex); if (!this->title_info) { pthread_mutex_unlock(&this->title_info_mutex); return -1; } int duration = this->title_info->duration / 90; if (time_offset < duration) time_offset = duration - time_offset; else time_offset = 0; pthread_mutex_unlock(&this->title_info_mutex); } lprintf("bluray_plugin_seek_time() seeking to %d.%03ds\n", time_offset / 1000, time_offset % 1000); return bd_seek_time(this->bdh, time_offset * INT64_C(90)); } static off_t bluray_plugin_get_current_pos (input_plugin_t *this_gen) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; return this->bdh ? bd_tell(this->bdh) : 0; } static int bluray_plugin_get_current_time (input_plugin_t *this_gen) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; return this->bdh ? (int)(bd_tell_time(this->bdh) / UINT64_C(90)) : -1; } static off_t bluray_plugin_get_length (input_plugin_t *this_gen) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; return this->bdh ? (off_t)bd_get_title_size(this->bdh) : (off_t)-1; } static uint32_t bluray_plugin_get_blocksize (input_plugin_t *this_gen) { (void)this_gen; return ALIGNED_UNIT_SIZE; } static const char* bluray_plugin_get_mrl (input_plugin_t *this_gen) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; return this->mrl; } static int get_optional_data_impl (bluray_input_plugin_t *this, void *data, int data_type) { unsigned int current_clip = this->current_clip; switch (data_type) { case INPUT_OPTIONAL_DATA_DEMUXER: *(const char **)data = "mpeg-ts"; return INPUT_OPTIONAL_SUCCESS; /* * audio track language: * - channel number can be mpeg-ts PID (0x1100 ... 0x11ff) */ case INPUT_OPTIONAL_DATA_AUDIOLANG: if (this->title_info && this->title_info->clip_count < current_clip) { int channel = *((int *)data); BLURAY_CLIP_INFO *clip = &this->title_info->clips[current_clip]; if (channel >= 0 && channel < clip->audio_stream_count) { memcpy(data, clip->audio_streams[channel].lang, 4); lprintf("INPUT_OPTIONAL_DATA_AUDIOLANG: %02d [pid 0x%04x]: %s\n", channel, clip->audio_streams[channel].pid, clip->audio_streams[channel].lang); return INPUT_OPTIONAL_SUCCESS; } /* search by pid */ int i; for (i = 0; i < clip->audio_stream_count; i++) { if (channel == clip->audio_streams[i].pid) { memcpy(data, clip->audio_streams[i].lang, 4); lprintf("INPUT_OPTIONAL_DATA_AUDIOLANG: pid 0x%04x -> ch %d: %s\n", channel, i, clip->audio_streams[i].lang); return INPUT_OPTIONAL_SUCCESS; } } } return INPUT_OPTIONAL_UNSUPPORTED; /* * SPU track language: * - channel number can be mpeg-ts PID (0x1200 ... 0x12ff) */ case INPUT_OPTIONAL_DATA_SPULANG: if (this->title_info && this->title_info->clip_count < current_clip) { int channel = *((int *)data); BLURAY_CLIP_INFO *clip = &this->title_info->clips[current_clip]; if (channel >= 0 && channel < clip->pg_stream_count) { memcpy(data, clip->pg_streams[channel].lang, 4); lprintf("INPUT_OPTIONAL_DATA_SPULANG: %02d [pid 0x%04x]: %s\n", channel, clip->pg_streams[channel].pid, clip->pg_streams[channel].lang); return INPUT_OPTIONAL_SUCCESS; } /* search by pid */ int i; for (i = 0; i < clip->pg_stream_count; i++) { if (channel == clip->pg_streams[i].pid) { memcpy(data, clip->pg_streams[i].lang, 4); lprintf("INPUT_OPTIONAL_DATA_SPULANG: pid 0x%04x -> ch %d: %s\n", channel, i, clip->pg_streams[i].lang); return INPUT_OPTIONAL_SUCCESS; } } } return INPUT_OPTIONAL_UNSUPPORTED; default: return INPUT_OPTIONAL_UNSUPPORTED; } return INPUT_OPTIONAL_UNSUPPORTED; } static int bluray_plugin_get_optional_data (input_plugin_t *this_gen, void *data, int data_type) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; int r = INPUT_OPTIONAL_UNSUPPORTED; if (this && this->stream && data) { pthread_mutex_lock(&this->title_info_mutex); r = get_optional_data_impl(this, data, data_type); pthread_mutex_unlock(&this->title_info_mutex); } return r; } static void bluray_plugin_dispose (input_plugin_t *this_gen) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; if (this->bdh) { bd_register_argb_overlay_proc(this->bdh, NULL, NULL, NULL); bd_register_overlay_proc(this->bdh, NULL, NULL); } close_overlay(this, -1); if (this->event_queue) xine_event_dispose_queue(this->event_queue); pthread_mutex_lock(&this->title_info_mutex); if (this->title_info) bd_free_title_info(this->title_info); this->title_info = NULL; pthread_mutex_unlock(&this->title_info_mutex); pthread_mutex_destroy(&this->title_info_mutex); if (this->bdh) bd_close(this->bdh); osd_buf_destroy(&this->osd_buf); free (this->mrl); free (this->disc_root); free (this->disc_name); free (this); } static int parse_mrl(const char *mrl_in, char **path, int *title, int *chapter) { int skip = 0; if (!strncasecmp(mrl_in, "bluray:", 7)) skip = 7; else if (!strncasecmp(mrl_in, "bd:", 3)) skip = 3; else return -1; char *mrl = strdup(mrl_in + skip); /* title[.chapter] given ? parse and drop it */ if (mrl[strlen(mrl)-1] != '/') { char *end = strrchr(mrl, '/'); if (end && end[1]) { if (sscanf(end, "/%d.%d", title, chapter) < 1) *title = -1; else *end = 0; } } lprintf(" -> title %d, chapter %d, mrl \'%s\'\n", *title, *chapter, mrl); if ((mrl[0] == 0) || (mrl[1] == 0 && mrl[0] == '/') || (mrl[2] == 0 && mrl[1] == '/' && mrl[0] == '/') || (mrl[3] == 0 && mrl[2] == '/' && mrl[1] == '/' && mrl[0] == '/')){ /* default device */ *path = NULL; } else if (*mrl == '/') { /* strip extra slashes */ char *start = mrl; while (start[0] == '/' && start[1] == '/') start++; *path = strdup(start); _x_mrl_unescape(*path); lprintf("non-defaut mount point \'%s\'\n", *path); } else { lprintf("invalid mrl \'%s\'\n", mrl_in); free(mrl); return 0; } free(mrl); return 1; } static int get_disc_info(bluray_input_plugin_t *this) { const BLURAY_DISC_INFO *disc_info; disc_info = bd_get_disc_info(this->bdh); if (!disc_info) { LOGMSG("bd_get_disc_info() failed\n"); return -1; } if (!disc_info->bluray_detected) { LOGMSG("bd_get_disc_info(): BluRay not detected\n"); this->nav_mode = 0; return 0; } if (disc_info->aacs_detected && !disc_info->aacs_handled) { if (!disc_info->libaacs_detected) _x_message (this->stream, XINE_MSG_ENCRYPTED_SOURCE, "Media stream scrambled/encrypted with AACS", "libaacs not installed", NULL); else _x_message (this->stream, XINE_MSG_ENCRYPTED_SOURCE, "Media stream scrambled/encrypted with AACS", NULL); return -1; } if (disc_info->bdplus_detected && !disc_info->bdplus_handled) { if (!disc_info->libbdplus_detected) _x_message (this->stream, XINE_MSG_ENCRYPTED_SOURCE, "Media scrambled/encrypted with BD+", "libbdplus not installed.", NULL); else _x_message (this->stream, XINE_MSG_ENCRYPTED_SOURCE, "Media stream scrambled/encrypted with BD+", NULL); return -1; } #if 0 if (this->nav_mode && !disc_info->first_play_supported) { _x_message (this->stream, XINE_MSG_GENERAL_WARNING, "Can't play disc using menus", "First Play title not supported", NULL); this->nav_mode = 0; } if (this->nav_mode && disc_info->num_unsupported_titles > 0) { _x_message (this->stream, XINE_MSG_GENERAL_WARNING, "Unsupported titles found", "Some titles can't be played in navigation mode", NULL); } #endif this->num_titles = disc_info->num_hdmv_titles + disc_info->num_bdj_titles; this->disc_info = disc_info; return 1; } static int bluray_plugin_open (input_plugin_t *this_gen) { bluray_input_plugin_t *this = (bluray_input_plugin_t *) this_gen; int title = -1; int chapter = 0; lprintf("bluray_plugin_open\n"); /* validate and parse mrl */ if (!parse_mrl(this->mrl, &this->disc_root, &title, &chapter)) return -1; if (!strncasecmp(this->mrl, "bd:", 3)) this->nav_mode = 1; if (!this->disc_root) this->disc_root = strdup(this->class->mountpoint); /* open libbluray */ if (! (this->bdh = bd_open (this->disc_root, NULL))) { LOGMSG("bd_open(\'%s\') failed: %s\n", this->disc_root, strerror(errno)); return -1; } lprintf("bd_open(\'%s\') OK\n", this->disc_root); if (get_disc_info(this) < 0) { return -1; } /* load title list */ this->num_title_idx = bd_get_titles(this->bdh, TITLES_RELEVANT, MIN_TITLE_LENGTH); LOGMSG("%d titles\n", this->num_title_idx); if (this->num_title_idx < 1) return -1; /* select title */ /* if title was not in mrl, guess the main title */ if (title < 0) { uint64_t duration = 0; int i, playlist = 99999; for (i = 0; i < this->num_title_idx; i++) { BLURAY_TITLE_INFO *info = bd_get_title_info(this->bdh, i, 0); if (info->duration > duration) { title = i; duration = info->duration; playlist = info->playlist; } bd_free_title_info(info); } lprintf("main title: %d (%05d.mpls)\n", title, playlist); } /* update player settings */ bd_set_player_setting (this->bdh, BLURAY_PLAYER_SETTING_REGION_CODE, this->class->region); bd_set_player_setting (this->bdh, BLURAY_PLAYER_SETTING_PARENTAL, this->class->parental); bd_set_player_setting_str(this->bdh, BLURAY_PLAYER_SETTING_AUDIO_LANG, this->class->language); bd_set_player_setting_str(this->bdh, BLURAY_PLAYER_SETTING_PG_LANG, this->class->language); bd_set_player_setting_str(this->bdh, BLURAY_PLAYER_SETTING_MENU_LANG, this->class->language); bd_set_player_setting_str(this->bdh, BLURAY_PLAYER_SETTING_COUNTRY_CODE, this->class->country); /* init event queue */ bd_get_event(this->bdh, NULL); /* get disc name */ this->meta_dl = bd_get_meta(this->bdh); if (this->meta_dl && this->meta_dl->di_name && strlen(this->meta_dl->di_name) > 1) { this->disc_name = strdup(this->meta_dl->di_name); } else if (strcmp(this->disc_root, this->class->mountpoint)) { char *t = strrchr(this->disc_root, '/'); if (!t[1]) while (t > this->disc_root && t[-1] != '/') t--; else while (t[0] == '/') t++; this->disc_name = strdup(t); char *end = this->disc_name + strlen(this->disc_name) - 1; if (*end == '/') *end = 0; } /* register overlay (graphics) handler */ if (this->stream->video_out->get_capabilities(this->stream->video_out) & VO_CAP_ARGB_LAYER_OVERLAY) { fprintf(stderr, "argb overlays\n"); osd_buf_init(&this->osd_buf); bd_register_argb_overlay_proc(this->bdh, this, argb_overlay_proc, &this->osd_buf.buf); } else { fprintf(stderr, "no argb overlay support. NO BD-J.\n"); } bd_register_overlay_proc(this->bdh, this, overlay_proc); /* open */ this->current_title = -1; this->current_title_idx = -1; if (this->nav_mode) { if (bd_play(this->bdh) <= 0) { LOGMSG("bd_play() failed\n"); return -1; } } else { if (open_title(this, title) <= 0 && open_title(this, 0) <= 0) return -1; } /* jump to chapter */ if (chapter > 0) { chapter = MAX(0, MIN((int)this->title_info->chapter_count, chapter) - 1); bd_seek_chapter(this->bdh, chapter); _x_stream_info_set(this->stream, XINE_STREAM_INFO_DVD_CHAPTER_NUMBER, chapter + 1); } return 1; } static input_plugin_t *bluray_class_get_instance (input_class_t *cls_gen, xine_stream_t *stream, const char *mrl) { bluray_input_plugin_t *this; lprintf("bluray_class_get_instance\n"); if (strncasecmp(mrl, "bluray:", 7) && strncasecmp(mrl, "bd:", 3)) return NULL; this = (bluray_input_plugin_t *) calloc(1, sizeof (bluray_input_plugin_t)); this->stream = stream; this->class = (bluray_input_class_t*)cls_gen; this->mrl = strdup(mrl); this->input_plugin.open = bluray_plugin_open; this->input_plugin.get_capabilities = bluray_plugin_get_capabilities; this->input_plugin.read = bluray_plugin_read; this->input_plugin.read_block = bluray_plugin_read_block; this->input_plugin.seek = bluray_plugin_seek; this->input_plugin.seek_time = bluray_plugin_seek_time; this->input_plugin.get_current_pos = bluray_plugin_get_current_pos; this->input_plugin.get_current_time = bluray_plugin_get_current_time; this->input_plugin.get_length = bluray_plugin_get_length; this->input_plugin.get_blocksize = bluray_plugin_get_blocksize; this->input_plugin.get_mrl = bluray_plugin_get_mrl; this->input_plugin.get_optional_data = bluray_plugin_get_optional_data; this->input_plugin.dispose = bluray_plugin_dispose; this->input_plugin.input_class = cls_gen; this->event_queue = xine_event_new_queue (this->stream); pthread_mutex_init(&this->title_info_mutex, NULL); this->pg_stream = -1; return &this->input_plugin; } /* * plugin class */ static void mountpoint_change_cb(void *data, xine_cfg_entry_t *cfg) { bluray_input_class_t *this = (bluray_input_class_t *) data; this->mountpoint = cfg->str_value; } static void language_change_cb(void *data, xine_cfg_entry_t *cfg) { bluray_input_class_t *this = (bluray_input_class_t *) data; this->language = cfg->str_value; } static void country_change_cb(void *data, xine_cfg_entry_t *cfg) { bluray_input_class_t *this = (bluray_input_class_t *) data; this->country = cfg->str_value; } static void region_change_cb(void *data, xine_cfg_entry_t *cfg) { bluray_input_class_t *this = (bluray_input_class_t *) data; this->region = cfg->num_value; } static void parental_change_cb(void *data, xine_cfg_entry_t *cfg) { bluray_input_class_t *this = (bluray_input_class_t *) data; this->parental = cfg->num_value; } static const char * const *bluray_class_get_autoplay_list (input_class_t *this_gen, int *num_files) { (void)this_gen; static char *autoplay_list[] = { "bluray:/", NULL }; *num_files = 1; return (const char * const *)autoplay_list; } static int bluray_class_eject_media (input_class_t *this_gen) { return 1; } static void bluray_class_dispose (input_class_t *this_gen) { bluray_input_class_t *this = (bluray_input_class_t *) this_gen; config_values_t *config = this->xine->config; config->unregister_callback(config, "media.bluray.mountpoint"); config->unregister_callback(config, "media.bluray.region"); config->unregister_callback(config, "media.bluray.language"); config->unregister_callback(config, "media.bluray.country"); config->unregister_callback(config, "media.bluray.parental"); free (this); } static void *bluray_init_plugin (xine_t *xine, void *data) { (void)data; static char *skip_modes[] = {"skip chapter", "skip title", NULL}; config_values_t *config = xine->config; bluray_input_class_t *this = (bluray_input_class_t *) calloc(1, sizeof (bluray_input_class_t)); this->xine = xine; this->input_class.get_instance = bluray_class_get_instance; this->input_class.identifier = "bluray"; this->input_class.description = _("BluRay input plugin"); this->input_class.get_dir = NULL; this->input_class.get_autoplay_list = bluray_class_get_autoplay_list; this->input_class.dispose = bluray_class_dispose; this->input_class.eject_media = bluray_class_eject_media; this->mountpoint = config->register_filename(config, "media.bluray.mountpoint", "/mnt/bluray", XINE_CONFIG_STRING_IS_DIRECTORY_NAME, _("BluRay mount point"), _("Default mount location for BluRay discs."), 0, mountpoint_change_cb, (void *) this); /* Player settings */ this->language = config->register_string(config, "media.bluray.language", "eng", _("default language for BluRay playback"), _("xine tries to use this language as a default for BluRay playback. " "As far as the BluRay supports it, menus and audio tracks will be presented " "in this language.\nThe value must be a three character" "ISO639-2 language code."), 0, language_change_cb, this); this->country = config->register_string(config, "media.bluray.country", "en", _("BluRay player country code"), _("The value must be a two character ISO3166-1 country code."), 0, country_change_cb, this); this->region = config->register_num(config, "media.bluray.region", 7, _("BluRay player region code (1=A, 2=B, 4=C)"), _("This only needs to be changed if your BluRay jumps to a screen " "complaining about a wrong region code. It has nothing to do with " "the region code set in BluRay drives, this is purely software."), 0, region_change_cb, this); this->parental = config->register_num(config, "media.bluray.parental", 99, _("parental control age limit (1-99)"), _("Prevents playback of BluRay titles where parental " "control age limit is higher than this limit"), 0, parental_change_cb, this); /* */ config->register_enum(config, "media.bluray.skip_behaviour", 0, skip_modes, _("unit for the skip action"), _("You can configure the behaviour when issuing a skip command (using the skip " "buttons for example)."), 20, NULL, NULL); return this; } static const char * const *bd_class_get_autoplay_list (input_class_t *this_gen, int *num_files) { static const char * const autoplay_list[] = { "bd:/", NULL }; *num_files = 1; return autoplay_list; } static void *bd_init_plugin (xine_t *xine, void *data) { bluray_input_class_t *this = bluray_init_plugin(xine, data); if (this) { this->input_class.identifier = "bluray"; this->input_class.description = _("BluRay input plugin (using menus)"); this->input_class.get_dir = NULL; this->input_class.get_autoplay_list = bd_class_get_autoplay_list; } return this; } /* * exported plugin catalog entry */ const plugin_info_t xine_plugin_info[] EXPORTED = { /* type, API, "name", version, special_info, init_function */ { PLUGIN_INPUT | PLUGIN_MUST_PRELOAD, INPUT_PLUGIN_IFACE_VERSION, "BLURAY", XINE_VERSION_CODE, NULL, bluray_init_plugin }, { PLUGIN_INPUT | PLUGIN_MUST_PRELOAD, INPUT_PLUGIN_IFACE_VERSION, "BD", XINE_VERSION_CODE, NULL, bd_init_plugin }, { PLUGIN_NONE, 0, "", 0, NULL, NULL } };
29.911561
124
0.627573
aef953c3af584853ffdbe76a8188ac0fa4e1a7ef
289
h
C
include/option.h
Cargo2k/simplestCMS
633cdd4ff5d7d79306a14d86b0f28e193b3b0cfe
[ "MIT" ]
null
null
null
include/option.h
Cargo2k/simplestCMS
633cdd4ff5d7d79306a14d86b0f28e193b3b0cfe
[ "MIT" ]
null
null
null
include/option.h
Cargo2k/simplestCMS
633cdd4ff5d7d79306a14d86b0f28e193b3b0cfe
[ "MIT" ]
null
null
null
#ifndef OPTION_H_KC #define OPTION_H_KC #include <iostream> #include <string> #include <libconfig.h++> struct HostSetting { std::string dataPath; std::string htmlPath; std::string themePath; std::string themeName; }; bool load_config(libconfig::Config& cfg); #endif // OPTION_H_KC
16.055556
41
0.743945
08b60bac06e34d320c35e79b9b3bf2147d90b98f
1,525
h
C
CalFp02-/src/Sudoku.h
GuilhermeJSilva/CAL-TP
5e9dac1c56370a82d16f1633f03ec6302d81652d
[ "MIT" ]
null
null
null
CalFp02-/src/Sudoku.h
GuilhermeJSilva/CAL-TP
5e9dac1c56370a82d16f1633f03ec6302d81652d
[ "MIT" ]
null
null
null
CalFp02-/src/Sudoku.h
GuilhermeJSilva/CAL-TP
5e9dac1c56370a82d16f1633f03ec6302d81652d
[ "MIT" ]
null
null
null
/* * Sudoku.h * */ #ifndef SUDOKU_H_ #define SUDOKU_H_ #include <string> #include <sstream> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; #define IllegalArgumentException -1 class Sudoku { /** * numbers[i][j] - n�mero que ocupa a linha i, coluna j (de 0 a 8) * 0 quer dizer n�o preenchido. */ int numbers[9][9]; /** * Informa��o derivada da anterior, para acelerar processamento (n�mero de 1 a 9, nao usa 0) */ int countFilled; bool columnHasNumber[9][10]; bool lineHasNumber[9][10]; bool block3x3HasNumber[3][3][10]; /** * Solucoes para o sudoko */ int n_solucoes; void initialize(); public: /** Inicia um Sudoku vazio. */ Sudoku(); /** * Inicia um Sudoku com um conte�do inicial. * Lan�a excep��o IllegalArgumentException se os valores * estiverem fora da gama de 1 a 9 ou se existirem n�meros repetidos * por linha, coluna ou bloc 3x3. * * @param nums matriz com os valores iniciais (0 significa por preencher) */ Sudoku(int nums[9][9]); /** * Obtem o conte�do actual (s� para leitura!). */ int** getNumbers(); /** * Verifica se o Sudoku j� est� completamente resolvido */ bool isComplete(); /** * Resolve o Sudoku. * Retorna indica��o de sucesso ou insucesso (sudoku imposs�vel). */ bool solve(); /** * Imprime o Sudoku. */ void print(); int getSolucoes() const { return n_solucoes; } void setSolucoes(int solucoes) { n_solucoes = solucoes; } }; #endif /* SUDOKU_H_ */
16.758242
93
0.650492
d3e355282551f413c5ab945d4c4553f7f5f69ec8
389
h
C
WasteMobile/ModelManager/PileShapeCode+CoreDataClass.h
bcgov/eForWaste
09c624901d2784e5e7989211b922a932d27638dc
[ "Apache-2.0" ]
null
null
null
WasteMobile/ModelManager/PileShapeCode+CoreDataClass.h
bcgov/eForWaste
09c624901d2784e5e7989211b922a932d27638dc
[ "Apache-2.0" ]
5
2020-04-17T19:37:31.000Z
2022-01-10T22:20:45.000Z
WasteMobile/ModelManager/PileShapeCode+CoreDataClass.h
bcgov/eForWaste
09c624901d2784e5e7989211b922a932d27638dc
[ "Apache-2.0" ]
null
null
null
// // PileShapeCode+CoreDataClass.h // WasteMobile // // Created by Sweta Kutty on 2019-03-06. // Copyright © 2019 Salus Systems. All rights reserved. // // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class WastePile; NS_ASSUME_NONNULL_BEGIN @interface PileShapeCode : NSManagedObject @end NS_ASSUME_NONNULL_END #import "PileShapeCode+CoreDataProperties.h"
16.208333
56
0.758355
643730b1c96eb0182646addc745f38e076172301
9,184
c
C
mDNSMacOSX/uDNSPathEvaluation.c
olivierlevon/mdnsresponder-1
c2a146765c5a8a392842bc97be04418039b00a20
[ "Apache-2.0" ]
4
2021-02-19T16:50:02.000Z
2021-04-19T07:54:02.000Z
mDNSMacOSX/uDNSPathEvaluation.c
olivierlevon/mdnsresponder-1
c2a146765c5a8a392842bc97be04418039b00a20
[ "Apache-2.0" ]
1
2018-08-21T04:12:55.000Z
2018-08-21T04:12:55.000Z
mDNSMacOSX/uDNSPathEvaluation.c
olivierlevon/mdnsresponder-1
c2a146765c5a8a392842bc97be04418039b00a20
[ "Apache-2.0" ]
2
2018-08-22T03:43:37.000Z
2019-11-01T19:09:18.000Z
/* * Copyright (c) 2013-2020 Apple 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mDNSMacOSX.h" #include <libproc.h> #include <nw/private.h> #include "dns_sd_internal.h" #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) #include "QuerierSupport.h" #endif #define _nw_forget(PTR) \ do \ { \ if (*(PTR)) \ { \ nw_release(*(PTR)); \ *(PTR) = NULL; \ } \ } while (0) //Gets the DNSPolicy from NW PATH EVALUATOR mDNSexport void mDNSPlatformGetDNSRoutePolicy(DNSQuestion *q) { nw_endpoint_t host = NULL; nw_parameters_t parameters = NULL; nw_path_evaluator_t evaluator = NULL; nw_path_t path = NULL; mDNSBool isBlocked = mDNSfalse; q->ServiceID = -1; // initialize the ServiceID to default value of -1 // Return for non-unicast DNS queries, or invalid PID. if (mDNSOpaque16IsZero(q->TargetQID) || (q->pid < 0)) { goto exit; } mDNSs32 service_id; mDNSu32 client_ifindex, dnspol_ifindex; int retval; struct proc_uniqidentifierinfo info; mDNSBool isUUIDSet; char unenc_name[MAX_ESCAPED_DOMAIN_NAME]; ConvertDomainNameToCString(&q->qname, unenc_name); host = nw_endpoint_create_host(unenc_name, "0"); if (host == NULL) { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, "[Q%u] mDNSPlatformGetDNSRoutePolicy: Query for " PRI_DM_NAME " (" PUB_S "), PID[%d], EUID[%d], ServiceID[%d]" " host is NULL", mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->pid, q->euid, q->ServiceID); goto exit; } parameters = nw_parameters_create(); if (parameters == NULL) { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, "[Q%u] mDNSPlatformGetDNSRoutePolicy: Query for " PRI_DM_NAME " (" PUB_S "), PID[%d], EUID[%d], ServiceID[%d]" " parameters is NULL", mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->pid, q->euid, q->ServiceID); goto exit; } #if TARGET_OS_WATCH static xpc_object_t prohibited_interface_subtypes = NULL; // Companion interface on watchOS does not support DNS, so we don't want path evalution to return it to us. if (prohibited_interface_subtypes == NULL) { prohibited_interface_subtypes = xpc_array_create(NULL, 0); if (prohibited_interface_subtypes != NULL) { xpc_array_set_uint64(prohibited_interface_subtypes, XPC_ARRAY_APPEND, nw_interface_subtype_companion); } } if (prohibited_interface_subtypes == NULL) { LogRedact(MDNS_LOG_CATEGORY_UDNS, MDNS_LOG_ERROR, "mDNSPlatformGetDNSRoutePolicy: DNS Route Policy: prohibited_interface_subtypes returned by xpc_array_create() is NULL"); } else { nw_parameters_set_prohibited_interface_subtypes(parameters, prohibited_interface_subtypes); } #endif // TARGET_OS_WATCH // Check for all the special (negative) internal value interface indices before initializing client_ifindex if ( (q->InterfaceID == mDNSInterface_Any) || (q->InterfaceID == mDNSInterface_LocalOnly) || (q->InterfaceID == mDNSInterfaceMark) || (q->InterfaceID == mDNSInterface_P2P) || (q->InterfaceID == mDNSInterface_BLE) || (q->InterfaceID == uDNSInterfaceMark)) { client_ifindex = 0; } else { client_ifindex = (mDNSu32)(uintptr_t)q->InterfaceID; } if (client_ifindex > 0) { nw_interface_t client_intf = nw_interface_create_with_index(client_ifindex); if (client_intf) { nw_parameters_require_interface(parameters, client_intf); _nw_forget(&client_intf); } else { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[Q%u] mDNSPlatformGetDNSRoutePolicy: nw_interface_create_with_index() returned NULL for index %u", mDNSVal16(q->TargetQID), client_ifindex); } } nw_parameters_set_uid(parameters,(uid_t)q->euid); if (q->pid != 0) { nw_parameters_set_pid(parameters, q->pid); retval = proc_pidinfo(q->pid, PROC_PIDUNIQIDENTIFIERINFO, 1, &info, sizeof(info)); if (retval == (int)sizeof(info)) { nw_parameters_set_e_proc_uuid(parameters, info.p_uuid); isUUIDSet = mDNStrue; } else { debugf("mDNSPlatformGetDNSRoutePolicy: proc_pidinfo returned %d", retval); isUUIDSet = mDNSfalse; } } else { nw_parameters_set_e_proc_uuid(parameters, q->uuid); isUUIDSet = mDNStrue; } evaluator = nw_path_create_evaluator_for_endpoint(host, parameters); if (evaluator == NULL) { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, "[Q%u] mDNSPlatformGetDNSRoutePolicy: Query for " PRI_DM_NAME " (" PUB_S "), PID[%d], EUID[%d], ServiceID[%d]" " evaluator is NULL", mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->pid, q->euid, q->ServiceID); goto exit; } _nw_forget(&host); _nw_forget(&parameters); path = nw_path_evaluator_copy_path(evaluator); if (path == NULL) { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, "[Q%u] mDNSPlatformGetDNSRoutePolicy: Query for " PRI_DM_NAME " (" PUB_S "), PID[%d], EUID[%d], ServiceID[%d]" " path is NULL", mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->pid, q->euid, q->ServiceID); goto exit; } service_id = nw_path_get_flow_divert_unit(path); if (service_id != 0) { q->ServiceID = service_id; LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[Q%u] mDNSPlatformGetDNSRoutePolicy: Query for " PRI_DM_NAME " service ID is set ->service_ID:[%d] ", mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), service_id); } else { nw_interface_t nwpath_intf = nw_path_copy_scoped_interface(path); if (nwpath_intf != NULL) { // Use the new scoped interface given by NW PATH EVALUATOR dnspol_ifindex = nw_interface_get_index(nwpath_intf); q->InterfaceID = (mDNSInterfaceID)(uintptr_t)dnspol_ifindex; _nw_forget(&nwpath_intf); if (dnspol_ifindex != client_ifindex) { LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[Q%u] mDNSPlatformGetDNSRoutePolicy: DNS Route Policy has changed the scoped ifindex from [%d] to [%d]", mDNSVal16(q->TargetQID), client_ifindex, dnspol_ifindex); } } else { debugf("mDNSPlatformGetDNSRoutePolicy: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] nw_interface_t nwpath_intf is NULL ", q->qname.c, DNSTypeName(q->qtype), q->pid, q->euid, q->ServiceID); } } #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) uuid_clear(q->ResolverUUID); if (__builtin_available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)) { if (path != NULL) { __block nw_resolver_config_t best_config = NULL; __block nw_resolver_class_t best_class = nw_resolver_class_default_direct; nw_path_enumerate_resolver_configs(path, ^bool(nw_resolver_config_t config) { const nw_resolver_class_t class = nw_resolver_config_get_class(config); if (class != nw_resolver_class_default_direct && (best_class == nw_resolver_class_default_direct || class < best_class)) { best_class = class; best_config = config; } return true; }); if (best_config != NULL) { nw_resolver_config_get_identifier(best_config, q->ResolverUUID); } } } if (!uuid_is_null(q->ResolverUUID)) { Querier_RegisterPathResolver(q->ResolverUUID); } #endif if (isUUIDSet && path && (nw_path_get_status(path) == nw_path_status_unsatisfied) && (nw_path_get_reason(path) != nw_path_reason_no_route)) { isBlocked = mDNStrue; } exit: _nw_forget(&host); _nw_forget(&parameters); _nw_forget(&path); _nw_forget(&evaluator); q->BlockedByPolicy = isBlocked; }
36.444444
209
0.622931
eaeebd3ec4842f28bf4ec1531b1710228a7db131
1,308
h
C
external/virtgpu_cross_domain_protocol.h
proton-vayu/android_external_minigbm
35f428147361dba3c5792241226e864a978cb873
[ "BSD-3-Clause" ]
1
2020-11-16T20:32:06.000Z
2020-11-16T20:32:06.000Z
external/virtgpu_cross_domain_protocol.h
proton-vayu/android_external_minigbm
35f428147361dba3c5792241226e864a978cb873
[ "BSD-3-Clause" ]
3
2020-07-23T14:01:39.000Z
2021-03-03T12:22:52.000Z
external/virtgpu_cross_domain_protocol.h
proton-vayu/android_external_minigbm
35f428147361dba3c5792241226e864a978cb873
[ "BSD-3-Clause" ]
3
2019-12-24T07:57:34.000Z
2021-10-17T12:59:24.000Z
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef VIRTGPU_CROSS_DOMAIN_PROTOCOL_H #define VIRTGPU_CROSS_DOMAIN_PROTOCOL_H #include <stdint.h> // Cross-domain commands (only a maximum of 255 supported) #define CROSS_DOMAIN_CMD_INIT 1 #define CROSS_DOMAIN_CMD_GET_IMAGE_REQUIREMENTS 2 // Channel types (must match rutabaga channel types) #define CROSS_DOMAIN_CHANNEL_TYPE_WAYLAND 0x0001 #define CROSS_DOMAIN_CHANNEL_TYPE_CAMERA 0x0002 struct CrossDomainCapabilities { uint32_t version; uint32_t supported_channels; uint32_t supports_dmabuf; uint32_t supports_external_gpu_memory; }; struct CrossDomainImageRequirements { uint32_t strides[4]; uint32_t offsets[4]; uint64_t modifier; uint64_t size; uint64_t blob_id; uint32_t map_info; uint32_t pad; int32_t memory_idx; int32_t physical_device_idx; }; struct CrossDomainHeader { uint8_t cmd; uint8_t fence_ctx_idx; uint16_t cmd_size; uint32_t pad; }; struct CrossDomainInit { struct CrossDomainHeader hdr; uint32_t ring_id; uint32_t channel_type; }; struct CrossDomainGetImageRequirements { struct CrossDomainHeader hdr; uint32_t width; uint32_t height; uint32_t drm_format; uint32_t flags; }; #endif
22.169492
73
0.810398
6c90720a63e7443046ddf978aa5f16ef5b51f132
176
c
C
tests/analysis/da_di/distance_4/sample/main.c
dvm-system/tsar-test
b3047eaa2ad8e4d6c0ab2a86f61a596736dbd762
[ "Apache-2.0" ]
null
null
null
tests/analysis/da_di/distance_4/sample/main.c
dvm-system/tsar-test
b3047eaa2ad8e4d6c0ab2a86f61a596736dbd762
[ "Apache-2.0" ]
11
2021-01-28T21:06:08.000Z
2021-02-24T09:49:35.000Z
tests/analysis/da_di/distance_4/sample/main.c
zoocide/tsar-test-template
b3047eaa2ad8e4d6c0ab2a86f61a596736dbd762
[ "Apache-2.0" ]
null
null
null
double U[100][100]; void foo() { int JStart = 0; for (int I = 1; I < 99; ++I) { ++JStart; for (int J = JStart; J < 99; ++J) U[I][J] = U[I - 1][J] + 1; } }
16
37
0.414773
caaff6ab4b257ff000bba54a4191922d8c85cf26
1,078
c
C
lib/generateCode/example2/testing sample/single_fifo1/single/tile/sdfactor/sdfactor_p1.c
Rojods/CInTSyDe
b026d7e59b7707b0d43032a74a085875b43dd281
[ "MIT" ]
1
2022-03-29T13:16:25.000Z
2022-03-29T13:16:25.000Z
lib/generateCode/example2/testing sample/single_fifo1/single/tile/sdfactor/sdfactor_p1.c
Rojods/CInTSyDe
b026d7e59b7707b0d43032a74a085875b43dd281
[ "MIT" ]
null
null
null
lib/generateCode/example2/testing sample/single_fifo1/single/tile/sdfactor/sdfactor_p1.c
Rojods/CInTSyDe
b026d7e59b7707b0d43032a74a085875b43dd281
[ "MIT" ]
null
null
null
/* Includes */ #include "../../datatype/datatype_definition.h" #include "../../circular_fifo_lib/circular_fifo_lib.h" #include "sdfactor_p1.h" /* ======================================== Declare Extern Channal Variables ======================================== */ /* Input FIFO */ extern circular_fifo_UInt32 fifo_s6; extern circular_fifo_UInt32 fifo_s_in; /* Output FIFO */ extern circular_fifo_UInt32 fifo_s1; /* ======================================== Declare Extern Global Variables ======================================== */ /* ======================================== Actor Function ======================================== */ void actor_p1(){ /* initialize memory*/ UInt32 s6; Array2OfUInt32Type s_in; UInt32 s1; /* Read From Input Port */ int ret=0; read_fifo_UInt32(&fifo_s_in, s_in,2); read_fifo_UInt32(&fifo_s6, &s6,1); printf("p1 reads s_in: %d, %d\n",s_in[0],s_in[1]); /* Inline Code */ /* in combFunction p1Body */ s1=s_in[0]+s_in[1]+s6; /* Write To Output Ports */ write_fifo_UInt32(&fifo_s1,&s1,1); }
20.339623
54
0.518553
1e61cfded76c568936168898496760e67d85357f
1,609
h
C
Archived/v1/WCDistractionFreeXcodePlugin/Headers/Frameworks/IDEKit/IDEPatchDraggingController.h
wokalski/Distraction-Free-Xcode-plugin
54ab4b9d9825e8370855b7985d6ff39d64c19f25
[ "MIT" ]
25
2016-03-03T07:43:56.000Z
2021-09-05T08:47:40.000Z
Frameworks/IDEKit/IDEPatchDraggingController.h
cameroncooke/XcodeHeaders
be955d30b5fc62c4312b354045b4561d164ebd9c
[ "MIT" ]
8
2016-02-23T18:40:20.000Z
2016-08-18T13:21:05.000Z
Frameworks/IDEKit/IDEPatchDraggingController.h
cameroncooke/XcodeHeaders
be955d30b5fc62c4312b354045b4561d164ebd9c
[ "MIT" ]
4
2016-02-24T13:24:27.000Z
2016-06-28T12:50:36.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" #import "NSDraggingSource.h" @class DVTComparisonDocumentLocation, DVTFilePath, IDEWorkspace, IDEWorkspaceTabController, NSArray, NSString; @interface IDEPatchDraggingController : NSObject <NSDraggingSource> { DVTFilePath *_droppingDestination; NSArray *_diffDescriptors; DVTComparisonDocumentLocation *_comparisonLocation; IDEWorkspaceTabController *_tabController; IDEWorkspace *_workspace; } + (id)patchExtension; @property(readonly) IDEWorkspace *workspace; // @synthesize workspace=_workspace; @property(retain) IDEWorkspaceTabController *tabController; // @synthesize tabController=_tabController; @property(readonly) DVTComparisonDocumentLocation *comparisonLocation; // @synthesize comparisonLocation=_comparisonLocation; @property(readonly) NSArray *diffDescriptors; // @synthesize diffDescriptors=_diffDescriptors; - (void).cxx_destruct; - (void)draggingSession:(id)arg1 endedAtPoint:(struct CGPoint)arg2 operation:(unsigned long long)arg3; - (id)namesOfPromisedFilesDroppedAtDestination:(id)arg1; - (unsigned long long)draggingSession:(id)arg1 sourceOperationMaskForDraggingContext:(long long)arg2; - (id)initWithDiffDescriptors:(id)arg1 comparisonDocumentLocation:(id)arg2 inWorkspace:(id)arg3; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
39.243902
125
0.799876
37bdff0c8040b9842f0cf3c43dd8c145d55468a2
5,594
c
C
app/src/main/jni/tests/dim/testdim.c
tsndongo/TO52_eCare_NoteLayout
2bcd6004e61a39a975e4d16e23ed0e23692f104e
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/tests/dim/testdim.c
tsndongo/TO52_eCare_NoteLayout
2bcd6004e61a39a975e4d16e23ed0e23692f104e
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/tests/dim/testdim.c
tsndongo/TO52_eCare_NoteLayout
2bcd6004e61a39a975e4d16e23ed0e23692f104e
[ "Apache-2.0" ]
null
null
null
/********************************************************************** * Copyright (C) 2010 Signove Tecnologia Corporation. * All rights reserved. * Contact: Signove Tecnologia Corporation (contact@signove.com) * * $LICENSE_TEXT:BEGIN$ * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation and appearing * in the file LICENSE included in the packaging of this file; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * $LICENSE_TEXT:END$ * * test_dim.c * * Created on: Jun 11, 2010 * Author: fabricio.silva **********************************************************************/ #ifdef TEST_ENABLED #include "Basic.h" #include "src/asn1/phd_types.h" #include "src/dim/nomenclature.h" #include "src/dim/mds.h" #include "src/dim/scanner.h" #include "src/dim/peri_cfg_scanner.h" #include "src/dim/epi_cfg_scanner.h" #include "src/dim/cfg_scanner.h" #include "src/dim/metric.h" #include "src/dim/numeric.h" #include "src/dim/rtsa.h" #include "src/dim/pmstore.h" #include "src/dim/pmsegment.h" #include "src/dim/enumeration.h" #include "src/dim/rtsa.h" #include "testdim.h" #include <stdlib.h> int test_dim_init_suite(void) { return 0; } int test_dim_finish_suite(void) { return 0; } void testdim_add_suite() { CU_pSuite suite = CU_add_suite("DIM Test Suite", test_dim_init_suite, test_dim_finish_suite); /* Add tests here - Start */ CU_add_test(suite, "test_dim_mds_initialization", test_dim_mds_initialization); CU_add_test(suite, "test_dim_scanner_initialization", test_dim_scanner_initialization); CU_add_test(suite, "test_dim_cfg_scanner_initialization", test_dim_cfg_scanner_initialization); CU_add_test(suite, "test_dim_peri_cfg_scanner_initialization", test_dim_peri_cfg_scanner_initialization); CU_add_test(suite, "test_dim_epi_cfg_scanner_initialization", test_dim_epi_cfg_scanner_initialization); CU_add_test(suite, "test_dim_metric_initialization", test_dim_metric_initialization); /* Add tests here - End */ } void test_dim_mds_initialization(void) { MDS *mds = mds_create(); CU_ASSERT_PTR_NOT_NULL(mds); CU_ASSERT_EQUAL(mds->dim.id, MDC_MOC_VMS_MDS_SIMP); mds_destroy(mds); } void test_dim_scanner_initialization(void) { HANDLE handle = 0; OperationalState state = 0; struct Scanner *sc = scanner_instance(handle, state); CU_ASSERT_PTR_NOT_NULL(sc); CU_ASSERT_EQUAL(sc->dim.id, MDC_MOC_SCAN); free(sc); } void test_dim_cfg_scanner_initialization(void) { HANDLE handle = 0; OperationalState state = 0; struct Scanner *sc = scanner_instance(handle, state); ConfirmMode mode = 0; struct CfgScanner *cfg = cfg_scanner_instance(sc, mode); CU_ASSERT_PTR_NOT_NULL(cfg); CU_ASSERT_EQUAL(cfg->dim.id, MDC_MOC_SCAN_CFG); free(cfg); free(sc); } void test_dim_peri_cfg_scanner_initialization(void) { HANDLE handle = 0; OperationalState state = 0; struct Scanner *sc = scanner_instance(handle, state); ConfirmMode mode = 0; struct CfgScanner *cfg_scanner = cfg_scanner_instance(sc, mode); struct PeriCfgScanner *peri = peri_cfg_scanner_instance(cfg_scanner); CU_ASSERT_PTR_NOT_NULL(peri); CU_ASSERT_EQUAL(peri->dim.id, MDC_MOC_SCAN_CFG_PERI); free(peri); free(cfg_scanner); free(sc); } void test_dim_epi_cfg_scanner_initialization(void) { HANDLE handle = 0; OperationalState state = 0; struct Scanner *sc = scanner_instance(handle, state); ConfirmMode mode = 0; struct CfgScanner *cfg_scanner = cfg_scanner_instance(sc, mode); struct EpiCfgScanner *epi = epi_cfg_scanner_instance(cfg_scanner); CU_ASSERT_PTR_NOT_NULL(epi); CU_ASSERT_EQUAL(epi->dim.id, MDC_MOC_SCAN_CFG_EPI); free(epi); free(cfg_scanner); free(sc); } void test_dim_metric_initialization(void) { HANDLE handle = 0; MetricSpecSmall small = 0; TYPE type; struct Metric *metric = metric_instance(handle, type, small); CU_ASSERT_PTR_NOT_NULL(metric); CU_ASSERT_EQUAL(metric->dim.id, MDC_MOC_VMO_METRIC); struct Numeric *num = numeric_instance(metric); CU_ASSERT_PTR_NOT_NULL(num); CU_ASSERT_EQUAL(num->dim.id, MDC_MOC_VMO_METRIC_NU); free(num); struct Enumeration *enum_ = enumeration_instance(metric); CU_ASSERT_PTR_NOT_NULL(enum_); CU_ASSERT_EQUAL(enum_->dim.id, MDC_MOC_VMO_METRIC_ENUM); free(enum_); RelativeTime sample = 0; octet_string simple; ScaleRangeSpec8 scale8; ScaleRangeSpec16 scale16; ScaleRangeSpec32 scale32; SaSpec sa; struct RTSA *rtsa8 = rtsa_instance_spec8(metric, sample, simple, scale8, sa); CU_ASSERT_PTR_NOT_NULL(rtsa8); CU_ASSERT_EQUAL(rtsa8->dim.id, MDC_MOC_VMO_METRIC_SA_RT); free(rtsa8); struct RTSA *rtsa16 = rtsa_instance_spec16(metric, sample, simple, scale16, sa); CU_ASSERT_PTR_NOT_NULL(rtsa16); CU_ASSERT_EQUAL(rtsa16->dim.id, MDC_MOC_VMO_METRIC_SA_RT); free(rtsa16); struct RTSA *rtsa32 = rtsa_instance_spec32(metric, sample, simple, scale32, sa); CU_ASSERT_PTR_NOT_NULL(rtsa32); CU_ASSERT_EQUAL(rtsa32->dim.id, MDC_MOC_VMO_METRIC_SA_RT); free(rtsa32); free(metric); } #endif
26.386792
81
0.746872
53732dff69d026f4186ec03a9aa419436ddc7a3d
1,806
c
C
0x14-sockets/server.c
Samhaydarr/holbertonschool-c
d0384a27dc105cbce8f990568792ba03e99026f9
[ "Apache-2.0" ]
null
null
null
0x14-sockets/server.c
Samhaydarr/holbertonschool-c
d0384a27dc105cbce8f990568792ba03e99026f9
[ "Apache-2.0" ]
null
null
null
0x14-sockets/server.c
Samhaydarr/holbertonschool-c
d0384a27dc105cbce8f990568792ba03e99026f9
[ "Apache-2.0" ]
null
null
null
#include "http.h" /** * start_server - opens & binds inet socket and accepts messages * Return: EXIT_SUCCESS or EXIT_FAILURE */ int start_server(void) { struct sockaddr_in server; int sd; setbuf(stdout, NULL); sd = socket(PF_INET, SOCK_STREAM, 0); if (sd < 0) { perror("socket failed"); return (EXIT_FAILURE); } server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sd, (struct sockaddr *)&server, sizeof(server)) < 0) { perror("bind failure"); return (EXIT_FAILURE); } if (listen(sd, BACKLOG) < 0) { perror("listen failure"); return (EXIT_FAILURE); } printf("Server listening on port %d\n", ntohs(server.sin_port)); while (1) accept_messages(sd); close(sd); } /** * accept_messages - accepts messages from server socket * @sd: the server socket * Return: SUCCESS or FAILURE */ int accept_messages(int sd) { int client_sd; struct sockaddr_in client; socklen_t client_size = sizeof(client); char buf[BUF_SIZE + 1] = {0}; ssize_t bytes_read; client_sd = accept(sd, (struct sockaddr *)&client, &client_size); if (client_sd < 0) { perror("accept failure"); return (EXIT_FAILURE); } inet_ntop(AF_INET, &client.sin_addr, buf, INET_ADDRSTRLEN); printf("Client connected: %s\n", buf); buf[0] = 0; bytes_read = recv(client_sd, buf, BUF_SIZE, 0); if (bytes_read > 0) { buf[bytes_read] = 0; printf("Raw request: \"%s\"\n", buf); parse_request(client_sd, buf); } close(client_sd); return (EXIT_SUCCESS); } /** * send_response - sends response back to client * @client_sd: client socket descriptor * @response: the response message * Return: 0 on success else 1 */ int send_response(int client_sd, char *response) { send(client_sd, response, strlen(response), 0); return (0); }
21.5
66
0.686047
bb13d089bc8fd78b403ef1fafa2739959886b10e
19,491
c
C
sbin/umount/umount.c
ivadasz/DragonFlyBSD
460227f342554313be3c7728ff679dd4a556cce9
[ "BSD-3-Clause" ]
1
2016-05-03T05:46:32.000Z
2016-05-03T05:46:32.000Z
sbin/umount/umount.c
ivadasz/DragonFlyBSD
460227f342554313be3c7728ff679dd4a556cce9
[ "BSD-3-Clause" ]
null
null
null
sbin/umount/umount.c
ivadasz/DragonFlyBSD
460227f342554313be3c7728ff679dd4a556cce9
[ "BSD-3-Clause" ]
null
null
null
/*- * Copyright (c) 1980, 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. 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. * * @(#) Copyright (c) 1980, 1989, 1993 The Regents of the University of California. All rights reserved. * @(#)umount.c 8.8 (Berkeley) 5/8/95 * $FreeBSD: src/sbin/umount/umount.c,v 1.28 2001/10/13 02:04:54 iedowse Exp $ */ #include <sys/param.h> #include <sys/mount.h> #include <sys/socket.h> #include <netdb.h> #include <rpc/rpc.h> #include <nfs/rpcv2.h> #include <err.h> #include <fstab.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "mounttab.h" #define ISDOT(x) ((x)[0] == '.' && (x)[1] == '\0') #define ISDOTDOT(x) ((x)[0] == '.' && (x)[1] == '.' && (x)[2] == '\0') typedef enum { MNTON, MNTFROM, NOTHING } mntwhat; typedef enum { MARK, UNMARK, NAME, COUNT, FREE } dowhat; struct addrinfo *nfshost_ai = NULL; int fflag, vflag; char *nfshost; void checkmntlist (char *, char **, char **, char **); int checkvfsname (const char *, char **); char *getmntname (const char *, const char *, mntwhat, char **, dowhat); char *getrealname(char *, char *resolved_path); char **makevfslist (const char *); int mntinfo (struct statfs **); int namematch (struct addrinfo *); int sacmp (struct sockaddr *, struct sockaddr *); int umountall (char **); int checkname (char *, char **); int umountfs (char *, char *, char *); void usage (void); int xdr_dir (XDR *, char *); int main(int argc, char *argv[]) { int all, errs, ch, mntsize, error; char **typelist = NULL, *mntonname, *mntfromname; char *type, *mntfromnamerev, *mntonnamerev; struct statfs *mntbuf; struct addrinfo hints; all = errs = 0; while ((ch = getopt(argc, argv, "AaF:fh:t:v")) != -1) { switch (ch) { case 'A': all = 2; break; case 'a': all = 1; break; case 'F': setfstab(optarg); break; case 'f': fflag = MNT_FORCE; break; case 'h': /* -h implies -A. */ all = 2; nfshost = optarg; break; case 't': if (typelist != NULL) err(1, "only one -t option may be specified"); typelist = makevfslist(optarg); break; case 'v': vflag = 1; break; default: usage(); /* NOTREACHED */ } } argc -= optind; argv += optind; if ((argc == 0 && !all) || (argc != 0 && all)) usage(); /* -h implies "-t nfs" if no -t flag. */ if ((nfshost != NULL) && (typelist == NULL)) typelist = makevfslist("nfs"); if (nfshost != NULL) { memset(&hints, 0, sizeof hints); error = getaddrinfo(nfshost, NULL, &hints, &nfshost_ai); if (error) errx(1, "%s: %s", nfshost, gai_strerror(error)); } switch (all) { case 2: if ((mntsize = mntinfo(&mntbuf)) <= 0) break; /* * We unmount the nfs-mounts in the reverse order * that they were mounted. */ for (errs = 0, mntsize--; mntsize > 0; mntsize--) { if (checkvfsname(mntbuf[mntsize].f_fstypename, typelist)) continue; /* * Check if a mountpoint is laid over by another mount. * A warning will be printed to stderr if this is * the case. The laid over mount remains unmounted. */ mntonname = mntbuf[mntsize].f_mntonname; mntfromname = mntbuf[mntsize].f_mntfromname; mntonnamerev = getmntname(getmntname(mntonname, NULL, MNTFROM, &type, NAME), NULL, MNTON, &type, NAME); mntfromnamerev = getmntname(mntonnamerev, NULL, MNTFROM, &type, NAME); if (strcmp(mntonnamerev, mntonname) == 0 && strcmp(mntfromnamerev, mntfromname ) != 0) warnx("cannot umount %s, %s\n " "is mounted there, umount it first", mntonname, mntfromnamerev); if (checkname(mntbuf[mntsize].f_mntonname, typelist) != 0) errs = 1; } free(mntbuf); break; case 1: if (setfsent() == 0) err(1, "%s", getfstab()); errs = umountall(typelist); break; case 0: for (errs = 0; *argv != NULL; ++argv) if (checkname(*argv, typelist) != 0) errs = 1; break; } getmntname(NULL, NULL, NOTHING, NULL, FREE); exit(errs); } int umountall(char **typelist) { struct vfsconf vfc; struct fstab *fs; int rval; char *cp; static int firstcall = 1; if ((fs = getfsent()) != NULL) firstcall = 0; else if (firstcall) errx(1, "fstab reading failure"); else return (0); do { /* Ignore the root. */ if (strcmp(fs->fs_file, "/") == 0) continue; /* * !!! * Historic practice: ignore unknown FSTAB_* fields. */ if (strcmp(fs->fs_type, FSTAB_RW) && strcmp(fs->fs_type, FSTAB_RO) && strcmp(fs->fs_type, FSTAB_RQ)) continue; /* Ignore unknown file system types. */ if (getvfsbyname(fs->fs_vfstype, &vfc) == -1) continue; if (checkvfsname(fs->fs_vfstype, typelist)) continue; /* * We want to unmount the file systems in the reverse order * that they were mounted. So, we save off the file name * in some allocated memory, and then call recursively. */ if ((cp = malloc((size_t)strlen(fs->fs_file) + 1)) == NULL) err(1, "malloc failed"); strcpy(cp, fs->fs_file); rval = umountall(typelist); rval = checkname(cp, typelist) || rval; free(cp); return (rval); } while ((fs = getfsent()) != NULL); return (0); } /* * Do magic checks on mountpoint and device or hand over * it to unmount(2) if everything fails. */ int checkname(char *name, char **typelist) { size_t len; int speclen; char *mntonname, *mntfromname; char *mntfromnamerev; char *resolved, realname[MAXPATHLEN]; char *type, *hostp, *delimp, *origname; char none[] = "none"; len = 0; mntfromname = mntonname = delimp = hostp = NULL; /* * 1. Check if the name exists in the mounttable. */ checkmntlist(name, &mntfromname, &mntonname, &type); if (mntfromname == NULL && mntonname == NULL) { checkmntlist(getdevpath(name, 0), &mntfromname, &mntonname, &type); } /* * 2. Remove trailing slashes if there are any. After that * we look up the name in the mounttable again. */ if (mntfromname == NULL && mntonname == NULL) { speclen = strlen(name); for (speclen = strlen(name); speclen > 1 && name[speclen - 1] == '/'; speclen--) name[speclen - 1] = '\0'; checkmntlist(name, &mntfromname, &mntonname, &type); resolved = name; /* Save off original name in origname */ if ((origname = strdup(name)) == NULL) err(1, "strdup"); /* * 3. Check if the deprecated nfs-syntax with an '@' * has been used and translate it to the ':' syntax. * Look up the name in the mounttable again. */ if (mntfromname == NULL && mntonname == NULL) { if ((delimp = strrchr(name, '@')) != NULL) { hostp = delimp + 1; if (*hostp != '\0') { /* * Make both '@' and ':' * notations equal */ char *host = strdup(hostp); len = strlen(hostp); if (host == NULL) err(1, "strdup"); memmove(name + len + 1, name, (size_t)(delimp - name)); name[len] = ':'; memmove(name, host, len); free(host); } for (speclen = strlen(name); speclen > 1 && name[speclen - 1] == '/'; speclen--) name[speclen - 1] = '\0'; name[len + speclen + 1] = '\0'; checkmntlist(name, &mntfromname, &mntonname, &type); resolved = name; } /* * 4. Check if a relative mountpoint has been * specified. This should happen as last check, * the order is important. To prevent possible * nfs-hangs, we just call realpath(3) on the * basedir of mountpoint and add the dirname again. * Check the name in mounttable one last time. */ if (mntfromname == NULL && mntonname == NULL) { strcpy(name, origname); if ((getrealname(name, realname)) != NULL) { checkmntlist(realname, &mntfromname, &mntonname, &type); resolved = realname; } /* * 5. All tests failed, just hand over the * mountpoint to the kernel, maybe the statfs * structure has been truncated or is not * useful anymore because of a chroot(2). * Please note that nfs will not be able to * notify the nfs-server about unmounting. * These things can change in future when the * fstat structure get's more reliable, * but at the moment we cannot thrust it. */ if (mntfromname == NULL && mntonname == NULL) { strcpy(name, origname); if (umountfs(NULL, origname, none) == 0) { warnx("%s not found in " "mount table, " "unmounted it anyway", origname); free(origname); return (0); } else free(origname); return (1); } } } free(origname); } else resolved = name; if (checkvfsname(type, typelist)) return (1); /* * Check if the reverse entrys of the mounttable are really the * same as the normal ones. */ if ((mntfromnamerev = strdup(getmntname(getmntname(mntfromname, NULL, MNTON, &type, NAME), NULL, MNTFROM, &type, NAME))) == NULL) err(1, "strdup"); /* * Mark the uppermost mount as unmounted. */ getmntname(mntfromname, mntonname, NOTHING, &type, MARK); /* * If several equal mounts are in the mounttable, check the order * and warn the user if necessary. */ if (strcmp(mntfromnamerev, mntfromname ) != 0 && strcmp(resolved, mntonname) != 0) { warnx("cannot umount %s, %s\n " "is mounted there, umount it first", mntonname, mntfromnamerev); /* call getmntname again to set mntcheck[i] to 0 */ getmntname(mntfromname, mntonname, NOTHING, &type, UNMARK); return (1); } free(mntfromnamerev); return (umountfs(mntfromname, mntonname, type)); } /* * NFS stuff and unmount(2) call */ int umountfs(char *mntfromname, char *mntonname, char *type) { enum clnt_stat clnt_stat; struct timeval try; struct addrinfo *ai, hints; int do_rpc; CLIENT *clp; char *nfsdirname, *orignfsdirname; char *hostp, *delimp; ai = NULL; do_rpc = 0; hostp = NULL; nfsdirname = delimp = orignfsdirname = NULL; memset(&hints, 0, sizeof hints); if (strcmp(type, "nfs") == 0) { if ((nfsdirname = strdup(mntfromname)) == NULL) err(1, "strdup"); orignfsdirname = nfsdirname; if ((delimp = strrchr(nfsdirname, ':')) != NULL) { *delimp = '\0'; hostp = nfsdirname; getaddrinfo(hostp, NULL, &hints, &ai); if (ai == NULL) { warnx("can't get net id for host"); } nfsdirname = delimp + 1; } /* * Check if we have to start the rpc-call later. * If there are still identical nfs-names mounted, * we skip the rpc-call. Obviously this has to * happen before unmount(2), but it should happen * after the previous namecheck. * A non-NULL return means that this is the last * mount from mntfromname that is still mounted. */ if (getmntname(mntfromname, NULL, NOTHING, &type, COUNT) != NULL) do_rpc = 1; } if (!namematch(ai)) return (1); if (unmount(mntonname, fflag) != 0 ) { warn("unmount of %s failed", mntonname); return (1); } if (vflag) printf("%s: unmount from %s\n", mntfromname, mntonname); /* * Report to mountd-server which nfsname * has been unmounted. */ if (ai != NULL && !(fflag & MNT_FORCE) && do_rpc) { clp = clnt_create(hostp, RPCPROG_MNT, RPCMNT_VER1, "udp"); if (clp == NULL) { warnx("%s: %s", hostp, clnt_spcreateerror("RPCPROG_MNT")); return (1); } clp->cl_auth = authsys_create_default(); try.tv_sec = 20; try.tv_usec = 0; clnt_stat = clnt_call(clp, RPCMNT_UMOUNT, (xdrproc_t)xdr_dir, nfsdirname, (xdrproc_t)xdr_void, (caddr_t)0, try); if (clnt_stat != RPC_SUCCESS) { warnx("%s: %s", hostp, clnt_sperror(clp, "RPCMNT_UMOUNT")); return (1); } /* * Remove the unmounted entry from /var/db/mounttab. */ if (read_mtab()) { clean_mtab(hostp, nfsdirname, vflag); if(!write_mtab(vflag)) warnx("cannot remove mounttab entry %s:%s", hostp, nfsdirname); free_mtab(); } free(orignfsdirname); auth_destroy(clp->cl_auth); clnt_destroy(clp); } return (0); } char * getmntname(const char *fromname, const char *onname, mntwhat what, char **type, dowhat mark) { static struct statfs *mntbuf; static int mntsize = 0; static char *mntcheck = NULL; static char *mntcount = NULL; int i, count; if (mntsize <= 0) { if ((mntsize = mntinfo(&mntbuf)) <= 0) return (NULL); } if (mntcheck == NULL) { if ((mntcheck = calloc(mntsize + 1, sizeof(int))) == NULL || (mntcount = calloc(mntsize + 1, sizeof(int))) == NULL) err(1, "calloc"); } /* * We want to get the file systems in the reverse order * that they were mounted. Mounted and unmounted filesystems * are marked or unmarked in a table called 'mntcheck'. * Unmount(const char *dir, int flags) does only take the * mountpoint as argument, not the destination. If we don't pay * attention to the order, it can happen that a overlaying * filesystem get's unmounted instead of the one the user * has choosen. */ switch (mark) { case NAME: /* Return only the specific name */ for (i = mntsize - 1; i >= 0; i--) { if (fromname != NULL && what == MNTON && !strcmp(mntbuf[i].f_mntfromname, fromname) && mntcheck[i] != 1) { if (type) *type = mntbuf[i].f_fstypename; return (mntbuf[i].f_mntonname); } if (fromname != NULL && what == MNTFROM && !strcmp(mntbuf[i].f_mntonname, fromname) && mntcheck[i] != 1) { if (type) *type = mntbuf[i].f_fstypename; return (mntbuf[i].f_mntfromname); } } return (NULL); case MARK: /* Mark current mount with '1' and return name */ for (i = mntsize - 1; i >= 0; i--) { if (mntcheck[i] == 0 && (strcmp(mntbuf[i].f_mntonname, onname) == 0) && (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)) { mntcheck[i] = 1; return (mntbuf[i].f_mntonname); } } return (NULL); case UNMARK: /* Unmark current mount with '0' and return name */ for (i = 0; i < mntsize; i++) { if (mntcheck[i] == 1 && (strcmp(mntbuf[i].f_mntonname, onname) == 0) && (strcmp(mntbuf[i].f_mntfromname, fromname) == 0)) { mntcheck[i] = 0; return (mntbuf[i].f_mntonname); } } return (NULL); case COUNT: /* Count the equal mntfromnames */ count = 0; for (i = mntsize - 1; i >= 0; i--) { if (strcmp(mntbuf[i].f_mntfromname, fromname) == 0) count++; } /* Mark the already unmounted mounts and return * mntfromname if count <= 1. Else return NULL. */ for (i = mntsize - 1; i >= 0; i--) { if (strcmp(mntbuf[i].f_mntfromname, fromname) == 0) { if (mntcount[i] == 1) count--; else { mntcount[i] = 1; break; } } } if (count <= 1) return (mntbuf[i].f_mntonname); else return (NULL); case FREE: free(mntbuf); free(mntcheck); free(mntcount); return (NULL); default: return (NULL); } } int sacmp(struct sockaddr *sa1, struct sockaddr *sa2) { void *p1, *p2; int len; if (sa1->sa_family != sa2->sa_family) return (1); switch (sa1->sa_family) { case AF_INET: p1 = &((struct sockaddr_in *)sa1)->sin_addr; p2 = &((struct sockaddr_in *)sa2)->sin_addr; len = 4; break; case AF_INET6: p1 = &((struct sockaddr_in6 *)sa1)->sin6_addr; p2 = &((struct sockaddr_in6 *)sa2)->sin6_addr; len = 16; if (((struct sockaddr_in6 *)sa1)->sin6_scope_id != ((struct sockaddr_in6 *)sa2)->sin6_scope_id) return (1); break; default: return (1); } return memcmp(p1, p2, len); } int namematch(struct addrinfo *ai) { struct addrinfo *aip; if (nfshost == NULL || nfshost_ai == NULL) return (1); while (ai != NULL) { aip = nfshost_ai; while (aip != NULL) { if (sacmp(ai->ai_addr, aip->ai_addr) == 0) return (1); aip = aip->ai_next; } ai = ai->ai_next; } return (0); } void checkmntlist(char *name, char **fromname, char **onname, char **type) { *fromname = getmntname(name, NULL, MNTFROM, type, NAME); if (*fromname == NULL) { *onname = getmntname(name, NULL, MNTON, type, NAME); if (*onname != NULL) *fromname = name; } else *onname = name; } int mntinfo(struct statfs **mntbuf) { static struct statfs *origbuf; size_t bufsize; int mntsize; mntsize = getfsstat(NULL, 0, MNT_NOWAIT); if (mntsize <= 0) return (0); bufsize = (mntsize + 1) * sizeof(struct statfs); if ((origbuf = malloc(bufsize)) == NULL) err(1, "malloc"); mntsize = getfsstat(origbuf, (long)bufsize, MNT_NOWAIT); *mntbuf = origbuf; return (mntsize); } char * getrealname(char *name, char *realname) { char *dirname; int havedir; size_t baselen; size_t dirlen; dirname = NULL; havedir = 0; if (*name == '/') { if (ISDOT(name + 1) || ISDOTDOT(name + 1)) strcpy(realname, "/"); else { if ((dirname = strrchr(name + 1, '/')) == NULL) snprintf(realname, MAXPATHLEN, "%s", name); else havedir = 1; } } else { if (ISDOT(name) || ISDOTDOT(name)) realpath(name, realname); else { if ((dirname = strrchr(name, '/')) == NULL) { if ((realpath(name, realname)) == NULL) return (NULL); } else havedir = 1; } } if (havedir) { *dirname++ = '\0'; if (ISDOT(dirname)) { *dirname = '\0'; if ((realpath(name, realname)) == NULL) return (NULL); } else if (ISDOTDOT(dirname)) { *--dirname = '/'; if ((realpath(name, realname)) == NULL) return (NULL); } else { if ((realpath(name, realname)) == NULL) return (NULL); baselen = strlen(realname); dirlen = strlen(dirname); if (baselen + dirlen + 1 > MAXPATHLEN) return (NULL); if (realname[1] == '\0') { memmove(realname + 1, dirname, dirlen); realname[dirlen + 1] = '\0'; } else { realname[baselen] = '/'; memmove(realname + baselen + 1, dirname, dirlen); realname[baselen + dirlen + 1] = '\0'; } } } return (realname); } /* * xdr routines for mount rpc's */ int xdr_dir(XDR *xdrsp, char *dirp) { return (xdr_string(xdrsp, &dirp, RPCMNT_PATHLEN)); } void usage(void) { fprintf(stderr, "%s\n%s\n", "usage: umount [-fv] special | node", " umount -a | -A [-F fstab] [-fv] [-h host] [-t type]"); exit(1); }
25.988
105
0.618696
765914c7e269f03adf1d1d9ead59bd21d2f86ee8
3,499
h
C
BBB-firmware/u-boot-v2018.05-rc2/arch/arm/include/asm/armv8/mmu.h
guileschool/BEAGLEBONE-tutorials
eecd83e0c14941b05ad38eeb77e5a50602cc29ca
[ "MIT" ]
4
2018-09-28T04:33:26.000Z
2021-03-10T06:29:55.000Z
BBB-firmware/u-boot-v2018.05-rc2/arch/arm/include/asm/armv8/mmu.h
guileschool/BEAGLEBONE-tutorials
eecd83e0c14941b05ad38eeb77e5a50602cc29ca
[ "MIT" ]
4
2016-08-30T11:30:25.000Z
2020-12-27T09:58:07.000Z
BBB-firmware/u-boot-v2018.05-rc2/arch/arm/include/asm/armv8/mmu.h
guileschool/BEAGLEBONE-tutorials
eecd83e0c14941b05ad38eeb77e5a50602cc29ca
[ "MIT" ]
2
2016-12-30T08:02:57.000Z
2020-05-16T05:59:30.000Z
/* * (C) Copyright 2013 * David Feng <fenghua@phytium.com.cn> * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef _ASM_ARMV8_MMU_H_ #define _ASM_ARMV8_MMU_H_ /* * block/section address mask and size definitions. */ /* PAGE_SHIFT determines the page size */ #undef PAGE_SIZE #define PAGE_SHIFT 12 #define PAGE_SIZE (1 << PAGE_SHIFT) #define PAGE_MASK (~(PAGE_SIZE - 1)) /***************************************************************/ /* * Memory types */ #define MT_DEVICE_NGNRNE 0 #define MT_DEVICE_NGNRE 1 #define MT_DEVICE_GRE 2 #define MT_NORMAL_NC 3 #define MT_NORMAL 4 #define MEMORY_ATTRIBUTES ((0x00 << (MT_DEVICE_NGNRNE * 8)) | \ (0x04 << (MT_DEVICE_NGNRE * 8)) | \ (0x0c << (MT_DEVICE_GRE * 8)) | \ (0x44 << (MT_NORMAL_NC * 8)) | \ (UL(0xff) << (MT_NORMAL * 8))) /* * Hardware page table definitions. * */ #define PTE_TYPE_MASK (3 << 0) #define PTE_TYPE_FAULT (0 << 0) #define PTE_TYPE_TABLE (3 << 0) #define PTE_TYPE_PAGE (3 << 0) #define PTE_TYPE_BLOCK (1 << 0) #define PTE_TYPE_VALID (1 << 0) #define PTE_TABLE_PXN (1UL << 59) #define PTE_TABLE_XN (1UL << 60) #define PTE_TABLE_AP (1UL << 61) #define PTE_TABLE_NS (1UL << 63) /* * Block */ #define PTE_BLOCK_MEMTYPE(x) ((x) << 2) #define PTE_BLOCK_NS (1 << 5) #define PTE_BLOCK_NON_SHARE (0 << 8) #define PTE_BLOCK_OUTER_SHARE (2 << 8) #define PTE_BLOCK_INNER_SHARE (3 << 8) #define PTE_BLOCK_AF (1 << 10) #define PTE_BLOCK_NG (1 << 11) #define PTE_BLOCK_PXN (UL(1) << 53) #define PTE_BLOCK_UXN (UL(1) << 54) /* * AttrIndx[2:0] */ #define PMD_ATTRINDX(t) ((t) << 2) #define PMD_ATTRINDX_MASK (7 << 2) #define PMD_ATTRMASK (PTE_BLOCK_PXN | \ PTE_BLOCK_UXN | \ PMD_ATTRINDX_MASK | \ PTE_TYPE_VALID) /* * TCR flags. */ #define TCR_T0SZ(x) ((64 - (x)) << 0) #define TCR_IRGN_NC (0 << 8) #define TCR_IRGN_WBWA (1 << 8) #define TCR_IRGN_WT (2 << 8) #define TCR_IRGN_WBNWA (3 << 8) #define TCR_IRGN_MASK (3 << 8) #define TCR_ORGN_NC (0 << 10) #define TCR_ORGN_WBWA (1 << 10) #define TCR_ORGN_WT (2 << 10) #define TCR_ORGN_WBNWA (3 << 10) #define TCR_ORGN_MASK (3 << 10) #define TCR_SHARED_NON (0 << 12) #define TCR_SHARED_OUTER (2 << 12) #define TCR_SHARED_INNER (3 << 12) #define TCR_TG0_4K (0 << 14) #define TCR_TG0_64K (1 << 14) #define TCR_TG0_16K (2 << 14) #define TCR_EPD1_DISABLE (1 << 23) #define TCR_EL1_RSVD (1 << 31) #define TCR_EL2_RSVD (1 << 31 | 1 << 23) #define TCR_EL3_RSVD (1 << 31 | 1 << 23) #ifndef __ASSEMBLY__ static inline void set_ttbr_tcr_mair(int el, u64 table, u64 tcr, u64 attr) { asm volatile("dsb sy"); if (el == 1) { asm volatile("msr ttbr0_el1, %0" : : "r" (table) : "memory"); asm volatile("msr tcr_el1, %0" : : "r" (tcr) : "memory"); asm volatile("msr mair_el1, %0" : : "r" (attr) : "memory"); } else if (el == 2) { asm volatile("msr ttbr0_el2, %0" : : "r" (table) : "memory"); asm volatile("msr tcr_el2, %0" : : "r" (tcr) : "memory"); asm volatile("msr mair_el2, %0" : : "r" (attr) : "memory"); } else if (el == 3) { asm volatile("msr ttbr0_el3, %0" : : "r" (table) : "memory"); asm volatile("msr tcr_el3, %0" : : "r" (tcr) : "memory"); asm volatile("msr mair_el3, %0" : : "r" (attr) : "memory"); } else { hang(); } asm volatile("isb"); } struct mm_region { u64 virt; u64 phys; u64 size; u64 attrs; }; extern struct mm_region *mem_map; void setup_pgtables(void); u64 get_tcr(int el, u64 *pips, u64 *pva_bits); #endif #endif /* _ASM_ARMV8_MMU_H_ */
25.172662
74
0.618177
763419642e8f1b8fc1db1eeaebd419bd54d5357c
872
h
C
System/Library/PrivateFrameworks/iTunesStore.framework/Support/itunesstored/GetAutomaticDownloadKindsOperation.h
lechium/tvOS130Headers
6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd
[ "MIT" ]
11
2019-11-06T04:48:48.000Z
2022-02-09T17:48:15.000Z
System/Library/PrivateFrameworks/iTunesStore.framework/Support/itunesstored/GetAutomaticDownloadKindsOperation.h
lechium/tvOS130Headers
6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd
[ "MIT" ]
1
2020-04-16T01:41:56.000Z
2020-04-16T04:32:00.000Z
System/Library/PrivateFrameworks/iTunesStore.framework/Support/itunesstored/GetAutomaticDownloadKindsOperation.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:47:22 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/PrivateFrameworks/iTunesStore.framework/Support/itunesstored * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <iTunesStore/ISOperation.h> @class SSAuthenticationContext, NSArray; @interface GetAutomaticDownloadKindsOperation : ISOperation { SSAuthenticationContext* _authContext; NSArray* _enabledDownloadKinds; } @property (copy) SSAuthenticationContext * authenticationContext; @property (readonly) NSArray * enabledDownloadKinds; -(void)dealloc; -(void)run; -(void)setAuthenticationContext:(SSAuthenticationContext *)arg1 ; -(SSAuthenticationContext *)authenticationContext; -(NSArray *)enabledDownloadKinds; @end
30.068966
92
0.798165
6f7921d63bef7e29f98bd7ab2f6c9e33406be76a
5,836
h
C
Include/MBE/Input/InputHandler.h
AdrianKoch3010/MarsBaseEngine
77bdd93c74caad0576b226c25ac4b0fe375f51be
[ "MIT" ]
4
2019-06-28T09:27:54.000Z
2020-04-10T03:24:35.000Z
Include/MBE/Input/InputHandler.h
AdrianKoch3010/MarsBaseEngine
77bdd93c74caad0576b226c25ac4b0fe375f51be
[ "MIT" ]
null
null
null
Include/MBE/Input/InputHandler.h
AdrianKoch3010/MarsBaseEngine
77bdd93c74caad0576b226c25ac4b0fe375f51be
[ "MIT" ]
1
2020-09-15T02:33:21.000Z
2020-09-15T02:33:21.000Z
#pragma once /// @file /// @brief Class mbe::InputHandler #include <map> #include <vector> #include <algorithm> #include <SFML/Window/Event.hpp> #include <SFML/Window/Window.hpp> #include <MBE/Core/EventManager.h> #include <MBE/Core/Utility.h> #include <MBE/Input/MouseButtonEvents.h> #include <MBE/Input/ActionEvents.h> using mbe::event::MouseButtonPressedEvent; using mbe::event::MouseButtonHoldEvent; using mbe::event::MouseButtonReleasedEvent; using mbe::event::ActionBaseEvent; using mbe::event::ActionPressedEvent; using mbe::event::ActionHoldEvent; using mbe::event::ActionReleasedEvent; namespace mbe { /// @brief Handels mouse and keyboard events as well as realtime input and raises respective events /// @details Furthermore, the input handler allows for subscribing keys to actions which allows for dynamic key bindings. /// @note The action strings are not case sensitive so capital letters don't matter. <b>Use ACII characters only!<b> /// When an action string or a list of action strings is returned, they are always normalised. To compare an action string, /// call mbe::NormaliseIDString() on it before the comparision. class InputHandler { public: /// @brief Default constructor InputHandler() = default; /// @brief Default destructor ~InputHandler() = default; /// @brief Raises respective events for mouse button events and any registered key released events /// @details This function should be called within the poll event loop of the window. /// It checks for mouse clicks and any registred key release events and raises the according /// events when they occur. Generally speaking the handleEvent method checks for changes in state. /// To check whether a key or mouse button is currently pressed use the mbe::InputHandler::HandleRealtimeInput() method. /// @param event A reference to the event that is currently polled in the poll event loop of the window. /// @param eventManager The EventManager which is used to raise the events void HandleEvent(const sf::Event & event, EventManager & eventManager); /// @brief Raises respective events for the mouse buttons or any registered keys that are currently pressed /// @details This function should not be called within the poll event loop of the window. /// Generally speaking, this function checks the current state. To check for changes in state (i.e. sf::Event) /// use the mbe::InputHandler::HandleEvent() method. /// @param eventManager The mbe::EventManager which is used to raise the events /// @param window The sf::Window to which the mouse position is relative to void HandleRealtimeInput(EventManager & eventManager, sf::Window & window); /// @brief Assigns a mouse button to an action /// @details More than one button can be assigned to the same action. /// A button cannot be assigned to multiple action. If done so the old assigned action binding /// will be overwritten. /// @param action The action that will be passed as data of one of the action events /// @param button The mouse button to be assigned /// @param isRealtimeInput If set to true, it is checked whether the button is pressed and /// events are raised in the HandleRealtimeInput method. If set to false, it is checked whether /// a mouse button released event has occured and events are raised in the HandleEvent() method. void AssignMouseButton(ActionBaseEvent::Action action, sf::Mouse::Button button, bool isRealTimeInput = false); /// @brief Returns a list of the mouse buttons assigned to the past in action /// @param action The action for which the buttons will be fetched /// @returns A list of buttons. If no buttons are assigned, an empty list will be returned std::vector<sf::Mouse::Button> GetAssignedMouseButtons(ActionBaseEvent::Action action) const; /// @brief Assigns a key to an action /// @details More than one key can be assigned to the same action. /// A key cannot be assigned to multiple action. If done so the old assigned action binding /// will be overwritten. /// @param action The action that will be passed as data of one of the action events /// @param key The key to be assigned /// @param isRealtimeInput If set to true, it is checked whether the key is pressed and /// events are raised in the HandleRealtimeInput method. If set to false, it is checked whether /// a key released event has occured and events are raised in the HandleEvent() method. void AssignKey(ActionBaseEvent::Action action, sf::Keyboard::Key key, bool isRealtimeInput = false); /// @brief Returns a list of the keys assigned to the past in action /// @param action The action for which the keys will be fetched /// @returns A list of keys. If no keys are assigned, an empty list will be returned std::vector<sf::Keyboard::Key> GetAssignedKeys(ActionBaseEvent::Action action) const; /// @brief Returns whether an action is active /// @details This method allows for checking directly whether a specific action is /// currently active. An action is active when one of the assigned mouse buttons or keys /// are pressed (sf::Mouse::isButtonPressed() or sf::Keyboard::isKeyPressed() returns true). /// If an action is active the respective mbe::event::ActionHoldEvent will also be raised. /// @param action The action that is checked for whether it is active / hold /// @returns True if the action is active / hold, flase otherwise bool IsActionActive(ActionBaseEvent::Action action) const; private: std::map<sf::Keyboard::Key, ActionBaseEvent::Action> eventKeyBindings; std::map<sf::Keyboard::Key, ActionBaseEvent::Action> realtimeInputKeyBindings; std::map<sf::Mouse::Button, ActionBaseEvent::Action> eventMouseButtonBindings; std::map<sf::Mouse::Button, ActionBaseEvent::Action> realtimeMouseButtonBindings; }; } // namespace mbe
54.037037
124
0.751542
c0d13da40de6cf9ab06c6a0b3e3464a19f716cb6
206
h
C
robot/hwhdrs/switch.h
kkevlar/bazelrobot
7b858a0513d6c8e4241641d9132b5d74a9a80ca5
[ "MIT" ]
1
2020-02-04T23:40:37.000Z
2020-02-04T23:40:37.000Z
robot/hwhdrs/switch.h
kkevlar/bazelrobot
7b858a0513d6c8e4241641d9132b5d74a9a80ca5
[ "MIT" ]
6
2019-12-23T02:31:25.000Z
2019-12-23T02:33:03.000Z
robot/hwhdrs/switch.h
kkevlar/roborodentia2020
7b858a0513d6c8e4241641d9132b5d74a9a80ca5
[ "MIT" ]
null
null
null
#ifndef SWITCH_H #define SWTICH_H #include "robottypes.h" void switch_init(void); pin_t switch_test_all(); bool switch_test_up(direction_t dir); bool switch_test_down(direction_t dir); #endif
17.166667
40
0.757282
9d95e094e154b34febb360fcee2dab875d000d2b
403
h
C
swig/structs/fibonacci.h
tleonhardt/Python_Interface_Cpp
398eab0c6e7f5e0358edb6644c71b5fdc6b2606a
[ "MIT" ]
64
2017-03-10T09:32:22.000Z
2022-01-25T08:44:06.000Z
swig/structs/fibonacci.h
tleonhardt/Python_Interface_Cpp
398eab0c6e7f5e0358edb6644c71b5fdc6b2606a
[ "MIT" ]
null
null
null
swig/structs/fibonacci.h
tleonhardt/Python_Interface_Cpp
398eab0c6e7f5e0358edb6644c71b5fdc6b2606a
[ "MIT" ]
13
2017-03-13T23:28:56.000Z
2021-06-07T08:37:03.000Z
/* File : fibonacci.h * * Header declaring the public interface. */ #pragma once #include <stdint.h> typedef uint32_t dtype; struct MsgMetaData { dtype type; // Message Type dtype job; // Job ID dtype size; // Message Size (not including the metadata header) }; extern int compute_fibonacci(int n); struct MsgMetaData populate_struct(dtype msgType, dtype jobId, dtype msgSize);
18.318182
78
0.709677
3e360c807c4be5a8ec642777ba4728b5249f03dd
4,019
h
C
ctp2_code/robotcom/backdoor/pool.h
xiaolanchong/call_to_power2
39f19d18b363cefb151bbbf050c6b672ee544117
[ "DOC" ]
null
null
null
ctp2_code/robotcom/backdoor/pool.h
xiaolanchong/call_to_power2
39f19d18b363cefb151bbbf050c6b672ee544117
[ "DOC" ]
null
null
null
ctp2_code/robotcom/backdoor/pool.h
xiaolanchong/call_to_power2
39f19d18b363cefb151bbbf050c6b672ee544117
[ "DOC" ]
null
null
null
#ifndef __Pool_h__ #define __Pool_h__ #include "common.h" #include "list_array.h" template <class DATA_TYPE> class list_array; #define INITIAL_CHUNK_LIST_SIZE (30) template <class DATA_TYPE> class Pool { public: Pool ( int i_chunk_size, int i_max_chunks = -1 ); ~Pool(); DATA_TYPE * Get_Next_Pointer(int & which_element_is_it); void Release_Pointer ( int ptr_to_free ); void Clear(); protected: DATA_TYPE * Get_Nth_Pointer ( int n ); bool Prepare_New_Chunk(); int chunk_size; int max_chunks; int count; int next_element; list_array<DATA_TYPE *> * chunks; list_array<int> *next_free_element_list; }; template <class DATA_TYPE> bool Pool<DATA_TYPE>::Prepare_New_Chunk() { DATA_TYPE *new_chunk; int i; int first_new_element; if (chunks->count is max_chunks) return false; new_chunk = new DATA_TYPE[chunk_size]; chunks->Append_Data(new_chunk); first_new_element = (chunks->count - 1) * chunk_size; for (i = first_new_element; i < first_new_element + chunk_size; i++) { next_free_element_list->Append_Data(i+1); } return true; } template <class DATA_TYPE> Pool<DATA_TYPE>::Pool ( int i_chunk_size, int i_max_chunks ) { _ASSERTE(i_chunk_size > 0); chunk_size = i_chunk_size; max_chunks = i_max_chunks; count = 0; chunks = new list_array<DATA_TYPE *> (INITIAL_CHUNK_LIST_SIZE); next_free_element_list = new list_array<int>(chunk_size, chunk_size, max_chunks); next_element = 0; Prepare_New_Chunk(); } template <class DATA_TYPE> Pool<DATA_TYPE>::~Pool() { DATA_TYPE *bad_chunk; int i; for (i = 0; i < chunks->count; i++) { bad_chunk = chunks->Return_Data_By_Number(i); delete[] bad_chunk; } delete chunks; delete next_free_element_list; } template <class DATA_TYPE> DATA_TYPE * Pool<DATA_TYPE>::Get_Next_Pointer(int & which_element_is_it) { DATA_TYPE *the_ptr; DATA_TYPE *the_chunk; int which_chunk; int which_element_in_chunk; count++; if (count > (chunks->count * chunk_size)) { if (not Prepare_New_Chunk()) { which_element_is_it = -1; return NULL; } } which_element_is_it = next_element; which_chunk = which_element_is_it/chunk_size; which_element_in_chunk = which_element_is_it - (which_chunk * chunk_size); the_chunk = chunks->Return_Data_By_Number(which_chunk); the_ptr = &(the_chunk[which_element_in_chunk]); next_element = next_free_element_list->Return_Data_By_Number(next_element); next_free_element_list->Set_Data(-1, which_element_is_it); #ifdef _DEBUG #endif return the_ptr; } template <class DATA_TYPE> void Pool<DATA_TYPE>::Release_Pointer ( int ptr_to_free ) { #ifdef _DEBUG #endif _ASSERTE(next_free_element_list->Return_Data_By_Number(ptr_to_free) is -1); #ifdef _DEBUG #endif next_free_element_list->Set_Data(next_element, ptr_to_free); next_element = ptr_to_free; count--; } template <class DATA_TYPE> void Pool<DATA_TYPE>::Clear() { int i; int first_new_element; for (i = 0; i < (chunks->count * chunk_size); i++) { next_free_element_list->Set_Data(i+1, i); } count = 0; next_element = 0; } template <class DATA_TYPE> DATA_TYPE * Pool<DATA_TYPE>::Get_Nth_Pointer ( int n ) { DATA_TYPE *the_ptr; DATA_TYPE *the_chunk; int which_chunk; int which_element_in_chunk; which_chunk = n/chunk_size; which_element_in_chunk = n - (which_chunk * chunk_size); the_chunk = chunks->Return_Data_By_Number(which_chunk); the_ptr = &(the_chunk[which_element_in_chunk]); return the_ptr; } #endif __Pool_h__
9.154897
76
0.637472
857bee0fef4c664a084c25146013e71b7c72c2c1
7,338
h
C
xdk-asf-3.51.0/sam/utils/cmsis/sam4cp/include/instance/instance_slcdc.h
j3270/SAMD_Experiments
5c242aff44fc8d7092322d7baf2dda450a78a9b7
[ "MIT" ]
null
null
null
xdk-asf-3.51.0/sam/utils/cmsis/sam4cp/include/instance/instance_slcdc.h
j3270/SAMD_Experiments
5c242aff44fc8d7092322d7baf2dda450a78a9b7
[ "MIT" ]
null
null
null
xdk-asf-3.51.0/sam/utils/cmsis/sam4cp/include/instance/instance_slcdc.h
j3270/SAMD_Experiments
5c242aff44fc8d7092322d7baf2dda450a78a9b7
[ "MIT" ]
null
null
null
/** * \file * * Copyright (c) 2014-2018 Microchip Technology Inc. and its subsidiaries. * * \asf_license_start * * \page License * * Subject to your compliance with these terms, you may use Microchip * software and any derivatives exclusively with Microchip products. * It is your responsibility to comply with third party license terms applicable * to your use of third party software (including open source software) that * may accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, * WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, * INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE * LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL * LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE * SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE * POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT * ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY * RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. * * \asf_license_stop * */ /* * Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a> */ #ifndef _SAM4CP_SLCDC_INSTANCE_ #define _SAM4CP_SLCDC_INSTANCE_ /* ========== Register definition for SLCDC peripheral ========== */ #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_SLCDC_CR (0x4003C000U) /**< \brief (SLCDC) SLCDC Control Register */ #define REG_SLCDC_MR (0x4003C004U) /**< \brief (SLCDC) SLCDC Mode Register */ #define REG_SLCDC_FRR (0x4003C008U) /**< \brief (SLCDC) SLCDC Frame Rate Register */ #define REG_SLCDC_DR (0x4003C00CU) /**< \brief (SLCDC) SLCDC Display Register */ #define REG_SLCDC_SR (0x4003C010U) /**< \brief (SLCDC) SLCDC Status Register */ #define REG_SLCDC_IER (0x4003C020U) /**< \brief (SLCDC) SLCDC Interrupt Enable Register */ #define REG_SLCDC_IDR (0x4003C024U) /**< \brief (SLCDC) SLCDC Interrupt Disable Register */ #define REG_SLCDC_IMR (0x4003C028U) /**< \brief (SLCDC) SLCDC Interrupt Mask Register */ #define REG_SLCDC_ISR (0x4003C02CU) /**< \brief (SLCDC) SLCDC Interrupt Status Register */ #define REG_SLCDC_SMR0 (0x4003C030U) /**< \brief (SLCDC) SLCDC Segment Map Register 0 */ #define REG_SLCDC_SMR1 (0x4003C034U) /**< \brief (SLCDC) SLCDC Segment Map Register 1 */ #define REG_SLCDC_WPMR (0x4003C0E4U) /**< \brief (SLCDC) SLCDC Write Protect Mode Register */ #define REG_SLCDC_WPSR (0x4003C0E8U) /**< \brief (SLCDC) SLCDC Write Protect Status Register */ #define REG_SLCDC_LMEMR0 (0x4003C200U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 0) */ #define REG_SLCDC_MMEMR0 (0x4003C204U) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 0) */ #define REG_SLCDC_LMEMR1 (0x4003C208U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 1) */ #define REG_SLCDC_MMEMR1 (0x4003C20CU) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 1) */ #define REG_SLCDC_LMEMR2 (0x4003C210U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 2) */ #define REG_SLCDC_MMEMR2 (0x4003C214U) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 2) */ #define REG_SLCDC_LMEMR3 (0x4003C218U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 3) */ #define REG_SLCDC_MMEMR3 (0x4003C21CU) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 3) */ #define REG_SLCDC_LMEMR4 (0x4003C220U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 4) */ #define REG_SLCDC_MMEMR4 (0x4003C224U) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 4) */ #define REG_SLCDC_LMEMR5 (0x4003C228U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 5) */ #define REG_SLCDC_MMEMR5 (0x4003C22CU) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 5) */ #else #define REG_SLCDC_CR (*(__O uint32_t*)0x4003C000U) /**< \brief (SLCDC) SLCDC Control Register */ #define REG_SLCDC_MR (*(__IO uint32_t*)0x4003C004U) /**< \brief (SLCDC) SLCDC Mode Register */ #define REG_SLCDC_FRR (*(__IO uint32_t*)0x4003C008U) /**< \brief (SLCDC) SLCDC Frame Rate Register */ #define REG_SLCDC_DR (*(__IO uint32_t*)0x4003C00CU) /**< \brief (SLCDC) SLCDC Display Register */ #define REG_SLCDC_SR (*(__I uint32_t*)0x4003C010U) /**< \brief (SLCDC) SLCDC Status Register */ #define REG_SLCDC_IER (*(__O uint32_t*)0x4003C020U) /**< \brief (SLCDC) SLCDC Interrupt Enable Register */ #define REG_SLCDC_IDR (*(__O uint32_t*)0x4003C024U) /**< \brief (SLCDC) SLCDC Interrupt Disable Register */ #define REG_SLCDC_IMR (*(__O uint32_t*)0x4003C028U) /**< \brief (SLCDC) SLCDC Interrupt Mask Register */ #define REG_SLCDC_ISR (*(__I uint32_t*)0x4003C02CU) /**< \brief (SLCDC) SLCDC Interrupt Status Register */ #define REG_SLCDC_SMR0 (*(__IO uint32_t*)0x4003C030U) /**< \brief (SLCDC) SLCDC Segment Map Register 0 */ #define REG_SLCDC_SMR1 (*(__IO uint32_t*)0x4003C034U) /**< \brief (SLCDC) SLCDC Segment Map Register 1 */ #define REG_SLCDC_WPMR (*(__IO uint32_t*)0x4003C0E4U) /**< \brief (SLCDC) SLCDC Write Protect Mode Register */ #define REG_SLCDC_WPSR (*(__I uint32_t*)0x4003C0E8U) /**< \brief (SLCDC) SLCDC Write Protect Status Register */ #define REG_SLCDC_LMEMR0 (*(__IO uint32_t*)0x4003C200U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 0) */ #define REG_SLCDC_MMEMR0 (*(__IO uint32_t*)0x4003C204U) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 0) */ #define REG_SLCDC_LMEMR1 (*(__IO uint32_t*)0x4003C208U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 1) */ #define REG_SLCDC_MMEMR1 (*(__IO uint32_t*)0x4003C20CU) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 1) */ #define REG_SLCDC_LMEMR2 (*(__IO uint32_t*)0x4003C210U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 2) */ #define REG_SLCDC_MMEMR2 (*(__IO uint32_t*)0x4003C214U) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 2) */ #define REG_SLCDC_LMEMR3 (*(__IO uint32_t*)0x4003C218U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 3) */ #define REG_SLCDC_MMEMR3 (*(__IO uint32_t*)0x4003C21CU) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 3) */ #define REG_SLCDC_LMEMR4 (*(__IO uint32_t*)0x4003C220U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 4) */ #define REG_SLCDC_MMEMR4 (*(__IO uint32_t*)0x4003C224U) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 4) */ #define REG_SLCDC_LMEMR5 (*(__IO uint32_t*)0x4003C228U) /**< \brief (SLCDC) SLCDC LSB Memory Register (com = 5) */ #define REG_SLCDC_MMEMR5 (*(__IO uint32_t*)0x4003C22CU) /**< \brief (SLCDC) SLCDC MSB Memory Register (com = 5) */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #endif /* _SAM4CP_SLCDC_INSTANCE_ */
78.06383
116
0.665576
3f86c169a73f5a776c40164fe091809a8e21cc97
15,463
h
C
B2G/external/wpa_supplicant/wpa_gui/wpagui.ui.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/external/wpa_supplicant/wpa_gui/wpagui.ui.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/external/wpa_supplicant/wpa_gui/wpagui.ui.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/**************************************************************************** ** ui.h extension file, included from the uic-generated form implementation. ** ** If you want to add, delete, or rename functions or slots, use ** Qt Designer to update this file, preserving your code. ** ** You should not define a constructor or destructor in this file. ** Instead, write your code in functions called init() and destroy(). ** These will automatically be called by the form's constructor and ** destructor. *****************************************************************************/ #ifdef __MINGW32__ /* Need to get getopt() */ #include <unistd.h> #endif #include <stdlib.h> void WpaGui::init() { eh = NULL; scanres = NULL; udr = NULL; ctrl_iface = NULL; ctrl_conn = NULL; monitor_conn = NULL; msgNotifier = NULL; ctrl_iface_dir = strdup("/var/run/wpa_supplicant"); parse_argv(); textStatus->setText("connecting to wpa_supplicant"); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(ping())); timer->start(1000, FALSE); if (openCtrlConnection(ctrl_iface) < 0) { printf("Failed to open control connection to wpa_supplicant.\n"); } updateStatus(); networkMayHaveChanged = true; updateNetworks(); } void WpaGui::destroy() { delete msgNotifier; if (monitor_conn) { wpa_ctrl_detach(monitor_conn); wpa_ctrl_close(monitor_conn); monitor_conn = NULL; } if (ctrl_conn) { wpa_ctrl_close(ctrl_conn); ctrl_conn = NULL; } if (eh) { eh->close(); delete eh; eh = NULL; } if (scanres) { scanres->close(); delete scanres; scanres = NULL; } if (udr) { udr->close(); delete udr; udr = NULL; } free(ctrl_iface); ctrl_iface = NULL; free(ctrl_iface_dir); ctrl_iface_dir = NULL; } void WpaGui::parse_argv() { int c; for (;;) { c = getopt(qApp->argc(), qApp->argv(), "i:p:"); if (c < 0) break; switch (c) { case 'i': free(ctrl_iface); ctrl_iface = strdup(optarg); break; case 'p': free(ctrl_iface_dir); ctrl_iface_dir = strdup(optarg); break; } } } int WpaGui::openCtrlConnection(const char *ifname) { char *cfile; int flen; char buf[2048], *pos, *pos2; size_t len; if (ifname) { if (ifname != ctrl_iface) { free(ctrl_iface); ctrl_iface = strdup(ifname); } } else { #ifdef CONFIG_CTRL_IFACE_UDP free(ctrl_iface); ctrl_iface = strdup("udp"); #endif /* CONFIG_CTRL_IFACE_UDP */ #ifdef CONFIG_CTRL_IFACE_UNIX struct dirent *dent; DIR *dir = opendir(ctrl_iface_dir); free(ctrl_iface); ctrl_iface = NULL; if (dir) { while ((dent = readdir(dir))) { #ifdef _DIRENT_HAVE_D_TYPE /* Skip the file if it is not a socket. * Also accept DT_UNKNOWN (0) in case * the C library or underlying file * system does not support d_type. */ if (dent->d_type != DT_SOCK && dent->d_type != DT_UNKNOWN) continue; #endif /* _DIRENT_HAVE_D_TYPE */ if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue; printf("Selected interface '%s'\n", dent->d_name); ctrl_iface = strdup(dent->d_name); break; } closedir(dir); } #endif /* CONFIG_CTRL_IFACE_UNIX */ #ifdef CONFIG_CTRL_IFACE_NAMED_PIPE struct wpa_ctrl *ctrl; int ret; free(ctrl_iface); ctrl_iface = NULL; ctrl = wpa_ctrl_open(NULL); if (ctrl) { len = sizeof(buf) - 1; ret = wpa_ctrl_request(ctrl, "INTERFACES", 10, buf, &len, NULL); if (ret >= 0) { buf[len] = '\0'; pos = strchr(buf, '\n'); if (pos) *pos = '\0'; ctrl_iface = strdup(buf); } wpa_ctrl_close(ctrl); } #endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */ } if (ctrl_iface == NULL) return -1; #ifdef CONFIG_CTRL_IFACE_UNIX flen = strlen(ctrl_iface_dir) + strlen(ctrl_iface) + 2; cfile = (char *) malloc(flen); if (cfile == NULL) return -1; snprintf(cfile, flen, "%s/%s", ctrl_iface_dir, ctrl_iface); #else /* CONFIG_CTRL_IFACE_UNIX */ flen = strlen(ctrl_iface) + 1; cfile = (char *) malloc(flen); if (cfile == NULL) return -1; snprintf(cfile, flen, "%s", ctrl_iface); #endif /* CONFIG_CTRL_IFACE_UNIX */ if (ctrl_conn) { wpa_ctrl_close(ctrl_conn); ctrl_conn = NULL; } if (monitor_conn) { delete msgNotifier; msgNotifier = NULL; wpa_ctrl_detach(monitor_conn); wpa_ctrl_close(monitor_conn); monitor_conn = NULL; } printf("Trying to connect to '%s'\n", cfile); ctrl_conn = wpa_ctrl_open(cfile); if (ctrl_conn == NULL) { free(cfile); return -1; } monitor_conn = wpa_ctrl_open(cfile); free(cfile); if (monitor_conn == NULL) { wpa_ctrl_close(ctrl_conn); return -1; } if (wpa_ctrl_attach(monitor_conn)) { printf("Failed to attach to wpa_supplicant\n"); wpa_ctrl_close(monitor_conn); monitor_conn = NULL; wpa_ctrl_close(ctrl_conn); ctrl_conn = NULL; return -1; } #if defined(CONFIG_CTRL_IFACE_UNIX) || defined(CONFIG_CTRL_IFACE_UDP) msgNotifier = new QSocketNotifier(wpa_ctrl_get_fd(monitor_conn), QSocketNotifier::Read, this); connect(msgNotifier, SIGNAL(activated(int)), SLOT(receiveMsgs())); #endif adapterSelect->clear(); adapterSelect->insertItem(ctrl_iface); adapterSelect->setCurrentItem(0); len = sizeof(buf) - 1; if (wpa_ctrl_request(ctrl_conn, "INTERFACES", 10, buf, &len, NULL) >= 0) { buf[len] = '\0'; pos = buf; while (*pos) { pos2 = strchr(pos, '\n'); if (pos2) *pos2 = '\0'; if (strcmp(pos, ctrl_iface) != 0) adapterSelect->insertItem(pos); if (pos2) pos = pos2 + 1; else break; } } return 0; } static void wpa_gui_msg_cb(char *msg, size_t) { /* This should not happen anymore since two control connections are used. */ printf("missed message: %s\n", msg); } int WpaGui::ctrlRequest(const char *cmd, char *buf, size_t *buflen) { int ret; if (ctrl_conn == NULL) return -3; ret = wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), buf, buflen, wpa_gui_msg_cb); if (ret == -2) { printf("'%s' command timed out.\n", cmd); } else if (ret < 0) { printf("'%s' command failed.\n", cmd); } return ret; } void WpaGui::updateStatus() { char buf[2048], *start, *end, *pos; size_t len; pingsToStatusUpdate = 10; len = sizeof(buf) - 1; if (ctrl_conn == NULL || ctrlRequest("STATUS", buf, &len) < 0) { textStatus->setText("Could not get status from wpa_supplicant"); textAuthentication->clear(); textEncryption->clear(); textSsid->clear(); textBssid->clear(); textIpAddress->clear(); return; } buf[len] = '\0'; bool auth_updated = false, ssid_updated = false; bool bssid_updated = false, ipaddr_updated = false; bool status_updated = false; char *pairwise_cipher = NULL, *group_cipher = NULL; start = buf; while (*start) { bool last = false; end = strchr(start, '\n'); if (end == NULL) { last = true; end = start; while (end[0] && end[1]) end++; } *end = '\0'; pos = strchr(start, '='); if (pos) { *pos++ = '\0'; if (strcmp(start, "bssid") == 0) { bssid_updated = true; textBssid->setText(pos); } else if (strcmp(start, "ssid") == 0) { ssid_updated = true; textSsid->setText(pos); } else if (strcmp(start, "ip_address") == 0) { ipaddr_updated = true; textIpAddress->setText(pos); } else if (strcmp(start, "wpa_state") == 0) { status_updated = true; textStatus->setText(pos); } else if (strcmp(start, "key_mgmt") == 0) { auth_updated = true; textAuthentication->setText(pos); /* TODO: could add EAP status to this */ } else if (strcmp(start, "pairwise_cipher") == 0) { pairwise_cipher = pos; } else if (strcmp(start, "group_cipher") == 0) { group_cipher = pos; } } if (last) break; start = end + 1; } if (pairwise_cipher || group_cipher) { QString encr; if (pairwise_cipher && group_cipher && strcmp(pairwise_cipher, group_cipher) != 0) { encr.append(pairwise_cipher); encr.append(" + "); encr.append(group_cipher); } else if (pairwise_cipher) { encr.append(pairwise_cipher); } else if (group_cipher) { encr.append(group_cipher); encr.append(" [group key only]"); } else { encr.append("?"); } textEncryption->setText(encr); } else textEncryption->clear(); if (!status_updated) textStatus->clear(); if (!auth_updated) textAuthentication->clear(); if (!ssid_updated) textSsid->clear(); if (!bssid_updated) textBssid->clear(); if (!ipaddr_updated) textIpAddress->clear(); } void WpaGui::updateNetworks() { char buf[2048], *start, *end, *id, *ssid, *bssid, *flags; size_t len; int first_active = -1; bool selected = false; if (!networkMayHaveChanged) return; networkSelect->clear(); if (ctrl_conn == NULL) return; len = sizeof(buf) - 1; if (ctrlRequest("LIST_NETWORKS", buf, &len) < 0) return; buf[len] = '\0'; start = strchr(buf, '\n'); if (start == NULL) return; start++; while (*start) { bool last = false; end = strchr(start, '\n'); if (end == NULL) { last = true; end = start; while (end[0] && end[1]) end++; } *end = '\0'; id = start; ssid = strchr(id, '\t'); if (ssid == NULL) break; *ssid++ = '\0'; bssid = strchr(ssid, '\t'); if (bssid == NULL) break; *bssid++ = '\0'; flags = strchr(bssid, '\t'); if (flags == NULL) break; *flags++ = '\0'; QString network(id); network.append(": "); network.append(ssid); networkSelect->insertItem(network); if (strstr(flags, "[CURRENT]")) { networkSelect->setCurrentItem(networkSelect->count() - 1); selected = true; } else if (first_active < 0 && strstr(flags, "[DISABLED]") == NULL) first_active = networkSelect->count() - 1; if (last) break; start = end + 1; } if (!selected && first_active >= 0) networkSelect->setCurrentItem(first_active); networkMayHaveChanged = false; } void WpaGui::helpIndex() { printf("helpIndex\n"); } void WpaGui::helpContents() { printf("helpContents\n"); } void WpaGui::helpAbout() { QMessageBox::about(this, "wpa_gui for wpa_supplicant", "Copyright (c) 2003-2008,\n" "Jouni Malinen <j@w1.fi>\n" "and contributors.\n" "\n" "This program is free software. You can\n" "distribute it and/or modify it under the terms of\n" "the GNU General Public License version 2.\n" "\n" "Alternatively, this software may be distributed\n" "under the terms of the BSD license.\n" "\n" "This product includes software developed\n" "by the OpenSSL Project for use in the\n" "OpenSSL Toolkit (http://www.openssl.org/)\n"); } void WpaGui::disconnect() { char reply[10]; size_t reply_len = sizeof(reply); ctrlRequest("DISCONNECT", reply, &reply_len); } void WpaGui::scan() { if (scanres) { scanres->close(); delete scanres; } scanres = new ScanResults(); if (scanres == NULL) return; scanres->setWpaGui(this); scanres->show(); scanres->exec(); } void WpaGui::eventHistory() { if (eh) { eh->close(); delete eh; } eh = new EventHistory(); if (eh == NULL) return; eh->addEvents(msgs); eh->show(); eh->exec(); } void WpaGui::ping() { char buf[10]; size_t len; #ifdef CONFIG_CTRL_IFACE_NAMED_PIPE /* * QSocketNotifier cannot be used with Windows named pipes, so use a timer * to check for received messages for now. This could be optimized be doing * something specific to named pipes or Windows events, but it is not clear * what would be the best way of doing that in Qt. */ receiveMsgs(); #endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */ if (scanres && !scanres->isVisible()) { delete scanres; scanres = NULL; } if (eh && !eh->isVisible()) { delete eh; eh = NULL; } if (udr && !udr->isVisible()) { delete udr; udr = NULL; } len = sizeof(buf) - 1; if (ctrlRequest("PING", buf, &len) < 0) { printf("PING failed - trying to reconnect\n"); if (openCtrlConnection(ctrl_iface) >= 0) { printf("Reconnected successfully\n"); pingsToStatusUpdate = 0; } } pingsToStatusUpdate--; if (pingsToStatusUpdate <= 0) { updateStatus(); updateNetworks(); } } static int str_match(const char *a, const char *b) { return strncmp(a, b, strlen(b)) == 0; } void WpaGui::processMsg(char *msg) { char *pos = msg, *pos2; int priority = 2; if (*pos == '<') { /* skip priority */ pos++; priority = atoi(pos); pos = strchr(pos, '>'); if (pos) pos++; else pos = msg; } WpaMsg wm(pos, priority); if (eh) eh->addEvent(wm); msgs.append(wm); while (msgs.count() > 100) msgs.pop_front(); /* Update last message with truncated version of the event */ if (strncmp(pos, "CTRL-", 5) == 0) { pos2 = strchr(pos, str_match(pos, WPA_CTRL_REQ) ? ':' : ' '); if (pos2) pos2++; else pos2 = pos; } else pos2 = pos; QString lastmsg = pos2; lastmsg.truncate(40); textLastMessage->setText(lastmsg); pingsToStatusUpdate = 0; networkMayHaveChanged = true; if (str_match(pos, WPA_CTRL_REQ)) processCtrlReq(pos + strlen(WPA_CTRL_REQ)); } void WpaGui::processCtrlReq(const char *req) { if (udr) { udr->close(); delete udr; } udr = new UserDataRequest(); if (udr == NULL) return; if (udr->setParams(this, req) < 0) { delete udr; udr = NULL; return; } udr->show(); udr->exec(); } void WpaGui::receiveMsgs() { char buf[256]; size_t len; while (monitor_conn && wpa_ctrl_pending(monitor_conn) > 0) { len = sizeof(buf) - 1; if (wpa_ctrl_recv(monitor_conn, buf, &len) == 0) { buf[len] = '\0'; processMsg(buf); } } } void WpaGui::connectB() { char reply[10]; size_t reply_len = sizeof(reply); ctrlRequest("REASSOCIATE", reply, &reply_len); } void WpaGui::selectNetwork( const QString &sel ) { QString cmd(sel); char reply[10]; size_t reply_len = sizeof(reply); int pos = cmd.find(':'); if (pos < 0) { printf("Invalid selectNetwork '%s'\n", cmd.ascii()); return; } cmd.truncate(pos); cmd.prepend("SELECT_NETWORK "); ctrlRequest(cmd.ascii(), reply, &reply_len); } void WpaGui::editNetwork() { QString sel(networkSelect->currentText()); int pos = sel.find(':'); if (pos < 0) { printf("Invalid selectNetwork '%s'\n", sel.ascii()); return; } sel.truncate(pos); NetworkConfig *nc = new NetworkConfig(); if (nc == NULL) return; nc->setWpaGui(this); nc->paramsFromConfig(sel.toInt()); nc->show(); nc->exec(); } void WpaGui::triggerUpdate() { updateStatus(); networkMayHaveChanged = true; updateNetworks(); } void WpaGui::addNetwork() { NetworkConfig *nc = new NetworkConfig(); if (nc == NULL) return; nc->setWpaGui(this); nc->newNetwork(); nc->show(); nc->exec(); } void WpaGui::selectAdapter( const QString & sel ) { if (openCtrlConnection(sel.ascii()) < 0) printf("Failed to open control connection to wpa_supplicant.\n"); updateStatus(); updateNetworks(); }
21.095498
80
0.601565
aca22498c108c561d39828e3128dacf9954759bb
2,541
h
C
ui/dragging/drag_tab_handler.h
careylam/vivaldi
bff2a435c35fe2cb3327d8d4a76430d4be5f666e
[ "BSD-3-Clause" ]
null
null
null
ui/dragging/drag_tab_handler.h
careylam/vivaldi
bff2a435c35fe2cb3327d8d4a76430d4be5f666e
[ "BSD-3-Clause" ]
null
null
null
ui/dragging/drag_tab_handler.h
careylam/vivaldi
bff2a435c35fe2cb3327d8d4a76430d4be5f666e
[ "BSD-3-Clause" ]
1
2020-05-12T23:54:41.000Z
2020-05-12T23:54:41.000Z
// Copyright (c) 2016 Vivaldi Technologies AS. All rights reserved // // Based on code that is: // // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_DRAGGING_DRAG_TAB_HANDLER_H_ #define UI_DRAGGING_DRAG_TAB_HANDLER_H_ #include <string> #include "base/macros.h" #include "content/public/browser/web_contents.h" #if defined(OS_MACOSX) #include "chrome/browser/ui/cocoa/tab_contents/web_drag_bookmark_handler_mac.h" #else #include "chrome/browser/ui/aura/tab_contents/web_drag_bookmark_handler_aura.h" #endif // defined(OS_MACOSX) #include "extensions/api/tabs/tabs_private_api.h" #include "third_party/WebKit/public/platform/WebDragOperation.h" #include "ui/base/dragdrop/os_exchange_data.h" namespace content { class WebContents; } namespace extensions { class VivaldiAppHelper; } #if defined(OS_MACOSX) typedef WebDragBookmarkHandlerMac BaseClass; #else typedef WebDragBookmarkHandlerAura BaseClass; #endif // OS_MACOSX namespace vivaldi { // Vivaldi needs to intercept tab drag events so it can dispatch them to the // extensions system. // We override the bookmark drag handler from Chromium and handle our own // data, if needed, otherwise we call the base class to let it handle // bookmark drags. class DragTabHandler : #if defined(OS_MACOSX) public WebDragBookmarkHandlerMac { #else public WebDragBookmarkHandlerAura { #endif // OS_MACOSX public: DragTabHandler(); ~DragTabHandler() override; // Overridden from content::WebDragDestDelegate: void DragInitialize(content::WebContents* contents) override; void OnDragOver() override; void OnDragEnter() override; void OnDrop() override; void OnDragLeave() override; blink::WebDragOperationsMask OnDragEnd(int screen_x, int screen_y, blink::WebDragOperationsMask ops, bool cancelled) override; #if defined(USE_AURA) void OnReceiveDragData(const ui::OSExchangeData& data) override; #endif // defined(USE_AURA) #if defined(OS_MACOSX) void SetDragData(const content::DropData* data) override; #endif // OS_MACOSX private: content::WebContents* web_contents_; // The data for the active drag. Empty when there is no active drag. TabDragDataCollection tab_drag_data_; DISALLOW_COPY_AND_ASSIGN(DragTabHandler); }; } // namespace vivaldi #endif // UI_DRAGGING_DRAG_TAB_HANDLER_H_
29.894118
79
0.744195
0d90cc474f3ca80d7972cee0801fdad062de3376
1,574
h
C
MobManager3.0/headers/enemy.h
GabrielCalhabeu/MobManager
f04995f55ac81d444a465189814c770a2af0c05b
[ "MIT" ]
null
null
null
MobManager3.0/headers/enemy.h
GabrielCalhabeu/MobManager
f04995f55ac81d444a465189814c770a2af0c05b
[ "MIT" ]
null
null
null
MobManager3.0/headers/enemy.h
GabrielCalhabeu/MobManager
f04995f55ac81d444a465189814c770a2af0c05b
[ "MIT" ]
null
null
null
#ifndef MOBMANAGER_ENEMY_H #define MOBMANAGER_ENEMY_H #include <stdio.h> #include <stdlib.h> #include <string.h> //Segment for Enemy, enemyCell, and enemyList creation. typedef struct enemy { int ID; int maxHp; int curHp; char state[10]; }TypeEnemy; typedef struct enemyCell { TypeEnemy enemy; struct enemyCell* next; }enemyCell; typedef struct enemyList{ int size; struct enemyCell* first; struct enemyCell* last; }enemyList; //Segment for Group, groupCell, and groupList. typedef struct group{ char groupName[50]; enemyList* enemyList; }TypeGroup; typedef struct groupCell{ TypeGroup group; struct groupCell* next; }groupCell; typedef struct groupList{ int size; struct groupCell* first; struct groupCell* last; }groupList; enemyList* createEnemyList(enemyList *enemyList, int hp, int numberOfEnemies); enemyList* addEnemy(TypeEnemy enemy, enemyList *enemyList); void makeEnemyList(enemyList* enemyList); void makeGroupList(groupList * groupList); void addGroup(TypeGroup group, groupList *groupList); void createGroup(groupList * groupList); void freeEnemyList(enemyList * enemyList); void deleteGroup(groupList * groupList, int pos); void editGroup(groupList * groupList, int pos); void damageEnemy(groupList* groupList1, int posX, int posY, int damage, int mode); void changeStatus(groupList* groupList1, int posX, int posY, char status[10]); void removeStatus(groupList* groupList1, int posX, int posY); void flushGroupList(groupList *groupList); #endif //MOBMANAGER_ENEMY_H
19.924051
82
0.746506
1dec98227c693a472dbfe466267f1cd7a2e609ee
2,271
h
C
src/AnimatedRobot.h
stuartmd/little-lost-robot
16b80ab2cfefb38caf0295fdd88fbb90d6ca3dc5
[ "MIT" ]
null
null
null
src/AnimatedRobot.h
stuartmd/little-lost-robot
16b80ab2cfefb38caf0295fdd88fbb90d6ca3dc5
[ "MIT" ]
2
2016-07-31T22:09:48.000Z
2016-08-01T01:19:00.000Z
src/AnimatedRobot.h
stuartmd/little-lost-robot
16b80ab2cfefb38caf0295fdd88fbb90d6ca3dc5
[ "MIT" ]
null
null
null
// AnimatedRobot.h: interface for the AnimatedRobot class. // // MIT License // // Copyright (c) [2016] [Stuart McDonald Dickson] // // 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. ///////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_ANIMATEDROBOT_H__FA8E9302_292A_11D4_95D9_103453C14F00__INCLUDED_) #define AFX_ANIMATEDROBOT_H__FA8E9302_292A_11D4_95D9_103453C14F00__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "Robot.h" class Game; class AnimatedRobot : public Robot { public: void SetGame(Game* pGame); AnimatedRobot(Game* pGame); bool IsAnimated(); virtual void DrawInteractObject(); void TurnRight(); void TurnLeft(); // Actions bool ExtendArms(); bool RetractArms(); AnimatedRobot(); virtual ~AnimatedRobot(); protected: Game* m_pGame; virtual bool DrawArm(); /* Turning State Vars */ bool bTorsoTurnLft; bool bTorsoTurnRgt; /* Gripping/Releasing State Vars */ bool m_bExtendingArms; bool m_bRetractingArms; float m_nExtendArmStep; int m_nAnimStep; }; #endif // !defined(AFX_ANIMATEDROBOT_H__FA8E9302_292A_11D4_95D9_103453C14F00__INCLUDED_)
30.689189
89
0.711581
ce4ae52b0c24808725e6a12e2ab2e52c9bf5781f
388
c
C
recursivo-1.c
MateSilver/EAD1
dd6419377a366b0af41c6ffb9aaf06d0285940af
[ "MIT" ]
null
null
null
recursivo-1.c
MateSilver/EAD1
dd6419377a366b0af41c6ffb9aaf06d0285940af
[ "MIT" ]
null
null
null
recursivo-1.c
MateSilver/EAD1
dd6419377a366b0af41c6ffb9aaf06d0285940af
[ "MIT" ]
null
null
null
#include <stdio.h> /** * inf/UFG - AED1: lista de exercicios de recursividade - 1 * o programa a seguir usa a recursão pra exibir na tela uma contagem * crescente de 'n' numeros a partir de uma entrada 'n' **/ void print(int n){ if(n == 0){ return; } print(n-1); printf("%d ", n); return; } int main(){ int n; scanf("%d", &n); print(n); }
15.52
69
0.559278
0e34cc21f2eca40c6819d61cb6adb9bd87598115
14,874
c
C
coconut_mobileClient/coconut_sdk_ios/src/sigmsg/src/epida_loadprefiles.c
coconut201812/coconut
15f09f258318ecbd4f467950e5eefbb770ad457c
[ "Apache-2.0" ]
13
2018-12-06T22:31:38.000Z
2021-01-15T03:36:13.000Z
coconut_mobileClient/coconut_sdk_ios/src/sigmsg/src/epida_loadprefiles.c
HeapxLabs/coconut
15f09f258318ecbd4f467950e5eefbb770ad457c
[ "Apache-2.0" ]
null
null
null
coconut_mobileClient/coconut_sdk_ios/src/sigmsg/src/epida_loadprefiles.c
HeapxLabs/coconut
15f09f258318ecbd4f467950e5eefbb770ad457c
[ "Apache-2.0" ]
9
2018-12-06T21:08:20.000Z
2019-04-16T10:18:46.000Z
/*############################################################################ # Copyright 2018 BITMAINTECH PTE LTD. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################*/ /*! * \file * load prebuilt files, ONLY for test. */ /* system header files */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* epdia common header files */ #include "include/epida_define.h" #include "util/buffutil.h" #include "include/epida_define.h" #define CREDENTIAL_FILE_NAME "epid_credential.dat" #define NONCE_FILE_NAME "epid_nonce.dat" #define TRANSACTION_FILE_NAME "transaction.dat" INT32 load_cacert(const CHAR* res_directory_path) { CHAR cacert_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(cacert_file_path, sizeof(cacert_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, CACERT_FILE_NAME); CHAR cacert_data[] = { 0x02, 0x00, 0x00, 0x11, 0xE3, 0xF5, 0x5A, 0xBF, 0xF9, 0xE1, 0x8E, 0xAD, 0xC0, 0x38, 0xC0, 0xAB, 0x28, 0xA4, 0x80, 0x2A, 0x09, 0x0D, 0x4D, 0xBE, 0x0C, 0x4F, 0x31, 0x92, 0x15, 0x1F, 0x2C, 0x9D, 0xB7, 0x12, 0x91, 0xC4, 0xE2, 0xE9, 0xAC, 0x1D, 0x52, 0x29, 0x29, 0xDE, 0xE1, 0x1D, 0xFF, 0x40, 0xE2, 0xFC, 0x1A, 0x87, 0x0B, 0x17, 0xCF, 0x9C, 0xB7, 0x7E, 0x95, 0x9C, 0xD6, 0x8B, 0x23, 0x93, 0xFE, 0xE1, 0x0C, 0xD6, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x5A, 0xC6, 0x35, 0xD8, 0xAA, 0x3A, 0x93, 0xE7, 0xB3, 0xEB, 0xBD, 0x55, 0x76, 0x98, 0x86, 0xBC, 0x65, 0x1D, 0x06, 0xB0, 0xCC, 0x53, 0xB0, 0xF6, 0x3B, 0xCE, 0x3C, 0x3E, 0x27, 0xD2, 0x60, 0x4B, 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, 0x77, 0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96, 0x4F, 0xE3, 0x42, 0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, 0x2B, 0xCE, 0x33, 0x57, 0x6B, 0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBC, 0xE6, 0xFA, 0xAD, 0xA7, 0x17, 0x9E, 0x84, 0xF3, 0xB9, 0xCA, 0xC2, 0xFC, 0x63, 0x25, 0x51, 0x5F, 0x96, 0xDC, 0xA2, 0x64, 0x58, 0x85, 0x67, 0x02, 0xBE, 0x71, 0x37, 0x4D, 0xE6, 0x80, 0x64, 0xAC, 0x57, 0x9B, 0xAC, 0x24, 0x85, 0x48, 0x62, 0xBC, 0x38, 0x1A, 0xEC, 0x8E, 0x44, 0x02, 0xC3, 0xC1, 0xD6, 0x26, 0xBA, 0x1B, 0xB2, 0xBC, 0x23, 0xD4, 0xFB, 0x4A, 0x4C, 0x20, 0x71, 0x13, 0x5E, 0xCD, 0x04, 0x1B, 0x6D, 0x8A, 0xDD, 0x35, 0xC7, 0x70, 0xEA, 0xA3, 0x37, 0x5A, 0x24, 0x45, 0xD8 }; if (0 != WriteLoud(cacert_data, sizeof(cacert_data), cacert_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } INT32 load_pubkey(const CHAR* res_directory_path) { CHAR pubkey_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(pubkey_file_path, sizeof(pubkey_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, PUBKEY_FILE_NAME); CHAR pubkey_data[] = { 0x02, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0xCB, 0x06, 0x04, 0xB3, 0xF7, 0x23, 0xB2, 0xD1, 0xD1, 0x0D, 0x4F, 0x51, 0x7B, 0xBB, 0x8F, 0x71, 0x15, 0xD7, 0xF1, 0xDC, 0x15, 0x37, 0xC8, 0xB8, 0x3D, 0x68, 0x0A, 0x18, 0xA5, 0x34, 0x14, 0x0C, 0xDC, 0xD9, 0x15, 0x7E, 0xBA, 0x56, 0xC5, 0xE5, 0x61, 0xFA, 0x6A, 0x86, 0xA0, 0xAC, 0x6A, 0x81, 0x36, 0x6D, 0x01, 0x5F, 0x86, 0xC0, 0x04, 0x8B, 0x1E, 0xFF, 0x49, 0xD9, 0x37, 0x96, 0x66, 0xF1, 0xC3, 0x16, 0xB5, 0xC5, 0x1C, 0x67, 0xB6, 0xFF, 0x28, 0x23, 0x79, 0x59, 0xEA, 0x80, 0xE6, 0x09, 0x07, 0xE7, 0xD3, 0x38, 0xEC, 0xB9, 0x16, 0x83, 0x88, 0xDA, 0x64, 0xDD, 0xC4, 0x9D, 0x6A, 0x5C, 0xB2, 0x1C, 0x88, 0x97, 0xEA, 0xAF, 0xA9, 0xF3, 0x3E, 0x07, 0xEA, 0xB6, 0x2A, 0xD5, 0x7A, 0xED, 0x32, 0xD9, 0x3D, 0x90, 0xD7, 0xB9, 0x91, 0x08, 0x05, 0x9E, 0xE3, 0x22, 0x75, 0x06, 0x35, 0xE5, 0xC4, 0x77, 0xAD, 0x52, 0xB9, 0x7C, 0x04, 0x2D, 0x7E, 0x81, 0xF2, 0x5D, 0x5D, 0x52, 0x7D, 0xD7, 0x1D, 0x29, 0xFB, 0x6A, 0xA7, 0xBC, 0xB5, 0xA9, 0x1A, 0xA6, 0xFD, 0x20, 0xEA, 0xF2, 0x98, 0xE2, 0x67, 0x33, 0x28, 0x67, 0x5F, 0xBE, 0x23, 0xA0, 0x43, 0xE8, 0x71, 0xAA, 0xAB, 0xF6, 0xF0, 0x6A, 0x2B, 0x52, 0xA8, 0x61, 0x51, 0x22, 0x44, 0x00, 0x91, 0xD7, 0xF1, 0x7E, 0x05, 0x48, 0xDC, 0x51, 0x0C, 0xEF, 0xA0, 0xF3, 0x72, 0xCD, 0x59, 0xD4, 0x7A, 0x2A, 0x60, 0xA3, 0x62, 0x54, 0xA8, 0xB6, 0x8F, 0xED, 0x90, 0xDF, 0x3E, 0x94, 0xE8, 0xA4, 0x89, 0x32, 0xAA, 0x52, 0x5A, 0x97, 0xAE, 0x4C, 0x86, 0xF4, 0xBA, 0xEC, 0xC6, 0x36, 0x13, 0x87, 0x42, 0x5D, 0x16, 0x49, 0x12, 0x66, 0xC5, 0xE0, 0xE4, 0x9B, 0xF9, 0x68, 0xAA, 0xA9, 0x95, 0x81, 0x16, 0x5C, 0xD2, 0xCA, 0xD4, 0x2E, 0x61, 0x49, 0x2F, 0xBC, 0x95, 0xAD, 0xF2, 0x74, 0xDB, 0x4A, 0x48, 0xA1, 0x88, 0xDB, 0xB1, 0x9D, 0x31, 0x9C, 0xD6, 0xC3, 0x93, 0x93, 0xFC, 0x55, 0xBD, 0x54, 0xA6, 0x93, 0xC4, 0x49, 0xE1, 0xEE, 0xC3, 0xA4, 0x72, 0x43, 0x54, 0xD0, 0xD4, 0xE7, 0xD9, 0x09, 0x01, 0xCD, 0x3E, 0xBF, 0xA5, 0x69, 0xC0, 0x16, 0x21, 0x5B, 0xC2, 0xEA, 0x5F, 0x21, 0xE2, 0xD8, 0x2B, 0x7F, 0xDD, 0xAD, 0x02, 0x6D, 0xCE }; if (0 != WriteLoud(pubkey_data, sizeof(pubkey_data), pubkey_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } INT32 load_credential(const CHAR* res_directory_path) { CHAR credential_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(credential_file_path, sizeof(credential_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, CREDENTIAL_FILE_NAME); CHAR credential_data[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCA, 0x24, 0x49, 0x67, 0x86, 0x98, 0xFE, 0x05, 0xD2, 0x66, 0xC5, 0x7C, 0xD2, 0x40, 0xB6, 0xED, 0x4F, 0x76, 0xC0, 0xB8, 0x08, 0x62, 0x9A, 0x56, 0x46, 0x76, 0x01, 0x40, 0xD8, 0xA3, 0xE1, 0xB8, 0x2F, 0x83, 0x64, 0x88, 0x99, 0xCA, 0xD3, 0x2B, 0xD9, 0x50, 0xFB, 0x74, 0x8B, 0xA5, 0x32, 0xB8, 0xCE, 0x31, 0xD7, 0x56, 0x4B, 0xDD, 0xDD, 0x1C, 0x0E, 0x5E, 0xBA, 0x34, 0x68, 0x66, 0xBC, 0xB6, 0x9C, 0x92, 0xF0, 0x2F, 0xA2, 0x27, 0x56, 0xC1, 0xEF, 0x3A, 0x21, 0x5E, 0x9A, 0x05, 0x13, 0x63, 0x0E, 0x2F, 0x12, 0xAC, 0x95, 0xB9, 0x26, 0x6D, 0x1D, 0xE2, 0xCF, 0x64, 0x4A, 0x09, 0xDD, 0x4F }; if (0 != WriteLoud(credential_data, sizeof(credential_data), credential_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } INT32 load_nonce(const CHAR* res_directory_path) { CHAR nonce_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(nonce_file_path, sizeof(nonce_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, NONCE_FILE_NAME); CHAR nonce_data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f, 0x00, 0x01, 0x02 }; if (0 != WriteLoud(nonce_data, sizeof(nonce_data), nonce_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } static INT32 load_privatef(const CHAR* res_directory_path) { CHAR privatef_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(privatef_file_path, sizeof(privatef_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, PRIVATEF_FILE_NAME); CHAR privatf_data[] = { 0x15, 0x9D, 0x08, 0x6B, 0x93, 0xBF, 0x95, 0x89, 0x11, 0xB8, 0x31, 0x11, 0xB1, 0x36, 0x76, 0x4D, 0x0A, 0xBE, 0x5A, 0x42, 0xE7, 0x44, 0xBB, 0x17, 0x6D, 0x36, 0x7B, 0x80, 0x0B, 0x10, 0x1E, 0xC6 }; if (0 != WriteLoud(privatf_data, sizeof(privatf_data), privatef_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } INT32 load_mprivkey(const CHAR* res_directory_path) { CHAR mprivkey_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(mprivkey_file_path, sizeof(mprivkey_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, MPRIVKEY_FILE_NAME); CHAR mprivkey_data[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCA, 0x24, 0x49, 0x67, 0x86, 0x98, 0xFE, 0x05, 0xD2, 0x66, 0xC5, 0x7C, 0xD2, 0x40, 0xB6, 0xED, 0x4F, 0x76, 0xC0, 0xB8, 0x08, 0x62, 0x9A, 0x56, 0x46, 0x76, 0x01, 0x40, 0xD8, 0xA3, 0xE1, 0xB8, 0x2F, 0x83, 0x64, 0x88, 0x99, 0xCA, 0xD3, 0x2B, 0xD9, 0x50, 0xFB, 0x74, 0x8B, 0xA5, 0x32, 0xB8, 0xCE, 0x31, 0xD7, 0x56, 0x4B, 0xDD, 0xDD, 0x1C, 0x0E, 0x5E, 0xBA, 0x34, 0x68, 0x66, 0xBC, 0xB6, 0x9C, 0x92, 0xF0, 0x2F, 0xA2, 0x27, 0x56, 0xC1, 0xEF, 0x3A, 0x21, 0x5E, 0x9A, 0x05, 0x13, 0x63, 0x0E, 0x2F, 0x12, 0xAC, 0x95, 0xB9, 0x26, 0x6D, 0x1D, 0xE2, 0xCF, 0x64, 0x4A, 0x09, 0xDD, 0x4F, 0x15, 0x9D, 0x08, 0x6B, 0x93, 0xBF, 0x95, 0x89, 0x11, 0xB8, 0x31, 0x11, 0xB1, 0x36, 0x76, 0x4D, 0x0A, 0xBE, 0x5A, 0x42, 0xE7, 0x44, 0xBB, 0x17, 0x6D, 0x36, 0x7B, 0x80, 0x0B, 0x10, 0x1E, 0xC6 }; if (0 != WriteLoud(mprivkey_data, sizeof(mprivkey_data), mprivkey_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } INT32 load_bsnlist(const CHAR* res_directory_path) { CHAR basename_list_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(basename_list_file_path, sizeof(basename_list_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, BASENAME_LIST_FILE_NAME); CHAR basenames_data[] = { 0x7B, 0x0A, 0x0D, 0x0A, 0x20, 0x20, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x43, 0x6F, 0x75, 0x6E, 0x74, 0x22, 0x3A, 0x20, 0x22, 0x31, 0x30, 0x22, 0x2C, 0x0D, 0x0A, 0x20, 0x20, 0x0A, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x73, 0x22, 0x3A, 0x0A, 0x5B, 0x0A, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x30, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x31, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x32, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x33, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x34, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x35, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x36, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x37, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x38, 0x22, 0x7D, 0x2C, 0x7B, 0x22, 0x62, 0x61, 0x73, 0x65, 0x6E, 0x61, 0x6D, 0x65, 0x22, 0x3A, 0x22, 0x39, 0x22, 0x7D, 0x0A, 0x5D, 0x0D, 0x0A, 0x0D, 0x7D }; if (0 != WriteLoud(basenames_data, sizeof(basenames_data), basename_list_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } INT32 load_transaction(const CHAR* res_directory_path) { CHAR transaction_file_path[EPIDA_FILE_PATH_MAX] = { 0 }; snprintf(transaction_file_path, sizeof(transaction_file_path) - 1, "%s%s%s", res_directory_path, PATH_SLASH, TRANSACTION_FILE_NAME); char transaction_data[] = {0x0a, 0x0b, 0x0c,0x0d, 0x0e, 0x0f}; if (0 != WriteLoud(transaction_data, sizeof(transaction_data), transaction_file_path)) { return EPIDA_WRITE_FILE_FAIL; } return EPIDA_OK; } /* ONLY test interface to provide the test data about epid key meterial files */ INT32 load_epid_prebuilt_files(const CHAR* res_directory_path) { INT32 ret = EPIDA_OK; if (NULL == res_directory_path) { return EPIDA_NO_RES_PATH; } UINT32 res_directory_path_len = (UINT32)strlen(res_directory_path); if ((0 == res_directory_path_len) || (res_directory_path_len > EPIDA_RES_DIR_PATH_MAX)) { return EPIDA_INVALID_RES_PATH_LEN; } do { if (EPIDA_OK != load_cacert(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } if (EPIDA_OK != load_pubkey(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } if (EPIDA_OK != load_bsnlist(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } if (EPIDA_OK != load_credential(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } if (EPIDA_OK != load_nonce(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } if (EPIDA_OK != load_privatef(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } if (EPIDA_OK != load_mprivkey(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } if (EPIDA_OK != load_transaction(res_directory_path)) { ret = EPIDA_WRITE_FILE_FAIL; break; } }while(0); return EPIDA_OK; }
42.988439
107
0.60441
079464f3455d0bafadb964a6da6d1228672b0a8f
14,029
c
C
ARIS/boot/synergy/ssp/src/framework/sf_el_ux/ux_hcd_synergy_port_status_get.c
arrow-acs/acn-embedded
b31d4cf2055f8809fa7b80ec80703402fc09001e
[ "Apache-2.0" ]
7
2017-03-27T01:08:22.000Z
2019-08-20T18:29:03.000Z
ARIS/boot/synergy/ssp/src/framework/sf_el_ux/ux_hcd_synergy_port_status_get.c
konexios/moonstone-acn-embedded
b31d4cf2055f8809fa7b80ec80703402fc09001e
[ "Apache-2.0" ]
5
2017-11-10T23:09:50.000Z
2018-04-04T13:58:31.000Z
ARIS/boot/synergy/ssp/src/framework/sf_el_ux/ux_hcd_synergy_port_status_get.c
konexios/moonstone-acn-embedded
b31d4cf2055f8809fa7b80ec80703402fc09001e
[ "Apache-2.0" ]
5
2017-03-29T02:15:10.000Z
2019-02-22T13:09:42.000Z
#ifdef AMS_ENCRYPT_PACKAGE -----BEGIN ENCRYPTED FILE v0.6----- 9S04Fc0roaJnwZGP6OG7EDBImvEWKQdoMQNOXjk4Zvzx9KJz15dhDWXbFxwtj3cm 3oCHwqJRRhBS/vYIEa2vzbP579lfNCrR1am1nuP5kikK1OpF4wzL8FVjx6P60Da6 mXoNlhQm8BisfiV97s/MPrDLAKMZKFcwpF4tMFZ615XZ74JrUJAZbIjCRzGDttix 3p9/VN81LdLO6XHuzROV4d+m+XaLFz+HWk4mxQCBdpc8K+lbI7HXUhEDKpAcBmvk LUQx2P5dVNQf6ePTYKiGN3X6WAxtUhjb6bEInS/CF4KoqYpy9tWPCUiZG1Xg/cH1 UFJW61nE4uMJfL754v/fIszAunuDUoGP2LQI2G3pnNHnY5LJ+hH2ZjCwepMsDSDw SVGP7mgC0JjzJiGErawwCAxH/Jnn09bMDL7NIEHtTMgkkk5pu+ka215LCTazCTVW pR3im/poEfwDVPhdaYb3AOTlx8dG3gsJr7vP0M0n/72OT4UwlcSxPxx93mLmRMCQ gMEPFJpIoN+rURzDcpRyMO40vseT3Z7S4ubdu7q6XeZNA0IyrD8Uw9kcEZP1k3p2 4IsuTRZFNCt6tALnA+tUM8l3rADHGbPTWLks8bjjVwQ7D2vueI7v3mvs/ugG7LJ/ vPuEUufzZqUg4rMWoGZCMtdd+KeWDTWDbfvbox+jw2Bdi3l2kTshhTCVZHt85jAH XEwxec51jMaATIpZge6LqHXbama5galdTFg/t1L2vS7ZD/SUpp2yo81sxw2IWYL6 NOWrNHIYRIwS1lj0Vag4hbBEW5eZZdFBwe7f4otBv4TKrEEABfAcJoJ8GDrfY2M/ MRJWlq02ouFVD49s3nRIi0tbkmTqlVJFpKlGP89VojtrKdHnEAP23WRA32n9tXBb VO7/Rq6PKkTsTB4SfkUiiZJkLqytj/4LIFBHy4HLtD87lt8+lOBcSNVIAGDp0kWP fX0QB7Hs8lrUwXOerMBgEBfysh2jVUiY8Ri2WjPbSHDlX5y92hOOalllB4SENn7+ XGjNtypa2f0EfoY0dIRZsDsjMcrW7EMhN/of1gQGcUSSGpGSym555Cm8dX+/8NaE XzHaDuQkivKrtic3MQVNmj976Ew4CsUdXyqjS1hAmkd3ulIrJOKtNLJbxIP3R/tQ ZpjyqeRNt9+XrCJ/xBdm6UgXBZi1aWdlMtG0U3Xwm/RoAXNISTeuUOhhieDmDQKo 4a5EMo+SRhVVC061+nP6uUiZz63UY8/i39STq39UH/55l1FBtQb/T9MP+cRqjijp 6Aen1HOHmK2vva3IToFHVenwHWg189BF+RfBLCgGeX5wc/XXWaQkKLg6sC0xUE/M kI3pk3BKoj4/7+njKDrbIuEQLefKKLN+FuEzKn3KqwfUuYctMEO5xBkq3JqShHcw FkxnT9lKuKWwybuNWfUZ7hlNvA2O2vPCf5t93Xs5Bsuod8RZnWTygRJRzP1EjCD6 oB8wq1QGdXYdDN9Pw/AsRFwdD2iEOzciIs3aDnHwqjDOL19qSErDm44IJfELixZC DS5Fzx+Y9efnKgwz8bkZLDjVqJTbF0r+B03S9OeGapnDEHAVQK4YsXwyCtaMES2u 5Jxa7bIz8Br9vfECC1t1MXNGuPG0YidYmyYbkNZMOmrpPcaTOe7ScZh6ZCx5TIS0 wlNkjJUAAK9nTCzYeljz5VkYMjCbLPTq8AImpVtdM1evslNLZKkn2MzFc5seZ23U k173Wgg5gIk699sKPS7m9mEd0J1zO+LOyg0W7fthkoNhX/D4wm7pM/dTprmu6w0N sx34NucaB/uA+BEONCG2m+MYpKEyI8v2NxI1O/8PHnJLFIt8c9kFbB/rHlbHf3oW RLyJnC9WqNXq06E5lEBH3Lg4lOdij4ZIUd10gDpqdLZ2iA1diuwGXr6sTEBtE7yP Ga8LoVI3+WgZg1QUv9IB4xuUVGO9By0R2K+/tBYFTj21ZeV9ojvPHxt99rI9vNm8 VClqMFnn/mYFMMhZzDLj4rwmnIyeQiVA6Ea8dzeaAw9wYzJFDkHB73BDHw5Meo2C gWcIBkR4m9ipOoVuPEbPuZsGRBGr4+51om7FI8aWOUakwmvxjvBihl0wG/7STA50 sOF6l03vIxHeVbkeXBHHi3exIwKoPVBINvK/izHJpB00W2sBEDeOE0hVS3MLNzEA MGG+pfFzRCgCli/ysgmVrFtSZnwuO30cZmnAxiq8k7EKjgi2W4+UFRBsIijxBAov KedqzahkVkxHoSb8YPzrZplGpEtKENhxmy7ONHen2fI2DV73XLvR0kSHY/tBApZE RjRT94Os7jZ+TUEDCzEXTlNRPtjIzHxzfXHe9YoKVVgYAtSkaL/zL5MMUHxhdFi5 wx8s/DNjJwbI5+FrHb+8L4l0Lw+w1o2x4A6Y0YiNdLvxL3OYuT9DLP/B9+lrzReI O8YE098O+LPlTRerZ4zlINgvna/ZChuizCj1wtoovwcKYOdeYx1cGD5RIwGxK9+M MFLeeFsD7XAdlB1/rp27QlBLkLhe0XK61a0XjmPJoZI4cEcOUFDflSTW/nP4D5r3 0JaUfRI67k2jKdHKIqjyH2MQnluYk7iHkiEKX0cgaNSnYVSXNG37DtgXnROPpC17 hMm/X6ISugGtYyTnkqK+vHqh5UwmrTbwo1MaQjMTstBl0SqcI40O28J5cTXfQGFW 2wfkWoXCuMaewiX7ihOQOx3bhJhWS+AbXaIKLxqL/NcQv7zeRDRrAmcXndshmkas X0oosS1gp0LjDfmWsK++/6XtyMFOY186DKRmGZ5iGuISe27I4eIJMTZljeyKF5uI 7ispS8hoxLrWYKMhm13Nfe0xTE/X3TaQVGZzjzGw/EmWmpV63Hv4EATMfhkyFsrj S5gVJSARuTQHbd7Xt33K/3d7G/w3fiOZH9iEx4zT1S1E8ZhN3JgbtiFg3vc0M008 2GIMt43mPrIlueV2KgD+lgKodKJl8ake7+7DJku1cfpXYJmaABh4tEzx/WDrB6W2 HfzwI5dT0LEmqLE7vIoByw0BKal2Fby5rRyV2/X6T8Sv3quoWxRfW1+aFrG8X5HH wKDXwksJnlVWPnkXdgY67XB4ZGUUcU8xutsa7fJkxNOnEOPcotAJyc2VOyB/mW7t sIr+QBAuFiWhMXloYBEwTz5EkGrGnSVS9z6fV6dHncbCzPjFvpBzIOVRp7+kr1t/ nRyZCFFzjumFcD/eWSZ73z1oxS+kK/FET29AXNBtDJ29q3jAJ9tFfWmz0LZcPUyK SsEANv/hjjnYwsXxkxW9QrfPTUY7CZ5H9ogDT9e3OU/pnhKSlKV2h6zMky2Z1ueX 1AIAWOC8OMNxvhcc8yc9nfjd4J/k2f6MsNFE9otXQV34ER6c1lvyv+FTJaasWJ7w 5CHFrOXJ43/e13OOQZ81eW3Sl1i4sswvb26zGfpwLBJ5Pp6RmGVfxbsruC4IXaTI ViaF+Kni0L58X7wtAGNA8U7Alt9Ontmx8jwdoS4ENcHPhc+d092bJwCs9xCI2/QR aZh0FVfEE9whp8FQf0bD/+TiJCTNIFnyNcZM6li4CjS681aNoetTWW5ATTbDhn3q FomIcfC7BnYi2P7PfoqKnD1BBZ2a5aZP49XjmSVAZfQhG0dicXBaFwx10xBF9Suk jnD2ews5KtZHupMzkUE0hjzubvJBNs5+RKxK3uo24lW0K2UjEZlK/pMhFaGk0Ctz RTSIJlj1ISzCXMxMpIZoApZUEftA5KswX0oOZ4N6mowS9WxOnSzTnCFM6i26K0n2 eO7tbmU+WvYrHrPMOliiqldFeOGjMtvaGOJxWHyzxQyd+x7PJvwMVvWFBA/zTOUu 7a4EcF+bW7Dc3NJNSshKmWWCkLw79Q6nH9NhrbHsCEKGfkB/hwNYU3hXcF4N5M2B rJ9PEgmQH1cWdEDg/kU7aCyCgrhE2Nj2N43r7Z1eO8y39gagRXdnUwIKWGt7rQ7J R7tmgV9mIMqr+Sa/rRUj1WHpbdVAnYpzIikzxWY2Oo4Blix/YJVwPIGOoPc0cVGn jcQrazLKP06dkVkrQafXRSABo6qH6+g8fguX5cNLsUrzkVLJ/i1IHL+wnA2zhBQx FHyqiZ9+cFpmFuc5R21imMKWhrPN/V4VKfWo9mCLIPQOU7+qzdN8663j/vkBjoK6 J7mJR9r9lOXaCoM2cVTmf2MTfOHC6zt00rUWxzM5VSOtPqo8cLmTh1R/L0OxMMmH wv+awV5cIRbRXKlKxE6wkWKa/og8LZPvbPiQ6mJq6t+VrS900ersmH5Z4tYp4SEg HuSmfsYhR9pz5qiCefcxpmyHu9bs8zaL1BLDOUWYEfNaX+Ds7iWbADZ3N9dc0D56 bUTqozNvheoBRQfrRjB5YLhFNU9E/neA+EZVd/pn8V65mKpa3LTveHHXsSxLrzG/ aFRzmX+NVI7jiCOYRsq+DFxFtjVyokwabE8Hqp2GuW7rOoBMuRoshtMdmC5TTNFH qpAOYV1/gbM/DV2JAta8KlyFE9gNTo10+73mnha72em2wG0iZtT/Wdi+aIZ8F2Gp ifRHNWQ0kCiopZ2PUj+YSJ90Bt7p8ozE1S4u6IBLbc/cmb5l5eeWv2XWWipaIgwH +N94ZlnPfBMD7A2ylkAwIrtS2e0JbFrAGv5CfbWD7g7TaNEyvK0FaEzOK/qWO8Aj /o8ss225lK9H0Q8PexXCOCcpSX4gMgqyhpe1vWxKiWT2JmWF3H4cGAGEk4kjTSAJ HU0m7BIZUuS1ObeOnk3F+EMeJfqmMV3+gbr56cZFd4xwhU7jSFmOm8XCO7ml+Vzg 3SHZo642j3xKtQKuwiu+vKWnRTE3Dw2MH9IuCp2svHzrq9GNnqDxz7S/PM2dhOs8 v/ld750Sy6NIMe2GkbHNZj69JU+bChZMMkAnroAHuhshjESs9aJR5cQ6DD5jl6eZ zzkQs7Ss+KhTVoSHlANVNvsRqUtmpiSpTwvp48VeFr9oiBBQOGypqVEnURteBQzR q00017LLx3HQfyZPeY/mCBzKc/bI6e1S6yCFOK7ux2pp5VIrVlIRFaauwZhPjOHW uw+CwxcDsdHanT+uvn8R+N0NEzY9txY/jcsjL1gym0ih9aej8mzcVsYo9PJzuL1i /5+ICfXxBn9OZ68SJvFF5ZvOdj/IL0mlZYKOcUD/W9Epld4IJ0Dg8jHUQrr5wTFX uezEG2FYVc6qE23k5AquUBHyjjDX3Xw49ZMa+xdkKJj1pWu7ool8PzVGiekNIfw+ ujbLN3x6HGdN5UBZ7kL1vu5sT4mjhlHKDtbtqkKPjNwq93oQzjxBPMdvRcftcwUI SPxbhkFCQcjBlo8UNM+5bId91QfrsEoaoujOPyl6Fwfdw8Ut3hHBTCNSAZq/+ott wCEOZGmOJl64ap79SwONRbViSA7oAOAcHxwykziTMjLkNK5cuKUECqoX5HHC2nvT UxqHF3+2D5wafXlPlnOqd6Sl25NHLmcfO5JozsW04V0iY4av6L05dHtNys+cZzGP yE5q9jSX3mx4ZE3xIWNsj7dqXDJqBAVMXDiS44uiaaLE0nkURhj81VgdPuEtHDtm sVM6E36VjmLiJvX22fGSbwnFxWmdzYRiBhKIDc5MF7akUmKGp5zs7Q6j2KHh3hw2 j0NL9NnMIDTkAXfLGEDJ0EZbgx1sGpGytb+IPMkxOKQYYDDy9MJCl0M17vZuIzs3 8pHiilm/rP1IQWGKN1EbdVRdwz0ms9qsJcP6ON6SckUOBQbEfAZyprkcqfzavgUN vFO1HQdEdXOBbYYx0Oq5ht3CD41jjaRGS6X9PN2mFZWTuGgSS4flAsMEIqky5ryn 9wO5O66pNcEe5mhYzdMkdtFVD6ylkqW/C+OCP32SVig/D4vOUOpMgAP6sEVljwSo 8qx77QwxiwGzOlLF6wMmuwIly06J5cgFr9utkg1g9yusYaMCCikw1BUyFI48ocD2 wPVx8F7eArNkWOkOmsOjYfMbxB3lfKgSvzPFWDWnLTIjeMC2PemL4sgF2oQrUWwM QnQZH8mT956j7HlchAuF+OIhjPE9SM53HYFE9WwGqrfoUXzF2KgJL8rYyZnYSGig boGi6ucrnILDu3et++isaF5fnFXZw/rfd1yBwDhUdDp7MjlWj/cwt3qntFA+yjrk 9CsKIINqLytWAZlq8+DJ/+YbS6pReM9zvMeUggavqHfX6pS/lpo2DvVs452XOT6j vrtIOgHjfVOnc9CsKgy1K5MQw+esXUEfZQubG2Cx7hpIvZrAmkXxAfYF+gbtTBN5 kHTDkqIk/gdX+Hcsolyxx2mpEUct+GaL+yWruGbOt9MVLgCYb5zkEZkMaO+2Wsyu 4DOqrqeCX7uazS0q0c2AsWwFvuhTjc8DdKhTwkgMi3lg077F2K2XIBbwVTsV3573 qiz80YaaYL5lYOe6t8yHVjI4D5o2NCBuzAzr8snLlaPBbDv4sf8MzwWSiaRUqUC3 2RVTJrR2xSLl0dzxsHLlHokK+oXyQd7P8tDa6aDei89rPH6vtoYlhDoKFj6D9NQr FNXhupVF6F/VI2Sg2J2HthOkDuBuwTPF/KBHkDC6ZwvNuBJe9D48rsXY0/gW9x4e hp486DJ1Yw3VZJX16qAPqLEwZ14Wmshy0eKtMo6nGEX4B7nDH9P4/tI6Cs/YlC45 dnLNrZt5/DCIyBDyxUFVUa7+AKQrFP5GPPyOm9dVxUjJurjYnchlyclcCFuXpB5E HYMVsGJ8KXXwPI6euprHjNC6Qs2YatGxXJBsgJdHzu/rCGHu6PCfR/v7CkdzlMaU ZhqXKYQWkIxBNXus+P2GJSTxj1gZ2dNnQK1FN9JHwMNOG0TUcxaBNXqThJhds/1e bkoV3uJnjFIfvH84I543KK0VAZ054hYi7v7bysOnln3edkp/kmT3fIdL4ALAaQvF XLuekfg37OpWlcveaA6UHKtuRqOPvS+JI01mRZCm2938TUufiDZ5WNRPM597Ql9g PtsoVvPwG0Qf2B9PsWhMwVb8KYrw9bp4n9zjHo9IvQ38XkcuZFNKsOonjFOMN3JO OfizNttBhLVWvO7xitg/tEBgZdtIdMjAzz0bySsRWq7Ch1dHum2tEn4BnLJv6ssI 9picyDo5DFA/DFscxSfhfNX+lmwjTTRQDFo8oEs/qPwGpVnBZG2o7Cyj7E5qtHdc 5j0a6H2xIvvdKMer9WdFlJHDBNclGry4zj4SNLoAsXB4fr2PInXXGpBuwZd+pM70 7HahEgATVKLRvAv32ugz9dfbVUE5muE/t7HK6HHEOzSEPCXHDOwnv9WFxJq7o2j8 RhX0dvjDGIetjRJqHmWOYOfPqSJ9R8hKhG/3iiW6LRYqTixg7sYl26AQEEYZs6Zu 9EhAaf33E2SqxXo6LC9VGIvOTaRTMYWm2HIISlrt/DUDCoDTsJmI5Rmow9dl9obx V4wJaw49pCG6F8qKXJVzp8y+Qk8lI8gJVZi+N0FFnAyNauxpyFU2XnO8yFjy3wt2 DygYrNJFz/tWzn46DRblZeZv4CQ2A6tWU9VwRNQwKagpgqOUSzzSROCl3ZC4vTyl euGse11YAtr0M+Yfk19+RhwSpRHXh7ibIVmzcFM32udritk0blFrnFHKrcEGk8ny Q3UeJrhTGjdm7pFfl6qs1iuqRHX2ToMyIuO7YlAZIaZYnN+/DxkZs+mBYlaa3wka mC1l7GtFnBTVC7Tbe0kltVKeoGd2afgz/aQYuMEajvbftv55owXTrz2TGzWEk/N/ jsdUccGwDhhNk8oYcgcsFyE1c7Wj2nfnwP5gFStkW9xjXVrkTAf75mwMmCR8J8Tv 0+4onWDOV/7o1mXGpmI3vDfF2ULlT3gqwofTXlVCMDLzUzbdWZ9maTjOwEjC9OHC aXmQqATS5XxFxQomlY65vB4bM/H+K97Hs5OuZdKylIc/myHOOJ2HqIOzhicV/AUi r3WLcYLAKO2IHh4O/3/xTZGfx7QOhzn5brGr4Je1MkXChCHIPB5DY+DM/Jz5UvJf v5LB+op8noP0Vd8Q1KmWGZCe2tp36rAfecyfdyXfOGOpTZy/YKoi9s/t0y7H+1+Q LFoslEVkPdtSBnC1forCscDksOzo3hrFzvWRaWIXVpRHL5WBUdMfamF67XLFyXAL fnz2jgiY6wPa7yuIOCBWeoUSnghsvD3d911eF6j/NVeJG1amxHlvy1MiWs2z+PeL aX1bzbQFZ9gxDn0b//nlbL+5OIAqO05g12jfhMs6pngwMJo+UNNgZjMF2rbB7uCQ KAKMA+d/h0iwDHGIcdeMVYctX2vMm+An63YUYnzj0nGBbKQMaBwzA/YUkpP7BSDK yLUuWjYmwt6hueqm/rmUGLWCTmEP8mmfNRCjQSuDQYzfZvfymRcwb79tswW+OPAt 9PyGByW8SpLK9JEE2mCQTgkGX/ocoHMGoJeL1HHzlfE9GLgDltra7+9iwEkd58BJ H97hUwsOu45cmpLUJl9SwhJgKipfJCKOsvhNToNdu2ZJFD27DnehSmAbUpJbQNx3 XmuBYbYTnKoWEUCTabKvws7sIEaTJHlBCKSJCj+UiXxmT5xkELXv00dysHKKElpz vby3JY7wUE9agxRsUV1lxHu+AZ6Qi32bPNijLHt45jnVp4mCMEeOQWu58QudX1VE CfjL1Ui1Ie2+6p7ypo8qPhWSx4lywtTu76bfH7BzpxsbD1jtXKFhpZkWnZtlgPt6 POkujmJ2rGo6ddOmdS6RcDVpRyJ08lCSFAqbCjh95v5kOfQaDEoW9WmuAtwDkgFk BRaOAvZ7Q2pDpegnWVqz+nCobOFXp8TQEAQS/fQi7mQPWWZmJoXYzEXOb1Tq18ay ijvOti+MM7sV75kn8otkjVCcvBCYiHhkTFQ249Ja4r9W0B4KQuKt4/Eo6y68Buy4 uvidUtnCG12Uc47o3xErogEKlGZuN/icHXcj4SpDD6qZ5DzMBtJsedVpbzZXtBPm SO2W1XMqAOCKZYvQSgcSrpmTgBf1oZir+nskhomZqb4r54RNaR5nCiO7pO+BwxJn bWVsjiqNx6Q+jn0cG/KiUU4fYBhcfqhd+ZZdWMJkh7CIp8ufMrRqcpX0R1q6Hf52 5mF4lPXI3YmdHE8LRQKptFgjEED0a8C047Wdw1zB92nagTWxNbJp+lLe76Hmfqpi zyYSHO9dItMSTQEY146mPl3cPiL2t6b9aXgPbJyvYePZEdcTyXDICGTz3glX16g2 unY64GqIDZyMqukUCxV6NSiO2KA91jRIEX0C4T8aMGUSct5l2okqBip/w1lVx47D VWfwmBUtfz0A9Lk5YQ10JQcFiMHkO+K5JejOI89rL2DWxkwMxzynVBO4tzdN00Wu Tf+0eIPIaesmTfg+chQ6WLTbeER5o2+fEwh3XMah9d/VjJ30/8UDQ8Vz451iQYW0 tg/er9E1V78NZg8OqMKhCmsLqr0zXnOH2TRiSxsmVLU8rE9J+nd2y+MKCzNy4/7E diYmTUXJRfJbFsi5f9jtxAg9vOFjGIY4g+9pEGsVDtduqkvTrN8JdB/d1afxRkH3 DQ9Bqqo6RpQTBmXLdbOyYeFl9qWENiCDDFLvrUibG0GNdRh6GyDczKsrOXunVepu VoMblwzLJLBVc9ixM2XhOz6keBwLhBDQPqLp1ewuWjuyKO2Do7IHA21vR2tx251E DGqg7D20OkjtZ+vH4InbVDqZdR3OUnqqciz6HNt45PRBGs6dtr/JzlPOY3xSbwsG 1KWPcXvNvF5L2Gz3lCLfJzOz9SUp2UlBKDgQKwBUnVvJecwbGv6GY67M1bml27PQ I3Jf4IGMAcu1GAhe5jCoFMHdFnbR8Iwovd/cXn/xCTOPAYAXNb0CsmB2xLxWb5Zr nkOw2MNfybFVuv/S8mxzoiwo9tmmEGp3+/TdocP7EN5jt0WPPH3vc+O7cXBKPydq XLPlhdjSSVvRnux965U2/wrU3RO4vaTNBrfE881rngc7Tm8dsiYlNiIeT7aIDMHf lpQ0DzxqBd5DjnhMYqjp68qb64l318X84MocAWORPcHILDFvuHhGKohOQzsay6N3 ijJ2UT3jLXhJr6Bm7/kR898ALgSAmiPvQjsUH8ZwbXiVzzNTkjgIA/wn8GnmgMcR 0MHnRsY9sYwuOdUFxNknWIhykATZiLwuinNB3f23aqB5sJ0LRqw9URYX6PjOuQry a1MjYKDgCvC3flkVto7KPRbLDzUp9P8dlXb54oyuGb4t7VQGAlnm4etAsZtct6Cz C0squcoSCl8Hr1k0dmufoA/RUE5ft+fOYXFbnMyIwyD52pkE/EbgMk2pEDYKZPGK 2WgQYL0V5eEQYg9VG3pbc320PJblCs+pNEAiaRV56z/9IoEfiz+iqKFk+Y1Dp93L ldk/gvaYbGhJrLezkCGN+WRdFQPaEZjTEZy/Rr+DCuHmUlLW2t2MJPRUusrvVuRP P5MH0TezZXRFrGJGSmm7SDeZFV6GI2g0R5nYhHQcI4xsbyTL9xVLEsADLWbv0/6A lq7YVByi+H5ZsWAks4QSN1CP8SuaPHs3lKADOOuN/vdi3LPm5KcwlvRqTbGtkMiz lFyt9hsqGzYSTujGwXWarRZO0eLPFdX4SRfSH1DPlsit5woUN/YvTz/u7n/XiMCw fcXGx2SfJqKJEBqtB9PuD4pe8oT5PIDJyq6k4hNoRNwfTo7qD3ICXarjQLFNOtK1 pI8ZuNnfM2kRd2C1zfQBj7HGCxLmX5VTJvRoh6HWbmL8kgglqp447fF3aeXG5c5G KcKbHl97IU7k5He00vBbCtRIfYDE2bifqA+KMJBKgj/uviD2TWP99y8fvKTf5zCK VhkF6sXoKpDvicilMOTFNVWK8oqPlScrSNM5bpKTU980+1qJYqyOxk3bJB8NIpkn Y09lWrb446NhiI73+2e6m9YHS1uER3qrvcgaT+XLMGaBIln3U2dSmS5iNxnyeEKs B0axBrbsW+joy6/7XddR1dEc5953wPthH50+k5okQ2X5ApmCG8V152vsjOxTLS9J RfndYMjh+Afc/Vabc5l9XC8i7Pp4yJy7p/6aTwPUU2V5BKIp2bLyl93CoxW3lrRz aaGhiVoZfryuJu6/b2+Pq+0rnKPD4tvDbA9oRF0Cin1YPgwcf9Joi8TpzyyAjbs8 nXXe57FGDIrZS2sjEmGeGTN0x/eKo1/kTEXcG+gIQGsyxkJqPCBXmxK6F5zemDld jd1Yk1ybcuIv/zt2yV8AC3LrmA5rIJxmZ+9TgVol1SEfuzsQzJfznA1kTFEPZsCT bpFrQJTjLVIZOAYuugtCDqpJA135UG63y2TTqfh34/ROLGeZOqNpgh3T0P75E5Vo pAz7ejWLr1J6eIabiidEJWHrM2SFp4ptwlOkXNeuwByF7fujDtChn1P/K86jGCyF RcbY0tY3BnGIaqWj9hYkFHFb+uVtN86315zPS6nwzQHP5YFzFojWRAz5QAcQJJij FY1ziDXSa4TwjEEWLUJDw37Q6HlJWGgkomuEeAUe+uLBNywG4xWG997FJR+JveUY OpZGbp/oDCBmNqd3X/lEA1sv9puLQvzx3EPAQ4RZrfMeBuAxUA+LhywT8roy1cdA qzVu2gda6yZZ1cx9LeyZ7oJGLTbmWLZaTo/KvJpGMiE2pZQwMVLtat1yBzdDqSSg OsWbjweY0LnO3oHFfF7ZNHNzlvobd7PWTOVNv8XtAlR2w0j5Cy4q2LNuxRrFVb+R kVWDcQ20E9ouXsizU9/Fknr8kNCYv+TiGiYTMJmlhYR1ZAV9MpRfBfTWeNnKkIGk YVrTE/LzUOlzgaH7vd7gg4p5zBeX4D0HqUYcnkW0a+0ERRQIcV17WwRqpW01FfZp JhNPK55VzwvElXt6AXw7VN6+80QlEMG2rMQDC3HvOiRUe1nF/ezUyCf8/LJH1O0l iocVKyKa0c8Nm3988zqw2u/I61N+U0APzRkhKMgPoAPjIuPbMKISiB3N94p3cFxF bFuIk03tK7gprJYsgLLd4aVGc8m5/F7N5oLkmS4IDNQKbtAIdIHTaDjzXzUXf+Dl ozPznJ0w6+Q7W2dleli8eCAZhw91whAiVO/0mbiILYRVDmMW2I/q8OzixvBvoHXe nLZ8MLr775BIjZbVe32ZxCI5fMixJ8RpXEMXkG8tR9sScxOoPO3sbr/Vxzxwjs87 D2xRb6MyjtL505ismaCw527/s/i+FuC+tFUobz8Uksn7LeUPKoZzqx8WAs0C5HOf RWCMMTwqaSisdLmayYbwcNz6Lz/b+rgTaVP+FEkW0L5pL7gVs7ibELhs8IhzWItC 6TORs18oENY3d2GCed4MsKY/vLqMvR1Px76ookAzsEKE2gfNyN5I+Slk+ANh2tB1 mfNYA6xuYbbWF6s9YIZS1cXmDHRR3l1dZtk3eF9G58tiS+Axjwq4B9idbZFjJStL AfST8dTHsHoMACJyP1xCaPeQqNnjSrxvU4H/noc4M1wHojvMow5TqX5ba7tp+0IJ ZqeWgguftJqUjDKL6uKItG7PcHM1SLh1xDXWlWvZ0jJOSBbAEegI+4emXM05l7zA rqjfidpICnxs3zE2Fb37jeWB4tgQ8XPICKGG3PGaJOEo3CcGqeDj8STVZ3MZRlqx JoAalHUVOkcdIodcEqZEbKHMCuYMAXahWNpIBCa/zMtbAgWwEYwmyS1A1GoUeSxl /aK4msNGQyrwYI6UP5zWzQS0ajNPKogqdOgglrkTrmDcguycbRGO2EjjME5bfmwf cdDi4JNyoHuOPZ3W0RGkcjLlTcWZv5P1dAh4WUfNKUspAIS2AYI/xxqecp+LsOib jJDX8FFc2/RvJUIMQ/X81gfw2YHIvPlQJM8082mlAOtB0UqM4H7huimxsDjVFweD IJH5Nl9BQqINxco9VdHkfaKGhRweg+x+Gh1DV0c3Vrpn06tiaQ/Ong4ms4pcqNKB vdcoj8RBufvbxEM/ibfP9tV0SLAp9hqrfrUp0LJTDRPale/XYqvheie5kkeg+Kyl ebpCCoEywx7LeX83mp0t0nTXONC+6LGlbE/rIR4qzLJ1uRxeYd8hVvcXcA2kpNv8 9R3R6VgO5Zbi7HOlY7lCn5XevjVG6E6/9iHKcWbwyOZy83jFWkoMESGkN2qay3ru 7m1/e3N/lElAdsdThNIBlvLR46VUJ6rVik+E/XH0kPkWw3LT4rjS4SZ6hEgmUfFj EgSemBKjwyAJqQDw0csXCkYeBV/w2zBi8Nv1PHAMFV32LHHGtpRfvPIJ6MJdVR2U daOpt8+lUZazmUdosgeYqSHMXiwfrqlnCPsmHleW1PfHKba44XbpuDtt2S6UB4lT r358GipaDkow+RpjYf5fTqaQqeRoGY/AEV4D708wjg1EjtwriHBflYjH6fw3iFmR CzVn6u8WjRtRG3WDiWdQkVBPCxbOkhXcbhHAWrzZmPVXWiuAJBjwKofQM5JwjZok mrvzj6vb6vtL+zX3tWs8KYniFN5iJkRU3PyuIXzNzKD6O+vW2ZUASLDI2IqgymHX bRIlAyKTyqWk9piLxjMc+ZW59BWLkBDXNOIr6JGrkyaNCgfWdKCszdOw1MfU7IG4 EcdD4DgJIJ3l2hXNHycE2Upxztp68gESBbBy6OWx/bZ/6Cq3AgL/UehH2awSlCqx TzEMsXT8MHr/Zh50p5HL0w== -----END ENCRYPTED FILE----- #else #error "Secure builder required to compile this file" #endif
63.479638
64
0.952384
35bc9470825b6d1018cc004492247c490c594da5
15,706
c
C
drivers/power/bq24157_charger.c
tuxafgmur/OLD_Dhollmen_Kernel
90ed4e2e3e6321de246fa193705ae40ede4e2d8e
[ "BSD-Source-Code" ]
null
null
null
drivers/power/bq24157_charger.c
tuxafgmur/OLD_Dhollmen_Kernel
90ed4e2e3e6321de246fa193705ae40ede4e2d8e
[ "BSD-Source-Code" ]
null
null
null
drivers/power/bq24157_charger.c
tuxafgmur/OLD_Dhollmen_Kernel
90ed4e2e3e6321de246fa193705ae40ede4e2d8e
[ "BSD-Source-Code" ]
null
null
null
/* * drivers/power/bq2415x_battery.c * * BQ24153 / BQ24156 battery charging driver * * Copyright (C) 2010 Texas Instruments, Inc. * Author: Texas Instruments, Inc. * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/jiffies.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/i2c/twl.h> #include <linux/i2c/bq2415x.h> #include <linux/interrupt.h> #include <linux/i2c-gpio.h> #include <linux/gpio.h> static int timer_fault; struct charge_params { unsigned long currentmA; unsigned long voltagemV; unsigned long term_currentmA; unsigned long enable_iterm; bool enable; }; struct bq2415x_device_info *dev_info_irq; struct bq2415x_device_info { struct device *dev; struct work_struct bq24157_work; struct work_struct bq24157_vf_work; struct i2c_client *client; struct bq2415x_platform_data *pdata; struct bq2415x_charger_callbacks callbacks; struct charge_params params; unsigned short status_reg; unsigned short control_reg; unsigned short voltage_reg; unsigned short bqchip_version; unsigned short current_reg; unsigned short special_charger_reg; unsigned int cin_limit; unsigned int currentmA; unsigned int voltagemV; unsigned int max_currentmA; unsigned int max_voltagemV; unsigned int term_currentmA; bool cfg_params; bool enable_iterm; bool active; }; static int bq2415x_write_block(struct bq2415x_device_info *di, u8 *value, u8 reg, unsigned num_bytes) { struct i2c_msg msg[1]; int ret; int count = 0; *value = reg; msg[0].addr = di->client->addr; msg[0].flags = 0; msg[0].buf = value; msg[0].len = num_bytes + 1; do { count++; ret = i2c_transfer(di->client->adapter, msg, 1); if (ret != 1) dev_err(di->dev, "i2c_write failed to transfer all messages\n"); } while (ret != 1 && count < 0xff); if (ret != 1) { dev_err(di->dev, "i2c_write failed to transfer all messages\n"); if (ret < 0) return ret; else return -EIO; } else { return 0; } } static int bq2415x_read_block(struct bq2415x_device_info *di, u8 *value, u8 reg, unsigned num_bytes) { struct i2c_msg msg[2]; u8 buf; int ret; int count = 0; buf = reg; msg[0].addr = di->client->addr; msg[0].flags = 0; msg[0].buf = &buf; msg[0].len = 1; msg[1].addr = di->client->addr; msg[1].flags = I2C_M_RD; msg[1].buf = value; msg[1].len = num_bytes; do { count++; ret = i2c_transfer(di->client->adapter, msg, 2); if (ret != 2) dev_err(di->dev, "i2c_write failed to transfer all messages\n"); } while (ret != 2 && count < 0xff); if (ret != 2) { dev_err(di->dev, "i2c_write failed to transfer all messages\n"); if (ret < 0) return ret; else return -EIO; } else { return 0; } } static int bq2415x_write_byte(struct bq2415x_device_info *di, u8 value, u8 reg) { /* 2 bytes offset 1 contains the data offset 0 is used by i2c_write */ u8 temp_buffer[2] = { 0 }; /* offset 1 contains the data */ temp_buffer[1] = value; return bq2415x_write_block(di, temp_buffer, reg, 1); } static int bq2415x_read_byte(struct bq2415x_device_info *di, u8 *value, u8 reg) { return bq2415x_read_block(di, value, reg, 1); } static void bq2415x_config_status_reg(struct bq2415x_device_info *di) { di->status_reg = (TIMER_RST | ENABLE_STAT_PIN); bq2415x_write_byte(di, di->status_reg, REG_STATUS_CONTROL); return; } static void bq2415x_config_control_reg(struct bq2415x_device_info *di) { u8 Iin_limit; if (di->cin_limit <= 100) Iin_limit = 0; else if (di->cin_limit > 100 && di->cin_limit <= 500) Iin_limit = 1; else if (di->cin_limit > 500 && di->cin_limit <= 800) Iin_limit = 2; else Iin_limit = 3; di->control_reg = ((Iin_limit << INPUT_CURRENT_LIMIT_SHIFT) | (1 << ENABLE_ITERM_SHIFT)); bq2415x_write_byte(di, di->control_reg, REG_CONTROL_REGISTER); return; } static void bq2415x_config_control_reg_800mA() { u8 read_reg = 0; struct bq2415x_device_info *di = dev_info_irq; bq2415x_read_byte(di, &read_reg, REG_CONTROL_REGISTER); di->control_reg = ((2 << INPUT_CURRENT_LIMIT_SHIFT) | (1 << ENABLE_ITERM_SHIFT)); bq2415x_write_byte(di, di->control_reg, REG_CONTROL_REGISTER); bq2415x_read_byte(di, &read_reg, REG_CONTROL_REGISTER); return; } static void bq2415x_config_control_reg_limit() { u8 read_reg = 0; struct bq2415x_device_info *di = dev_info_irq; bq2415x_read_byte(di, &read_reg, REG_CONTROL_REGISTER); di->control_reg = ((1 << INPUT_CURRENT_LIMIT_SHIFT) | (1 << ENABLE_ITERM_SHIFT)); bq2415x_write_byte(di, di->control_reg, REG_CONTROL_REGISTER); bq2415x_read_byte(di, &read_reg, REG_CONTROL_REGISTER); return; } static void bq2415x_config_voltage_reg(struct bq2415x_device_info *di) { unsigned int voltagemV; u8 Voreg; voltagemV = di->voltagemV; if (voltagemV < 3500) voltagemV = 3500; else if (voltagemV > 4440) voltagemV = 4440; Voreg = (voltagemV - 3500)/20; di->voltage_reg = (Voreg << VOLTAGE_SHIFT); bq2415x_write_byte(di, di->voltage_reg, REG_BATTERY_VOLTAGE); return; } static void get_charge_register(void) { u8 read_reg0 = 0; u8 read_reg1 = 0; u8 read_reg2 = 0; u8 read_reg3 = 0; u8 read_reg4 = 0; u8 read_reg5 = 0; u8 read_reg6 = 0; struct bq2415x_device_info *di = dev_info_irq; bq2415x_read_block(di, &read_reg0, 0, 1); bq2415x_read_block(di, &read_reg1, 1, 1); bq2415x_read_block(di, &read_reg2, 2, 1); bq2415x_read_block(di, &read_reg3, 3, 1); bq2415x_read_block(di, &read_reg4, 4, 1); bq2415x_read_block(di, &read_reg5, 5, 1); bq2415x_read_block(di, &read_reg6, 6, 1); pr_info("get_charge_register :%x %x %x %x %x %x %x\n", read_reg0, read_reg1, read_reg2, read_reg3, read_reg4, read_reg5, read_reg6); return; } static void bq2415x_config_current_reg(struct bq2415x_device_info *di) { unsigned int currentmA = 0; unsigned int term_currentmA = 0; u8 Vichrg = 0; u8 shift = 0; u8 Viterm = 0; u8 read_reg = 0; currentmA = di->currentmA; term_currentmA = di->term_currentmA; dev_info(di->dev, "charge current : %d\n", di->currentmA); if (currentmA < 550) currentmA = 550; if ((di->bqchip_version & (BQ24153 | BQ24158 | BQ24157))) { shift = BQ24153_CURRENT_SHIFT; if (currentmA > 1250) currentmA = 1250; } if ((di->bqchip_version & BQ24156)) { shift = BQ24156_CURRENT_SHIFT; if (currentmA > 1550) currentmA = 1550; } if (term_currentmA > 350) term_currentmA = 350; Vichrg = (currentmA - 550)/100; Viterm = term_currentmA/50 - 1; di->current_reg = (Vichrg << shift | Viterm); bq2415x_write_byte(di, di->current_reg, REG_BATTERY_CURRENT); return; } static void bq2415x_config_special_charger_reg(struct bq2415x_device_info *di) { u8 Vsreg = 3; /* DPM voltage : 4.44V for GOKEY 20121115*/ di->special_charger_reg = Vsreg; bq2415x_write_byte(di, di->special_charger_reg, REG_SPECIAL_CHARGER_VOLTAGE); return; } static void bq2415x_config_safety_reg(struct bq2415x_device_info *di, unsigned int max_currentmA, unsigned int max_voltagemV) { u8 Vmchrg; u8 Vmreg; u8 limit_reg; if (max_currentmA < 550) max_currentmA = 550; else if (max_currentmA > 1550) max_currentmA = 1550; if (max_voltagemV < 4200) max_voltagemV = 4200; else if (max_voltagemV > 4440) max_voltagemV = 4440; di->max_voltagemV = max_voltagemV; di->max_currentmA = max_currentmA; di->voltagemV = max_voltagemV; di->currentmA = max_currentmA; Vmchrg = (max_currentmA - 550)/100; Vmreg = (max_voltagemV - 4200)/20; limit_reg = ((Vmchrg << MAX_CURRENT_SHIFT) | Vmreg); bq2415x_write_byte(di, limit_reg, REG_SAFETY_LIMIT); return; } static bool bq2415x_charger_update_status(void) { struct bq2415x_device_info *di = dev_info_irq; u8 read_reg[7] = {0}; int i = 0; pr_info("bq2415x_charger_update_status\n"); timer_fault = 0; bq2415x_read_block(di, &read_reg[0], 0, 7); dev_dbg(di->dev, "Charging Status : %x\n", read_reg[0]); if ((read_reg[0] & 0x30) == 0x20) dev_info(di->dev, "CHARGE DONE\n"); if ((read_reg[0] & 0x7) == 0x6) timer_fault = 1; if (read_reg[0] & 0x7) { di->cfg_params = 1; dev_err(di->dev, "CHARGER FAULT %x\n", read_reg[0]); } if ((read_reg[1] & 0xc0) == 0x0) dev_info(di->dev, "Current_Limit fualt\n"); if (read_reg[2] < 0xac) dev_info(di->dev, "Voltage_Register fualt\n"); if ((timer_fault == 1) || (di->cfg_params == 1) || ((read_reg[1] & 0xc0) == 0x0) || (read_reg[2] < 0xac)) { bq2415x_write_byte(di, di->control_reg, REG_CONTROL_REGISTER); bq2415x_write_byte(di, di->voltage_reg, REG_BATTERY_VOLTAGE); bq2415x_write_byte(di, di->current_reg, REG_BATTERY_CURRENT); bq2415x_config_special_charger_reg(di); di->cfg_params = 0; } bq2415x_read_block(di, &read_reg[0], 0, 1); if ((read_reg[0] & 0x30) == 0x30) return 1; else return 0; } static void bq24157_irq_work(struct work_struct *bq24157_work) { u8 read_reg = 0; struct bq2415x_device_info *di = dev_info_irq; /* 500ms delay is required * change delay IRQ */ msleep(500); bq2415x_read_block(di, &read_reg, 0, 1); if ((read_reg & 0x30) == 0x20) { if (di->term_currentmA == di->pdata->first_term_currentmA) { dev_info(di->dev, "1st full charged\n"); di->pdata->set_full_charge(); } else if (di->term_currentmA == di->pdata->second_term_currentmA) { dev_info(di->dev, "2nd full charged\n"); di->pdata->set_full_charge(); } else if (di->term_currentmA == di->pdata->third_term_currentmA) { dev_info(di->dev, "3rd full charged\n"); di->pdata->set_full_charge(); } } else if (read_reg == 0xf0) { /* abnormal charger fault case */ di->pdata->set_charge_fault(); dev_info(di->dev, "charger is fault\n"); } } static irqreturn_t bq2415x_charging_isr(int irq, void *data) { struct bq2415x_device_info *di = data; schedule_work(&di->bq24157_work); return IRQ_HANDLED; } static void bq24157_irq_vf_work(struct work_struct *bq24157_vf_work) { u8 read_reg = 0; int state = 0; struct bq2415x_device_info *di = dev_info_irq; /*if battery is not detected, make charging set disable*/ if (!gpio_get_value(di->pdata->vf_gpio)) state = 0; else state = 1; gpio_set_value(di->pdata->ta_enable_gpio, !state); pr_debug("%s: Set charge status : %d, current status: %d\n", __func__, state, gpio_get_value(di->pdata->ta_enable_gpio)); } static irqreturn_t bq2415x_vf_isr(int irq, void *data) { struct bq2415x_device_info *di = data; schedule_work(&di->bq24157_vf_work); return IRQ_HANDLED; } static void set_charge_current(struct bq2415x_charger_callbacks *ptr, int cable_type) { struct bq2415x_device_info *di = container_of(ptr, struct bq2415x_device_info, callbacks); if (cable_type == 2) di->currentmA = di->pdata->charge_ac_current; /* Cable AC */ else if (cable_type == 1) di->currentmA = di->pdata->charge_usb_current; /* Cable USB */ bq2415x_config_current_reg(di); } static void set_term_current(struct bq2415x_charger_callbacks *ptr, int term_type) { struct bq2415x_device_info *di = container_of(ptr, struct bq2415x_device_info, callbacks); switch (term_type) { case 1: di->term_currentmA = di->pdata->first_term_currentmA; break; case 2: di->term_currentmA = di->pdata->second_term_currentmA; break; default: case 3: di->term_currentmA = di->pdata->third_term_currentmA; break; } #if 0 if (term_type == 1) di->term_currentmA = di->pdata->first_term_currentmA; else if (term_type == 2) di->term_currentmA = di->pdata->second_term_currentmA; #endif di->enable_iterm = 1; bq2415x_config_current_reg(di); } static int __devinit bq2415x_charger_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct bq2415x_device_info *di; int ret; u8 read_reg = 0; di = kzalloc(sizeof(*di), GFP_KERNEL); if (!di) return -ENOMEM; dev_info_irq = di; di->dev = &client->dev; di->client = client; i2c_set_clientdata(client, di); di->pdata = client->dev.platform_data; ret = bq2415x_read_byte(di, &read_reg, REG_PART_REVISION); if (ret < 0) { dev_err(&client->dev, "chip not present at address %x\n", client->addr); ret = -EINVAL; goto err_kfree; } if ((read_reg & 0x18) == 0x10 && ((client->addr == 0x6B) || (client->addr == 0x6A))) di->bqchip_version = BQ24157; if (di->bqchip_version == 0) { dev_info(&client->dev, "charger chip rev error \r"); dev_info(&client->dev, "unknown bq chip\n"); dev_info(&client->dev, "Chip address %x", client->addr); dev_info(&client->dev, "chip version reg %x", read_reg); ret = -EINVAL; goto err_kfree; } bq2415x_config_safety_reg(di, di->pdata->max_charger_currentmA, di->pdata->max_charger_voltagemV); di->cin_limit = di->pdata->cin_limit_current; di->currentmA = di->pdata->charge_ac_current; di->term_currentmA = di->pdata->first_term_currentmA; bq2415x_config_control_reg(di); bq2415x_config_voltage_reg(di); bq2415x_config_current_reg(di); di->active = 0; di->params.enable = 1; di->cfg_params = 1; di->enable_iterm = 1; di->callbacks.set_charge_current = set_charge_current; di->callbacks.set_termination_current = set_term_current; di->callbacks.get_charger_register = get_charge_register; di->callbacks.set_charger_voreg = bq2415x_charger_update_status; di->callbacks.set_control_limit = bq2415x_config_control_reg_limit; di->callbacks.set_control_800 = bq2415x_config_control_reg_800mA; if (di->pdata->register_callbacks) di->pdata->register_callbacks(&di->callbacks); INIT_WORK(&di->bq24157_work, bq24157_irq_work); if (di->pdata->ta_irq < 0) { ret = di->pdata->ta_irq; goto err_kfree; } ret = request_irq(di->pdata->ta_irq, bq2415x_charging_isr, IRQF_TRIGGER_RISING, "TA_nCHG", di); if (ret < 0) { dev_err(&client->dev, "request_threaded_irq() failed: %d", ret); goto err_kfree; } ret = enable_irq_wake(di->pdata->ta_irq); if (ret) { pr_err("%s : Failed to enable_irq_wake.\n", __func__); goto err_enable_irq_wake; } INIT_WORK(&di->bq24157_vf_work, bq24157_irq_vf_work); if (di->pdata->vf_irq < 0) { ret = di->pdata->vf_irq; goto err_kfree; } ret = request_irq(di->pdata->vf_irq, bq2415x_vf_isr, IRQF_TRIGGER_FALLING, "BAT_REMOVAL", di); if (ret < 0) { dev_err(&client->dev, "request_threaded_irq() failed: %d", ret); goto err_kfree; } ret = bq2415x_read_byte(di, &read_reg, REG_SPECIAL_CHARGER_VOLTAGE); if (!(read_reg & 0x08)) di->active = 1; bq2415x_charger_update_status(); return 0; err_enable_irq_wake: free_irq(di->pdata->ta_irq, di); err_kfree: kfree(di); return ret; } static int __devexit bq2415x_charger_remove(struct i2c_client *client) { struct bq2415x_device_info *di = i2c_get_clientdata(client); kfree(di); return 0; } static const struct i2c_device_id bq2415x_id[] = { { "bq2415x_charger", 0 }, {}, }; static struct i2c_driver bq2415x_charger_driver = { .probe = bq2415x_charger_probe, .remove = __devexit_p(bq2415x_charger_remove), .id_table = bq2415x_id, .driver = { .name = "bq2415x_charger", }, }; static int __init bq2415x_charger_init(void) { return i2c_add_driver(&bq2415x_charger_driver); } module_init(bq2415x_charger_init); static void __exit bq2415x_charger_exit(void) { i2c_del_driver(&bq2415x_charger_driver); } module_exit(bq2415x_charger_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Texas Instruments Inc");
24.656201
79
0.712148
6d96733464af68f0b4b9edcad25728bb299ec54e
421
c
C
fiddles/c/fiddle-0002-ArithmeticOperators/arithmeticoperators/src/main.c
oneorthomedical/house
03bc23075f4d7a18362f596f96fabddcb237af30
[ "MIT" ]
48
2016-01-06T14:34:26.000Z
2021-07-14T16:10:36.000Z
fiddles/c/fiddle-0002-ArithmeticOperators/arithmeticoperators/src/main.c
oneorthomedical/house
03bc23075f4d7a18362f596f96fabddcb237af30
[ "MIT" ]
311
2016-05-28T12:35:22.000Z
2022-03-25T14:57:06.000Z
fiddles/c/fiddle-0002-ArithmeticOperators/arithmeticoperators/src/main.c
oneorthomedical/house
03bc23075f4d7a18362f596f96fabddcb237af30
[ "MIT" ]
33
2015-11-07T06:39:17.000Z
2020-12-22T18:59:14.000Z
#include <stdio.h> int main(void) { int a = 100; int b = 2; int c = 25; int d = 4; int result; result = a - b; printf("a - b = %i\n", result); result = b * c; printf("b * c = %i\n", result); result = a / c; printf("a / c = %i\n", result); result = a + b * c; printf("a + b * c = %i\n", result); printf("a * b + c * d = %i\n", a * b + c * d); return 0; }
16.192308
50
0.420428
ed75c9919c6a8d5c354b925f5bb45ae43864ee98
8,087
h
C
IceSDK/Utils/Instrumentor.h
loanselot1/IceSDK
3d8e554ac6ca56a890b74b5f4cc1901f073e3f64
[ "MIT" ]
null
null
null
IceSDK/Utils/Instrumentor.h
loanselot1/IceSDK
3d8e554ac6ca56a890b74b5f4cc1901f073e3f64
[ "MIT" ]
null
null
null
IceSDK/Utils/Instrumentor.h
loanselot1/IceSDK
3d8e554ac6ca56a890b74b5f4cc1901f073e3f64
[ "MIT" ]
null
null
null
#pragma once // https://github.com/TheCherno/Hazel/blob/master/Hazel/src/Hazel/Debug/Instrumentor.h // Apache2 license #include <algorithm> #include <chrono> #include <fstream> #include <iomanip> #include <mutex> #include <sstream> #include <string> #include <thread> namespace IceSDK { using FloatingPointMicroseconds = std::chrono::duration<double, std::micro>; struct ProfileResult { std::string Name; FloatingPointMicroseconds Start; std::chrono::microseconds ElapsedTime; std::thread::id ThreadID; }; struct InstrumentationSession { std::string Name; }; class Instrumentor { public: Instrumentor(const Instrumentor&) = delete; Instrumentor(Instrumentor&&) = delete; void BeginSession(const std::string& name, const std::string& filepath = "results.json") { std::lock_guard lock(m_Mutex); if (m_CurrentSession) { InternalEndSession(); } m_OutputStream.open(filepath); if (m_OutputStream.is_open()) { m_CurrentSession = new InstrumentationSession({ name }); WriteHeader(); } else { } } void EndSession() { std::lock_guard lock(m_Mutex); InternalEndSession(); } void WriteProfile(const ProfileResult& result) { std::stringstream json; json << std::setprecision(3) << std::fixed; json << ",{"; json << "\"cat\":\"function\","; json << "\"dur\":" << (result.ElapsedTime.count()) << ','; json << "\"name\":\"" << result.Name << "\","; json << "\"ph\":\"X\","; json << "\"pid\":0,"; json << "\"tid\":" << result.ThreadID << ","; json << "\"ts\":" << result.Start.count(); json << "}"; std::lock_guard lock(m_Mutex); if (m_CurrentSession) { m_OutputStream << json.str(); m_OutputStream.flush(); } } static Instrumentor& Get() { static Instrumentor instance; return instance; } private: Instrumentor() : m_CurrentSession(nullptr) { } ~Instrumentor() { EndSession(); } void WriteHeader() { m_OutputStream << "{\"otherData\": {},\"traceEvents\":[{}"; m_OutputStream.flush(); } void WriteFooter() { m_OutputStream << "]}"; m_OutputStream.flush(); } // Note: you must already own lock on m_Mutex before // calling InternalEndSession() void InternalEndSession() { if (m_CurrentSession) { WriteFooter(); m_OutputStream.close(); delete m_CurrentSession; m_CurrentSession = nullptr; } } private: std::mutex m_Mutex; InstrumentationSession* m_CurrentSession; std::ofstream m_OutputStream; }; class InstrumentationTimer { public: InstrumentationTimer(const char* name) : m_Name(name), m_Stopped(false) { m_StartTimepoint = std::chrono::steady_clock::now(); } ~InstrumentationTimer() { if (!m_Stopped) Stop(); } void Stop() { auto endTimepoint = std::chrono::steady_clock::now(); auto highResStart = FloatingPointMicroseconds{ m_StartTimepoint.time_since_epoch() }; auto elapsedTime = std::chrono::time_point_cast<std::chrono::microseconds>( endTimepoint) .time_since_epoch() - std::chrono::time_point_cast<std::chrono::microseconds>( m_StartTimepoint) .time_since_epoch(); Instrumentor::Get().WriteProfile({ m_Name, highResStart, elapsedTime, std::this_thread::get_id() }); m_Stopped = true; } private: const char* m_Name; std::chrono::time_point<std::chrono::steady_clock> m_StartTimepoint; bool m_Stopped; }; namespace InstrumentorUtils { template<size_t N> struct ChangeResult { char Data[N]; }; template<size_t N, size_t K> constexpr auto CleanupOutputString(const char (&expr)[N], const char (&remove)[K]) { ChangeResult<N> result = {}; size_t srcIndex = 0; size_t dstIndex = 0; while (srcIndex < N) { size_t matchIndex = 0; while (matchIndex < K - 1 && srcIndex + matchIndex < N - 1 && expr[srcIndex + matchIndex] == remove[matchIndex]) matchIndex++; if (matchIndex == K - 1) srcIndex += matchIndex; result.Data[dstIndex++] = expr[srcIndex] == '"' ? '\'' : expr[srcIndex]; srcIndex++; } return result; } } // namespace InstrumentorUtils } // namespace IceSDK #define ICESDK_PROFILE 1 #if ICESDK_PROFILE // Resolve which function signature macro will be used. Note that this only // is resolved when the (pre)compiler starts, so the syntax highlighting // could mark the wrong one in your editor! #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) \ || (defined(__ICC) && (__ICC >= 600)) || defined(__ghs__) #define ICESDK_FUNC_SIG __PRETTY_FUNCTION__ #elif defined(__DMC__) && (__DMC__ >= 0x810) #define ICESDK_FUNC_SIG __PRETTY_FUNCTION__ #elif (defined(__FUNCSIG__) || (_MSC_VER)) #define ICESDK_FUNC_SIG __FUNCSIG__ #elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) \ || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) #define ICESDK_FUNC_SIG __FUNCTION__ #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550) #define ICESDK_FUNC_SIG __FUNC__ #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) #define ICESDK_FUNC_SIG __func__ #elif defined(__cplusplus) && (__cplusplus >= 201103) #define ICESDK_FUNC_SIG __func__ #else #define ICESDK_FUNC_SIG "ICESDK_FUNC_SIG unknown!" #endif #define ICESDK_PROFILE_BEGIN_SESSION(name, filepath) \ ::IceSDK::Instrumentor::Get().BeginSession(name, filepath) #define ICESDK_PROFILE_END_SESSION() \ ::IceSDK::Instrumentor::Get().EndSession() #define ICESDK_PROFILE_SCOPE_LINE2(name, line) \ constexpr auto fixedName##line = \ ::IceSDK::InstrumentorUtils::CleanupOutputString(name, \ "__cdecl "); \ ::IceSDK::InstrumentationTimer timer##line(fixedName##line.Data) #define ICESDK_PROFILE_SCOPE_LINE(name, line) \ ICESDK_PROFILE_SCOPE_LINE2(name, line) #define ICESDK_PROFILE_SCOPE(name) ICESDK_PROFILE_SCOPE_LINE(name, __LINE__) #define ICESDK_PROFILE_FUNCTION() ICESDK_PROFILE_SCOPE(ICESDK_FUNC_SIG) #else #define ICESDK_PROFILE_BEGIN_SESSION(name, filepath) #define ICESDK_PROFILE_END_SESSION() #define ICESDK_PROFILE_SCOPE(name) #define ICESDK_PROFILE_FUNCTION() #endif
33.279835
87
0.517992
ef837890d1b49436843ee4b8153bdcb9ec623175
3,402
h
C
Builds/JuceLibraryCode/modules/juce_gui_basics/buttons/juce_ToggleButton.h
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
[ "BSD-4-Clause-UC" ]
null
null
null
Builds/JuceLibraryCode/modules/juce_gui_basics/buttons/juce_ToggleButton.h
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
[ "BSD-4-Clause-UC" ]
null
null
null
Builds/JuceLibraryCode/modules/juce_gui_basics/buttons/juce_ToggleButton.h
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
[ "BSD-4-Clause-UC" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__ #define __JUCE_TOGGLEBUTTON_JUCEHEADER__ #include "juce_Button.h" //============================================================================== /** A button that can be toggled on/off. All buttons can be toggle buttons, but this lets you create one of the standard ones which has a tick-box and a text label next to it. @see Button, DrawableButton, TextButton */ class JUCE_API ToggleButton : public Button { public: //============================================================================== /** Creates a ToggleButton. */ ToggleButton(); /** Creates a ToggleButton. @param buttonText the text to put in the button (the component's name is also initially set to this string, but these can be changed later using the setName() and setButtonText() methods) */ explicit ToggleButton (const String& buttonText); /** Destructor. */ ~ToggleButton(); //============================================================================== /** Resizes the button to fit neatly around its current text. The button's height won't be affected, only its width. */ void changeWidthToFitText(); //============================================================================== /** A set of colour IDs to use to change the colour of various aspects of the button. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour() methods. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour */ enum ColourIds { textColourId = 0x1006501 /**< The colour to use for the button's text. */ }; protected: //============================================================================== /** @internal */ void paintButton (Graphics&, bool isMouseOverButton, bool isButtonDown); /** @internal */ void colourChanged(); private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton); }; #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
37.384615
106
0.524691
d44de419d41bb3fb59e40ccc283e5389e113c182
1,470
h
C
include/dxgmx/mem/mmap.h
oda404/dxgmx
1965f384e8247312b091ef681833f3b04becaaa4
[ "MIT" ]
2
2021-08-11T18:05:21.000Z
2022-01-09T19:55:37.000Z
include/dxgmx/mem/mmap.h
oda404/dxgmx
1965f384e8247312b091ef681833f3b04becaaa4
[ "MIT" ]
null
null
null
include/dxgmx/mem/mmap.h
oda404/dxgmx
1965f384e8247312b091ef681833f3b04becaaa4
[ "MIT" ]
null
null
null
/** * Copyright 2021 Alexandru Olaru. * Distributed under the MIT license. */ #ifndef _DXGMX_MEM_MAP_H #define _DXGMX_MEM_MAP_H #include<dxgmx/types.h> #include<dxgmx/compiler_attrs.h> #include<dxgmx/mem/memrange.h> #define MMAP_AVAILABLE 1 #define MMAP_RESERVED 2 #define MMAP_ACPI_RECLAIMABLE 3 #define MMAP_NVS 4 #define MMAP_BADRAM 5 typedef struct S_MemoryMap { #define MMAP_MAX_ENTRIES_CNT 15 size_t entries_cnt; MemRangeTyped entries[MMAP_MAX_ENTRIES_CNT]; } MemoryMap; /* * Initiate the memory map. */ void mmap_init(MemoryMap *mmap); /* * Adds a new entry to the memory map. * @param base Where the area begins. * @param size How big is the area. * @param type Type of area. */ void mmap_add_entry(u64 base, u64 size, u8 type, MemoryMap *mmap); int mmap_update_entry_type(u64 base, u64 size, u8 type, MemoryMap *mmap); /* Aligns all the available areas' on 'bytes' boundaries, shrinking if needed. @param bytes Alignment. */ void mmap_align_entries(u8 type, u32 align, MemoryMap *mmap); /* * Print all entries. */ void mmap_dump(const MemoryMap *mmap); bool mmap_is_addr_inside_entry(u64 addr, const MemRangeTyped *entry); #define FOR_EACH_MMAP_ENTRY(entry, mmap) \ for(MemoryMap m = mmap; m.entries_cnt; m.entries_cnt = 0) \ for( \ MemRangeTyped *entry = m.entries; \ entry < &m.entries[m.entries_cnt - 1]; \ ++entry \ ) #endif // _DXGMX_MEM_MAP_H
23.333333
73
0.701361
33253012ca632ec513c0a7c04cfd813ffd060c5c
8,558
h
C
MDC-111/Swift/Starter/Pods/MaterialComponents/components/Chips/src/MDCChipField.h
codeman7/material-components-ios-codelabs
334c3c8cfc7deba07db1810c6aa0eb63239da177
[ "Apache-2.0" ]
49
2017-06-08T20:09:37.000Z
2022-02-23T17:36:07.000Z
MDC-111/Swift/Starter/Pods/MaterialComponents/components/Chips/src/MDCChipField.h
codeman7/material-components-ios-codelabs
334c3c8cfc7deba07db1810c6aa0eb63239da177
[ "Apache-2.0" ]
27
2018-05-09T20:42:48.000Z
2018-09-10T17:52:08.000Z
iosApp/Pods/MaterialComponents/components/Chips/src/MDCChipField.h
archiegq21/DroidconKotlin
8c3ec05448d586037c924f245f77fcd0150f0476
[ "Apache-2.0" ]
47
2017-09-17T11:16:49.000Z
2021-08-09T06:15:40.000Z
// Copyright 2017-present the Material Components for iOS 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. #import <CoreGraphics/CoreGraphics.h> #import <UIKit/UIKit.h> #import "MDCChipView.h" #import "MaterialTextFields.h" /** Note: There is a UIKit bug affecting iOS 8.0-8.2 where UITextFields do not properly call the public |deleteBackward| method when the user presses backspace, which means that users can't delete chips with the backspace key. Apple fixed the underlying bug in iOS 8.3, so clients targeting a minimum iOS version of >= 8.3 are not affected by this bug. As a workaround, this class can OPTIONALLY USE THE PRIVATE |keyboardInputShouldDelete| method to detect when backspace is pressed and forward the event to |deleteBackward|. There is anecdotal evidence that this private usage is currently acceptable by Apple, see http://stackoverflow.com/a/25862878/23624. To enable the workaround, define MDC_CHIPFIELD_PRIVATE_API_BUG_FIX to be 1 when building MDCChipField. MDC itself will never define this macro, it's entirely a client decision. If you target iOS versions < 8.3 and you decide not to define MDC_CHIPFIELD_PRIVATE_API_BUG_FIX, your iOS 8.0-8.2 users will *not be able to delete chips using the backspace key*. Please consider adding a delete button to each chip's accessoryView. An alternative approach (using an empty character to detect backspace) makes MDCChipField unusable by VoiceOver users on all versions of iOS. */ /** The minimum text field width of the text field contained within the MDCChipField. */ extern const CGFloat MDCChipFieldDefaultMinTextFieldWidth; /** The default content edge insets for the MDCChipField. */ extern const UIEdgeInsets MDCChipFieldDefaultContentEdgeInsets; @protocol MDCChipFieldDelegate; /** Defines when text field input is changed into a chip. */ typedef NS_OPTIONS(NSUInteger, MDCChipFieldDelimiter) { MDCChipFieldDelimiterNone = 0, MDCChipFieldDelimiterReturn = 1 << 0, MDCChipFieldDelimiterSpace = 1 << 1, MDCChipFieldDelimiterDidEndEditing = 1 << 2, MDCChipFieldDelimiterDefault = (MDCChipFieldDelimiterReturn | MDCChipFieldDelimiterDidEndEditing), MDCChipFieldDelimiterAll = 0xFFFFFFFF }; @interface MDCChipField : UIView /** The text field used to enter new chips. Do not set the delegate or positioningDelegate. If you set a custom font, make sure to also set the custom font on textField.placeholderLabel and on your MDCChipView instances. */ @property(nonatomic, nonnull, readonly) MDCTextField *textField; /** The fixed height of all chip views. Default is 32dp. */ @property(nonatomic, assign) CGFloat chipHeight; /** Attribute to determine whether to show the placeholder text (if it exists) when chips are present. Default is YES. */ @property(nonatomic, assign) BOOL showPlaceholderWithChips; /** Enabling this property allows chips to be deleted by tapping on them. @note This does not support the 48x48 touch targets that Google recommends. We recommend if this behavior is enabled that a snackbar or dialog are used as well to allow the user to confirm if they want to delete the chip. */ @property(nonatomic) BOOL showChipsDeleteButton; /** The delimiter used to create chips in the text field. Uses default value MDCChipFieldDelimiterDefault if no delimiter is set. */ @property(nonatomic, assign) MDCChipFieldDelimiter delimiter; /** The minimum width of the text field. Default is |kMDCChipFieldDefaultMinTextFieldWidth|. */ @property(nonatomic, assign) CGFloat minTextFieldWidth; /** The chips that are visible in the input area. */ @property(nonatomic, nonnull, copy) NSArray<MDCChipView *> *chips; /** Delegate to receive updates to the chip field view. Implement |chipFieldHeightDidChange| to receive updates when the height of the chip field changes. */ @property(nonatomic, nullable, weak) id<MDCChipFieldDelegate> delegate; /** The inset or outset margins for the rectangle surrounding all of the chip field's content. Default is |kMDCChipFieldDefaultContentEdgeInsets|. */ @property(nonatomic, assign) UIEdgeInsets contentEdgeInsets; /** Adds a chip to the chip field. @param chip The chip to add to the field. Note: Implementing |chipField:shouldAddChip| only affects whether user interface input entered into the text field is changed into chips and will not affect use of this method. */ - (void)addChip:(nonnull MDCChipView *)chip; /** Removes a chip from the chip field. @param chip The chip to remove from the field. */ - (void)removeChip:(nonnull MDCChipView *)chip; /** Removes all selected chips from the chip field. */ - (void)removeSelectedChips; /** Removes all text from the chip field text input area. */ - (void)clearTextInput; /** Selects a chip in a chip field. */ - (void)selectChip:(nonnull MDCChipView *)chip; /** Deselects all chips in a chip field. */ - (void)deselectAllChips; /** Sets the VoiceOver focus on the text field. */ - (void)focusTextFieldForAccessibility; @end @protocol MDCChipFieldDelegate <NSObject> @optional /** Tells the delegate that editing began in the specified chip field. @param chipField The MDCChipField where editing began. */ - (void)chipFieldDidBeginEditing:(nonnull MDCChipField *)chipField; /** Tells the delegate when editing ends for the specified MDCChipField. @param chipField The MDCChipField where editing ended. */ - (void)chipFieldDidEndEditing:(nonnull MDCChipField *)chipField; /** Tells the delegate when a chip is added. This delegate method is not called if @c chips array is directly set. @param chipField The MDCChipField where a chip was added. @param chip The chip that was added. */ - (void)chipField:(nonnull MDCChipField *)chipField didAddChip:(nonnull MDCChipView *)chip; /** Asks the delegate whether the user-entered chip should be added to the chip field. If not implemented, YES is assumed. @param chipField The MDCChipField where a chip will be added. @param chip The chip to be added. @return YES if the chip should be added, NO otherwise. */ - (BOOL)chipField:(nonnull MDCChipField *)chipField shouldAddChip:(nonnull MDCChipView *)chip; /** Tells the delegate when a chip is removed. This delegate method is not called if @c chips array is directly set. @param chipField The MDCChipField where a chip was removed. @param chip The chip that was removed. */ - (void)chipField:(nonnull MDCChipField *)chipField didRemoveChip:(nonnull MDCChipView *)chip; /** Tells the delegate when the height of the chip field changes. @param chipField The MDCChipField which height changed. */ - (void)chipFieldHeightDidChange:(nonnull MDCChipField *)chipField; /** Tells the delegate when the text in the chip field changes. @param chipField The MDCChipField where text has changed. @param input The text entered into the chip field that has not yet been converted to a chip. */ - (void)chipField:(nonnull MDCChipField *)chipField didChangeInput:(nullable NSString *)input; /** Tells the delegate when a chip in the chip field is tapped. @param chipField The MDCChipField which has a chip that was tapped. @param chip The chip that was tapped. */ - (void)chipField:(nonnull MDCChipField *)chipField didTapChip:(nonnull MDCChipView *)chip; /** Called when 'return' key is pressed in the text field contained within the chip field. Return YES to use default behavior where chip is created. Return NO to override default behavior, no chip is created and client must manually create and add a chip. @param chipField The MDCChipField where return was pressed. */ - (BOOL)chipFieldShouldReturn:(nonnull MDCChipField *)chipField; /** Asks the delegate whether the chip field should become first responder when it is tapped. If not implemented, YES is assumed. @param chipField The MDCChipField that becomes the first responder. @return YES if the chip field should become first responder, NO otherwise. */ - (BOOL)chipFieldShouldBecomeFirstResponder:(nonnull MDCChipField *)chipField; @end
34.095618
100
0.770741
98dde5ade2797eabf79a4521c0e99bf3cbd908fc
233
h
C
test/TestSuite1/CIoTA/CIoTA_TestAgent.h
golomb1/CIoTA-Collaborative-IoT-Anomaly-detection-via-Blockchain
7704e5d22f09783250ec3b448ef4d5d24bbaf8af
[ "MIT" ]
14
2018-12-18T07:49:11.000Z
2021-12-17T10:06:02.000Z
test/TestSuite1/CIoTA/CIoTA_TestAgent.h
golomb1/CIoTA-Collaborative-IoT-Anomaly-detection-via-Blockchain
7704e5d22f09783250ec3b448ef4d5d24bbaf8af
[ "MIT" ]
2
2019-01-28T18:11:43.000Z
2020-11-11T08:23:10.000Z
test/TestSuite1/CIoTA/CIoTA_TestAgent.h
golomb1/CIoTA-Collaborative-IoT-Anomaly-detection-via-Blockchain
7704e5d22f09783250ec3b448ef4d5d24bbaf8af
[ "MIT" ]
7
2018-08-31T15:59:58.000Z
2021-11-03T02:11:02.000Z
// // Created by golombt on 28/12/2017. // #ifndef CIOTA_COMPLETE_PROJECT_CIOTA_TEST_AGENT_H #define CIOTA_COMPLETE_PROJECT_CIOTA_TEST_AGENT_H bool CIoTA_TestAgent(); #endif //CIOTA_COMPLETE_PROJECT_CIOTA_TEST_AGENT_H
19.416667
51
0.793991
471e0cb4c097107addb5d1ba60c108b106b1570b
5,581
h
C
include/h5rd/DataSetType.h
readdy/readdy
ef400db60a29107672a7f2bc42f6c3db4de34eb0
[ "BSD-3-Clause" ]
51
2015-02-24T18:19:34.000Z
2022-03-30T06:57:47.000Z
include/h5rd/DataSetType.h
readdy/h5rd
bfcd8a7cd68bb37bf94ca0d2705826289da4c9f1
[ "BSD-3-Clause" ]
81
2016-05-25T22:29:39.000Z
2022-03-28T14:22:18.000Z
include/h5rd/DataSetType.h
readdy/h5rd
bfcd8a7cd68bb37bf94ca0d2705826289da4c9f1
[ "BSD-3-Clause" ]
15
2015-03-10T03:16:49.000Z
2021-10-11T11:26:39.000Z
/******************************************************************** * Copyright © 2018 Computational Molecular Biology Group, * * Freie Universität Berlin (GER) * * * * Redistribution and use in source and binary forms, with or * * without modification, are permitted provided that the * * following conditions are met: * * 1. Redistributions of source code must retain the above * * copyright notice, this list of conditions and the * * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * * copyright notice, this list of conditions and the following * * disclaimer in the documentation and/or other materials * * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of * * its contributors may be used to endorse or promote products * * derived from this software without specific * * prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ********************************************************************/ /** * << detailed description >> * * @file DataSetType.h * @brief << brief description >> * @author clonker * @date 05.09.17 * @copyright BSD-3 */ #pragma once #include "Object.h" namespace h5rd { class DataSetType : public SubObject { public: explicit DataSetType(handle_id hid, ParentFileRef parentFile); DataSetType(const DataSetType &rhs); DataSetType &operator=(const DataSetType &rhs); void close() override; ~DataSetType() override; }; class VLENDataSetType : public DataSetType { public: explicit VLENDataSetType(const DataSetType &other); }; template<typename T> class NativeDataSetType : public DataSetType { public: explicit NativeDataSetType(ParentFileRef parentFile); using type = T; }; template<typename T, unsigned int len> class NativeArrayDataSetType : public DataSetType { public: using type = typename std::remove_pointer<typename std::decay<T>::type>::type; explicit NativeArrayDataSetType(ParentFileRef parentFile); constexpr static unsigned int size = len; private: NativeDataSetType<type> nativeType; }; template<typename T, typename = typename std::enable_if<util::is_std_array<T>::value>::type> class NativeStdArrayDataSetType : public DataSetType { public: using type = typename T::value_type; NativeStdArrayDataSetType(ParentFileRef parentFile); constexpr static std::size_t size = std::tuple_size<T>::value; private: NativeDataSetType<type> nativeType; }; template<typename T> class STDDataSetType : public DataSetType { public: explicit STDDataSetType(ParentFileRef parentFile); using type = T; }; template<typename T, unsigned int len> class STDArrayDataSetType : public DataSetType { public: using type = typename std::remove_pointer<typename std::decay<T>::type>::type; explicit STDArrayDataSetType(ParentFileRef parentFile); constexpr static unsigned int size = len; private: STDDataSetType<type> stdType; }; class NativeCompoundType : public DataSetType { public: explicit NativeCompoundType(handle_id tid, ParentFileRef parentFile, std::vector<DataSetType> &&insertTypes); private: std::vector<DataSetType> insertedTypes; }; class STDCompoundType : public DataSetType { public: explicit STDCompoundType(const NativeCompoundType &nativeType); }; class NativeCompoundTypeBuilder { public: explicit NativeCompoundTypeBuilder(std::size_t size, Object::ParentFileRef parentFile); NativeCompoundTypeBuilder &insert(const std::string &name, std::size_t offset, DataSetType &&type); template<typename T> NativeCompoundTypeBuilder &insert(const std::string &name, std::size_t offset); template<typename T, unsigned int size> NativeCompoundTypeBuilder &insertArray(const std::string &name, std::size_t offset); template<typename T, typename = typename std::enable_if<util::is_std_array<T>::value>::type> NativeCompoundTypeBuilder &insertStdArray(const std::string &name, std::size_t offset); NativeCompoundTypeBuilder &insertString(const std::string &name, std::size_t offset); NativeCompoundType build(); private: handle_id tid; Object::ParentFileRef _parentFile; std::vector<DataSetType> insertedTypes; }; } #include "detail/DataSetType_detail.h"
34.450617
113
0.660634
81638474fae478af9e5bfb1350733e0891f8dec7
185
h
C
production/include/interpreter/svg/path.h
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/include/interpreter/svg/path.h
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/include/interpreter/svg/path.h
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
#ifndef PATH_H_MASOIDM8923mf34ufgniurfjioejfkdlsflkdmfkjrefiu34nfiu43f #define PATH_H_MASOIDM8923mf34ufgniurfjioejfkdlsflkdmfkjrefiu34nfiu43f namespace svg { class path {}; } #endif
18.5
70
0.875676
54e174b9a022217486f797e48399c6e06b926d22
2,321
h
C
include/msp.h
ShuangQiuac/UNIPAR
f24223ee4239fc74063726416e196622388fe887
[ "MIT" ]
6
2019-02-13T12:48:50.000Z
2019-03-17T13:27:21.000Z
include/msp.h
RapidsAtHKUST/UNIPAR
f24223ee4239fc74063726416e196622388fe887
[ "MIT" ]
null
null
null
include/msp.h
RapidsAtHKUST/UNIPAR
f24223ee4239fc74063726416e196622388fe887
[ "MIT" ]
null
null
null
/* * msp.h * * Created on: 2015-7-7 * Author: qiushuang */ #ifndef MSP_H_ #define MSP_H_ #include "utility.h" #include "dbgraph.h" //#include "io.h" #define MAX_NUM_THREADS 64 #ifndef THREADS_MSP_COMPUTE #define THREADS_MSP_COMPUTE MAX_NUM_THREADS #endif #define HIST_BLOCK_SIZE 512 #define HIST_TOTAL_THREADS (HIST_BLOCK_SIZE * THREADS_PER_BLOCK) #ifdef LONG_MINSTR #define PSTR_UNIT_LENGTH 2 #else #define PSTR_UNIT_LENGTH 1 #endif #define PSTR_UNIT_BYTES 4 #define NUM_OF_RANGES 5 #define AVE_NUM_SPK 4 /* typedef struct bound { uint up; uint low; } bound_t;*/ #ifdef NUM_OF_RANGES typedef uint bound_t; typedef struct length_range { bound_t l1; bound_t l2; bound_t l3; bound_t l4; bound_t l5; } length_range_t; #endif typedef struct read_buf { seq_t * buf; offset_t offset[THREADS_MSP_COMPUTE]; // offsets for encoded reads uint num[THREADS_MSP_COMPUTE]; } read_buf_t; typedef struct { char ** read_buffer; uch ** d_msp_ptr; // ull read_size; char *** rbufs; uint ** rnums; int p; int k; int num_of_partitions; int read_length; int nstreams; int world_size; int world_rank; } cpu_msp_arg; typedef struct { char ** read_buffer; uch ** d_msp_ptr; char *** rbufs; uint ** rnums; int p; int k; int num_of_partitions; int read_length; int nstreams; int world_size; int world_rank; } output_msp_arg; typedef struct { char ** read_buffer; uch ** h_msp_ptr; read_buf_t * reads; uch * d_msp_ptr; seq_t * d_reads; char *** rbufs; uint ** rnums; int p; int k; int num_of_partitions; int read_length; int nstreams; int did; int world_size; int world_rank; } gpu_msp_arg; /* SoA for msp of all reads in buffer */ typedef struct msp { uch * nums; uch * poses; // start positions of partitioned superkmer on the read msp_id_t * ids; // msp id of the corresponding superkmer } msp_t; /* meta information for both msp output buffer and superkmers */ typedef struct msp_meta { uint size; // number of superkmers uint offset; // array offset: number of superkmers in current msp buffer -- for output control uint num_kmers; offset_t spksize; offset_t spkoffset; rid_t * idarr; // read id array pointer uch * lenarr; // length array of superkmers seq_t * spkbuf; } msp_meta_t; typedef void (* thread_function) (kmer_t *, int); #endif /* MSP_H_ */
16.818841
95
0.724688
8e7b1cd9f67133ccaf20d6dda837d25bad6342a4
4,989
h
C
lib/nvme_kernel/host/fabrics.h
omnicube/omnicube-os
85188ceb58c056e88f41583e7f512310f365508a
[ "BSD-3-Clause" ]
null
null
null
lib/nvme_kernel/host/fabrics.h
omnicube/omnicube-os
85188ceb58c056e88f41583e7f512310f365508a
[ "BSD-3-Clause" ]
null
null
null
lib/nvme_kernel/host/fabrics.h
omnicube/omnicube-os
85188ceb58c056e88f41583e7f512310f365508a
[ "BSD-3-Clause" ]
null
null
null
/* * fabrics.h - NVMe Fabrics implementation header for * host/initiator devices. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * This is used to implement a specific network fabric technology to the * NVMe Fabrics standard found in the NVMe specification. */ #ifndef _NVME_FABRICS_H #define _NVME_FABRICS_H 1 #include <linux/in.h> #include <linux/inet.h> #define NVMF_MIN_QUEUE_SIZE 16 #define NVMF_MAX_QUEUE_SIZE 1024 #define NVMF_DEF_QUEUE_SIZE 128 /** * enum nvmf_parsing_opts - used to define the sysfs parsing options used. * * For example, defining NVMF_OPT_IPADDR in the * .required_opts and .allowed_opts field in struct nvmf_transport_opts * will allow the following sysfs manipulation on the command-line * when adding a fabric controller to a host connection: * echo "ipaddr=192.168.13.55" > /sys/class/nvme-fabrics/ctl/add_ctrl. */ enum { NVMF_OPT_ERR = 0, NVMF_OPT_TRANSPORT = 1 << 0, NVMF_OPT_NQN = 1 << 1, NVMF_OPT_IPADDR = 1 << 2, NVMF_OPT_PORT = 1 << 3, NVMF_OPT_QUEUE_SIZE = 1 << 4, NVMF_OPT_NR_IO_QUEUES = 1 << 5, NVMF_OPT_TL_RETRY_COUNT = 1 << 6, }; /** * struct nvmf_ctrl_options - Used to hold the options specified * with the parsing opts enum. * @mask: Used by the fabrics library to parse through sysfs options * on adding a NVMe controller. * @transport: Holds the fabric transport "technology name" (for a lack of * better description) that will be used by an NVMe controller * being added. * @subsysnqn: Hold the fully qualified NQN subystem name (format defined * in the NVMe specification, "NVMe Qualified Names"). * @ipaddr: IP network address that will be used by the host to communicate * to the added NVMe controller. * @queue_size: Number of IO queue elements. * @nr_io_queues: Number of controller IO queues that will be established. * @tl_retry_count: Number of transport layer retries for a fabric queue before * kicking upper layer(s) error recovery. * * Example: echo ipaddr=192.168.13.55,transport=rdma,port=7,\ * nqn=nqn.2015-01.com.example:nvme:nvm-subsystem-sn-d78432 \ * > /sys/class/nvme-fabrics/ctl/add_ctrl on the command-line would * have transport = "rdma", ipaddr struct variable hold the * IP and port address, and * subsysnqn = "nqn.2015-01.com.example:nvme:nvm-subsystem-sn-d78432" */ struct nvmf_ctrl_options { unsigned mask; char *transport; char *subsysnqn; union { struct sockaddr addr; struct sockaddr_in ipaddr; }; size_t queue_size; unsigned int nr_io_queues; unsigned short tl_retry_count; }; /* * struct nvmf_transport_ops - used to register a specific * fabric implementation of NVMe fabrics. * @entry: Used by the fabrics library to add the new * registration entry to its linked-list internal tree. * @name: Name of the NVMe fabric driver implementation. * @required_opts: sysfs command-line options that must be specified * when adding a new NVMe controller. * @allowed_opts: sysfs command-line options that can be specified * when adding a new NVMe controller. * @create_ctrl(): function pointer that points to a non-NVMe * implementation-specific fabric technology * that would go into starting up that fabric * for the purpose of conneciton to an NVMe controller * using that fabric technology. * * Notes: * 1. At minimum, 'required_opts' and 'allowed_opts' should * be set to the same enum parsing options defined earlier. * 2. create_ctrl() must be defined (even if it does nothing) */ struct nvmf_transport_ops { struct list_head entry; const char *name; int required_opts; int allowed_opts; int (*create_ctrl)(struct device *dev, struct nvmf_ctrl_options *opts); }; int nvmf_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val); int nvmf_reg_read64(struct nvme_ctrl *ctrl, u32 off, u64 *val); int nvmf_reg_write32(struct nvme_ctrl *ctrl, u32 off, u32 val); int nvmf_connect_admin_queue(struct nvme_ctrl *ctrl, const char *subsysnqn, u16 *cntlid); int nvmf_connect_io_queue(struct nvme_ctrl *ctrl, const char *subsysnqn, u16 cntlid, u16 qid); void nvmf_register_transport(struct nvmf_transport_ops *ops); void nvmf_unregister_transport(struct nvmf_transport_ops *ops); void nvmf_identify_attrs(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id); void nvmf_free_options(struct nvmf_ctrl_options *opts); const char *nvmf_get_subsysnqn(struct nvme_ctrl *ctrl); int nvmf_get_address(struct nvme_ctrl *ctrl, char *buf, int size); #endif /* _NVME_FABRICS_H */
38.376923
79
0.734416
b8509f28679391ff3b875a065d5261842dd972bb
664
c
C
Code/src/uart.c
EugeneDN/tracker_STM32F100C8T6_CMSIS
557bf094533b32bb035fdbfab93cd58e657b600a
[ "MIT" ]
null
null
null
Code/src/uart.c
EugeneDN/tracker_STM32F100C8T6_CMSIS
557bf094533b32bb035fdbfab93cd58e657b600a
[ "MIT" ]
null
null
null
Code/src/uart.c
EugeneDN/tracker_STM32F100C8T6_CMSIS
557bf094533b32bb035fdbfab93cd58e657b600a
[ "MIT" ]
null
null
null
/* * uart.c */ #include "uart.h" void uart1_init(void) { RCC->APB2ENR |= RCC_APB2ENR_AFIOEN; RCC->APB2ENR |= RCC_APB2ENR_USART1EN; RCC->APB2ENR |= RCC_APB2ENR_IOPAEN; GPIOA->CRH |= GPIO_CRH_MODE9_1; GPIOA->CRH &= ~(GPIO_CRH_MODE9_0); GPIOA->CRH |= GPIO_CRH_CNF9_1; GPIOA->CRH &= ~(GPIO_CRH_CNF9_0); GPIOA->CRH &= ~(GPIO_CRH_MODE10); GPIOA->CRH |= GPIO_CRH_CNF10_0; GPIOA->CRH &= ~(GPIO_CRH_CNF10_1); USART1->BRR = 0x9C4; USART1->CR1 |= USART_CR1_UE; USART1->CR1 |= USART_CR1_TE; USART1->CR1 |= USART_CR1_RE; } void uart1_tx(char *str) { while(*str) { if(USART1->SR & USART_SR_TC) { USART1->DR = *str++; } } }
18.971429
39
0.635542
525e4e46998fca22f39b86d42fd1c5846fab16c8
2,793
c
C
test/test.c
oSumAtrIX/oppai-ng
b75e43d8591920ba1570161dc875b5f31f22f553
[ "Unlicense" ]
160
2017-08-15T16:53:42.000Z
2022-03-29T21:47:01.000Z
test/test.c
oSumAtrIX/oppai-ng
b75e43d8591920ba1570161dc875b5f31f22f553
[ "Unlicense" ]
78
2017-08-16T16:04:16.000Z
2022-03-10T16:07:02.000Z
test/test.c
oSumAtrIX/oppai-ng
b75e43d8591920ba1570161dc875b5f31f22f553
[ "Unlicense" ]
83
2017-08-17T02:52:43.000Z
2022-03-29T20:22:58.000Z
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../oppai.c" #include "test_suite.c" /* defines suite */ #define ERROR_MARGIN 0.02f /* pp can be off by +- 2% */ /* * margin is actually * - 3x for < 100pp * - 2x for 100-200pp * - 1.5x for 200-300pp */ void print_score(score_t* s) { char mods_str_buf[20]; char* mods_str = mods_str_buf; strcpy(mods_str, "nomod"); #define m(mod) \ if (s->mods & MODS_##mod) { \ mods_str += sprintf(mods_str, #mod); \ } \ m(HR) m(NC) m(HT) m(SO) m(NF) m(EZ) m(DT) m(FL) m(HD) #undef m printf("m=%d %u +%s %dx %dx300 %dx100 %dx50 %dxmiss %g pp\n", s->mode, s->id, mods_str_buf, s->max_combo, s->n300, s->n100, s->n50, s->nmiss, s->pp); } int main() { char fname_buf[4096]; char* fname = fname_buf; int i, n = (int)(sizeof(suite) / sizeof(suite[0])); float max_err[2] = { 0, 0 }; int max_err_map[2] = { 0, 0 }; float avg_err[2] = { 0, 0 }; int count[2] = { 0, 0 }; float error = 0; float error_percent = 0; ezpp_t ez = ezpp_new(); int err; int last_id = 0; fname += sprintf(fname, "test_suite/"); for (i = 0; i < n; ++i) { score_t* s = &suite[i]; float margin; float pptotal; print_score(s); if (s->id != last_id) { sprintf(fname, "%u.osu", s->id); last_id = s->id; /* force reparse and don't reuse prev map ar/cs/od/hp */ ezpp_set_base_cs(ez, -1); ezpp_set_base_ar(ez, -1); ezpp_set_base_od(ez, -1); ezpp_set_base_hp(ez, -1); } ezpp_set_mods(ez, s->mods); ezpp_set_accuracy(ez, s->n100, s->n50); ezpp_set_nmiss(ez, s->nmiss); ezpp_set_combo(ez, s->max_combo); ezpp_set_mode_override(ez, s->mode); err = ezpp(ez, fname_buf); if (err < 0) { printf("%s\n", errstr(err)); exit(1); } pptotal = ezpp_pp(ez); ++count[s->mode]; margin = (float)s->pp * ERROR_MARGIN; if (s->pp < 100) { margin *= 3; } else if (s->pp < 200) { margin *= 2; } else if (s->pp < 300) { margin *= 1.5f; } error = (float)fabs(pptotal - (float)s->pp); error_percent = error / (float)s->pp; avg_err[s->mode] += error_percent; if (error_percent > max_err[s->mode]) { max_err[s->mode] = error_percent; max_err_map[s->mode] = s->id; } if (error >= margin) { printf("failed test: got %g pp, expected %g\n", pptotal, s->pp); exit(1); } } for (i = 0; i < 2; ++i) { switch (i) { case MODE_STD: puts("osu"); break; case MODE_TAIKO: puts("taiko"); break; } avg_err[i] /= count[i]; printf("%d scores\n", count[i]); printf("avg err %f\n", avg_err[i]); printf("max err %f on %d\n", max_err[i], max_err_map[i]); } ezpp_free(ez); return 0; }
23.275
70
0.552095
52afd6734e439fb174c9782daf72258760cdc8a2
530
h
C
libs/appengine/gadgets/tonemap-gadget.h
dpt/PrivateEye
c84406e33d231189b5b2a550026a74ee76715b71
[ "BSD-2-Clause" ]
12
2016-08-24T20:40:07.000Z
2022-02-01T01:46:31.000Z
libs/appengine/gadgets/tonemap-gadget.h
dpt/PrivateEye
c84406e33d231189b5b2a550026a74ee76715b71
[ "BSD-2-Clause" ]
7
2021-02-22T00:14:55.000Z
2022-02-04T22:02:06.000Z
libs/appengine/gadgets/tonemap-gadget.h
dpt/PrivateEye
c84406e33d231189b5b2a550026a74ee76715b71
[ "BSD-2-Clause" ]
1
2019-11-08T16:46:38.000Z
2019-11-08T16:46:38.000Z
/* -------------------------------------------------------------------------- * Name: tonemap-gadget.h * Purpose: ToneMap gadget * ----------------------------------------------------------------------- */ #ifndef APPENGINE_TONEMAP_GADGET_H #define APPENGINE_TONEMAP_GADGET_H #include "oslib/wimp.h" #include "appengine/graphics/tonemap.h" int tonemapgadget_update(tonemap *map, wimp_w w, wimp_i i); int tonemapgadget_redraw(tonemap *map, wimp_w w, wimp_i i, wimp_draw *redraw); #endif /* APPENGINE_TONEMAP_GADGET_H */
31.176471
78
0.549057
50148bff8a5bf495ee70f56dd911708c63ed093b
4,594
h
C
runtime/opencl/command.h
hugots363/Multi2Sim
37f146ffa18427885aa10260f74719b00c127692
[ "Unlicense" ]
null
null
null
runtime/opencl/command.h
hugots363/Multi2Sim
37f146ffa18427885aa10260f74719b00c127692
[ "Unlicense" ]
null
null
null
runtime/opencl/command.h
hugots363/Multi2Sim
37f146ffa18427885aa10260f74719b00c127692
[ "Unlicense" ]
null
null
null
/* * Multi2Sim * Copyright (C) 2012 Rafael Ubal (ubal@ece.neu.edu) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RUNTIME_OPENCL_COMMAND_H #define RUNTIME_OPENCL_COMMAND_H #include "kernel.h" #include "opencl.h" struct opencl_command_t; typedef void (*opencl_command_func_t)(struct opencl_command_t *command); enum opencl_command_type_t { opencl_command_invalid = 0, opencl_command_nop, opencl_command_end, opencl_command_mem_read, opencl_command_mem_write, opencl_command_mem_copy, opencl_command_map_buffer, opencl_command_unmap_buffer, opencl_command_launch_ndrange }; struct opencl_command_t { enum opencl_command_type_t type; opencl_command_func_t func; int num_wait_events; struct opencl_event_t *done_event; struct opencl_event_t **wait_events; struct opencl_command_queue_t *command_queue; struct opencl_device_t *device; void *ndrange; /* Architecture-specific ND-Range */ union { struct { void *host_ptr; /* Destination */ void *device_ptr; /* Source */ unsigned int size; } mem_read; struct { void *device_ptr; /* Destination */ void *host_ptr; /* Source */ unsigned int size; } mem_write; struct { void *device_dest_ptr; void *device_src_ptr; unsigned int size; } mem_copy; struct { struct opencl_mem_t *mem; } map_buffer; struct { struct opencl_mem_t *mem; } unmap_buffer; }; }; struct opencl_command_t *opencl_command_create( enum opencl_command_type_t type, opencl_command_func_t func, struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_nop( struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_end( struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_mem_read( void *host_ptr, void *device_ptr, unsigned int size, struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_mem_write( void *device_ptr, void *host_ptr, unsigned int size, struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_mem_copy( void *device_dest_ptr, void *device_src_ptr, unsigned int size, struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_map_buffer( struct opencl_mem_t *mem, struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_unmap_buffer( struct opencl_mem_t *mem, struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); struct opencl_command_t *opencl_command_create_ndrange( struct opencl_device_t *device, struct opencl_kernel_t *kernel, int work_dim, unsigned int *global_work_offset, unsigned int *global_work_size, unsigned int *local_work_size, struct opencl_command_queue_t *command_queue, struct opencl_event_t **done_event_ptr, int num_wait_events, struct opencl_event_t **wait_events); void opencl_command_free(struct opencl_command_t *command); void opencl_command_run(struct opencl_command_t *command); #endif
27.508982
77
0.783413
38f3c4fb2215fb36773ef9086587a31671cd45cf
821
h
C
gcc-build/i686-pc-linux-gnu/libjava/java/io/Writer.h
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
1
2021-06-15T05:43:22.000Z
2021-06-15T05:43:22.000Z
gcc-build/i686-pc-linux-gnu/libjava/java/io/Writer.h
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
null
null
null
gcc-build/i686-pc-linux-gnu/libjava/java/io/Writer.h
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
null
null
null
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __java_io_Writer__ #define __java_io_Writer__ #pragma interface #include <java/lang/Object.h> #include <gcj/array.h> class ::java::io::Writer : public ::java::lang::Object { public: // actually protected Writer (); Writer (::java::lang::Object *); public: virtual void flush () = 0; virtual void close () = 0; virtual void write (jint); virtual void write (jcharArray); virtual void write (jcharArray, jint, jint) = 0; virtual void write (::java::lang::String *); virtual void write (::java::lang::String *, jint, jint); public: // actually protected ::java::lang::Object * __attribute__((aligned(__alignof__( ::java::lang::Object )))) lock; public: static ::java::lang::Class class$; }; #endif /* __java_io_Writer__ */
25.65625
92
0.673569
3a86d24cf77d8cdaf3d77073886bc1e5421ec7da
3,155
h
C
ft_print.h
ostef/ft_printf
b6db7eb5710b1ea1d33166823be2c5bde7815ccd
[ "Unlicense" ]
null
null
null
ft_print.h
ostef/ft_printf
b6db7eb5710b1ea1d33166823be2c5bde7815ccd
[ "Unlicense" ]
null
null
null
ft_print.h
ostef/ft_printf
b6db7eb5710b1ea1d33166823be2c5bde7815ccd
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: soumanso <soumanso@student.42lyon.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/05 18:50:38 by soumanso #+# #+# */ /* Updated: 2021/11/23 13:47:53 by soumanso ### ########lyon.fr */ /* */ /* ************************************************************************** */ #ifndef FT_PRINT_H # define FT_PRINT_H # include "libft/libft.h" # include <stdarg.h> typedef struct s_buff { char *data; t_s64 count; } t_buff; typedef enum e_fmt_flags { FLAG_NONE = 0x00, FLAG_LJUSTIFY = 0x01, FLAG_SIGN = 0x02, FLAG_SPACE = 0x04, FLAG_HASH = 0x08, FLAG_ZPAD = 0x10, FLAG_ESCAPED = 0x20 } t_fmt_flags; typedef enum e_fmt_width { WIDTH_ARG = -2, WIDTH_DEFAULT = -1 } t_fmt_width; typedef enum e_fmt_precision { PREC_ARG = -2, PREC_DEFAULT = -1 } t_fmt_precision; struct s_fmt_arg; typedef t_s64 (*t_fmt_func) (t_buff *, struct s_fmt_arg, va_list va); typedef struct s_fmt_arg { t_fmt_flags flags; t_fmt_width width; t_fmt_precision precision; char specifier; t_fmt_func func; } t_fmt_arg; t_s64 ft_putchars_buff(t_buff *buff, char c, t_s64 len, t_bool escaped); t_s64 ft_putchar_buff(t_buff *buff, char c, t_bool escaped); t_s64 ft_putstr_buff(t_buff *buff, t_cstr str, t_bool escaped); t_s64 ft_putstrn_buff(t_buff *buff, t_cstr str, t_s64 len, t_bool escaped); t_s64 ft_putuint_buff(t_buff *buff, t_u64 n, t_int min, const char *base); t_s64 ft_next_arg(t_cstr fmt, t_buff *buff, va_list va); t_s64 ft_read_arg(t_cstr fmt, t_fmt_arg *arg, va_list va); t_s64 ft_sprint_c(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_sprint_s(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_sprint_p(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_sprint_i(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_sprint_u(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_sprint_x(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_sprint_b(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_sprint_n(t_buff *buff, t_fmt_arg arg, va_list va); t_s64 ft_vsprint(t_str buff, t_cstr fmt, va_list va); t_s64 ft_sprint(t_str buff, t_cstr fmt, ...); t_s64 ft_vsprintln(t_str buff, t_cstr fmt, va_list va); t_s64 ft_sprintln(t_str buff, t_cstr fmt, ...); t_s64 ft_vfprint(t_file f, t_cstr fmt, va_list va); t_s64 ft_fprint(t_file f, t_cstr fmt, ...); t_s64 ft_vfprintln(t_file f, t_cstr fmt, va_list va); t_s64 ft_fprintln(t_file f, t_cstr fmt, ...); t_s64 ft_vprint(t_cstr fmt, va_list va); t_s64 ft_print(t_cstr fmt, ...); t_s64 ft_vprintln(t_cstr fmt, va_list va); t_s64 ft_println(t_cstr fmt, ...); #endif
33.924731
80
0.571157
6b57f5bced46a8089ccde885d92320bcea73c5df
24,771
c
C
core-vm/src/native/wonka/vm/Wonka.c
kifferltd/open-mika
079bcf51dce9442deee2cc728ee1d4a303f738ed
[ "ICU" ]
41
2015-05-14T12:03:18.000Z
2021-11-28T20:18:59.000Z
core-vm/src/native/wonka/vm/Wonka.c
kifferltd/open-mika
079bcf51dce9442deee2cc728ee1d4a303f738ed
[ "ICU" ]
11
2015-04-11T10:45:33.000Z
2020-12-14T18:08:58.000Z
core-vm/src/native/wonka/vm/Wonka.c
kifferltd/open-mika
079bcf51dce9442deee2cc728ee1d4a303f738ed
[ "ICU" ]
9
2016-05-05T15:19:17.000Z
2021-07-13T11:35:45.000Z
/************************************************************************** * Copyright (c) 2004, 2005, 2006, 2008, 2015 by Chris Gray, /k/ Embedded * * Java Solutions and KIFFER 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: * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * 3. Neither the name of KIFFER Ltd nor the names of other contributors * * may be used to endorse or promote products derived from this * * software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND 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 KIFFER LTD OR OTHER CONTRIBUTORS BE LIABLE FOR ANY * * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * **************************************************************************/ #include <string.h> #include "clazz.h" #include "descriptor.h" #include "exception.h" #include "fields.h" #include "loading.h" #include "methods.h" #include "sha.h" #include "wstrings.h" #include "wonka.h" #ifdef JDWP extern void jdwp_init(void); #endif #ifdef MODULES extern void loadExtensions(void); #else extern void init_extensions(void); #endif w_int sort_interfaces(const void * v_i1, const void * v_i2) { w_clazz i1 = *(w_clazz *)v_i1; w_clazz i2 = *(w_clazz *)v_i2; return compareStrings(i1->dotified, i2->dotified); } w_int sort_methods(const void * v_m1, const void * v_m2) { w_method m1 = *(w_method *)v_m1; w_method m2 = *(w_method *)v_m2; w_size l1; w_size l2; w_size i; w_string s1; w_string s2; w_char *b1; w_char *b2; w_int result; l1 = string_length(m1->spec.name) + 2; if (m1->spec.arg_types) { for (i = 0; m1->spec.arg_types[i]; ++i) { s1 = clazz2desc(m1->spec.arg_types[i]); if (!s1) { wabort(ABORT_WONKA, "Unable to create s1\n"); } l1 += string_length(s1); deregisterString(s1); } } s1 = clazz2desc(m1->spec.return_type); if (!s1) { wabort(ABORT_WONKA, "Unable to create s1\n"); } l1 += string_length(s1); deregisterString(s1); l2 = string_length(m2->spec.name) + 2; if (m2->spec.arg_types) { for (i = 0; m2->spec.arg_types[i]; ++i) { s2 = clazz2desc(m2->spec.arg_types[i]); if (!s2) { wabort(ABORT_WONKA, "Unable to create s2\n"); } l2 += string_length(s2); deregisterString(s2); } } s2 = clazz2desc(m2->spec.return_type); if (!s2) { wabort(ABORT_WONKA, "Unable to create s2\n"); } l2 += string_length(s2); deregisterString(s2); b1 = allocMem(l1 * sizeof(w_char)); if (!b1) { wabort(ABORT_WONKA, "Unable to allocate b1\n"); } stringAdd(b1, m1->spec.name); l1 = string_length(m1->spec.name); b1[l1++] = '('; if (m1->spec.arg_types) { for (i = 0; m1->spec.arg_types[i]; ++i) { s1 = clazz2desc(m1->spec.arg_types[i]); if (!s1) { wabort(ABORT_WONKA, "Unable to create s1\n"); } stringAdd(b1 + l1, s1); l1 += string_length(s1); deregisterString(s1); } } b1[l1++] = ')'; s1 = clazz2desc(m1->spec.return_type); if (!s1) { wabort(ABORT_WONKA, "Unable to create s1\n"); } stringAdd(b1 + l1, s1); l1 += string_length(s1); deregisterString(s1); s1 = unicode2String(b1, l1); if (!s1) { wabort(ABORT_WONKA, "Unable to create s1\n"); } releaseMem(b1); b2 = allocMem(l2 * sizeof(w_char)); if (!b2) { wabort(ABORT_WONKA, "Unable to allocate b2\n"); } stringAdd(b2, m2->spec.name); l2 = string_length(m2->spec.name); b2[l2++] = '('; if (m2->spec.arg_types) { for (i = 0; m2->spec.arg_types[i]; ++i) { s2 = clazz2desc(m2->spec.arg_types[i]); if (!s2) { wabort(ABORT_WONKA, "Unable to create s2\n"); } stringAdd(b2 + l2, s2); l2 += string_length(s2); deregisterString(s2); } } b2[l2++] = ')'; s2 = clazz2desc(m2->spec.return_type); if (!s2) { wabort(ABORT_WONKA, "Unable to create s2\n"); } stringAdd(b2 + l2, s2); l2 += string_length(s2); deregisterString(s2); s2 = unicode2String(b2, l2); if (!s2) { wabort(ABORT_WONKA, "Unable to create s2\n"); } releaseMem(b2); woempa(1, "SERIALISE: %w <=> %w\n", s1, s2); result = compareStrings(s1, s2); deregisterString(s1); deregisterString(s2); return result; } w_int sort_fields(const void * v_f1, const void * v_f2) { w_field f1 = *(w_field *)v_f1; w_field f2 = *(w_field *)v_f2; return compareStrings(f1->name, f2->name); } typedef union { w_word W; w_byte B[4]; } word2bytes; static w_int addModifiers(w_byte *buffer, w_word modifiers) { word2bytes u; u.W = (modifiers & ACC_FLAGS); #if __BYTE_ORDER == __LITTLE_ENDIAN buffer[0] = u.B[3]; buffer[1] = u.B[2]; buffer[2] = u.B[1]; buffer[3] = u.B[0]; #else buffer[0] = u.B[0]; buffer[1] = u.B[1]; buffer[2] = u.B[2]; buffer[3] = u.B[3]; #endif return 4; } w_word bytes2word(w_byte *bytes) { word2bytes u; #if __BYTE_ORDER == __LITTLE_ENDIAN u.B[3] = bytes[0]; u.B[2] = bytes[1]; u.B[1] = bytes[2]; u.B[0] = bytes[3]; #else u.B[0] = bytes[0]; u.B[1] = bytes[1]; u.B[2] = bytes[2]; u.B[3] = bytes[3]; #endif return u.W; } #include <ctype.h> w_long Wonka_suid(JNIEnv *env, w_instance Wonka, w_instance Class) { w_clazz clazz = Class2clazz(Class); w_long suid = 0; w_clazz *interfaces = NULL; w_size numInterfaces = 0; w_field *fields = NULL; w_size numFields = 0; w_method *constructors = NULL; w_size numConstructors = 0; w_method *methods = NULL; w_size numMethods = 0; w_size i; w_size j; w_size k; w_size chars; w_byte *buffer; w_byte *utf8; w_int length; w_sha sha; w_string zig; w_string tmp; w_size sigsize; w_char *sig; w_flags flags; w_method m; woempa(1, "SERIALISE: Calculating suid of clazz %k\n", clazz); if (mustBeInitialized(clazz) == CLASS_LOADING_FAILED) { return 0; } /* ** See if we have a cached version of the SUID in our sleeves... */ if (clazz->suid != 0) { woempa(1, "SERIALISE: Returning cached suid 0x%x%x\n", MSW_PART(clazz->suid), LSW_PART(clazz->suid)); return clazz->suid; } if (!clazz->dims) { /* ** First create the arrays so that they can be sorted, some arrays are overallocated ** but they are released soon enough so that is not a problem. */ numInterfaces = clazz->numDirectInterfaces; if (numInterfaces) { interfaces = allocMem(numInterfaces * sizeof(w_clazz)); if (!interfaces) { wabort(ABORT_WONKA, "Unable to allocate interfaces\n"); } w_memcpy(interfaces, clazz->interfaces, numInterfaces * sizeof(w_clazz)); qsort(interfaces, numInterfaces, sizeof(w_clazz), sort_interfaces); } if (clazz->numFields) { fields = allocMem(clazz->numFields * sizeof(w_field)); if (!fields) { wabort(ABORT_WONKA, "Unable to allocate fields\n"); } for (i = 0; i < clazz->numFields; i++) { if (clazz->own_fields[i].declaring_clazz == clazz) { flags = clazz->own_fields[i].flags; if (! (isSet(flags, ACC_PRIVATE) && isSet(flags, ACC_STATIC)) && ! (isSet(flags, ACC_PRIVATE) && isSet(flags, ACC_TRANSIENT)) ) { fields[numFields++] = &clazz->own_fields[i]; } } } qsort(fields, numFields, sizeof(w_field), sort_fields); } /* ** We can not directly rule out that constructors or methods do not apply to this algorithm. So ** we have to allocate memory, but still can end up with numConstructors and numMethods being 0... */ constructors = allocMem(clazz->numDeclaredMethods * sizeof(w_method)); if (!constructors) { wabort(ABORT_WONKA, "Unable to allocate constructors\n"); } for (i = 0; i < clazz->numDeclaredMethods; ++i) { m = &clazz->own_methods[i]; if ((m->spec.name == string_angle_brackets_init) && isNotSet(m->flags, ACC_PRIVATE)) { constructors[numConstructors++] = m; } } if (numConstructors) { qsort(constructors, numConstructors, sizeof(w_method), sort_methods); } methods = allocMem(clazz->numDeclaredMethods * sizeof(w_method)); if (!methods) { wabort(ABORT_WONKA, "Unable to allocate methods\n"); } for (i = 0; i < clazz->numDeclaredMethods; ++i) { m = &clazz->own_methods[i]; if (m->spec.name != string_angle_brackets_init && m->spec.name != string_angle_brackets_clinit && isNotSet(m->flags, ACC_PRIVATE)) { methods[numMethods++] = m; } } if (numMethods) { qsort(methods, numMethods, sizeof(w_method), sort_methods); } /* ** Count the number of chars we need to convert back to UTF8, we need this count so we can allocate a suitably size ** buffer to convert the strings to UTF8, add the 32 bit modifier integers and calculate the SHA signature from. ** Note that we add 2 to each length to accomodate the 2 bytes for the length in the UTF8 byte sequence, and ** we add sizeof(w_word) for accomodating the modifiers. */ chars = string_length(clazz->dotified) + 2; chars += sizeof(w_word); for (i = 0; i < numInterfaces; i++) { chars += string_length(interfaces[i]->dotified) + 2; woempa(1, " INTERFACE %2d: %w\n", i, interfaces[i]->dotified); } if (clazz->clinit) { chars += string_length(clazz->clinit->spec.name); if (clazz->clinit->spec.arg_types) { for (j = 0; clazz->clinit->spec.arg_types[j]; ++j) { tmp = clazz2desc(clazz->clinit->spec.arg_types[j]); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } chars += string_length(tmp); deregisterString(tmp); } } tmp = clazz2desc(clazz->clinit->spec.return_type); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } chars += string_length(tmp); deregisterString(tmp); chars += sizeof(w_word) + 2 + 2; } for (i = 0; i < numFields; i++) { chars += string_length(fields[i]->name); tmp = clazz2desc(fields[i]->value_clazz); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } chars += string_length(tmp); deregisterString(tmp); chars += sizeof(w_word) + 2 + 2; woempa(1, " FIELD %2d: %w\n", i, fields[i]->name); } for (i = 0; i < numConstructors; i++) { chars += string_length(constructors[i]->spec.name); if (constructors[i]->spec.arg_types) { for (j = 0; constructors[i]->spec.arg_types[j]; ++j) { tmp = clazz2desc(constructors[i]->spec.arg_types[j]); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } chars += string_length(tmp); deregisterString(tmp); } } tmp = clazz2desc(constructors[i]->spec.return_type); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } chars += string_length(tmp); deregisterString(tmp); chars += sizeof(w_word) + 2 + 2; woempa(1, "CONSTRUCTOR %2d: %m\n", i, constructors[i]); } for (i = 0; i < numMethods; i++) { chars += string_length(methods[i]->spec.name); if (methods[i]->spec.arg_types) { for (j = 0; methods[i]->spec.arg_types[j]; ++j) { tmp = clazz2desc(methods[i]->spec.arg_types[j]); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } chars += string_length(tmp); deregisterString(tmp); } } tmp = clazz2desc(methods[i]->spec.return_type); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } chars += string_length(tmp); deregisterString(tmp); chars += sizeof(w_word) + 2 + 2; woempa(1, " METHOD %2d: %m\n", i, methods[i]); } /* ** Now allocate a working buffer and convert strings back to UTF8, add the modifiers at the same time, for ** each w_char we allocate 3 bytes for the worst case UTF8 encoding. */ buffer = allocMem(chars * (3 * sizeof(w_byte))); if (!buffer) { wabort(ABORT_WONKA, "Unable to allocate buffer\n"); } chars = 0; utf8 = string2UTF8(clazz->dotified, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer, utf8, length); releaseMem(utf8); chars += length; /* ** It seems that this ACC_SUPER flag, which is always set by the compiler, needs to be unset ** before calculating the SUID. Try to find this when it's not in the SUN specs for serialization... */ flags = clazz->flags; unsetFlag(flags, ACC_SUPER); chars += addModifiers(buffer + chars, flags); for (i = 0; i < numInterfaces; i++) { utf8 = string2UTF8(interfaces[i]->dotified, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; } for (i = 0; i < numFields; i++) { utf8 = string2UTF8(fields[i]->name, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; chars += addModifiers(buffer + chars, fields[i]->flags); woempa(1, "SERIALISE: buffer length = %d\n", chars); tmp = clazz2desc(fields[i]->value_clazz); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } utf8 = string2UTF8(tmp, &length); deregisterString(tmp); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; } if (clazz->clinit) { utf8 = string2UTF8(clazz->clinit->spec.name, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; chars += addModifiers(buffer + chars, ACC_STATIC); woempa(1, "SERIALISE: buffer length = %d\n", chars); w_memcpy(buffer + chars, "\000\003()V", 5); chars += 5; } for (i = 0; i < numConstructors; i++) { utf8 = string2UTF8(constructors[i]->spec.name, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; chars += addModifiers(buffer + chars, constructors[i]->flags); sigsize = 2; if (constructors[i]->spec.arg_types) { for (j = 0; constructors[i]->spec.arg_types[j]; ++j) { tmp = clazz2desc(constructors[i]->spec.arg_types[j]); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } sigsize += string_length(tmp); deregisterString(tmp); } } tmp = clazz2desc(constructors[i]->spec.return_type); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } sigsize += string_length(tmp); deregisterString(tmp); sig = allocMem(sigsize * sizeof(w_char)); if (!sig) { wabort(ABORT_WONKA, "Unable to allocate sig\n"); } sig[0] = '('; sigsize = 1; if (constructors[i]->spec.arg_types) { for (j = 0; constructors[i]->spec.arg_types[j]; ++j) { tmp = clazz2desc(constructors[i]->spec.arg_types[j]); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } for (k = 0; k < string_length(tmp); ++k) { sig[k + sigsize] = string_char(tmp, k); } sigsize += string_length(tmp); deregisterString(tmp); } } sig[sigsize++] = ')'; tmp = clazz2desc(constructors[i]->spec.return_type); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } for (k = 0; k < string_length(tmp); ++k) { sig[k + sigsize] = string_char(tmp, k); } sigsize += string_length(tmp); deregisterString(tmp); zig = unicode2String(sig, sigsize); if (!zig) { wabort(ABORT_WONKA, "Unable to create zig\n"); } releaseMem(sig); tmp = slashes2dots(zig); if (!tmp) { wabort(ABORT_WONKA, "Unable to dotify zig\n"); } woempa(1, "SERIALISE: %w descriptor = '%w', dotified = '%w'\n", constructors[i]->spec.name, zig, tmp); deregisterString(zig); utf8 = string2UTF8(tmp, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); deregisterString(tmp); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; } for (i = 0; i < numMethods; i++) { utf8 = string2UTF8(methods[i]->spec.name, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; chars += addModifiers(buffer + chars, methods[i]->flags); sigsize = 2; if (methods[i]->spec.arg_types) { for (j = 0; methods[i]->spec.arg_types[j]; ++j) { tmp = clazz2desc(methods[i]->spec.arg_types[j]); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } sigsize += string_length(tmp); deregisterString(tmp); } } tmp = clazz2desc(methods[i]->spec.return_type); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } sigsize += string_length(tmp); deregisterString(tmp); sig = allocMem(sigsize * sizeof(w_char)); if (!sig) { wabort(ABORT_WONKA, "Unable to allocate sig\n"); } woempa(1, "sigsize %d\n", sigsize); sig[0] = '('; sigsize = 1; if (methods[i]->spec.arg_types) { for (j = 0; methods[i]->spec.arg_types[j]; ++j) { tmp = clazz2desc(methods[i]->spec.arg_types[j]); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } for (k = 0; k < string_length(tmp); ++k) { sig[k + sigsize] = string_char(tmp, k); } sigsize += string_length(tmp); deregisterString(tmp); } } sig[sigsize++] = ')'; tmp = clazz2desc(methods[i]->spec.return_type); if (!tmp) { wabort(ABORT_WONKA, "Unable to create tmp\n"); } for (k = 0; k < string_length(tmp); ++k) { sig[k + sigsize] = string_char(tmp, k); } sigsize += string_length(tmp); deregisterString(tmp); woempa(1, "sigsize %d\n", sigsize); zig = unicode2String(sig, sigsize); if (!zig) { wabort(ABORT_WONKA, "Unable to create zig\n"); } releaseMem(sig); tmp = slashes2dots(zig); if (!tmp) { wabort(ABORT_WONKA, "Unable to dotify zig\n"); } woempa(1, "SERIALISE: %w descriptor = '%w', dotified = '%w'\n", methods[i]->spec.name, zig, tmp); deregisterString(zig); utf8 = string2UTF8(tmp, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); deregisterString(tmp); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; } } else { /* ** It is an array clazz, just take name and modifiers and process along... */ buffer = allocMem(2 + string_length(clazz->dotified) * (3 * sizeof(w_byte))); if (!buffer) { wabort(ABORT_WONKA, "Unable to allocate buffer\n"); } chars = 0; utf8 = string2UTF8(clazz->dotified, &length); woempa(1, "SERIALISE: utf8 = %d:'%s'\n", length-2, utf8+2); w_memcpy(buffer + chars, utf8, length); releaseMem(utf8); chars += length; flags = clazz->flags; unsetFlag(flags, ACC_SUPER); chars += addModifiers(buffer + chars, flags); } woempa(1, "SERIALISE: buffer length = %d\n", chars); sha = allocSha(); processSha(sha, buffer, chars); finishSha(sha); suid = sha->signature.W[1] & 0xff; suid = (suid << 8) | ((sha->signature.W[1] >> 8) & 0xff); suid = (suid << 8) | ((sha->signature.W[1] >> 16) & 0xff); suid = (suid << 8) | ((sha->signature.W[1] >> 24) & 0xff); suid = (suid << 8) | ((sha->signature.W[0]) & 0xff); suid = (suid << 8) | ((sha->signature.W[0] >> 8) & 0xff); suid = (suid << 8) | ((sha->signature.W[0] >> 16) & 0xff); suid = (suid << 8) | ((sha->signature.W[0] >> 24) & 0xff); woempa(1,"SERIALISE: suid = %02x %02x %02x %02x %02x %02x %02x %02x\n", sha->signature.B[7], sha->signature.B[6], sha->signature.B[5], sha->signature.B[4], sha->signature.B[3], sha->signature.B[2], sha->signature.B[1], sha->signature.B[0]); if (interfaces) { releaseMem(interfaces); } if (fields) { releaseMem(fields); } if (constructors) { releaseMem(constructors); } if (methods) { releaseMem(methods); } releaseMem(buffer); releaseSha(sha); /* ** Cache the SUID in the clazz structure for the next time around... */ clazz->suid = suid; return suid; } void Wonka_static_setWonkaVerbose(JNIEnv *env, w_instance theClass, w_instance verboseString) { w_string verbose_string = String2string(verboseString); if (verbose_string && !verbose_cstring) { w_size l = string_length(verbose_string); verbose_cstring = allocMem(l + 1); x_snprintf(verbose_cstring, l + 1, "%w", verbose_string); // Don't think the next line is needed, but here it is anyway verbose_cstring[l] = 0; if (l == 1 && verbose_cstring[0] == '?') { w_printf("mika.verbose should be a colon(:)-separated selection from the following list\n"); w_printf(" startup: VM startup\n"); w_printf(" shutdown: VM shutdown\n"); w_printf(" gc: garbage collection\n"); w_printf(" threads: thread creation/completion\n"); w_printf(" loading: loading and unloading of classes\n"); #ifdef DEBUG_STACKS w_printf(" stack: stack depth etc. at each method invocation\n"); #endif w_printf(" throw: exception handling\n"); w_printf(" socket: socket activity\n"); w_printf(" traffic: bytes sent/received over sockets\n"); w_printf(" http: traffic interpreted as HTTP\n"); w_printf(" exec: Runtime.exec()\n"); #ifdef JDWP w_printf(" jdwp: JDWP\n"); #endif } else if (l) { w_printf("mika.verbose=%s\n", verbose_cstring); } if (strstr(verbose_cstring, "start")) { verbose_flags |= VERBOSE_FLAG_STARTUP; } if (strstr(verbose_cstring, "shut")) { verbose_flags |= VERBOSE_FLAG_SHUTDOWN; } if (strstr(verbose_cstring, "thread")) { verbose_flags |= VERBOSE_FLAG_THREAD; } if (strstr(verbose_cstring, "gc")) { verbose_flags |= VERBOSE_FLAG_GC; } if (strstr(verbose_cstring, "init")) { verbose_flags |= VERBOSE_FLAG_INIT; } if (strstr(verbose_cstring, "load")) { verbose_flags |= VERBOSE_FLAG_LOAD; } if (strstr(verbose_cstring, "stack")) { verbose_flags |= VERBOSE_FLAG_STACK; } if (strstr(verbose_cstring, "socket")) { verbose_flags |= VERBOSE_FLAG_SOCKET; } if (strstr(verbose_cstring, "traffic")) { verbose_flags |= VERBOSE_FLAG_TRAFFIC; } if (strstr(verbose_cstring, "throw")) { verbose_flags |= VERBOSE_FLAG_THROW; } if (strstr(verbose_cstring, "url")) { verbose_flags |= VERBOSE_FLAG_URL; } if (strstr(verbose_cstring, "http")) { verbose_flags |= VERBOSE_FLAG_HTTP; } if (strstr(verbose_cstring, "exec")) { verbose_flags |= VERBOSE_FLAG_EXEC; } if (strstr(verbose_cstring, "jdwp")) { verbose_flags |= VERBOSE_FLAG_JDWP; } } } void Wonka_static_setMethodDebugInfo(JNIEnv *env, w_instance theClass, w_boolean enable) { use_method_debug_info = enable; } void Wonka_static_loadExtensions(JNIEnv *env, w_instance theClass) { #ifdef MODULES loadExtensions(); #else init_extensions(); #endif }
30.543773
137
0.600743
59319d32ee33259f3fa6e0178a0b25129eb0c40c
21
c
C
keyboards/manta60/manta60.c
fzf/qmk_toolbox
10d6b425bd24b45002555022baf16fb11254118b
[ "MIT" ]
null
null
null
keyboards/manta60/manta60.c
fzf/qmk_toolbox
10d6b425bd24b45002555022baf16fb11254118b
[ "MIT" ]
null
null
null
keyboards/manta60/manta60.c
fzf/qmk_toolbox
10d6b425bd24b45002555022baf16fb11254118b
[ "MIT" ]
null
null
null
#include "manta60.h"
10.5
20
0.714286
8dc68a5cbf370c59b4b03547c934ab0782f0495e
39
h
C
include/trick/compat/sim_services/CommandLineArguments/include/command_line_protos.h
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
647
2015-05-07T16:08:16.000Z
2022-03-30T02:33:21.000Z
include/trick/compat/sim_services/CommandLineArguments/include/command_line_protos.h
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
995
2015-04-30T19:44:31.000Z
2022-03-31T20:14:44.000Z
include/trick/compat/sim_services/CommandLineArguments/include/command_line_protos.h
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
251
2015-05-15T09:24:34.000Z
2022-03-22T20:39:05.000Z
#include "trick/command_line_protos.h"
19.5
38
0.820513
cef99861f8e707e86a7d02e27a72eeb736cecd2b
4,222
h
C
FindSecret/Classes/Native/UnityEngine_UnityEngine_Particle1728345354.h
GodIsWord/NewFindSecret
4f98f316d29936380f9665d6a6d89962d9ee5478
[ "MIT" ]
null
null
null
FindSecret/Classes/Native/UnityEngine_UnityEngine_Particle1728345354.h
GodIsWord/NewFindSecret
4f98f316d29936380f9665d6a6d89962d9ee5478
[ "MIT" ]
null
null
null
FindSecret/Classes/Native/UnityEngine_UnityEngine_Particle1728345354.h
GodIsWord/NewFindSecret
4f98f316d29936380f9665d6a6d89962d9ee5478
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_ValueType3640485471.h" #include "UnityEngine_UnityEngine_Vector33722313464.h" #include "UnityEngine_UnityEngine_Color2555686324.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Particle struct Particle_t1728345354 { public: // UnityEngine.Vector3 UnityEngine.Particle::m_Position Vector3_t3722313464 ___m_Position_0; // UnityEngine.Vector3 UnityEngine.Particle::m_Velocity Vector3_t3722313464 ___m_Velocity_1; // System.Single UnityEngine.Particle::m_Size float ___m_Size_2; // System.Single UnityEngine.Particle::m_Rotation float ___m_Rotation_3; // System.Single UnityEngine.Particle::m_AngularVelocity float ___m_AngularVelocity_4; // System.Single UnityEngine.Particle::m_Energy float ___m_Energy_5; // System.Single UnityEngine.Particle::m_StartEnergy float ___m_StartEnergy_6; // UnityEngine.Color UnityEngine.Particle::m_Color Color_t2555686324 ___m_Color_7; public: inline static int32_t get_offset_of_m_Position_0() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_Position_0)); } inline Vector3_t3722313464 get_m_Position_0() const { return ___m_Position_0; } inline Vector3_t3722313464 * get_address_of_m_Position_0() { return &___m_Position_0; } inline void set_m_Position_0(Vector3_t3722313464 value) { ___m_Position_0 = value; } inline static int32_t get_offset_of_m_Velocity_1() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_Velocity_1)); } inline Vector3_t3722313464 get_m_Velocity_1() const { return ___m_Velocity_1; } inline Vector3_t3722313464 * get_address_of_m_Velocity_1() { return &___m_Velocity_1; } inline void set_m_Velocity_1(Vector3_t3722313464 value) { ___m_Velocity_1 = value; } inline static int32_t get_offset_of_m_Size_2() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_Size_2)); } inline float get_m_Size_2() const { return ___m_Size_2; } inline float* get_address_of_m_Size_2() { return &___m_Size_2; } inline void set_m_Size_2(float value) { ___m_Size_2 = value; } inline static int32_t get_offset_of_m_Rotation_3() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_Rotation_3)); } inline float get_m_Rotation_3() const { return ___m_Rotation_3; } inline float* get_address_of_m_Rotation_3() { return &___m_Rotation_3; } inline void set_m_Rotation_3(float value) { ___m_Rotation_3 = value; } inline static int32_t get_offset_of_m_AngularVelocity_4() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_AngularVelocity_4)); } inline float get_m_AngularVelocity_4() const { return ___m_AngularVelocity_4; } inline float* get_address_of_m_AngularVelocity_4() { return &___m_AngularVelocity_4; } inline void set_m_AngularVelocity_4(float value) { ___m_AngularVelocity_4 = value; } inline static int32_t get_offset_of_m_Energy_5() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_Energy_5)); } inline float get_m_Energy_5() const { return ___m_Energy_5; } inline float* get_address_of_m_Energy_5() { return &___m_Energy_5; } inline void set_m_Energy_5(float value) { ___m_Energy_5 = value; } inline static int32_t get_offset_of_m_StartEnergy_6() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_StartEnergy_6)); } inline float get_m_StartEnergy_6() const { return ___m_StartEnergy_6; } inline float* get_address_of_m_StartEnergy_6() { return &___m_StartEnergy_6; } inline void set_m_StartEnergy_6(float value) { ___m_StartEnergy_6 = value; } inline static int32_t get_offset_of_m_Color_7() { return static_cast<int32_t>(offsetof(Particle_t1728345354, ___m_Color_7)); } inline Color_t2555686324 get_m_Color_7() const { return ___m_Color_7; } inline Color_t2555686324 * get_address_of_m_Color_7() { return &___m_Color_7; } inline void set_m_Color_7(Color_t2555686324 value) { ___m_Color_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
36.08547
147
0.800332
69ce611090faa2511d77f46d86ab526afb9ac6f0
30,984
c
C
C/gfpem.c
aszepieniec/bacuov
7931ddd0b4b8f233d433c09ce24dd38d61e5df4b
[ "AFL-1.1" ]
1
2021-11-15T12:19:07.000Z
2021-11-15T12:19:07.000Z
C/gfpem.c
aszepieniec/bacuov
7931ddd0b4b8f233d433c09ce24dd38d61e5df4b
[ "AFL-1.1" ]
null
null
null
C/gfpem.c
aszepieniec/bacuov
7931ddd0b4b8f233d433c09ce24dd38d61e5df4b
[ "AFL-1.1" ]
null
null
null
#include "gfpem.h" #include <stdlib.h> #include <stdio.h> /** * gfpem * Create gfpematrix object with given buffer. Usefule for reusing * the same data line. */ gfpematrix gfpem( unsigned int height, unsigned int width, gfpe_element* pdata ) { int i, j; gfpematrix mat; mat.height = height; mat.width = width; mat.data = pdata; return mat; } /** * gfpem_init * Create a field matrix object and allocate space for it. */ gfpematrix gfpem_init( unsigned int height, unsigned int width ) { int i, j; gfpematrix mat; mat.width = width; mat.height = height; mat.data = malloc(width*height*sizeof(gfpe_element)); /* printf("created gfpem object with data member set to memory address %#010x\n", mat.data); */ return mat; } /** * gfpem_destroy * Deallocates space allocated to a field matrix object. Call this * function before closing the scope where the field matrix object * was initialized. * @return * * 1 if success */ int gfpem_destroy( gfpematrix fm ) { int i, j; free(fm.data); fm.width = 0; fm.height = 0; return 1; } /** * gfpem_copy * Copy the contents of one matrix to another. Does not allocate * memory for the new object; you must do that yourself! (Or use * gfpem_clone instead.) * @promise * * dest.width >= source.width * * dest.height >= source.height * @return * * 1 if success */ int gfpem_copy( gfpematrix dest, gfpematrix source ) { unsigned int i, j; for( i = 0 ; i < source.height ; ++i ) { for( j = 0 ; j < source.width ; ++j ) { gfpe_copy(&dest.data[i*dest.width + j], source.data[i*source.width + j]); } } return 1; } /** * gfpem_clone * Copy one matrix into a new object. Don't forget to call * gfpem_destroy at the end of scope! */ gfpematrix gfpem_clone( gfpematrix source ) { gfpematrix mat; mat = gfpem_init(source.height, source.width); gfpem_copy(mat, source); return mat; } /** * gfpem_eye * Set a matrix to the identity matrix. * @param * * eye : matrix object to set to identity * @returns * * 1 if success, 0 otherwise */ int gfpem_eye( gfpematrix eye ) { unsigned int i, j; for( i = 0 ; i < eye.height ; ++i ) { for( j = 0 ; j < eye.width ; ++j ) { gfpe_zero(&eye.data[i*eye.width + j]); } gfpe_one(&eye.data[i*eye.width + i]); } return 1; } /** * Decide whether the given matrix is an identity matrix or, for * rectangular matrices, whether the main diagonal has ones and all * the rest is zero. * @return * * 1 if identity, 0 otherwise */ int gfpem_is_eye( gfpematrix eye ) { unsigned int i, j; int b = 1; gfpe_element one, zero; gfpe_one(&one); gfpe_zero(&zero); for( i = 0 ; i < eye.height ; ++i ) { for( j = 0 ; j < eye.width ; ++j ) { if( i == j ) { b = b & gfpe_compare(eye.data[i*eye.width + j], one); } else { b = b & gfpe_compare(eye.data[i*eye.width + j], zero); } } } return b; } /** * gfpem_equals * Test two matrices for equality. * @return * * 1 if equal, 0 otherwise */ int gfpem_equals( gfpematrix lhs, gfpematrix rhs ) { unsigned int i, j; int b; if( lhs.width != rhs.width || lhs.height != rhs.height ) { return 0; } b = 1; for( i = 0 ; i < lhs.height ; ++i ) { for( j = 0 ; j < lhs.width ; ++j ) { b = b & gfpe_compare(lhs.data[lhs.width*i + j], rhs.data[rhs.width*i + j]); } } return b; } /** * gfpem_zero * Sets a matrix to all zeros. * @param * * zero : matrix object to set to zero * @returns * * 1 if success */ int gfpem_zeros( gfpematrix zero ) { unsigned int i, j; for( i = 0 ; i < zero.height ; ++i ) { for( j = 0 ; j < zero.width ; ++j ) { gfpe_zero(&zero.data[i*zero.width + j]); } } return 1; } /** * gfpem_random * Put random values into the matrix. * @params * * random : matrix objects with data already allocated and whose * elements are to be assigned random values * * randomness : pointer to large-enough string of random bytes * "large enough" means n*n*sizeof(unsigned int) * @result * * random <-$- matrix_space(random.height, random.width) */ int gfpem_random( gfpematrix random, unsigned char * randomness ) { unsigned int i, j; unsigned int l; unsigned int * rand = (unsigned int *)randomness; unsigned int num_limbs; num_limbs = (GFP_NUMBITS + sizeof(unsigned long int)*8 - 1) / (sizeof(unsigned long int)*8); l = 0; for( i = 0 ; i < random.height ; ++i ) { for( j = 0 ; j < random.width ; ++j ) { gfpe_random(&random.data[i*random.width + j], randomness + l*num_limbs*sizeof(unsigned long int)); l = l + 1; } } return 1; } /** * gfpem_random_upper_triangular * Set the matrix to a random upper triangular with ones on the * diagonal. * @params * * random : matrix objects with data already allocated and whose * elements above the diagonal are to be assigned random values; * whereas the elements above the diagonal are to be 0 and the * elements on the diagonal are to be 1. * * randomness : pointer to large-enough string of random bytes * "large enough" means n*(n-1)/2*sizeof(unsigned int) * @result * * random <-$- matrix_space(random.height, random.width) * subject to * forall i . random[i,i] = 1 * forall i, j>i . random[i,j] = 0 */ int gfpem_random_upper_triangular( gfpematrix random, unsigned char * randomness ) { unsigned int i, j; unsigned int l; l = 0; for( i = 0 ; i < random.height ; ++i ) { for( j = 0 ; j < i ; ++j ) { gfpe_random(&random.data[i*random.width + j], &randomness[(l++)*(GFP_NUMBYTES+1)]); } gfpe_one(&random.data[i*random.width + i]); for( j = i+1 ; j < random.width ; ++j ) { gfpe_zero(&random.data[i*random.width + j]); } } return 1; } /** * gfpem_transpose_square * Perform a matrix transposition in situ. */ int gfpem_transpose( gfpematrix * trans ) { unsigned int a; unsigned int i, j; gfpematrix T; T = gfpem_init(trans->height, trans->width); gfpem_copy(T, *trans); a = trans->width; trans->width = trans->height; trans->height = a; for( i = 0 ; i < trans->height ; ++i ) { for( j = 0 ; j < trans->width ; ++j ) { gfpe_copy(&trans->data[i*trans->width + j], T.data[j*T.width + i]); } } gfpem_destroy(T); return 1; } /** * gfpem_multiply * Multiplies two matrices and stores the result in the third, which * should be pre-allocated. * @params * * dest : field matrix object to store the matrix product * * left, right : field matrix object representing left- and right- * hand-sides respectively. * @return * * 1 if success, 0 otherwise * NOTE. Modular reduction is applied only once, after computing the * inner product between left row and right column and storing the * intermediate result in an int. If the int is four bytes and the * field element takes up a full byte, then in the worst case every * product requires two bytes and every 2^k additions requires k * extra bits. Since we have 16 bits to spare we have at most 2^16 * additions which is anyway the max. height and width of matrices * that can be stored in a unsigned int. */ int gfpem_multiply( gfpematrix * dest, gfpematrix left, gfpematrix right ) { unsigned int i, j, k; gfpe_element prod, sum, lsum; gfpe_element * data; data = malloc(sizeof(gfpe_element) * dest->width * dest->height); #ifdef DEBUG if( dest->height != left.height || dest->width != right.width || left.width != right.height ) { printf("in gfpem_multiply: trying to multiply matrices with unmatched dimensions: %ix%i * %ix%i = %ix%i\n", left.height, left.width, right.height, right.width, dest->height, dest->width); return 0; } #endif for( i = 0 ; i < left.height ; ++i ) { for( j = 0 ; j < right.width ; ++j ) { gfpe_zero(&sum); for( k = 0 ; k < left.width ; ++k ) { gfpe_copy(&lsum, sum); gfpe_multiply(&prod, left.data[i*left.width + k], right.data[k*right.width + j]); gfpe_add(&sum, lsum, prod); } gfpe_copy(&data[i*dest->width + j], sum); } } free(dest->data); dest->data = data; return 1; } /** * gfpem_multiply_transpose * Multiplies the left hand side matrix with the transpose of the * hand side matrix and stores the result in the third, which * should be pre-allocated. * @params * * dest : field matrix object to store the matrix product * * left, rightT : field matrix object representing left- and right- * hand-sides respectively. * @return * * 1 if success, 0 otherwise * NOTE. Modular reduction is applied only once, after computing the * inner product between left row and right column and storing the * intermediate result in an int. If the int is four bytes and the * field element takes up a full byte, then in the worst case every * product requires two bytes and every 2^k additions requires k * extra bits. Since we have 16 bits to spare we have at most 2^16 * additions which is anyway the max. height and width of matrices * that can be stored in a unsigned int. */ int gfpem_multiply_transpose( gfpematrix * dest, gfpematrix left, gfpematrix rightT ) { unsigned int i, j, k; gfpe_element prod, sum, lsum; gfpe_element * data; #ifdef DEBUG if( dest->height != left.height || dest->width != rightT.height || left.width != rightT.width ) { printf("in gfpem_multiply_transpose: trying to multiply matrices with unmatched dimensions: %ix%i * (%ix%i)^T = %ix%i\n", left.height, left.width, rightT.height, rightT.width, dest->height, dest->width); return 0; } #endif data = malloc(sizeof(gfpe_element) * dest->width * dest->height); for( i = 0 ; i < left.height ; ++i ) { for( j = 0 ; j < rightT.height ; ++j ) { gfpe_zero(&sum); for( k = 0 ; k < left.width ; ++k ) { gfpe_copy(&lsum, sum); gfpe_multiply(&prod, left.data[i*left.width + k], rightT.data[j*rightT.width + k]); gfpe_add(&sum, lsum, prod); } gfpe_copy(&data[i*dest->width + j], sum); } } free(dest->data); dest->data = data; return 1; } /** * gfpem_transpose_multiply * Multiplies the transpose of the left hand side matrix with the * hand side matrix and stores the result in the third, which * should be pre-allocated. * @params * * dest : field matrix object to store the matrix product * * leftT, right : field matrix object representing left- and right- * hand-sides respectively. * @return * * 1 if success, 0 otherwise * NOTE. Modular reduction is applied only once, after computing the * inner product between left row and right column and storing the * intermediate result in an int. If the int is four bytes and the * field element takes up a full byte, then in the worst case every * product requires two bytes and every 2^k additions requires k * extra bits. Since we have 16 bits to spare we have at most 2^16 * additions which is anyway the max. height and width of matrices * that can be stored in a unsigned int. */ int gfpem_transpose_multiply( gfpematrix * dest, gfpematrix leftT, gfpematrix right ) { unsigned int i, j, k; gfpe_element prod, sum, lsum; gfpe_element * data; #ifdef DEBUG if( dest->height != leftT.width || dest->width != right.width || leftT.height != right.height ) { printf("in gfpem_transpose_multiply: trying to multiply matrices with unmatched dimensions: (%ix%i)^T * %ix%i = %ix%i\n", leftT.height, leftT.width, right.height, right.width, dest->height, dest->width); return 0; } #endif data = malloc(sizeof(gfpe_element)*dest->width*dest->height); for( i = 0 ; i < leftT.width ; ++i ) { for( j = 0 ; j < right.width ; ++j ) { gfpe_zero(&sum); for( k = 0 ; k < leftT.height ; ++k ) { gfpe_copy(&lsum, sum); gfpe_multiply(&prod, leftT.data[k*leftT.width + i], right.data[k*right.width + j]); gfpe_add(&sum, lsum, prod); } gfpe_copy(&data[i*dest->width + j], sum); } } free(dest->data); dest->data = data; return 1; } /** * gfpem_multiply_constant * Multiply the matrix with a constant. * @return * * 1 if success */ int gfpem_multiply_constant( gfpematrix dest, gfpematrix source, gfpe_element constant ) { unsigned int i, j; gfpe_element lhs, rhs; #ifdef DEBUG if( dest.width != source.width || dest.height != source.height ) { printf("gfpem_multiply_constant: cannot multiply matrix with constant because dimensions of destination do not match those of source! %ix%i <- %ix%i\n", dest.height, dest.width, source.height, source.width); return 0; } #endif for( i = 0 ; i < dest.height ; ++i ) { for( j = 0 ; j < dest.width ; ++j ) { gfpe_multiply(&dest.data[i*dest.width + j], source.data[i*dest.width + j], constant); } } return 1; } /** * gfpem_add * Add one matrix to another and store the result in a third. The * third matrix must be preallocated. * @params * * dest : the matrix object to store the result in * * left, right : the matrix objects to add together; they must * have the same dimensions! * @return * * 1 if success, 0 otherwise */ int gfpem_add( gfpematrix dest, gfpematrix left, gfpematrix right ) { unsigned int i, j; #ifdef DEBUG if( dest.width != left.width || left.width != right.width || dest.height != left.height || left.height != right.height ) { printf("in gfpem_add: trying to add matrices of incompatible dimensions! %ix%i + %ix%i = %ix%i\n", left.height, left.width, right.height, right.width, dest.height, dest.width); return 0; } #endif for( i = 0 ; i < dest.height ; ++i ) { for( j = 0 ; j < dest.width ; ++j ) { gfpe_add(&dest.data[i*dest.width + j], left.data[i*left.width + j], right.data[i*right.width + j]); } } return 1; } /** * gfpem_weighted_sum * Compute the weighted sum of two matrices, and store the result in * a third one. This third matrix must be pre-allocated. * @params: * * dest : the matrix object to store the result into * * left_constant, right_constant : gfpe_elements that represent * the field elements to weight the left and right matrices with * * left_matrix, right_matrix : the two matrix objects to add * together. * @return * 1 if success, 0 otherwise */ int gfpem_weighted_sum( gfpematrix dest, gfpe_element left_constant, gfpematrix left_matrix, gfpe_element right_constant, gfpematrix right_matrix ) { unsigned int i, j; gfpe_element lhs, rhs; #ifdef DEBUG if( dest.width != left_matrix.width || left_matrix.width != right_matrix.width || dest.height != left_matrix.height || left_matrix.height != right_matrix.height ) { printf("in gfpem_weighted_sum: trying to add matrices of incompatible dimensions! %ix%i + %ix%i = %ix%i\n", left_matrix.height, left_matrix.width, right_matrix.height, right_matrix.width, dest.height, dest.width); return 0; } #endif for( i = 0 ; i < dest.height ; ++i ) { for( j = 0 ; j < dest.width ; ++j ) { gfpe_multiply(&lhs, left_matrix.data[i*left_matrix.width + j], left_constant); gfpe_multiply(&rhs, right_matrix.data[i*right_matrix.width + j], right_constant); gfpe_add(&dest.data[i*dest.width + j], lhs, rhs); } } return 1; } /** * gfpem_rowop * Perform a row operation on the given matrix, i.e., add one row, * weighted by a constant, to another. * @params * * mat : the matrix object to operate on * * destrow, sourcerow : unsigned ints representing indices of the rows to operate on * * constant : gfpe_element representing the right constant * * offset : unsigned int, represents the number of zeros to skip before applying the row operation * @returns * * 1 if success */ int gfpem_rowop( gfpematrix mat, unsigned int destrow, unsigned int sourcerow, gfpe_element constant, unsigned int offset ) { unsigned int j; gfpe_element prod, sum; for( j = offset ; j < mat.width ; ++j ) { gfpe_multiply(&prod, mat.data[sourcerow*mat.width + j], constant); gfpe_add(&sum, mat.data[destrow*mat.width + j], prod); gfpe_copy(&mat.data[destrow*mat.width + j], sum); } return 1; } /** * gfpem_scalerow * Scales a single row in the matrix with a given constant. * @params * * mat : the matrix object to operate on * * rowidx : index of the row to scale * * constant : gfpe_element -- the field element to multiply the * row with * @returns * * 1 if success, 0 otherwise */ int gfpem_scalerow( gfpematrix mat, unsigned int rowidx, gfpe_element constant ) { unsigned int j; gfpe_element temp; for( j = 0 ; j < mat.width ; ++j ) { gfpe_multiply(&temp, mat.data[rowidx*mat.width + j], constant); gfpe_copy(&mat.data[rowidx*mat.width + j], temp); } return 1; } /** * gfpem_fliprows * Flip two rows in the given matrix. * @params * * mat : the matrix object to operate on * * destrow, sourcerow : the indices of the rows to flip * @return * * 1 if success */ int gfpem_fliprows( gfpematrix mat, unsigned int destrow, unsigned int sourcerow ) { unsigned int j; gfpe_element a; for( j = 0 ; j < mat.width ; ++j ) { gfpe_copy(&a, mat.data[destrow*mat.width + j]); gfpe_copy(&mat.data[destrow*mat.width + j], mat.data[sourcerow*mat.width + j]); gfpe_copy(&mat.data[sourcerow*mat.width + j], a); } return 1; } /** * gfpem_redech * Reduce the given matrix to reduced row echelon form using row * operations. * @params * * mat : the matrix object to work on * @return * 1 if success */ int gfpem_redech( gfpematrix mat ) { unsigned int col, row, i; gfpe_element inv; gfpe_element prod; gfpe_element diff; row = 0; for( col = 0 ; col < mat.width ; ++col ) { for( i = row ; i < mat.height ; ++i ) { if( gfpe_is_zero(mat.data[i*mat.width + col]) != 1 ) { if( i != row ) { gfpem_fliprows(mat, i, row); } break; } } if( i == mat.height ) { continue; } gfpe_inverse(&inv, mat.data[row*mat.width + col]); if( gfpe_is_one(inv) != 1 ) { gfpem_scalerow(mat, row, inv); } for( i = 0 ; i < mat.height ; ++i ) { if( i == row ) { continue; } gfpe_negate(&diff, mat.data[i*mat.width + col]); gfpem_rowop(mat, i, row, diff, col); } row = row + 1; if( row == mat.height ) { break; } } return 1; } /** * gfpem_solve * Solve a matrix equation of the form Ax = b for x up to a term in * the kernel of A. This routine also initializes a kernel matrix, * whose rows form a basis for the kernel of A. * @params * * coeffs : a mxn gfpematrix object representing the coefficient * matrix A * * target : a mx1 gfpematrix object representing the b vector * * solution : a nx1 gfpematrix object to store one solution into * * kernel : an uninitialized gfpematrix object whose columns will * span the kernel of A * @post * * for all kernel.width x 1 vectors "random" holds: * coeffs * (solution + kernel * random) = target * @return * * 1 if a solution exists, 0 otherwise */ int gfpem_solve( gfpematrix coeffs, gfpematrix target, gfpematrix solution, gfpematrix * kernel ) { /* declare variables for echelon reduction */ unsigned int col, row, i, j; gfpe_element inv, zero, one, minusone, neg; gfpematrix mat; /* declare variables for pivot tracking */ unsigned int *pivots; unsigned int *npivots; unsigned int num_pivots; unsigned int num_npivots; int have_solution; gfpe_zero(&zero); gfpe_one(&one); gfpe_negate(&minusone, one); /* initialize variables for pivot tracking */ num_pivots = 0; num_npivots = 0; pivots = malloc(sizeof(unsigned int) * (coeffs.width+1)); npivots = malloc(sizeof(unsigned int) * (coeffs.width+1)); /* initialize mat and copy coeffs and target to it */ mat = gfpem_init(coeffs.height, coeffs.width+1); /*gfpem_copy(mat, coeffs);*/ for( i = 0 ; i < mat.height ; ++i ) { for( j = 0 ; j < coeffs.width ; ++j ) { gfpe_copy(&mat.data[i*mat.width + j], coeffs.data[i*coeffs.width + j]); } } for( i = 0 ; i < mat.height ; ++i ) { gfpe_copy(&mat.data[i*mat.width + mat.width - 1], target.data[i*target.width + 0]); } /* perform row echelon reduction */ row = 0; for( col = 0 ; col < mat.width ; ++col ) { for( i = row ; i < mat.height ; ++i ) { /* if the leading element is different from zero, use it as pivot element */ if( gfpe_compare(mat.data[i*mat.width + col], zero) != 1 ) { if( i != row ) { gfpem_fliprows(mat, i, row); } break; } } if( i == mat.height ) { /* non pivot */ npivots[num_npivots++] = col; continue; } /* pivot */ pivots[num_pivots++] = col; gfpe_inverse(&inv, mat.data[row*mat.width + col]); /* rescale row if necessary */ if( gfpe_compare(inv, one) != 1 ) { gfpem_scalerow(mat, row, inv); } for( i = 0 ; i < mat.height ; ++i ) { if( i == row ) { continue; } gfpe_negate(&neg, mat.data[i*mat.width + col]); gfpem_rowop(mat, i, row, neg, col); } row = row + 1; if( row == mat.height ) { for( i = col+1 ; i < mat.width ; ++i ) { npivots[num_npivots++] = i; } break; } } /* read out solution if the system is consistent */ have_solution = (pivots[num_pivots-1] != mat.width-1); for( i = 0 ; i < mat.width-1 ; ++i ) { gfpe_zero(&solution.data[i*solution.width]); } if( have_solution == 1 ) { for( i = 0 ; i < num_pivots ; ++i ) { gfpe_copy(&solution.data[pivots[i]*solution.width], mat.data[i*mat.width + mat.width - 1]); } } /* read out kernel, if it exists */ if( num_npivots > 1 ) { *kernel = gfpem_init(mat.width-1, num_npivots-1); gfpem_zeros(*kernel); for( j = 0 ; j < num_npivots-1 ; ++j ) { gfpe_copy(&(kernel->data[npivots[j]*kernel->width + j]), minusone); for( i = 0 ; i < num_pivots && pivots[i] < npivots[j] ; ++i ) { gfpe_copy(&(kernel->data[pivots[i]*kernel->width + j]), mat.data[i*mat.width + npivots[j]]); } } } else { kernel->width = 0; } /* free allocated memory */ gfpem_destroy(mat); free(pivots); free(npivots); return have_solution; } /** * gfpem_inspan * Decide if a vector is in the column span of a matrix. * @params: * * vec : nx1 matrix * * mat : nxm matrix * @returns: * * 1 if vec is in colspan(mat); 0 otherwise */ int gfpem_inspan( gfpematrix vec, gfpematrix mat ) { gfpematrix solution, kernel; int i, j; int success; #ifdef DEBUG if( mat.height != vec.height || vec.width != 1 ) { printf("cannot decide if %ix%i vector is in colspan of %ix%i matrix because of dimension mismatch.\n", vec.height, vec.width, mat.height, mat.width); return 0; } #endif /* try and solve the system; if the system is consistent, the vector * lies in the span of the matrix */ solution = gfpem_init(mat.width, 1); success = gfpem_solve(mat, vec, solution, &kernel); gfpem_destroy(solution); if( kernel.width > 0 ) gfpem_destroy(kernel); return success; } /** * gfpem_stack * Stacks one matrix on top of another, and stores the result in the third * @params * * mat : matrix object to store the result into * * top, bottom : matrix objects to stack * @return * * 1 if success, 0 otherwise */ int gfpem_stack( gfpematrix mat, gfpematrix top, gfpematrix bottom ) { unsigned int i, j; #ifdef DEBUG if( mat.width != top.width || top.width != bottom.width || mat.height != top.height + bottom.height ) { printf("in gfpem_stack: cannot stack matrices of conflicting dimensions! %ix%i stack %ix%i = %ix%i\n", top.height, top.width, bottom.height, bottom.width, mat.height, mat.width); return 0; } #endif for( i = 0 ; i < top.height ; ++i ) { for( j = 0 ; j < top.width ; ++j ) { gfpe_copy(&mat.data[i*mat.width + j], top.data[i*top.width + j]); } } for( i = 0 ; i < bottom.height ; ++i ) { for( j = 0 ; j < bottom.width ; ++j ) { gfpe_copy(&mat.data[(i+top.height)*mat.width + j], bottom.data[i*bottom.width + j]); } } return 1; } /** * gfpem_cat * Concatenates one matrix to another, and stores the result in a * third matrix. * @params * * res : matrix object that contains the result * * left, right : matrix objects to be stacked on the left, and * right, respectively * @return * * 1 if success, 0 otherwise */ int gfpem_cat( gfpematrix res, gfpematrix left, gfpematrix right ) { unsigned int i, j; #ifdef DEBUG if( res.height != left.height || left.height != right.height || res.width != left.width + right.width ) { printf("in gfpem_cat: cannot concatenate two matrices of conflicting dimensions! %ix%i cat %ix%i = %ix%i\n", left.height, left.width, right.height, right.width, res.height, res.width); return 0; } #endif for( i = 0 ; i < res.height ; ++i ) { for( j = 0 ; j < left.width ; ++j ) { gfpe_copy(&res.data[i*res.width + j], left.data[i*left.width + j]); } for( j = 0 ; j < right.width ; ++j ) { gfpe_copy(&res.data[i*res.width + left.width + j], right.data[i*right.width + j]); } } return 1; } /** * gfpem_slice * Slice a submatrix out of another matrix. * @params: * * dest : the matrix to store the result in; the height and width * of this matrix determine the area of elements to be copied * * source : the matrix where the slice comes from * * row_start, col_start : the indices of the row and column at * which to start the slice * @return * * 1 if success, 0 otherwise */ int gfpem_slice( gfpematrix dest, gfpematrix source, unsigned int row_start, unsigned int col_start ) { unsigned int i, j; #ifdef DEBUG if( source.width < col_start + dest.width || source.height < row_start + dest.height ) { printf("in gfpem_slice: cannot grab slice because slice size exceeds bounds! slicing %ix%i submatrix starting at (%i,%i) from %ix%i matrix\n", dest.height, dest.width, row_start, col_start, source.height, source.width); return 0; } #endif for( i = 0 ; i < dest.height ; ++i ) { for( j = 0 ; j < dest.width ; ++j ) { gfpe_copy(&dest.data[i*dest.width + j], source.data[(i+row_start)*source.width + col_start + j]); } } return 0; } /** * gfpem_inverse * Compute the matrix inverse of mat, store the result in inv. * @return * * 1 if success */ int gfpem_inverse( gfpematrix inv, gfpematrix mat ) { unsigned int i, j; unsigned int catwidth; int invertible; gfpematrix concat; catwidth = inv.width + mat.width; /* Set inv to the identity matrix. */ for( i = 0 ; i < inv.height ; ++i ) { for( j = 0 ; j < inv.width ; ++j ) { gfpe_zero(&inv.data[i*inv.width + j]); } gfpe_one(&inv.data[i*inv.width + i]); } /* Concatenate mat with identity */ concat = gfpem_init(mat.height, catwidth); gfpem_cat(concat, mat, inv); /* row-reduce concat to echelon form */ gfpem_redech(concat); /* test if main diagonal has only ones, because otherwise the * matrix is not invertible */ invertible = 1; for( i = 0 ; i < inv.height ; ++i ) { invertible = invertible & gfpe_is_one(concat.data[i*concat.width + i]); } if( 0 == invertible ) { gfpem_destroy(concat); return 0; } /* select rightmost square from concat */ for( i = 0 ; i < inv.height ; ++i ) { for( j = 0 ; j < inv.width ; ++j ) { gfpe_copy(&inv.data[i*inv.width + j], concat.data[i*concat.width + mat.width + j]); } } /* free concat */ gfpem_destroy(concat); return 1; } /** * gfpem_print * Use printf to print the matrix to stdout. */ int gfpem_print( gfpematrix mat ) { unsigned int i, j; printf("["); for( i = 0 ; i < mat.height ; ++i ) { printf("["); for( j = 0 ; j < mat.width ; ++j ) { gfpe_print(mat.data[i*mat.width+j]); if( j < mat.width - 1 ) { printf(","); printf(" "); } } printf("]"); if( i < mat.height - 1 ) { printf(","); printf("\n"); } } printf("]\n"); } /** * gfpem_print_transpose * Use printf to print the transpose of the matrix to stdout. */ int gfpem_print_transpose( gfpematrix mat ) { gfpematrix temp; temp = gfpem_clone(mat); gfpem_transpose(&temp); gfpem_print(temp); gfpem_destroy(temp); return 1; }
27.888389
231
0.57775
0795ba06109ecdf0b781956958e095ae3c5c6d41
1,834
h
C
Pod/Classes/Categories/NSLayoutConstraint+AutolayoutHelpers.h
iliu/ILLibrary
38bd762cb6ba3db30ef693589c02272119c144bd
[ "MIT" ]
null
null
null
Pod/Classes/Categories/NSLayoutConstraint+AutolayoutHelpers.h
iliu/ILLibrary
38bd762cb6ba3db30ef693589c02272119c144bd
[ "MIT" ]
null
null
null
Pod/Classes/Categories/NSLayoutConstraint+AutolayoutHelpers.h
iliu/ILLibrary
38bd762cb6ba3db30ef693589c02272119c144bd
[ "MIT" ]
null
null
null
// // NSLayoutConstraint+AutolayoutHelpers.h // ILLibrary // // Created by Isaac Liu on 12/6/14. // Copyright (c) 2014 Isaac Liu Inc. All rights reserved. // #import <UIKit/UIKit.h> @interface NSLayoutConstraint (AutolayoutHelpers) // ====== Positional Constraints ====== +(NSArray *) constraintsForCenteredViews:(UIView *)view1 andView2:(UIView *)view2; +(NSArray *) constraintsForHorizontallyCenteredItems:(NSArray *)items inView:(UIView *)view; +(NSArray *) constraintsForVerticallyCenteredItems:(NSArray *)items inView:(UIView *)view; // ====== Full Size Constraints ====== +(NSArray *) constraintsForSameSizeViews:(UIView *)view1 andView2:(UIView *)view2; +(NSArray *) constraintsForSameSizeViews:(UIView *)view1 containingView2:(UIView *)view2 withInset:(UIEdgeInsets) insets; // ====== Horizontal Constraints ====== +(NSArray *) constraintsForHorizontalBar:(UIView *)barView onMainView:(UIView *)mainView withHeight:(CGFloat)height; +(NSArray *) constraintsForSameWidthItems:(NSArray *)items; +(NSArray *) constraintsForFullWidthItems:(NSArray *)items inView:(UIView *)view; // ====== Vertical Constraints ====== +(NSArray *) constraintsForSameHeightItems:(NSArray *)items; +(NSArray *) constraintsForHeightOfItems:(NSArray *)items inView:(UIView *)view withInset:(UIEdgeInsets) inset; // ==== Collection items Constraints ===== +(NSArray *) constraintsForHorizontalItems:(NSArray *)items inView:(UIView *)view; +(NSArray *) constraintsForHorizontalItems:(NSArray *)items inView:(UIView *)view withSpacing:(CGFloat) space; +(NSArray *) constraintsForHorizontalItems:(NSArray *)items inView:(UIView *)view withSpacing:(CGFloat)space andInset:(UIEdgeInsets) inset; // ==== Other ===== +(NSArray *) constraintsForNavigationBar:(UIView *) navBarView onMainView:(UIView *)mainView withHeight:(CGFloat)height; @end
40.755556
139
0.740458
0d44f4fae9e3b6131ec436cf95db3ca9da1cd5ba
351
h
C
src/core_mymalloc.h
dptriani/sage-dust
6837c9d0d29cce03e46f93f69e73206cbb38efc3
[ "MIT" ]
6
2020-02-06T02:47:49.000Z
2022-03-20T04:14:05.000Z
src/core_mymalloc.h
dptriani/sage-dust
6837c9d0d29cce03e46f93f69e73206cbb38efc3
[ "MIT" ]
2
2019-02-13T10:57:27.000Z
2021-06-23T02:16:53.000Z
src/core_mymalloc.h
dptriani/sage-dust
6837c9d0d29cce03e46f93f69e73206cbb38efc3
[ "MIT" ]
2
2020-02-14T05:45:47.000Z
2021-04-09T11:12:02.000Z
#pragma once #ifdef __cplusplus extern "C" { #endif /* functions in core_mymalloc.c */ extern void *mymalloc(size_t n); extern void *mycalloc(const size_t count, const size_t size); extern void *myrealloc(void *p, size_t n); extern void myfree(void *p); extern void print_allocated(void); #ifdef __cplusplus } #endif
17.55
65
0.680912
3707bc80cf248dce08c7439de61df949b0ab7619
1,487
h
C
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ScriptBind_Network.h
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ScriptBind_Network.h
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.8.1/CryEngine/CryAction/Network/ScriptBind_Network.h
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Binding of network functions into script ------------------------------------------------------------------------- History: - 24:11:2004 11:30 : Created by Craig Tiller *************************************************************************/ #ifndef __SCRIPTBIND_NETWORK_H__ #define __SCRIPTBIND_NETWORK_H__ #pragma once #include <IScriptSystem.h> #include <ScriptHelpers.h> class CGameContext; class CCryAction; class CScriptBind_Network : public CScriptableBase { public: CScriptBind_Network( ISystem *pSystem, CCryAction *pFW ); virtual ~CScriptBind_Network(); void Release() { delete this; }; //! <code>Network.Expose()</code> int Expose( IFunctionHandler * pFH ); //! <code>Network.DelegateAuthority(ent, channel)</code> //! <param name="ent">Entity identifier.</param> //! <param name="channel">Network channel.</param> //! <description>Delegate authority for an object to some client.</description> int DelegateAuthority( IFunctionHandler * pFH, ScriptHandle ent, int channel ); virtual void GetMemoryUsage(ICrySizer *pSizer) const { pSizer->AddObject(this, sizeof(*this)); } private: void RegisterGlobals(); void RegisterMethods(); ISystem *m_pSystem; CCryAction *m_pFW; }; #endif
26.553571
80
0.585071
6c21229ac124544477e1c93408ce25e3aef2d952
974
h
C
libfreerdp-core/rail.h
viralkatwad12/FreeRDP-old
0c1e533b09aabc0c8abb1865dbfb79ebe52a7f58
[ "Apache-2.0" ]
7
2015-01-27T11:11:05.000Z
2021-12-08T22:25:16.000Z
libfreerdp-core/rail.h
viralkatwad12/FreeRDP-old
0c1e533b09aabc0c8abb1865dbfb79ebe52a7f58
[ "Apache-2.0" ]
3
2015-02-09T10:05:57.000Z
2021-03-05T09:25:48.000Z
libfreerdp-core/rail.h
viralkatwad12/FreeRDP-old
0c1e533b09aabc0c8abb1865dbfb79ebe52a7f58
[ "Apache-2.0" ]
572
2015-01-26T04:44:44.000Z
2022-03-31T12:18:59.000Z
/* FreeRDP: A Remote Desktop Protocol client. Remote Applications Integrated Locally (RAIL) Copyright 2009 Marc-Andre Moreau <marcandre.moreau@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __RAIL_H #define __RAIL_H #include "rdp.h" struct rdp_app { char application_name[260]; char working_directory[260]; char arguments[260]; }; typedef struct rdp_app rdpApp; void rdp_send_client_execute_pdu(rdpRdp * rdp); #endif // __RAIL_H
26.324324
75
0.75462