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
bf09d96d94841077634808507f72acd032783f8f
3,212
c
C
FSLP_Files/src/linux/serialPortAdapter.c
westpoint-robotics/boson_usma_sdk
b4ef56cf4250ebd860821a41ae62a2ca571f146b
[ "MIT" ]
null
null
null
FSLP_Files/src/linux/serialPortAdapter.c
westpoint-robotics/boson_usma_sdk
b4ef56cf4250ebd860821a41ae62a2ca571f146b
[ "MIT" ]
null
null
null
FSLP_Files/src/linux/serialPortAdapter.c
westpoint-robotics/boson_usma_sdk
b4ef56cf4250ebd860821a41ae62a2ca571f146b
[ "MIT" ]
null
null
null
#include "serialPortAdapter.h" //specific implementation of serial port #include "serial.h" //platform agnostic timeout // #include "timeoutLogic.h" not needed for current serial library. #include <stdio.h> #define DO_DEBUG_TRACE(x...) //printf(x) #define KNOWN_PORTS 48 static HANDLE port_handles[KNOWN_PORTS] = {0}; static char port_names[KNOWN_PORTS][16] = { "/dev/ttyUSB0", "/dev/ttyUSB1","/dev/ttyUSB2","/dev/ttyUSB3", "/dev/ttyUSB4","/dev/ttyUSB5","/dev/ttyUSB6", "/dev/ttyUSB7", "/dev/ttyUSB8","/dev/ttyUSB9","/dev/ttyUSB10","/dev/ttyUSB11", "/dev/ttyUSB12","/dev/ttyUSB13","/dev/ttyUSB14","/dev/ttyUSB15", "/dev/ttyACM0","/dev/ttyACM1","/dev/ttyACM2","/dev/ttyACM3", "/dev/ttyACM4","/dev/ttyACM5","/dev/ttyACM6","/dev/ttyACM7", "/dev/ttyACM8","/dev/ttyACM9","/dev/ttyACM10","/dev/ttyACM11", "/dev/ttyACM12","/dev/ttyACM13","/dev/ttyACM14","/dev/ttyACM15", "/dev/ttyS0","/dev/ttyS1","/dev/ttyS2","/dev/ttyS3", "/dev/ttyS4","/dev/ttyS5","/dev/ttyS6","/dev/ttyS7", "/dev/ttyS8","/dev/ttyS9","/dev/ttyS10","/dev/ttyS11", "/dev/ttyS12","/dev/ttyS13","/dev/ttyS14","/dev/boson_ser", }; int32_t FSLP_lookup_port_id( char *port_name, int32_t len ){ int32_t port_id = -1; if (len > 16) { //no port names >16 characters return -1; } for (int32_t port_id=0; port_id<KNOWN_PORTS; port_id++) { if ( 0 == strncmp(port_names[port_id],port_name,len) ) { return port_id; } } return -1; } uint8_t FSLP_open_port(int32_t port_id, int32_t baud_rate){ char settings_buff[16]; sprintf(settings_buff,"%d,8,n,1",baud_rate); PortSettingsType port_settings = str2ps(port_names[port_id], settings_buff); int32_t success = open_port(port_settings, &(port_handles[port_id]) ); if (0 != success) { port_handles[port_id] = 0; } return (uint8_t) success; // 0 == success. } void FSLP_close_port(int32_t port_id){ int32_t ignore = close_port(port_handles[port_id]); port_handles[port_id] = 0; } //Return type is int16_t, so that the full uint8_t value can be represented // without overlapping with negative error codes. int16_t FSLP_read_byte_with_timeout(int32_t port_id, double timeout) { uint8_t in_byte = 0x00; int32_t timeout_us = (int32_t) timeout*1e6; //seconds * 1e6 int32_t timeout_occurred = 0; in_byte = read_byte_time( port_handles[port_id] , timeout_us, &timeout_occurred); if (0 != timeout_occurred) { return -1; } return (int16_t) in_byte; } void FSLP_flush_write_buffer(int32_t port_id) { flush_buffer_tx(port_handles[port_id]); } #ifdef WRITE_BUFFER_AS_SINGLE_BYTES // use single byte writes #error "NOT Implemented!" #else // use buffer access function writes int32_t FSLP_write_buffer(int32_t port_id, uint8_t *frame_buf, int32_t len) { int32_t result; result = send_buffer(port_handles[port_id], frame_buf, (uint16_t) len); FSLP_flush_write_buffer(port_id); return result; } #endif// WRITE_BUFFER_AS_SINGLE_BYTES vs frame writes
32.444444
86
0.648817
bfdde89e7c8d660bf2de8fd72293a20d9d2b93fb
304
h
C
ros2_mod_ws/build/rcl_interfaces/rosidl_generator_objc/ROS_rcl_interfaces/srv/ListParameters.h
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
1
2020-05-19T14:33:49.000Z
2020-05-19T14:33:49.000Z
ros2_mod_ws/install/include/ROS_rcl_interfaces/srv/ListParameters.h
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
null
null
null
ros2_mod_ws/install/include/ROS_rcl_interfaces/srv/ListParameters.h
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
null
null
null
#import <Foundation/Foundation.h> #import "ROS_rcl_interfaces/srv/ListParameters_Request.h" #import "ROS_rcl_interfaces/srv/ListParameters_Response.h" @interface ROS_rcl_interfaces_srv_ListParameters : NSObject + (intptr_t)serviceTypesupportHandle; + (Class)requestType; + (Class)responseType; @end
21.714286
59
0.822368
2a0c2aa705412b25d17fb5173b30094c0963502b
1,096
h
C
src/main/include/io_opentimeline_opentimelineio_Effect.h
reinecke/OpenTimelineIO-Java-Bindings
3e66d59a692e814700bfdd2cc8b7def0f837fe9a
[ "Apache-2.0" ]
4
2021-03-30T17:37:03.000Z
2021-07-26T11:43:08.000Z
src/main/include/io_opentimeline_opentimelineio_Effect.h
OpenTimelineIO/OpenTimelineIO-Java-Bindings
11a6e62ca052dc99cc8a96b587a51926ee055a7d
[ "Apache-2.0" ]
49
2020-09-09T18:00:12.000Z
2022-03-30T17:06:07.000Z
src/main/include/io_opentimeline_opentimelineio_Effect.h
reinecke/OpenTimelineIO-Java-Bindings
3e66d59a692e814700bfdd2cc8b7def0f837fe9a
[ "Apache-2.0" ]
4
2020-09-09T05:10:11.000Z
2021-07-21T15:25:23.000Z
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class io_opentimeline_opentimelineio_Effect */ #ifndef _Included_io_opentimeline_opentimelineio_Effect #define _Included_io_opentimeline_opentimelineio_Effect #ifdef __cplusplus extern "C" { #endif /* * Class: io_opentimeline_opentimelineio_Effect * Method: initialize * Signature: (Ljava/lang/String;Ljava/lang/String;Lio/opentimeline/opentimelineio/AnyDictionary;)V */ JNIEXPORT void JNICALL Java_io_opentimeline_opentimelineio_Effect_initialize (JNIEnv *, jobject, jstring, jstring, jobject); /* * Class: io_opentimeline_opentimelineio_Effect * Method: getEffectName * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_io_opentimeline_opentimelineio_Effect_getEffectName (JNIEnv *, jobject); /* * Class: io_opentimeline_opentimelineio_Effect * Method: setEffectName * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_io_opentimeline_opentimelineio_Effect_setEffectName (JNIEnv *, jobject, jstring); #ifdef __cplusplus } #endif #endif
28.842105
99
0.789234
71fac36ee580641ebba81994add85459a3aa53b1
3,728
c
C
ext/capture.c
cmol/multicast-perf-test
8add6669939626e9a2388e5cad7b198a82d01a20
[ "MIT" ]
null
null
null
ext/capture.c
cmol/multicast-perf-test
8add6669939626e9a2388e5cad7b198a82d01a20
[ "MIT" ]
null
null
null
ext/capture.c
cmol/multicast-perf-test
8add6669939626e9a2388e5cad7b198a82d01a20
[ "MIT" ]
null
null
null
#include <pcap.h> #include <stdio.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #define PORT 0xbeee #define SERVADDR "::1" void DumpHex(const void* data, size_t size) { char ascii[17]; size_t i, j; ascii[16] = '\0'; for (i = 0; i < size; ++i) { printf("%02X ", ((unsigned char*)data)[i]); if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') { ascii[i % 16] = ((unsigned char*)data)[i]; } else { ascii[i % 16] = '.'; } if ((i+1) % 8 == 0 || i+1 == size) { printf(" "); if ((i+1) % 16 == 0) { printf("| %s \n", ascii); } else if (i+1 == size) { ascii[(i+1) % 16] = '\0'; if ((i+1) % 16 <= 8) { printf(" "); } for (j = (i+1) % 16; j < 16; ++j) { printf(" "); } printf("| %s \n", ascii); } } } } int main(int argc, char *argv[]) { pcap_t *handle; /* Session handle */ char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */ struct bpf_program fp; /* The compiled filter */ //char filter_exp[] = "port 22"; /* The filter expression */ char filter_exp[] = "dst host fd00:1::101 and udp port 48879"; /* The filter expression */ bpf_u_int32 mask; /* Our netmask */ bpf_u_int32 net; /* Our IP */ struct pcap_pkthdr header; /* The header that pcap gives us */ const u_char *packet; /* The actual packet */ /* Socket definitions */ int sock; socklen_t clilen; struct sockaddr_in6 server_addr, client_addr; char buffer[1024]; char addrbuf[INET6_ADDRSTRLEN]; /* create a DGRAM (UDP) socket in the INET6 (IPv6) protocol */ sock = socket(PF_INET6, SOCK_DGRAM, 0); if (sock < 0) { perror("creating socket"); exit(1); } /* create server address: where we want to send to */ /* clear it out */ memset(&server_addr, 0, sizeof(server_addr)); /* it is an INET address */ server_addr.sin6_family = AF_INET6; /* the server IP address, in network byte order */ inet_pton(AF_INET6, SERVADDR, &server_addr.sin6_addr); /* the port we are going to send to, in network byte order */ server_addr.sin6_port = htons(PORT); /* Define the device */ if(argc < 2) { printf("Usage: %s [device]\n", argv[0]); return 1; } char *dev = argv[1]; printf("Device: %s\n", dev); /* Find the properties for the device */ if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf); net = 0; mask = 0; } /* Open the session in promiscuous mode */ handle = pcap_open_live(dev, BUFSIZ, 1, 5, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); return(2); } /* Compile and apply the filter */ if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle)); return(2); } if (pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle)); return(2); } while(1) { /* Grab a packet */ packet = pcap_next(handle, &header); /* Print its length */ printf("Jacked a packet with length of [%d]\n", header.len); DumpHex(&packet[62], header.len - 62); /* now send a datagram */ if (sendto(sock, &packet[62], header.len - 62, 0, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("sendto failed"); exit(4); } } /* And close the session */ pcap_close(handle); return(0); }
27.614815
93
0.574571
d51c6a3ea954e573f1af26683d4a74f719430061
626
h
C
MusicPlayer/BasicFramework/BasicFramework/Vender/IMGBrowse/LYLIMGScrollView.h
LiuYulei001/MusicPlayer
80b70a9187a2871ba69152a54d463e09703491c9
[ "MIT" ]
2
2017-10-20T02:02:58.000Z
2017-12-05T10:48:10.000Z
MusicPlayer/BasicFramework/BasicFramework/Vender/IMGBrowse/LYLIMGScrollView.h
LiuYulei001/MusicPlayer
80b70a9187a2871ba69152a54d463e09703491c9
[ "MIT" ]
1
2020-12-08T15:47:40.000Z
2020-12-08T15:47:40.000Z
MusicPlayer/BasicFramework/BasicFramework/Vender/IMGBrowse/LYLIMGScrollView.h
LiuYulei001/MusicPlayer
80b70a9187a2871ba69152a54d463e09703491c9
[ "MIT" ]
null
null
null
// // LYLIMGScrollView.h // SPI-Piles // // Created by SPI-绿能宝 on 16/5/16. // Copyright © 2016年 北京SPI绿能宝. All rights reserved. // #import <UIKit/UIKit.h> @protocol LYLIMGScrollViewDelegate <NSObject> - (void)touchedImageViewAction:(id)sender; @end @class LYLPageControl; @interface LYLIMGScrollView : UIScrollView @property(nonatomic,weak)id<LYLIMGScrollViewDelegate> LYLScrDelegate; @property(nonatomic,strong)LYLPageControl *pageControl; -(instancetype)initWithImgURLs:(NSArray *)imgs withIndexPage:(NSInteger)page_number; -(instancetype)initWithImgs:(NSArray *)imgs withIndexPage:(NSInteger)page_number; @end
21.586207
84
0.777955
57b45d8fac4dc0d518f473e63203a0c4663c653e
567
c
C
Sprint08/t03/mx_hex_to_nbr.c
LoveNek0/UCode-Connect-Marathone
d80e0c1e6719dd5069d2a065fe529fd09a1dad40
[ "MIT" ]
null
null
null
Sprint08/t03/mx_hex_to_nbr.c
LoveNek0/UCode-Connect-Marathone
d80e0c1e6719dd5069d2a065fe529fd09a1dad40
[ "MIT" ]
null
null
null
Sprint08/t03/mx_hex_to_nbr.c
LoveNek0/UCode-Connect-Marathone
d80e0c1e6719dd5069d2a065fe529fd09a1dad40
[ "MIT" ]
null
null
null
unsigned long mx_hex_to_nbr(const char *hex){ unsigned long step = 1; unsigned long itog = 0; char *str = (char *)hex; char *str2 = str; while (*str != '\0') str++; while (str-- != str2) if (*str >= '0' && *str <= '9') { itog += (*str - '0') * step; step *= 16; } else if(*str >= 'a' && *str <= 'f'){ itog+=(*str - 'a' + 10)*step; step *= 16; } else if(*str >= 'A' && *str <= 'F'){ itog+=(*str - 'A' + 10)*step; step *= 16; } else return 0; return itog; }
21
45
0.417989
41a8de8801ac34f42fdd80bca48267917db56ea5
1,381
c
C
stats/battery.d.c
voutilad/oxbar
37fbca62e83cb4bfd4450d40ba18da97969d8c80
[ "0BSD" ]
41
2018-11-14T18:00:47.000Z
2022-01-02T13:03:06.000Z
stats/battery.d.c
voutilad/oxbar
37fbca62e83cb4bfd4450d40ba18da97969d8c80
[ "0BSD" ]
4
2018-12-13T09:37:23.000Z
2020-03-23T14:14:53.000Z
stats/battery.d.c
voutilad/oxbar
37fbca62e83cb4bfd4450d40ba18da97969d8c80
[ "0BSD" ]
2
2020-06-17T19:55:00.000Z
2021-03-08T08:31:14.000Z
/* * Copyright (c) 2018 Ryan Flannery <ryan.flannery@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <err.h> #include <signal.h> #include <stdio.h> #include <unistd.h> #include "battery.h" volatile sig_atomic_t sig_stop = 0; void stop(int __attribute__((unused)) sig) { sig_stop = 1; } int main() { struct battery_stats s; signal(SIGINT, stop); battery_init(&s); if (!s.is_setup) errx(1, "failed to setup battery!"); printf("%8s\t%8s\t%8s\n", "plugged?", "%", "minutes"); while (!sig_stop) { battery_update(&s); printf("%8s\t%8.1f\t%8d\n", s.plugged_in ? "TRUE" : "false", s.charge_pct, s.minutes_remaining); sleep(1); } battery_close(&s); }
27.62
75
0.712527
e0ea3ba208dd7642c3f2a7444566ea20652aa52d
54
c
C
SRCMutation/test/lcr/lcr_or_assign/test.c
SNTSVV/FAQAS_MASS
aaa54d6723ddf505b5ecd3ae2fd033c7132bb0bb
[ "Apache-2.0" ]
1
2021-11-22T16:03:47.000Z
2021-11-22T16:03:47.000Z
SRCMutation/test/lcr/lcr_or_assign/test.c
SNTSVV/FAQAS_MASS
aaa54d6723ddf505b5ecd3ae2fd033c7132bb0bb
[ "Apache-2.0" ]
null
null
null
SRCMutation/test/lcr/lcr_or_assign/test.c
SNTSVV/FAQAS_MASS
aaa54d6723ddf505b5ecd3ae2fd033c7132bb0bb
[ "Apache-2.0" ]
null
null
null
double function() { int a = 1, b; b |= a; return b; }
9
19
0.537037
f16ea4edaf30a0d225196cb14c058211b070ddff
4,104
h
C
PYHero/Page/F001/PYMedia/Helper/RainbowAV/c2s.h
BobliiExp/F-001
31124e5f3276798859ebb34b43cf03d4b43b8c8f
[ "Apache-2.0" ]
3
2018-12-11T08:02:11.000Z
2018-12-12T03:33:48.000Z
PYHero/Page/F001/PYMedia/Helper/RainbowAV/c2s.h
BobliiExp/F-001
31124e5f3276798859ebb34b43cf03d4b43b8c8f
[ "Apache-2.0" ]
1
2018-08-20T08:56:17.000Z
2018-08-20T08:56:17.000Z
PYHero/Page/F001/PYMedia/Helper/RainbowAV/c2s.h
fightCrow/F-001
b23bef780d8616ef7447102462295b3fee66370a
[ "Apache-2.0" ]
7
2018-08-20T07:18:05.000Z
2018-08-29T02:55:49.000Z
#ifndef __C2S_H_ #define __C2S_H_ #include <string.h> #include <stdint.h> #include "pdu.h" #ifdef __cplusplus extern "C" { #endif // 消息包结构: 2字节包长(TotalLen)+2字节命令字(CmdId)+2字节序列号(SeqId)+2字节响应码(CmdStatus)+包体(可选) // 命令ID定义 #define C2S_HEART_BEAT 0x0001 // 心跳 #define C2S_HEART_BEAT_RSP 0x1001 // 心跳响应 #define C2S_LOGIN 0x0002 // 登录 #define C2S_LOGIN_RSP 0x1002 // 登录响应 #define C2S_LOGOUT 0x0003 // 注销 #define C2S_HOLE 0x0004 // 请求对方地址,并让对方往自己打洞 #define C2S_HOLE_RSP 0x1004 // 打洞响应 #define C2S_HOLE_NOTIFY 0x1005 // 服务器发来消息让自己往对方打洞 // 错误码定义 #define C2S_ERR_OK 0x0000 // 正确 #define C2S_ERR_INVALID_ACCOUNT 0x0001 // 无效帐号 #define C2S_ERR_INVALID_PASSWORD 0x0002 // 无效密码 #define C2S_ERR_OFFLINE 0x0003 // 对方离线 #define C2S_ERR_NOTLOGIN 0x0004 // 没有登录 #define C2S_ERR_Disconnect 0x0005 // 没有链接 #define C2S_ERR_ServerConfg 0x0006 // 服务器配置错误 #define C2S_ERR_Data 0x0007 // 接收到数据错误 #define C2S_ERR_NotMyData 0x0008 // 不是属于我的数据 // 结构定义 #pragma pack(1) typedef struct { int64_t account; int8_t password[64]; char localIp[16]; uint16_t localPort; } CmdLogin; typedef struct { int64_t account; char ip[16]; uint16_t port; char localIp[16]; uint16_t localPort; } CmdLoginRsp; typedef struct { int64_t account; } CmdLogout; typedef struct { int64_t account; char localIp[16]; uint16_t localPort; } CmdHeartBeat; typedef struct { int64_t account; char ip[16]; uint16_t port; char localIp[16]; uint16_t localPort; } CmdHeartBeatRsp; typedef struct { int64_t account; char localIp[16]; uint16_t localPort; int64_t toAccount; } CmdC2SHole; typedef struct { int64_t account; char ip[16]; uint16_t port; char localIp[16]; uint16_t localPort; int64_t toAccount; char toIp[16]; uint16_t toPort; char toLocalIp[16]; uint16_t toLocalPort; } CmdC2SHoleRsp; typedef struct { int64_t account; char ip[16]; uint16_t port; char localIp[16]; uint16_t localPort; int64_t toAccount; char toIp[16]; uint16_t toPort; char toLocalIp[16]; uint16_t toLocalPort; } CmdC2SHoleNotify; #pragma pack() /** * 登录协议编码 */ int encodeLogin(uint16_t SeqId, uint16_t CmdStatus, CmdLogin *pBody, uint8_t *buf, uint16_t *len); /** * 登录协议解码 */ int decodeLogin(uint8_t *buf, uint16_t len, Header *pHeader, CmdLogin *pBody); /** * 登录回包编码 */ int encodeLoginRsp(uint16_t SeqId, uint16_t CmdStatus, CmdLoginRsp *pBody, uint8_t *buf, uint16_t *len); /** * 登录回包解码 */ int decodeLoginRsp(uint8_t *buf, uint16_t len, Header *pHeader, CmdLoginRsp *pBody); /** * 退出登录协议编码 */ int encodeLogout(uint16_t SeqId, uint16_t CmdStatus, CmdLogout *pBody, uint8_t *buf, uint16_t *len); /** * 退出登录协议解码 */ int decodeLogout(uint8_t *buf, uint16_t len, Header *pHeader, CmdLogout *pBody); /** * c2s心跳编码 */ int encodeHeartBeat(uint16_t SeqId, uint16_t CmdStatus, CmdHeartBeat *pBody, uint8_t *buf, uint16_t *len); /** * c2s心跳解码 */ int decodeHeartBeat(uint8_t *buf, uint16_t len, Header *pHeader, CmdHeartBeat *pBody); /** * c2s心跳回包编码 */ int encodeHeartBeatRsp(uint16_t SeqId, uint16_t CmdStatus, CmdHeartBeatRsp *pBody, uint8_t *buf, uint16_t *len); /** * c2s心跳回包解码 */ int decodeHeartBeatRsp(uint8_t *buf, uint16_t len, Header *pHeader, CmdHeartBeatRsp *pBody); /** * 往服务器打洞协议编码 */ int encodeC2SHole(uint16_t SeqId, uint16_t CmdStatus, CmdC2SHole *pBody, uint8_t *buf, uint16_t *len); /** * 往服务器打洞协议解码 */ int decodeC2SHole(uint8_t *buf, uint16_t len, Header *pHeader, CmdC2SHole *pBody); /** * 往服务器打洞回包协议编码 */ int encodeC2SHoleRsp(uint16_t SeqId, uint16_t CmdStatus, CmdC2SHoleRsp *pBody, uint8_t *buf, uint16_t *len); /** * 往服务器打洞回包协议解码 */ int decodeC2SHoleRsp(uint8_t *buf, uint16_t len, Header *pHeader, CmdC2SHoleRsp *pBody); /** * c2s打洞消息协议编码 */ int encodeC2SHoleNotify(uint16_t SeqId, uint16_t CmdStatus, CmdC2SHoleNotify *pBody, uint8_t *buf, uint16_t *len); /** * c2s打洞消息协议解码 */ int decodeC2SHoleNotify(uint8_t *buf, uint16_t len, Header *pHeader, CmdC2SHoleNotify *pBody); #ifdef __cplusplus } #endif #endif
23.186441
114
0.710283
0b986428fe7523af7ae9bef21829559461f7fefe
598
c
C
sig.c
AyanAgrawal25/Ssshhelll
f3dc82409149c0141ada3f1c0ca0a5fb1f4be91c
[ "Apache-2.0" ]
null
null
null
sig.c
AyanAgrawal25/Ssshhelll
f3dc82409149c0141ada3f1c0ca0a5fb1f4be91c
[ "Apache-2.0" ]
null
null
null
sig.c
AyanAgrawal25/Ssshhelll
f3dc82409149c0141ada3f1c0ca0a5fb1f4be91c
[ "Apache-2.0" ]
null
null
null
#include "header.h" int sig(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Error :Wrong arguments.\n"); return 0; } int jobn = atoi(argv[0]); int sign = atoi(argv[0]); if (jobn <= 0 || sign <= 0) { fprintf(stderr, "Error: Give valid argument\n"); return 0; } procinfo *p = info_id(procs, jobn); if (p == NULL) { fprintf(stderr, "Process not found!\n"); return 0; } if (kill(p->pid, sign) == -1) { perror("Error sending signal"); return 0; } return 1; }
17.588235
56
0.48495
010828860437f91649bff4ac596a4405b7add564
271
c
C
1.c
joe1166/noi
be2e9fcd8306ff4f20a4306e219656346a396013
[ "Apache-2.0" ]
null
null
null
1.c
joe1166/noi
be2e9fcd8306ff4f20a4306e219656346a396013
[ "Apache-2.0" ]
null
null
null
1.c
joe1166/noi
be2e9fcd8306ff4f20a4306e219656346a396013
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> int n[9] = {1,2,3,4,5,6,7,8,9}; int a = 0, b = 0, c = 0; int main(){ for(int i = 0; i < 9; i++){ //printf("%d\n", n[8]); for(int j = 0; j < 9; j++){ if(j == i){ continue; } for(int k = 0; k < 9; k++){ } } } return 0; }
13.55
31
0.387454
78e862aa9c579732deed16605d3b4adcf3f2a3e8
593
c
C
MPI/mpi-simple/text_mpi.c
ebaty/ParallelProgramming
6212f8c6601bb6dd6e365dfa0866d6fa11e44745
[ "MIT" ]
null
null
null
MPI/mpi-simple/text_mpi.c
ebaty/ParallelProgramming
6212f8c6601bb6dd6e365dfa0866d6fa11e44745
[ "MIT" ]
null
null
null
MPI/mpi-simple/text_mpi.c
ebaty/ParallelProgramming
6212f8c6601bb6dd6e365dfa0866d6fa11e44745
[ "MIT" ]
null
null
null
#include <stdio.h> #include <mpi.h> int main(int argc, char **argv) { int rank, tag = 0; char sendbuf[1024]; char recvbuf[1024]; MPI_Status status; MPI_Request hoge; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); printf("rank = %d\n", rank); if ((rank & 1) == 0) { sprintf(sendbuf, "hoge!!! from %d", rank); int i, error; MPI_Isend(sendbuf, 1024, MPI_BYTE, rank+1, tag, MPI_COMM_WORLD, &hoge); } else { MPI_Recv(recvbuf, 1024, MPI_BYTE, rank-1, tag, MPI_COMM_WORLD, &status); printf("recv string = %s\n", recvbuf); } MPI_Finalize(); return 0; }
18.53125
74
0.644182
f3d813870a988dd013579379bc915c73940ea60f
35,443
h
C
LibWinRegUtil/LibWinRegUtil.h
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
5
2020-09-17T08:15:14.000Z
2021-06-17T08:35:51.000Z
LibWinRegUtil/LibWinRegUtil.h
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
null
null
null
LibWinRegUtil/LibWinRegUtil.h
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
4
2019-12-29T00:58:23.000Z
2022-01-27T12:58:36.000Z
#pragma once #include <string> #include <memory> #include <vector> #include <map> #include <locale> #include <codecvt> #include <Windows.h> namespace WinReg { enum class eHKey { eHkeyNotDefined = 0 , eHKeyClassesRoot = 1 , eHKeyCurrentConfig = 2 , eHKeyCurrentUser = 3 , eHKeyLocalMachine = 4 , eHKeyUsers = 5 }; enum class eRegAccessRights { eAccessKeyAllAccess = 0xF003F , eAccessKeyCreateSubKey = 0x0004 , eAccessKeyEnumerateSubKeys = 0x0008 , eAccessKeynotify = 0x0010 , eAccessKeyQueryValue = 0x0001 , eAccessKeyRead = 0x20019 , eAccessKeySetValue = 0x0002 , eAccessKeyWrite = 0x20006 }; enum class eRegView { eViewDefault = 0x0000 , eViewWow6432 = 0x0200 , eViewWow6464 = 0x0100 , eViewUndefined = 0x9999 }; enum class eRegValueKind { eValueKindUnknown = 0 , eValueKindString = 1 , eValueKindExpandedString = 2 , eValueKindBinary = 3 , eValueKindDword = 4 , eValueKindMultiString = 7 , eValueKindQWord = 11 }; enum class eRegKeyAccess : std::uint32_t { eKeyAllAccess = 0xF003F , eKeyCreateLink = 0x0020 , eKeyCreateSubKey = 0x0004 , eKeyEnumerateSubKeys = 0x0008 , eKeyExecute = 0x20019 , eKeyNotify = 0x0010 , eKeyQueryValue = 0x0001 , eKeyRead = 0x20019 , eKeySetValue = 0x0002 , eKeyWow6432Key = 0x0200 , eKeyWow6464Key = 0x0100 , eKeyWrite = 0x20006 }; namespace Utils { const int MAX_VALUE_NAME{ 16383 }; const int MAX_KEY_LENGTH{ 255 }; static inline std::string WStringToString(const std::wstring &wsVal) { return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(wsVal); } static inline void AssertIntNotEqual(const std::wstring &wsLocation, const std::wstring &swValName, const int iNotEqal, const int iTestVal) { if (iTestVal == iNotEqal) { std::wstring wsMsg(wsLocation); wsMsg += L": Parameter->"; wsMsg += swValName; wsMsg += L" cannot be "; wsMsg += std::to_wstring(iNotEqal); throw std::invalid_argument(WStringToString(wsMsg).c_str()); } } static inline HKEY enumHKeyToHKey(const int eHKeyVal) { { std::wstring sLocation(L"Utils::enumHKeyToHKey"); AssertIntNotEqual(sLocation, L"eHKeyVal", 0, eHKeyVal); switch (eHKeyVal) { case 1: return HKEY_CLASSES_ROOT; case 2: return HKEY_CURRENT_CONFIG; case 3: return HKEY_CURRENT_USER; case 4: return HKEY_LOCAL_MACHINE; case 5: return HKEY_USERS; } } } static inline std::wstring enumHKeyToName(const int eHKeyVal) { std::wstring sLocation(L"Utils::enumHKeyToHKey"); AssertIntNotEqual(sLocation, L"eHKeyVal", 0, eHKeyVal); switch (eHKeyVal) { case 1: return std::wstring{ L"HKEY_CLASSES_ROOT" }; case 2: return std::wstring{ L"HKEY_CURRENT_CONFIG" }; case 3: return std::wstring{ L"HKEY_CURRENT_USER" }; case 4: return std::wstring{ L"HKEY_LOCAL_MACHINE" }; case 5: return std::wstring{ L"HKEY_USERS" }; } } static inline void AssertHr(const std::wstring & wsLocation, const std::wstring & wsFunction, const HRESULT hr) { if (hr != S_OK) { LPSTR buffer = NULL; size_t size(::FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL , hr , MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) , (LPSTR)&buffer , 0 , NULL)); std::string sMsg(Utils::WStringToString(wsLocation)); sMsg += ": Function->"; sMsg += Utils::WStringToString(wsFunction); sMsg += " HRESULT->" + std::to_string(hr); sMsg += " "; sMsg += std::string(buffer); throw std::exception(sMsg.c_str()); } } template<typename T> static inline void AssertParamNotEqual(const std::wstring &wsLocation, const std::wstring &wsParamName, const T notEqualToVal, const T testVal) { if (notEqualToVal == testVal) { std::string sMsg(Utils::WStringToString(wsLocation)); sMsg += ": Parameter->"; sMsg += WStringToString(wsParamName); sMsg += " Invalid parameter value. Parameter value cannot be equal to its current value."; throw std::invalid_argument(sMsg.c_str()); } } static inline void ThrowUnknown(const std::wstring & wsLocation) { std::string sMsg(Utils::WStringToString(wsLocation)); sMsg += " Unknown exception"; throw std::exception(sMsg.c_str()); } static inline DWORD GetRegValueSize(const HKEY &regHKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const DWORD &dwFlags) { std::wstring wsLocation(L"Utils::GetRegValueSize"); DWORD dwDataSize{}; Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(regHKey, wsSubKey.c_str(), wsValueName.c_str(), dwFlags, nullptr, nullptr, &dwDataSize) ); return dwDataSize; } static inline std::wstring GetStringValue(const HKEY &regHkey, const std::wstring &wsSubKey, const std::wstring &wsValueName, DWORD &dwSize) { std::wstring wsLocation(L"Utils::GetStringValue"); std::wstring wsData; wsData.resize(dwSize / sizeof(wchar_t)); Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(regHkey, wsSubKey.c_str(), wsValueName.c_str(), RRF_RT_REG_SZ, nullptr, &wsData[0], &dwSize) ); DWORD dwDataSizeWChar{ dwSize / sizeof(wchar_t) }; --dwDataSizeWChar; wsData.resize(dwDataSizeWChar); return wsData; } static inline std::vector<std::wstring> GetMultiStringValue(const HKEY & regHKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, DWORD &dwSize) { std::wstring wsLocation(L"Utils::GetMultiStringValue"); std::vector<wchar_t> vwcData; vwcData.resize(dwSize / sizeof(wchar_t)); Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(regHKey, wsSubKey.c_str(), wsValueName.c_str(), RRF_RT_REG_MULTI_SZ, nullptr, &vwcData[0], &dwSize) ); vwcData.resize(dwSize / sizeof(wchar_t)); std::vector<std::wstring> vwsRet; const wchar_t* pwcCurrStringPtr{ &vwcData[0] }; while (*pwcCurrStringPtr != L'\0') { const size_t szCurrStringLength{ wcslen(pwcCurrStringPtr) }; vwsRet.push_back(std::wstring{ pwcCurrStringPtr, szCurrStringLength }); pwcCurrStringPtr += szCurrStringLength + 1; } return vwsRet; } static inline std::wstring GetExpandedStringValue(const HKEY &regHKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const bool bExpand, DWORD &dwSize) { std::wstring wsLocation(L"Utils::GetExpandedStringValue"); DWORD isExpanded{ (DWORD)(bExpand ? RRF_RT_REG_SZ : RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND) }; std::wstring wsData; wsData.resize(dwSize / sizeof(wchar_t)); Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(regHKey, wsSubKey.c_str(), wsValueName.c_str(), isExpanded, nullptr, &wsData[0], &dwSize) ); DWORD dwDataSizeWChar{ dwSize / sizeof(wchar_t) }; --dwDataSizeWChar; wsData.resize(dwDataSizeWChar); return wsData; } static inline DWORD GetDwordValue(const HKEY &regHKey, const std::wstring &wsSubKey, const std::wstring &wsValueName) { std::wstring wsLocation(L"Utils::GetDwordValue"); DWORD dwRet{}; DWORD dwDataSize{ sizeof(dwRet) }; Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(regHKey, wsSubKey.c_str(), wsValueName.c_str(), RRF_RT_REG_DWORD, nullptr, &dwRet, &dwDataSize) ); return dwRet; } static inline ULONGLONG GetQwordValue(const HKEY &regHKey, const std::wstring &wsSubKey, const std::wstring &wsValueName) { std::wstring wsLocation(L"Utils::GetQwordValue"); ULONGLONG dwRet{}; DWORD dwDataSize{ sizeof(dwRet) }; Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(regHKey, wsSubKey.c_str(), wsValueName.c_str(), RRF_RT_REG_QWORD, nullptr, &dwRet, &dwDataSize) ); return dwRet; } static inline std::vector<BYTE> GetBinaryValues(const HKEY &regHKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, DWORD &dwSize) { std::wstring wsLocation(L"Utils::GetBinaryValues"); std::vector<BYTE> vucData; vucData.resize(dwSize); Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(regHKey, wsSubKey.c_str(), wsValueName.c_str(), RRF_RT_REG_BINARY, nullptr, &vucData[0], &dwSize) ); vucData.resize(dwSize); return vucData; } static inline void SetStringValue(const HKEY &regKey, const std::wstring &wsValueName, const std::wstring &wsValueData) { std::wstring wsLocation(L"Utils::SetStringValue"); DWORD dwDataSize{ (wsValueData.size() + 1) * sizeof(wchar_t) }; Utils::AssertHr ( wsLocation , L"::RegSetValueEx" , ::RegSetValueExW(regKey, wsValueName.c_str(), 0, REG_SZ, (LPBYTE)(wsValueData.c_str()), dwDataSize) ); } static inline void SetExpandedStringValue(const HKEY &regKey, const std::wstring &wsValueName, const std::wstring &wsValueData) { std::wstring wsLocation(L"Utils::SetExpandedStringValue"); DWORD dwDataSize{ (wsValueData.size() + 1) * sizeof(wchar_t) }; Utils::AssertHr ( wsLocation , L"::RegSetValueEx" , ::RegSetValueExW(regKey, wsValueName.c_str(), 0, REG_EXPAND_SZ, (LPBYTE)(wsValueData.c_str()), dwDataSize) ); } static inline void SetMultiStringValue(const HKEY &regKey, const std::wstring &wsValueName, const std::vector<std::wstring> &vwsValueData) { std::wstring wsLocation(L"Utils::SetMultiStringValue"); std::vector<wchar_t> vwcBuffer; for (auto val : vwsValueData) { wchar_t const *buf = val.c_str(); vwcBuffer.insert(vwcBuffer.end(), &buf[0], &buf[val.length() + 1]); } wchar_t const *buf = L""; vwcBuffer.insert(vwcBuffer.end(), &buf[0], &buf[1]); DWORD dwDataSize{ vwcBuffer.size() * sizeof(wchar_t) }; Utils::AssertHr ( wsLocation , L"::RegSetValueEx" , ::RegSetValueEx(regKey, wsValueName.c_str(), 0, REG_MULTI_SZ, (LPBYTE)(&vwcBuffer[0]), dwDataSize) ); } static inline void SetBinaryValue(const HKEY &regKey, const std::wstring & wsValueName, const std::vector<BYTE>& vucValueData) { std::wstring wsLocation(L"Utils::SetBinaryValue"); DWORD dwDataSize{ vucValueData.size() * sizeof(BYTE) }; Utils::AssertHr ( wsLocation , L"::RegSetValueEx" , ::RegSetValueEx(regKey, wsValueName.c_str(), 0, REG_BINARY, (LPBYTE)(&vucValueData[0]), dwDataSize) ); } static inline void SetDwordValue(const HKEY &regKey, const std::wstring & wsValueName, const DWORD dwValueData) { std::wstring wsLocation(L"Utils::SetDwordValue"); DWORD dwDataSize{ sizeof(dwValueData) }; Utils::AssertHr ( wsLocation , L"::RegSetValueEx" , ::RegSetValueEx(regKey, wsValueName.c_str(), 0, REG_DWORD, (LPBYTE)&dwValueData, dwDataSize) ); } static inline void SetQwordValue(const HKEY &regKey, const std::wstring & wsValueName, const ULONGLONG qwValueData) { std::wstring wsLocation(L"Utils::SetQwordValue"); DWORD dwDataSize{ sizeof(qwValueData) }; Utils::AssertHr ( wsLocation , L"::RegSetValueEx" , ::RegSetValueEx(regKey, wsValueName.c_str(), 0, REG_QWORD, (LPBYTE)&qwValueData, dwDataSize) ); } static inline REGSAM eRegAccessRightsToRegSam(const int eRegAccessRightsVal) { switch (eRegAccessRightsVal) { case 0xF003F: return KEY_ALL_ACCESS; case 0x0004: return KEY_CREATE_SUB_KEY; case 0x0008: return KEY_ENUMERATE_SUB_KEYS; case 0x0010: return KEY_NOTIFY; case 0x0001: return KEY_QUERY_VALUE; case 0x20019: return KEY_READ; case 0x0002: return KEY_SET_VALUE; case 0x20006: return KEY_WRITE; } } } class CRegistryKey { public: CRegistryKey() = delete; inline CRegistryKey(const eHKey hKey) : mRegView(eRegView::eViewDefault) { std::wstring wsLocation(L"CRegistryKey::CRegistryKey"); try { int iHKey{ static_cast<int>(hKey) }; Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, iHKey); mEnumHKey = hKey; Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(Utils::enumHKeyToHKey(iHKey), NULL, 0, KEY_READ, &mHKEY) ); } catch (std::exception) { throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } CRegistryKey(CRegistryKey&&) = default; CRegistryKey& operator=(CRegistryKey&&) = default; inline virtual CRegistryKey::~CRegistryKey() { ::RegCloseKey(mHKEY); } inline std::wstring CRegistryKey::Name() { return std::wstring(Utils::enumHKeyToName(static_cast<int>(mEnumHKey)) + mwsName); } inline int CRegistryKey::SubKeyCount() { if (mbMustUpdate) UpdateProperties(); return mdwSubKeyCount; } inline int CRegistryKey::ValueCount() { if (mbMustUpdate) UpdateProperties(); return mdwValueCount; } inline eRegView CRegistryKey::View() { return mRegView; } inline CRegistryKey OpenSubKey(const std::wstring &wsSubKey, const eRegAccessRights enumAccessRights = eRegAccessRights::eAccessKeyRead) { return CRegistryKey(*this, wsSubKey, enumAccessRights); } inline CRegistryKey CreateSubKey(const std::wstring &wsSubKey, const eRegAccessRights enumAccessRights = eRegAccessRights::eAccessKeyRead) { mbMustUpdate = true; return CRegistryKey(*this, wsSubKey, enumAccessRights, true); } inline void DeleteSubKey(const std::wstring &wsSubKey) { std::wstring wsLocation{ L"CRegistryKey::DeleteSubkey" }; try { Utils::AssertHr ( wsLocation , L"::RegDeleteKey" , ::RegDeleteKey(mHKEY, wsSubKey.c_str()) ); mbMustUpdate = true; } catch (std::exception) { throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::vector<std::wstring> GetValueNames() { if (mbMustUpdate) UpdateProperties(); return mvwsValueNames; } inline std::vector<std::wstring> GetSubKeyNames() { if (mbMustUpdate) UpdateProperties(); return mvwsSubKeyNames; } inline eRegValueKind GetValueKind(const std::wstring &wsValueName) { if (mbMustUpdate) UpdateProperties(); return mmpValueKinds.at(wsValueName); } inline void Flush() { std::wstring wsLocation{ L"CRegistryKey::Flush" }; try { Utils::AssertHr ( wsLocation , L"::RegFlushKey" , ::RegFlushKey(mHKEY) ); } catch (std::exception) { throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::wstring GetStringValue(const std::wstring &wsValueName, const bool bDefaultOnError = false, const std::wstring &wsDefaultVal = L"") { std::wstring wsLocation{ L"CRegistryKey::GetStringValue" }; try { DWORD dwDataSize { Utils::GetRegValueSize(mHKEY, L"", wsValueName, RRF_RT_REG_SZ) }; return Utils::GetStringValue(mHKEY, L"", wsValueName, dwDataSize); } catch (std::exception) { if (bDefaultOnError) return wsDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::vector<std::wstring> GetMultiStringValue(const std::wstring &wsValueName, const bool bDefaultOnError = false) { std::wstring wsLocation{ L"CRegistryKe::GetMultiStringValue" }; try { DWORD dwDataSize { Utils::GetRegValueSize(mHKEY, L"", wsValueName, RRF_RT_REG_MULTI_SZ) }; return Utils::GetMultiStringValue(mHKEY, L"", wsValueName, dwDataSize); } catch (std::exception) { if (bDefaultOnError) return std::vector<std::wstring>{}; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::wstring GetExpandedStringValue(const std::wstring &wsValueName, const bool bExpand = false, const bool bDefaultOnError = false, const std::wstring &wsDefaultVal = L"") { std::wstring wsLocation{ L"CRegistryKey::GetExpandedStringValue" }; try { DWORD dwDataSize { Utils::GetRegValueSize ( mHKEY , L"" , wsValueName , (DWORD)(bExpand ? RRF_RT_REG_SZ : RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND) ) }; return Utils::GetExpandedStringValue(mHKEY, L"", wsValueName, bExpand, dwDataSize); } catch (std::exception) { if (bDefaultOnError) return wsDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline DWORD GetDwordValue(const std::wstring &wsValueName, const bool bDefaultOnError = false, const DWORD dwDefaultVal = 0) { std::wstring wsLocation{ L"CRegistryKey::GetDwordValue" }; try { return Utils::GetDwordValue(mHKEY, L"", wsValueName); } catch (std::exception) { if (bDefaultOnError) return dwDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline ULONGLONG GetQwordValue(const std::wstring &wsValueName, const bool bDefaultOnError = false, const ULONGLONG qwDefaultVal = 0) { std::wstring wsLocation{ L"CRegistryKey::GetQwordValue" }; try { return Utils::GetQwordValue(mHKEY, L"", wsValueName); } catch (std::exception) { if (bDefaultOnError) return qwDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::vector<BYTE> GetBinaryValue(const std::wstring &wsValueName, const bool bDefaultOnError = false) { std::wstring wsLocation{ L"CRegistryKey::GetBinaryValue" }; try { DWORD dwDataSize { Utils::GetRegValueSize(mHKEY, L"", wsValueName, RRF_RT_REG_BINARY) }; return Utils::GetBinaryValues(mHKEY, L"", wsValueName, dwDataSize); } catch (std::exception) { if (bDefaultOnError) return std::vector<BYTE>{}; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline void SetStringValue(const std::wstring &wsValueName, const std::wstring &wsVal) { std::wstring wsLocation{ L"CRegistryKey::SetStringValue" }; HKEY hRegHandle{}; try { Utils::SetStringValue(mHKEY, wsValueName, wsVal); mbMustUpdate = true; } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetMultiStringValue(const std::wstring &wsValueName, const std::vector<std::wstring> &vwsVal) { std::wstring wsLocation{ L"CRegistryKey::SetMultiStringValue" }; HKEY hRegHandle{}; try { Utils::SetMultiStringValue(mHKEY, wsValueName, vwsVal); mbMustUpdate = true; } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetExpandedStringValue(const std::wstring &wsValueName, const std::wstring &wsVal) { std::wstring wsLocation{ L"CRegistryKey::SetExpandedStringValue" }; HKEY hRegHandle{}; try { Utils::SetExpandedStringValue(mHKEY, wsValueName, wsVal); mbMustUpdate = true; } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetBinaryValue(const std::wstring &wsValueName, const std::vector<BYTE> &vucVal) { std::wstring wsLocation{ L"CRegistryKey::SetMultiStringValue" }; HKEY hRegHandle{}; try { Utils::SetBinaryValue(mHKEY, wsValueName, vucVal); mbMustUpdate = true; } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetDwordValue(const std::wstring &wsValueName, const DWORD dwVal) { std::wstring wsLocation{ L"CRegistryKey::SetDwordValue" }; HKEY hRegHandle{}; try { Utils::SetDwordValue(mHKEY, wsValueName, dwVal); mbMustUpdate = true; } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetQwordValue(const std::wstring &wsValueName, const ULONGLONG qwVal) { std::wstring wsLocation{ L"CRegistryKey::SetQwordValue" }; HKEY hRegHandle{}; try { Utils::SetQwordValue(mHKEY, wsValueName, qwVal); mbMustUpdate = true; } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void DeleteValue(const std::wstring &wsValueName) { std::wstring wsLocation{ L"CRegistryKey::DeleteValue" }; try { Utils::AssertHr ( wsLocation , L"::RegDeleteValue" , ::RegDeleteValue(mHKEY, wsValueName.c_str()) ); mbMustUpdate = true; } catch (std::exception) { throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } private: eHKey mEnumHKey{ eHKey::eHkeyNotDefined }; HKEY mHKEY{ nullptr }; std::wstring mwsName{ L"" }; DWORD mdwSubKeyCount{ 0 }; DWORD mdwValueCount{ 0 }; std::vector<std::wstring> mvwsValueNames; std::vector<std::wstring> mvwsSubKeyNames; std::map<std::wstring, eRegValueKind> mmpValueKinds; eRegView mRegView{ eRegView::eViewUndefined }; bool mbMustUpdate{ true }; eRegAccessRights mAccessRights{ eRegAccessRights::eAccessKeyRead }; inline CRegistryKey(const CRegistryKey &parentRegKey, const std::wstring &wsSubKey, const eRegAccessRights enumAccessRights = eRegAccessRights::eAccessKeyRead, const bool bCreate = false) : mEnumHKey(parentRegKey.mEnumHKey) , mwsName(wsSubKey.length() > 0 ? parentRegKey.mwsName + L"\\" + wsSubKey : L"") , mRegView(eRegView::eViewDefault) , mAccessRights(enumAccessRights) { std::wstring wsLocation(L"CRegistryKey::CRegistryKey"); try { if (bCreate) { Utils::AssertHr ( wsLocation , L"::RegCreateKeyEx" , ::RegCreateKeyEx(parentRegKey.mHKEY, wsSubKey.c_str(), 0, nullptr, REG_OPTION_NON_VOLATILE, Utils::eRegAccessRightsToRegSam(static_cast<int>(mAccessRights)), nullptr, &mHKEY, nullptr) ); } else { Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(parentRegKey.mHKEY, wsSubKey.c_str(), 0, Utils::eRegAccessRightsToRegSam(static_cast<int>(mAccessRights)), &mHKEY) ); } } catch (std::exception) { throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline void UpdateProperties() { std::wstring wsLocation(L"CRegistryKey::UpdateProperties"); try { Utils::AssertHr ( wsLocation , L"::RegQueryInfoKey" , ::RegQueryInfoKey(mHKEY, nullptr, nullptr, nullptr, &mdwSubKeyCount, nullptr, nullptr, &mdwValueCount, nullptr, nullptr, nullptr, nullptr) ); mvwsValueNames.clear(); mvwsValueNames.reserve(mdwValueCount); mmpValueKinds.clear(); if (mdwValueCount > 0) { for (DWORD dwCount = 0; dwCount < mdwValueCount; dwCount++) { std::wstring wsValueName; wsValueName.resize(Utils::MAX_VALUE_NAME); // function works with wide strings so no need to double size DWORD dwSize{ Utils::MAX_VALUE_NAME }; DWORD dwType{ 0 }; Utils::AssertHr ( wsLocation , L"::RegEnumValue" , ::RegEnumValue(mHKEY, dwCount, &wsValueName[0], &dwSize, nullptr, &dwType, nullptr, nullptr) ); wsValueName.resize(dwSize); //size not including string terminator, no need to decrease by one mvwsValueNames.emplace_back(wsValueName); mmpValueKinds.emplace(wsValueName, static_cast<eRegValueKind>(dwType)); } } mvwsSubKeyNames.clear(); mvwsSubKeyNames.reserve(mdwSubKeyCount); if (mdwSubKeyCount > 0) { for (DWORD dwCount = 0; dwCount < mdwSubKeyCount; dwCount++) { std::wstring wsSubKeyName; wsSubKeyName.resize(Utils::MAX_KEY_LENGTH); // function works with wide strings so no need to double size DWORD dwSize{ Utils::MAX_KEY_LENGTH }; Utils::AssertHr ( wsLocation , L"::RegEnumValue" , ::RegEnumKeyEx(mHKEY, dwCount, &wsSubKeyName[0], &dwSize, nullptr, nullptr, nullptr, nullptr) ); wsSubKeyName.resize(dwSize); //size not including string terminator, no need to decrease by one mvwsSubKeyNames.emplace_back(wsSubKeyName); } } mbMustUpdate = false; } catch (std::exception) { throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } }; namespace Registry { inline CRegistryKey ClassesRoot() { return CRegistryKey(eHKey::eHKeyClassesRoot); } inline CRegistryKey CurrentConfig() { return CRegistryKey(eHKey::eHKeyCurrentConfig); } inline CRegistryKey CurrentUser() { return CRegistryKey(eHKey::eHKeyCurrentUser); } inline CRegistryKey LocalMachine() { return CRegistryKey(eHKey::eHKeyLocalMachine); } inline CRegistryKey Users() { return CRegistryKey(eHKey::eHKeyUsers); } inline std::wstring GetStringValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const bool bDefaultOnError = false, const std::wstring &wsDefaultVal = L"") { std::wstring wsLocation{ L"Registry::GetStringValue" }; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); DWORD dwDataSize { Utils::GetRegValueSize(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName, RRF_RT_REG_SZ) }; return Utils::GetStringValue(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName, dwDataSize); } catch (std::exception) { if (bDefaultOnError) return wsDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::wstring GetExpandedStringValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const bool bExpand = false, const bool bDefaultOnError = false, const std::wstring &wsDefaultVal = L"") { std::wstring wsLocation{ L"Registry::GetExpandedStringValue" }; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); DWORD dwDataSize { Utils::GetRegValueSize ( Utils::enumHKeyToHKey(static_cast<int>(hKey)) , wsSubKey , wsValueName , (DWORD)(bExpand ? RRF_RT_REG_SZ : RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND) ) }; return Utils::GetExpandedStringValue(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName, bExpand, dwDataSize); } catch (std::exception) { if (bDefaultOnError) return wsDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline DWORD GetDwordValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const bool bDefaultOnError = false, const DWORD dwDefaultVal = 0) { std::wstring wsLocation{ L"Registry::GetDwordValue" }; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); return Utils::GetDwordValue(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName);; } catch (std::exception) { if (bDefaultOnError) return dwDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline ULONGLONG GetQwordValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const bool bDefaultOnError = false, const ULONGLONG qwDefaultVal = 0) { std::wstring wsLocation{ L"Registry::GetQwordValue" }; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); return Utils::GetQwordValue(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName); } catch (std::exception) { if (bDefaultOnError) return qwDefaultVal; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::vector<std::wstring> GetMultiStringValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const bool bDefaultOnError = false) { std::wstring wsLocation{ L"Registry::GetMultiStringValue" }; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); DWORD dwDataSize { Utils::GetRegValueSize(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName, RRF_RT_REG_MULTI_SZ) }; return Utils::GetMultiStringValue(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName, dwDataSize); } catch (std::exception) { if (bDefaultOnError) return std::vector<std::wstring>{}; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline std::vector<BYTE> GetBinaryValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const bool bDefaultOnError = false) { std::wstring wsLocation{ L"Registry::GetBinaryValue" }; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); DWORD dwDataSize { Utils::GetRegValueSize(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey, wsValueName, RRF_RT_REG_BINARY) }; std::vector<BYTE> vucData; vucData.resize(dwDataSize); Utils::AssertHr ( wsLocation , L"::RegGetValue" , ::RegGetValue(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey.c_str(), wsValueName.c_str(), RRF_RT_REG_BINARY, nullptr, &vucData[0], &dwDataSize) ); vucData.resize(dwDataSize); return vucData; } catch (std::exception) { if (bDefaultOnError) return std::vector<BYTE>{}; else throw; } catch (...) { Utils::ThrowUnknown(wsLocation); } } inline void SetStringValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const std::wstring &wsVal) { std::wstring wsLocation{ L"Registry::SetStringValue" }; HKEY hRegHandle{}; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey.c_str(), 0, KEY_SET_VALUE, &hRegHandle) ); Utils::SetStringValue(hRegHandle, wsValueName, wsVal); Utils::AssertHr ( wsLocation , L"::RegCloseKey" , ::RegCloseKey(hRegHandle) ); } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetExpandedStringValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const std::wstring &wsVal) { std::wstring wsLocation{ L"Registry::SetExpandedStringValue" }; HKEY hRegHandle{}; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey.c_str(), 0, KEY_SET_VALUE, &hRegHandle) ); Utils::SetExpandedStringValue(hRegHandle, wsValueName, wsVal); Utils::AssertHr ( wsLocation , L"::RegCloseKey" , ::RegCloseKey(hRegHandle) ); } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetDwordValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const DWORD dwVal) { std::wstring wsLocation{ L"Registry::SetDwordValue" }; HKEY hRegHandle{}; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey.c_str(), 0, KEY_SET_VALUE, &hRegHandle) ); Utils::SetDwordValue(hRegHandle, wsValueName, dwVal); Utils::AssertHr ( wsLocation , L"::RegCloseKey" , ::RegCloseKey(hRegHandle) ); } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetQwordValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const ULONGLONG qwVal) { std::wstring wsLocation{ L"Registry::SetQwordValue" }; HKEY hRegHandle{}; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey.c_str(), 0, KEY_SET_VALUE, &hRegHandle) ); Utils::SetQwordValue(hRegHandle, wsValueName, qwVal); Utils::AssertHr ( wsLocation , L"::RegCloseKey" , ::RegCloseKey(hRegHandle) ); } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetMultiStringValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const std::vector<std::wstring> &vwsVal) { std::wstring wsLocation{ L"Registry::SetMultiStringValue" }; HKEY hRegHandle{}; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey.c_str(), 0, KEY_SET_VALUE, &hRegHandle) ); Utils::SetMultiStringValue(hRegHandle, wsValueName, vwsVal); Utils::AssertHr ( wsLocation , L"::RegCloseKey" , ::RegCloseKey(hRegHandle) ); } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } inline void SetBinaryValue(const eHKey hKey, const std::wstring &wsSubKey, const std::wstring &wsValueName, const std::vector<BYTE> &vucVal) { std::wstring wsLocation{ L"Registry::SetMultiStringValue" }; HKEY hRegHandle{}; try { Utils::AssertParamNotEqual(wsLocation, L"hKey", 0, static_cast<int>(hKey)); Utils::AssertHr ( wsLocation , L"::RegOpenKeyEx" , ::RegOpenKeyEx(Utils::enumHKeyToHKey(static_cast<int>(hKey)), wsSubKey.c_str(), 0, KEY_SET_VALUE, &hRegHandle) ); Utils::SetBinaryValue(hRegHandle, wsValueName, vucVal); Utils::AssertHr ( wsLocation , L"::RegCloseKey" , ::RegCloseKey(hRegHandle) ); } catch (std::exception) { if (hRegHandle) ::RegCloseKey(hRegHandle); throw; } catch (...) { if (hRegHandle) ::RegCloseKey(hRegHandle); Utils::ThrowUnknown(wsLocation); } } } }
26.410581
229
0.666225
36e483164a331350b206c959e138a0d6f56a5d40
221
h
C
iOSBasicAlgorithmDemo/iOSBasicAlgorithmDemo/ViewController.h
qq455158249/iOSBasicAlgorithmDemo
8ac6e15cb8ad2ea4f022ca80aee9db54ab84be7a
[ "MIT" ]
2
2017-08-25T07:34:05.000Z
2017-10-30T15:33:12.000Z
iOSBasicAlgorithmDemo/iOSBasicAlgorithmDemo/ViewController.h
qq455158249/iOSBasicAlgorithmDemo
8ac6e15cb8ad2ea4f022ca80aee9db54ab84be7a
[ "MIT" ]
null
null
null
iOSBasicAlgorithmDemo/iOSBasicAlgorithmDemo/ViewController.h
qq455158249/iOSBasicAlgorithmDemo
8ac6e15cb8ad2ea4f022ca80aee9db54ab84be7a
[ "MIT" ]
null
null
null
// // ViewController.h // iOSBasicAlgorithmDemo // // Created by nf on 2017/8/2. // Copyright © 2017年 com.nf1000. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
13.8125
54
0.696833
82bec85bedc6778753f28e3d4e2dc898f35bd03c
5,102
c
C
libs/libc/unistd/lib_sleep.c
eenurkka/incubator-nuttx
5c3d6bba6d9ec5015896c3019cd2064696373210
[ "Apache-2.0" ]
1,006
2019-12-17T23:45:41.000Z
2022-03-31T19:42:44.000Z
libs/libc/unistd/lib_sleep.c
eenurkka/incubator-nuttx
5c3d6bba6d9ec5015896c3019cd2064696373210
[ "Apache-2.0" ]
2,661
2019-12-21T15:16:09.000Z
2022-03-31T22:30:04.000Z
libs/libc/unistd/lib_sleep.c
eenurkka/incubator-nuttx
5c3d6bba6d9ec5015896c3019cd2064696373210
[ "Apache-2.0" ]
613
2019-12-21T10:17:37.000Z
2022-03-28T09:42:20.000Z
/**************************************************************************** * libs/libc/unistd/lib_sleep.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <unistd.h> #include <signal.h> #include <nuttx/clock.h> #include <arch/irq.h> /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: sleep * * Description: * The sleep() function will cause the calling thread to be suspended from * execution until either the number of real-time seconds specified by the * argument 'seconds' has elapsed or a signal is delivered to the calling * thread and its action is to invoke a signal-catching function or to * terminate the process. The suspension time may be longer than requested * due to the scheduling of other activity by the system. * * If a SIGALRM signal is generated for the calling process during * execution of sleep() and if the SIGALRM signal is being ignored or * blocked from delivery, it is unspecified whether sleep() returns * when the SIGALRM signal is scheduled. If the signal is being blocked, it * is also unspecified whether it remains pending after sleep() returns or * it is discarded. * * If a SIGALRM signal is generated for the calling process during * execution of sleep(), except as a result of a prior call to alarm(), * and if the SIGALRM signal is not being ignored or blocked from delivery, * it is unspecified whether that signal has any effect other than causing * sleep() to return. * * If a signal-catching function interrupts sleep() and examines or changes * either the time a SIGALRM is scheduled to be generated, the action * associated with the SIGALRM signal, or whether the SIGALRM signal is * blocked from delivery, the results are unspecified. * * If a signal-catching function interrupts sleep() and calls siglongjmp() * or longjmp() to restore an environment saved prior to the sleep() call, * the action associated with the SIGALRM signal and the time at which a * SIGALRM signal is scheduled to be generated are unspecified. It is also * unspecified whether the SIGALRM signal is blocked, unless the process' * signal mask is restored as part of the environment. * * Implementations may place limitations on the granularity of timer * values. For each interval timer, if the requested timer value requires a * finer granularity than the implementation supports, the actual timer * value will be rounded up to the next supported value. * * Interactions between sleep() and any of setitimer(), ualarm() or sleep() * are unspecified. * * Input Parameters: * seconds - The number of seconds to sleep * * Returned Value: * If sleep() returns because the requested time has elapsed, the value * returned will be 0. If sleep() returns because of premature arousal due * to delivery of a signal, the return value will be the "unslept" amount * (the requested time minus the time actually slept) in seconds. * * Assumptions: * ****************************************************************************/ unsigned int sleep(unsigned int seconds) { struct timespec rqtp; struct timespec rmtp; unsigned int remaining = 0; int ret; /* Don't sleep if seconds == 0 */ if (seconds > 0) { /* Let clock_nanosleep() do all of the work. */ rqtp.tv_sec = seconds; rqtp.tv_nsec = 0; ret = clock_nanosleep(CLOCK_REALTIME, 0, &rqtp, &rmtp); /* clock_nanosleep() should only fail if it was interrupted by a * signal, but we treat all errors the same, */ if (ret < 0) { remaining = rmtp.tv_sec; if (remaining < seconds && rmtp.tv_nsec >= 500000000) { /* Round up */ remaining++; } } return remaining; } return 0; }
38.651515
78
0.616621
d6355e97d5ccd4a511e0ec5a233487c9d87e5b6a
7,736
c
C
contrib/gmp/mpz/and.c
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
432
2015-01-03T20:05:29.000Z
2022-03-24T16:39:09.000Z
contrib/gmp/mpz/and.c
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
145
2015-03-18T10:08:17.000Z
2022-03-31T01:27:08.000Z
contrib/gmp/mpz/and.c
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
114
2015-01-07T16:23:00.000Z
2022-03-23T18:26:01.000Z
/* mpz_and -- Logical and. Copyright 1991, 1993, 1994, 1996, 1997, 2000, 2001, 2003, 2005 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ #include "gmp.h" #include "gmp-impl.h" void mpz_and (mpz_ptr res, mpz_srcptr op1, mpz_srcptr op2) { mp_srcptr op1_ptr, op2_ptr; mp_size_t op1_size, op2_size; mp_ptr res_ptr; mp_size_t res_size; mp_size_t i; TMP_DECL; TMP_MARK; op1_size = SIZ(op1); op2_size = SIZ(op2); op1_ptr = PTR(op1); op2_ptr = PTR(op2); res_ptr = PTR(res); if (op1_size >= 0) { if (op2_size >= 0) { res_size = MIN (op1_size, op2_size); /* First loop finds the size of the result. */ for (i = res_size - 1; i >= 0; i--) if ((op1_ptr[i] & op2_ptr[i]) != 0) break; res_size = i + 1; /* Handle allocation, now then we know exactly how much space is needed for the result. */ if (UNLIKELY (ALLOC(res) < res_size)) { _mpz_realloc (res, res_size); res_ptr = PTR(res); /* Don't re-read op1_ptr and op2_ptr. Since res_size <= MIN(op1_size, op2_size), we will not reach this code when op1 is identical to res or op2 is identical to res. */ } SIZ(res) = res_size; if (LIKELY (res_size != 0)) mpn_and_n (res_ptr, op1_ptr, op2_ptr, res_size); return; } else /* op2_size < 0 */ { /* Fall through to the code at the end of the function. */ } } else { if (op2_size < 0) { mp_ptr opx; mp_limb_t cy; mp_size_t res_alloc; /* Both operands are negative, so will be the result. -((-OP1) & (-OP2)) = -(~(OP1 - 1) & ~(OP2 - 1)) = = ~(~(OP1 - 1) & ~(OP2 - 1)) + 1 = = ((OP1 - 1) | (OP2 - 1)) + 1 */ /* It might seem as we could end up with an (invalid) result with a leading zero-limb here when one of the operands is of the type 1,,0,,..,,.0. But some analysis shows that we surely would get carry into the zero-limb in this situation... */ op1_size = -op1_size; op2_size = -op2_size; res_alloc = 1 + MAX (op1_size, op2_size); opx = TMP_ALLOC_LIMBS (op1_size); mpn_sub_1 (opx, op1_ptr, op1_size, (mp_limb_t) 1); op1_ptr = opx; opx = TMP_ALLOC_LIMBS (op2_size); mpn_sub_1 (opx, op2_ptr, op2_size, (mp_limb_t) 1); op2_ptr = opx; if (ALLOC(res) < res_alloc) { _mpz_realloc (res, res_alloc); res_ptr = PTR(res); /* Don't re-read OP1_PTR and OP2_PTR. They point to temporary space--never to the space PTR(res) used to point to before reallocation. */ } if (op1_size >= op2_size) { MPN_COPY (res_ptr + op2_size, op1_ptr + op2_size, op1_size - op2_size); for (i = op2_size - 1; i >= 0; i--) res_ptr[i] = op1_ptr[i] | op2_ptr[i]; res_size = op1_size; } else { MPN_COPY (res_ptr + op1_size, op2_ptr + op1_size, op2_size - op1_size); for (i = op1_size - 1; i >= 0; i--) res_ptr[i] = op1_ptr[i] | op2_ptr[i]; res_size = op2_size; } cy = mpn_add_1 (res_ptr, res_ptr, res_size, (mp_limb_t) 1); if (cy) { res_ptr[res_size] = cy; res_size++; } SIZ(res) = -res_size; TMP_FREE; return; } else { /* We should compute -OP1 & OP2. Swap OP1 and OP2 and fall through to the code that handles OP1 & -OP2. */ MPZ_SRCPTR_SWAP (op1, op2); MPN_SRCPTR_SWAP (op1_ptr,op1_size, op2_ptr,op2_size); } } { #if ANDNEW mp_size_t op2_lim; mp_size_t count; /* OP2 must be negated as with infinite precision. Scan from the low end for a non-zero limb. The first non-zero limb is simply negated (two's complement). Any subsequent limbs are one's complemented. Of course, we don't need to handle more limbs than there are limbs in the other, positive operand as the result for those limbs is going to become zero anyway. */ /* Scan for the least significant non-zero OP2 limb, and zero the result meanwhile for those limb positions. (We will surely find a non-zero limb, so we can write the loop with one termination condition only.) */ for (i = 0; op2_ptr[i] == 0; i++) res_ptr[i] = 0; op2_lim = i; op2_size = -op2_size; if (op1_size <= op2_size) { /* The ones-extended OP2 is >= than the zero-extended OP1. RES_SIZE <= OP1_SIZE. Find the exact size. */ for (i = op1_size - 1; i > op2_lim; i--) if ((op1_ptr[i] & ~op2_ptr[i]) != 0) break; res_size = i + 1; for (i = res_size - 1; i > op2_lim; i--) res_ptr[i] = op1_ptr[i] & ~op2_ptr[i]; res_ptr[op2_lim] = op1_ptr[op2_lim] & -op2_ptr[op2_lim]; /* Yes, this *can* happen! */ MPN_NORMALIZE (res_ptr, res_size); } else { /* The ones-extended OP2 is < than the zero-extended OP1. RES_SIZE == OP1_SIZE, since OP1 is normalized. */ res_size = op1_size; MPN_COPY (res_ptr + op2_size, op1_ptr + op2_size, op1_size - op2_size); for (i = op2_size - 1; i > op2_lim; i--) res_ptr[i] = op1_ptr[i] & ~op2_ptr[i]; res_ptr[op2_lim] = op1_ptr[op2_lim] & -op2_ptr[op2_lim]; } SIZ(res) = res_size; #else /* OP1 is positive and zero-extended, OP2 is negative and ones-extended. The result will be positive. OP1 & -OP2 = OP1 & ~(OP2 - 1). */ mp_ptr opx; op2_size = -op2_size; opx = TMP_ALLOC_LIMBS (op2_size); mpn_sub_1 (opx, op2_ptr, op2_size, (mp_limb_t) 1); op2_ptr = opx; if (op1_size > op2_size) { /* The result has the same size as OP1, since OP1 is normalized and longer than the ones-extended OP2. */ res_size = op1_size; /* Handle allocation, now then we know exactly how much space is needed for the result. */ if (ALLOC(res) < res_size) { _mpz_realloc (res, res_size); res_ptr = PTR(res); /* Don't re-read OP1_PTR or OP2_PTR. Since res_size = op1_size, we will not reach this code when op1 is identical to res. OP2_PTR points to temporary space. */ } MPN_COPY (res_ptr + op2_size, op1_ptr + op2_size, res_size - op2_size); for (i = op2_size - 1; i >= 0; i--) res_ptr[i] = op1_ptr[i] & ~op2_ptr[i]; SIZ(res) = res_size; } else { /* Find out the exact result size. Ignore the high limbs of OP2, OP1 is zero-extended and would make the result zero. */ for (i = op1_size - 1; i >= 0; i--) if ((op1_ptr[i] & ~op2_ptr[i]) != 0) break; res_size = i + 1; /* Handle allocation, now then we know exactly how much space is needed for the result. */ if (ALLOC(res) < res_size) { _mpz_realloc (res, res_size); res_ptr = PTR(res); /* Don't re-read OP1_PTR. Since res_size <= op1_size, we will not reach this code when op1 is identical to res. */ /* Don't re-read OP2_PTR. It points to temporary space--never to the space PTR(res) used to point to before reallocation. */ } for (i = res_size - 1; i >= 0; i--) res_ptr[i] = op1_ptr[i] & ~op2_ptr[i]; SIZ(res) = res_size; } #endif } TMP_FREE; }
28.758364
77
0.61802
cf4ddd38c75417e5fbc5449994c3da689f521771
3,955
h
C
PhysX_3.4/Source/LowLevel/common/include/pipeline/PxcNpMemBlockPool.h
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
1
2019-12-09T16:03:55.000Z
2019-12-09T16:03:55.000Z
PhysX_3.4/Source/LowLevel/common/include/pipeline/PxcNpMemBlockPool.h
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
null
null
null
PhysX_3.4/Source/LowLevel/common/include/pipeline/PxcNpMemBlockPool.h
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
null
null
null
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PXC_NP_MEM_BLOCK_POOL_H #define PXC_NP_MEM_BLOCK_POOL_H #include "PxvConfig.h" #include "PsArray.h" #include "PxcScratchAllocator.h" namespace physx { struct PxcNpMemBlock { enum { SIZE = 16384 }; PxU8 data[SIZE]; }; typedef Ps::Array<PxcNpMemBlock*> PxcNpMemBlockArray; class PxcNpMemBlockPool { PX_NOCOPY(PxcNpMemBlockPool) public: PxcNpMemBlockPool(PxcScratchAllocator& allocator); ~PxcNpMemBlockPool(); void init(PxU32 initial16KDataBlocks, PxU32 maxBlocks); void flush(); void setBlockCount(PxU32 count); PxU32 getUsedBlockCount() const; PxU32 getMaxUsedBlockCount() const; PxU32 getPeakConstraintBlockCount() const; void releaseUnusedBlocks(); PxcNpMemBlock* acquireConstraintBlock(); PxcNpMemBlock* acquireConstraintBlock(PxcNpMemBlockArray& memBlocks); PxcNpMemBlock* acquireContactBlock(); PxcNpMemBlock* acquireFrictionBlock(); PxcNpMemBlock* acquireNpCacheBlock(); PxU8* acquireExceptionalConstraintMemory(PxU32 size); void acquireConstraintMemory(); void releaseConstraintMemory(); void releaseConstraintBlocks(PxcNpMemBlockArray& memBlocks); void releaseContacts(); void swapFrictionStreams(); void swapNpCacheStreams(); void flushUnused(); private: Ps::Mutex mLock; PxcNpMemBlockArray mConstraints; PxcNpMemBlockArray mContacts[2]; PxcNpMemBlockArray mFriction[2]; PxcNpMemBlockArray mNpCache[2]; PxcNpMemBlockArray mScratchBlocks; Ps::Array<PxU8*> mExceptionalConstraints; PxcNpMemBlockArray mUnused; PxU32 mNpCacheActiveStream; PxU32 mFrictionActiveStream; PxU32 mCCDCacheActiveStream; PxU32 mContactIndex; PxU32 mAllocatedBlocks; PxU32 mMaxBlocks; PxU32 mInitialBlocks; PxU32 mUsedBlocks; PxU32 mMaxUsedBlocks; PxcNpMemBlock* mScratchBlockAddr; PxU32 mNbScratchBlocks; PxcScratchAllocator& mScratchAllocator; PxU32 mPeakConstraintAllocations; PxU32 mConstraintAllocations; PxcNpMemBlock* acquire(PxcNpMemBlockArray& trackingArray, PxU32* allocationCount = NULL, PxU32* peakAllocationCount = NULL, bool isScratchAllocation = false); void release(PxcNpMemBlockArray& deadArray, PxU32* allocationCount = NULL); }; } #endif
32.958333
159
0.782807
a625d7ba9a830b6b3520ae4f4306b119cacd5ac7
11,481
c
C
games/sail/dr_1.c
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
432
2015-01-03T20:05:29.000Z
2022-03-24T16:39:09.000Z
games/sail/dr_1.c
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
8
2015-12-03T15:45:38.000Z
2020-12-25T15:42:08.000Z
games/sail/dr_1.c
lambdaxymox/DragonFlyBSD
6379cf2998a4a073c65b12d99e62988a375b4598
[ "BSD-3-Clause" ]
114
2015-01-07T16:23:00.000Z
2022-03-23T18:26:01.000Z
/* $NetBSD: dr_1.c,v 1.27 2009/03/14 22:52:52 dholland Exp $ */ /* * Copyright (c) 1983, 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. */ #include <sys/cdefs.h> #ifndef lint #if 0 static char sccsid[] = "@(#)dr_1.c 8.1 (Berkeley) 5/31/93"; #else __RCSID("$NetBSD: dr_1.c,v 1.27 2009/03/14 22:52:52 dholland Exp $"); #endif #endif /* not lint */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "extern.h" #include "driver.h" static int fightitout(struct ship *, struct ship *, int); void unfoul(void) { struct ship *sp; struct ship *to; int nat; int i; foreachship(sp) { if (sp->file->captain[0]) continue; nat = capship(sp)->nationality; foreachship(to) { if (nat != capship(to)->nationality && !is_toughmelee(sp, to, 0, 0)) continue; for (i = fouled2(sp, to); --i >= 0;) if (dieroll() <= 2) cleanfoul(sp, to, 0); } } } void boardcomp(void) { int crew[3]; struct ship *sp, *sq; foreachship(sp) { if (*sp->file->captain) continue; if (sp->file->dir == 0) continue; if (sp->file->struck || sp->file->captured != 0) continue; if (!snagged(sp)) continue; crew[0] = sp->specs->crew1 != 0; crew[1] = sp->specs->crew2 != 0; crew[2] = sp->specs->crew3 != 0; foreachship(sq) { if (!Xsnagged2(sp, sq)) continue; if (meleeing(sp, sq)) continue; if (!sq->file->dir || sp->nationality == capship(sq)->nationality) continue; switch (sp->specs->class - sq->specs->class) { case -3: case -4: case -5: if (crew[0]) { /* OBP */ sendbp(sp, sq, crew[0]*100, 0); crew[0] = 0; } else if (crew[1]) { /* OBP */ sendbp(sp, sq, crew[1]*10, 0); crew[1] = 0; } break; case -2: if (crew[0] || crew[1]) { /* OBP */ sendbp(sp, sq, crew[0]*100+crew[1]*10, 0); crew[0] = crew[1] = 0; } break; case -1: case 0: case 1: if (crew[0]) { /* OBP */ sendbp(sp, sq, crew[0]*100+crew[1]*10, 0); crew[0] = crew[1] = 0; } break; case 2: case 3: case 4: case 5: /* OBP */ sendbp(sp, sq, crew[0]*100+crew[1]*10+crew[2], 0); crew[0] = crew[1] = crew[2] = 0; break; } } } } static int fightitout(struct ship *from, struct ship *to, int key) { struct ship *fromcap, *tocap; int crewfrom[3], crewto[3], menfrom, mento; int pcto, pcfrom, fromstrength, strengthto, frominjured, toinjured; int topoints; int indx, totalfrom = 0, totalto = 0; int count; char message[60]; menfrom = mensent(from, to, crewfrom, &fromcap, &pcfrom, key); mento = mensent(to, from, crewto, &tocap, &pcto, 0); if (fromcap == NULL) fromcap = from; if (tocap == NULL) tocap = to; if (key) { if (!menfrom) { /* if crew surprised */ if (fromcap == from) menfrom = from->specs->crew1 + from->specs->crew2 + from->specs->crew3; else menfrom = from->file->pcrew; } else { menfrom *= 2; /* DBP's fight at an advantage */ } } fromstrength = menfrom * fromcap->specs->qual; strengthto = mento * tocap->specs->qual; for (count = 0; ((fromstrength < strengthto * 3 && strengthto < fromstrength * 3) || fromstrength == -1) && count < 4; count++) { indx = fromstrength/10; if (indx > 8) indx = 8; toinjured = MT[indx][2 - dieroll() / 3]; totalto += toinjured; indx = strengthto/10; if (indx > 8) indx = 8; frominjured = MT[indx][2 - dieroll() / 3]; totalfrom += frominjured; menfrom -= frominjured; mento -= toinjured; fromstrength = menfrom * fromcap->specs->qual; strengthto = mento * tocap->specs->qual; } if (fromstrength >= strengthto * 3 || count == 4) { unboard(to, from, 0); subtract(from, fromcap, totalfrom, crewfrom, pcfrom); subtract(to, tocap, totalto, crewto, pcto); makemsg(from, "boarders from %s repelled", to->shipname); snprintf(message, sizeof(message), "killed in melee: %d. %s: %d", totalto, from->shipname, totalfrom); send_signal(to, message); if (key) return 1; } else if (strengthto >= fromstrength * 3) { unboard(from, to, 0); subtract(from, fromcap, totalfrom, crewfrom, pcfrom); subtract(to, tocap, totalto, crewto, pcto); if (key) { if (fromcap != from) send_points(fromcap, fromcap->file->points - from->file->struck ? from->specs->pts : 2 * from->specs->pts); send_captured(from, to->file->index); topoints = 2 * from->specs->pts + to->file->points; if (from->file->struck) topoints -= from->specs->pts; send_points(to, topoints); mento = crewto[0] ? crewto[0] : crewto[1]; if (mento) { subtract(to, tocap, mento, crewto, pcto); subtract(from, to, - mento, crewfrom, 0); } snprintf(message, sizeof(message), "captured by the %s!", to->shipname); send_signal(from, message); snprintf(message, sizeof(message), "killed in melee: %d. %s: %d", totalto, from->shipname, totalfrom); send_signal(to, message); mento = 0; return 0; } } return 0; } void resolve(void) { int thwart; struct ship *sp, *sq; foreachship(sp) { if (sp->file->dir == 0) continue; for (sq = sp + 1; sq < ls; sq++) if (sq->file->dir && meleeing(sp, sq) && meleeing(sq, sp)) fightitout(sp, sq, 0); thwart = 2; foreachship(sq) { if (sq->file->dir && meleeing(sq, sp)) thwart = fightitout(sp, sq, 1); if (!thwart) break; } if (!thwart) { foreachship(sq) { if (sq->file->dir && meleeing(sq, sp)) unboard(sq, sp, 0); unboard(sp, sq, 0); } unboard(sp, sp, 1); } else if (thwart == 2) unboard(sp, sp, 1); } } void compcombat(void) { int n; struct ship *sp; struct ship *closest; int crew[3], men = 0, target, temp; int r, guns, ready, load, car; int indx, rakehim, sternrake; int shootat, hit; foreachship(sp) { if (sp->file->captain[0] || sp->file->dir == 0) continue; crew[0] = sp->specs->crew1; crew[1] = sp->specs->crew2; crew[2] = sp->specs->crew3; for (n = 0; n < 3; n++) { if (sp->file->OBP[n].turnsent) men += sp->file->OBP[n].mensent; } for (n = 0; n < 3; n++) { if (sp->file->DBP[n].turnsent) men += sp->file->DBP[n].mensent; } if (men) { crew[0] = men/100 ? 0 : crew[0] != 0; crew[1] = (men%100)/10 ? 0 : crew[1] != 0; crew[2] = men%10 ? 0 : crew[2] != 0; } for (r = 0; r < 2; r++) { if (!crew[2]) continue; if (sp->file->struck) continue; if (r) { ready = sp->file->readyR; guns = sp->specs->gunR; car = sp->specs->carR; } else { ready = sp->file->readyL; guns = sp->specs->gunL; car = sp->specs->carL; } if (!guns && !car) continue; if ((ready & R_LOADED) == 0) continue; closest = closestenemy(sp, r ? 'r' : 'l', 0); if (closest == NULL) continue; if (range(closest, sp) > range(sp, closestenemy(sp, r ? 'r' : 'l', 1))) continue; if (closest->file->struck) continue; target = range(sp, closest); if (target > 10) continue; if (!guns && target >= 3) continue; load = L_ROUND; if (target == 1 && sp->file->loadwith == L_GRAPE) load = L_GRAPE; if (target <= 3 && closest->file->FS) load = L_CHAIN; if (target == 1 && load != L_GRAPE) load = L_DOUBLE; if (load > L_CHAIN && target < 6) shootat = HULL; else shootat = RIGGING; rakehim = gunsbear(sp, closest) && !gunsbear(closest, sp); temp = portside(closest, sp, 1) - closest->file->dir + 1; if (temp < 1) temp += 8; if (temp > 8) temp -= 8; sternrake = temp > 4 && temp < 6; indx = guns; if (target < 3) indx += car; indx = (indx - 1) / 3; indx = indx > 8 ? 8 : indx; if (!rakehim) hit = HDT[indx][target-1]; else hit = HDTrake[indx][target-1]; if (rakehim && sternrake) hit++; hit += QUAL[indx][capship(sp)->specs->qual - 1]; for (n = 0; n < 3 && sp->file->captured == 0; n++) { if (!crew[n]) { if (indx <= 5) hit--; else hit -= 2; } } if (ready & R_INITIAL) { if (!r) sp->file->readyL &= ~R_INITIAL; else sp->file->readyR &= ~R_INITIAL; if (indx <= 3) hit++; else hit += 2; } if (sp->file->captured != 0) { if (indx <= 1) hit--; else hit -= 2; } hit += AMMO[indx][load - 1]; temp = sp->specs->class; if ((temp >= 5 || temp == 1) && windspeed == 5) hit--; if (windspeed == 6 && temp == 4) hit -= 2; if (windspeed == 6 && temp <= 3) hit--; if (hit >= 0) { if (load != L_GRAPE) hit = hit > 10 ? 10 : hit; table(sp, closest, shootat, load, hit, dieroll()); } } } } int next(void) { if (++turn % 55 == 0) { if (alive) alive = 0; else people = 0; } if (people <= 0 || windspeed == 7) { struct ship *s; struct ship *bestship = NULL; float net, best = 0.0; foreachship(s) { if (*s->file->captain) continue; net = (float)s->file->points / s->specs->pts; if (net > best) { best = net; bestship = s; } } if (best > 0.0 && bestship) { char *tp = getenv("WOTD"); const char *p; if (tp == NULL) p = "Driver"; else { *tp = toupper((unsigned char)*tp); p = tp; } strlcpy(bestship->file->captain, p, sizeof bestship->file->captain); logger(bestship); } return -1; } send_turn(turn); if (turn % 7 == 0 && (dieroll() >= cc->windchange || !windspeed)) { switch (dieroll()) { case 1: winddir = 1; break; case 2: break; case 3: winddir++; break; case 4: winddir--; break; case 5: winddir += 2; break; case 6: winddir -= 2; break; } if (winddir > 8) winddir -= 8; if (winddir < 1) winddir += 8; if (windspeed) switch (dieroll()) { case 1: case 2: windspeed--; break; case 5: case 6: windspeed++; break; } else windspeed++; send_wind( winddir, windspeed); } return 0; }
23.869023
77
0.576082
340372007a77b0faa61f027424b843b74afea4f3
9,155
h
C
paddle/fluid/platform/cuda_primitives.h
OuyangChao/Paddle
cac9635a6733ffbbd816b33e21c3054e0cd81ab1
[ "Apache-2.0" ]
1
2020-12-21T09:01:24.000Z
2020-12-21T09:01:24.000Z
paddle/fluid/platform/cuda_primitives.h
OuyangChao/Paddle
cac9635a6733ffbbd816b33e21c3054e0cd81ab1
[ "Apache-2.0" ]
1
2021-03-14T15:24:46.000Z
2021-03-14T15:24:46.000Z
paddle/fluid/platform/cuda_primitives.h
OuyangChao/Paddle
cac9635a6733ffbbd816b33e21c3054e0cd81ab1
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2016 PaddlePaddle 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. */ #pragma once #ifdef PADDLE_WITH_CUDA #include <cuda.h> #endif #ifdef PADDLE_WITH_HIP #include <hip/hip_runtime.h> #endif #include <stdio.h> #include "paddle/fluid/platform/complex128.h" #include "paddle/fluid/platform/complex64.h" #include "paddle/fluid/platform/float16.h" namespace paddle { namespace platform { #define CUDA_ATOMIC_WRAPPER(op, T) \ __device__ __forceinline__ T CudaAtomic##op(T *address, const T val) #define USE_CUDA_ATOMIC(op, T) \ CUDA_ATOMIC_WRAPPER(op, T) { return atomic##op(address, val); } // Default thread count per block(or block size). // TODO(typhoonzero): need to benchmark against setting this value // to 1024. constexpr int PADDLE_CUDA_NUM_THREADS = 512; // For atomicAdd. USE_CUDA_ATOMIC(Add, float); USE_CUDA_ATOMIC(Add, int); USE_CUDA_ATOMIC(Add, unsigned int); // CUDA API uses unsigned long long int, we cannot use uint64_t here. // It because unsigned long long int is not necessarily uint64_t USE_CUDA_ATOMIC(Add, unsigned long long int); // NOLINT CUDA_ATOMIC_WRAPPER(Add, int64_t) { // Here, we check long long int must be int64_t. static_assert(sizeof(int64_t) == sizeof(long long int), // NOLINT "long long should be int64"); return CudaAtomicAdd( reinterpret_cast<unsigned long long int *>(address), // NOLINT static_cast<unsigned long long int>(val)); // NOLINT } #if defined(__HIPCC__) || (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 600) USE_CUDA_ATOMIC(Add, double); #else CUDA_ATOMIC_WRAPPER(Add, double) { unsigned long long int *address_as_ull = // NOLINT reinterpret_cast<unsigned long long int *>(address); // NOLINT unsigned long long int old = *address_as_ull, assumed; // NOLINT do { assumed = old; old = atomicCAS(address_as_ull, assumed, __double_as_longlong(val + __longlong_as_double(assumed))); // Note: uses integer comparison to avoid hang in case of NaN } while (assumed != old); return __longlong_as_double(old); } #endif #ifdef PADDLE_CUDA_FP16 // NOTE(dzhwinter): cuda do not have atomicCAS for half. // Just use the half address as a unsigned value address and // do the atomicCAS. According to the value store at high 16 bits // or low 16 bits, then do a different sum and CAS. // Given most warp-threads will failed on the atomicCAS, so this // implemented should be avoided in high concurrency. It's will be // slower than the way convert value into 32bits and do a full atomicCAS. // convert the value into float and do the add arithmetic. // then store the result into a uint32. inline static __device__ uint32_t add_to_low_half(uint32_t val, float x) { float16 low_half; // the float16 in lower 16bits low_half.x = static_cast<uint16_t>(val & 0xFFFFu); low_half = static_cast<float16>(static_cast<float>(low_half) + x); return (val & 0xFFFF0000u) | low_half.x; } inline static __device__ uint32_t add_to_high_half(uint32_t val, float x) { float16 high_half; // the float16 in higher 16bits high_half.x = static_cast<uint16_t>(val >> 16); high_half = static_cast<float16>(static_cast<float>(high_half) + x); return (val & 0xFFFFu) | (static_cast<uint32_t>(high_half.x) << 16); } CUDA_ATOMIC_WRAPPER(Add, float16) { // concrete packed float16 value may exsits in lower or higher 16bits // of the 32bits address. uint32_t *address_as_ui = reinterpret_cast<uint32_t *>( reinterpret_cast<char *>(address) - (reinterpret_cast<uintptr_t>(address) & 0x02)); float val_f = static_cast<float>(val); uint32_t old = *address_as_ui; uint32_t sum; uint32_t newval; uint32_t assumed; if (((uintptr_t)address & 0x02) == 0) { // the float16 value stay at lower 16 bits of the address. do { assumed = old; old = atomicCAS(address_as_ui, assumed, add_to_low_half(assumed, val_f)); } while (old != assumed); float16 ret; ret.x = old & 0xFFFFu; return ret; } else { // the float16 value stay at higher 16 bits of the address. do { assumed = old; old = atomicCAS(address_as_ui, assumed, add_to_high_half(assumed, val_f)); } while (old != assumed); float16 ret; ret.x = old >> 16; return ret; } } #endif CUDA_ATOMIC_WRAPPER(Add, complex64) { float *real = reinterpret_cast<float *>(address); float *imag = real + 1; return complex64(CudaAtomicAdd(real, val.real), CudaAtomicAdd(imag, val.imag)); } CUDA_ATOMIC_WRAPPER(Add, complex128) { double *real = reinterpret_cast<double *>(address); double *imag = real + 1; return complex128(CudaAtomicAdd(real, val.real), CudaAtomicAdd(imag, val.imag)); } // For atomicMax USE_CUDA_ATOMIC(Max, int); USE_CUDA_ATOMIC(Max, unsigned int); // CUDA API uses unsigned long long int, we cannot use uint64_t here. // It because unsigned long long int is not necessarily uint64_t #if defined(__HIPCC__) || (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 350) USE_CUDA_ATOMIC(Max, unsigned long long int); // NOLINT #else CUDA_ATOMIC_WRAPPER(Max, unsigned long long int) { // NOLINT if (*address >= val) { return *address; } unsigned long long int old = *address, assumed; // NOLINT do { assumed = old; if (assumed >= val) { break; } old = atomicCAS(address, assumed, val); } while (assumed != old); } #endif CUDA_ATOMIC_WRAPPER(Max, int64_t) { // Here, we check long long int must be int64_t. static_assert(sizeof(int64_t) == sizeof(long long int), // NOLINT "long long should be int64"); return CudaAtomicMax( reinterpret_cast<unsigned long long int *>(address), // NOLINT static_cast<unsigned long long int>(val)); // NOLINT } CUDA_ATOMIC_WRAPPER(Max, float) { if (*address >= val) { return *address; } int *const address_as_i = reinterpret_cast<int *>(address); int old = *address_as_i, assumed; do { assumed = old; if (__int_as_float(assumed) >= val) { break; } old = atomicCAS(address_as_i, assumed, __float_as_int(val)); } while (assumed != old); } CUDA_ATOMIC_WRAPPER(Max, double) { if (*address >= val) { return *address; } unsigned long long int *const address_as_ull = // NOLINT reinterpret_cast<unsigned long long int *>(address); // NOLINT unsigned long long int old = *address_as_ull, assumed; // NOLINT do { assumed = old; if (__longlong_as_double(assumed) >= val) { break; } old = atomicCAS(address_as_ull, assumed, __double_as_longlong(val)); } while (assumed != old); } // For atomicMin USE_CUDA_ATOMIC(Min, int); USE_CUDA_ATOMIC(Min, unsigned int); // CUDA API uses unsigned long long int, we cannot use uint64_t here. // It because unsigned long long int is not necessarily uint64_t #if defined(__HIPCC__) || (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 350) USE_CUDA_ATOMIC(Min, unsigned long long int); // NOLINT #else CUDA_ATOMIC_WRAPPER(Min, unsigned long long int) { // NOLINT if (*address <= val) { return *address; } unsigned long long int old = *address, assumed; // NOLINT do { assumed = old; if (assumed <= val) { break; } old = atomicCAS(address, assumed, val); } while (assumed != old); } #endif CUDA_ATOMIC_WRAPPER(Min, int64_t) { // Here, we check long long int must be int64_t. static_assert(sizeof(int64_t) == sizeof(long long int), // NOLINT "long long should be int64"); return CudaAtomicMin( reinterpret_cast<unsigned long long int *>(address), // NOLINT static_cast<unsigned long long int>(val)); // NOLINT } CUDA_ATOMIC_WRAPPER(Min, float) { if (*address <= val) { return *address; } int *const address_as_i = reinterpret_cast<int *>(address); int old = *address_as_i, assumed; do { assumed = old; if (__int_as_float(assumed) <= val) { break; } old = atomicCAS(address_as_i, assumed, __float_as_int(val)); } while (assumed != old); } CUDA_ATOMIC_WRAPPER(Min, double) { if (*address <= val) { return *address; } unsigned long long int *const address_as_ull = // NOLINT reinterpret_cast<unsigned long long int *>(address); // NOLINT unsigned long long int old = *address_as_ull, assumed; // NOLINT do { assumed = old; if (__longlong_as_double(assumed) <= val) { break; } old = atomicCAS(address_as_ull, assumed, __double_as_longlong(val)); } while (assumed != old); } } // namespace platform } // namespace paddle
30.721477
80
0.684435
a158384d2ec6298124605b6a28d2214811380232
7,435
c
C
shell/osshell/accesory/packager/register.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/osshell/accesory/packager/register.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/osshell/accesory/packager/register.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/* register.c - Handles the Win 3.1 registration library. * * Created by Microsoft Corporation. */ #include "packager.h" TCHAR gszAppName[] = "packager.exe"; /* RegInit() - Prepare the registration database for calls. */ VOID RegInit( VOID ) { CHAR sz[CBMESSAGEMAX]; CHAR szVerb[CBMESSAGEMAX]; DWORD dwBytes = CBMESSAGEMAX; static TCHAR szAppClassID[] = TEXT("{0003000C-0000-0000-C000-000000000046}"); // If the server is not in the registration database, add it if (RegQueryValue(HKEY_CLASSES_ROOT, gszAppClassName, sz, &dwBytes)) { HKEY hkey; if (RegOpenKey(HKEY_CLASSES_ROOT, NULL, &hkey)) return; // Add the server name string LoadString(ghInst, IDS_FILTER, sz, CBMESSAGEMAX); RegSetValue(HKEY_CLASSES_ROOT, gszAppClassName, REG_SZ, sz, lstrlen(sz) + 1); // Add the server execute string (don't forget the terminating zero // on "packgr32.exe") StringCchCopy(sz, ARRAYSIZE(sz), gszAppClassName); StringCchCat(sz, ARRAYSIZE(sz), "\\protocol\\StdFileEditing\\server"); RegSetValue(HKEY_CLASSES_ROOT, sz, REG_SZ, gszAppName, (lstrlen(gszAppName) + 1)); // Primary verb StringCchCopy(sz, ARRAYSIZE(sz), gszAppClassName); StringCchCat(sz, ARRAYSIZE(sz), "\\protocol\\StdFileEditing\\verb\\0"); LoadString(ghInst, IDS_PRIMARY_VERB, szVerb, CBMESSAGEMAX); RegSetValue(HKEY_CLASSES_ROOT, sz, REG_SZ, szVerb, sizeof(szVerb)); // Secondary verb StringCchCopy(sz, ARRAYSIZE(sz), gszAppClassName); StringCchCat(sz, ARRAYSIZE(sz), "\\protocol\\StdFileEditing\\verb\\1"); LoadString(ghInst, IDS_SECONDARY_VERB, szVerb, CBMESSAGEMAX); RegSetValue(HKEY_CLASSES_ROOT, sz, REG_SZ, szVerb, sizeof(szVerb)); // CLSID StringCchCopy(sz, ARRAYSIZE(sz), gszAppClassName); StringCchCat(sz, ARRAYSIZE(sz), "\\CLSID"); RegSetValue(HKEY_CLASSES_ROOT, sz, REG_SZ, szAppClassID, sizeof(szAppClassID)); RegCloseKey(hkey); } // If the CLSID is not in the registration database, add it dwBytes = CBMESSAGEMAX; StringCchCopy(sz, ARRAYSIZE(sz), "CLSID\\"); StringCchCat(sz, ARRAYSIZE(sz), szAppClassID); if (RegQueryValue(HKEY_CLASSES_ROOT, sz, szVerb, &dwBytes)) { HKEY hkey; if (RegOpenKey(HKEY_CLASSES_ROOT, "CLSID", &hkey)) return; // Add the CLSID name string RegSetValue(hkey, szAppClassID, REG_SZ, gszAppClassName, lstrlen(gszAppClassName) + 1); // Add the OLE class StringCchCopy(sz, ARRAYSIZE(sz), szAppClassID); StringCchCat(sz, ARRAYSIZE(sz), "\\Ole1Class"); RegSetValue(hkey, sz, REG_SZ, gszAppClassName, lstrlen(gszAppClassName) + 1); // Add the prog id StringCchCopy(sz, ARRAYSIZE(sz), szAppClassID); StringCchCat(sz, ARRAYSIZE(sz), "\\ProgID"); RegSetValue(hkey, sz, REG_SZ, gszAppClassName, lstrlen(gszAppClassName) + 1); RegCloseKey(hkey); } } /* RegGetClassId() - Retrieves the string name of a class. * * Note: Classes are guaranteed to be in ASCII, but should * not be used directly as a rule because they might * be meaningless if running non-English Windows. */ VOID RegGetClassId( LPSTR lpstrName, DWORD nameBufferSize, LPSTR lpstrClass ) { DWORD dwSize = KEYNAMESIZE; CHAR szName[KEYNAMESIZE]; if (!RegQueryValue(HKEY_CLASSES_ROOT, lpstrClass, szName, &dwSize)) { StringCchCopy(lpstrName, nameBufferSize, szName); // potential overrun fixed } else StringCchCopy(lpstrName, nameBufferSize, lpstrClass); } /* RegMakeFilterSpec() - Retrieves class-associated default extensions. * * This function returns a filter spec, to be used in the "Change Link" * standard dialog box, which contains all the default extensions which * are associated with the given class name. Again, the class names are * guaranteed to be in ASCII. * * Returns: The index nFilterIndex stating which filter item matches the * extension, or 0 if none is found. */ INT RegMakeFilterSpec( LPSTR lpstrClass, LPSTR lpstrExt, LPSTR lpstrFilterSpec ) { DWORD dwSize; CHAR szClass[KEYNAMESIZE]; CHAR szName[KEYNAMESIZE]; CHAR szString[KEYNAMESIZE]; UINT i; INT idWhich = 0; INT idFilterIndex = 0; LPSTR pMaxStr = lpstrFilterSpec + 4 * MAX_PATH; // Per caller size for (i = 0; !RegEnumKey(HKEY_CLASSES_ROOT, i++, szName, KEYNAMESIZE);) { dwSize = KEYNAMESIZE; if (*szName == '.' /* Default Extension... */ /* ... so, get the class name */ && !RegQueryValue(HKEY_CLASSES_ROOT, szName, szClass, &dwSize) /* ... and if the class name matches (null class is wildcard) */ && (!lpstrClass || !lstrcmpi(lpstrClass, szClass))) { /* ... get the class name string */ dwSize = KEYNAMESIZE; if(!RegQueryValue(HKEY_CLASSES_ROOT, szClass, szString, &dwSize)) { idWhich++; /* Which item of the combo box is it? */ // If the extension matches, save the filter index if (lpstrExt && !lstrcmpi(lpstrExt, szName)) idFilterIndex = idWhich; // // Copy over "<Class Name String> (*<Default Extension>)" // e.g. "Server Picture (*.PIC)" // // because lpstrFilterSpec changes, we need to check all the concats now if(lpstrFilterSpec + (lstrlen(szString) + lstrlen(" (*") + lstrlen(szName) + lstrlen(")") + lstrlen("*") + lstrlen(szName) + 1) >= pMaxStr) { break; } lstrcpy(lpstrFilterSpec, szString); lstrcat(lpstrFilterSpec, " (*"); lstrcat(lpstrFilterSpec, szName); lstrcat(lpstrFilterSpec, ")"); lpstrFilterSpec += lstrlen(lpstrFilterSpec) + 1; // Copy over "*<Default Extension>" (e.g. "*.PIC") lstrcpy(lpstrFilterSpec, "*"); lstrcat(lpstrFilterSpec, szName); lpstrFilterSpec += lstrlen(lpstrFilterSpec) + 1; } } } // Add another NULL at the end of the spec *lpstrFilterSpec = 0; return idFilterIndex; } VOID RegGetExeName( LPSTR lpstrExe, LPSTR lpstrClass, DWORD dwBytes ) { // Add the server execute string CHAR szServer[KEYNAMESIZE]; if(SUCCEEDED(StringCchCopy(szServer, ARRAYSIZE(szServer), lpstrClass))) { if(SUCCEEDED(StringCchCat(szServer, ARRAYSIZE(szServer), "\\protocol\\StdFileEditing\\server"))) { RegQueryValue(HKEY_CLASSES_ROOT, szServer, lpstrExe, &dwBytes); } else { *lpstrExe = 0; } } else { *lpstrClass = 0; *lpstrExe = 0; } }
32.186147
105
0.579422
2ec70c9fe4c0ab3d70a236fc1a6dd271f19ad1cd
3,525
h
C
external/Angle/Project/src/libEGL/Surface.h
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
external/Angle/Project/src/libEGL/Surface.h
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
external/Angle/Project/src/libEGL/Surface.h
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Surface.h: Defines the egl::Surface class, representing a drawing surface // such as the client area of a window, including any back buffers. // Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3. #ifndef LIBEGL_SURFACE_H_ #define LIBEGL_SURFACE_H_ #define EGLAPI #include <EGL/egl.h> #include "common/angleutils.h" namespace gl { class Texture2D; } namespace rx { class Renderer; class SwapChain; } namespace egl { class Display; class Config; class Surface { public: Surface(Display *display, const egl::Config *config, EGLNativeWindowType window, EGLint postSubBufferSupported); Surface(Display *display, const egl::Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureTarget); ~Surface(); bool initialize(); void release(); bool resetSwapChain(); EGLNativeWindowType getWindowHandle(); bool swap(); bool postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height); virtual EGLint getWidth() const; virtual EGLint getHeight() const; virtual EGLint isPostSubBufferSupported() const; virtual rx::SwapChain *getSwapChain() const; void setSwapInterval(EGLint interval); bool checkForOutOfDateSwapChain(); // Returns true if swapchain changed due to resize or interval update virtual EGLenum getTextureFormat() const; virtual EGLenum getTextureTarget() const; virtual EGLenum getFormat() const; virtual void setBoundTexture(gl::Texture2D *texture); virtual gl::Texture2D *getBoundTexture() const; private: DISALLOW_COPY_AND_ASSIGN(Surface); Display *const mDisplay; rx::Renderer *mRenderer; HANDLE mShareHandle; rx::SwapChain *mSwapChain; void subclassWindow(); void unsubclassWindow(); bool resizeSwapChain(int backbufferWidth, int backbufferHeight); bool resetSwapChain(int backbufferWidth, int backbufferHeight); bool swapRect(EGLint x, EGLint y, EGLint width, EGLint height); EGLNativeWindowType mWindow; bool mWindowSubclassed; // Indicates whether we successfully subclassed mWindow for WM_RESIZE hooking const egl::Config *mConfig; // EGL config surface was created with EGLint mHeight; // Height of surface EGLint mWidth; // Width of surface // EGLint horizontalResolution; // Horizontal dot pitch // EGLint verticalResolution; // Vertical dot pitch // EGLBoolean largestPBuffer; // If true, create largest pbuffer possible // EGLBoolean mipmapTexture; // True if texture has mipmaps // EGLint mipmapLevel; // Mipmap level to render to // EGLenum multisampleResolve; // Multisample resolve behavior EGLint mPixelAspectRatio; // Display aspect ratio EGLenum mRenderBuffer; // Render buffer EGLenum mSwapBehavior; // Buffer swap behavior EGLenum mTextureFormat; // Format of texture: RGB, RGBA, or no texture EGLenum mTextureTarget; // Type of texture: 2D or no texture // EGLenum vgAlphaFormat; // Alpha format for OpenVG // EGLenum vgColorSpace; // Color space for OpenVG EGLint mSwapInterval; EGLint mPostSubBufferSupported; bool mSwapIntervalDirty; gl::Texture2D *mTexture; }; } #endif // LIBEGL_SURFACE_H_
31.473214
152
0.71461
2c084098dcece635d0acee7abdb4f426a442e52d
292
h
C
Example/TJKitManager/TJZAppDelegate.h
Jasonmin/TJKitManager
e20845a73ef1fe2ac27d1d78db47acb0007a1006
[ "MIT" ]
null
null
null
Example/TJKitManager/TJZAppDelegate.h
Jasonmin/TJKitManager
e20845a73ef1fe2ac27d1d78db47acb0007a1006
[ "MIT" ]
null
null
null
Example/TJKitManager/TJZAppDelegate.h
Jasonmin/TJKitManager
e20845a73ef1fe2ac27d1d78db47acb0007a1006
[ "MIT" ]
null
null
null
// // TJZAppDelegate.h // TJKitManager // // Created by 313410158@qq.com on 10/25/2019. // Copyright (c) 2019 313410158@qq.com. All rights reserved. // @import UIKit; @interface TJZAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
18.25
63
0.722603
087f571a75ad3a549911ad8a5f811cc87b4c1279
760
h
C
libc/nt/struct/consolescreenbufferinfoex.h
waldyrious/cosmopolitan
3e17c7b20f9c6e8695f9a12ef67e42f98cec7cca
[ "0BSD" ]
2
2021-02-13T19:26:06.000Z
2021-03-03T12:28:34.000Z
libc/nt/struct/consolescreenbufferinfoex.h
waldyrious/cosmopolitan
3e17c7b20f9c6e8695f9a12ef67e42f98cec7cca
[ "0BSD" ]
null
null
null
libc/nt/struct/consolescreenbufferinfoex.h
waldyrious/cosmopolitan
3e17c7b20f9c6e8695f9a12ef67e42f98cec7cca
[ "0BSD" ]
null
null
null
#ifndef COSMOPOLITAN_LIBC_NT_STRUCT_CONSOLESCREENBUFFERINFOEX_H_ #define COSMOPOLITAN_LIBC_NT_STRUCT_CONSOLESCREENBUFFERINFOEX_H_ #include "libc/nt/struct/coord.h" #include "libc/nt/struct/smallrect.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) struct NtConsoleScreenBufferInfoEx { uint32_t cbSize; /* sizeof(struct NtConsoleScreenBufferInfoEx) */ struct NtCoord dwSize; struct NtCoord dwCursorPosition; uint16_t wAttributes; /* kNt{Foreground,Background}... */ struct NtSmallRect srWindow; struct NtCoord dwMaximumWindowSize; uint16_t wPopupAttributes; bool32 bFullscreenSupported; uint32_t ColorTable[16]; /* 0x00BBGGRR */ }; #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_LIBC_NT_STRUCT_CONSOLESCREENBUFFERINFOEX_H_ */
36.190476
69
0.798684
232f63df50549677687f6201b4455659cc243141
2,334
c
C
Lista 5 - Registros/3.c
henrique-tavares/IFB-Programacao-de-Computadores-1
0c7d764edec6eb5e09b2f27761a8009486e796b3
[ "MIT" ]
null
null
null
Lista 5 - Registros/3.c
henrique-tavares/IFB-Programacao-de-Computadores-1
0c7d764edec6eb5e09b2f27761a8009486e796b3
[ "MIT" ]
null
null
null
Lista 5 - Registros/3.c
henrique-tavares/IFB-Programacao-de-Computadores-1
0c7d764edec6eb5e09b2f27761a8009486e796b3
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct Pontos { double x; double y; } pontos_t; double fatorial(int n); void le_poligono(pontos_t *poligono, int n); double perimetro(pontos_t *poligono, int n); double area(pontos_t *poligono, int n); double triangulos(pontos_t *poligono, int n, int m); int main() { int n; do { printf("\nDigite o número de lados do polígono (>= 3): "); scanf("%li", &n); if (n < 3) system("clear"); } while (n < 3); pontos_t *poligono = malloc(n * sizeof(pontos_t)); le_poligono(poligono, n); system("clear"); printf("\n\tPerímetro = %lf\n", perimetro(poligono, n)); printf("\n\tÁrea = %lf\n", area(poligono, n)); printf("\n\tQuantidade de triângulos possíveis = %.0lf\n\n", triangulos(poligono, n, 3)); free(poligono); return 0; } double fatorial(int n) { return (n > 0) ? n * fatorial(n-1) : 1; } void le_poligono(pontos_t *poligono, int n) { for (int i = 0; i < n; i++) { printf("\nDigite as coordenadas do %liº ponto:\n", i+1); printf("\t-> Coordenada x: "); scanf("%lf", &poligono[i].x); getchar(); printf("\t-> Coordenada y: "); scanf("%lf", &poligono[i].y); getchar(); } } double perimetro(pontos_t *poligono, int n) { double perimetro = 0; for (int i = 0; i < n; i++) { if (i == n-1) { perimetro += sqrtf(powf(poligono[i].x - poligono[0].x,2) + powf(poligono[i].y - poligono[0].y,2)); } else { perimetro += sqrtf(powf(poligono[i].x - poligono[i+1].x,2) + powf(poligono[i].y - poligono[i+1].y,2)); } } return perimetro; } double area(pontos_t *poligono, int n) { double area = 0; for (int i = 0; i < n; i++) { if (i == n-1) { area += (poligono[i].x * poligono[0].y) - (poligono[0].x * poligono[i].y); } else { area += (poligono[i].x * poligono[i+1].y) - (poligono[i+1].x * poligono[i].y); } } area /= 2; return (area < 0) ? area*(-1) : area; } double triangulos(pontos_t *poligono, int n, int m) { double triangulos; triangulos = fatorial(n) / (fatorial(n-m) * fatorial(m)); return triangulos; }
20.12069
114
0.533419
641f8b96ba4b4dde753bd9013f32f3d464a4f3e0
17,120
c
C
sws/benchmarks/stamp/ssca2/computeGraph.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
6
2015-09-08T15:40:48.000Z
2019-08-14T19:58:38.000Z
ssca2/computeGraph.c
nmldiegues/tm-study-pact14
da558d18a3690f56027512110b1c33864dbd68d8
[ "Apache-2.0" ]
null
null
null
ssca2/computeGraph.c
nmldiegues/tm-study-pact14
da558d18a3690f56027512110b1c33864dbd68d8
[ "Apache-2.0" ]
6
2015-01-20T20:44:39.000Z
2020-02-19T18:48:56.000Z
/* ============================================================================= * * computeGraph.c * * ============================================================================= * * For the license of bayes/sort.h and bayes/sort.c, please see the header * of the files. * * ------------------------------------------------------------------------ * * For the license of kmeans, please see kmeans/LICENSE.kmeans * * ------------------------------------------------------------------------ * * For the license of ssca2, please see ssca2/COPYRIGHT * * ------------------------------------------------------------------------ * * For the license of lib/mt19937ar.c and lib/mt19937ar.h, please see the * header of the files. * * ------------------------------------------------------------------------ * * For the license of lib/rbtree.h and lib/rbtree.c, please see * lib/LEGALNOTICE.rbtree and lib/LICENSE.rbtree * * ------------------------------------------------------------------------ * * Unless otherwise noted, the following license applies to STAMP files: * * Copyright (c) 2007, Stanford University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Stanford 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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 <assert.h> #include <stdio.h> #include <stdlib.h> #include "computeGraph.h" #include "createPartition.h" #include "defs.h" #include "globals.h" #include "thread.h" #include "utility.h" #include "tm.h" static ULONGINT_T* global_p = NULL; static ULONGINT_T global_maxNumVertices = 0; static ULONGINT_T global_outVertexListSize = 0; static ULONGINT_T* global_impliedEdgeList = NULL; static ULONGINT_T** global_auxArr = NULL; /* ============================================================================= * prefix_sums * ============================================================================= */ static void prefix_sums (ULONGINT_T* result, LONGINT_T* input, ULONGINT_T arraySize) { long myId = thread_getId(); long numThread = thread_getNumThread(); ULONGINT_T* p = NULL; if (myId == 0) { p = (ULONGINT_T*)P_MALLOC(NOSHARE(numThread) * sizeof(ULONGINT_T)); assert(p); global_p = p; } thread_barrier_wait(); p = global_p; long start; long end; long r = arraySize / numThread; start = myId * r + 1; end = (myId + 1) * r; if (myId == (numThread - 1)) { end = arraySize; } ULONGINT_T j; for (j = start; j < end; j++) { result[j] = input[j-1] + result[j-1]; } p[NOSHARE(myId)] = result[end-1]; thread_barrier_wait(); if (myId == 0) { for (j = 1; j < numThread; j++) { p[NOSHARE(j)] += p[NOSHARE(j-1)]; } } thread_barrier_wait(); if (myId > 0) { ULONGINT_T add_value = p[NOSHARE(myId-1)]; for (j = start-1; j < end; j++) { result[j] += add_value; } } thread_barrier_wait(); if (myId == 0) { P_FREE(p); } } /* ============================================================================= * computeGraph * ============================================================================= */ void computeGraph (void* argPtr) { TM_THREAD_ENTER(); graph* GPtr = ((computeGraph_arg_t*)argPtr)->GPtr; graphSDG* SDGdataPtr = ((computeGraph_arg_t*)argPtr)->SDGdataPtr; long myId = thread_getId(); long numThread = thread_getNumThread(); ULONGINT_T j; ULONGINT_T maxNumVertices = 0; ULONGINT_T numEdgesPlaced = SDGdataPtr->numEdgesPlaced; /* * First determine the number of vertices by scanning the tuple * startVertex list */ long i; long i_start; long i_stop; createPartition(0, numEdgesPlaced, myId, numThread, &i_start, &i_stop); for (i = i_start; i < i_stop; i++) { if (SDGdataPtr->startVertex[i] > maxNumVertices) { maxNumVertices = SDGdataPtr->startVertex[i]; } } TM_BEGIN(); long tmp_maxNumVertices = (long)TM_SHARED_READ(global_maxNumVertices); long new_maxNumVertices = MAX(tmp_maxNumVertices, maxNumVertices) + 1; TM_SHARED_WRITE(global_maxNumVertices, new_maxNumVertices); TM_END(); thread_barrier_wait(); maxNumVertices = global_maxNumVertices; if (myId == 0) { GPtr->numVertices = maxNumVertices; GPtr->numEdges = numEdgesPlaced; GPtr->intWeight = SDGdataPtr->intWeight; GPtr->strWeight = SDGdataPtr->strWeight; for (i = 0; i < numEdgesPlaced; i++) { if (GPtr->intWeight[numEdgesPlaced-i-1] < 0) { GPtr->numStrEdges = -(GPtr->intWeight[numEdgesPlaced-i-1]) + 1; GPtr->numIntEdges = numEdgesPlaced - GPtr->numStrEdges; break; } } GPtr->outDegree = (LONGINT_T*)P_MALLOC((GPtr->numVertices) * sizeof(LONGINT_T)); assert(GPtr->outDegree); GPtr->outVertexIndex = (ULONGINT_T*)P_MALLOC((GPtr->numVertices) * sizeof(ULONGINT_T)); assert(GPtr->outVertexIndex); } thread_barrier_wait(); createPartition(0, GPtr->numVertices, myId, numThread, &i_start, &i_stop); for (i = i_start; i < i_stop; i++) { GPtr->outDegree[i] = 0; GPtr->outVertexIndex[i] = 0; } ULONGINT_T outVertexListSize = 0; thread_barrier_wait(); ULONGINT_T i0 = -1UL; for (i = i_start; i < i_stop; i++) { ULONGINT_T k = i; if ((outVertexListSize == 0) && (k != 0)) { while (i0 == -1UL) { for (j = 0; j < numEdgesPlaced; j++) { if (k == SDGdataPtr->startVertex[j]) { i0 = j; break; } } k--; } } if ((outVertexListSize == 0) && (k == 0)) { i0 = 0; } for (j = i0; j < numEdgesPlaced; j++) { if (i == GPtr->numVertices-1) { break; } if ((i != SDGdataPtr->startVertex[j])) { if ((j > 0) && (i == SDGdataPtr->startVertex[j-1])) { if (j-i0 >= 1) { outVertexListSize++; GPtr->outDegree[i]++; ULONGINT_T t; for (t = i0+1; t < j; t++) { if (SDGdataPtr->endVertex[t] != SDGdataPtr->endVertex[t-1]) { outVertexListSize++; GPtr->outDegree[i] = GPtr->outDegree[i]+1; } } } } i0 = j; break; } } if (i == GPtr->numVertices-1) { if (numEdgesPlaced-i0 >= 0) { outVertexListSize++; GPtr->outDegree[i]++; ULONGINT_T t; for (t = i0+1; t < numEdgesPlaced; t++) { if (SDGdataPtr->endVertex[t] != SDGdataPtr->endVertex[t-1]) { outVertexListSize++; GPtr->outDegree[i]++; } } } } } /* for i */ thread_barrier_wait(); prefix_sums(GPtr->outVertexIndex, GPtr->outDegree, GPtr->numVertices); thread_barrier_wait(); TM_BEGIN(); TM_SHARED_WRITE( global_outVertexListSize, ((long)TM_SHARED_READ(global_outVertexListSize) + outVertexListSize) ); TM_END(); thread_barrier_wait(); outVertexListSize = global_outVertexListSize; if (myId == 0) { GPtr->numDirectedEdges = outVertexListSize; GPtr->outVertexList = (ULONGINT_T*)P_MALLOC(outVertexListSize * sizeof(ULONGINT_T)); assert(GPtr->outVertexList); GPtr->paralEdgeIndex = (ULONGINT_T*)P_MALLOC(outVertexListSize * sizeof(ULONGINT_T)); assert(GPtr->paralEdgeIndex); GPtr->outVertexList[0] = SDGdataPtr->endVertex[0]; } thread_barrier_wait(); /* * Evaluate outVertexList */ i0 = -1UL; for (i = i_start; i < i_stop; i++) { ULONGINT_T k = i; while ((i0 == -1UL) && (k != 0)) { for (j = 0; j < numEdgesPlaced; j++) { if (k == SDGdataPtr->startVertex[j]) { i0 = j; break; } } k--; } if ((i0 == -1) && (k == 0)) { i0 = 0; } for (j = i0; j < numEdgesPlaced; j++) { if (i == GPtr->numVertices-1) { break; } if (i != SDGdataPtr->startVertex[j]) { if ((j > 0) && (i == SDGdataPtr->startVertex[j-1])) { if (j-i0 >= 1) { long ii = GPtr->outVertexIndex[i]; ULONGINT_T r = 0; GPtr->paralEdgeIndex[ii] = i0; GPtr->outVertexList[ii] = SDGdataPtr->endVertex[i0]; r++; ULONGINT_T t; for (t = i0+1; t < j; t++) { if (SDGdataPtr->endVertex[t] != SDGdataPtr->endVertex[t-1]) { GPtr->paralEdgeIndex[ii+r] = t; GPtr->outVertexList[ii+r] = SDGdataPtr->endVertex[t]; r++; } } } } i0 = j; break; } } /* for j */ if (i == GPtr->numVertices-1) { ULONGINT_T r = 0; if (numEdgesPlaced-i0 >= 0) { long ii = GPtr->outVertexIndex[i]; GPtr->paralEdgeIndex[ii+r] = i0; GPtr->outVertexList[ii+r] = SDGdataPtr->endVertex[i0]; r++; ULONGINT_T t; for (t = i0+1; t < numEdgesPlaced; t++) { if (SDGdataPtr->endVertex[t] != SDGdataPtr->endVertex[t-1]) { GPtr->paralEdgeIndex[ii+r] = t; GPtr->outVertexList[ii+r] = SDGdataPtr->endVertex[t]; r++; } } } } } /* for i */ thread_barrier_wait(); if (myId == 0) { P_FREE(SDGdataPtr->startVertex); P_FREE(SDGdataPtr->endVertex); GPtr->inDegree = (LONGINT_T*)P_MALLOC(GPtr->numVertices * sizeof(LONGINT_T)); assert(GPtr->inDegree); GPtr->inVertexIndex = (ULONGINT_T*)P_MALLOC(GPtr->numVertices * sizeof(ULONGINT_T)); assert(GPtr->inVertexIndex); } thread_barrier_wait(); for (i = i_start; i < i_stop; i++) { GPtr->inDegree[i] = 0; GPtr->inVertexIndex[i] = 0; } /* A temp. array to store the inplied edges */ ULONGINT_T* impliedEdgeList; if (myId == 0) { impliedEdgeList = (ULONGINT_T*)P_MALLOC(GPtr->numVertices * MAX_CLUSTER_SIZE * sizeof(ULONGINT_T)); global_impliedEdgeList = impliedEdgeList; } thread_barrier_wait(); impliedEdgeList = global_impliedEdgeList; createPartition(0, (GPtr->numVertices * MAX_CLUSTER_SIZE), myId, numThread, &i_start, &i_stop); for (i = i_start; i < i_stop; i++) { impliedEdgeList[i] = 0; } /* * An auxiliary array to store implied edges, in case we overshoot * MAX_CLUSTER_SIZE */ ULONGINT_T** auxArr; if (myId == 0) { auxArr = (ULONGINT_T**)P_MALLOC(GPtr->numVertices * sizeof(ULONGINT_T*)); assert(auxArr); global_auxArr = auxArr; } thread_barrier_wait(); auxArr = global_auxArr; createPartition(0, GPtr->numVertices, myId, numThread, &i_start, &i_stop); for (i = i_start; i < i_stop; i++) { /* Inspect adjacency list of vertex i */ for (j = GPtr->outVertexIndex[i]; j < (GPtr->outVertexIndex[i] + GPtr->outDegree[i]); j++) { ULONGINT_T v = GPtr->outVertexList[j]; ULONGINT_T k; for (k = GPtr->outVertexIndex[v]; k < (GPtr->outVertexIndex[v] + GPtr->outDegree[v]); k++) { if (GPtr->outVertexList[k] == i) { break; } } if (k == GPtr->outVertexIndex[v]+GPtr->outDegree[v]) { TM_BEGIN(); /* Add i to the impliedEdgeList of v */ long inDegree = (long)TM_SHARED_READ(GPtr->inDegree[v]); TM_SHARED_WRITE(GPtr->inDegree[v], (inDegree + 1)); if (inDegree < MAX_CLUSTER_SIZE) { TM_SHARED_WRITE(impliedEdgeList[v*MAX_CLUSTER_SIZE+inDegree], i); } else { /* Use auxiliary array to store the implied edge */ /* Create an array if it's not present already */ ULONGINT_T* a = NULL; if ((inDegree % MAX_CLUSTER_SIZE) == 0) { a = (ULONGINT_T*)TM_MALLOC(MAX_CLUSTER_SIZE * sizeof(ULONGINT_T)); assert(a); TM_SHARED_WRITE_P(auxArr[v], a); } else { a = auxArr[v]; } TM_SHARED_WRITE(a[inDegree % MAX_CLUSTER_SIZE], i); } TM_END(); } } } /* for i */ thread_barrier_wait(); prefix_sums(GPtr->inVertexIndex, GPtr->inDegree, GPtr->numVertices); if (myId == 0) { GPtr->numUndirectedEdges = GPtr->inVertexIndex[GPtr->numVertices-1] + GPtr->inDegree[GPtr->numVertices-1]; GPtr->inVertexList = (ULONGINT_T *)P_MALLOC(GPtr->numUndirectedEdges * sizeof(ULONGINT_T)); } thread_barrier_wait(); /* * Create the inVertex List */ for (i = i_start; i < i_stop; i++) { for (j = GPtr->inVertexIndex[i]; j < (GPtr->inVertexIndex[i] + GPtr->inDegree[i]); j++) { if ((j - GPtr->inVertexIndex[i]) < MAX_CLUSTER_SIZE) { GPtr->inVertexList[j] = impliedEdgeList[i*MAX_CLUSTER_SIZE+j-GPtr->inVertexIndex[i]]; } else { GPtr->inVertexList[j] = auxArr[i][(j-GPtr->inVertexIndex[i]) % MAX_CLUSTER_SIZE]; } } } thread_barrier_wait(); if (myId == 0) { P_FREE(impliedEdgeList); } for (i = i_start; i < i_stop; i++) { if (GPtr->inDegree[i] > MAX_CLUSTER_SIZE) { P_FREE(auxArr[i]); } } thread_barrier_wait(); if (myId == 0) { P_FREE(auxArr); } TM_THREAD_EXIT(); } /* ============================================================================= * * End of computeGraph.c * * ============================================================================= */
30.516934
85
0.475526
ea91d0c6282487684505c8d2c28b8f372e885fdd
103
h
C
TemplePlus/python/python_module.h
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
69
2015-05-05T14:09:25.000Z
2022-02-15T06:13:04.000Z
TemplePlus/python/python_module.h
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
457
2015-05-01T22:07:45.000Z
2022-03-31T02:19:10.000Z
TemplePlus/python/python_module.h
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
25
2016-02-04T21:19:53.000Z
2021-11-15T23:14:51.000Z
#pragma once /* Initializes the toee Python module and all its content. */ void PyToeeInitModule();
12.875
56
0.737864
eaa45f77c90d3c2e3fee56b772a8248aae60f996
1,168
h
C
vendor/github.com/rajivnavada/gpgme/gpgme-bridge.h
rajivnavada/cryptzd
9868ccdaf80defe381ac0c658b9ed41a9ccf985c
[ "MIT" ]
null
null
null
vendor/github.com/rajivnavada/gpgme/gpgme-bridge.h
rajivnavada/cryptzd
9868ccdaf80defe381ac0c658b9ed41a9ccf985c
[ "MIT" ]
null
null
null
vendor/github.com/rajivnavada/gpgme/gpgme-bridge.h
rajivnavada/cryptzd
9868ccdaf80defe381ac0c658b9ed41a9ccf985c
[ "MIT" ]
null
null
null
#pragma once #include <stdlib.h> #include <string.h> #include <gpgme.h> #include <gpg-error.h> enum { KEY_FINGERPRINT_LEN = 40, KEY_USERNAME_LEN = 255, KEY_USEREMAIL_LEN = 255, KEY_USERCOMMENT_LEN = 255 }; // +1 for the terminating 0 typedef struct key_info { long int expires; char user_name[KEY_USERNAME_LEN+1]; char user_email[KEY_USEREMAIL_LEN+1]; char user_comment[KEY_USERCOMMENT_LEN+1]; char fingerprint[KEY_FINGERPRINT_LEN+1]; int is_new; } *key_info_t; #ifdef __cplusplus extern "C" { #endif // Returns an instance of key_info key_info_t new_key_info (); // Frees memory allocation to INFO void free_key_info (key_info_t info); // Tries to import KEY into the system keychain void import_key (key_info_t info, const char *key); void get_key_info (key_info_t info, const char *fingerprint, gpgme_ctx_t ctx); // Returns encrypted data that MUST be freed by the caller char *encrypt (const char *fingerprint, const char *message); // Returns decrypted data that MUST be freed by the caller char *decrypt (const char *encrypted_message); #ifdef __cplusplus } #endif
22.901961
82
0.712329
967b8057b71edf9f612aed9d491eb1f553734e70
4,589
c
C
tools/regression/audit/audit_pipe_ioctl/audit_pipe_ioctl.c
TrustedBSD/sebsd
fd5de6f587183087cf930779701d5713e8ca64cc
[ "Naumen", "Condor-1.1", "MS-PL" ]
4
2017-04-06T21:39:15.000Z
2019-10-09T17:34:14.000Z
tools/regression/audit/audit_pipe_ioctl/audit_pipe_ioctl.c
TrustedBSD/sebsd
fd5de6f587183087cf930779701d5713e8ca64cc
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
tools/regression/audit/audit_pipe_ioctl/audit_pipe_ioctl.c
TrustedBSD/sebsd
fd5de6f587183087cf930779701d5713e8ca64cc
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-01-04T06:36:39.000Z
2020-01-04T06:36:39.000Z
/*- * Copyright (c) 2006 Robert N. M. Watson * All rights reserved. * * This software was developed by Robert Watson for the TrustedBSD Project. * * 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 AUTHOR 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 AUTHOR 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. * * $FreeBSD: src/tools/regression/audit/audit_pipe_ioctl/audit_pipe_ioctl.c,v 1.1 2006/03/19 15:47:53 rwatson Exp $ */ /* * Simple audit pipe regression test to confirm that the ioctls for queue * limit information basically work. No attempt is made to validate the * queue length returned, however. */ #include <sys/types.h> #include <sys/ioctl.h> #include <security/audit/audit_ioctl.h> #include <err.h> #include <fcntl.h> int main(int argc, char *argv[]) { u_int len, minlen, maxlen; u_int64_t astat; int fd; fd = open("/dev/auditpipe", O_RDONLY); if (fd < 0) err(-1, "/dev/auditpipe"); /* * First, test that we can read the queue length, queue limit, and * bounds on queue length limits. */ len = (u_int)(-1); if (ioctl(fd, AUDITPIPE_GET_QLEN, &len) < 0) err(-1, "AUDITPIPE_GET_QLEN"); if (len == (u_int)(-1)) errx(-1, "AUDITPIPE_GET_QLEN: unchanged"); minlen = (u_int)(-1); if (ioctl(fd, AUDITPIPE_GET_QLIMIT_MIN, &minlen) < 0) err(-1, "AUDITPIPE_GET_QLIMIT_MIN"); if (minlen == (u_int)(-1)) errx(-1, "AUDITPIPE_GET_QLIMIT_MIN: unchanged"); maxlen = (u_int)(-1); if (ioctl(fd, AUDITPIPE_GET_QLIMIT_MAX, &maxlen) < 0) err(-1, "AUDITPIPE_GET_QLIMIT_MAX"); if (maxlen == (u_int)(-1)) errx(-1, "AUDITPIPE_GET_QLIMIT_MAX: unchanged"); len = (u_int)(-1); if (ioctl(fd, AUDITPIPE_GET_QLIMIT, &len) < 0) err(-1, "AUDITPIPE_GET_QLIMIT"); if (len == (u_int)(-1)) errx(-1, "AUDITPIPE_GET_QLIMIT: unchanged"); if (!(len >= minlen)) errx(-1, "queue length < minlen"); if (!(len <= maxlen)) errx(-1, "queue length > maxlen"); /* * Try setting the queue length to first minimum, then maximum * lengths. Query after each to make sure it changed. */ len = minlen; if (ioctl(fd, AUDITPIPE_SET_QLIMIT, &len) < 0) err(-1, "AUDITPIPE_SET_QLIMIT(min)"); if (ioctl(fd, AUDITPIPE_GET_QLIMIT, &len) < 0) err(-1, "AUDITPIPE_GET_QLIMIT"); if (len != minlen) errx(-1, "set to minlen didn't work"); len = maxlen; if (ioctl(fd, AUDITPIPE_SET_QLIMIT, &len) < 0) err(-1, "AUDITPIPE_SET_QLIMIT(max)"); if (ioctl(fd, AUDITPIPE_GET_QLIMIT, &len) < 0) err(-1, "AUDITPIPE_GETQLIMIT"); if (len != maxlen) errx(-1, "set to maxlen didn't work"); /* * Check that we can query the defined stats. No attempt to * validate. */ astat = (u_int64_t)(int64_t)(-1); if (ioctl(fd, AUDITPIPE_GET_INSERTS, &astat) < 0) err(-1, "AUDITPIPE_GET_INSERTS"); if (astat == (u_int64_t)(int64_t)(-1)) errx(-1, "AUDITPIPE_GET_INSERTS: unchanged"); astat = (u_int64_t)(int64_t)(-1); if (ioctl(fd, AUDITPIPE_GET_READS, &astat) < 0) err(-1, "AUDITPIPE_GET_READS"); if (astat == (u_int64_t)(int64_t)(-1)) errx(-1, "AUDITPIPE_GET_READS: unchanged"); astat = (u_int64_t)(int64_t)(-1); if (ioctl(fd, AUDITPIPE_GET_DROPS, &astat) < 0) err(-1, "AUDITPIPE_GET_DROPS"); if (astat == (u_int64_t)(int64_t)(-1)) errx(-1, "AUDITPIPE_GET_DROPS: unchanged"); astat = (u_int64_t)(int64_t)(-1); if (ioctl(fd, AUDITPIPE_GET_TRUNCATES, &astat) < 0) err(-1, "AUDITPIPE_GET_TRUNCATES"); if (astat == (u_int64_t)(int64_t)(-1)) errx(-1, "AUDITPIPE_GET_TRUNCATES: unchanged"); return (0); }
31.868056
115
0.693179
148920eb003f2b73b43fc1b976c02440c7c2b5a6
114
h
C
Scripts/Enums/Generated/UserNotifications+NATEnums.h
jvisenti/NativeNative
f4baa227766ee5481ca8bf1b6789940657bd1eb1
[ "MIT" ]
2
2017-03-29T12:24:00.000Z
2019-09-11T19:39:13.000Z
Scripts/Enums/Generated/UserNotifications+NATEnums.h
jvisenti/NativeNative
f4baa227766ee5481ca8bf1b6789940657bd1eb1
[ "MIT" ]
18
2015-12-11T15:42:08.000Z
2018-08-15T11:30:25.000Z
Scripts/Enums/Generated/UserNotifications+NATEnums.h
jvisenti/NativeNative
f4baa227766ee5481ca8bf1b6789940657bd1eb1
[ "MIT" ]
null
null
null
// Registers NATSymbols for enums defined in UserNotifications @interface NSObject (UserNotificationsEnums) @end
22.8
62
0.833333
14970e308ce5186486e442308d20be746b209a46
3,033
c
C
pr7/01_sort.c
brueghell/timp-Brueghell
de8f7b67decfcbde305ab889d3fcf44744d63c6b
[ "BSD-3-Clause" ]
null
null
null
pr7/01_sort.c
brueghell/timp-Brueghell
de8f7b67decfcbde305ab889d3fcf44744d63c6b
[ "BSD-3-Clause" ]
null
null
null
pr7/01_sort.c
brueghell/timp-Brueghell
de8f7b67decfcbde305ab889d3fcf44744d63c6b
[ "BSD-3-Clause" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <malloc.h> #include <time.h> FILE* f; int heapUp(int Arr[], int Size, int* t) { int i, iS, j, r, l, RD, LD, v, N = Size; iS = (Size / 2) - 1; while (Size != 0) { i = iS; while (i != (-1)) { j = i; while (1) { l = 2 * j + 1; r = 2 * j + 2; if (l < Size) LD = Arr[l]; else LD = -1001; if (r < Size) RD = Arr[r]; else RD = -1001; if (RD > LD) { if (RD > Arr[j]) { v = Arr[j]; Arr[j] = Arr[r]; Arr[r] = v; j = r; // if ((*t) != 0) fprintf(f, "\n"); else (*t)++; for (int k = 0; k < N; k++) { if (k != 0) fprintf(f, " "); fprintf(f, "%d", Arr[k]); } // } else break; } else { if (LD > Arr[j]) { v = Arr[j]; Arr[j] = Arr[l]; Arr[l] = v; j = l; // if ((*t) != 0) fprintf(f, "\n"); else (*t)++; for (int k = 0; k < N; k++) { if (k != 0) fprintf(f, " "); fprintf(f, "%d", Arr[k]); } // } else break; } } i--; } Size--; if (Arr[0] > Arr[Size]) { v = Arr[0]; Arr[0] = Arr[Size]; Arr[Size] = v; // if ((*t) != 0) fprintf(f, "\n"); else (*t)++; for (int k = 0; k < N; k++) { if (k != 0) fprintf(f, " "); fprintf(f, "%d", Arr[k]); } // } } return 0; } int quickUp(int Arr[], int B, int E, int N, int* t) { int i = B, j = E, v = 0, el = Arr[(E + B) / 2], elN = (E + B) / 2; while (1) { while (Arr[i] < el) i++; while (Arr[j] > el) j--; if (i < j) { v = Arr[i]; Arr[i] = Arr[j]; Arr[j] = v; // if (i != elN) j--; else elN = j; if ((j + 1) != elN) i++; else elN = i; if ((*t) != 0) fprintf(f, "\n"); else (*t)++; for (int k = 0; k < N; k++) { if (k != 0) fprintf(f, " "); fprintf(f, "%d", Arr[k]); } // } else break; } if ((i - B - 1) > 0) quickUp(Arr, B, i - 1, N, t); if ((E - i - 1) > 0) quickUp(Arr, i + 1, E, N, t); return 0; } int main() { int* Arr = (int*)malloc(sizeof(int)), * CArr = (int*)malloc(sizeof(int)), N, i, t = 0; double k; scanf("%lf", &k); N = k; Arr = (int*)realloc(Arr, N * sizeof(int)); CArr = (int*)realloc(CArr, N * sizeof(int)); for (i = 0; i < N; i++) { scanf("%lf", &k); Arr[i] = k; CArr[i] = k; } f = fopen("quicksort.log", "w+"); fclose(f); f = fopen("quicksort.log", "w+"); quickUp(Arr, 0, N - 1, N, &t); fclose(f); t = 0; f = fopen("heapsort.log", "w+"); fclose(f); f = fopen("heapsort.log", "r+"); heapUp(CArr, N, &t); fclose(f); for (int k = 0; k < N; k++) { if (k != 0) printf(" "); printf("%d", Arr[k]); } return 0; }
17.135593
88
0.355424
9f14391fcae64080cc571b178db6b0f0cbb03d54
2,043
h
C
TradeaiderQC/Pods/Headers/Public/MOBFoundation_IDFA/MOBFoundation/MOBFRegex.h
littleFrenchfries/kefuSystem
70b4bc34b74ccf5224c78cf716253b704d6a64c5
[ "MIT" ]
1
2016-10-13T02:00:39.000Z
2016-10-13T02:00:39.000Z
TradeaiderQC/Pods/Headers/Public/MOBFoundation_IDFA/MOBFoundation/MOBFRegex.h
littleFrenchfries/kefuSystem
70b4bc34b74ccf5224c78cf716253b704d6a64c5
[ "MIT" ]
1
2016-10-13T02:02:05.000Z
2016-10-22T09:27:05.000Z
TradeaiderQC/Pods/Headers/Public/MOBFoundation_IDFA/MOBFoundation/MOBFRegex.h
littleFrenchfries/kefuSystem
70b4bc34b74ccf5224c78cf716253b704d6a64c5
[ "MIT" ]
2
2018-09-30T12:54:43.000Z
2019-08-26T02:04:58.000Z
// // MOBFRegex.h // MOBFoundation // // Created by vimfung on 15-1-20. // Copyright (c) 2015年 MOB. All rights reserved. // #import <Foundation/Foundation.h> /** * 替换处理 * * @param captureCount 捕获数量 * @param capturedStrings 捕获字符串集合 * @param capturedRanges 捕获字符串范围集合 * @param stop 是否停止捕获标识 * * @return 替换后的字符串 */ typedef NSString *(^MOBFReplacingOccurrencesHandler) (NSInteger captureCount, NSString *const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop); /** * 正则表达式选项 */ typedef NS_ENUM(NSUInteger, MOBFRegexOptions){ /** * 无设置 */ MOBFRegexOptionsNoOptions = 0, /** * 不区分大小写 */ MOBFRegexOptionsCaseless = 2, /** * 注释 */ MOBFRegexOptionsComments = 4, /** * 匹配点 */ MOBFRegexOptionsDotAll = 32, /** * 多行模式 */ MOBFRegexOptionsMultiline = 8, /** * Unicode字符 */ MOBFRegexOptionsUnicodeWordBoundaries = 256 }; /** * 正则表达式工具类 */ @interface MOBFRegex : NSObject /** * 替换字符串 * * @param regex 正则表达式 * @param string 原始字符串 * @param block 块回调处理替换规则 * * @return 字符串 */ + (NSString *)stringByReplacingOccurrencesOfRegex:(NSString *)regex withString:(NSString *)string usingBlock:(MOBFReplacingOccurrencesHandler)block; /** * 匹配字符串 * * @param regex 正则表达式 * @param options 表达式选项 * @param range 匹配范围 * @param string 原始字符串 * * @return YES 匹配,NO 不匹配 */ + (BOOL)isMatchedByRegex:(NSString *)regex options:(MOBFRegexOptions)options inRange:(NSRange)range withString:(NSString *)string; /** * 匹配字符串 * * @param regex 正则表达式 * @param string 原始字符串 * * @return 匹配的字符串集合 */ + (NSArray *)captureComponentsMatchedByRegex:(NSString *)regex withString:(NSString *)string; @end
20.846939
197
0.57024
bb2ec82d8eb92a95445c52d49c7293f12f34ecb3
3,329
h
C
Vc/include/Vc/avx/writemaskedvector.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
Vc/include/Vc/avx/writemaskedvector.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
Vc/include/Vc/avx/writemaskedvector.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/* This file is part of the Vc library. Copyright (C) 2009-2012 Matthias Kretz <kretz@kde.org> Vc 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 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #ifndef VC_AVX_WRITEMASKEDVECTOR_H #define VC_AVX_WRITEMASKEDVECTOR_H #include "macros.h" namespace AliRoot { namespace Vc { namespace AVX { template<typename T> class WriteMaskedVector { friend class Vector<T>; typedef typename VectorTypeHelper<T>::Type VectorType; typedef typename DetermineEntryType<T>::Type EntryType; enum Constants { Size = sizeof(VectorType) / sizeof(EntryType) }; typedef typename Vc::AVX::Mask<Size, sizeof(VectorType)> Mask; public: FREE_STORE_OPERATORS_ALIGNED(32) //prefix Vector<T> Vc_ALWAYS_INLINE_L &operator++() Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE_L &operator--() Vc_ALWAYS_INLINE_R; //postfix Vector<T> Vc_ALWAYS_INLINE_L operator++(int) Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE_L operator--(int) Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE_L &operator+=(const Vector<T> &x) Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE_L &operator-=(const Vector<T> &x) Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE_L &operator*=(const Vector<T> &x) Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE_L &operator/=(const Vector<T> &x) Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE &operator+=(EntryType x) { return operator+=(Vector<T>(x)); } Vector<T> Vc_ALWAYS_INLINE &operator-=(EntryType x) { return operator-=(Vector<T>(x)); } Vector<T> Vc_ALWAYS_INLINE &operator*=(EntryType x) { return operator*=(Vector<T>(x)); } Vector<T> Vc_ALWAYS_INLINE &operator/=(EntryType x) { return operator/=(Vector<T>(x)); } Vector<T> Vc_ALWAYS_INLINE_L &operator=(const Vector<T> &x) Vc_ALWAYS_INLINE_R; Vector<T> Vc_ALWAYS_INLINE &operator=(EntryType x) { return operator=(Vector<T>(x)); } template<typename F> Vc_INTRINSIC void call(const F &f) const { return vec->call(f, mask); } template<typename F> Vc_INTRINSIC void call(F &f) const { return vec->call(f, mask); } template<typename F> Vc_INTRINSIC Vector<T> apply(const F &f) const { return vec->apply(f, mask); } template<typename F> Vc_INTRINSIC Vector<T> apply(F &f) const { return vec->apply(f, mask); } private: Vc_ALWAYS_INLINE WriteMaskedVector(Vector<T> *v, const Mask &k) : vec(v), mask(k) {} Vector<T> *const vec; Mask mask; }; } // namespace AVX } // namespace Vc } // namespace AliRoot #include "writemaskedvector.tcc" #include "undomacros.h" #endif // VC_AVX_WRITEMASKEDVECTOR_H
40.108434
96
0.683989
4b1618940dbd2b477af86197e00a3f507d89bf0d
2,368
h
C
sys/include/kernel.h
PingChung/prex
fa9df6697c5ae4af1a2c6977e5aa63935ad68843
[ "BSD-3-Clause" ]
6
2017-05-20T09:17:14.000Z
2020-10-12T22:32:16.000Z
sys/include/kernel.h
PingChung/prex
fa9df6697c5ae4af1a2c6977e5aa63935ad68843
[ "BSD-3-Clause" ]
null
null
null
sys/include/kernel.h
PingChung/prex
fa9df6697c5ae4af1a2c6977e5aa63935ad68843
[ "BSD-3-Clause" ]
5
2015-07-21T16:12:06.000Z
2019-09-22T14:34:51.000Z
/*- * Copyright (c) 2005-2009, Kohsuke Ohtani * 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 author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _KERNEL_H #define _KERNEL_H #include <conf/config.h> #include <types.h> #include <machine/stdarg.h> #include <sys/cdefs.h> #include <sys/param.h> #include <sys/errno.h> #include <task.h> #include <thread.h> #include <version.h> #include <debug.h> #include <libkern.h> #define __s(x) __STRING(x) #define HOSTNAME "Preky" #define PROFILE __s(CONFIG_PROFILE) #define MACHINE __s(CONFIG_MACHINE) #define VERSION __s(MAJORVERSION) "." __s(MINORVERSION) "." __s(PATCHLEVEL) #define BANNER "Prex version " VERSION PROFILE " for " MACHINE \ " ("__DATE__ ")\n" \ "Copyright (c) 2005-2009 Kohsuke Ohtani\n" /* * Global variables in the kernel. */ extern struct thread *curthread; /* pointer to the current thread */ extern struct task kernel_task; /* kernel task */ #endif /* !_KERNEL_H */
37.587302
77
0.744088
4bac3be1c3c5d1d87d7aedcf52d4b28808c04f5c
502
h
C
ThorEngine/Source Code/W_EngineConfig.h
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
12
2019-10-07T12:30:12.000Z
2021-09-25T13:05:26.000Z
ThorEngine/Source Code/W_EngineConfig.h
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
15
2017-06-14T13:10:06.000Z
2020-11-21T11:27:54.000Z
ThorEngine/Source Code/W_EngineConfig.h
markitus18/Thor-Engine
d89c75f803357d6493cd018450bceb384d2dd265
[ "Unlicense" ]
4
2019-12-17T11:48:45.000Z
2020-11-13T19:09:59.000Z
#ifndef __W_ENGINECONFIG_H__ #define __W_ENGINECONFIG_H__ #include "Window.h" #include "PerfTimer.h" #include <vector> #include <string> struct ImGuiWindowClass; class W_EngineConfig : public Window { public: W_EngineConfig(M_Editor* editor, ImGuiWindowClass* windowClass, int ID); ~W_EngineConfig() {} void Draw() override; void UpdateFPSData(int fps, int ms); static inline const char* GetName() { return "Engine Config"; }; private: float FPS_data[100]; float ms_data[100]; }; #endif
17.310345
73
0.747012
b7283ebe6b4bfdcf5819f80fdc853c896e5704b6
265
c
C
d/antioch/greaterantioch/rooms/grassland/grassland7.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/antioch/greaterantioch/rooms/grassland/grassland7.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/antioch/greaterantioch/rooms/grassland/grassland7.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> #include "../../gantioch.h" inherit ROOMS"grassland.c"; void create() { ::create(); set_exits(([ "north" : ROAD"road13", "south" : GRASSLAND"grassland8", "east" : ROAD"road12", "west" : GRASSLAND"grassland13", ])); }
13.947368
35
0.569811
f4f6d505b131ef551041f7cb547f1f28812cf705
543
h
C
mvp_tips/CPUID/CPUID/ExtendedCPU1EAXAMD.h
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
9
2017-08-31T06:03:18.000Z
2019-01-06T05:07:26.000Z
mvp_tips/CPUID/CPUID/ExtendedCPU1EAXAMD.h
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
mvp_tips/CPUID/CPUID/ExtendedCPU1EAXAMD.h
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2017-08-31T06:23:22.000Z
2022-01-24T06:47:19.000Z
#pragma once #include "afxwin.h" #include "BasicCPU1EAXAMD.h" // CExtendedCPU1EAXAMD dialog class CExtendedCPU1EAXAMD : public CBasicCPU1EAXAMD { DECLARE_DYNCREATE(CExtendedCPU1EAXAMD) public: CExtendedCPU1EAXAMD(); virtual ~CExtendedCPU1EAXAMD(); // Dialog Data // enum { IDD = IDD_CPUID_EXTENDED_1_EAX_AMD }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); virtual BOOL OnSetActive(); DECLARE_MESSAGE_MAP() };
22.625
78
0.694291
764c4ac09bd6b9ba98ee595eb3a003331232922f
635
c
C
Exercicios/pasta 1/Atividade-6/N.c
Elvis-Almeida/C
6734d4e671746a92a4d2c28e15c15021280aa887
[ "MIT" ]
null
null
null
Exercicios/pasta 1/Atividade-6/N.c
Elvis-Almeida/C
6734d4e671746a92a4d2c28e15c15021280aa887
[ "MIT" ]
null
null
null
Exercicios/pasta 1/Atividade-6/N.c
Elvis-Almeida/C
6734d4e671746a92a4d2c28e15c15021280aa887
[ "MIT" ]
null
null
null
#include <stdio.h> int main(){ int i; float tot=0, menor, maior, matrizA[20]; for (i = 0; i < 20; i++) { printf("digite a temperatura: "); scanf("%f", &matrizA[i]); } for(i=0; i < 20; i++){ tot += matrizA[i]; if (i==0) { menor = matrizA[i]; maior = matrizA[i]; } if (matrizA[i] > maior) { maior = matrizA[i]; } if (matrizA[i] < menor){ menor = matrizA[i]; } } printf("O menor foi: %f\nO maior foi: %f\nA media foi: %.2f", menor, maior, tot*1.0/20); }
21.166667
92
0.411024
63af7935636c029a2ffbc8bfed821cf9c44786e0
2,074
h
C
src/public/dme_controls/AttributeBoolChoicePanel.h
DeadZoneLuna/csso-src
6c978ea304ee2df3796bc9c0d2916bac550050d5
[ "Unlicense" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/public/dme_controls/AttributeBoolChoicePanel.h
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/public/dme_controls/AttributeBoolChoicePanel.h
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #ifndef ATTRIBUTEBOOLCHOICEPANEL_h #define ATTRIBUTEBOOLCHOICEPANEL_h #ifdef _WIN32 #pragma once #endif #include "dme_controls/BaseAttributeChoicePanel.h" #include "movieobjects/dmeeditortypedictionary.h" #include "vgui_controls/MessageMap.h" //----------------------------------------------------------------------------- // Forward declarations //----------------------------------------------------------------------------- struct AttributeWidgetInfo_t; namespace vgui { class Panel; class ComboBox; } //----------------------------------------------------------------------------- // Configuration for integer choices //----------------------------------------------------------------------------- class CDmeEditorBoolChoicesInfo : public CDmeEditorChoicesInfo { DEFINE_ELEMENT( CDmeEditorBoolChoicesInfo, CDmeEditorChoicesInfo ); public: // Add a choice void SetFalseChoice( const char *pChoiceString ); void SetTrueChoice( const char *pChoiceString ); // Gets the choices const char *GetFalseChoiceString( ) const; const char *GetTrueChoiceString( ) const; }; //----------------------------------------------------------------------------- // CAttributeBoolChoicePanel //----------------------------------------------------------------------------- class CAttributeBoolChoicePanel : public CBaseAttributeChoicePanel { DECLARE_CLASS_SIMPLE( CAttributeBoolChoicePanel, CBaseAttributeChoicePanel ); public: CAttributeBoolChoicePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ); private: // Derived classes can re-implement this to fill the combo box however they like virtual void PopulateComboBox( vgui::ComboBox *pComboBox ); virtual void SetAttributeFromComboBox( vgui::ComboBox *pComboBox, KeyValues *pKeyValues ); virtual void SetComboBoxFromAttribute( vgui::ComboBox *pComboBox ); }; #endif // ATTRIBUTEBOOLCHOICEPANEL_h
29.628571
91
0.57136
aa03fc8bcf66c11a408c78afe857f76fc40ea6ce
1,227
c
C
SEC306/TD/TD4/tp-conteneurs_virtualisation_1/tp-mac/1-confine-that-shell/shell.c
uvsq-versailles/Master2_SeCReTS_Semestre1
82124b2377a50b9c261d841e314df110b01c9b62
[ "MIT" ]
1
2020-11-10T20:47:16.000Z
2020-11-10T20:47:16.000Z
SEC306/TD/TD4/tp-conteneurs_virtualisation_1/tp-mac/1-confine-that-shell/shell.c
uvsq-versailles/Master2_SeCReTS_Semestre1
82124b2377a50b9c261d841e314df110b01c9b62
[ "MIT" ]
null
null
null
SEC306/TD/TD4/tp-conteneurs_virtualisation_1/tp-mac/1-confine-that-shell/shell.c
uvsq-versailles/Master2_SeCReTS_Semestre1
82124b2377a50b9c261d841e314df110b01c9b62
[ "MIT" ]
null
null
null
#include <unistd.h> /* setuid, .. */ #include <sys/types.h> /* setuid, .. */ #include <grp.h> /* setgroups */ #include <stdio.h> /* perror */ int main (int argc, char** argv) { gid_t newGrp = 0; /** * if you installed programming manual pages, you can get the * man page for execve 'man execvp'. Same goes for all the * other system calls that we're using here. * */ /* this will tattoo the suid bit so that bash won't see that * we're not really root. we also drop all other memberships * just in case we're running with PAGs (in AFS) */ if (setuid(0) != 0) { perror("Setuid failed, no suid-bit set?"); return 1; } setgid(0); seteuid(0); setegid(0); /* we also drop all the groups that the old user had * (verify with id -tool afterwards) * this is not strictly necessary but we want to get rid of the * groups that the original user was part of. */ setgroups(1, &newGrp); /* load the default shell on top of this program * to exit from the shell, use 'exit' :-) */ execvp("/bin/sh", argv); return 0; }
30.675
76
0.554197
ebaf6515bab1f16f94c59c848bdf3977467eeb1e
543
h
C
yun2win/yun2win/Model/Y2WImageMessage.h
yun2win/yun2win-sdk-iOS
8001f3bf678edd5446b5710efaed5aedcaa33f3d
[ "MIT" ]
10
2016-05-12T02:01:49.000Z
2020-04-18T10:21:50.000Z
yun2win/yun2win/Model/Y2WImageMessage.h
yun2win/yun2win-sdk-iOS
8001f3bf678edd5446b5710efaed5aedcaa33f3d
[ "MIT" ]
1
2016-06-03T09:52:08.000Z
2016-06-03T09:52:08.000Z
yun2win/yun2win/Model/Y2WImageMessage.h
yun2win/yun2win-sdk-iOS
8001f3bf678edd5446b5710efaed5aedcaa33f3d
[ "MIT" ]
13
2016-03-29T02:00:33.000Z
2020-10-27T16:26:35.000Z
// // Y2WImageMessage.h // API // // Created by ShingHo on 16/4/7. // Copyright © 2016年 yun2win. All rights reserved. // #import "Y2WBaseMessage.h" @class Y2WAttachment; @interface Y2WImageMessage : Y2WBaseMessage @property (nonatomic, retain) Y2WAttachment *attachment; @property (nonatomic, copy) NSString *attachmentId; @property (nonatomic, copy) NSString *imagePath; @property (nonatomic, copy) NSString *imageUrl; @property (nonatomic, copy) NSString *thumImagePath; @property (nonatomic, copy) NSString *thumImageUrl; @end
20.111111
56
0.744015
6f5100245bdee7708bfbae437073328601503a12
1,190
h
C
src/api/dsl/Serde.h
Jwright707/nebula
3886855c00b8cda97dcb4cf4802a1ba9a3613238
[ "Apache-2.0" ]
null
null
null
src/api/dsl/Serde.h
Jwright707/nebula
3886855c00b8cda97dcb4cf4802a1ba9a3613238
[ "Apache-2.0" ]
null
null
null
src/api/dsl/Serde.h
Jwright707/nebula
3886855c00b8cda97dcb4cf4802a1ba9a3613238
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017-present Shawn Cao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Query.h" /** * Define serialization functions to ser/de expressions to be transferred through network bounds. */ namespace nebula { namespace api { namespace dsl { class Serde { public: // expression serde static std::string serialize(const Expression&); static std::shared_ptr<Expression> deserialize(const std::string&); // custom column object serde static std::string serialize(const std::vector<CustomColumn>&); static std::vector<CustomColumn> deserialize(const char*, size_t); }; } // namespace dsl } // namespace api } // namespace nebula
29.02439
97
0.736134
e452d35976647e4c5919561fb68d57e6dd596843
203
h
C
include/azgra/io/stream/buffer_source_type.h
theazgra/AzgraCppLibrary
ccc9ff75731d456882a72343bd53bd8e4c38b9e7
[ "BSL-1.0" ]
3
2019-09-17T17:54:33.000Z
2020-01-09T05:06:44.000Z
include/azgra/io/stream/buffer_source_type.h
theazgra/AzgraCppLibrary
ccc9ff75731d456882a72343bd53bd8e4c38b9e7
[ "BSL-1.0" ]
1
2019-09-18T17:01:54.000Z
2019-09-20T16:52:01.000Z
include/azgra/io/stream/buffer_source_type.h
theazgra/AzgraCppLibrary
ccc9ff75731d456882a72343bd53bd8e4c38b9e7
[ "BSL-1.0" ]
null
null
null
#pragma once namespace azgra::io::stream { enum BufferSourceType { BufferSourceType_Stream, BufferSourceType_Memory, BufferSourceType_NoSource }; } // namespace azgra
18.454545
33
0.674877
a535628a7111dc81fc605251d329e1415bc69dec
107,438
c
C
act.movement.c
rrebrick/Luminari-Source
b200a755354e3320130462dbfb9c783fd8c69271
[ "Unlicense" ]
null
null
null
act.movement.c
rrebrick/Luminari-Source
b200a755354e3320130462dbfb9c783fd8c69271
[ "Unlicense" ]
null
null
null
act.movement.c
rrebrick/Luminari-Source
b200a755354e3320130462dbfb9c783fd8c69271
[ "Unlicense" ]
null
null
null
/************************************************************************** * File: act.movement.c Part of LuminariMUD * * Usage: Movement commands, door handling, & sleep/rest/etc state. * * * * All rights reserved. See license complete information. * * * * Copyright (C) 1993, 94 by the Trustees of the Johns Hopkins University * * CircleMUD is based on DikuMUD, Copyright (C) 1990, 1991. * **************************************************************************/ #include "conf.h" #include "sysdep.h" #include "structs.h" #include "utils.h" #include "comm.h" #include "interpreter.h" #include "handler.h" #include "db.h" #include "spells.h" #include "house.h" #include "constants.h" #include "dg_scripts.h" #include "act.h" #include "fight.h" #include "oasis.h" /* for buildwalk */ #include "spec_procs.h" #include "mud_event.h" #include "hlquest.h" #include "mudlim.h" #include "wilderness.h" /* Wilderness! */ #include "actions.h" #include "traps.h" /* for check_traps() */ #include "spell_prep.h" #include "trails.h" #include "assign_wpn_armor.h" /* do_gen_door utility functions */ static int find_door(struct char_data *ch, const char *type, char *dir, const char *cmdname); static int has_key(struct char_data *ch, obj_vnum key); static void do_doorcmd(struct char_data *ch, struct obj_data *obj, int door, int scmd); static int ok_pick(struct char_data *ch, obj_vnum keynum, int pickproof, int scmd, int door); /***** start file body *****/ /* doorbash - unfinished */ /* ACMD(do_doorbash) { bool failure = FALSE; int door; struct room_direction_data *back = 0; int other_room; struct obj_data *obj = 0; if (!INN_FLAGGED(ch, INNATE_DOORBASH)) { send_to_char("But you are way too small to attempt that.\r\n", ch); return; } one_argument(argument, arg); if (!*arg) { send_to_char("Doorbash which direction?\r\n", ch); return; } door = search_block(arg, dirs, FALSE); if (door < 0) { send_to_char("That is not a direction!\r\n", ch); return; } if (!EXIT(ch, door) || EXIT_FLAGGED(EXIT(ch, door), EX_HIDDEN)) { send_to_char("There is nothing to doorbash in that direction.\r\n", ch); return; } if (!EXIT_FLAGGED(EXIT(ch, door), EX_CLOSED)) { send_to_char("But that direction does not need to be doorbashed.\r\n", ch); return; } if ((other_room = EXIT(ch, door)->to_room) != NOWHERE) { back = world[other_room].dir_option[rev_dir[door]]; if (back && back->to_room != ch->in_room) back = 0; } if (EXIT_FLAGGED(EXIT(ch, door), EX_PICKPROOF) || dice(1, 300) > GET_R_STR(ch) + GET_LEVEL(ch) || EXIT_FLAGGED(EXIT(ch, door), EX_LOCKED2) || EXIT_FLAGGED(EXIT(ch, door), EX_LOCKED3) ) failure = TRUE; act("$n charges straight into the door with $s entire body.", FALSE, ch, 0, 0, TO_ROOM); act("You throw your entire body at the door.", FALSE, ch, 0, 0, TO_CHAR); if (failure) { act("But it holds steady against the onslaught.", FALSE, ch, 0, 0, TO_ROOM); act("But it holds steady against the onslaught.", FALSE, ch, 0, 0, TO_CHAR); return; } act("and it shatters into a million pieces!!", FALSE, ch, 0, 0, TO_ROOM); act("and it shatters into a million pieces!!.", FALSE, ch, 0, 0, TO_CHAR); UNLOCK_DOOR(ch->in_room, obj, door); OPEN_DOOR(ch->in_room, obj, door); if (back) { UNLOCK_DOOR(other_room, obj, rev_dir[door]); OPEN_DOOR(other_room, obj, rev_dir[door]); REMOVE_BIT(back->exit_info, EX_HIDDEN); } WAIT_STATE(ch, 1 * PULSE_VIOLENCE); check_trap(ch, TRAP_TYPE_OPEN_DOOR, ch->in_room, 0, door); return; } */ /* checks if target ch is first-in-line in singlefile room */ bool is_top_of_room_for_singlefile(struct char_data *ch, int dir) { bool exit = FALSE; int i; for (i = 0; i < 6; i++) { if (EXIT(ch, i)) { if (exit == FALSE && dir == i) return TRUE; exit = TRUE; } } return FALSE; } /* function to find which char is ahead of the next in a singlefile room */ struct char_data *get_char_ahead_of_me(struct char_data *ch, int dir) { struct char_data *tmp; if (is_top_of_room_for_singlefile(ch, dir)) { tmp = world[ch->in_room].people; while (tmp) { if (tmp->next_in_room == ch) return tmp; tmp = tmp->next_in_room; } return 0; } return ch->next_in_room; } /* falling system */ /* TODO objects */ /* this function will check whether a obj should fall or not based on circumstances and whether the obj is floating */ bool obj_should_fall(struct obj_data *obj) { int falling = FALSE; if (!obj) return FALSE; if (ROOM_FLAGGED(obj->in_room, ROOM_FLY_NEEDED) && EXIT_OBJ(obj, DOWN)) falling = TRUE; if (OBJ_FLAGGED(obj, ITEM_FLOAT)) { act("You watch as $p floats gracefully in the air!", FALSE, 0, obj, 0, TO_ROOM); return FALSE; } return falling; } /* this function will check whether a char should fall or not based on circumstances and whether the ch is flying / levitate */ bool char_should_fall(struct char_data *ch, bool silent) { int falling = FALSE; if (!ch) return FALSE; if (IN_ROOM(ch) == NOWHERE) return FALSE; if (ROOM_FLAGGED(IN_ROOM(ch), ROOM_FLY_NEEDED) && EXIT(ch, DOWN)) falling = TRUE; if (RIDING(ch) && is_flying(RIDING(ch))) { if (!silent) send_to_char(ch, "Your mount flies gracefully through the air...\r\n"); return FALSE; } if (is_flying(ch)) { if (!silent) send_to_char(ch, "You fly gracefully through the air...\r\n"); return FALSE; } if (AFF_FLAGGED(ch, AFF_LEVITATE)) { if (!silent) send_to_char(ch, "You levitate above the ground...\r\n"); return FALSE; } return falling; } EVENTFUNC(event_falling) { struct mud_event_data *pMudEvent = NULL; struct char_data *ch = NULL; int height_fallen = 0; char buf[50] = {'\0'}; /* This is just a dummy check, but we'll do it anyway */ if (event_obj == NULL) return 0; /* For the sake of simplicity, we will place the event data in easily * referenced pointers */ pMudEvent = (struct mud_event_data *)event_obj; /* nab char data */ ch = (struct char_data *)pMudEvent->pStruct; /* dummy checks */ if (!ch) return 0; if (!IS_NPC(ch) && !IS_PLAYING(ch->desc)) return 0; /* retrieve svariables and convert it */ height_fallen += atoi((char *)pMudEvent->sVariables); send_to_char(ch, "AIYEE!!! You have fallen %d feet!\r\n", height_fallen); /* already checked if there is a down exit, lets move the char down */ do_simple_move(ch, DOWN, FALSE); send_to_char(ch, "You fall into a new area!\r\n"); act("$n appears from above, arms flailing helplessly as $e falls...", FALSE, ch, 0, 0, TO_ROOM); height_fallen += 20; // 20 feet per room right now /* can we continue this fall? */ if (!ROOM_FLAGGED(ch->in_room, ROOM_FLY_NEEDED) || !CAN_GO(ch, DOWN)) { if (AFF_FLAGGED(ch, AFF_SAFEFALL)) { send_to_char(ch, "Moments before slamming into the ground, a 'safefall'" " enchantment stops you!\r\n"); act("Moments before $n slams into the ground, some sort of magical force" " stops $s from the impact.", FALSE, ch, 0, 0, TO_ROOM); REMOVE_BIT_AR(AFF_FLAGS(ch), AFF_SAFEFALL); return 0; } /* potential damage */ int dam = dice((height_fallen / 5), 6) + 20; /* check for slow-fall! */ if (!IS_NPC(ch) && HAS_FEAT(ch, FEAT_SLOW_FALL)) { dam -= 21; dam -= dice((HAS_FEAT(ch, FEAT_SLOW_FALL) * 4), 6); } if (dam <= 0) { /* woo! avoided damage */ send_to_char(ch, "You gracefully land on your feet from your perilous fall!\r\n"); act("$n comes falling in from above, but at the last minute, pulls of an acrobatic flip and lands gracefully on $s feet!", FALSE, ch, 0, 0, TO_ROOM); return 0; //end event } else { /* ok we know damage is going to be suffered at this stage */ send_to_char(ch, "You fall headfirst to the ground! OUCH!\r\n"); act("$n crashes into the ground headfirst, OUCH!", FALSE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RECLINING); start_action_cooldown(ch, atSTANDARD, 12 RL_SEC); /* we have a special situation if you die, the event will get cleared */ if (dam >= GET_HIT(ch) + 9) { GET_HIT(ch) = -999; send_to_char(ch, "You attempt to scream in horror as your skull slams " "into the ground, the very brief sensation of absolute pain " "strikes you as all your upper-body bones shatter and your " "head splatters all over the area!\r\n"); act("$n attempts to scream in horror as $s skull slams " "into the ground. There is the sound like the cracking of a " "ripe melon. You watch as all of $s upper-body bones shatter and $s " "head splatters all over the area!\r\n", FALSE, ch, 0, 0, TO_ROOM); return 0; } else { damage(ch, ch, dam, TYPE_UNDEFINED, DAM_FORCE, FALSE); return 0; //end event } } } /* hitting ground or fixing your falling situation is the only way to stop * this event :P * theoritically the player now could try to cast a spell, use an item, hop * on a mount to fix his falling situation, so we gotta check if he's still * falling every event call * */ if (char_should_fall(ch, FALSE)) { send_to_char(ch, "You fall tumbling down!\r\n"); act("$n drops from sight.", FALSE, ch, 0, 0, TO_ROOM); /* are we falling more? then we gotta increase the heigh fallen */ snprintf(buf, sizeof(buf), "%d", height_fallen); /* Need to free the memory, if we are going to change it. */ if (pMudEvent->sVariables) free(pMudEvent->sVariables); pMudEvent->sVariables = strdup(buf); return (1 * PASSES_PER_SEC); } else { // stop falling! send_to_char(ch, "You put a stop to your fall!\r\n"); act("$n turns on the air-brakes from a plummet!", FALSE, ch, 0, 0, TO_ROOM); return 0; } return 0; } /* END falling system */ /* simple function to determine if char can walk on water (or swim through it )*/ int has_boat(struct char_data *ch, room_rnum going_to) { struct obj_data *obj; int i; if (GET_LEVEL(ch) >= LVL_IMMORT) return (1); if (AFF_FLAGGED(ch, AFF_WATERWALK) || is_flying(ch) || AFF_FLAGGED(ch, AFF_LEVITATE)) return (1); /* non-wearable boats in inventory will do it */ for (obj = ch->carrying; obj; obj = obj->next_content) if (GET_OBJ_TYPE(obj) == ITEM_BOAT && (find_eq_pos(ch, obj, NULL) < 0)) return (1); /* and any boat you're wearing will do it too */ for (i = 0; i < NUM_WEARS; i++) if (GET_EQ(ch, i) && GET_OBJ_TYPE(GET_EQ(ch, i)) == ITEM_BOAT) return (1); // they can't swim here, so no need for a skill check. if (SECT(going_to) == SECT_WATER_NOSWIM || SECT(going_to) == SECT_UD_WATER_NOSWIM || SECT(going_to) == SECT_UD_NOSWIM) return 0; /* we should do a swim check now */ int swim_dc = 13 + ZONE_MINLVL(GET_ROOM_ZONE(going_to)); send_to_char(ch, "Swim DC: %d - ", swim_dc); if (!skill_check(ch, ABILITY_SWIM, swim_dc)) { send_to_char(ch, "You attempt to swim, but fail!\r\n"); USE_MOVE_ACTION(ch); return 0; } else { /*success!*/ send_to_char(ch, "You successfully swim!: "); return 1; } return (0); } /* Simple function to determine if char can fly. */ int has_flight(struct char_data *ch) { struct obj_data *obj; int i; if (GET_LEVEL(ch) >= LVL_IMMORT) return (1); if (is_flying(ch)) return (1); /* Non-wearable flying items in inventory will do it. */ for (obj = ch->carrying; obj; obj = obj->next_content) if (OBJAFF_FLAGGED(obj, AFF_FLYING) && (find_eq_pos(ch, obj, NULL) < 0)) return (1); /* Any equipped objects with AFF_FLYING will do it too. */ for (i = 0; i < NUM_WEARS; i++) if (GET_EQ(ch, i) && OBJAFF_FLAGGED(GET_EQ(ch, i), AFF_FLYING)) return (1); return (0); } /* Simple function to determine if char can scuba. */ int has_scuba(struct char_data *ch, room_rnum destination) { struct obj_data *obj; int i; if (GET_LEVEL(ch) >= LVL_IMMORT) return (1); if (AFF_FLAGGED(ch, AFF_SCUBA)) return (1); /* Non-wearable scuba items in inventory will do it. */ for (obj = ch->carrying; obj; obj = obj->next_content) if (OBJAFF_FLAGGED(obj, AFF_SCUBA) && (find_eq_pos(ch, obj, NULL) < 0)) return (1); /* Any equipped objects with AFF_SCUBA will do it too. */ for (i = 0; i < NUM_WEARS; i++) if (GET_EQ(ch, i) && OBJAFF_FLAGGED(GET_EQ(ch, i), AFF_SCUBA)) return (1); if (IS_SET_AR(ROOM_FLAGS(destination), ROOM_AIRY)) return (1); return (0); } /* Simple function to determine if char can climb */ int can_climb(struct char_data *ch) { struct obj_data *obj; int i; if (GET_LEVEL(ch) >= LVL_IMMORT) return (1); if (has_flight(ch)) return 1; if (AFF_FLAGGED(ch, AFF_CLIMB)) return (1); /* Non-wearable 'climb' items in inventory will do it. */ for (obj = ch->carrying; obj; obj = obj->next_content) if (OBJAFF_FLAGGED(obj, AFF_CLIMB) && (find_eq_pos(ch, obj, NULL) < 0)) return (1); /* Any equipped objects with AFF_CLIMB will do it too. */ for (i = 0; i < NUM_WEARS; i++) if (GET_EQ(ch, i) && OBJAFF_FLAGGED(GET_EQ(ch, i), AFF_CLIMB)) return (1); return (0); } /** Leave tracks in the current room * */ #define TRACKS_UNDEFINED 0 #define TRACKS_IN 1 #define TRACKS_OUT 2 #define DIR_NONE -1 void create_tracks(struct char_data *ch, int dir, int flag) { struct room_data *room = NULL; struct trail_data *cur = NULL; struct trail_data *prev = NULL; struct trail_data *new_trail = NULL; if (IN_ROOM(ch) != NOWHERE) { room = &world[ch->in_room]; } else { log("SYSERR: Char at location NOWHERE trying to create tracks."); return; } /* Here we create the track structure, set the values and assign it to the room. At the same time, we can prune off any really old trails. Threshold is set, in seconds, in trails.h. Eventually this cna be adjusted based on weather - rain/show/wind can all obscure trails. */ CREATE(new_trail, struct trail_data, 1); new_trail->name = strdup(GET_NAME(ch)); new_trail->race = (IS_NPC(ch) ? strdup(race_family_types[GET_NPC_RACE(ch)]) : strdup(race_list[GET_RACE(ch)].name)); new_trail->from = (flag == TRACKS_IN ? dir : DIR_NONE); new_trail->to = (flag == TRACKS_OUT ? dir : DIR_NONE); new_trail->age = time(NULL); new_trail->next = room->trail_tracks->head; new_trail->prev = NULL; if (new_trail->next != NULL) { room->trail_tracks->head->prev = new_trail; } room->trail_tracks->head = new_trail; prev = NULL; for (cur = room->trail_tracks->head; cur != NULL; cur = cur->next) { if (time(NULL) - cur->age >= TRAIL_PRUNING_THRESHOLD) { if (prev != NULL) { //if (prev->next != NULL) DISPOSE(prev->next); prev->next = cur->next; if (cur->next != NULL) { cur->next->prev = prev; } } else { room->trail_tracks->head = cur->next; if (cur->next != NULL) { //if (cur->next->prev != NULL) DISPOSE(cur->next->prev); cur->next->prev = NULL; } } } prev = cur; } /* struct trail_data_list *trail_scent; struct trail_data_list *trail_blood; */ } /** Move a PC/NPC character from their current location to a new location. This * is the standard movement locomotion function that all normal walking * movement by characters should be sent through. This function also defines * the move cost of normal locomotion as: * ( (move cost for source room) + (move cost for destination) ) / 2 * * @pre Function assumes that ch has no master controlling character, that * ch has no followers (in other words followers won't be moved by this * function) and that the direction traveled in is one of the valid, enumerated * direction. * @param ch The character structure to attempt to move. * @param dir The defined direction (NORTH, SOUTH, etc...) to attempt to * move into. * @param need_specials_check If TRUE will cause * @retval int 1 for a successful move (ch is now in a new location) * or 0 for a failed move (ch is still in the original location). */ int do_simple_move(struct char_data *ch, int dir, int need_specials_check) { /* Begin Local variable definitions */ /*---------------------------------------------------------------------*/ /* Used in our special proc check. By default, we pass a NULL argument * when checking for specials */ char spec_proc_args[MAX_INPUT_LENGTH] = {'\0'}; /* The room the character is currently in and will move from... */ room_rnum was_in = NOWHERE; /* ... and the room the character will move into. */ room_rnum going_to = NOWHERE; /* How many movement points are required to travel from was_in to going_to. * We redefine this later when we need it. */ int need_movement = 0; /* used for looping the room for sneak-checks */ struct char_data *tch = NULL, *next_tch = NULL; // for mount code int same_room = 0, riding = 0, ridden_by = 0; /* extra buffers */ char buf2[MAX_STRING_LENGTH] = {'\0'}; // char buf3[MAX_STRING_LENGTH] = {'\0'}; /* singlefile variables */ struct char_data *other; struct char_data **prev; bool was_top = TRUE; /* Wilderness variables */ int new_x = 0, new_y = 0; /* added some dummy checks to deal with a fairly mysterious crash */ if (!ch) return 0; if (IN_ROOM(ch) == NOWHERE) return 0; if (dir < 0 || dir >= NUM_OF_DIRS) return 0; /* dummy check, if you teleport while in a falling event, BOOM otherwise :P */ if (!EXIT(ch, dir)) return 0; /* The following is to support the wilderness code. */ if (ZONE_FLAGGED(GET_ROOM_ZONE(IN_ROOM(ch)), ZONE_WILDERNESS) && (EXIT(ch, dir)->to_room == real_room(1000000))) { new_x = X_LOC(ch); //world[IN_ROOM(ch)].coords[0]; new_y = Y_LOC(ch); //world[IN_ROOM(ch)].coords[1]; /* This is a wilderness movement! Find out which coordinates we need * to check, based on the dir and local coordinates. */ switch (dir) { case NORTH: new_y++; break; case SOUTH: new_y--; break; case EAST: new_x++; break; case WEST: new_x--; break; default: /* Bad direction for wilderness travel.*/ return 0; } going_to = find_room_by_coordinates(new_x, new_y); if (going_to == NOWHERE) { going_to = find_available_wilderness_room(); if (going_to == NOWHERE) { log("SYSERR: Wilderness movement failed from (%d, %d) to (%d, %d)", X_LOC(ch), Y_LOC(ch), new_x, new_y); return 0; } /* Must set the coords, etc in the going_to room. */ assign_wilderness_room(going_to, new_x, new_y); } } else if (world[IN_ROOM(ch)].dir_option[dir]) { going_to = EXIT(ch, dir)->to_room; /* Since we are in non-wilderness moving to wilderness, set up the coords. */ if (ZONE_FLAGGED(GET_ROOM_ZONE(going_to), ZONE_WILDERNESS)) { new_x = world[going_to].coords[0]; new_y = world[going_to].coords[1]; } } if (going_to == NOWHERE) return 0; was_in = IN_ROOM(ch); /* end dummy checks */ /*---------------------------------------------------------------------*/ /* End Local variable definitions */ /* Begin checks that can prevent a character from leaving the was_in room. */ /* Future checks should be implemented within this section and return 0. */ /*---------------------------------------------------------------------*/ /* Check for special routines that might activate because of the move and * also might prevent the movement. Special requires commands, so we pass * in the "command" equivalent of the direction (ie. North is '1' in the * command list, but NORTH is defined as '0'). * Note -- only check if following; this avoids 'double spec-proc' bug */ if (need_specials_check && special(ch, dir + 1, spec_proc_args)) return 0; /* Leave Trigger Checks: Does a leave trigger block exit from the room? */ /* next 3 if blocks prevent teleport crashes */ if (!leave_mtrigger(ch, dir) || IN_ROOM(ch) != was_in) return 0; if (!leave_wtrigger(&world[IN_ROOM(ch)], ch, dir) || IN_ROOM(ch) != was_in) return 0; if (!leave_otrigger(&world[IN_ROOM(ch)], ch, dir) || IN_ROOM(ch) != was_in) return 0; if (AFF_FLAGGED(ch, AFF_GRAPPLED) || AFF_FLAGGED(ch, AFF_ENTANGLED)) { send_to_char(ch, "You struggle to move but you are unable to leave the area!\r\n"); act("$n struggles to move, but can't!", FALSE, ch, 0, 0, TO_ROOM); return 0; } if (affected_by_spell(ch, SKILL_DEFENSIVE_STANCE) && !HAS_FEAT(ch, FEAT_MOBILE_DEFENSE)) { send_to_char(ch, "You can't move while in defensive stance!\r\n"); return 0; } /* check if they're mounted */ if (RIDING(ch)) riding = 1; if (RIDDEN_BY(ch)) ridden_by = 1; /* if they're mounted, are they in the same room w/ their mount(ee)? */ if (riding && RIDING(ch)->in_room == ch->in_room) same_room = 1; else if (ridden_by && RIDDEN_BY(ch)->in_room == ch->in_room) same_room = 1; /* tamed mobiles cannot move about */ if (ridden_by && same_room && AFF_FLAGGED(ch, AFF_TAMED)) { send_to_char(ch, "You've been tamed. Now act it!\r\n"); return 0; } /* begin singlefile mechanic */ if (ROOM_FLAGGED(ch->in_room, ROOM_SINGLEFILE)) { other = get_char_ahead_of_me(ch, dir); if (other && RIDING(other) != ch && RIDDEN_BY(other) != ch) { if (GET_POS(other) == POS_RECLINING) { was_top = is_top_of_room_for_singlefile(ch, dir); prev = &world[ch->in_room].people; while (*prev) { if (*prev == ch) { *prev = ch->next_in_room; ch->next_in_room = 0; } if (*prev) prev = &((*prev)->next_in_room); } prev = &world[ch->in_room].people; if (was_top) { while (*prev) { if (*prev == other) { *prev = ch; ch->next_in_room = other; } prev = &((*prev)->next_in_room); } } else { ch->next_in_room = other->next_in_room; other->next_in_room = ch; } act("You squeeze by the prone body of $N.", FALSE, ch, 0, other, TO_CHAR); act("$n squeezes by YOU.", FALSE, ch, 0, other, TO_VICT); act("$n squeezes by the prone body of $N.", FALSE, ch, 0, other, TO_NOTVICT); return 0; } else if (GET_POS(ch) == POS_RECLINING && GET_POS(other) >= POS_FIGHTING && FIGHTING(ch) != other && FIGHTING(other) != ch) { was_top = is_top_of_room_for_singlefile(ch, dir); prev = &world[ch->in_room].people; while (*prev) { if (*prev == ch) { *prev = ch->next_in_room; ch->next_in_room = 0; } if (*prev) prev = &((*prev)->next_in_room); } prev = &world[ch->in_room].people; if (was_top) { while (*prev) { if (*prev == other) { *prev = ch; ch->next_in_room = other; } prev = &((*prev)->next_in_room); } } else { ch->next_in_room = other->next_in_room; other->next_in_room = ch; } act("You crawl by $N.", FALSE, ch, 0, other, TO_CHAR); act("$n crawls by YOU.", FALSE, ch, 0, other, TO_VICT); act("$n crawls by $N.", FALSE, ch, 0, other, TO_NOTVICT); return 0; } else { act("You bump into $N.", FALSE, ch, 0, other, TO_CHAR); return 0; } } } /* end singlefile mechanic */ /* Charm effect: Does it override the movement? for now it is cut out of the code */ // dummy check if (going_to == NOWHERE) return 0; /* druid spell */ if (IS_EVIL(ch) && IS_HOLY(going_to)) { send_to_char(ch, "The sanctity of the area prevents " "you from entering.\r\n"); return 0; } if (IS_GOOD(ch) && IS_UNHOLY(going_to)) { send_to_char(ch, "The corruption of the area prevents " "you from entering.\r\n"); return 0; } /* Water, No Swimming Rooms: Does the deep water prevent movement? */ if ((SECT(was_in) == SECT_WATER_NOSWIM) || (SECT(was_in) == SECT_UD_NOSWIM) || (SECT(going_to) == SECT_WATER_NOSWIM) || (SECT(going_to) == SECT_UD_NOSWIM)) { if ((riding && !has_boat(RIDING(ch), going_to)) || !has_boat(ch, going_to)) { send_to_char(ch, "You need a boat to go there.\r\n"); return (0); } } if (SECT(was_in) == SECT_WATER_SWIM || SECT(was_in) == SECT_UD_WATER || SECT(was_in) == SECT_UNDERWATER || SECT(going_to) == SECT_WATER_SWIM || SECT(going_to) == SECT_UD_WATER || SECT(going_to) == SECT_UNDERWATER) { if ((riding && !has_boat(RIDING(ch), going_to)) || !has_boat(ch, going_to)) { if (GET_MOVE(ch) < 20) { send_to_char(ch, "You don't have the energy to try and swim there.\r\n"); return 0; } send_to_char(ch, "You try to swim there, but fail.\r\n"); GET_MOVE(ch) -= 20; return (0); } } /* Flying Required: Does lack of flying prevent movement? */ if ((SECT(was_in) == SECT_FLYING) || (SECT(going_to) == SECT_FLYING) || (SECT(was_in) == SECT_UD_NOGROUND) || (SECT(going_to) == SECT_UD_NOGROUND)) { if (char_has_mud_event(ch, eFALLING)) ; /* zusuk's cheesy falling code */ else if ((riding && !has_flight(RIDING(ch))) || !has_flight(ch)) { send_to_char(ch, "You need to be flying to go there!\r\n"); return (0); } } /* Underwater Room: Does lack of underwater breathing prevent movement? */ if ((SECT(was_in) == SECT_UNDERWATER) || (SECT(going_to) == SECT_UNDERWATER)) { if (!has_scuba(ch, going_to) && (!IS_NPC(ch) && !PRF_FLAGGED(ch, PRF_NOHASSLE))) { send_to_char(ch, "You need to be able to breathe water to go there!\r\n"); return (0); } } /* High Mountain (and any other climb rooms) */ if ((SECT(was_in) == SECT_HIGH_MOUNTAIN) || (SECT(going_to) == SECT_HIGH_MOUNTAIN)) { if ((riding && !can_climb(RIDING(ch))) || !can_climb(ch)) { send_to_char(ch, "You need to be able to climb to go there!\r\n"); return (0); } } /* Ocean restriction */ if (SECT(was_in) == SECT_OCEAN || SECT(going_to) == SECT_OCEAN) { if (!IS_NPC(ch) && !PRF_FLAGGED(ch, PRF_NOHASSLE)) { send_to_char(ch, "You need an ocean-ready ship to go there!\r\n"); return (0); } } /* flight restricted to enter that room */ if (ROOM_FLAGGED(going_to, ROOM_NOFLY) && is_flying(ch)) { send_to_char(ch, "It is not possible to fly in that direction\r\n"); return 0; } /* size restricted to enter that room */ if (ROOM_FLAGGED(going_to, ROOM_SIZE_TINY) && GET_SIZE(ch) > SIZE_TINY) { send_to_char(ch, "You'd have to be tiny or smaller to go there.\r\n"); return 0; } if (ROOM_FLAGGED(going_to, ROOM_SIZE_DIMINUTIVE) && GET_SIZE(ch) > SIZE_DIMINUTIVE) { send_to_char(ch, "You'd have to be diminutive or smaller to go there.\r\n"); return 0; } /* Houses: Can the player walk into the house? */ if (ROOM_FLAGGED(was_in, ROOM_ATRIUM)) { if (!House_can_enter(ch, GET_ROOM_VNUM(going_to))) { send_to_char(ch, "That's private property -- no trespassing!\r\n"); return (0); } } /* Check zone flag restrictions */ if (ZONE_FLAGGED(GET_ROOM_ZONE(going_to), ZONE_CLOSED)) { send_to_char(ch, "A mysterious barrier forces you back! That area is " "off-limits.\r\n"); return (0); } if (ZONE_FLAGGED(GET_ROOM_ZONE(going_to), ZONE_NOIMMORT) && (GET_LEVEL(ch) >= LVL_IMMORT) && (GET_LEVEL(ch) < LVL_GRSTAFF)) { send_to_char(ch, "A mysterious barrier forces you back! That area is off-limits.\r\n"); return (0); } /* Room Size Capacity: Is the room full of people already? */ if (riding && ROOM_FLAGGED(going_to, ROOM_TUNNEL)) { send_to_char(ch, "There isn't enough space to enter mounted!\r\n"); return 0; } if (ROOM_FLAGGED(going_to, ROOM_TUNNEL) && num_pc_in_room(&(world[going_to])) >= CONFIG_TUNNEL_SIZE) { if (CONFIG_TUNNEL_SIZE > 1) send_to_char(ch, "There isn't enough room for you to go there!\r\n"); else send_to_char(ch, "There isn't enough room there for more than" " one person!\r\n"); return (0); } /* Room Level Requirements: Is ch privileged enough to enter the room? */ if (ROOM_FLAGGED(going_to, ROOM_STAFFROOM) && GET_LEVEL(ch) < LVL_STAFF) { send_to_char(ch, "You aren't godly enough to use that room!\r\n"); return (0); } /* climb is needed to get to going_to, skill required is based on min-level of zone */ if (ROOM_FLAGGED(going_to, ROOM_CLIMB_NEEDED)) { /* do a climb check */ int climb_dc = 13 + ZONE_MINLVL(GET_ROOM_ZONE(going_to)); send_to_char(ch, "Climb DC: %d - ", climb_dc); if (!skill_check(ch, ABILITY_CLIMB, climb_dc)) { send_to_char(ch, "You attempt to climb to that area, but fall and get hurt!\r\n"); damage((ch), (ch), dice(climb_dc - 10, 4), -1, -1, -1); update_pos(ch); return 0; } else { /*success!*/ send_to_char(ch, "You successfully climb!: "); } } /* check for traps (leave room) */ check_trap(ch, TRAP_TYPE_LEAVE_ROOM, ch->in_room, 0, 0); /* check for magical walls, such as wall of force (also death from wall damage) */ if (check_wall(ch, dir)) /* true = wall stopped ch somehow */ return (0); /* a silly zusuk dummy check */ update_pos(ch); if (GET_POS(ch) <= POS_STUNNED) { send_to_char(ch, "You are in no condition to move!\r\n"); return (0); } /* Check zone level recommendations */ if (GET_LEVEL(ch) <= NEWBIE_LEVEL && (ZONE_MINLVL(GET_ROOM_ZONE(going_to)) != -1) && ZONE_MINLVL(GET_ROOM_ZONE(going_to)) > GET_LEVEL(ch)) { send_to_char(ch, "(OOC) This zone is above your recommended level.\r\n"); } //acrobatics check /* for now acrobatics check disabled */ /************************************* int cantFlee = 0; if (affected_by_spell(ch, SPELL_EXPEDITIOUS_RETREAT)) cantFlee--; if (affected_by_spell(ch, SPELL_GREASE)) cantFlee++; if (need_specials_check == 3 && GET_POS(ch) > POS_DEAD && FIGHTING(ch) && IN_ROOM(ch) == IN_ROOM(FIGHTING(ch)) && cantFlee >= 0) { //able to flee away with acrobatics check? if (!IS_NPC(ch)) { //player if (((HAS_FEAT(ch, FEAT_MOBILITY)) || (HAS_FEAT(ch, FEAT_ENHANCED_MOBILITY)) || dice(1, 20) + compute_ability(ch, ABILITY_ACROBATICS) > 15) && cantFlee <= 0) { send_to_char(ch, "\tW*Acrobatics Success\tn*"); send_to_char(FIGHTING(ch), "\tR*Opp Acrobatics Success*\tn"); } else { // failed send_to_char(ch, "\tR*Acrobatics Fail\tn*"); send_to_char(FIGHTING(ch), "\tW*Opp Acrobatics Fail*\tn"); return 0; } //npc } else { if (dice(1, 20) > 10 && cantFlee <= 0) { send_to_char(ch, "\tW*Acrobatics Success\tn*"); send_to_char(FIGHTING(ch), "\tR*Opp Acrobatics Success*\tn"); } else { // failed send_to_char(ch, "\tR*Acrobatics Fail\tn*"); send_to_char(FIGHTING(ch), "\tW*Opp Acrobatics Fail*\tn"); return 0; } } } *****************************/ /* fleeing: no retreat feat offers free AOO */ if (need_specials_check == 3 && GET_POS(ch) > POS_DEAD) { /* loop room */ struct char_data *tch, *next_tch; for (tch = world[IN_ROOM(ch)].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* next value in linked list */ if (FIGHTING(tch) && FIGHTING(tch) == ch && HAS_FEAT(tch, FEAT_NO_RETREAT)) { attack_of_opportunity(tch, ch, 4); } } } /* All checks passed, nothing will prevent movement now other than lack of * move points. */ /* move points needed is avg. move loss for src and destination sect type */ need_movement = (movement_loss[SECT(was_in)] + movement_loss[SECT(going_to)]) / 2; if (!IS_NPC(ch) && HAS_FEAT(ch, FEAT_FAST_MOVEMENT)) need_movement--; /* if in "spot-mode" double cost of movement */ if (AFF_FLAGGED(ch, AFF_SPOT)) need_movement *= 2; /* if in "listen-mode" double cost of movement */ if (AFF_FLAGGED(ch, AFF_LISTEN)) need_movement *= 2; /* if reclined quadruple movement cost */ if (GET_POS(ch) <= POS_RECLINING) need_movement *= 4; // new movement system requires we multiply this need_movement *= 10; // Now let's reduce based on skills, since this can // be a fraction of 10. int skill_bonus = skill_roll(ch, riding ? MAX(ABILITY_RIDE, ABILITY_SURVIVAL) : ABILITY_SURVIVAL); if (SECT(going_to) == SECT_HILLS || SECT(going_to) == SECT_MOUNTAIN || SECT(going_to) == SECT_HIGH_MOUNTAIN) skill_bonus += skill_roll(ch, ABILITY_CLIMB) / 2; need_movement -= skill_bonus; // we're using a base speed of 30. If it's 30, then speed won't have an effect on // movement. If the speed is less than 30, it'll cost more movement. If it's more // it will reduce the movement points required. // if we're mounted, we'll use the mount's speed instead. int speed_mod = get_speed(riding ? RIDING(ch) : ch, FALSE); speed_mod = speed_mod - 30; need_movement -= speed_mod; // regardless of bonuses, we'll never use less than 10 moves per room need_movement = MAX(10, need_movement); /* Move Point Requirement Check */ if (riding) { /* do NOT touch this until we re-evaluate the movement system and NPC movements points -zusuk */ need_movement = 0; /*if (GET_MOVE(RIDING(ch)) < need_movement) { send_to_char(ch, "Your mount is too exhausted.\r\n"); return 0; }*/ } else { if (GET_MOVE(ch) < need_movement && !IS_NPC(ch)) { if (need_specials_check && ch->master) send_to_char(ch, "You are too exhausted to follow.\r\n"); else send_to_char(ch, "You are too exhausted.\r\n"); return (0); } } /* chance of being thrown off mount */ if (riding && (compute_ability(ch, ABILITY_RIDE) + dice(1, 20)) < rand_number(1, GET_LEVEL(RIDING(ch))) - rand_number(-4, need_movement)) { act("$N rears backwards, throwing you to the ground.", FALSE, ch, 0, RIDING(ch), TO_CHAR); act("You rear backwards, throwing $n to the ground.", FALSE, ch, 0, RIDING(ch), TO_VICT); act("$N rears backwards, throwing $n to the ground.", FALSE, ch, 0, RIDING(ch), TO_NOTVICT); dismount_char(ch); damage(ch, ch, dice(1, 6), -1, -1, -1); return 0; } /*---------------------------------------------------------------------*/ /* End checks that can prevent a character from leaving the was_in room. */ /* Begin: the leave operation. */ /*---------------------------------------------------------------------*/ if (GET_LEVEL(ch) < LVL_IMMORT && !IS_NPC(ch) && !(riding || ridden_by)) GET_MOVE(ch) -= need_movement; /* artificial inflation of mount movement points */ else if (riding && !rand_number(0, 9)) GET_MOVE(RIDING(ch)) -= need_movement; else if (ridden_by) GET_MOVE(RIDDEN_BY(ch)) -= need_movement; /*****/ /* Generate the leave message(s) and display to others in the was_in room. */ /*****/ /* silly to keep people reclining when they leave a room */ /* actually this mechanic is a necessary one, single file room code, sorry folks -zusuk */ /* if (GET_POS(ch) == POS_RECLINING) { send_to_char(ch, "You move from a crawling position to standing as you leave the area.\r\n"); change_position(ch, POS_STANDING); } */ /* scenario: mounted char */ if (riding) { /* riding, mount is -not- attempting to sneak */ if (!IS_AFFECTED(RIDING(ch), AFF_SNEAK)) { /* character is attempting to sneak (mount is not) */ if (IS_AFFECTED(ch, AFF_SNEAK)) { /* we know the player is trying to sneak, we have to do the sneak-check with all the observers in the room */ for (tch = world[IN_ROOM(ch)].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip self and mount of course */ if (tch == ch || tch == RIDING(ch)) continue; /* sneak versus listen check */ if (!can_hear_sneaking(tch, ch)) { /* message: mount not sneaking, rider is sneaking */ snprintf(buf2, sizeof(buf2), "$n leaves %s.", dirs[dir]); act(buf2, TRUE, RIDING(ch), 0, tch, TO_VICT); } else { /* rider detected ! */ snprintf(buf2, sizeof(buf2), "$n rides %s %s.", GET_NAME(RIDING(ch)), dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_VICT); } } /* character is -not- attempting to sneak (mount not too) */ } else { snprintf(buf2, sizeof(buf2), "$n rides $N %s.", dirs[dir]); act(buf2, TRUE, ch, 0, RIDING(ch), TO_NOTVICT); } } /* riding, mount -is- attempting to sneak, if succesful, the whole * "package" is sneaking, if not ch might be able to sneak still */ else { if (!IS_AFFECTED(ch, AFF_SNEAK)) { /* we know the mount (and not ch) is trying to sneak, we have to do the sneak-check with all the observers in the room */ for (tch = world[IN_ROOM(RIDING(ch))].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip self (mount) of course and ch */ if (tch == RIDING(ch) || tch == ch) continue; /* sneak versus listen check */ if (can_hear_sneaking(tch, RIDING(ch))) { /* mount detected! */ snprintf(buf2, sizeof(buf2), "$n rides %s %s.", GET_NAME(RIDING(ch)), dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_VICT); } /* if we pass this check, the rider/mount are both sneaking */ } } /* ch is still trying to sneak (mount too) */ else { /* we know the mount (and ch) is trying to sneak, we have to do the sneak-check with all the observers in the room, mount * success in this case is free pass for sneak */ for (tch = world[IN_ROOM(RIDING(ch))].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip self (mount) of course, skipping ch too */ if (tch == RIDING(ch) || tch == ch) continue; /* sneak versus listen check */ if (!can_hear_sneaking(tch, RIDING(ch))) { /* mount success! "package" is sneaking */ } else if (!can_hear_sneaking(tch, ch)) { /* mount failed, player succeeded */ /* message: mount not sneaking, rider is sneaking */ snprintf(buf2, sizeof(buf2), "$n leaves %s.", dirs[dir]); act(buf2, TRUE, RIDING(ch), 0, tch, TO_VICT); } else { /* mount failed, player failed */ snprintf(buf2, sizeof(buf2), "$n rides %s %s.", GET_NAME(RIDING(ch)), dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_VICT); } } } } /* message to self */ send_to_char(ch, "You ride %s %s.\r\n", GET_NAME(RIDING(ch)), dirs[dir]); /* message to mount */ send_to_char(RIDING(ch), "You carry %s %s.\r\n", GET_NAME(ch), dirs[dir]); } /* end: mounted char */ /* scenario: char is mount */ else if (ridden_by) { /* ridden and mount-char is -not- attempting to sneak will either see whole 'package' move or just the mounted-char */ if (!IS_AFFECTED(ch, AFF_SNEAK)) { /* char's rider is attempting to sneak (mount-char is not) either going to see mount or 'package' move */ if (IS_AFFECTED(RIDDEN_BY(ch), AFF_SNEAK)) { /* we know the rider is trying to sneak, we have to do the sneak-check with all the observers in the room */ for (tch = world[IN_ROOM(ch)].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip self and rider of course */ if (tch == ch || tch == RIDDEN_BY(ch)) continue; /* sneak versus listen check */ if (!can_hear_sneaking(tch, RIDDEN_BY(ch))) { /* message: mount not sneaking, rider is sneaking */ snprintf(buf2, sizeof(buf2), "$n leaves %s.", dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_VICT); } else { /* rider detected ! */ snprintf(buf2, sizeof(buf2), "$n rides %s %s.", GET_NAME(ch), dirs[dir]); act(buf2, TRUE, RIDDEN_BY(ch), 0, tch, TO_VICT); } } /* rider is -not- attempting to sneak (mount-char not too) */ } else { snprintf(buf2, sizeof(buf2), "$n rides $N %s.", dirs[dir]); act(buf2, TRUE, RIDDEN_BY(ch), 0, ch, TO_NOTVICT); } } /* ridden and mount-char -is- attempting to sneak */ else { /* both are attempt to sneak */ if (IS_AFFECTED(RIDDEN_BY(ch), AFF_SNEAK)) { /* we know the mount and rider is trying to sneak, we have to do the sneak-check with all the observers in the room, mount (ch) * success in this case is free pass for sneak */ for (tch = world[IN_ROOM(RIDDEN_BY(ch))].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip rider of course, skipping mount-ch too */ if (tch == RIDDEN_BY(ch) || tch == ch) continue; /* sneak versus listen check */ if (!can_hear_sneaking(tch, ch)) { /* mount success! "package" is sneaking */ } else if (!can_hear_sneaking(tch, RIDDEN_BY(ch))) { /* mount failed, rider succeeded */ /* message: mount not sneaking, rider is sneaking */ snprintf(buf2, sizeof(buf2), "$n leaves %s.", dirs[dir]); act(buf2, TRUE, RIDDEN_BY(ch), 0, tch, TO_VICT); } else { /* mount failed, rider failed */ /* 3.23.18 Ornir Bugfix. */ snprintf(buf2, sizeof(buf2), "$n rides %s %s.", GET_NAME(RIDING(ch)), dirs[dir]); act(buf2, TRUE, RIDDEN_BY(ch), 0, tch, TO_VICT); } } /* ridden and mount-char -is- attempt to sneak, rider -not- */ } else { /* we know the mount (rider no) is trying to sneak, we have to do the sneak-check with all the observers in the room */ for (tch = world[IN_ROOM(ch)].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip self (mount) and rider */ if (tch == RIDDEN_BY(ch) || tch == ch) continue; /* sneak versus listen check */ if (can_hear_sneaking(tch, ch)) { /* mount detected! */ snprintf(buf2, sizeof(buf2), "$n rides %s %s.", GET_NAME(RIDING(ch)), dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_VICT); } /* if we pass this check, the rider/mount are both sneaking */ } } } /* message to self */ send_to_char(ch, "You carry %s %s.\r\n", GET_NAME(RIDDEN_BY(ch)), dirs[dir]); /* message to rider */ send_to_char(RIDDEN_BY(ch), "You are carried %s by %s.\r\n", dirs[dir], GET_NAME(ch)); } /* end char is mounted */ /* ch is on foot */ else if (IS_AFFECTED(ch, AFF_SNEAK)) { /* sneak attempt vs the room content */ for (tch = world[IN_ROOM(ch)].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip self */ if (tch == ch) continue; /* sneak versus listen check */ if (can_hear_sneaking(tch, ch)) { /* detected! */ if (IS_NPC(ch) && (ch->player.walkout != NULL)) { // if they have a walk-out message, display that instead of the boring default one snprintf(buf2, sizeof(buf2), "%s %s.", ch->player.walkout, dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_VICT); } else { snprintf(buf2, sizeof(buf2), "$n leaves %s.", dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_VICT); } } /* if we pass this check, we are sneaking */ } /* message to self */ send_to_char(ch, "You sneak %s.\r\n", dirs[dir]); } /* not attempting to sneak */ else if (!IS_AFFECTED(ch, AFF_SNEAK)) { if (IS_NPC(ch) && (ch->player.walkout != NULL)) { // if they have a walk-out message, display that instead of the boring default one snprintf(buf2, sizeof(buf2), "%s %s.", ch->player.walkout, dirs[dir]); act(buf2, TRUE, ch, 0, tch, TO_ROOM); } else { snprintf(buf2, sizeof(buf2), "$n leaves %s.", dirs[dir]); act(buf2, TRUE, ch, 0, 0, TO_ROOM); } /* message to self */ send_to_char(ch, "You leave %s.\r\n", dirs[dir]); } /*****/ /* end leave-room message code */ /*****/ /* Leave tracks, if not riding. */ if (!riding && (IS_NPC(ch) || !PRF_FLAGGED(ch, PRF_NOHASSLE))) { /*snprintf(buf3, sizeof(buf3), "%d \"%s\" \"%s\" %s", 6, (IS_NPC(ch) ? race_family_types[GET_NPC_RACE(ch)] : race_list[GET_RACE(ch)].type), GET_NAME(ch), dirs[dir]); */ create_tracks(ch, dir, TRACKS_OUT); } /* the actual technical moving of the char */ char_from_room(ch); X_LOC(ch) = new_x; Y_LOC(ch) = new_y; char_to_room(ch, going_to); /* move the mount too */ if (riding && same_room && RIDING(ch)->in_room != ch->in_room) { char_from_room(RIDING(ch)); X_LOC(RIDING(ch)) = new_x; Y_LOC(RIDING(ch)) = new_y; char_to_room(RIDING(ch), ch->in_room); } else if (ridden_by && same_room && RIDDEN_BY(ch)->in_room != ch->in_room) { char_from_room(RIDDEN_BY(ch)); X_LOC(RIDDEN_BY(ch)) = new_x; Y_LOC(RIDDEN_BY(ch)) = new_y; char_to_room(RIDDEN_BY(ch), ch->in_room); } /*---------------------------------------------------------------------*/ /* End: the leave operation. The character is now in the new room. */ /* Begin: Post-move operations. */ /*---------------------------------------------------------------------*/ /* Post Move Trigger Checks: Check the new room for triggers. * Assumptions: The character has already truly left the was_in room. If * the entry trigger "prevents" movement into the room, it is the triggers * job to provide a message to the original was_in room. */ if (!entry_mtrigger(ch) || !enter_wtrigger(&world[going_to], ch, dir)) { char_from_room(ch); if (ZONE_FLAGGED(GET_ROOM_ZONE(was_in), ZONE_WILDERNESS)) { X_LOC(ch) = world[was_in].coords[0]; Y_LOC(ch) = world[was_in].coords[1]; } char_to_room(ch, was_in); if (riding && same_room && RIDING(ch)->in_room != ch->in_room) { char_from_room(RIDING(ch)); if (ZONE_FLAGGED(GET_ROOM_ZONE(ch->in_room), ZONE_WILDERNESS)) { X_LOC(RIDING(ch)) = world[ch->in_room].coords[0]; Y_LOC(RIDING(ch)) = world[ch->in_room].coords[1]; } char_to_room(RIDING(ch), ch->in_room); } else if (ridden_by && same_room && RIDDEN_BY(ch)->in_room != ch->in_room) { char_from_room(RIDDEN_BY(ch)); if (ZONE_FLAGGED(GET_ROOM_ZONE(ch->in_room), ZONE_WILDERNESS)) { X_LOC(RIDDEN_BY(ch)) = world[ch->in_room].coords[0]; Y_LOC(RIDDEN_BY(ch)) = world[ch->in_room].coords[1]; } char_to_room(RIDDEN_BY(ch), ch->in_room); } return 0; } /* char moved from room, so shift everything around */ if (ROOM_FLAGGED(ch->in_room, ROOM_SINGLEFILE) && !is_top_of_room_for_singlefile(ch, rev_dir[dir])) { world[ch->in_room].people = ch->next_in_room; prev = &world[ch->in_room].people; while (*prev) prev = &((*prev)->next_in_room); *prev = ch; ch->next_in_room = NULL; } /* ... and the room description to the character. */ if (ch->desc != NULL) { look_at_room(ch, 0); if (!IS_NPC(ch) && PRF_FLAGGED(ch, PRF_AUTOSCAN)) do_scan(ch, 0, 0, 0); } if (ridden_by) { if (RIDDEN_BY(ch)->desc != NULL) { look_at_room(RIDDEN_BY(ch), 0); if (!IS_NPC(RIDDEN_BY(ch)) && PRF_FLAGGED(RIDDEN_BY(ch), PRF_AUTOSCAN)) do_scan(RIDDEN_BY(ch), 0, 0, 0); } } if (riding) { if (RIDING(ch)->desc != NULL) { look_at_room(RIDING(ch), 0); if (!IS_NPC(RIDING(ch)) && PRF_FLAGGED(RIDING(ch), PRF_AUTOSCAN)) do_scan(RIDING(ch), 0, 0, 0); } } /*****/ /* Generate the enter message(s) and display to others in the arrive room. */ /* This changes stock behavior: it doesn't work * * with in/out/enter/exit as dirs */ /*****/ if (!riding && !ridden_by) { /* simplest case, not riding or being ridden-by */ for (tch = world[IN_ROOM(ch)].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip self */ if (tch == RIDDEN_BY(ch) || tch == ch) continue; /* sneak versus listen check */ if (can_hear_sneaking(tch, ch)) { /* failed sneak attempt (if valid) */ if (IS_NPC(ch) && ch->player.walkin) { snprintf(buf2, sizeof(buf2), "%s %s%s.", ch->player.walkin, ((dir == UP || dir == DOWN) ? "" : "the "), (dir == UP ? "below" : dir == DOWN ? "above" : dirs[rev_dir[dir]])); } else { snprintf(buf2, sizeof(buf2), "$n arrives from %s%s.", ((dir == UP || dir == DOWN) ? "" : "the "), (dir == UP ? "below" : dir == DOWN ? "above" : dirs[rev_dir[dir]])); } act(buf2, TRUE, ch, 0, tch, TO_VICT); } } } else if (riding) { for (tch = world[IN_ROOM(RIDING(ch))].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip rider of course, and mount */ if (tch == RIDING(ch) || tch == ch) continue; /* sneak versus listen check */ if (!can_hear_sneaking(tch, RIDING(ch))) { /* mount success! "package" is sneaking */ } else if (!can_hear_sneaking(tch, ch)) { /* mount failed, rider succeeded */ /* message: mount not sneaking, rider is sneaking */ snprintf(buf2, sizeof(buf2), "$n arrives from %s%s.", ((dir == UP || dir == DOWN) ? "" : "the "), (dir == UP ? "below" : dir == DOWN ? "above" : dirs[rev_dir[dir]])); act(buf2, TRUE, RIDING(ch), 0, tch, TO_VICT); } else { /* mount failed, rider failed */ snprintf(buf2, sizeof(buf2), "$n arrives from %s%s, riding %s.", ((dir == UP || dir == DOWN) ? "" : "the "), (dir == UP ? "below" : dir == DOWN ? "above" : dirs[rev_dir[dir]]), GET_NAME(RIDING(ch))); act(buf2, TRUE, ch, 0, tch, TO_VICT); } } } else if (ridden_by) { for (tch = world[IN_ROOM(RIDDEN_BY(ch))].people; tch; tch = next_tch) { next_tch = tch->next_in_room; /* skip rider of course, and mount */ if (tch == RIDDEN_BY(ch) || tch == ch) continue; /* sneak versus listen check, remember ch = mount right now */ if (!can_hear_sneaking(tch, ch)) { /* mount success! "package" is sneaking */ } else if (!can_hear_sneaking(tch, RIDDEN_BY(ch))) { /* mount failed, rider succeeded */ /* message: mount not sneaking, rider is sneaking */ snprintf(buf2, sizeof(buf2), "$n arrives from %s%s.", ((dir == UP || dir == DOWN) ? "" : "the "), (dir == UP ? "below" : dir == DOWN ? "above" : dirs[rev_dir[dir]])); act(buf2, TRUE, ch, 0, tch, TO_VICT); } else { /* mount failed, rider failed */ snprintf(buf2, sizeof(buf2), "$n arrives from %s%s, ridden by %s.", ((dir == UP || dir == DOWN) ? "" : "the "), (dir == UP ? "below" : dir == DOWN ? "above" : dirs[rev_dir[dir]]), GET_NAME(RIDDEN_BY(ch))); act(buf2, TRUE, RIDDEN_BY(ch), 0, tch, TO_VICT); } } } /*****/ /* end enter-room message code */ /*****/ /* Maybe a wall will stop them? */ if (check_wall(ch, rev_dir[dir])) { /* send them back! */ char_from_room(ch); char_to_room(ch, was_in); return 0; } /* spike growth damages upon entering the room */ if (ROOM_AFFECTED(going_to, RAFF_SPIKE_STONES)) { /* only damage the character if they're not mounted (mount takes damage) */ if (riding && same_room) { // mount will take the damage, don't hurt rider /* damage characters upon entering spike growth room */ damage(RIDING(ch), RIDING(ch), dice(4, 4), SPELL_SPIKE_STONES, DAM_EARTH, FALSE); send_to_char(RIDING(ch), "You are impaled by large stone spikes as you enter the room.\r\n"); } else { // mount is not there, or not mounted damage(ch, ch, dice(4, 4), SPELL_SPIKE_STONES, DAM_EARTH, FALSE); send_to_char(ch, "You are impaled by large stone spikes as you enter the room.\r\n"); } } if (ROOM_AFFECTED(going_to, RAFF_SPIKE_GROWTH)) { /* only damage the character if they're not mounted (mount takes damage) */ if (riding && same_room) { // mount will take the damage, don't hurt rider /* damage characters upon entering spike growth room */ damage(RIDING(ch), RIDING(ch), dice(2, 4), SPELL_SPIKE_GROWTH, DAM_EARTH, FALSE); send_to_char(RIDING(ch), "You are impaled by large spikes as you enter the room.\r\n"); } else { // mount is not there, or not mounted damage(ch, ch, dice(2, 4), SPELL_SPIKE_GROWTH, DAM_EARTH, FALSE); send_to_char(ch, "You are impaled by large spikes as you enter the room.\r\n"); } } /************Death traps have been taken out*************/ /* ... and Kill the player if the room is a death trap. if (ROOM_FLAGGED(going_to, ROOM_DEATH)) { if (GET_LEVEL(ch) < LVL_IMMORT) { mudlog(BRF, LVL_IMMORT, TRUE, "%s hit death trap #%d (%s)", * GET_NAME(ch), GET_ROOM_VNUM(going_to), world[going_to].name); death_cry(ch); extract_char(ch); } if (riding && GET_LEVEL(RIDING(ch)) < LVL_IMMORT) { mudlog(BRF, LVL_IMMORT, TRUE, "%s hit death trap #%d (%s)", GET_NAME(RIDING(ch)), GET_ROOM_VNUM(going_to), world[going_to].name); death_cry(RIDING(ch)); extract_char(RIDING(ch)); } if (ridden_by && GET_LEVEL(RIDDEN_BY(ch)) < LVL_IMMORT) { mudlog(BRF, LVL_IMMORT, TRUE, "%s hit death trap #%d (%s)", GET_NAME(RIDDEN_BY(ch)), GET_ROOM_VNUM(going_to), world[going_to].name); death_cry(RIDDEN_BY(ch)); extract_char(RIDDEN_BY(ch)); } return (0); } ************end death trap code**********/ /* At this point, the character is safe and in the room. */ /* Fire memory and greet triggers, check and see if the greet trigger * prevents movement, and if so, move the player back to the previous room. */ entry_memory_mtrigger(ch); if (!greet_mtrigger(ch, dir)) { char_from_room(ch); if (ZONE_FLAGGED(GET_ROOM_ZONE(was_in), ZONE_WILDERNESS)) { X_LOC(ch) = world[was_in].coords[0]; Y_LOC(ch) = world[was_in].coords[1]; } char_to_room(ch, was_in); look_at_room(ch, 0); /* Failed move, return a failure */ return (0); } else greet_memory_mtrigger(ch); /*---------------------------------------------------------------------*/ /* End: Post-move operations. */ /* Only here is the move successful *and* complete. Return success for * calling functions to handle post move operations. */ /* homeland-port */ if (IS_NPC(ch)) quest_room(ch); /* trap sense will allow a rogue/berserker to auto detect traps if they make a successful check vs DC xx (defined right below ) */ bool sensed_trap = FALSE; if (!IS_NPC(ch)) { int trap_check = 0; int dc = 21; if ((trap_check = HAS_FEAT(ch, FEAT_TRAP_SENSE))) { if (skill_check(ch, ABILITY_PERCEPTION, (dc - trap_check))) sensed_trap = perform_detecttrap(ch, TRUE); /* silent */ } } /* check for traps (enter room) */ if (!sensed_trap) check_trap(ch, TRAP_TYPE_ENTER_ROOM, ch->in_room, 0, 0); return (1); } int perform_move(struct char_data *ch, int dir, int need_specials_check) { room_rnum was_in; struct follow_type *k, *next; if (ch == NULL || dir < 0 || dir >= NUM_OF_DIRS) return (0); else if (FIGHTING(ch)) send_to_char(ch, "You are too busy fighting to move!\r\n"); else if (char_has_mud_event(ch, eFISTED)) send_to_char(ch, "You can't move! You are being held in place by a large clenched fist!\r\n"); else if (!CONFIG_DIAGONAL_DIRS && IS_DIAGONAL(dir)) send_to_char(ch, "Alas, you cannot go that way...\r\n"); else if ((!EXIT(ch, dir) && !buildwalk(ch, dir)) || EXIT(ch, dir)->to_room == NOWHERE) send_to_char(ch, "Alas, you cannot go that way...\r\n"); else if (char_has_mud_event(ch, eFALLING)) send_to_char(ch, "You can't, you are falling!!!\r\n"); else if (EXIT_FLAGGED(EXIT(ch, dir), EX_CLOSED) && (GET_LEVEL(ch) < LVL_IMMORT || (!IS_NPC(ch) && !PRF_FLAGGED(ch, PRF_NOHASSLE)))) { if (EXIT(ch, dir)->keyword) send_to_char(ch, "The %s seems to be closed.\r\n", fname(EXIT(ch, dir)->keyword)); else send_to_char(ch, "It seems to be closed.\r\n"); } else { /* This was tricky - buildwalk for normal rooms is only activated above. * for wilderness rooms we need to activate it here. */ if (ZONE_FLAGGED(GET_ROOM_ZONE(IN_ROOM(ch)), ZONE_WILDERNESS)) buildwalk(ch, dir); if (!ch->followers) return (do_simple_move(ch, dir, need_specials_check)); was_in = IN_ROOM(ch); if (!do_simple_move(ch, dir, need_specials_check)) return (0); for (k = ch->followers; k; k = next) { next = k->next; if ((IN_ROOM(k->follower) == was_in) && (GET_POS(k->follower) >= POS_STANDING)) { act("You follow $N.\r\n", FALSE, k->follower, 0, ch, TO_CHAR); perform_move(k->follower, dir, 1); } } return (1); } return (0); } ACMD(do_move) { /* this test added for newer reclining position */ if (GET_POS(ch) == POS_SITTING || GET_POS(ch) == POS_RESTING) { send_to_char(ch, "You have to be standing or reclining to move.\r\n"); return; } /* These subcmd defines are mapped precisely to the direction defines. */ perform_move(ch, subcmd, 0); } static int find_door(struct char_data *ch, const char *type, char *dir, const char *cmdname) { int door; if (*dir) { /* a direction was specified */ if ((door = search_block(dir, dirs, FALSE)) == -1) { /* Partial Match */ if ((door = search_block(dir, autoexits, FALSE)) == -1) { /* Check 'short' dirs too */ send_to_char(ch, "That's not a direction.\r\n"); return (-1); } } if (EXIT(ch, door)) { /* Braces added according to indent. -gg */ if (EXIT(ch, door)->keyword) { if (is_name(type, EXIT(ch, door)->keyword)) return (door); else { send_to_char(ch, "I see no %s there.\r\n", type); return (-1); } } else return (door); } else { send_to_char(ch, "I really don't see how you can %s anything there.\r\n", cmdname); return (-1); } } else { /* try to locate the keyword */ if (!*type) { send_to_char(ch, "What is it you want to %s?\r\n", cmdname); return (-1); } for (door = 0; door < DIR_COUNT; door++) { if (EXIT(ch, door)) { if (EXIT(ch, door)->keyword) { if (isname(type, EXIT(ch, door)->keyword)) { if ((!IS_NPC(ch)) && (!PRF_FLAGGED(ch, PRF_AUTODOOR))) return door; else if (is_abbrev(cmdname, "open")) { if (IS_SET(EXIT(ch, door)->exit_info, EX_CLOSED)) return door; else if (IS_SET(EXIT(ch, door)->exit_info, EX_LOCKED)) return door; } else if ((is_abbrev(cmdname, "close")) && (!(IS_SET(EXIT(ch, door)->exit_info, EX_CLOSED)))) return door; else if ((is_abbrev(cmdname, "lock")) && (!(IS_SET(EXIT(ch, door)->exit_info, EX_LOCKED)))) return door; else if ((is_abbrev(cmdname, "unlock")) && (IS_SET(EXIT(ch, door)->exit_info, EX_LOCKED))) return door; else if ((is_abbrev(cmdname, "pick")) && (IS_SET(EXIT(ch, door)->exit_info, EX_LOCKED))) return door; } } } } if ((!IS_NPC(ch)) && (!PRF_FLAGGED(ch, PRF_AUTODOOR))) send_to_char(ch, "There doesn't seem to be %s %s here.\r\n", AN(type), type); else if (is_abbrev(cmdname, "open")) send_to_char(ch, "There doesn't seem to be %s %s that can be opened.\r\n", AN(type), type); else if (is_abbrev(cmdname, "close")) send_to_char(ch, "There doesn't seem to be %s %s that can be closed.\r\n", AN(type), type); else if (is_abbrev(cmdname, "lock")) send_to_char(ch, "There doesn't seem to be %s %s that can be locked.\r\n", AN(type), type); else if (is_abbrev(cmdname, "unlock")) send_to_char(ch, "There doesn't seem to be %s %s that can be unlocked.\r\n", AN(type), type); else send_to_char(ch, "There doesn't seem to be %s %s that can be picked.\r\n", AN(type), type); return (-1); } } int has_key(struct char_data *ch, obj_vnum key) { struct obj_data *o; for (o = ch->carrying; o; o = o->next_content) if (GET_OBJ_VNUM(o) == key) return (1); if (GET_EQ(ch, WEAR_HOLD_1)) if (GET_OBJ_VNUM(GET_EQ(ch, WEAR_HOLD_1)) == key) return (1); if (GET_EQ(ch, WEAR_HOLD_2)) if (GET_OBJ_VNUM(GET_EQ(ch, WEAR_HOLD_2)) == key) return (1); return (0); } #define NEED_OPEN (1 << 0) #define NEED_CLOSED (1 << 1) #define NEED_UNLOCKED (1 << 2) #define NEED_LOCKED (1 << 3) /* cmd_door is required external from act.movement.c */ const char *const cmd_door[] = { "open", "close", "unlock", "lock", "pick"}; static const int flags_door[] = { NEED_CLOSED | NEED_UNLOCKED, NEED_OPEN, NEED_CLOSED | NEED_LOCKED, NEED_CLOSED | NEED_UNLOCKED, NEED_CLOSED | NEED_LOCKED}; static void do_doorcmd(struct char_data *ch, struct obj_data *obj, int door, int scmd) { char buf[MAX_STRING_LENGTH]; size_t len; room_rnum other_room = NOWHERE; struct room_direction_data *back = NULL; if (!door_mtrigger(ch, scmd, door)) return; if (!door_wtrigger(ch, scmd, door)) return; len = snprintf(buf, sizeof(buf), "$n %ss ", cmd_door[scmd]); if (!obj && ((other_room = EXIT(ch, door)->to_room) != NOWHERE)) if ((back = world[other_room].dir_option[rev_dir[door]]) != NULL) if (back->to_room != IN_ROOM(ch)) back = NULL; switch (scmd) { case SCMD_OPEN: if (obj) { if (check_trap(ch, TRAP_TYPE_OPEN_CONTAINER, ch->in_room, obj, 0)) return; } else { if (check_trap(ch, TRAP_TYPE_OPEN_DOOR, ch->in_room, 0, door)) return; } OPEN_DOOR(IN_ROOM(ch), obj, door); if (back) OPEN_DOOR(other_room, obj, rev_dir[door]); send_to_char(ch, "%s", CONFIG_OK); break; case SCMD_CLOSE: if (obj) { if (check_trap(ch, TRAP_TYPE_OPEN_CONTAINER, ch->in_room, obj, 0)) return; } else { if (check_trap(ch, TRAP_TYPE_OPEN_DOOR, ch->in_room, 0, door)) return; } CLOSE_DOOR(IN_ROOM(ch), obj, door); if (back) CLOSE_DOOR(other_room, obj, rev_dir[door]); send_to_char(ch, "%s", CONFIG_OK); break; case SCMD_LOCK: LOCK_DOOR(IN_ROOM(ch), obj, door); if (back) LOCK_DOOR(other_room, obj, rev_dir[door]); send_to_char(ch, "*Click*\r\n"); break; case SCMD_UNLOCK: if (obj) { if (check_trap(ch, TRAP_TYPE_UNLOCK_CONTAINER, ch->in_room, obj, 0)) return; } else { if (check_trap(ch, TRAP_TYPE_UNLOCK_DOOR, ch->in_room, 0, door)) return; } UNLOCK_DOOR(IN_ROOM(ch), obj, door); if (back) UNLOCK_DOOR(other_room, obj, rev_dir[door]); send_to_char(ch, "*Click*\r\n"); break; case SCMD_PICK: if (obj) { if (check_trap(ch, TRAP_TYPE_UNLOCK_CONTAINER, ch->in_room, obj, 0)) return; } else { if (check_trap(ch, TRAP_TYPE_UNLOCK_DOOR, ch->in_room, 0, door)) return; } TOGGLE_LOCK(IN_ROOM(ch), obj, door); if (back) TOGGLE_LOCK(other_room, obj, rev_dir[door]); send_to_char(ch, "The lock quickly yields to your skills.\r\n"); len = strlcpy(buf, "$n skillfully picks the lock on ", sizeof(buf)); break; } /* Notify the room. */ if (len < sizeof(buf)) snprintf(buf + len, sizeof(buf) - len, "%s%s.", obj ? "" : "the ", obj ? "$p" : EXIT(ch, door)->keyword ? "$F" : "door"); if (!obj || IN_ROOM(obj) != NOWHERE) act(buf, FALSE, ch, obj, obj ? 0 : EXIT(ch, door)->keyword, TO_ROOM); /* Notify the other room */ if (back && (scmd == SCMD_OPEN || scmd == SCMD_CLOSE)) send_to_room(EXIT(ch, door)->to_room, "The %s is %s%s from the other side.\r\n", back->keyword ? fname(back->keyword) : "door", cmd_door[scmd], scmd == SCMD_CLOSE ? "d" : "ed"); /* Door actions are a move action. */ USE_MOVE_ACTION(ch); } int ok_pick(struct char_data *ch, obj_vnum keynum, int pickproof, int scmd, int door) { int skill_lvl; int lock_dc = 10; //struct obj_data *tools = NULL; if (scmd != SCMD_PICK) return (1); skill_lvl = compute_ability(ch, ABILITY_SLEIGHT_OF_HAND); /* this is a hack of sorts, we have some abuse of charmies being used to pick locks, so we add some penalties and restirctions here */ if (IS_NPC(ch)) { skill_lvl -= 4; /* wheeeeeee */ switch (GET_RACE(ch)) { case RACE_TYPE_UNDEAD: case RACE_TYPE_ANIMAL: case RACE_TYPE_DRAGON: case RACE_TYPE_MAGICAL_BEAST: case RACE_TYPE_OOZE: case RACE_TYPE_PLANT: case RACE_TYPE_VERMIN: send_to_char(ch, "What makes you think you know how to do this?!\r\n"); return (0); default: /* we will let them pick */ break; } } /* end npc hack */ if (skill_lvl <= 0) { /* not an untrained skill */ send_to_char(ch, "You have no idea how (train sleight of hand)!\r\n"); return (0); } if (FIGHTING(ch)) skill_lvl += dice(1, 20); else skill_lvl += 20; // take 20 /* thief tools */ /* if ((tools = get_obj_in_list_vis(ch, "thieves,tools", NULL, ch->carrying))) { if (GET_OBJ_VNUM(tools) == 105) skill_lvl += 2; } */ if (EXIT(ch, door)) { if (EXIT_FLAGGED(EXIT(ch, door), EX_LOCKED_EASY)) lock_dc += 14; else if (EXIT_FLAGGED(EXIT(ch, door), EX_LOCKED_MEDIUM)) lock_dc += 25; else if (EXIT_FLAGGED(EXIT(ch, door), EX_LOCKED_HARD)) lock_dc += 38; } if (keynum == NOTHING) { send_to_char(ch, "Odd - you can't seem to find a keyhole.\r\n"); } else if (pickproof) { send_to_char(ch, "It resists your attempts to pick it.\r\n"); } else if (lock_dc <= skill_lvl) { send_to_char(ch, "Success! [%d dc vs. %d skill]\r\n", lock_dc, skill_lvl); USE_MOVE_ACTION(ch); return (1); } /* failed */ USE_MOVE_ACTION(ch); return (0); } #define DOOR_IS_OPENABLE(ch, obj, door) ((obj) ? (((GET_OBJ_TYPE(obj) == \ ITEM_CONTAINER) || \ GET_OBJ_TYPE(obj) == ITEM_AMMO_POUCH) && \ OBJVAL_FLAGGED(obj, CONT_CLOSEABLE)) \ : (EXIT_FLAGGED(EXIT(ch, door), EX_ISDOOR))) #define DOOR_IS_OPEN(ch, obj, door) ((obj) ? (!OBJVAL_FLAGGED(obj, \ CONT_CLOSED)) \ : (!EXIT_FLAGGED(EXIT(ch, door), EX_CLOSED))) #define DOOR_IS_UNLOCKED(ch, obj, door) ((obj) ? (!OBJVAL_FLAGGED(obj, \ CONT_LOCKED)) \ : (!EXIT_FLAGGED(EXIT(ch, door), EX_LOCKED))) #define DOOR_IS_PICKPROOF(ch, obj, door) ((obj) ? (OBJVAL_FLAGGED(obj, \ CONT_PICKPROOF)) \ : (EXIT_FLAGGED(EXIT(ch, door), EX_PICKPROOF))) #define DOOR_IS_CLOSED(ch, obj, door) (!(DOOR_IS_OPEN(ch, obj, door))) #define DOOR_IS_LOCKED(ch, obj, door) (!(DOOR_IS_UNLOCKED(ch, obj, door))) #define DOOR_KEY(ch, obj, door) ((obj) ? (GET_OBJ_VAL(obj, 2)) : (EXIT(ch, door)->key)) ACMD(do_gen_door) { int door = -1; obj_vnum keynum; char type[MAX_INPUT_LENGTH], dir[MAX_INPUT_LENGTH]; struct obj_data *obj = NULL; struct char_data *victim = NULL; skip_spaces(&argument); if (!*argument) { send_to_char(ch, "%c%s what?\r\n", UPPER(*cmd_door[subcmd]), cmd_door[subcmd] + 1); return; } two_arguments(argument, type, dir); if (!generic_find(type, FIND_OBJ_INV | FIND_OBJ_ROOM, ch, &victim, &obj)) door = find_door(ch, type, dir, cmd_door[subcmd]); if ((obj) && (GET_OBJ_TYPE(obj) != ITEM_CONTAINER && GET_OBJ_TYPE(obj) != ITEM_AMMO_POUCH)) { obj = NULL; door = find_door(ch, type, dir, cmd_door[subcmd]); } if ((obj) || (door >= 0)) { keynum = DOOR_KEY(ch, obj, door); if (!(DOOR_IS_OPENABLE(ch, obj, door))) send_to_char(ch, "You can't %s that!\r\n", cmd_door[subcmd]); else if (!DOOR_IS_OPEN(ch, obj, door) && IS_SET(flags_door[subcmd], NEED_OPEN)) send_to_char(ch, "But it's already closed!\r\n"); else if (!DOOR_IS_CLOSED(ch, obj, door) && IS_SET(flags_door[subcmd], NEED_CLOSED)) send_to_char(ch, "But it's currently open!\r\n"); else if (!(DOOR_IS_LOCKED(ch, obj, door)) && IS_SET(flags_door[subcmd], NEED_LOCKED)) send_to_char(ch, "Oh.. it wasn't locked, after all..\r\n"); else if (!(DOOR_IS_UNLOCKED(ch, obj, door)) && IS_SET(flags_door[subcmd], NEED_UNLOCKED) && ((!IS_NPC(ch) && PRF_FLAGGED(ch, PRF_AUTOKEY))) && (has_key(ch, keynum))) { send_to_char(ch, "It is locked, but you have the key.\r\n"); do_doorcmd(ch, obj, door, SCMD_UNLOCK); send_to_char(ch, "*Click*\r\n"); do_doorcmd(ch, obj, door, subcmd); } else if (!(DOOR_IS_UNLOCKED(ch, obj, door)) && IS_SET(flags_door[subcmd], NEED_UNLOCKED) && ((!IS_NPC(ch) && PRF_FLAGGED(ch, PRF_AUTOKEY))) && (!has_key(ch, keynum))) { send_to_char(ch, "It is locked, and you do not have the key!\r\n"); } else if (!(DOOR_IS_UNLOCKED(ch, obj, door)) && IS_SET(flags_door[subcmd], NEED_UNLOCKED) && (GET_LEVEL(ch) < LVL_IMMORT || (!IS_NPC(ch) && !PRF_FLAGGED(ch, PRF_NOHASSLE)))) send_to_char(ch, "It seems to be locked.\r\n"); else if (!has_key(ch, keynum) && (GET_LEVEL(ch) < LVL_STAFF) && ((subcmd == SCMD_LOCK) || (subcmd == SCMD_UNLOCK))) send_to_char(ch, "You don't seem to have the proper key.\r\n"); else if (ok_pick(ch, keynum, DOOR_IS_PICKPROOF(ch, obj, door), subcmd, door)) do_doorcmd(ch, obj, door, subcmd); } return; } ACMD(do_enter) { char buf[MAX_INPUT_LENGTH] = {'\0'}; int door = 0, portal_type = 0, count = 0, diff = 0; room_vnum portal_dest = 1; room_rnum was_in = NOWHERE, real_dest = NOWHERE; struct follow_type *k = NULL; struct obj_data *portal = NULL; //room_vnum vClanhall = NOWHERE; //int iPlayerClan = 0; //room_rnum rClanhall = 0; if (FIGHTING(ch)) { send_to_char(ch, "You are too busy fighting to enter!\r\n"); return; } was_in = IN_ROOM(ch); one_argument_c(argument, buf, sizeof(buf)); /* an argument was supplied, search for door keyword */ if (*buf) { /* Portals first */ portal = get_obj_in_list_vis(ch, buf, NULL, world[IN_ROOM(ch)].contents); if ((portal) && (GET_OBJ_TYPE(portal) == ITEM_PORTAL)) { portal_type = portal->obj_flags.value[0]; /* Perform checks and get destination */ switch (portal_type) { case PORTAL_NORMAL: portal_dest = portal->obj_flags.value[1]; break; case PORTAL_CHECKFLAGS: if (((IS_WIZARD(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_WIZARD))) || ((IS_CLERIC(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_CLERIC))) || ((IS_RANGER(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_RANGER))) || ((IS_PALADIN(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_PALADIN))) || ((IS_ROGUE(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_ROGUE))) || ((IS_MONK(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_MONK))) || ((IS_DRUID(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_DRUID))) || ((IS_BERSERKER(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_BERSERKER))) || ((IS_SORCERER(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_SORCERER))) || ((IS_BARD(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_BARD))) || ((IS_WARRIOR(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_WARRIOR))) || ((IS_WEAPONMASTER(ch)) && (OBJ_FLAGGED(portal, ITEM_ANTI_WEAPONMASTER)))) { act("You try to enter $p, but a mysterious power " "forces you back! (class restriction)", FALSE, ch, portal, 0, TO_CHAR); act("\tRA booming voice in your head shouts '\tWNot " "for your class!\tR'\tn", FALSE, ch, portal, 0, TO_CHAR); act("$n tries to enter $p, but a mysterious power " "forces $m back!", FALSE, ch, portal, 0, TO_ROOM); return; } if (IS_EVIL(ch) && OBJ_FLAGGED(portal, ITEM_ANTI_EVIL)) { act("You try to enter $p, but a mysterious power " "forces you back! (alignment restriction)", FALSE, ch, portal, 0, TO_CHAR); act("\tRA booming voice in your head shouts '\tWBEGONE " "EVIL-DOER!\tR'\tn", FALSE, ch, portal, 0, TO_CHAR); act("$n tries to enter $p, but a mysterious power " "forces $m back!", FALSE, ch, portal, 0, TO_ROOM); return; } if (IS_GOOD(ch) && OBJ_FLAGGED(portal, ITEM_ANTI_GOOD)) { act("You try to enter $p, but a mysterious power " "forces you back! (alignment restriction)", FALSE, ch, portal, 0, TO_CHAR); act("\tRA booming voice in your head shouts '\tWBEGONE " "DO-GOODER!\tR'\tn", FALSE, ch, portal, 0, TO_CHAR); act("$n tries to enter $p, but a mysterious power " "forces $m back!", FALSE, ch, portal, 0, TO_ROOM); return; } if (((!IS_EVIL(ch)) && !(IS_GOOD(ch))) && OBJ_FLAGGED(portal, ITEM_ANTI_NEUTRAL)) { act("You try to enter $p, but a mysterious power " "forces you back! (alignment restriction)", FALSE, ch, portal, 0, TO_CHAR); act("\tRA booming voice in your head shouts '\tWBEGONE!" "\tR'\tn", FALSE, ch, portal, 0, TO_CHAR); act("$n tries to enter $p, but a mysterious power " "forces $m back!", FALSE, ch, portal, 0, TO_ROOM); return; } portal_dest = portal->obj_flags.value[1]; break; /* case PORTAL_CLANHALL: iPlayerClan = GET_CLAN(ch); if (iPlayerClan <= 0) { send_to_char(ch, "You try to enter the portal, but it returns you back to the same room!\n\r"); return; } if (GET_CLANHALL_ZONE(ch) == NOWHERE) { send_to_char(ch, "Your clan does not have a clanhall!\n\r"); log("[PORTAL] Clan Portal - No clanhall (Player: %s, Clan ID: %d)", GET_NAME(ch), iPlayerClan); return; } vClanhall = (GET_CLANHALL_ZONE(ch) * 100) + 1; rClanhall = real_room(vClanhall); if (rClanhall == NOWHERE ) { send_to_char(ch, "Your clanhall is currently broken - contact an Imm!\n\r"); log("[PORTAL] Clan Portal failed (Player: %s, Clan ID: %d)", GET_NAME(ch), iPlayerClan); return; } portal_dest = vClanhall; break; */ case PORTAL_RANDOM: if (real_room(portal->obj_flags.value[1]) == NOWHERE) { send_to_char(ch, "The portal leads nowhere. (please tell a staff member)\r\n"); return; } if (real_room(portal->obj_flags.value[2]) == NOWHERE) { send_to_char(ch, "The portal leads nowhere. (pleaes tell a staff member)\r\n"); return; } count = 0; if (portal->obj_flags.value[1] > portal->obj_flags.value[2]) { diff = portal->obj_flags.value[1] - portal->obj_flags.value[2]; do { portal_dest = (portal->obj_flags.value[2]) + rand_number(0, diff); } while ((real_room(portal_dest) == NOWHERE) && (++count < 150)); } else { diff = portal->obj_flags.value[2] - portal->obj_flags.value[1]; do { portal_dest = (portal->obj_flags.value[1]) + rand_number(0, diff); } while ((real_room(portal_dest) == NOWHERE) && (++count < 150)); } log("Random Portal: Sending %s to vnum %d", GET_NAME(ch), portal_dest); break; default: mudlog(NRM, LVL_STAFF, TRUE, "SYSERR: Invalid portal type (%d) in room %d", portal->obj_flags.value[0], world[IN_ROOM(ch)].number); send_to_char(ch, "This portal is broken, please tell an Imm.\r\n"); return; break; } if ((real_dest = real_room(portal_dest)) == NOWHERE) { send_to_char(ch, "The portal appears to be a vacuum! (tell a staff member please)\r\n"); return; } /* All checks passed, except checking the destination, so let's do that now */ /* this function needs a vnum, not rnum */ if (ch && !House_can_enter(ch, portal_dest)) { send_to_char(ch, "As you try to enter the portal, it flares " "brightly, pushing you back! (someone's private house)\r\n"); return; } if (ROOM_FLAGGED(real_dest, ROOM_PRIVATE)) { send_to_char(ch, "As you try to enter the portal, it flares " "brightly, pushing you back!! (private area)\r\n"); return; } if (ROOM_FLAGGED(real_dest, ROOM_DEATH)) { send_to_char(ch, "As you try to enter the portal, it flares " "brightly, pushing you back!!! (death room, eek!)\r\n"); return; } if (ROOM_FLAGGED(real_dest, ROOM_STAFFROOM)) { send_to_char(ch, "As you try to enter the portal, it flares " "brightly, pushing you back!!!! (destination is staff only)\r\n"); return; } if (ZONE_FLAGGED(GET_ROOM_ZONE(real_dest), ZONE_CLOSED)) { send_to_char(ch, "As you try to enter the portal, it flares " "brightly, pushing you back!!!!! (destination zone is closed for construction/repairs)\r\n"); return; } /* ok NOW we are good to go */ act("$n enters $p, and vanishes!", FALSE, ch, portal, 0, TO_ROOM); act("You enter $p, and you are transported elsewhere.", FALSE, ch, portal, 0, TO_CHAR); char_from_room(ch); if (ZONE_FLAGGED(GET_ROOM_ZONE(real_dest), ZONE_WILDERNESS)) { X_LOC(ch) = world[real_dest].coords[0]; Y_LOC(ch) = world[real_dest].coords[1]; } char_to_room(ch, real_dest); look_at_room(ch, 0); act("$n appears from thin air!", FALSE, ch, 0, 0, TO_ROOM); /* Then, any followers should auto-follow (Jamdog 19th June 2006) */ for (k = ch->followers; k; k = k->next) { if ((IN_ROOM(k->follower) == was_in) && (GET_POS(k->follower) >= POS_STANDING)) { act("You follow $N.\r\n", FALSE, k->follower, 0, ch, TO_CHAR); act("$n enters $p, and vanishes!", FALSE, k->follower, portal, 0, TO_ROOM); char_from_room(k->follower); if (ZONE_FLAGGED(GET_ROOM_ZONE(real_dest), ZONE_WILDERNESS)) { X_LOC(k->follower) = world[real_dest].coords[0]; Y_LOC(k->follower) = world[real_dest].coords[1]; } char_to_room(k->follower, real_dest); look_at_room(k->follower, 0); act("$n appears from thin air!", FALSE, k->follower, 0, 0, TO_ROOM); } } return; /* Must be a door */ } else { for (door = 0; door < NUM_OF_DIRS; door++) { if (EXIT(ch, door) && (EXIT(ch, door)->keyword)) { if (!str_cmp(EXIT(ch, door)->keyword, buf)) { perform_move(ch, door, 1); return; } } } send_to_char(ch, "There is no %s here.\r\n", buf); } } else if (!OUTSIDE(ch)) { send_to_char(ch, "You are already indoors.\r\n"); } else { /* try to locate an entrance */ for (door = 0; door < NUM_OF_DIRS; door++) { if (EXIT(ch, door)) { if (EXIT(ch, door)->to_room != NOWHERE) { if (!EXIT_FLAGGED(EXIT(ch, door), EX_CLOSED) && ROOM_OUTSIDE(EXIT(ch, door)->to_room)) { perform_move(ch, door, 1); return; } } } } /*fail!!*/ send_to_char(ch, "You can't seem to find anything to enter.\r\n"); } } ACMD(do_leave) { int door; if (OUTSIDE(ch)) send_to_char(ch, "You are outside.. where do you want to go?\r\n"); else { for (door = 0; door < DIR_COUNT; door++) if (EXIT(ch, door)) if (EXIT(ch, door)->to_room != NOWHERE) if (!EXIT_FLAGGED(EXIT(ch, door), EX_CLOSED) && !ROOM_FLAGGED(EXIT(ch, door)->to_room, ROOM_INDOORS)) { perform_move(ch, door, 1); return; } send_to_char(ch, "I see no obvious exits to the outside.\r\n"); } } /* Stand - Standing costs a move action. */ ACMD(do_stand) { if (AFF_FLAGGED(ch, AFF_PINNED)) { send_to_char(ch, "You can't, you are pinned! (try struggle or grapple <target>).\r\n"); return; } switch (GET_POS(ch)) { case POS_STANDING: send_to_char(ch, "You are already standing.\r\n"); break; case POS_SITTING: send_to_char(ch, "You stand up.\r\n"); act("$n clambers to $s feet.", TRUE, ch, 0, 0, TO_ROOM); /* Were they sitting in something? */ char_from_furniture(ch); /* Will be sitting after a successful bash and may still be fighting. */ GET_POS(ch) = FIGHTING(ch) ? POS_FIGHTING : POS_STANDING; USE_MOVE_ACTION(ch); if (FIGHTING(ch)) attacks_of_opportunity(ch, 0); break; case POS_RESTING: send_to_char(ch, "You stop resting, and stand up.\r\n"); act("$n stops resting, and clambers on $s feet.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_STANDING); /* Were they sitting in something. */ char_from_furniture(ch); USE_MOVE_ACTION(ch); if (FIGHTING(ch)) attacks_of_opportunity(ch, 0); break; case POS_RECLINING: send_to_char(ch, "You hop from prone position to standing.\r\n"); act("$n hops from prone to standing on $s feet.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_STANDING); /* Were they sitting in something. */ char_from_furniture(ch); USE_MOVE_ACTION(ch); if (FIGHTING(ch)) attacks_of_opportunity(ch, 0); break; case POS_SLEEPING: send_to_char(ch, "You have to wake up first!\r\n"); break; case POS_FIGHTING: send_to_char(ch, "Do you not consider fighting as standing?\r\n"); break; default: send_to_char(ch, "You stop floating around, and put your feet on the ground.\r\n"); act("$n stops floating around, and puts $s feet on the ground.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_STANDING); break; } } ACMD(do_sit) { char arg[MAX_STRING_LENGTH]; struct obj_data *furniture; struct char_data *tempch; int found; one_argument_c(argument, arg, sizeof(arg)); if (!*arg) found = 0; if (!(furniture = get_obj_in_list_vis(ch, arg, NULL, world[ch->in_room].contents))) found = 0; else found = 1; switch (GET_POS(ch)) { case POS_STANDING: if (found == 0) { send_to_char(ch, "You sit down.\r\n"); act("$n sits down.", FALSE, ch, 0, 0, TO_ROOM); change_position(ch, POS_SITTING); } else { if (GET_OBJ_TYPE(furniture) != ITEM_FURNITURE) { send_to_char(ch, "You can't sit on that!\r\n"); return; } else if (GET_OBJ_VAL(furniture, 1) > GET_OBJ_VAL(furniture, 0)) { /* Val 1 is current number sitting, 0 is max in sitting. */ act("$p looks like it's all full.", TRUE, ch, furniture, 0, TO_CHAR); log("SYSERR: Furniture %d holding too many people.", GET_OBJ_VNUM(furniture)); return; } else if (GET_OBJ_VAL(furniture, 1) == GET_OBJ_VAL(furniture, 0)) { act("There is no where left to sit upon $p.", TRUE, ch, furniture, 0, TO_CHAR); return; } else { if (OBJ_SAT_IN_BY(furniture) == NULL) OBJ_SAT_IN_BY(furniture) = ch; for (tempch = OBJ_SAT_IN_BY(furniture); tempch != ch; tempch = NEXT_SITTING(tempch)) { if (NEXT_SITTING(tempch)) continue; NEXT_SITTING(tempch) = ch; } act("You sit down upon $p.", TRUE, ch, furniture, 0, TO_CHAR); act("$n sits down upon $p.", TRUE, ch, furniture, 0, TO_ROOM); SITTING(ch) = furniture; NEXT_SITTING(ch) = NULL; GET_OBJ_VAL(furniture, 1) += 1; change_position(ch, POS_SITTING); } } break; case POS_SITTING: send_to_char(ch, "You're sitting already.\r\n"); break; case POS_RESTING: send_to_char(ch, "You stop resting, and sit up.\r\n"); act("$n stops resting.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_SITTING); break; case POS_RECLINING: send_to_char(ch, "You shift your body from prone to sitting up.\r\n"); act("$n shifts $s body from prone to sitting up.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_SITTING); break; case POS_SLEEPING: send_to_char(ch, "You have to wake up first.\r\n"); break; case POS_FIGHTING: send_to_char(ch, "You drop down in a low squat!\r\n"); change_position(ch, POS_SITTING); break; default: send_to_char(ch, "You stop floating around, and sit down.\r\n"); act("$n stops floating around, and sits down.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_SITTING); break; } } ACMD(do_rest) { if (affected_by_spell(ch, SKILL_RAGE)) { send_to_char(ch, "Rest now? No way. PRESS ON!\r\n"); return; } switch (GET_POS(ch)) { case POS_STANDING: send_to_char(ch, "You sit down and rest your tired bones.\r\n"); act("$n sits down and rests.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RESTING); break; case POS_SITTING: send_to_char(ch, "You rest your tired bones.\r\n"); act("$n rests.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RESTING); break; case POS_RESTING: send_to_char(ch, "You are already resting.\r\n"); break; case POS_RECLINING: send_to_char(ch, "You sit up slowly.\r\n"); act("$n sits up slowly.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RESTING); break; case POS_SLEEPING: send_to_char(ch, "You have to wake up first.\r\n"); break; case POS_FIGHTING: send_to_char(ch, "Rest while fighting? Are you MAD?\r\n"); break; default: send_to_char(ch, "You stop floating around, and stop to rest your tired bones.\r\n"); act("$n stops floating around, and rests.", FALSE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RESTING); break; } } ACMD(do_recline) { switch (GET_POS(ch)) { case POS_STANDING: send_to_char(ch, "You drop down to a prone position.\r\n"); act("$n drops down to a prone position.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RECLINING); break; case POS_SITTING: send_to_char(ch, "You shift to a prone position.\r\n"); act("$n shifts to a prone position.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RECLINING); break; case POS_RESTING: send_to_char(ch, "You lie down and continue resting.\r\n"); act("$n lays down.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RECLINING); break; case POS_RECLINING: send_to_char(ch, "You are already reclining.\r\n"); break; case POS_SLEEPING: send_to_char(ch, "You have to wake up first.\r\n"); break; case POS_FIGHTING: send_to_char(ch, "You drop down to your stomach!\r\n"); change_position(ch, POS_RECLINING); break; default: send_to_char(ch, "You stop floating around, and drop prone to the ground.\r\n"); act("$n stops floating around, and drops prone to the ground.", FALSE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RECLINING); break; } } ACMD(do_sleep) { if (affected_by_spell(ch, SKILL_RAGE)) { send_to_char(ch, "You are way too hyper for that right now!\r\n"); return; } switch (GET_POS(ch)) { case POS_STANDING: case POS_SITTING: case POS_RESTING: case POS_RECLINING: send_to_char(ch, "You go to sleep.\r\n"); act("$n lies down and falls asleep.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_SLEEPING); break; case POS_SLEEPING: send_to_char(ch, "You are already sound asleep.\r\n"); break; case POS_FIGHTING: send_to_char(ch, "Sleep while fighting? Are you MAD?\r\n"); break; default: send_to_char(ch, "You stop floating around, and lie down to sleep.\r\n"); act("$n stops floating around, and lie down to sleep.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_SLEEPING); break; } } ACMD(do_wake) { char arg[MAX_INPUT_LENGTH]; struct char_data *vict; int self = 0; one_argument_c(argument, arg, sizeof(arg)); if (*arg) { if (GET_POS(ch) == POS_SLEEPING) send_to_char(ch, "Maybe you should wake yourself up first.\r\n"); else if ((vict = get_char_vis(ch, arg, NULL, FIND_CHAR_ROOM)) == NULL) send_to_char(ch, "%s", CONFIG_NOPERSON); else if (vict == ch) self = 1; else if (AWAKE(vict)) act("$E is already awake.", FALSE, ch, 0, vict, TO_CHAR); else if (AFF_FLAGGED(vict, AFF_SLEEP)) act("You can't wake $M up!", FALSE, ch, 0, vict, TO_CHAR); else if (GET_POS(vict) < POS_SLEEPING) act("$E's in pretty bad shape!", FALSE, ch, 0, vict, TO_CHAR); else { act("You wake $M up.", FALSE, ch, 0, vict, TO_CHAR); act("You are awakened by $n.", FALSE, ch, 0, vict, TO_VICT | TO_SLEEP); change_position(vict, POS_RECLINING); } if (!self) return; } if (AFF_FLAGGED(ch, AFF_SLEEP)) send_to_char(ch, "You can't wake up!\r\n"); else if (GET_POS(ch) > POS_SLEEPING) send_to_char(ch, "You are already awake...\r\n"); else { send_to_char(ch, "You awaken and are now in a prone position.\r\n"); act("$n awakens and is now in a prone position.", TRUE, ch, 0, 0, TO_ROOM); change_position(ch, POS_RECLINING); } } ACMD(do_follow) { char buf[MAX_INPUT_LENGTH]; struct char_data *leader; one_argument_c(argument, buf, sizeof(buf)); if (*buf) { if (!(leader = get_char_vis(ch, buf, NULL, FIND_CHAR_ROOM))) { send_to_char(ch, "%s", CONFIG_NOPERSON); return; } } else { send_to_char(ch, "Whom do you wish to follow?\r\n"); return; } if (ch->master == leader) { act("You are already following $M.", FALSE, ch, 0, leader, TO_CHAR); return; } if (AFF_FLAGGED(ch, AFF_CHARM) && (ch->master)) { act("But you only feel like following $N!", FALSE, ch, 0, ch->master, TO_CHAR); } else { /* Not Charmed follow person */ if (leader == ch) { if (!ch->master) { send_to_char(ch, "You are already following yourself.\r\n"); return; } stop_follower(ch); } else { if (circle_follow(ch, leader)) { send_to_char(ch, "Sorry, but following in loops is not allowed.\r\n"); return; } if (ch->master) stop_follower(ch); add_follower(ch, leader); } } } ACMD(do_unlead) { char buf[MAX_INPUT_LENGTH]; struct char_data *follower; one_argument_c(argument, buf, sizeof(buf)); if (*buf) { if (!(follower = get_char_vis(ch, buf, NULL, FIND_CHAR_ROOM))) { send_to_char(ch, "%s", CONFIG_NOPERSON); return; } } else { send_to_char(ch, "Whom do you wish to stop leading?\r\n"); return; } if (follower->master != ch) { act("$E isn't following you!", FALSE, ch, 0, follower, TO_CHAR); return; } // Not replicating the AFF_CHARM check from do_follow here - if you want to unlead a charmee, // go right ahead. We also don't want to call stop_follower() on the follower, or you'd be freeing // your charmees instead of just making them stay put. We'll use stop_follower_engine() instead. stop_follower_engine(follower); follower->master = NULL; act("$N stops following you.", FALSE, ch, 0, follower, TO_CHAR); act("You are no longer following $n.", TRUE, ch, 0, follower, TO_VICT); act("$N stops following $n.", TRUE, ch, 0, follower, TO_NOTVICT); } /* i put this here for reference */ /* #define POS_DEAD 0 //Position = dead #define POS_MORTALLYW 1 //Position = mortally wounded #define POS_INCAP 2 //Position = incapacitated #define POS_STUNNED 3 //Position = stunned #define POS_SLEEPING 4 //Position = sleeping #define POS_RECLINING 5 //Position = reclining #define POS_RESTING 6 //Position = resting #define POS_SITTING 7 //Position = sitting #define POS_FIGHTING 8 //Position = fighting #define POS_STANDING 9 //Position = standing */ /* in: character, position change out: as of this writing, nothing yet function: changing a position use to be just GET_POS(ch) = POS_X, but that did not account for dynamic changes that would be connected to the change in position.. the classic example is the combat maneuver TRIP, which would change your position from POS_STANDING to POS_SITTING, if the victim is casting, then they should be -immediately- interrupted. */ int change_position(struct char_data *ch, int new_position) { int old_position = GET_POS(ch); /* we will put some general checks for having your position changed */ /* casting */ if (char_has_mud_event(ch, eCASTING) && new_position <= POS_SITTING) { act("$n's spell is interrupted!", FALSE, ch, 0, 0, TO_ROOM); send_to_char(ch, "Your spell is aborted!\r\n"); resetCastingData(ch); } /* preparing spells */ if (char_has_mud_event(ch, ePREPARATION) && new_position != POS_RESTING) { act("$n's preparations are aborted!", FALSE, ch, 0, 0, TO_ROOM); send_to_char(ch, "Your preparations are aborted!\r\n"); stop_all_preparations(ch); } /* end general checks */ /* we set up some switches to account for -every- scenario of switches possible this can create unique messages, etc */ switch (new_position) { case POS_DEAD: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_MORTALLYW: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_INCAP: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_STUNNED: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_SLEEPING: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_RECLINING: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_RESTING: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_SITTING: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_FIGHTING: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; case POS_STANDING: switch (old_position) { case POS_DEAD: break; case POS_MORTALLYW: break; case POS_INCAP: break; case POS_STUNNED: break; case POS_SLEEPING: break; case POS_RECLINING: break; case POS_RESTING: break; case POS_SITTING: break; case POS_FIGHTING: break; case POS_STANDING: break; default: break; } break; default: break; } /* this is really all that is going on here :P */ GET_POS(ch) = new_position; /* we don't have a significant return value yet */ if (old_position == new_position) return 0; else return 1; } ACMD(do_sorcerer_draconic_wings) { if (IS_NPC(ch) || !HAS_FEAT(ch, FEAT_DRACONIC_HERITAGE_WINGS)) { send_to_char(ch, "You have no idea how.\r\n"); return; } if (affected_by_spell(ch, SKILL_DRHRT_WINGS)) { send_to_char(ch, "You retract your draconic wings.\r\n"); act("$n retracts a large pair of draconic wings into $s back.", TRUE, ch, 0, 0, TO_ROOM); affect_from_char(ch, SKILL_DRHRT_WINGS); return; } struct affected_type af; new_affect(&af); af.spell = SKILL_DRHRT_WINGS; SET_BIT_AR(af.bitvector, AFF_FLYING); af.duration = -1; affect_to_char(ch, &af); send_to_char(ch, "You spread your draconic wings, giving you flight at a speed of 60.\r\n"); act("$n spreads $s draconic wings.", TRUE, ch, 0, 0, TO_ROOM); } ACMD(do_pullswitch) { //- item-switch( command(push/pull), room, dir, unhide/unlock/open) int other_room = 0; struct room_direction_data *back = 0; int door = 0; int room = 0; struct obj_data *obj; struct char_data *tmp_ch; struct obj_data *dummy = 0; char arg[MAX_INPUT_LENGTH]; one_argument_c(argument, arg, sizeof(arg)); if (!*arg) { send_to_char(ch, "You want to do what?!\r\n"); return; } generic_find(arg, FIND_OBJ_ROOM, ch, &tmp_ch, &obj); if (!obj) { send_to_char(ch, "You do not see that here.\r\n"); return; } if (GET_OBJ_TYPE(obj) != ITEM_SWITCH) { send_to_char(ch, "But that is not a switch\r\n"); return; } if (CMD_IS("pull") && 0 != GET_OBJ_VAL(obj, 0)) { send_to_char(ch, "But you can't pull that.\r\n"); return; } if (CMD_IS("push") && 1 != GET_OBJ_VAL(obj, 0)) { send_to_char(ch, "But you can't push that.\r\n"); return; } room = real_room(GET_OBJ_VAL(obj, 1)); door = GET_OBJ_VAL(obj, 2); if (room < 0) { send_to_char(ch, "Bug in switch here, contact an immortal\r\n"); log("SYSERR: Broken switch: real_room() for %s (VNUM %ld) evaluated to -1", obj->name, obj->id); return; } if (!world[room].dir_option[door]) { send_to_char(ch, "Bug in switch here, contact an immortal\r\n"); return; } if ((other_room = EXITN(room, door)->to_room) != NOWHERE) { if ((back = world[other_room].dir_option[rev_dir[door]])) { if (back->to_room != ch->in_room) back = 0; } } switch (GET_OBJ_VAL(obj, 3)) { case SWITCH_UNHIDE: break; case SWITCH_UNLOCK: UNLOCK_DOOR(room, dummy, door); if (back) UNLOCK_DOOR(other_room, dummy, rev_dir[door]); break; case SWITCH_OPEN: if (EXIT_FLAGGED(world[room].dir_option[door], EX_LOCKED)) UNLOCK_DOOR(room, dummy, door); OPEN_DOOR(room, dummy, door); if (back) { if (EXIT_FLAGGED(world[other_room].dir_option[rev_dir[door]], EX_LOCKED)) UNLOCK_DOOR(other_room, dummy, rev_dir[door]); OPEN_DOOR(other_room, dummy, rev_dir[door]); } break; } if (obj->action_description != NULL) send_to_room(ch->in_room, obj->action_description); else send_to_room(ch->in_room, "*ka-ching*\r\n"); } int get_speed(struct char_data *ch, sbyte to_display) { int speed = 30; switch (GET_RACE(ch)) { case RACE_DWARF: case RACE_CRYSTAL_DWARF: case RACE_HALFLING: case RACE_GNOME: speed = 25; } if (IS_NPC(ch) && MOB_FLAGGED(ch, MOB_MOUNTABLE)) speed = 50; if (is_flying(ch)) speed = 50; // haste and exp. retreat don't stack for balance reasons if (AFF_FLAGGED(ch, AFF_HASTE)) speed += 30; else if (affected_by_spell(ch, SPELL_EXPEDITIOUS_RETREAT)) speed += 30; // likewise, monk speed and fast movement don't stack for balance reasons if (monk_gear_ok(ch)) speed += MIN(60, CLASS_LEVEL(ch, CLASS_MONK) / 3 * 10); else if (HAS_FEAT(ch, FEAT_FAST_MOVEMENT)) if (compute_gear_armor_type(ch) <= ARMOR_TYPE_MEDIUM) speed += 10; if (affected_by_spell(ch, SPELL_GREASE)) speed -= 10; // if they're slowed, it's half regardless. Same with entangled. // if they're blind, they can make an acrobatics check against dc 10 // to avoid halving their speed, but we only want to do this is the // function is called to apply their speed. If to_display is true, // we won't worry about the blind effect, because it's only showing // the person's base speed for display purposes (ie. score) if (AFF_FLAGGED(ch, AFF_SLOW)) speed /= 2; else if (AFF_FLAGGED(ch, AFF_ENTANGLED)) speed /= 2; else if (!to_display && AFF_FLAGGED(ch, AFF_BLIND) && skill_roll(ch, ABILITY_ACROBATICS) < 10) speed /= 2; return speed; } /*EOF*/
29.827318
170
0.581014
ae0becbc23c432e79692bcceb7314f8e12b956e0
1,074
h
C
analysis/filter.h
hzanoli/hf_sim
d0c46650cdfd8c6306e9b3f3cc0d13ae997354f6
[ "MIT" ]
null
null
null
analysis/filter.h
hzanoli/hf_sim
d0c46650cdfd8c6306e9b3f3cc0d13ae997354f6
[ "MIT" ]
null
null
null
analysis/filter.h
hzanoli/hf_sim
d0c46650cdfd8c6306e9b3f3cc0d13ae997354f6
[ "MIT" ]
1
2020-04-29T14:42:44.000Z
2020-04-29T14:42:44.000Z
#include <vector> #include "Pythia8/Pythia.h" namespace analysis { namespace filter { /* Takes as input a vector with particles and a maximum value eta_max that the particle pseudorapidity can have. Returns a vector with the index of particles that are have an absolute pseudoradity smaller than eta_max */ std::vector<int> FilterKinematics(const Pythia8::Event& event, double eta_max = 0.8); /* Finds if a value of type T is in is in vector. Returns true if value is in vector, false otherwise */ template <typename T> inline bool IsInVector(T value, std::vector<T> vector) { return std::find(vector.begin(), vector.end(), value) != vector.end(); } /* Takes as input a vector with the index of particles and a vector with the PDG code of the particles that will be filtered. Returns the particles which the absolute value of the PDG code is in particle_ids*/ std::vector<int> FilterParticles(const Pythia8::Event& event, const std::vector<int>& particles, std::vector<int> particle_ids = {411, 421, 413, 431}); } // namespace filter } // namespace analysis
34.645161
92
0.74581
53a25883e13939762335490c90aa259746d7132a
278
h
C
Moles/system/events/ToneEvent.h
WilliamParty/wacky
d3d792f1b70e31ced8fff37511cc3c9fab4b4606
[ "BSD-2-Clause" ]
null
null
null
Moles/system/events/ToneEvent.h
WilliamParty/wacky
d3d792f1b70e31ced8fff37511cc3c9fab4b4606
[ "BSD-2-Clause" ]
null
null
null
Moles/system/events/ToneEvent.h
WilliamParty/wacky
d3d792f1b70e31ced8fff37511cc3c9fab4b4606
[ "BSD-2-Clause" ]
null
null
null
// // ToneEvent.h // Moles // // Created by William Izzo on 18/09/16. // Copyright © 2016 wizzo. All rights reserved. // #import "Event.h" static const NSUInteger kEventTone = 0x0000A000; @interface ToneEvent : Event{ @public float pitch; double duration; } @end
14.631579
48
0.672662
87e71c4bde8ab5840ac22f036e8821afa0f36f3c
1,771
h
C
MISS Project/simulation/utils.h
Grzego/miss-project
2409d1e737a6790ae38fd6728a0a35557ca6281c
[ "MIT" ]
1
2016-06-17T06:32:31.000Z
2016-06-17T06:32:31.000Z
MISS Project/simulation/utils.h
Grzego/miss-project
2409d1e737a6790ae38fd6728a0a35557ca6281c
[ "MIT" ]
null
null
null
MISS Project/simulation/utils.h
Grzego/miss-project
2409d1e737a6790ae38fd6728a0a35557ca6281c
[ "MIT" ]
null
null
null
#pragma once #include <SFML\Graphics.hpp> #include <unordered_set> #include <unordered_map> struct Vec2 { public: Vec2(int _y = 0, int _x = 0); operator sf::Vector2f const &() const; friend bool operator==(Vec2 const &, Vec2 const &); friend bool operator!=(Vec2 const &, Vec2 const &); friend bool operator<(Vec2 const &, Vec2 const &); int x, y; }; namespace std { template<> struct hash<Vec2> { public: inline size_t operator()(Vec2 const & _v) const { return hash<int>()(_v.x) * 31 + hash<int>()(_v.y); } }; template<> struct hash<pair<int, int>> { public: inline size_t operator()(pair<int, int> const &_p) const { return hash<int>()(_p.first) * 31 + hash<int>()(_p.second); } }; } Vec2 hex_position(double _radius, int _y, int _x); Vec2 hex_position(double _radius, Vec2 const &); Vec2 position_hex(double _radius, int _y, int _x); Vec2 position_hex(double _radius, Vec2 const &); int euklid_dist(Vec2 const &, Vec2 const &); std::vector<Vec2> hex_places(int _y, int _x); std::vector<Vec2> hex_places(Vec2 const &); std::vector<std::pair<Vec2, double>> distribute_point(Vec2 const &, int, double); std::vector<Vec2> on_line(Vec2 const &, Vec2 const &); bool are_same(double, double); double clamp(double, double, double); // --- randomness Vec2 random_element(std::unordered_set<Vec2> const &); int random_int(int, int); double random_double(); // ----- std::vector<std::string> split(std::string _str, char _on); std::string trim(std::string _str); template <typename T> T from_string(std::string _str) { T result; std::stringstream ss; ss << _str; ss >> result; return result; }
19.461538
81
0.630152
8f3e507eb6c7fc34832ebad6f03205f697806665
810
h
C
secret_number_client/GameClient.h
abdalmoez/cpp-secret-number
cd8c00bf0c4f1d712fa48e67c66f22e2f3372a6f
[ "MIT" ]
null
null
null
secret_number_client/GameClient.h
abdalmoez/cpp-secret-number
cd8c00bf0c4f1d712fa48e67c66f22e2f3372a6f
[ "MIT" ]
null
null
null
secret_number_client/GameClient.h
abdalmoez/cpp-secret-number
cd8c00bf0c4f1d712fa48e67c66f22e2f3372a6f
[ "MIT" ]
null
null
null
#ifndef GAMECLIENT_H #define GAMECLIENT_H #include <QtCore/QObject> #include <QtWebSockets/QWebSocket> class MainWindow; const uint32_t INVALID_PLAYER_ID = 0xFFFFFFFF; const uint32_t INVALID_GAME_ID = 0xFFFFFFFF; class GameClient: public QObject { Q_OBJECT public: GameClient(const QUrl &url, MainWindow* parent); bool sendMsg(QString msg); uint32_t getPlayerId() { return m_playerId; } uint32_t getGameId() { return m_currentGameId; } Q_SIGNALS: void closeApp(); private Q_SLOTS: void onConnected(); void onMsgReceived(QString msg); private: QWebSocket m_webSocket; QUrl m_url; uint32_t m_playerId; uint32_t m_currentGameId; MainWindow* m_parent; }; #endif // GAMECLIENT_H
18.837209
53
0.669136
ac7b524809af321d84b7bfe029f195d0153c9771
1,388
h
C
src/VertexBufferLayout.h
hai-bu-cuo/Fust
6956ffea8ff1504fc39539c009d5424ea7de34dd
[ "Apache-2.0" ]
null
null
null
src/VertexBufferLayout.h
hai-bu-cuo/Fust
6956ffea8ff1504fc39539c009d5424ea7de34dd
[ "Apache-2.0" ]
null
null
null
src/VertexBufferLayout.h
hai-bu-cuo/Fust
6956ffea8ff1504fc39539c009d5424ea7de34dd
[ "Apache-2.0" ]
null
null
null
#pragma once #include<vector> #include"Renderer.h" struct VertexBufferElement { unsigned int type; int count; unsigned char normalized; static unsigned int GetSizeOfType(unsigned int type) { switch (type) { case GL_FLOAT: return 4; case GL_UNSIGNED_INT: return 4; case GL_UNSIGNED_BYTE: return 1; } ASSERT(false); return 0; } }; class VertexBufferLayout { private: std::vector<VertexBufferElement> m_Elements; unsigned int m_Stride; public: VertexBufferLayout() :m_Stride(0) { } ~VertexBufferLayout() { } template<typename T> void Push(int count) { static_assert(false); } template<> void Push<float>(int count) { m_Elements.push_back({ GL_FLOAT,count,GL_FALSE }); m_Stride += count * VertexBufferElement::GetSizeOfType(GL_FLOAT); } template<> void Push<unsigned int>(int count) { m_Elements.push_back({ GL_UNSIGNED_INT,count,GL_FALSE }); m_Stride += count * VertexBufferElement::GetSizeOfType(GL_UNSIGNED_INT); } template<> void Push<unsigned char>(int count) { m_Elements.push_back({ GL_UNSIGNED_BYTE,count,GL_FALSE }); m_Stride += count * VertexBufferElement::GetSizeOfType(GL_UNSIGNED_BYTE); } inline const std::vector<VertexBufferElement> GetElement() const { return m_Elements; } inline unsigned int GetStride() const { return m_Stride; } };
20.716418
89
0.696686
fede0124ae33e63a2eb8ccc4c1cb89a3a6894537
3,111
h
C
engine/source/network/connectionProtocol.h
close-code/Torque2D
ad141fc7b5f28b75f727ef29dcc93aafbb3f5aa3
[ "MIT" ]
1,309
2015-01-01T02:46:14.000Z
2022-03-14T04:56:02.000Z
engine/source/network/connectionProtocol.h
SwaroopGuvvala/Torque2D
55efccc7c7a4331547f5d71c733a75b8de1189e8
[ "MIT" ]
155
2015-01-11T19:26:32.000Z
2021-11-22T04:08:55.000Z
engine/source/network/connectionProtocol.h
SwaroopGuvvala/Torque2D
55efccc7c7a4331547f5d71c733a75b8de1189e8
[ "MIT" ]
1,595
2015-01-01T23:19:48.000Z
2022-02-17T07:00:52.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- #ifndef _CONNECTION_PROTOCOL_H_ #define _CONNECTION_PROTOCOL_H_ #ifndef _PLATFORM_H_ #include "platform/platform.h" #endif #ifndef _EVENT_H_ #include "platform/event.h" #endif class BitStream; class ResizeBitStream; /// The base class for Torque's networking protocol. /// /// This implements a sliding window connected message stream over an unreliable transport (UDP). It /// provides a simple notify protocol to allow subclasses to be aware of what packets were sent /// succesfully and which failed. /// /// Basically, a window size of 32 is provided, and each packet contains in the header a bitmask, /// acknowledging the receipt (or failure to receive) of the last 32 packets. /// /// @see NetConnection, @ref NetProtocol class ConnectionProtocol { protected: U32 mLastSeqRecvdAtSend[32]; U32 mLastSeqRecvd; U32 mHighestAckedSeq; U32 mLastSendSeq; U32 mAckMask; U32 mConnectSequence; U32 mLastRecvAckAck; bool mConnectionEstablished; public: ConnectionProtocol(); void buildSendPacketHeader(BitStream *bstream, S32 packetType = 0); void sendPingPacket(); void sendAckPacket(); void setConnectionEstablished() { mConnectionEstablished = true; } bool windowFull(); bool connectionEstablished(); void setConnectSequence(U32 connectSeq) { mConnectSequence = connectSeq; } virtual void writeDemoStartBlock(ResizeBitStream *stream); virtual bool readDemoStartBlock(BitStream *stream); virtual void processRawPacket(BitStream *bstream); virtual Net::Error sendPacket(BitStream *bstream) = 0; virtual void keepAlive() = 0; virtual void handleConnectionEstablished() = 0; virtual void handleNotify(bool recvd) = 0; virtual void handlePacket(BitStream *bstream) = 0; }; #endif
37.939024
101
0.702025
3a1be2dd7cc57e7668b439b8d7c3433a1f5ee895
1,164
c
C
Experiment_7/Exp7.c
vishalvijaynair/DS-LAB
34b9ffff6cef3660a89a9c9a0426223d178aa486
[ "MIT" ]
null
null
null
Experiment_7/Exp7.c
vishalvijaynair/DS-LAB
34b9ffff6cef3660a89a9c9a0426223d178aa486
[ "MIT" ]
null
null
null
Experiment_7/Exp7.c
vishalvijaynair/DS-LAB
34b9ffff6cef3660a89a9c9a0426223d178aa486
[ "MIT" ]
null
null
null
#include <stdio.h> #include<stdlib.h> struct stack{ int data; struct stack *next; }; struct stack *s=NULL; struct stack *temp; int x; struct stack* push(){ printf("Enter number to be pushed:\n"); scanf("%d",&x); temp=(struct stack*)malloc(sizeof(struct stack)); temp->data=x; temp->next=s; s=temp; temp=NULL; return s; } struct stack* pop(){ if(s==NULL){ printf("Stack is empty\n"); return s; } x=s->data; printf("Value poped is:%d\n",x); temp=s; s=s->next; temp->next=NULL; free(temp); temp=NULL; return s; } void dsply(struct stack *s){ if(s==NULL) printf("Stack is empty\n"); else{ printf("Values in stack are:\n"); while(s!=NULL){ printf("%d\t",s->data); s=s->next; } printf("\n"); } } int main(){ int o,a; do{ printf("Choose the operation to be peformed:(1.Push/2.Pop/3.Display)\n"); scanf("%d",&o); switch(o){ case 1:s=push(); break; case 2:s=pop(); break; case 3:dsply(s); break; default:printf("Choose a valid option..\n"); } printf("Do you want to continue?(1 for Yes/0 for No)\n"); scanf("%d",&a); printf("\n"); }while(a==1); return 0; }
16.394366
75
0.581615
6b54f0e932920c613208411a6515ec268779ce46
4,664
h
C
Source/Io/PodCommon.h
glhrmfrts/Io
2df31f550d3d8f0501f5de17290e781af5fcdcb3
[ "MIT" ]
2
2020-08-27T22:49:30.000Z
2021-06-14T14:01:32.000Z
Source/Io/PodCommon.h
glhrmfrts/Io
2df31f550d3d8f0501f5de17290e781af5fcdcb3
[ "MIT" ]
null
null
null
Source/Io/PodCommon.h
glhrmfrts/Io
2df31f550d3d8f0501f5de17290e781af5fcdcb3
[ "MIT" ]
null
null
null
#pragma once #include <Urho3D/Core/Context.h> #include <Urho3D/IO/File.h> #include <Urho3D/IO/Deserializer.h> #include <string> #include "Application.h" #include "Utils.h" enum PodFilesOffset { PodBv4Key = 0x00000F2E, PodBv4Len = 0x00001000 }; enum PodFileType { FILE_VEHICLE, FILE_CIRCUIT, }; enum PodFileFlags { FLAG_NAMED_FACES = 1, FLAG_FACE_UNK_PROPERTY = (1 << 1), FLAG_OBJ_HAS_PRISM = (1 << 2), }; typedef int fp1616_t; struct ImageData { char FileName[32]; uint32_t Left; uint32_t Top; uint32_t Right; uint32_t Bottom; uint32_t ImageFlags; // 00000001 = Non-zero pixel(s)? }; struct ImageList { uint32_t Count; UniqueArray<ImageData> ImgData; }; struct TexturePixelData { UniqueArray<uint16_t> Pixels; // RGB565 }; struct TextureList { int Width, Height; // runtime uint32_t Count; uint32_t Flags; UniqueArray<ImageList> ImageList; UniqueArray<TexturePixelData> PixelData; }; struct ObjectData; struct FaceData; struct FaceData { bool IsVisible() const; String Name; // if (NamedFaces) uint32_t Vertices; // 3..4 uint32_t Indices[4]; fp1616_t Normal[3]; String MaterialType; uint32_t ColorOrTexIndex; float TexCoord[4][2]; uint32_t Reserved1; uint32_t Reserved2; // Circuit only, if (Normal == VectorZero) fp1616_t QuadReserved[3]; // if (Vertices == 4) uint32_t Unknown; // (if HasUnk) uint32_t FaceProperties; ObjectData* Obj; // ptr to owner obj Vector2 AnimTexCoord[4]; bool UseAnimTexCoord; }; struct ObjectData { uint32_t VertexCount; // uint16_t UniqueArray<fp1616_t> VertexArray; // [VertexCount][3] uint32_t FaceCount; uint32_t TriangleCount; // used for alloc uint32_t QuadrangleCount; // used for alloc UniqueArray<FaceData> FaceData; // [FaceCount] UniqueArray<fp1616_t> Normals; // [VertexCount] [3] uint32_t Unknown; uint8_t Prism[28]; // Vehicle only PODVector<::FaceData*> TriFaces; PODVector<::FaceData*> QuadFaces; }; class PodBdfFile : public Deserializer { public: explicit PodBdfFile(Context* context, const String& fileName); bool Load(); virtual bool LoadData() = 0; /// Read bytes from the stream. Return number of bytes actually read. unsigned Read(void* dest, unsigned size) override; /// Set position from the beginning of the stream. Return actual new position. unsigned Seek(unsigned position) override; /// Read an encrypted pod string String ReadPodString(); /// Seek an offset at the offset table. Return actual new position unsigned int SeekOffset(unsigned int idx); float ReadFloat(); Vector3 ReadVector3(); Matrix3 ReadMatrix3(); void ReadTextureList(TextureList& list, int width, int height); void ReadFace(FaceData& face, unsigned int flags); void ReadObject(ObjectData& obj, unsigned int flags); const String& GetFileName() { return fileName_; } template<typename T, typename Functor, typename... Args> void ReadArray(Vector<T>& arr, Functor f, Args&&... args) { arr.Resize(ReadUInt()); for (uint32_t i = 0; i < arr.Size(); i++) f(*this, arr[i], std::forward<Args>(args)...); } template<typename T, typename Functor, typename... Args> void ReadArrayN(Vector<T>& arr, int count, Functor f, Args&&... args) { arr.Resize(count); for (uint32_t i = 0; i < arr.Size(); i++) f(*this, arr[i], std::forward<Args>(args)...); } Context* context_; PodFileType fileType_; private: String fileName_; /// Decrypted data PODVector<unsigned char> data_; /// Offsets relative to data start PODVector<int> offsets_; /// Header end offset unsigned int headerEnd_; /// Encryption key unsigned int key_; /// Block size unsigned int blockSize_; }; static float FloatFromFP1616(fp1616_t fp) { return fp / float(1 << 16); } static Vector3 Vector3FromFP1616(fp1616_t* fp) { return Vector3(FloatFromFP1616(fp[0]), FloatFromFP1616(fp[1]), FloatFromFP1616(fp[2])); } static Color ColorFromRGB565(uint16_t pix) { uint8_t r5 = (pix >> 11) & 0x001f; uint8_t g6 = (pix & 0x07e0) >> 5; uint8_t b5 = (pix & 0x001f); uint8_t r = (r5 * 527 + 23) >> 6; uint8_t g = (g6 * 259 + 33) >> 6; uint8_t b = (b5 * 527 + 23) >> 6; return Color(float(r) / 255.0f, float(g) / 255.0f, float(b) / 255.0f, 1.0f); } static Vector3 PodTransform(const Vector3& v) { return Vector3(-v.y_, v.z_, v.x_); }
23.795918
91
0.64494
38e3f6ba11632d40ed5110097edc238a63a5ae41
1,540
h
C
IAP/Src/myUsartFunction.h
XiaojiaoChen/HydrosoftBootLoader
99c8849545eaef816c6a6345eda1a407eaeba83b
[ "MIT" ]
null
null
null
IAP/Src/myUsartFunction.h
XiaojiaoChen/HydrosoftBootLoader
99c8849545eaef816c6a6345eda1a407eaeba83b
[ "MIT" ]
null
null
null
IAP/Src/myUsartFunction.h
XiaojiaoChen/HydrosoftBootLoader
99c8849545eaef816c6a6345eda1a407eaeba83b
[ "MIT" ]
null
null
null
///* // * myUsartFunction.h // * // * Created on: Jun 12, 2018 // * Author: 402072495 // */ // //#ifndef FRAMEINC_MYUSARTFUNCTION_H_ //#define FRAMEINC_MYUSARTFUNCTION_H_ // //#ifdef __cplusplus // extern "C" { //#endif // //#include "main.h" //#include "stdio.h" // // //#define UART_TX_BUF_SIZE 2048 //#define UART_RX_BUF_SIZE 30 // ////---------------------------RING BUFFER-------------------------- //// ////| 0 | 1 | 2 | 3 | 4 | 5 | ... |UART_TX_BUF_SIZE-1| ////|---flushLen----|------------------------------|--------flushLen-----------| //// * * //// bufStartNum flushStartNum // // // //---------------------------RING BUFFER-------------------------- // // // //| 0 | 1 | 2 | 3 | 4 | 5 | ... |UART_TX_BUF_SIZE-1| // //|-------------------------------------------|----flushLen--|---------------| // // * * // // flushStartNum bufStartNum // // ////possible to overlap sending data in exchange for better utilization // // // typedef struct UART_DEVICE_STRUCT{ // uint8_t TxBuf[UART_TX_BUF_SIZE]; /*Tx ring + dynamic Buffer */ // // int16_t flushStartNum; // int16_t flushLen; // // int16_t bufStartNum; // int16_t transLen; // uint8_t isFree; // // UART_HandleTypeDef *huart; // //}UART_DEVICE; // //extern UART_DEVICE Usart1Device; // //#ifdef __cplusplus //} //#endif // // //#endif /* FRAMEINC_MYUSARTFUNCTION_H_ */
24.444444
81
0.447403
df85e0c0cead3d5a5727db03ad2162f64bccf861
5,990
h
C
source/Audio/AudioSystem.h
BodbDearg/phoenix_doom
9648b1cc742634d5aefc18cd3699cd7cb2c0e21c
[ "MIT" ]
29
2019-09-25T06:29:07.000Z
2022-02-20T23:52:36.000Z
source/Audio/AudioSystem.h
monyarm/phoenix_doom
78c75f985803b94b981469ac32764169ed56aee4
[ "MIT" ]
4
2019-09-25T03:24:31.000Z
2020-09-07T18:38:32.000Z
source/Audio/AudioSystem.h
monyarm/phoenix_doom
78c75f985803b94b981469ac32764169ed56aee4
[ "MIT" ]
4
2019-09-26T06:43:12.000Z
2020-09-05T16:25:03.000Z
#pragma once #include "AudioVoice.h" #include <cstdint> #include <vector> class AudioDataMgr; class AudioOutputDevice; struct AudioData; //------------------------------------------------------------------------------------------------------------------------------------------ // Manages a collection of playing audio voices. // Also has a master volume and pause setting for the system. //------------------------------------------------------------------------------------------------------------------------------------------ class AudioSystem { public: // Default master volume static constexpr float DEFAULT_MASTER_VOLUME = 1.0f; // Voice index type and voice index returned to indicate an invalid voice typedef uint32_t VoiceIdx; static constexpr VoiceIdx INVALID_VOICE_IDX = UINT32_MAX; AudioSystem() noexcept; ~AudioSystem() noexcept; //------------------------------------------------------------------------------------------------------------------ // Notes: // (1) The given data manager MUST remain valid for the lifetime of the audio system. // (2) The given device MUST remain valid for the lifetime of the audio system. //------------------------------------------------------------------------------------------------------------------ void init(AudioOutputDevice& device, AudioDataMgr& dataMgr, const uint32_t maxVoices = 32) noexcept; void shutdown() noexcept; inline bool isInitialized() const noexcept { return mbIsInitialized; } inline AudioOutputDevice* getAudioOutputDevice() const { return mpAudioOutputDevice; } inline AudioDataMgr* getAudioDataMgr() const { return mpAudioDataMgr; } //------------------------------------------------------------------------------------------------------------------ // Get or set the state of a particular voice and query the number of voices //------------------------------------------------------------------------------------------------------------------ inline uint32_t getNumVoices() const { return (uint32_t) mVoices.size(); } AudioVoice getVoiceState(const VoiceIdx voiceIdx) const noexcept; void setVoiceState(const VoiceIdx voiceIdx, const AudioVoice& state) noexcept; //------------------------------------------------------------------------------------------------------------------ // Get or set the master volume for the system //------------------------------------------------------------------------------------------------------------------ inline float getMasterVolume() const { return mMasterVolume; } void setMasterVolume(const float volume) noexcept; //------------------------------------------------------------------------------------------------------------------ // Pause or unpause the entire system and query if paused //------------------------------------------------------------------------------------------------------------------ inline bool isPaused() const noexcept { return mbIsPaused; } void pause(const bool pause) noexcept; //------------------------------------------------------------------------------------------------------------------ // Try to play a particular audio piece with the given handle. // Returns the index of the voice allocated to the audio, or 'INVALID_VOICE_IDX' on failure. // Optionally, you can specify to stop other instances of the same sound. //------------------------------------------------------------------------------------------------------------------ VoiceIdx play( const uint32_t audioDataHandle, const bool bLooped = false, const float lVolume = 1.0f, const float rVolume = 1.0f, const bool bStopOtherInstances = false ) noexcept; //------------------------------------------------------------------------------------------------------------------ // Tell how many non stopped voices have the given audio data //------------------------------------------------------------------------------------------------------------------ uint32_t getNumVoicesWithAudioData(const uint32_t audioDataHandle) noexcept; //------------------------------------------------------------------------------------------------------------------ // Stop all voices in the system, a particular voice or voices with a particular sound //------------------------------------------------------------------------------------------------------------------ void stopAllVoices() noexcept; void stopVoice(const VoiceIdx voiceIdx) noexcept; void stopVoicesWithAudioData(const uint32_t audioDataHandle) noexcept; //------------------------------------------------------------------------------------------------------------------ // Called by the audio output device on the audio thread. // Should *NEVER* be called on any other thread as it already assumes the audio device is locked! // // This function should mix in (add) the requested number of audio samples in 2 channel stero // at the sample rate that the current audio device uses. The left/right stereo data should also // be interleaved for each sample point. //------------------------------------------------------------------------------------------------------------------ void mixAudio(float* const pSamples, const uint32_t numSamples) noexcept; private: void removeFromFreeVoiceList(const VoiceIdx voiceIdx) noexcept; void mixVoiceAudio( AudioVoice& voice, const AudioData& audioData, float* const pSamples, const uint32_t numSamples ) noexcept; bool mbIsInitialized; bool mbIsPaused; AudioOutputDevice* mpAudioOutputDevice; AudioDataMgr* mpAudioDataMgr; float mMasterVolume; std::vector<AudioVoice> mVoices; std::vector<uint32_t> mFreeVoices; };
53.963964
140
0.448414
8dc08ee460215c2b3fb7cd696941c75f4fe7bf7a
2,977
h
C
src/net/ssl/ssl_private_key.h
Chilledheart/naiveproxy
9d28da89b325a90d33add830f4202c8b17c7c3e3
[ "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
src/net/ssl/ssl_private_key.h
Chilledheart/naiveproxy
9d28da89b325a90d33add830f4202c8b17c7c3e3
[ "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
src/net/ssl/ssl_private_key.h
Chilledheart/naiveproxy
9d28da89b325a90d33add830f4202c8b17c7c3e3
[ "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2015 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 NET_SSL_SSL_PRIVATE_KEY_H_ #define NET_SSL_SSL_PRIVATE_KEY_H_ #include <stdint.h> #include <vector> #include "base/callback_forward.h" #include "base/containers/span.h" #include "base/memory/ref_counted.h" #include "net/base/net_errors.h" #include "net/base/net_export.h" namespace net { // An interface for a private key for use with SSL client authentication. A // private key may be used with multiple signature algorithms, so methods use // |SSL_SIGN_*| constants from BoringSSL, which correspond to TLS 1.3 // SignatureScheme values. // // Note that although ECDSA constants are named like // |SSL_SIGN_ECDSA_SECP256R1_SHA256|, they may be used with any curve for // purposes of this API. This descrepancy is due to differences between TLS 1.2 // and TLS 1.3. class NET_EXPORT SSLPrivateKey : public base::RefCountedThreadSafe<SSLPrivateKey> { public: using SignCallback = base::OnceCallback<void(Error, const std::vector<uint8_t>&)>; SSLPrivateKey() {} SSLPrivateKey(const SSLPrivateKey&) = delete; SSLPrivateKey& operator=(const SSLPrivateKey&) = delete; // Returns a human-readable name of the provider that backs this // SSLPrivateKey, for debugging. If not applicable or available, return the // empty string. virtual std::string GetProviderName() = 0; // Returns the algorithms that are supported by the key in decreasing // preference for TLS 1.2 and later. Note that |SSL_SIGN_RSA_PKCS1_MD5_SHA1| // is only used by TLS 1.1 and earlier and should not be in this list. virtual std::vector<uint16_t> GetAlgorithmPreferences() = 0; // Asynchronously signs an |input| with the specified TLS signing algorithm. // |input| is an unhashed message to be signed. On completion, it calls // |callback| with the signature or an error code if the operation failed. virtual void Sign(uint16_t algorithm, base::span<const uint8_t> input, SignCallback callback) = 0; // Returns the default signature algorithm preferences for the specified key // type, which should be a BoringSSL |EVP_PKEY_*| constant. RSA keys which use // this must support PKCS #1 v1.5 signatures with SHA-1, SHA-256, SHA-384, and // SHA-512. If |supports_pss| is true, they must additionally support PSS // signatures with SHA-256, SHA-384, and SHA-512. ECDSA keys must support // SHA-256, SHA-384, SHA-512. // // Keys with more specific capabilities or preferences should return a custom // list. static std::vector<uint16_t> DefaultAlgorithmPreferences(int type, bool supports_pss); protected: virtual ~SSLPrivateKey() {} private: friend class base::RefCountedThreadSafe<SSLPrivateKey>; }; } // namespace net #endif // NET_SSL_SSL_PRIVATE_KEY_H_
37.683544
80
0.724555
ce5ac42c5e1c0d007141b4d74e56d4654a0114db
614
h
C
IngenicoDirectSDK/IDBasicPaymentProducts.h
Ingenico/direct-sdk-client-objc
aa2a0e3b8c771fcf8b8d3174651502b717be365f
[ "MIT" ]
null
null
null
IngenicoDirectSDK/IDBasicPaymentProducts.h
Ingenico/direct-sdk-client-objc
aa2a0e3b8c771fcf8b8d3174651502b717be365f
[ "MIT" ]
null
null
null
IngenicoDirectSDK/IDBasicPaymentProducts.h
Ingenico/direct-sdk-client-objc
aa2a0e3b8c771fcf8b8d3174651502b717be365f
[ "MIT" ]
null
null
null
// // Do not remove or alter the notices in this preamble. // This software code is created for Ingencio ePayments on 17/07/2020 // Copyright © 2020 Global Collect Services. All rights reserved. // #import <Foundation/Foundation.h> #import "IDBasicPaymentProduct.h" @interface IDBasicPaymentProducts : NSObject @property (strong, nonatomic) NSMutableArray *paymentProducts; - (BOOL)hasAccountsOnFile; - (NSArray *)accountsOnFile; - (IDBasicPaymentProduct *)paymentProductWithIdentifier:(NSString *)paymentProductIdentifier; - (void)sort; - (void)setStringFormatter:(IDStringFormatter *)stringFormatter; @end
29.238095
93
0.785016
ced8e7d3efa4d91e37f982dafd369c8c06dd4b0e
1,854
h
C
src/inspector.h
gfeyer/KafkaDesktopClient
009bb12bb340d9c6d7714469e9b2dccf838b71e9
[ "Apache-2.0" ]
7
2021-11-30T01:33:31.000Z
2022-01-28T21:16:26.000Z
src/inspector.h
gfeyer/KafkaDesktopClient
009bb12bb340d9c6d7714469e9b2dccf838b71e9
[ "Apache-2.0" ]
null
null
null
src/inspector.h
gfeyer/KafkaDesktopClient
009bb12bb340d9c6d7714469e9b2dccf838b71e9
[ "Apache-2.0" ]
1
2021-05-18T13:34:22.000Z
2021-05-18T13:34:22.000Z
#ifndef INSPECTOR_H #define INSPECTOR_H // this needs to be defined on windows otherwise it will clash with rdkafka lib #ifdef _WIN32 #define _SSIZE_T // on MAC does not compile with this on #endif #include <memory> #include <mutex> #include <string> #include "ui/noname.h" #include "databuffer.h" #include "scheduler.h" class Inspector : public InspectorPanel { public: Inspector(wxWindow* window); ~Inspector(); void SetFilter(std::string); void SetTopic(std::string); std::string GetFilter(); std::string GetTopic(); std::vector<std::shared_ptr<std::string>> GetDisplayResults(); void AddToBuffer(std::shared_ptr<std::string> request); void AddToBuffer(std::string request); void ForceRefresh(void); private: // GUI Callbacks void OnRun(wxCommandEvent& event); void OnStop(wxCommandEvent& event); void OnFilter(wxCommandEvent& event); void OnKeyUpFilter(wxKeyEvent& event); void OnSelect(wxDataViewEvent& event); void OnSearchPartial(wxCommandEvent& event); void OnSearch(wxCommandEvent& event); void OnSearchCancel(wxCommandEvent& event); // Util func enum class State { Idle = 1, Connecting, Running}; void SetGUIState(State); void SyncCache(); void UpdateStats(); void ShowMessage(std::string); void ShowErrorDialog(std::string); // State state_; // Data Buffer used to accumulate kafka packets DataBuffer<std::shared_ptr<std::string>> buffer_; // shared_ptr because this will be passed down to the kafka consumer on another thread std::shared_ptr<bool> is_streaming_; // Filter and type selected in inspector std::string filter_query_; std::string filter_type_; // Scheduler for executing callbacks on main thread std::shared_ptr<Scheduler> scheduler_; // Help text const static std::string help; private: void OnMarginClick(wxStyledTextEvent& event); }; #endif // INSPECTOR_H
24.077922
87
0.74973
e1a1c29659792ed2759bd342b87ac226de48c7ae
6,388
c
C
kubernetes/model/v1beta1_mutating_webhook_configuration.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
69
2020-03-17T13:47:05.000Z
2022-03-30T08:25:05.000Z
kubernetes/model/v1beta1_mutating_webhook_configuration.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
115
2020-03-17T14:53:19.000Z
2022-03-31T11:31:30.000Z
kubernetes/model/v1beta1_mutating_webhook_configuration.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
28
2020-03-17T13:42:21.000Z
2022-03-19T23:37:16.000Z
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v1beta1_mutating_webhook_configuration.h" v1beta1_mutating_webhook_configuration_t *v1beta1_mutating_webhook_configuration_create( char *api_version, char *kind, v1_object_meta_t *metadata, list_t *webhooks ) { v1beta1_mutating_webhook_configuration_t *v1beta1_mutating_webhook_configuration_local_var = malloc(sizeof(v1beta1_mutating_webhook_configuration_t)); if (!v1beta1_mutating_webhook_configuration_local_var) { return NULL; } v1beta1_mutating_webhook_configuration_local_var->api_version = api_version; v1beta1_mutating_webhook_configuration_local_var->kind = kind; v1beta1_mutating_webhook_configuration_local_var->metadata = metadata; v1beta1_mutating_webhook_configuration_local_var->webhooks = webhooks; return v1beta1_mutating_webhook_configuration_local_var; } void v1beta1_mutating_webhook_configuration_free(v1beta1_mutating_webhook_configuration_t *v1beta1_mutating_webhook_configuration) { if(NULL == v1beta1_mutating_webhook_configuration){ return ; } listEntry_t *listEntry; if (v1beta1_mutating_webhook_configuration->api_version) { free(v1beta1_mutating_webhook_configuration->api_version); v1beta1_mutating_webhook_configuration->api_version = NULL; } if (v1beta1_mutating_webhook_configuration->kind) { free(v1beta1_mutating_webhook_configuration->kind); v1beta1_mutating_webhook_configuration->kind = NULL; } if (v1beta1_mutating_webhook_configuration->metadata) { v1_object_meta_free(v1beta1_mutating_webhook_configuration->metadata); v1beta1_mutating_webhook_configuration->metadata = NULL; } if (v1beta1_mutating_webhook_configuration->webhooks) { list_ForEach(listEntry, v1beta1_mutating_webhook_configuration->webhooks) { v1beta1_mutating_webhook_free(listEntry->data); } list_free(v1beta1_mutating_webhook_configuration->webhooks); v1beta1_mutating_webhook_configuration->webhooks = NULL; } free(v1beta1_mutating_webhook_configuration); } cJSON *v1beta1_mutating_webhook_configuration_convertToJSON(v1beta1_mutating_webhook_configuration_t *v1beta1_mutating_webhook_configuration) { cJSON *item = cJSON_CreateObject(); // v1beta1_mutating_webhook_configuration->api_version if(v1beta1_mutating_webhook_configuration->api_version) { if(cJSON_AddStringToObject(item, "apiVersion", v1beta1_mutating_webhook_configuration->api_version) == NULL) { goto fail; //String } } // v1beta1_mutating_webhook_configuration->kind if(v1beta1_mutating_webhook_configuration->kind) { if(cJSON_AddStringToObject(item, "kind", v1beta1_mutating_webhook_configuration->kind) == NULL) { goto fail; //String } } // v1beta1_mutating_webhook_configuration->metadata if(v1beta1_mutating_webhook_configuration->metadata) { cJSON *metadata_local_JSON = v1_object_meta_convertToJSON(v1beta1_mutating_webhook_configuration->metadata); if(metadata_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "metadata", metadata_local_JSON); if(item->child == NULL) { goto fail; } } // v1beta1_mutating_webhook_configuration->webhooks if(v1beta1_mutating_webhook_configuration->webhooks) { cJSON *webhooks = cJSON_AddArrayToObject(item, "webhooks"); if(webhooks == NULL) { goto fail; //nonprimitive container } listEntry_t *webhooksListEntry; if (v1beta1_mutating_webhook_configuration->webhooks) { list_ForEach(webhooksListEntry, v1beta1_mutating_webhook_configuration->webhooks) { cJSON *itemLocal = v1beta1_mutating_webhook_convertToJSON(webhooksListEntry->data); if(itemLocal == NULL) { goto fail; } cJSON_AddItemToArray(webhooks, itemLocal); } } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v1beta1_mutating_webhook_configuration_t *v1beta1_mutating_webhook_configuration_parseFromJSON(cJSON *v1beta1_mutating_webhook_configurationJSON){ v1beta1_mutating_webhook_configuration_t *v1beta1_mutating_webhook_configuration_local_var = NULL; // v1beta1_mutating_webhook_configuration->api_version cJSON *api_version = cJSON_GetObjectItemCaseSensitive(v1beta1_mutating_webhook_configurationJSON, "apiVersion"); if (api_version) { if(!cJSON_IsString(api_version)) { goto end; //String } } // v1beta1_mutating_webhook_configuration->kind cJSON *kind = cJSON_GetObjectItemCaseSensitive(v1beta1_mutating_webhook_configurationJSON, "kind"); if (kind) { if(!cJSON_IsString(kind)) { goto end; //String } } // v1beta1_mutating_webhook_configuration->metadata cJSON *metadata = cJSON_GetObjectItemCaseSensitive(v1beta1_mutating_webhook_configurationJSON, "metadata"); v1_object_meta_t *metadata_local_nonprim = NULL; if (metadata) { metadata_local_nonprim = v1_object_meta_parseFromJSON(metadata); //nonprimitive } // v1beta1_mutating_webhook_configuration->webhooks cJSON *webhooks = cJSON_GetObjectItemCaseSensitive(v1beta1_mutating_webhook_configurationJSON, "webhooks"); list_t *webhooksList; if (webhooks) { cJSON *webhooks_local_nonprimitive; if(!cJSON_IsArray(webhooks)){ goto end; //nonprimitive container } webhooksList = list_create(); cJSON_ArrayForEach(webhooks_local_nonprimitive,webhooks ) { if(!cJSON_IsObject(webhooks_local_nonprimitive)){ goto end; } v1beta1_mutating_webhook_t *webhooksItem = v1beta1_mutating_webhook_parseFromJSON(webhooks_local_nonprimitive); list_addElement(webhooksList, webhooksItem); } } v1beta1_mutating_webhook_configuration_local_var = v1beta1_mutating_webhook_configuration_create ( api_version ? strdup(api_version->valuestring) : NULL, kind ? strdup(kind->valuestring) : NULL, metadata ? metadata_local_nonprim : NULL, webhooks ? webhooksList : NULL ); return v1beta1_mutating_webhook_configuration_local_var; end: if (metadata_local_nonprim) { v1_object_meta_free(metadata_local_nonprim); metadata_local_nonprim = NULL; } return NULL; }
35.292818
154
0.755636
35e97bce0ba5bff430370eae45efe4261f80b954
1,763
h
C
src/visitpy/visitpy/PyGlobalLineoutAttributes.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
226
2018-12-29T01:13:49.000Z
2022-03-30T19:16:31.000Z
src/visitpy/visitpy/PyGlobalLineoutAttributes.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
5,100
2019-01-14T18:19:25.000Z
2022-03-31T23:08:36.000Z
src/visitpy/visitpy/PyGlobalLineoutAttributes.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
84
2019-01-24T17:41:50.000Z
2022-03-10T10:01:46.000Z
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. #ifndef PY_GLOBALLINEOUTATTRIBUTES_H #define PY_GLOBALLINEOUTATTRIBUTES_H #include <Python.h> #include <Py2and3Support.h> #include <GlobalLineoutAttributes.h> #include <visitpy_exports.h> // // Functions exposed to the VisIt module. // #define GLOBALLINEOUTATTRIBUTES_NMETH 20 void VISITPY_API PyGlobalLineoutAttributes_StartUp(GlobalLineoutAttributes *subj, void *data); void VISITPY_API PyGlobalLineoutAttributes_CloseDown(); VISITPY_API PyMethodDef * PyGlobalLineoutAttributes_GetMethodTable(int *nMethods); bool VISITPY_API PyGlobalLineoutAttributes_Check(PyObject *obj); VISITPY_API GlobalLineoutAttributes * PyGlobalLineoutAttributes_FromPyObject(PyObject *obj); VISITPY_API PyObject * PyGlobalLineoutAttributes_New(); VISITPY_API PyObject * PyGlobalLineoutAttributes_Wrap(const GlobalLineoutAttributes *attr); void VISITPY_API PyGlobalLineoutAttributes_SetParent(PyObject *obj, PyObject *parent); void VISITPY_API PyGlobalLineoutAttributes_SetDefaults(const GlobalLineoutAttributes *atts); std::string VISITPY_API PyGlobalLineoutAttributes_GetLogString(); std::string VISITPY_API PyGlobalLineoutAttributes_ToString(const GlobalLineoutAttributes *, const char *); VISITPY_API PyObject * PyGlobalLineoutAttributes_getattr(PyObject *self, char *name); int VISITPY_API PyGlobalLineoutAttributes_setattr(PyObject *self, char *name, PyObject *args); VISITPY_API extern PyMethodDef PyGlobalLineoutAttributes_methods[GLOBALLINEOUTATTRIBUTES_NMETH]; #endif
53.424242
109
0.811117
b8b8ef9de17b525f96c52fb496d1ced17d411ab8
44
h
C
_libs/SurfingTextEditor/SurfingTextEditor.h
moebiussurfing/ofxSurfingImGui
d12a3f75f99c8737d956c52077b6e9f0463fe7d9
[ "MIT" ]
11
2021-06-27T09:02:07.000Z
2022-03-13T07:40:36.000Z
_libs/SurfingTextEditor/SurfingTextEditor.h
moebiussurfing/ofxSurfingImGui
d12a3f75f99c8737d956c52077b6e9f0463fe7d9
[ "MIT" ]
null
null
null
_libs/SurfingTextEditor/SurfingTextEditor.h
moebiussurfing/ofxSurfingImGui
d12a3f75f99c8737d956c52077b6e9f0463fe7d9
[ "MIT" ]
6
2021-06-09T08:01:36.000Z
2021-12-06T07:28:52.000Z
#pragma once #include "TextEditorDemo.cpp"
11
29
0.772727
3373a548f76baafaeddf2d9fdb2c002d1dcac8b9
5,179
h
C
third_party/mplayer/libmpdemux/demux_avs.h
Narflex/sagetv
76cb5755e54fd3b01d2bb708a8a72af0aa1533f1
[ "Apache-2.0" ]
292
2015-08-10T18:34:55.000Z
2022-01-26T00:38:45.000Z
third_party/mplayer/libmpdemux/demux_avs.h
Narflex/sagetv
76cb5755e54fd3b01d2bb708a8a72af0aa1533f1
[ "Apache-2.0" ]
366
2015-08-10T18:21:02.000Z
2022-01-22T20:03:41.000Z
third_party/mplayer/libmpdemux/demux_avs.h
Narflex/sagetv
76cb5755e54fd3b01d2bb708a8a72af0aa1533f1
[ "Apache-2.0" ]
227
2015-08-10T22:24:29.000Z
2022-02-25T19:16:21.000Z
/* * Demuxer for avisynth * Copyright (c) 2005 Gianluigi Tiesi <sherpya@netfarm.it> * * Avisynth C Interface Version 0.20 * Copyright 2003 Kevin Atkinson * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. */ enum { AVISYNTH_INTERFACE_VERSION = 2 }; enum { AVS_SAMPLE_INT8 = 1<<0, AVS_SAMPLE_INT16 = 1<<1, AVS_SAMPLE_INT24 = 1<<2, AVS_SAMPLE_INT32 = 1<<3, AVS_SAMPLE_FLOAT = 1<<4 }; enum { AVS_PLANAR_Y=1<<0, AVS_PLANAR_U=1<<1, AVS_PLANAR_V=1<<2, AVS_PLANAR_ALIGNED=1<<3, AVS_PLANAR_Y_ALIGNED=AVS_PLANAR_Y|AVS_PLANAR_ALIGNED, AVS_PLANAR_U_ALIGNED=AVS_PLANAR_U|AVS_PLANAR_ALIGNED, AVS_PLANAR_V_ALIGNED=AVS_PLANAR_V|AVS_PLANAR_ALIGNED }; // Colorspace properties. enum { AVS_CS_BGR = 1<<28, AVS_CS_YUV = 1<<29, AVS_CS_INTERLEAVED = 1<<30, AVS_CS_PLANAR = 1<<31 }; // Specific colorformats enum { AVS_CS_UNKNOWN = 0, AVS_CS_BGR24 = 1<<0 | AVS_CS_BGR | AVS_CS_INTERLEAVED, AVS_CS_BGR32 = 1<<1 | AVS_CS_BGR | AVS_CS_INTERLEAVED, AVS_CS_YUY2 = 1<<2 | AVS_CS_YUV | AVS_CS_INTERLEAVED, AVS_CS_YV12 = 1<<3 | AVS_CS_YUV | AVS_CS_PLANAR, // y-v-u, planar AVS_CS_I420 = 1<<4 | AVS_CS_YUV | AVS_CS_PLANAR, // y-u-v, planar AVS_CS_IYUV = 1<<4 | AVS_CS_YUV | AVS_CS_PLANAR // same as above }; typedef struct AVS_Clip AVS_Clip; typedef struct AVS_ScriptEnvironment AVS_ScriptEnvironment; typedef struct AVS_Value AVS_Value; struct AVS_Value { short type; // 'a'rray, 'c'lip, 'b'ool, 'i'nt, 'f'loat, 's'tring, 'v'oid, or 'l'ong // for some function e'rror short array_size; union { void * clip; // do not use directly, use avs_take_clip char boolean; int integer; float floating_pt; const char * string; const AVS_Value * array; } d; }; // AVS_VideoInfo is layed out identicly to VideoInfo typedef struct AVS_VideoInfo { int width, height; // width=0 means no video unsigned fps_numerator, fps_denominator; int num_frames; int pixel_type; int audio_samples_per_second; // 0 means no audio int sample_type; uint64_t num_audio_samples; int nchannels; // Imagetype properties int image_type; } AVS_VideoInfo; typedef struct AVS_VideoFrameBuffer { BYTE * data; int data_size; // sequence_number is incremented every time the buffer is changed, so // that stale views can tell they're no longer valid. long sequence_number; long refcount; } AVS_VideoFrameBuffer; typedef struct AVS_VideoFrame { int refcount; AVS_VideoFrameBuffer * vfb; int offset, pitch, row_size, height, offsetU, offsetV, pitchUV; // U&V offsets are from top of picture. } AVS_VideoFrame; static __inline AVS_Value avs_new_value_string(const char * v0) { AVS_Value v; v.type = 's'; v.d.string = v0; return v; } static __inline AVS_Value avs_new_value_array(AVS_Value * v0, int size) { AVS_Value v; v.type = 'a'; v.d.array = v0; v.array_size = size; return v; } static __inline int avs_is_error(AVS_Value v) { return v.type == 'e'; } static __inline int avs_is_clip(AVS_Value v) { return v.type == 'c'; } static __inline int avs_is_string(AVS_Value v) { return v.type == 's'; } static __inline int avs_has_video(const AVS_VideoInfo * p) { return (p->width!=0); } static __inline int avs_has_audio(const AVS_VideoInfo * p) { return (p->audio_samples_per_second!=0); } static __inline const char * avs_as_string(AVS_Value v) { return avs_is_error(v) || avs_is_string(v) ? v.d.string : 0; } /* Color spaces */ static __inline int avs_is_rgb(const AVS_VideoInfo * p) { return (p->pixel_type&AVS_CS_BGR); } static __inline int avs_is_rgb24(const AVS_VideoInfo * p) { return (p->pixel_type&AVS_CS_BGR24)==AVS_CS_BGR24; } // Clear out additional properties static __inline int avs_is_rgb32(const AVS_VideoInfo * p) { return (p->pixel_type & AVS_CS_BGR32) == AVS_CS_BGR32 ; } static __inline int avs_is_yuy(const AVS_VideoInfo * p) { return (p->pixel_type&AVS_CS_YUV ); } static __inline int avs_is_yuy2(const AVS_VideoInfo * p) { return (p->pixel_type & AVS_CS_YUY2) == AVS_CS_YUY2; } static __inline int avs_is_yv12(const AVS_VideoInfo * p) { return ((p->pixel_type & AVS_CS_YV12) == AVS_CS_YV12)||((p->pixel_type & AVS_CS_I420) == AVS_CS_I420); } static __inline int avs_bits_per_pixel(const AVS_VideoInfo * p) { switch (p->pixel_type) { case AVS_CS_BGR24: return 24; case AVS_CS_BGR32: return 32; case AVS_CS_YUY2: return 16; case AVS_CS_YV12: case AVS_CS_I420: return 12; default: return 0; } }
31.387879
113
0.71983
35949b073f63f989a9060c0fd75ba7e007ce35ac
236
h
C
KeenClientTests/GlobalPropertiesTests.h
stevekellyhpe/KeenClient-iOS
6dce5d5282f6eb01b20adceb88185ffa501d6033
[ "MIT" ]
49
2015-01-14T09:59:39.000Z
2020-03-28T07:53:29.000Z
KeenClientTests/GlobalPropertiesTests.h
stevekellyhpe/KeenClient-iOS
6dce5d5282f6eb01b20adceb88185ffa501d6033
[ "MIT" ]
170
2015-02-06T16:12:19.000Z
2019-06-11T07:18:21.000Z
KeenClientTests/GlobalPropertiesTests.h
stevekellyhpe/KeenClient-iOS
6dce5d5282f6eb01b20adceb88185ffa501d6033
[ "MIT" ]
28
2015-04-17T13:15:31.000Z
2019-07-31T22:49:28.000Z
// // GlobalPropertiesTests.h // KeenClient // // Created by Brian Baumhover on 5/9/17. // Copyright © 2017 Keen Labs. All rights reserved. // #import "KeenTestCaseBase.h" @interface GlobalPropertiesTests : KeenTestCaseBase @end
16.857143
52
0.724576
722f44eeb161618803f20266b38312850738c00b
2,200
h
C
lib/external/wolfssl/IDE/zephyr/lib/settings/user_settings-tls-generic.h
Koneeee1/ms-tpm-20-ref
d99419bd30a4dad7ae5bfad3c1c0d5962c188913
[ "BSD-2-Clause" ]
null
null
null
lib/external/wolfssl/IDE/zephyr/lib/settings/user_settings-tls-generic.h
Koneeee1/ms-tpm-20-ref
d99419bd30a4dad7ae5bfad3c1c0d5962c188913
[ "BSD-2-Clause" ]
null
null
null
lib/external/wolfssl/IDE/zephyr/lib/settings/user_settings-tls-generic.h
Koneeee1/ms-tpm-20-ref
d99419bd30a4dad7ae5bfad3c1c0d5962c188913
[ "BSD-2-Clause" ]
null
null
null
/* wolfssl options.h * generated from configure options * * Copyright (C) 2006-2015 wolfSSL Inc. * * This file is part of wolfSSL. (formerly known as CyaSSL) * */ #ifndef WOLFSSL_OPTIONS_H #define WOLFSSL_OPTIONS_H #ifdef __cplusplus extern "C" { #endif #undef WOLFSSL_ZEPHYR #define WOLFSSL_ZEPHYR #if 0 #undef SINGLE_THREADED #define SINGLE_THREADED #endif #undef TFM_TIMING_RESISTANT #define TFM_TIMING_RESISTANT #undef ECC_TIMING_RESISTANT #define ECC_TIMING_RESISTANT #undef WC_RSA_BLINDING #define WC_RSA_BLINDING #undef HAVE_AESGCM #define HAVE_AESGCM #undef WOLFSSL_SHA512 #define WOLFSSL_SHA512 #undef WOLFSSL_SHA384 #define WOLFSSL_SHA384 #undef NO_DSA #define NO_DSA #undef HAVE_ECC #define HAVE_ECC #undef TFM_ECC256 #define TFM_ECC256 #undef WOLFSSL_BASE64_ENCODE #define WOLFSSL_BASE64_ENCODE #undef NO_RC4 #define NO_RC4 #undef NO_HC128 #define NO_HC128 #undef NO_RABBIT #define NO_RABBIT #undef WOLFSSL_SHA224 #define WOLFSSL_SHA224 #undef WOLFSSL_SHA3 #define WOLFSSL_SHA3 #undef HAVE_POLY1305 #define HAVE_POLY1305 #undef HAVE_ONE_TIME_AUTH #define HAVE_ONE_TIME_AUTH #undef HAVE_CHACHA #define HAVE_CHACHA #undef HAVE_HASHDRBG #define HAVE_HASHDRBG #undef NO_FILESYSTEM #define NO_FILESYSTEM #undef HAVE_TLS_EXTENSIONS #define HAVE_TLS_EXTENSIONS #undef HAVE_SUPPORTED_CURVES #define HAVE_SUPPORTED_CURVES #undef HAVE_EXTENDED_MASTER #define HAVE_EXTENDED_MASTER #undef NO_PSK #define NO_PSK #undef NO_MD4 #define NO_MD4 #undef NO_PWDBASED #define NO_PWDBASED #undef USE_FAST_MATH #define USE_FAST_MATH #undef WOLFSSL_NO_ASM #define WOLFSSL_NO_ASM #undef WOLFSSL_X86_BUILD #define WOLFSSL_X86_BUILD #undef WC_NO_ASYNC_THREADING #define WC_NO_ASYNC_THREADING #undef NO_DES3 #define NO_DES3 #if 1 #undef NO_ASN_TIME #define NO_ASN_TIME #endif #undef WOLFSSL_STATIC_MEMORY #define WOLFSSL_STATIC_MEMORY #if 0 #undef WOLFSSL_HAVE_SP_RSA #define WOLFSSL_HAVE_SP_RSA #undef WOLFSSL_HAVE_SP_DH #define WOLFSSL_HAVE_SP_DH #undef WOLFSSL_HAVE_SP_ECC #define WOLFSSL_HAVE_SP_ECC #endif #if 0 #undef DEBUG_WOLFSSL #define DEBUG_WOLFSSL #endif #ifdef __cplusplus } #endif #endif /* WOLFSSL_OPTIONS_H */
14.864865
59
0.807273
897d5f8453e8c210eabeb2c5f0ded8ced2db807e
1,172
h
C
iphone/Classes/TiUIScrollView.h
millenoki/titanium_mobile
e8c38673ba1945a3ea3920fa45f238c05d525d60
[ "Apache-2.0" ]
12
2015-01-18T01:05:00.000Z
2017-06-12T22:53:18.000Z
iphone/Classes/TiUIScrollView.h
millenoki/titanium_mobile
e8c38673ba1945a3ea3920fa45f238c05d525d60
[ "Apache-2.0" ]
3
2015-02-14T05:45:36.000Z
2016-10-18T06:27:51.000Z
iphone/Classes/TiUIScrollView.h
millenoki/titanium_mobile
e8c38673ba1945a3ea3920fa45f238c05d525d60
[ "Apache-2.0" ]
11
2015-01-09T14:03:50.000Z
2018-10-29T11:14:10.000Z
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #ifdef USE_TI_UISCROLLVIEW #ifdef USE_TI_UIREFRESHCONTROL #import "TiUIRefreshControlProxy.h" #endif #import "TiScrollingView.h" @interface TiUIScrollView : TiScrollingView <TiScrolling> { @private TDUIScrollView *scrollView; #ifdef TI_USE_AUTOLAYOUT TiLayoutView *contentView; #else UIView *wrapperView; TiDimension contentWidth; TiDimension contentHeight; #endif CGFloat minimumContentHeight; #ifdef USE_TI_UIREFRESHCONTROL TiUIRefreshControlProxy *refreshControl; #endif BOOL needsHandleContentSize; } @property (nonatomic, retain, readonly) TDUIScrollView *scrollView; //@property(nonatomic,readonly) TiDimension contentWidth; - (void)setNeedsHandleContentSize; - (void)setNeedsHandleContentSizeIfAutosizing; - (BOOL)handleContentSizeIfNeeded; - (void)handleContentSize; #ifndef TI_USE_AUTOLAYOUT - (UIView *)wrapperView; #endif - (BOOL)flexibleContentWidth; - (BOOL)flexibleContentHeight; @end #endif
22.980392
70
0.797782
ed7af080c575b26321cb0e514cafdbee9251343e
1,579
h
C
media/libstagefright/rtsp/ARawAudioAssembler.h
rubis-lab/NANS_framework_av
fc0e7dfab044f96b33c641d7ddf60d5a8f1ac46e
[ "Apache-2.0" ]
null
null
null
media/libstagefright/rtsp/ARawAudioAssembler.h
rubis-lab/NANS_framework_av
fc0e7dfab044f96b33c641d7ddf60d5a8f1ac46e
[ "Apache-2.0" ]
null
null
null
media/libstagefright/rtsp/ARawAudioAssembler.h
rubis-lab/NANS_framework_av
fc0e7dfab044f96b33c641d7ddf60d5a8f1ac46e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2011 The Android Open Source Project * * 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 A_RAW_AUDIO_ASSEMBLER_H_ #define A_RAW_AUDIO_ASSEMBLER_H_ #include "ARTPAssembler.h" namespace android { struct AMessage; struct AString; struct MetaData; struct ARawAudioAssembler : public ARTPAssembler { ARawAudioAssembler( const sp<AMessage> &notify, const char *desc, const AString &params); static bool Supports(const char *desc); static void MakeFormat( const char *desc, const sp<MetaData> &format); protected: virtual ~ARawAudioAssembler(); virtual AssemblyStatus assembleMore(const sp<ARTPSource> &source); virtual void onByeReceived(); virtual void packetLost(); private: bool mIsWide; sp<AMessage> mNotifyMsg; bool mNextExpectedSeqNoValid; uint32_t mNextExpectedSeqNo; AssemblyStatus addPacket(const sp<ARTPSource> &source); DISALLOW_EVIL_CONSTRUCTORS(ARawAudioAssembler); }; } // namespace android #endif // A_RAW_AUDIO_ASSEMBLER_H_
25.885246
75
0.730842
e4da97ec314136a49ca9cbe902fc8dc377aca0d1
2,633
h
C
include/MusicLibrary/MLPhotoAlbum.h
iMokhles/MyTheosHeaders
2c263362a8a6f947b1a868e03983ed188ead6539
[ "MIT" ]
7
2016-07-22T14:29:58.000Z
2021-03-19T05:31:48.000Z
iphone-private-frameworks-master/MusicLibrary/MLPhotoAlbum.h
tt295362026/demo
7d6e9e75f29c992ea9c5693d38f76e0012bbbf15
[ "BSD-4-Clause" ]
null
null
null
iphone-private-frameworks-master/MusicLibrary/MLPhotoAlbum.h
tt295362026/demo
7d6e9e75f29c992ea9c5693d38f76e0012bbbf15
[ "BSD-4-Clause" ]
3
2017-02-06T23:58:01.000Z
2017-10-31T03:47:52.000Z
/** * This header is generated by class-dump-z 0.2a. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: /System/Library/PrivateFrameworks/MusicLibrary.framework/MusicLibrary */ #import <Foundation/NSObject.h> #import "MLPhotoAlbum.h" #import "MusicLibrary-Structs.h" @class NSArray, NSString, NSDictionary; @interface MLPhotoAlbum : NSObject { @private int _albumID; int _filter; NSString* _albumName; NSString* _uuid; NSArray* _imagesAndVideos; NSArray* _filteredImages; int _cachedCount; id _posterImage; BOOL _imagesLoaded; BOOL _isLibrary; unsigned char _albumKind; unsigned long long _playlistID; unsigned long long _songID; int _imageCount; int _videoCount; NSDictionary* _slideshowSettings; int _keyPhotoKeyITunes; int _keyPhotoFaceIndexITunes; int _posterImageIndex; unsigned _didSetPosterImageIndex : 1; } +(id)libraryAlbum; -(id)init; -(id)initWithAlbumID:(unsigned)albumID albumName:(id)name; -(void)dealloc; -(id)description; -(id)faceImageWithSize:(CGSize)size returnLocationInImage:(CGRect*)image; -(id)_posterImage; -(void)_setPosterImage:(id)image; -(unsigned)albumID; -(id)name; -(void)setName:(id)name; -(id)uuid; -(void)setUuid:(id)uuid; -(int)albumKind; -(void)setAlbumKind:(int)kind; -(BOOL)isLibrary; -(void)setLibrary:(BOOL)library; -(BOOL)isEmpty; -(BOOL)isEditable; -(BOOL)deletedWhenEmpty; -(id)images; -(id)imagesAndVideos; -(BOOL)containsUnknownItems; -(id)imagesWithoutUnknownItems; -(void)setImages:(id)images; -(void)insertImage:(id)image atIndex:(unsigned)index; -(void)addImage:(id)image; -(unsigned)insertImageByDate:(id)date; -(void)removeImage:(id)image; -(id)imageWithImageID:(int)imageID; -(int)indexOfPhoto:(id)photo; -(int)count; -(int)imageCount; -(int)videoCount; -(void)deleteImageAtIndex:(int)index; -(void)deleteImagesAtIndexes:(id)indexes; -(unsigned long long)slideshowPlaylistID; -(void)setSlideshowPlaylistID:(unsigned long long)anId; -(unsigned long long)slideshowSongID; -(void)setSlideshowSongID:(unsigned long long)anId; -(id)slideshowSettings; -(void)setSlideshowSettings:(id)settings; -(BOOL)imagesLoaded; -(void)setImagesLoaded:(BOOL)loaded; -(int)cachedCount; -(void)setCachedCount:(int)count; -(int)filter; -(void)setFilter:(int)filter; -(int)keyPhotoKey; -(void)setKeyPhotoKey:(int)key; -(int)keyPhotoFaceIndex; -(void)setKeyPhotoFaceIndex:(int)index; -(int)indexOfPosterImage; -(id)photoAlbumSlideshowSettings; -(void)setPhotoAlbumSlideshowSettings:(id)settings; @end @interface MLPhotoAlbum (Internal) -(void)_reloadFilteredImages; -(void)_invalidateFilteredImages; -(void)_setFilteredImages:(id)images; @end
26.33
80
0.774402
691443f4ee941f1abe93529fc71441703ea50d8f
195
h
C
iOS_Template/iOS_Template/Sources/WJ_Macro/HHJNotificationMacro.h
wenjiehe/iOS_Template
b3990b2b0097cd3e58938fa5dc9c2db9904346b7
[ "MIT" ]
null
null
null
iOS_Template/iOS_Template/Sources/WJ_Macro/HHJNotificationMacro.h
wenjiehe/iOS_Template
b3990b2b0097cd3e58938fa5dc9c2db9904346b7
[ "MIT" ]
null
null
null
iOS_Template/iOS_Template/Sources/WJ_Macro/HHJNotificationMacro.h
wenjiehe/iOS_Template
b3990b2b0097cd3e58938fa5dc9c2db9904346b7
[ "MIT" ]
null
null
null
// // HHJNotificationMacro.h // iOS_Template // // Created by 贺文杰 on 2021/9/20. // #ifndef HHJNotificationMacro_h #define HHJNotificationMacro_h //通知key #endif /* HHJNotificationMacro_h */
13.928571
35
0.728205
76d523bcd36651cd00e9654574dc68b5fc133f93
1,255
c
C
libfat/source/disc_io/io_ak2_sd.c
lifehackerhansol/akrpg
6ffbe0e73ec205e7e7d2f4e6bbe69cfd0603ae6f
[ "MIT" ]
null
null
null
libfat/source/disc_io/io_ak2_sd.c
lifehackerhansol/akrpg
6ffbe0e73ec205e7e7d2f4e6bbe69cfd0603ae6f
[ "MIT" ]
null
null
null
libfat/source/disc_io/io_ak2_sd.c
lifehackerhansol/akrpg
6ffbe0e73ec205e7e7d2f4e6bbe69cfd0603ae6f
[ "MIT" ]
null
null
null
#include <nds.h> #include <string.h> #include <ioak2.h> #include "io_ak2_sd.h" //--------------------------------------------------------------- // Functions needed for the external interface bool _AK2_SD_isInserted (void) { u32 cmd[2] = { 0xCD000000, 0 }; u32 data = 0xFFFFFFFF; ioAK2SendCommand( cmd, 4, 0, &data ); return (0x00000fc2 == data ); } bool _AK2_SD_startUp (void) { sysSetBusOwners( BUS_OWNER_ARM9, BUS_OWNER_ARM9 ); return AK2_sddInitSD(); } bool _AK2_SD_readSectors (u32 sector, u32 numSectors, void* buffer) { AK2_sddReadBlocks( sector << 9, numSectors, buffer ); return true; } bool _AK2_SD_writeSectors (u32 sector, u32 numSectors, const void* buffer) { AK2_sddWriteBlocks( sector << 9, numSectors, buffer ); return true; } bool _AK2_SD_clearStatus (void) { return true; } bool _AK2_SD_shutdown (void) { return true; } const IO_INTERFACE _io_AK2_sd = { DEVICE_TYPE_AK2_SD, FEATURE_MEDIUM_CANREAD | FEATURE_MEDIUM_CANWRITE | FEATURE_SLOT_NDS, (FN_MEDIUM_STARTUP)&_AK2_SD_startUp, (FN_MEDIUM_ISINSERTED)&_AK2_SD_isInserted, (FN_MEDIUM_READSECTORS)&_AK2_SD_readSectors, (FN_MEDIUM_WRITESECTORS)&_AK2_SD_writeSectors, (FN_MEDIUM_CLEARSTATUS)&_AK2_SD_clearStatus, (FN_MEDIUM_SHUTDOWN)&_AK2_SD_shutdown };
22.017544
75
0.720319
a193ae2167c7a91aa827ce3ce5e4f422bc9405ef
4,444
h
C
src/googleapis/client/auth/webserver_authorization_getter.h
rcmaniac25/google-api-cpp-client
82b80f374c486cca7b4c94124532e4de34404146
[ "Apache-2.0" ]
1
2015-04-06T16:41:07.000Z
2015-04-06T16:41:07.000Z
src/googleapis/client/auth/webserver_authorization_getter.h
amyvmiwei/google-api-cpp-client
1a0a78b1f8f41085b91142f283690a07b474f0bc
[ "Apache-2.0" ]
null
null
null
src/googleapis/client/auth/webserver_authorization_getter.h
amyvmiwei/google-api-cpp-client
1a0a78b1f8f41085b91142f283690a07b474f0bc
[ "Apache-2.0" ]
null
null
null
/* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * 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. * * @} */ // Author: ewiseblatt@google.com (Eric Wiseblatt) #ifndef APISERVING_CLIENTS_CPP_AUTH_WEBSERVER_AUTHORIZATION_GETTER_H_ #define APISERVING_CLIENTS_CPP_AUTH_WEBSERVER_AUTHORIZATION_GETTER_H_ #include <ostream> // NOLINT #include <string> using std::string; #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/util/abstract_webserver.h" #include "googleapis/base/callback.h" #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/base/mutex.h" #include "googleapis/base/scoped_ptr.h" #include "googleapis/base/thread_annotations.h" #include "googleapis/strings/stringpiece.h" #include "googleapis/util/status.h" namespace googleapis { namespace client { /* * An adapter to use webserver with OAuth2AuthorizationFlows. * @ingroup AuthSupportOAuth2 * * This class will likely change significantly or go away in a future release. * * It is here to support samples, experimentation, and testing * OAuth2 web flows. */ class WebServerAuthorizationCodeGetter { public: /* * Callback used to prompt for authorization. * Receiving authorization will happen through a web server handler. */ typedef ResultCallback1< util::Status, const StringPiece& > AskCallback; /* * Standard constructor. * @param[in] ask_callback Must be a non-NULL repeatable callback. * takes ownership. */ explicit WebServerAuthorizationCodeGetter(AskCallback* ask_callback); /* * Standard destructor. */ virtual ~WebServerAuthorizationCodeGetter(); /* * How long we'll wait for authorization. * * @returns Time in milliseconds. */ int64 timeout_ms() const { return timeout_ms_; } /* * Set how long we'll weait. * * @param[in] ms Time in milliseconds. */ void set_timeout_ms(int64 ms) { timeout_ms_ = ms; } /* * Gets the ask callback. * * @return reference. This instance retains ownership. */ AskCallback* ask_callback() { return ask_callback_.get(); } /* * Returns a repeatable callback for flow to get an authorization code. * * @param[in] flow A reference to the flow is used to generate urls. * @return Ownershp is apssed back to the caller. */ OAuth2AuthorizationFlow::AuthorizationCodeCallback* MakeAuthorizationCodeCallback(OAuth2AuthorizationFlow* flow); /* * @param[in] path The path that uri_redirects are expected on. * @param[in] httpd The webserver to process the redirects wtih */ virtual void AddReceiveAuthorizationCodeUrlPath( const StringPiece& path, AbstractWebServer* httpd); virtual util::Status PromptForAuthorizationCode( OAuth2AuthorizationFlow* flow, const OAuth2RequestOptions& options, string* authorization_code); /* * A suitable function for an asker that execute a command (e.g. a browser). */ static util::Status PromptWithCommand( const string& program, const string& args, const StringPiece& url); /* * A suitable function for an asker that prompts a console. */ static util::Status PromptWithOstream( std::ostream* ostream, const string& prompt, const StringPiece& url); protected: virtual util::Status AskForAuthorization(const StringPiece& url); private: int64 timeout_ms_; scoped_ptr<AskCallback> ask_callback_; Mutex mutex_; CondVar authorization_condvar_ GUARDED_BY(mutex_); string authorization_code_ GUARDED_BY(mutex_); util::Status authorization_status_ GUARDED_BY(mutex_); util::Status ReceiveAuthorizationCode(WebServerRequest* request); DISALLOW_COPY_AND_ASSIGN(WebServerAuthorizationCodeGetter); }; } // namespace client } // namespace googleapis #endif // APISERVING_CLIENTS_CPP_AUTH_WEBSERVER_AUTHORIZATION_GETTER_H_
30.648276
78
0.734698
597a8c72ad0e5eb3602b4130d8d080276a9e182e
2,561
h
C
source/extensions/compression/zstd/decompressor/zstd_decompressor_impl.h
Licht-T/envoy
9418d079a62ebeeef632901369d71c399e0db2d4
[ "Apache-2.0" ]
null
null
null
source/extensions/compression/zstd/decompressor/zstd_decompressor_impl.h
Licht-T/envoy
9418d079a62ebeeef632901369d71c399e0db2d4
[ "Apache-2.0" ]
81
2022-01-05T04:54:46.000Z
2022-03-31T05:13:55.000Z
source/extensions/compression/zstd/decompressor/zstd_decompressor_impl.h
Licht-T/envoy
9418d079a62ebeeef632901369d71c399e0db2d4
[ "Apache-2.0" ]
null
null
null
#pragma once #include "envoy/compression/decompressor/decompressor.h" #include "envoy/stats/scope.h" #include "envoy/stats/stats_macros.h" #include "source/common/common/logger.h" #include "source/extensions/compression/zstd/common/base.h" #include "source/extensions/compression/zstd/common/dictionary_manager.h" #include "zstd_errors.h" namespace Envoy { namespace Extensions { namespace Compression { namespace Zstd { namespace Decompressor { using ZstdDDictManager = Common::DictionaryManager<ZSTD_DDict, ZSTD_freeDDict, ZSTD_getDictID_fromDDict>; using ZstdDDictManagerPtr = std::unique_ptr<ZstdDDictManager>; /** * All zstd decompressor stats. @see stats_macros.h */ #define ALL_ZSTD_DECOMPRESSOR_STATS(COUNTER) \ COUNTER(zstd_generic_error) \ COUNTER(zstd_dictionary_error) \ COUNTER(zstd_checksum_wrong_error) \ COUNTER(zstd_memory_error) /** * Struct definition for zstd decompressor stats. @see stats_macros.h */ struct ZstdDecompressorStats { ALL_ZSTD_DECOMPRESSOR_STATS(GENERATE_COUNTER_STRUCT) }; /** * Implementation of decompressor's interface. */ class ZstdDecompressorImpl : public Common::Base, public Envoy::Compression::Decompressor::Decompressor, public Logger::Loggable<Logger::Id::decompression>, NonCopyable { public: ZstdDecompressorImpl(Stats::Scope& scope, const std::string& stats_prefix, const ZstdDDictManagerPtr& ddict_manager, uint32_t chunk_size); // Envoy::Compression::Decompressor::Decompressor void decompress(const Buffer::Instance& input_buffer, Buffer::Instance& output_buffer) override; private: static ZstdDecompressorStats generateStats(const std::string& prefix, Stats::Scope& scope) { return ZstdDecompressorStats{ALL_ZSTD_DECOMPRESSOR_STATS(POOL_COUNTER_PREFIX(scope, prefix))}; } friend class ZstdDecompressorStatsTest; bool process(Buffer::Instance& output_buffer); bool isError(size_t result); std::unique_ptr<ZSTD_DCtx, decltype(&ZSTD_freeDCtx)> dctx_; const ZstdDDictManagerPtr& ddict_manager_; const ZstdDecompressorStats stats_; bool is_dictionary_set_{false}; }; } // namespace Decompressor } // namespace Zstd } // namespace Compression } // namespace Extensions } // namespace Envoy
35.082192
100
0.680203
daef1e6b8c2597bd1c76e0d7dc587f955c24f136
988
c
C
tests/com.oracle.truffle.llvm.tests.sulong/c/builtin_gcc/__builtin_isfinite.c
pointhi/sulong
5446c54d360f486f9e97590af5f466cf1f5cd1f7
[ "BSD-3-Clause" ]
1
2021-01-20T08:07:04.000Z
2021-01-20T08:07:04.000Z
tests/com.oracle.truffle.llvm.tests.sulong/c/builtin_gcc/__builtin_isfinite.c
pointhi/sulong
5446c54d360f486f9e97590af5f466cf1f5cd1f7
[ "BSD-3-Clause" ]
null
null
null
tests/com.oracle.truffle.llvm.tests.sulong/c/builtin_gcc/__builtin_isfinite.c
pointhi/sulong
5446c54d360f486f9e97590af5f466cf1f5cd1f7
[ "BSD-3-Clause" ]
1
2018-11-06T21:38:57.000Z
2018-11-06T21:38:57.000Z
int main() { volatile float a = __builtin_nanf(""); if (__builtin_isfinite(a)) { return 1; } volatile float b = __builtin_inff(); if (__builtin_isfinite(b)) { return 1; } volatile double c = __builtin_nan(""); if (__builtin_isfinite(c)) { return 1; } volatile double d = __builtin_inf(); if (__builtin_isfinite(d)) { return 1; } #ifdef __clang__ // TODO: dragonegg uses native calls which do not work with X86_FP80 volatile long double e = __builtin_nanl(""); if (__builtin_isfinite(e)) { return 1; } volatile long double f = __builtin_infl(); if (__builtin_isfinite(f)) { return 1; } #endif volatile float g = 0; if (!__builtin_isfinite(g)) { return 1; } volatile double h = 0; if (!__builtin_isfinite(h)) { return 1; } #ifdef __clang__ // TODO: dragonegg uses native calls which do not work with X86_FP80 volatile long double i = 0; if (!__builtin_isfinite(i)) { return 1; } #endif return 0; }
22.454545
85
0.648785
d36a3a4f01bd9ea139f87b4859899cb06298b224
1,395
h
C
EmbeddedJXcoreEngineIOS/jxcore/include/node/jx/Proxy/Mozilla/SpiderHelper.h
agenthunt/EmbeddedJXcoreEngineIOS
34d98d8f688b024f3a2356f5b3b98781c3c3d1fc
[ "MIT" ]
7
2015-06-23T00:54:36.000Z
2017-04-26T13:35:06.000Z
EmbeddedJXcoreEngineIOS/jxcore/include/node/jx/Proxy/Mozilla/SpiderHelper.h
agenthunt/EmbeddedJXcoreEngineIOS
34d98d8f688b024f3a2356f5b3b98781c3c3d1fc
[ "MIT" ]
null
null
null
EmbeddedJXcoreEngineIOS/jxcore/include/node/jx/Proxy/Mozilla/SpiderHelper.h
agenthunt/EmbeddedJXcoreEngineIOS
34d98d8f688b024f3a2356f5b3b98781c3c3d1fc
[ "MIT" ]
null
null
null
// Copyright & License details are available under JXCORE_LICENSE file #ifndef SRC_JX_PROXY_MOZILLA_SPIDERHELPER_H_ #define SRC_JX_PROXY_MOZILLA_SPIDERHELPER_H_ #include "MozJS/MozJS.h" namespace jxcore { class MemoryScript { void *data_; size_t length_; public: MemoryScript() : data_(NULL), length_(0) {} MemoryScript(void *data, size_t length) : data_(data), length_(length) {} void set(void *data, size_t length) { data_ = data; length_ = length; } inline bool IsEmpty() { return length_ == 0; } inline void *data() { return data_; } inline size_t length() { return length_; } void Dispose() { if (length_ != 0) { free(data_); } } }; MemoryScript GetScriptMemory(JSContext *ctx, JSScript *script); JSScript *GetScript(JSContext *ctx, MemoryScript ms); void NewGlobalObject(JSContext *ctx, JS::MutableHandleObject ret_val); void NewContextGlobal(JSContext *ctx, JS::MutableHandleObject ret_val); MozJS::Value getGlobal(const int threadId); JSObject *getGlobalObject(const int threadId); void NewTransplantObject(JSContext *ctx, JS::MutableHandleObject ret_val); void CrossCompartmentCopy(JSContext *orig_context, JSContext *new_context, MozJS::Value &source, bool global_object, JS::MutableHandleObject retval); } // namespace jxcore #endif // SRC_JX_PROXY_MOZILLA_SPIDERHELPER_H_
28.469388
75
0.71828
25b7e7a578243970ee46644d0a748cea9aea10db
1,194
h
C
thrift/compiler/filesystem.h
sakibguy/fbthrift
8123a9192519072e119ac9817c6b59a35b98b81c
[ "Apache-2.0" ]
2,112
2015-01-02T11:34:27.000Z
2022-03-31T16:30:42.000Z
thrift/compiler/filesystem.h
sakibguy/fbthrift
8123a9192519072e119ac9817c6b59a35b98b81c
[ "Apache-2.0" ]
372
2015-01-05T10:40:09.000Z
2022-03-31T20:45:11.000Z
thrift/compiler/filesystem.h
sakibguy/fbthrift
8123a9192519072e119ac9817c6b59a35b98b81c
[ "Apache-2.0" ]
582
2015-01-03T01:51:56.000Z
2022-03-31T02:01:09.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <string> #include <boost/filesystem.hpp> namespace apache { namespace thrift { namespace compiler { /** * Appends `path` to `base_path` to create an absolute path. * * @param base_path The base path to append `path` to. * @param path The path to append to the `base_path`. * @return The absolute path created by appending `path` to `base_path`. */ boost::filesystem::path make_abs_path( const boost::filesystem::path& base_path, const boost::filesystem::path& path); } // namespace compiler } // namespace thrift } // namespace apache
29.121951
75
0.722781
ce342f10a018f0cc3b2a48d74dee810d6849fa02
761
h
C
chrome/browser/android/offline_pages/offliner_helper.h
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chrome/browser/android/offline_pages/offliner_helper.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chrome/browser/android/offline_pages/offliner_helper.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2017 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 CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINER_HELPER_H_ #define CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINER_HELPER_H_ namespace content { class BrowserContext; } namespace offline_pages { bool AreThirdPartyCookiesBlocked(content::BrowserContext* browser_context); bool IsNetworkPredictionDisabled(content::BrowserContext* browser_context); enum class OfflinePagesCctApiPrerenderAllowedStatus { PRERENDER_ALLOWED, THIRD_PARTY_COOKIES_DISABLED, NETWORK_PREDICTION_DISABLED, }; } // namespace offline_pages #endif // CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINER_HELPER_H_
28.185185
75
0.842313
b8fe3486d0c8b81d27695ef8f90393e3820bb7fc
2,739
h
C
PrivateFrameworks/Geode/DGSmartToneOperation.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/Geode/DGSmartToneOperation.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/Geode/DGSmartToneOperation.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import <Geode/DGSmartOperation.h> @class PASmartToneAutoSettings; @interface DGSmartToneOperation : DGSmartOperation { double _inputLight; struct { double exposure; double contrast; double brightness; double shadows; double highlights; double black; double rawHighlights; double localLight; } _smartSettings; PASmartToneAutoSettings *_stats; double _inputLocalLight; double _offsetExposure; double _offsetContrast; double _offsetBrightness; double _offsetShadows; double _offsetHighlights; double _offsetBlack; double _offsetLocalLight; } + (id)autoCalculatedInputKeys; + (BOOL)supportsAutoCalculatedValues; + (id)outputKeys; + (id)inputKeys; + (id)attributes; + (id)_stringsTableName; @property(nonatomic) double offsetLocalLight; // @synthesize offsetLocalLight=_offsetLocalLight; @property(nonatomic) double offsetBlack; // @synthesize offsetBlack=_offsetBlack; @property(nonatomic) double offsetHighlights; // @synthesize offsetHighlights=_offsetHighlights; @property(nonatomic) double offsetShadows; // @synthesize offsetShadows=_offsetShadows; @property(nonatomic) double offsetBrightness; // @synthesize offsetBrightness=_offsetBrightness; @property(nonatomic) double offsetContrast; // @synthesize offsetContrast=_offsetContrast; @property(nonatomic) double offsetExposure; // @synthesize offsetExposure=_offsetExposure; @property(nonatomic) double inputLight; // @synthesize inputLight=_inputLight; - (void).cxx_destruct; - (void)resetAllAutoSettingsToPending; - (void)disableLocalLight; - (void)updateAutoSettings:(id)arg1; - (void)updateAutoSettingsFromOperation:(id)arg1; - (BOOL)needsUpdatedAutoSettingsForOperationFactory; - (void)_applyAutoSettings:(id)arg1; - (double)getAutoValueForInputKey:(id)arg1; - (id)autoCalculatedSlaveInputKeysForMasterInputKey:(id)arg1; - (void)resetOffsets; @property(readonly, nonatomic) double inputRawHighlights; @property(nonatomic) double inputLocalLight; @property(nonatomic) double inputBlack; @property(nonatomic) double inputHighlights; @property(nonatomic) double inputShadows; @property(nonatomic) double inputContrast; @property(nonatomic) double inputBrightness; @property(nonatomic) double inputExposure; - (void)_updateSettings; - (id)settingsDictionary; - (void)restoreAutoSettings:(id)arg1 currentAutoIdentifier:(id)arg2; - (BOOL)applySettingsDictionary:(id)arg1; - (unsigned long long)hash; @property(readonly, nonatomic) PASmartToneAutoSettings *statistics; - (id)initWithOperation:(id)arg1; - (BOOL)isMigratable; @end
35.115385
96
0.776196
ef22affc751ac84c413ced92b54b515a2beb7bdb
5,146
c
C
avionics/firmware/drivers/bq34z100.c
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1,178
2020-09-10T17:15:42.000Z
2022-03-31T14:59:35.000Z
avionics/firmware/drivers/bq34z100.c
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
1
2020-05-22T05:22:35.000Z
2020-05-22T05:22:35.000Z
avionics/firmware/drivers/bq34z100.c
leozz37/makani
c94d5c2b600b98002f932e80a313a06b9285cc1b
[ "Apache-2.0" ]
107
2020-09-10T17:29:30.000Z
2022-03-18T09:00:14.000Z
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "avionics/firmware/drivers/bq34z100.h" #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #include "avionics/common/endian.h" #include "avionics/firmware/cpu/i2c.h" #include "common/macros.h" // Write and read buffers for I2C communications with BQ34Z100 devices. static uint8_t g_read[2]; static const uint8_t kCmdReadVoltage[] = {0x08}; static const uint8_t kCmdReadCurrent[] = {0x0A}; static const uint8_t kCmdReadCapacity[] = {0x04}; static const uint8_t kCmdReadFullCapacity[] = {0x06}; static const uint8_t kCmdReadSoc[] = {0x02}; static const uint8_t kCmdReadTemp[] = {0x0C}; // StateNext merely advances device to chosen subsequent state. static void StateNext(Bq34z100State next, Bq34z100 *device) { device->state = next; } // Write a given byte sequence over I2C, then read a given number of bytes. static void StateWriteRead(Bq34z100State next, const Bq34z100Config *config, const uint8_t *cmd, int32_t write_len, int32_t read_len, Bq34z100 *device) { if (device->first_entry) { device->error = !I2cWriteReadAsync(config->addr, write_len, cmd, read_len, g_read); } else { device->state = next; } } // Advance state machine, where the device->state resulting from the // state-specific function specifies the state for the next iteration. // This state machine only runs after the I2C bus returns to idle. static bool StateProcess(const Bq34z100Config *config, Bq34z100 *device) { Bq34z100State current = device->state; switch (current) { case kBq34z100StateInit: StateNext(kBq34z100StateReadVoltage, device); break; case kBq34z100StateReadVoltage: StateWriteRead(kBq34z100StateReadCurrent, config, kCmdReadVoltage, ARRAYSIZE(kCmdReadVoltage), 2, device); if (!device->first_entry) { ReadUint16Le(g_read, &device->output.bus_raw); } break; case kBq34z100StateReadCurrent: StateWriteRead(kBq34z100StateReadCapacity, config, kCmdReadCurrent, ARRAYSIZE(kCmdReadCurrent), 2, device); if (!device->first_entry) { ReadInt16Le(g_read, &device->output.avg_current_raw); } break; case kBq34z100StateReadCapacity: StateWriteRead(kBq34z100StateReadFullCapacity, config, kCmdReadCapacity, ARRAYSIZE(kCmdReadCapacity), 2, device); if (!device->first_entry) { ReadUint16Le(g_read, &device->output.cur_capacity_raw); } break; case kBq34z100StateReadFullCapacity: StateWriteRead(kBq34z100StateReadSoc, config, kCmdReadFullCapacity, ARRAYSIZE(kCmdReadFullCapacity), 2, device); if (!device->first_entry) { ReadUint16Le(g_read, &device->output.full_capacity_raw); } break; case kBq34z100StateReadSoc: StateWriteRead(kBq34z100StateReadTemp, config, kCmdReadSoc, ARRAYSIZE(kCmdReadSoc), 1, device); if (!device->first_entry) { device->output.soc_raw = g_read[0]; } break; case kBq34z100StateReadTemp: StateWriteRead(kBq34z100StateIdle, config, kCmdReadTemp, ARRAYSIZE(kCmdReadTemp), 2, device); if (!device->first_entry) { ReadUint16Le(g_read, &device->output.temp_raw); } break; case kBq34z100StateIdle: StateNext(kBq34z100StateInit, device); break; default: device->state = kBq34z100StateInit; assert(false); break; } device->first_entry = (current != device->state); return device->state == kBq34z100StateIdle; } static bool HandleI2cError(Bq34z100 *device) { // Reset on I2C bus error. if (device->error) { device->state = kBq34z100StateInit; device->first_entry = true; device->error = false; return false; } else { return true; } } static bool IsValid(const Bq34z100 *device) { return !device->error; } void Bq34z100Init(Bq34z100 *device) { assert(device != NULL); memset(device, 0, sizeof(*device)); device->state = kBq34z100StateInit; device->first_entry = true; } bool Bq34z100Poll(const Bq34z100Config *config, Bq34z100 *device) { assert(config != NULL); assert(device != NULL); assert(config->addr <= 127U); // Return true for valid data. return I2cPoll(&device->error) && HandleI2cError(device) && StateProcess(config, device) && IsValid(device); }
33.2
76
0.675476
ef7554d7ab283fa0dffe79808181aee3945a78f8
3,052
h
C
usr/local/include/qt5/QtQml/5.4.1/QtQml/private/qv4variantobject_p.h
skarekrow/testrepo
af979b718aae49a2301c400964a603cf010a3c51
[ "BSD-3-Clause" ]
null
null
null
usr/local/include/qt5/QtQml/5.4.1/QtQml/private/qv4variantobject_p.h
skarekrow/testrepo
af979b718aae49a2301c400964a603cf010a3c51
[ "BSD-3-Clause" ]
null
null
null
usr/local/include/qt5/QtQml/5.4.1/QtQml/private/qv4variantobject_p.h
skarekrow/testrepo
af979b718aae49a2301c400964a603cf010a3c51
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QV4VARIANTOBJECT_P_H #define QV4VARIANTOBJECT_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtCore/qglobal.h> #include <QtQml/qqmllist.h> #include <QtCore/qvariant.h> #include <private/qv4value_inl_p.h> #include <private/qv4object_p.h> QT_BEGIN_NAMESPACE namespace QV4 { struct VariantObject : Object { struct Data : Object::Data, public ExecutionEngine::ScarceResourceData { Data(InternalClass *ic); Data(ExecutionEngine *engine, const QVariant &value); ~Data() { if (isScarce()) node.remove(); } bool isScarce() const; int vmePropertyReferenceCount; }; V4_OBJECT(Object) static QVariant toVariant(const ValueRef v); void addVmePropertyReference(); void removeVmePropertyReference(); static void destroy(Managed *that); static bool isEqualTo(Managed *m, Managed *other); }; struct VariantPrototype : VariantObject { public: void init(); static ReturnedValue method_preserve(CallContext *ctx); static ReturnedValue method_destroy(CallContext *ctx); static ReturnedValue method_toString(CallContext *ctx); static ReturnedValue method_valueOf(CallContext *ctx); }; } QT_END_NAMESPACE #endif
30.52
77
0.68709
d444a07f98a66f808af289d4446b1b463d8258f1
562
h
C
prototypes/custom_search/src/story/entity.h
solsword/dunyazad
9b9048396a8629904ecc77a924508fc99c956534
[ "MIT" ]
7
2015-03-30T18:06:58.000Z
2021-06-30T12:45:06.000Z
prototypes/custom_search/src/story/entity.h
solsword/dunyazad
9b9048396a8629904ecc77a924508fc99c956534
[ "MIT" ]
2
2015-07-04T05:25:34.000Z
2019-07-05T14:23:23.000Z
prototypes/custom_search/src/story/entity.h
solsword/dunyazad
9b9048396a8629904ecc77a924508fc99c956534
[ "MIT" ]
3
2017-07-04T08:12:04.000Z
2020-04-26T13:27:00.000Z
#ifndef ENTITY_H #define ENTITY_H // entity.h // Defines the basic data structures that represent a story entity. #include <stdint.h> /************** * Structures * **************/ // A character: an actor in the story. struct chr_s; typedef struct chr_s chr; // An location is a place for characters to be. struct loc_s; typedef struct loc_s loc; /********* * Types * *********/ // TODO: Any of these? /************************* * Structure Definitions * *************************/ struct chr_s { }; struct loc_s { }; #endif // ifndef ENTITY_H
14.789474
67
0.567616
60b4a45590d3af430d7472c3eedd13ab1fcc5dc0
2,918
h
C
include/neuralnetwork.h
Parasolll/Digit-Recognition
171954cee8b870f90b7986f139bec9fa914b7bb6
[ "MIT" ]
null
null
null
include/neuralnetwork.h
Parasolll/Digit-Recognition
171954cee8b870f90b7986f139bec9fa914b7bb6
[ "MIT" ]
null
null
null
include/neuralnetwork.h
Parasolll/Digit-Recognition
171954cee8b870f90b7986f139bec9fa914b7bb6
[ "MIT" ]
null
null
null
#ifndef NEURAL_NETWORK_H_INCLUDED #define NEURAL_NETWORK_H_INCLUDED #include <stdint.h> /* Neurals networks works with uint8_t inputs */ /* Requirements */ void NeuralNetwork_input_from_array_uint8(uint8_t *input, const uint32_t size, float *output); /* Neural Network */ typedef struct NeuralNetwork { uint32_t input_size; // number of "neurons" of the "input layer" uint32_t layers_count; // number of layer, input is not included and the last one is the output // An array containning `layers_count` element // element i correspond to the number of neurons in the layer i // note that input is not included and the last one is the output uint32_t *layers_sizes; float **neurons_value_in_layers; /* value always between 0 and 1 because of the sigmoid */ float **bias_in_layers; /* can be every floating point value */ // An array of matrices // matrix i correspond to the weight matrix of the layer i // note that input is not included and the last one is the output float ***weights_in_layers; } NeuralNetwork; /* Converting to a floating point value between 0 and 1*/ #define NeuralNetwork_input_from_uint8(value) ((float)(value) / 255.f) /* Get the output layer as floats array*/ #define NeuralNetwork_get_output_value(neural_network) (neural_network->neurons_value_in_layers[neural_network->layers_count-1]) NeuralNetwork *NeuralNetwork_create_new_with_random_parameters(uint32_t size_of_input, uint32_t number_of_layers, uint32_t *size_of_layers, float init_weight_min, float init_weight_max); void NeuralNetwork_free(NeuralNetwork* neural_network); uint32_t NeuralNetwork_get_max_layer_size(NeuralNetwork *network); void NeuralNetwork_expected_output_neurons_from_uint8_output(const uint8_t single_output, const uint32_t size_output,float *output); void NeuralNetwork_compute_z_for_layer(NeuralNetwork *neural_network,const uint32_t layer, float *input, float * output); void NeuralNetwork_feed_with_input(NeuralNetwork *neural_network, float *input); void NeuralNetwork_get_output_cost(NeuralNetwork *neural_network,const uint8_t input_value, float *bufferHelper1, float* output); void NeuralNetwork_backpropagate_gradient(NeuralNetwork *neural_network, float *input, float *cost_per_neuron, float *cost_per_neuron_next,const float learning_rate, float *bufferHelper); void NeuralNetwork_train_with_uint8_array(NeuralNetwork *neural_network, uint8_t *input, uint8_t *input_label,const uint32_t number_of_training, const float learning_rate); uint32_t NeuralNetwork_index_neuron_max_between_output(NeuralNetwork *neural_network); float NeuralNetwork_is_output_correct(NeuralNetwork *neural_network, const uint8_t expected_output); float NeuralNetwork_get_accuracy_on_test_set_uint8(NeuralNetwork *neural_network, uint8_t *input, uint8_t *input_value,const uint32_t number_of_test); #endif
37.410256
187
0.798492
e4e65594fd577d1ea248e14edd1958066e20ec7c
10,391
h
C
Engine/include/Fractal/IMesh.h
mbatc/Fractal
0df1f6a64d03676e3dd8af0686413f6ffdbf6627
[ "MIT" ]
null
null
null
Engine/include/Fractal/IMesh.h
mbatc/Fractal
0df1f6a64d03676e3dd8af0686413f6ffdbf6627
[ "MIT" ]
34
2021-05-09T10:31:24.000Z
2022-01-24T11:26:48.000Z
Engine/include/Fractal/IMesh.h
mbatc/Fractal
0df1f6a64d03676e3dd8af0686413f6ffdbf6627
[ "MIT" ]
null
null
null
#pragma once #include "Interface.h" #include "Math.h" #include "IElementArray.h" namespace Fractal { class ISurfaceMaterial; struct Vertex { // Element indices int64_t position; int64_t normal; int64_t texcoord; int64_t colour; }; class flEXPORT IMesh : public Interface { public: /** * @brief Reset the mesh to it's default state. */ virtual void Clear() = 0; /** * @brief Get the source file path for the Mesh data. * * @return The source file path as a c-string. */ virtual char const* GetSourcePath() = 0; /** * @brief Get the directory that contains the Mesh data. * * @return The source directory as a c-string. */ virtual char const* GetSourceDirectory() = 0; /** * @brief Set the source file path for the Mesh data. * * @param [in] path The new source file path. */ virtual void SetSourcePath(flIN char const* path) = 0; /** * @brief Get the Mesh's Position data. */ virtual IElementArray* GetPositionArray() const = 0; /** * @brief Get the Mesh's Texture Coordinate data. */ virtual IElementArray* GetTexcoordArray() const = 0; /** * @brief Get the Mesh's Normal data. */ virtual IElementArray* GetNormalArray() const = 0; /** * @brief Get the Mesh's Colour data. */ virtual IElementArray* GetColourArray() const = 0; /** * @brief Get the number of Positions in the Mesh. */ virtual int64_t GetPositionCount() const = 0; /** * @brief Get the number of Texture Coordinates in the Mesh. */ virtual int64_t GetTexcoordCount() const = 0; /** * @brief Get the number of Normals in the Mesh. */ virtual int64_t GetNormalCount() const = 0; /** * @brief Get the number of Colours in the Mesh. */ virtual int64_t GetColourCount() const = 0; /** * @brief Get the total number of vertices contained in this mesh. * * This is the sum of vertices contained within all polygons. * * @return The total number of vertices. */ virtual int64_t GetVertexCount() = 0; /** * @brief Get the number of polygons in the Mesh. * * @return The polygon count. */ virtual int64_t GetPolygonCount() const = 0; /** * @brief Get the number of Vertices assigned to a polygon. * * @param [in] polyIndex The index of the Polygon to query. * * @return The number of Vertex indices. */ virtual int64_t GetPolygonSize(flIN int64_t polyIndex) const = 0; /** * @brief Get a pointer to a Polygons vertex indices. * * @param [in] polyIndex The index of the Polygon to query. * * @return A pointer to the polygon's vertex indices. */ virtual Vertex* GetPolygonVertices(flIN int64_t polyIndex) = 0; /** * @brief Get a pointer to a Polygons vertex indices. (const) * * @param [in] polyIndex The index of the Polygon to query. * * @return A pointer to the polygon's vertex indices. */ virtual Vertex const* GetPolygonVertices(flIN int64_t polyIndex) const = 0; /** * @brief Get an index of a Vertex in a Polygon. * * @param [in] polyIndex The index of the Polygon to query. * @param [in] vertIndex The index of a vertex within the polygon, where 0 <= vertIndex < GetPolygonSize(polyIndex). * * @return The index of the polygons vertex. This is an index into the Mesh's Vertex array. */ virtual bool GetPolygonVertex(flIN int64_t polyIndex, flIN int64_t vertIndex, flOUT Vertex* pVertex) const = 0; /** * @brief Get the material index assigned to a Polygon. * * @param [in] polyIndex The index of the Polygon to query. * * @return The Material index. This is an index onto the Mesh's Material array. */ virtual int64_t GetPolygonMaterial(flIN int64_t polyIndex) const = 0; /** * @brief Add an empty Polygon to the Mesh. * * @return The index of the new Polygon. */ virtual int64_t AddPolygon() = 0; /** * @brief Add a Polygon with some initial data. * * @param [in] pIndices A pointer to the Polygon's index array. * @param [in] vertexCount The number of Vertex's in the index array. * @param [in] material The index of the Material to assign to the Polygon. * * @return The index of the new Polygon. */ virtual int64_t AddPolygon(flIN Vertex const* pIndices, flIN int64_t vertexCount, flIN int64_t material) = 0; /** * @brief Add a Vertex index to a Polygon. * * @param [in] polyIndex The index of the polygon to add the vertex to. * @param [in] vertIndex The Vertex index to add. * * @return The index of the new Vertex within the Polygon. */ virtual int64_t AddPolygonVertex(flIN int64_t polyIndex, flIN Vertex vertex) = 0; /** * @brief Set the Material index assigned to a Polygon. * * @param [in] polyIndex The index of the Polygon to assign the Material index to. * @param [in] material The index of the Material to assign to the Polygon. * * @return True if polyIndex is valid. Otherwise, False. */ virtual bool SetPolygonMaterial(flIN int64_t polyIndex, flIN int64_t material) = 0; /** * @brief Set the number of Vertices assigned to a Polygon. * * @param [in] polyIndex The index of the Polygon to resize. * @param [in] vertexCount The number of Vertices to allocate. * * @return True if polyIndex is valid. Otherwise, False. */ virtual bool SetPolygonSize(flIN int64_t polyIndex, flIN int64_t vertexCount) = 0; /** * @brief Set the index of a Vertex in a Polygon. * * @param [in] polyIndex The index of the Polygon to be modified. * @param [in] vertIndex The index of the Vertex within the Polygon. * @param [in] index The index of the Vertex to assign to the Polygon. * * @return True if polyIndex, and vertIndex, are valid. Otherwise, False. */ virtual bool SetPolygonVertex(flIN int64_t polyIndex, flIN int64_t vertIndex, flIN Vertex vertex) = 0; /** * @brief Set the indices assigned to a Polygon. * * @param [in] polyIndex The index of the Polygon to be modified. * @param [in] pIndices A pointer to the indices to assign to the Polygon. * @param [in] count The number of indices in the buffer. * * @return True if polyIndex is valid. Otherwise, false. */ virtual bool SetPolygonVertices(flIN int64_t polyIndex, flIN Vertex const* pIndices, flIN int64_t count) = 0; /** * @brief Add a new SurfaceMaterial to the Mesh. * * @return The index of the new SurfaceMaterial in the Mesh. */ virtual int64_t AddMaterial() = 0; /** * @brief Add an existing SurfaceMaterial to the Mesh. * * @return The index of the SurfaceMaterial in the Mesh. */ virtual int64_t AddMaterial(flIN ISurfaceMaterial* pMaterial) = 0; /** * @brief Get the index of a Material in the Mesh by name. * * @param [in] name The name of the Material as a c-string. * * @return The index of the Material or -1 if it was not found. */ virtual int64_t FindMaterial(flIN char const* name) const = 0; /** * @brief Get a SurfaceMaterial by its index. * * @param [in] materialIndex The index of the SurfaceMaterial to retrieve. * * @return A pointer to a SurfaceMaterial if it exists. Otherwise, null is returned. */ virtual ISurfaceMaterial* GetMaterial(flIN int64_t materialIndex) = 0; /** * @brief Get a SurfaceMaterial by its index. (const) * * @param [in] materialIndex The index of the SurfaceMaterial to retrieve. * * @return A const pointer to a SurfaceMaterial if it exists. Otherwise, null is returned. */ virtual ISurfaceMaterial const* GetMaterial(flIN int64_t materialIndex) const = 0; /** * @brief Get the number of Materials in the Mesh. * * @return The Material count. */ virtual int64_t GetMaterialCount() const = 0; virtual void Validate() = 0; virtual void DefaultMissingAttributes() = 0; /** * @brief Triangulate the Mesh. * * Ensures all Polygons only have 3 vertices (i.e. A triangle). Currently this * function only performs a basic triangle fan so convex polygons will produce * incorrect results. * * @return The number of new polygons added. If 0 is returned the mesh is already Triangulated. */ virtual int64_t Triangulate() = 0; /** * @brief Recalculate the normals for all polygons. */ virtual void CalculateFlatNormals() = 0; /** * @brief Add a Polygon with some initial data. * * @param [in] indices An initializer list of indices. * @param [in] material The index of the Material to assign to the Polygon. * * @return The index of the new Polygon. */ inline int64_t AddPolygon(flIN const std::initializer_list<Vertex>& indices, flIN int64_t material) { return AddPolygon(indices.begin(), indices.size(), material); } /** * @brief Set the indices assigned to a Polygon. * * @param [in] polyIndex The index of the Polygon to be modified. * @param [in] indices An initializer list of indices. * * @return True if polyIndex is valid. Otherwise, false. */ inline bool SetPolygonVertices(flIN int64_t polyIndex, flIN const std::initializer_list<Vertex>& indices) { return SetPolygonVertices(polyIndex, indices.begin(), indices.size()); } inline ElementArray<Vec3D> GetPositions() const { return ElementArray<Vec3D>(GetPositionArray()); } inline ElementArray<Vec2D> GetTexcoords() const { return ElementArray<Vec2D>(GetTexcoordArray()); } inline ElementArray<Vec3D> GetNormals() const { return ElementArray<Vec3D>(GetNormalArray()); } inline ElementArray<Vec4D> GetColours() const { return ElementArray<Vec4D>(GetColourArray()); } }; } extern "C" { /** * @brief Create a Mesh instance */ flEXPORT Fractal::IMesh* flCCONV Fractal_CreateMesh(); }
30.294461
120
0.635261
8ef49b10cdbe85e7a3f41c5fd9d39787fa20ea3d
1,672
c
C
comps/sdo/files/lib/CO_SDO_build_init_dl_rq.c
debosvi/canopen
31cacfab9a20c667fa5c18f149799920532a8b03
[ "MIT" ]
null
null
null
comps/sdo/files/lib/CO_SDO_build_init_dl_rq.c
debosvi/canopen
31cacfab9a20c667fa5c18f149799920532a8b03
[ "MIT" ]
null
null
null
comps/sdo/files/lib/CO_SDO_build_init_dl_rq.c
debosvi/canopen
31cacfab9a20c667fa5c18f149799920532a8b03
[ "MIT" ]
null
null
null
#include "private/CO_SDO_p.h" /////////////////////////////////////////////////////////////////////////////// int CO_SDO_build_init_dl_rq(unsigned char *const buf, const bool e, const bool s, const OD_index_t idx, const OD_subindex_t subidx, const CO_SDO_data_size_t lg) { int ret=CO_ERROR_NONE; if(!buf) return CO_ERROR_NULL_PTR; if(s && !lg) return CO_ERROR_BAD_ARGS; if(!s && lg) return CO_ERROR_BAD_ARGS; // reset whole buffer CO_RESET_WHOLE_BUFFER(buf); // set command type buf[0] = CO_SDO_CMD_CCS_INIT_DL_RQ; // set transfert type if(e) buf[0] |= CO_SDO_CMD_TRANSFERT_MASK; else buf[0] &= ~CO_SDO_CMD_TRANSFERT_MASK; // set size presence if(s) buf[0] |= CO_SDO_CMD_SEG_SZ_IND_MASK; else buf[0] &= ~CO_SDO_CMD_SEG_SZ_IND_MASK; // fill indexes if(CO_index_fill(&buf[1], idx, subidx)) { ret=CO_ERROR_BAD_IDX; goto exit; } // put data depending on arguments combination if(e && s) { uint8_t n=0; if((lg&0xFF)==lg) n=3; else if((lg&0xFFFF)==lg) n=2; else if((lg&0xFFFFFF)==lg) n=1; buf[0] |= (n<<2); uint32_t l=lg; for(int i=0; i<(4-n); i++) { buf[4+i] = (l&0xFF); l = l>>8; } } else if(!e && s) { uint32_t l=lg; for(int i=0; i<4; i++) { buf[4+i] = (l&0xFF); l = l>>8; } } else { return CO_ERROR_UNIMPLEMENTED; } exit: if(ret!=CO_ERROR_NONE) { CO_RESET_WHOLE_BUFFER(buf); } return ret; }
23.549296
88
0.504785
fc7aa856e96fcae745b66ef113dc1a7aa329ba5d
718
h
C
common/src/engine/gnump/gmp_wrap.h
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
1
2018-03-09T20:21:47.000Z
2018-03-09T20:21:47.000Z
common/src/engine/gnump/gmp_wrap.h
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
null
null
null
common/src/engine/gnump/gmp_wrap.h
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
1
2020-03-05T23:42:00.000Z
2020-03-05T23:42:00.000Z
/* * GMP MPZ Wrapper * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_GMP_MPZ_WRAP_H__ #define BOTAN_GMP_MPZ_WRAP_H__ #include <botan/bigint.h> #include <gmp.h> namespace Botan { /** * Lightweight GMP mpz_t wrapper. For internal use only. */ class GMP_MPZ { public: mpz_t value; BigInt to_bigint() const; void encode(byte[], size_t) const; size_t bytes() const; SecureVector<byte> to_bytes() const { return BigInt::encode(to_bigint()); } GMP_MPZ& operator=(const GMP_MPZ&); GMP_MPZ(const GMP_MPZ&); GMP_MPZ(const BigInt& = 0); GMP_MPZ(const byte[], size_t); ~GMP_MPZ(); }; } #endif
17.095238
55
0.640669
fc976e791ccf3fd8a221ee668cf23c59e30aadea
2,768
h
C
example/usps_api/async_server.h
samthanawalla/ghost-api
301acec439476f9e15bfc555fee0857e8c1cc0f0
[ "Apache-2.0" ]
1
2020-06-03T19:04:46.000Z
2020-06-03T19:04:46.000Z
example/usps_api/async_server.h
samthanawalla/ghost-api
301acec439476f9e15bfc555fee0857e8c1cc0f0
[ "Apache-2.0" ]
1
2020-06-29T15:07:48.000Z
2020-06-29T15:07:48.000Z
example/usps_api/async_server.h
samthanawalla/ghost-api
301acec439476f9e15bfc555fee0857e8c1cc0f0
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // 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 "config/config_parser.h" #include <grpc/grpc.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include "proto/usps_api/sfc.grpc.pb.h" namespace usps_api_server { class Call { public: virtual void Proceed() = 0; enum CallStatus { CREATE, PROCESS, FINISH }; }; class CreateSfc final : public Call { public: explicit CreateSfc(ghost::SfcService::AsyncService* service, grpc::ServerCompletionQueue* cq, std::shared_ptr<Config> config); void Proceed(); private: ghost::SfcService::AsyncService* service_; grpc::ServerCompletionQueue* cq_; grpc::ServerAsyncResponseWriter<ghost::CreateSfcResponse> responder_; grpc::ServerContext ctx_; CallStatus status_; std::shared_ptr<Config> config_; ghost::CreateSfcRequest request_; ghost::CreateSfcResponse response_; }; class DeleteSfc final : public Call { public: explicit DeleteSfc(ghost::SfcService::AsyncService* service, grpc::ServerCompletionQueue* cq, std::shared_ptr<Config> config); void Proceed(); private: ghost::SfcService::AsyncService* service_; grpc::ServerCompletionQueue* cq_; grpc::ServerContext ctx_; grpc::ServerAsyncResponseWriter<ghost::DeleteSfcResponse> responder_; CallStatus status_; std::shared_ptr<Config> config_; ghost::DeleteSfcRequest request_; ghost::DeleteSfcResponse response_; }; class Query final : public Call { public: explicit Query(ghost::SfcService::AsyncService* service, grpc::ServerCompletionQueue* cq, std::shared_ptr<Config> config); void Proceed(); private: ghost::SfcService::AsyncService* service_; grpc::ServerCompletionQueue* cq_; grpc::ServerContext ctx_; grpc::ServerAsyncResponseWriter<ghost::QueryResponse> responder_; CallStatus status_; std::shared_ptr<Config> config_; ghost::QueryRequest request_; ghost::QueryResponse response_; }; void HandleRpcs(ghost::SfcService::AsyncService& service, grpc::ServerCompletionQueue* cq, std::shared_ptr<Config> config); } //namespace
33.756098
80
0.715318
f78a8ecf7cc864ee3d7196a142ef6fdbcffea70f
1,475
h
C
feeds/ipq807x/qca-nss-drv/src/nss_crypto_cmn_log.h
ArthurSu0211/wlan-ap
5bf882b0e0225d49860b88d25c9b9ff9bc354516
[ "BSD-3-Clause" ]
2
2021-05-17T02:47:24.000Z
2021-05-17T02:48:01.000Z
feeds/ipq807x/qca-nss-drv/src/nss_crypto_cmn_log.h
ArthurSu0211/wlan-ap
5bf882b0e0225d49860b88d25c9b9ff9bc354516
[ "BSD-3-Clause" ]
1
2021-01-14T18:40:50.000Z
2021-01-14T18:40:50.000Z
feeds/ipq807x/qca-nss-drv/src/nss_crypto_cmn_log.h
ArthurSu0211/wlan-ap
5bf882b0e0225d49860b88d25c9b9ff9bc354516
[ "BSD-3-Clause" ]
3
2021-02-22T04:54:20.000Z
2021-04-13T01:54:40.000Z
/* ****************************************************************************** * Copyright (c) 2018, The Linux Foundation. All rights reserved. * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all copies. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * **************************************************************************** */ #ifndef __NSS_CRYPTO_CMN_LOG_H__ #define __NSS_CRYPTO_CMN_LOG_H__ /* * nss_crypto_cmn_log.h * NSS Crypto Common Log header file. */ /* * nss_crypto_cmn_log_tx_msg * Logs a crypto common message that is sent to the NSS firmware. */ void nss_crypto_cmn_log_tx_msg(struct nss_crypto_cmn_msg *ncm); /* * nss_crypto_cmn_log_rx_msg * Logs a crypto common message that is received from the NSS firmware. */ void nss_crypto_cmn_log_rx_msg(struct nss_crypto_cmn_msg *ncm); #endif /* __NSS_CRYPTO_CMN_LOG_H__ */
38.815789
79
0.692203
a1cf105ca5963e83f28633644f8dc488943dd3c9
6,029
h
C
Engine/Toolkit/Math/Math.h
scottcgi/Mojoc
94167a30175140878ac21ec3de43e1d09599dc77
[ "MIT" ]
1,042
2017-06-14T00:49:52.000Z
2022-03-30T16:54:59.000Z
Engine/Toolkit/Math/Math.h
lengxuejian1995/Mojoc
94167a30175140878ac21ec3de43e1d09599dc77
[ "MIT" ]
32
2015-07-22T15:04:40.000Z
2021-12-09T20:12:54.000Z
Engine/Toolkit/Math/Math.h
lengxuejian1995/Mojoc
94167a30175140878ac21ec3de43e1d09599dc77
[ "MIT" ]
174
2017-06-26T06:53:25.000Z
2022-03-30T16:55:08.000Z
/* * Copyright (c) scott.cgi All Rights Reserved. * * This source code belongs to project Mojoc, which is a pure C Game Engine hosted on GitHub. * The Mojoc Game Engine is licensed under the MIT License, and will continue to be iterated with coding passion. * * License : https://github.com/scottcgi/Mojoc/blob/master/LICENSE * GitHub : https://github.com/scottcgi/Mojoc * CodeStyle: https://github.com/scottcgi/Mojoc/blob/master/Docs/CodeStyle.md * * Since : 2013-1-24 * Update : 2019-1-18 * Author : scott.cgi */ #ifndef MATH_H #define MATH_H #include <stdlib.h> #include <math.h> #include <time.h> #include <float.h> #include <stdbool.h> #include "Engine/Toolkit/Utils/Array.h" #include "Engine/Toolkit/Platform/Log.h" struct AMath { /** * Test polygon contains 2D point. * one point of polygon contains pair of x, y. * * return true inside or false outside. */ bool (*TestPolygonPoint) (Array(float)* polygon, float x, float y); /** * Test polygonA intersects polygonB. * * not test polygonB intersects polygonA. * not test through and cross each others. * * return true inside or false outside. */ bool (*TestPolygonAB) (Array(float)* polygonA, Array(float)* polygonB); /** * Test polygonA and polygonB intersect each others. * not test through and cross each others. * * return true inside or false outside. */ bool (*TestPolygonPolygon) (Array(float)* polygonA, Array(float)* polygonB); /** * Test polygonA intersects polygonB. * * not test polygonB intersects polygonA. * can test through and cross each others. * * return true inside or false outside. */ bool (*TestPolygonABStrict) (Array(float)* polygonA, Array(float)* polygonB); /** * Test polygonA and polygonB intersect each others. * can test through and cross each others. * * return true inside or false outside. */ bool (*TestPolygonPolygonStrict)(Array(float)* polygonA, Array(float)* polygonB); /** * Test lineA intersects lineB. * not test lineB intersects lineA. * * return true inside or false outside. */ bool (*TestLineAB) (Array(float)* lineA, Array(float)* lineB); /** * Test lineA and lineB intersect each others. * * return true inside or false outside. */ bool (*TestLineLine) (Array(float)* lineA, Array(float)* lineB); /** * Rotate 2D points by angle. * one point of pointArr contains pair of x, y. */ void (*RotatePoints) (Array(float)* pointArr, float angle, Array(float)* outRotatedPointArr); }; extern struct AMath AMath[1]; //---------------------------------------------------------------------------------------------------------------------- #define GOLDEN_RATIO 0.618033988749894f /** * The value of (PI / 180.0f). */ #define DEGREE_TO_RADIAN 0.017453292519943f /** * The value of (PI / 360.0f). */ #define DEGREE_TO_RADIAN2 0.008726646259972f /** * The value of (180.0f / PI). */ #define RADIAN_TO_DEGREE 57.29577951308232f #define MATH_PI 3.141592653589793f /** * The value of (2 * PI). */ #define MATH_2PI 6.283185307179586f /** * The value of (PI / 2). */ #define MATH_PI2 1.570796326794897f //---------------------------------------------------------------------------------------------------------------------- /** * Random float in range [0.0, 1.0]. */ static inline float AMath_Random() { return (float) (rand() / (double) RAND_MAX); } /** * Random integer in range [from, to]. */ static inline int AMath_RandomInt(int from, int to) { return (from) + rand() % ((to) - (from) + 1); } /** * Random float in range [from, to]. */ static inline float AMath_RandomFloat(float from, float to) { return from + AMath_Random() * ((to) - (from)); } /** * Random seed by system time. */ static inline void AMath_RandomSeedByTime() { srand((unsigned) time(NULL)); } /** * Convert degree to radian. */ static inline float AMath_ToRadian(float degree) { return degree * DEGREE_TO_RADIAN; } /** * Convert radian to degree. */ static inline float AMath_ToDegree(float radian) { return radian * RADIAN_TO_DEGREE; } /** * Cos by degree. */ static inline float AMath_Cos(float degree) { return cosf(AMath_ToRadian(degree)); } /** * Sin by degree. */ static inline float AMath_Sin(float degree) { return sinf(AMath_ToRadian(degree)); } /** * Degree by atan2. */ static inline float AMath_Atan2(float x, float y) { return AMath_ToDegree(atan2f(y, x)); } /** * Degree by acosf. */ static inline float AMath_Acos(float ratio) { return AMath_ToDegree(acosf(ratio)); } /** * Degree by asinf. */ static inline float AMath_Asin(float ratio) { return AMath_ToDegree(asinf(ratio)); } /** * Compare float value equals. */ static inline bool AMath_IsFloatEqual(float x, float y) { return fabsf((x) - (y)) <= FLT_EPSILON; } /** * Fast square inverse root float. */ static inline float AMath_InvSqrtf(float x) { union { float f; int i; } u = {x}; u.i = 0x5f3759df - (u.i >> 1); return u.f * (1.5f - 0.5f * x * u.f * u.f); } /** * Fast square root float. * equals AMath_InvSqrtf(x) * x. */ static inline float AMath_Sqrtf(float x) { union { float f; int i; } u = {x}; u.i = 0x5f3759df - (u.i >> 1); x *= u.f; // reduce one multiplication and increase one assignment return x * (1.5f - 0.5f * x * u.f); } /** * Min in x and y, macro can use generic parameter. */ #define AMath_Min(x, y) \ (((x) < (y)) ? (x) : (y)) /** * Max in a and b, macro can use generic parameter. */ #define AMath_Max(x, y) \ (((x) > (y)) ? (x) : (y)) /** * Clamp x in min and max, macro can use generic parameter. */ #define AMath_Clamp(x, min, max) \ (AMath_Min((max), AMath_Max((x), (min)))) #endif
19.963576
120
0.598607
5985428de35615246d283163b12e13d23c142655
3,258
h
C
src/programs/mdrun/mdrun_main.h
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
384
2015-01-02T19:44:15.000Z
2022-03-27T15:13:15.000Z
src/programs/mdrun/mdrun_main.h
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
9
2015-04-07T20:48:00.000Z
2022-01-24T21:29:26.000Z
src/programs/mdrun/mdrun_main.h
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
258
2015-01-19T11:19:57.000Z
2022-03-18T08:59:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2013,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * * \brief This file declares C-style entrypoints for mdrun * * \author Mark Abraham <mark.j.abraham@gmail.com> * * \ingroup module_mdrun */ #ifndef GMX_PROGRAMS_MDRUN_MDRUN_H #define GMX_PROGRAMS_MDRUN_MDRUN_H #include "gromacs/utility/gmxmpi.h" struct gmx_hw_info_t; namespace gmx { /*! \brief Implements C-style main function for mdrun * * This implementation detects hardware itself, as suits * the gmx wrapper binary. * * \param[in] argc Number of C-style command-line arguments * \param[in] argv C-style command-line argument strings */ int gmx_mdrun(int argc, char* argv[]); /*! \brief Implements C-style main function for mdrun * * This implementation facilitates reuse of infrastructure. This * includes the information about the hardware detected across the * given \c communicator. That suits e.g. efficient implementation of * test fixtures. * * \param[in] communicator The communicator to use for the simulation * \param[in] hwinfo Describes the hardware detected on the physical nodes of the communicator * \param[in] argc Number of C-style command-line arguments * \param[in] argv C-style command-line argument strings * * \todo Progress on https://gitlab.com/gromacs/gromacs/-/issues/3774 * will remove the need of test binaries to call gmx_mdrun in a way * that is different from the command-line and gmxapi. */ int gmx_mdrun(MPI_Comm communicator, const gmx_hw_info_t& hwinfo, int argc, char* argv[]); } // namespace gmx #endif
38.785714
102
0.737262
598ee70ea365737cb267bb0d7e4a92ca6cb6651d
28,816
h
C
VirtoolsNMOLoader/VirtoolsNMOLoader/Virtools-SDK-2.1/Include/XHashTable.h
imengyu/Ballance
3975238876ce7095eb5592d49a624ae728552385
[ "MIT" ]
16
2021-11-12T12:42:04.000Z
2022-03-30T07:56:39.000Z
VirtoolsNMOLoader/VirtoolsNMOLoader/Virtools-SDK-2.1/Include/XHashTable.h
imengyu/Ballance
3975238876ce7095eb5592d49a624ae728552385
[ "MIT" ]
null
null
null
VirtoolsNMOLoader/VirtoolsNMOLoader/Virtools-SDK-2.1/Include/XHashTable.h
imengyu/Ballance
3975238876ce7095eb5592d49a624ae728552385
[ "MIT" ]
1
2022-03-18T04:42:49.000Z
2022-03-18T04:42:49.000Z
/*************************************************************************/ /* File : XHashTable.h */ /* Author : Aymeric Bard */ /* */ /* Virtools SDK */ /* Copyright (c) Virtools 2000, All Rights Reserved. */ /*************************************************************************/ #ifndef _XHashTable_H_ #define _XHashTable_H_ #include "XClassArray.h" #include "XArray.h" #include "XSArray.h" #include "XHashFun.h" #ifdef _WIN32 #pragma warning(disable : 4786) #endif const float L = 0.75f; /************************************************ Summary: Class representation of an Hash Table container. Remarks: T is the type of element to insert K is the type of the key H is the hash function to hash the key Several hash functions for basic types are already defined in XHashFun.h This implementation of the hash table uses Linked List in each bucket for element hashed to the same index, so there are memory allocation for each insertion. For a static implementation without dynamic allocation, look at XSHashTable. There is a m_LoadFactor member which allow the user to decide at which occupation the hash table must be extended and rehashed. ************************************************/ template <class T, class K, class H = XHashFun<K>, class Eq = XEqual<K> /*, float L = 0.75f*/> class XHashTable { // friendship friend class Iterator; // Types struct Entry { K key; T data; Entry *next; }; typedef Entry *pEntry; public: typedef XHashTable Table; typedef XHashTable *pTable; typedef const XHashTable *pConstTable; /************************************************ Summary: Iterator on a hash table. Remarks: This iterator is the only way to iterate on elements in a hash table. The iteration will be in no specific order, not in the insertion order. Here is an example of how to use it: Example: XHashTable<T,K,H>::Iterator it = hashtable.Begin(); while (it != hashtable.End()) { // access to the key it.GetKey(); // access to the element *it; // next element ++it; } ************************************************/ class Iterator { public: /************************************************ Summary: Default constructor of the iterator. ************************************************/ Iterator() : m_Node(0), m_Table(0) {} /************************************************ Summary: Copy constructor of the iterator. ************************************************/ Iterator(const Iterator &n) : m_Node(n.m_Node), m_Table(n.m_Table) {} /************************************************ Summary: Operator Equal of the iterator. ************************************************/ int operator==(const Iterator &it) const { return m_Node == it.m_Node; } /************************************************ Summary: Operator Not Equal of the iterator. ************************************************/ int operator!=(const Iterator &it) const { return m_Node != it.m_Node; } /************************************************ Summary: Returns a constant reference on the data pointed by the iterator. Remarks: The returned reference is constant, so you can't modify its value. Use the other * operator for this purpose. ************************************************/ const T &operator*() const { return (*m_Node).data; } /************************************************ Summary: Returns a reference on the data pointed by the iterator. Remarks: The returned reference is not constant, so you can modify its value. ************************************************/ T &operator*() { return (*m_Node).data; } /************************************************ Summary: Returns a pointer on a T object. ************************************************/ operator const T *() const { return &(m_Node->data); } /************************************************ Summary: Returns a pointer on a T object. ************************************************/ operator T *() { return &(m_Node->data); } /************************************************ Summary: Returns a const reference on the key of the pointed entry. ************************************************/ const K &GetKey() const { return m_Node->key; } K &GetKey() { return m_Node->key; } /************************************************ Summary: Jumps to next entry in the hashtable. ************************************************/ Iterator &operator++() { // Prefixe pEntry old = m_Node; // next element of the linked list m_Node = m_Node->next; if (!m_Node) { // end of linked list, we have to find next filled bucket // OPTIM : maybe keep the index current : save a % int index = m_Table->Index(old->key); while (!m_Node && ++index < m_Table->m_Table.Size()) m_Node = m_Table->m_Table[index]; } return *this; } /************************************************ Summary: Jumps to next entry in the hashtable. ************************************************/ Iterator operator++(int) { Iterator tmp = *this; ++*this; return tmp; } Iterator(pEntry n, pTable t) : m_Node(n), m_Table(t) {} pEntry m_Node; pTable m_Table; }; friend class Iterator; /************************************************ Summary: Constant Iterator on a hash table. Remarks: This iterator is the only way to iterate on elements in a constant hash table. The iteration will be in no specific order, not in the insertion order. Here is an example of how to use it: Example: void MyClass::MyMethod() const { XHashTable<T,K,H>::ConstIterator it = m_Hashtable.Begin(); while (it != m_Hashtable.End()) { // access to the key it.GetKey(); // access to the element *it; // next element ++it; } } ************************************************/ class ConstIterator { friend class XHashTable; public: /************************************************ Summary: Default constructor of the iterator. ************************************************/ ConstIterator() : m_Node(0), m_Table(0) {} /************************************************ Summary: Copy constructor of the iterator. ************************************************/ ConstIterator(const ConstIterator &n) : m_Node(n.m_Node), m_Table(n.m_Table) {} /************************************************ Summary: Operator Equal of the iterator. ************************************************/ int operator==(const ConstIterator &it) const { return m_Node == it.m_Node; } /************************************************ Summary: Operator Not Equal of the iterator. ************************************************/ int operator!=(const ConstIterator &it) const { return m_Node != it.m_Node; } /************************************************ Summary: Returns a constant reference on the data pointed by the iterator. Remarks: The returned reference is constant, so you can't modify its value. Use the other * operator for this purpose. ************************************************/ const T &operator*() const { return (*m_Node).data; } /************************************************ Summary: Returns a pointer on a T object. ************************************************/ operator const T *() const { return &(m_Node->data); } /************************************************ Summary: Returns a const reference on the key of the pointed entry. ************************************************/ const K &GetKey() const { return m_Node->key; } /************************************************ Summary: Jumps to next entry in the hashtable. ************************************************/ ConstIterator &operator++() { // Prefixe pEntry old = m_Node; // next element of the linked list m_Node = m_Node->next; if (!m_Node) { // end of linked list, we have to find next filled bucket // OPTIM : maybe keep the index current : save a % int index = m_Table->Index(old->key); while (!m_Node && ++index < m_Table->m_Table.Size()) m_Node = m_Table->m_Table[index]; } return *this; } /************************************************ Summary: Jumps to next entry in the hashtable. ************************************************/ ConstIterator operator++(int) { ConstIterator tmp = *this; ++*this; return tmp; } ConstIterator(pEntry n, pConstTable t) : m_Node(n), m_Table(t) { } pEntry m_Node; pConstTable m_Table; }; friend class ConstIterator; /************************************************ Summary: Struct containing an iterator on an object inserted and a BOOL determining if it were really inserted (TRUE) or already there (FALSE). ************************************************/ struct Pair { public: Pair(Iterator it, int n) : m_Iterator(it), m_New(n){}; Iterator m_Iterator; XBOOL m_New; }; /************************************************ Summary: Default Constructor. Input Arguments: initialsize: The default number of buckets (should be a power of 2, otherwise will be converted.) l: Load Factor (see Class Description). a: hash table to copy. ************************************************/ XHashTable(int initialsize = 16) { initialsize = Near2Power(initialsize); if (initialsize < 4) initialsize = 4; m_Table.Resize(initialsize); m_Table.Fill(0); m_Pool.Reserve((int)(initialsize * L)); } /************************************************ Summary: Copy Constructor. ************************************************/ XHashTable(const XHashTable &a) { XCopy(a); } /************************************************ Summary: Destructor. Remarks: Release the elements contained in the hash table. If you were storing pointers, you need first to iterate on the table and call delete on each pointer. ************************************************/ ~XHashTable() { } /************************************************ Summary: Removes all the elements from the table. Remarks: The hash table remains with the same number of buckets after a clear. ************************************************/ void Clear() { // we clear all the allocated entries m_Pool.Resize(0); // we clear the table m_Table.Fill(0); } /************************************************ Summary: Calculates the average occupation for the buckets by filling an array with the population for different bucket size (represented by the index of the array) ************************************************/ void GetOccupation(XArray<int> &iBucketOccupation) const { iBucketOccupation.Resize(1); iBucketOccupation[0] = 0; for (pEntry *it = m_Table.Begin(); it != m_Table.End(); it++) { if (!*it) { // there is someone there iBucketOccupation[0]++; } else { // count the number of occupant int count = 1; pEntry e = *it; while (e->next) { e = e->next; count++; } int oldsize = iBucketOccupation.Size(); if (oldsize <= count) { // we need to resize iBucketOccupation.Resize(count + 1); // and we init to 0 for (int i = oldsize; i <= count; ++i) iBucketOccupation[i] = 0; } // the recensing iBucketOccupation[count]++; } } } /************************************************ Summary: Affectation operator. Remarks: The content of the table is enterely overwritten by the given table. ************************************************/ Table &operator=(const Table &a) { if (this != &a) { // We clear the current table Clear(); // we then copy the content of a XCopy(a); } return *this; } /************************************************ Summary: Inserts an element in the table. Input Arguments: key: key of the element to insert. o: element to insert. override: if the key is already present, should the old element be overriden ? Remarks: Insert will automatically override the old value and InsertUnique will not replace the old value. TestInsert returns a XHashPair, which allow you to know if the element was already present. ************************************************/ XBOOL Insert(const K &key, const T &o, XBOOL override) { int index = Index(key); // we look for existing key pEntry e = XFind(index, key); if (!e) { if (m_Pool.Size() == m_Pool.Allocated()) { // Need Rehash Rehash(m_Table.Size() * 2); return Insert(key, o, override); } else { // No XInsert(index, key, o); } } else { if (!override) return FALSE; e->data = o; } return TRUE; } Iterator Insert(const K &key, const T &o) { int index = Index(key); Eq equalFunc; // we look for existing key for (pEntry e = m_Table[index]; e != 0; e = e->next) { if (equalFunc(e->key, key)) { e->data = o; return Iterator(e, this); } } if (m_Pool.Size() == m_Pool.Allocated()) { // Need Rehash Rehash(m_Table.Size() * 2); return Insert(key, o); } else { // No return Iterator(XInsert(index, key, o), this); } } Pair TestInsert(const K &key, const T &o) { int index = Index(key); Eq equalFunc; // we look for existing key for (pEntry e = m_Table[index]; e != 0; e = e->next) { if (equalFunc(e->key, key)) { return Pair(Iterator(e, this), 0); } } // Need Rehash if (m_Pool.Size() == m_Pool.Allocated()) { // Need Rehash Rehash(m_Table.Size() * 2); return TestInsert(key, o); } else { // No return Pair(Iterator(XInsert(index, key, o), this), 1); } } Iterator InsertUnique(const K &key, const T &o) { int index = Index(key); Eq equalFunc; // we look for existing key for (pEntry e = m_Table[index]; e != 0; e = e->next) { if (equalFunc(e->key, key)) { return Iterator(e, this); } } // Need Rehash if (m_Pool.Size() == m_Pool.Allocated()) { // Need Rehash Rehash(m_Table.Size() * 2); return InsertUnique(key, o); } else { // No return Iterator(XInsert(index, key, o), this); } } /************************************************ Summary: Removes an element. Input Arguments: key: key of the element to remove. it: iterator on the object to remove. Return Value: iterator on the lement next to the one just removed. ************************************************/ void Remove(const K &key) { int index = Index(key); Eq equalFunc; // we look for existing key pEntry old = NULL; for (pEntry e = m_Table[index]; e != 0; e = e->next) { if (equalFunc(e->key, key)) { // This is the element to remove // change the pointers to it if (old) { old->next = e->next; } else { m_Table[index] = e->next; } // then removed it from the pool m_Pool.FastRemove(e); if (e != m_Pool.End()) { // wasn't the last one... we need to remap RemapEntry(m_Pool.End(), e); } break; } old = e; } } Iterator Remove(const Iterator &it) { int index = Index(it.m_Node->key); if (index >= m_Table.Size()) return Iterator(0, this); // we look for existing key pEntry old = NULL; for (pEntry e = m_Table[index]; e != 0; e = e->next) { if (e == it.m_Node) { // This is the element to remove if (old) { old->next = e->next; old = old->next; } else { m_Table[index] = e->next; old = m_Table[index]; } // then removed it from the pool m_Pool.FastRemove(e); if (e != m_Pool.End()) { // wasn't the last one... we need to remap RemapEntry(m_Pool.End(), e); if (old == m_Pool.End()) old = e; } break; } old = e; } // There is an element in the same column, we return it if (!old) { // No element in the same bucket, we parse for the next while (!old && ++index < m_Table.Size()) old = m_Table[index]; } return Iterator(old, this); } /************************************************ Summary: Access to an hash table element. Input Arguments: key: key of the element to access. Return Value: a copy of the element found. Remarks: If no element correspond to the key, an element constructed with 0. ************************************************/ T &operator[](const K &key) { int index = Index(key); // we look for existing key pEntry e = XFind(index, key); if (!e) { if (m_Pool.Size() == m_Pool.Allocated()) { // Need Rehash Rehash(m_Table.Size() * 2); return operator[](key); } else { // No e = XInsert(index, key, T()); } } return e->data; } /************************************************ Summary: Access to an hash table element. Input Arguments: key: key of the element to access. Return Value: an iterator of the element found. End() if not found. ************************************************/ Iterator Find(const K &key) { return Iterator(XFindIndex(key), this); } /************************************************ Summary: Access to a constant hash table element. Input Arguments: key: key of the element to access. Return Value: a constant iterator of the element found. End() if not found. ************************************************/ ConstIterator Find(const K &key) const { return ConstIterator(XFindIndex(key), this); } /************************************************ Summary: Access to an hash table element. Input Arguments: key: key of the element to access. Return Value: a pointer on the element found. NULL if not found. ************************************************/ T *FindPtr(const K &key) const { pEntry e = XFindIndex(key); if (e) return &e->data; else return 0; } /************************************************ Summary: search for an hash table element. Input Arguments: key: key of the element to access. value: value to receive the element found value. Return Value: TRUE if the key was found, FALSE otherwise.. ************************************************/ XBOOL LookUp(const K &key, T &value) const { pEntry e = XFindIndex(key); if (e) { value = e->data; return TRUE; } else return FALSE; } /************************************************ Summary: test for the presence of a key. Input Arguments: key: key of the element to access. Return Value: TRUE if the key was found, FALSE otherwise.. ************************************************/ XBOOL IsHere(const K &key) const { return (XBOOL)XFindIndex(key); } /************************************************ Summary: Returns an iterator on the first element. Example: Typically, an algorithm iterating on an hash table looks like: XHashTable<T,K,H>::Iterator it = h.Begin(); XHashTable<T,K,H>::Iterator itend = h.End(); for(; it != itend; ++it) { // do something with *t } ************************************************/ Iterator Begin() { for (pEntry *it = m_Table.Begin(); it != m_Table.End(); it++) { if (*it) return Iterator(*it, this); } return End(); } ConstIterator Begin() const { for (pEntry *it = m_Table.Begin(); it != m_Table.End(); it++) { if (*it) return ConstIterator(*it, this); } return End(); } /************************************************ Summary: Returns an iterator out of the hash table. ************************************************/ Iterator End() { return Iterator(0, this); } ConstIterator End() const { return ConstIterator(0, this); } /************************************************ Summary: Returns the index of the given key. Input Arguments: key: key of the element to find the index. ************************************************/ int Index(const K &key) const { H hashfun; return XIndex(hashfun(key), m_Table.Size()); } /************************************************ Summary: Returns the elements number. ************************************************/ int Size() const { return m_Pool.Size(); } /************************************************ Summary: Return the occupied size in bytes. Parameters: addstatic: TRUE if you want to add the size occupied by the class itself. ************************************************/ int GetMemoryOccupation(XBOOL addstatic = FALSE) const { return m_Table.GetMemoryOccupation(addstatic) + m_Pool.Allocated() * sizeof(Entry) + (addstatic ? sizeof(*this) : 0); } /************************************************ Summary: Reserve an estimation of future hash occupation. Parameters: iCount: count of elements to reserve Remarks: you need to call this function before populating the hash table. ************************************************/ void Reserve(const int iCount) { // Reserve the elements m_Pool.Reserve(iCount); int tableSize = Near2Power((int)(iCount / L)); m_Table.Resize(tableSize); m_Table.Fill(0); } private: // Types /// // Methods pEntry *GetFirstBucket() const { return m_Table.Begin(); } void Rehash(int iSize) { int oldsize = m_Table.Size(); // we create a new pool XClassArray<Entry> pool((int)(iSize * L)); pool = m_Pool; // Temporary table XSArray<pEntry> tmp; tmp.Resize(iSize); tmp.Fill(0); for (int index = 0; index < oldsize; ++index) { Entry *first = m_Table[index]; while (first) { H hashfun; int newindex = XIndex(hashfun(first->key), iSize); Entry *newe = pool.Begin() + (first - m_Pool.Begin()); // insert new entry in new table newe->next = tmp[newindex]; tmp[newindex] = newe; first = first->next; } } m_Table.Swap(tmp); m_Pool.Swap(pool); } int XIndex(int key, int size) const { return key & (size - 1); } void XCopy(const XHashTable &a) { int size = a.m_Table.Size(); m_Table.Resize(size); m_Table.Fill(0); m_Pool.Reserve(a.m_Pool.Allocated()); m_Pool = a.m_Pool; // remap the address in the table for (int i = 0; i < size; ++i) { if (a.m_Table[i]) m_Table[i] = m_Pool.Begin() + (a.m_Table[i] - a.m_Pool.Begin()); } // remap the adresses in the entries for (Entry *e = m_Pool.Begin(); e != m_Pool.End(); ++e) { if (e->next) { e->next = m_Pool.Begin() + (e->next - a.m_Pool.Begin()); } } } pEntry XFindIndex(const K &key) const { int index = Index(key); return XFind(index, key); } pEntry XFind(int index, const K &key) const { Eq equalFunc; // we look for existing key for (pEntry e = m_Table[index]; e != 0; e = e->next) { if (equalFunc(e->key, key)) { return e; } } return NULL; } pEntry XInsert(int index, const K &key, const T &o) { Entry *newe = GetFreeEntry(); newe->key = key; newe->data = o; newe->next = m_Table[index]; m_Table[index] = newe; return newe; } pEntry GetFreeEntry() { // We consider when we arrive here that we have space m_Pool.Resize(m_Pool.Size() + 1); return (m_Pool.End() - 1); } void RemapEntry(pEntry iOld, pEntry iNew) { int index = Index(iNew->key); XASSERT(m_Table[index]); if (m_Table[index] == iOld) { // It was the first of the bucket m_Table[index] = iNew; } else { for (pEntry n = m_Table[index]; n->next != NULL; n = n->next) { if (n->next == iOld) { // found one n->next = iNew; break; // only one can match } } } } /// // Members // the hash table data {secret} XArray<pEntry> m_Table; // the entry pool {secret} XClassArray<Entry> m_Pool; }; #endif
28.140625
94
0.424452
1c6acf258be4c3373ef94fbd99161d879f8e581a
805
h
C
PrivateFrameworks/UIFoundation.framework/NSInsertionPointHelper.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
PrivateFrameworks/UIFoundation.framework/NSInsertionPointHelper.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
PrivateFrameworks/UIFoundation.framework/NSInsertionPointHelper.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/UIFoundation.framework/UIFoundation */ @interface NSInsertionPointHelper : NSObject { unsigned long long _altCount; struct _NSRange { unsigned long long location; unsigned long long length; } _charRange; unsigned long long _count; unsigned long long * _displayAltCharIndexes; double * _displayAltPositions; unsigned long long * _displayCharIndexes; double * _displayPositions; unsigned long long * _logicalAltCharIndexes; double * _logicalAltPositions; unsigned long long * _logicalCharIndexes; double * _logicalLeftBoundaries; double * _logicalPositions; double * _logicalRightBoundaries; long long _writingDirection; } - (void)dealloc; @end
28.75
79
0.731677
e118b6149d71e6780b3df96deb960e73b09856c0
8,502
h
C
src/uci2_ast.h
sartura/uci2
56064182acdd8fa522abab67fdbaa10c2a28165c
[ "BSD-3-Clause" ]
8
2021-02-20T05:40:34.000Z
2022-02-02T20:15:25.000Z
src/uci2_ast.h
sartura/uci2
56064182acdd8fa522abab67fdbaa10c2a28165c
[ "BSD-3-Clause" ]
null
null
null
src/uci2_ast.h
sartura/uci2
56064182acdd8fa522abab67fdbaa10c2a28165c
[ "BSD-3-Clause" ]
4
2021-02-20T05:40:44.000Z
2021-11-19T16:27:35.000Z
// SPDX-License-Identifier: BSD-3-Clause // // Copyright (C) 2019, Sartura Ltd. // /** * @file uci2_ast.h * @brief UCI2 AST handling */ #ifndef UCI2_AST_H #define UCI2_AST_H #include <inttypes.h> #include <stdio.h> /** AST node type */ typedef struct uci2_ast uci2_ast_t; /** Node iterator type */ typedef struct uci2_iter uci2_iter_t; /** Iterator function pointers */ typedef uci2_iter_t* (*uci2_iter_begin_fp)(uci2_iter_t*); typedef uci2_iter_t* (*uci2_iter_next_fp)(uci2_iter_t*); typedef uci2_iter_t* (*uci2_iter_prev_fp)(uci2_iter_t*); typedef uci2_iter_t* (*uci2_iter_end_fp)(uci2_iter_t*); /** Parser context type */ typedef struct uci2_parser_ctx uci2_parser_ctx_t; /** AST node separator byte */ extern char UCI2_AST_PATH_SEP; /** * Fixed node names */ #define UCI2_AST_ROOT "/" #define UCI2_AST_CFG "@C" #define UCI2_AST_PKG "@P" /** * Node type names */ #define UCI2_B_TYPE "T" #define UCI2_B_SECTION "S" #define UCI2_B_SECTION_NM "S" #define UCI2_B_OPTION "O" #define UCI2_B_LIST "L" #define UCI2_B_LIST_ITEM "I" /** UCI node type */ enum uci2_nt { /** Root AST node */ UCI2_NT_ROOT = 0, /** * config: main configuration groups like network, * system, firewall. Each configuration group has * it's own file in /etc/config */ UCI2_NT_CFG_GROUP = 1, /** * Package */ UCI2_NT_PACKAGE = 2, /** * sections: config is divided into sections. A section * can either be named or unnamed. */ UCI2_NT_SECTION = 3, /** * types: a section can have a type. E.g in the network * config we typically have 4 sections of the type * “interface”. The sections are “lan”, “wan”, “loopback” * and “wan6” */ /** * Section name when name is present */ UCI2_NT_SECTION_NAME = 4, /** * types: a section can have a type. E.g in the network * config we typically have 4 sections of the type * “interface”. The sections are “lan”, “wan”, “loopback” * and “wan6” */ UCI2_NT_TYPE = 5, /** * options: each section have some options where you * set your configuration values */ UCI2_NT_OPTION = 6, /** * values: value of option */ UCI2_NT_VALUE = 7, /** * In the lines starting with a list keyword an option with * multiple values is defined. All list statements that share * the same name will be combined into a single list of values * with the same order as in the configuration file */ UCI2_NT_LIST = 8, /** * List item */ UCI2_NT_LIST_ITEM = 9 }; /** * UCI Parser context struct */ struct uci2_parser_ctx { /** root AST */ uci2_ast_t *ast; /** AST node pool */ uci2_ast_t *pool; }; /** * AST node struct */ struct uci2_ast { /** Node type */ int nt; /** Node name */ char *name; /** Node value */ char *value; /** Node index (unnamed section) */ int index; /** Pointer to parent AST node */ uci2_ast_t *parent; /** Array of child AST nodes */ uci2_ast_t **ch; /** Number of children in ch array */ int ch_nr; /* Number of unnamed children in ch array */ int ch_un_nr; }; /** * Node iterator struct */ struct uci2_iter { /** iterate to previous sibling node */ uci2_iter_prev_fp prev; /** iterate to next sibling node */ uci2_iter_next_fp next; /** return NULL if current node is NOT the last sibling node */ uci2_iter_end_fp end; /** return NULL if current node is NOT the first sibling node */ uci2_iter_begin_fp begin; /** pointer to the current sibling node */ uci2_ast_t **np; /** sibling node count */ int n_nr; /** an array of sibling nodes to be iterated */ uci2_ast_t *n[]; }; /** * Check if iterator points to the first sibling node * @param[in] it Pointer to a node iterator * @return Pointer to node iterator or NULL if * the current node is NOT the first * sibling node */ uci2_iter_t *uci2_iter_begin(uci2_iter_t *it); /** * Check if iterator points to the last sibling node * @param[in] it Pointer to a node iterator * @return Pointer to node iterator or NULL if * the current node is NOT the last * sibling node */ uci2_iter_t *uci2_iter_end(uci2_iter_t *it); /** * Move iterator to the previous sibling node * @param[in] it Pointer to a node iterator * @return Pointer to a node iterator */ uci2_iter_t *uci2_iter_prev(uci2_iter_t *it); /** * Move iterator to the next sibling node * @param[in] it Pointer to a node iterator * @return Pointer to a node iterator */ uci2_iter_t *uci2_iter_next(uci2_iter_t *it); /** * Move iterator to the first sibling node * @param[in] it Pointer to a node iterator * @return Pointer to a node iterator */ uci2_iter_t *uci2_iter_first(uci2_iter_t *it); /** * Move iterator to the last sibling node * @param[in] it Pointer to a node iterator * @return Pointer to a node iterator */ uci2_iter_t *uci2_iter_last(uci2_iter_t *it); /** * Create a new iterator * @param[in] n Pointer to the AST node * whose children nodes should * be iterated * @return Pointer to a node iterator */ uci2_iter_t *uci2_iter_new(uci2_ast_t *n); /** iterator helper macros */ #define UCI2_IT_NEW(n) uci2_iter_new(n) #define UCI2_IT_FREE(it) \ do { \ free(it); \ } while (0); #define UCI2_IT_BEGIN(it) uci2_iter_begin(it) #define UCI2_IT_END(it) uci2_iter_end(it) #define UCI2_IT_NEXT(it) uci2_iter_next(it) #define UCI2_IT_PREV(it) uci2_iter_prev(it) #define UCI2_IT_LAST(it) uci2_iter_last(it) #define UCI2_IT_FIRST(it) uci2_iter_first(it) #define UCI2_IT_NODE(it) (*it->np) /** * Create new AST node * @param[in] nt Node type * @param[in] name Node name string * @param[in] value Node value string * @return Pointer to newly created AST node */ uci2_ast_t *uci2_new_ast(int nt, char *name, char *value); /** * Create new AST node, pooled * @param[in] nt Node type * @param[in] name Node name string * @param[in] value Node value string * @param[in] ref_pool Node reference pool * @return Pointer to newly created AST node */ uci2_ast_t *uci2_new_ast_rc(int nt, char *name, char *value, uci2_ast_t *ref_pool); /** * Add child AST node to existing AST node * @param[in,out] p Parent AST node * @param[in] c Child AST node * @return Pointer to Parent AST node */ uci2_ast_t *uci2_ast_add_ch(uci2_ast_t *p, uci2_ast_t *c); /** * Free memory consumed by AST node * @param[in,out] n Pointer to AST node to be freed * @param[in] fc If true, free children recursively */ void uci2_ast_free(uci2_ast_t *n, int fc); /** * Free memory consumed by AST nodes in ref pool * @param[in,out] pool Pointer to AST pool */ void uci2_ast_free_rc(uci2_ast_t *pool); /** * Print AST tree * @param[out] out Output stream * @param[in] n Pointer to starting AST node * @param[in] fmt Output format type * @param[in] depth Current depth, should be 0 */ void uci2_ast_print(FILE *out, uci2_ast_t *n, int depth); /** * @brief Get AST node (/path/to/node notation) * * - nodes use similar notation like linux * filesystem * - example 1: get interface loobpack node * ====================================== * /@C/interface/loobpack * * - example 2: get interface wifi ipaddr * ==================================================== * /@Cintarface/wifi/ipaddr * * * @param[in] root Pointer to root AST node * @param[in] path Destination path to search for * @return AST node that matches the path */ uci2_ast_t *uci2_ast_get(uci2_ast_t *root, const char *path); /** * Update AST auto-generated indexes * * @param[in] root Pointer to root AST node */ void uci2_ast_set_indexes(uci2_ast_t *root); // free and set to NULL #define UCI2_FN(p) \ do { \ free(p); \ p = NULL; \ } while (0) #endif /* ifndef UCI2_AST_H */
26.240741
68
0.609033
f462b94318af127e3a44c40afe7b92e560fbbcd3
279
h
C
src/async/semaphore/semaphore.h
Bubichoo-Teitichoo/libutils
d18ff2e44190a500089d01394aad089a7e345624
[ "MIT" ]
1
2021-11-24T16:59:56.000Z
2021-11-24T16:59:56.000Z
src/async/semaphore/semaphore.h
Bubichoo-Teitichoo/libutils
d18ff2e44190a500089d01394aad089a7e345624
[ "MIT" ]
null
null
null
src/async/semaphore/semaphore.h
Bubichoo-Teitichoo/libutils
d18ff2e44190a500089d01394aad089a7e345624
[ "MIT" ]
null
null
null
#if !defined( __SEMAPHORE_H__ ) #define __SEMAPHORE_H__ #include <Windows.h> typedef HANDLE sem_t; int sem_init( sem_t *sem, int pshare, unsigned int value ); void sem_destroy( sem_t *sem ); int sem_post( sem_t *sem ); int sem_wait( sem_t *sem ); #endif // __SEMAPHORE_H__
19.928571
59
0.727599
34fe87be8e8a81dc54edd4f7e1c39a5329930c7d
2,356
h
C
include/atanherf.h
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
7
2019-12-03T17:45:31.000Z
2021-04-21T15:46:41.000Z
include/atanherf.h
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
6
2020-09-28T06:57:23.000Z
2020-10-22T05:41:12.000Z
include/atanherf.h
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
1
2020-10-11T08:59:41.000Z
2020-10-11T08:59:41.000Z
#ifndef __atanherf_h__ #define __atanherf_h__ #ifndef PWD #define PWD '.' #endif #include <cmath> #include <fstream> #include <algorithm> #include <memory> #include <numeric> #include <iostream> #include <utils.hpp> #include <spline.h> namespace AtanhErf { /** * @brief Load spline data points from file. * * @details The filename is hard coded into the function body and it must be placed * in `$PWD/data/atanherf_interp.max_16.step_0.0001.first_1.dat`. * * The variable PWD is defined at compile time and its value is set by the CMake file. * If you want to use a file in a different location, please re-build the library setting * the variable * * \code{.sh} * -DPWD='new/path/location' * \endcode * * @return Spline object with the interpolated coordinates. */ spline getinp (); /** * @brief Atanh of erf function for large values of x. * * @param x Input variable. * * @return Approximated result of atanherf function. */ double atanherf_largex (const double & x); /** * @brief Atanh of erf function computed with the interpolation coordinates * extracted by the spline. * * @param x Input variable. * * @return Approximated result of atanherf function estimated using a pre-computed LUT. The * LUT is generated using a cubic spline interpolation. */ double atanherf_interp (const double & x); /** * @brief Atanh of erf function evaluated as polynomial decomposition. * * @param x Value as argument of atanherf function. * * @return Approximated result of atanherf function. */ double evalpoly (const double & x); /** * @brief Atanh of erf function. * * @details The result is evaluated with different numerical techniques according to its domain. * * In particular: * - if its abs is lower than 2 -> "standard" formula * - if its abs is lower than 15 -> `atanherf_interp` formula * - if its abs is greater than 15 -> `atanherf_largex` formula * * @param x Input variable. * * @return Approximated result of atanherf function. * * @note The function automatically use the most appropriated approximation of the atanherf function * to prevent possible overflows. */ double atanherf (const double & x); } #endif // __atanherf_h__
26.772727
102
0.671477
ede78261ccdd273449cee4e605f010cdbef71c7c
11,861
h
C
platform/gucefCOMCORE/include/CTCPServerConnection.h
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
5
2016-04-18T23:12:51.000Z
2022-03-06T05:12:07.000Z
platform/gucefCOMCORE/include/CTCPServerConnection.h
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
2
2015-10-09T19:13:25.000Z
2018-12-25T17:16:54.000Z
platform/gucefCOMCORE/include/CTCPServerConnection.h
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
15
2015-02-23T16:35:28.000Z
2022-03-25T13:40:33.000Z
/* * gucefCOMCORE: GUCEF module providing basic communication facilities * * Copyright (C) 1998 - 2020. Dinand Vanvelzen * * 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 GUCEF_COMCORE_CTCPSERVERCONNECTION_H #define GUCEF_COMCORE_CTCPSERVERCONNECTION_H /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #ifndef GUCEF_CORE_CCYCLICDYNAMICBUFFER_H #include "CCyclicDynamicBuffer.h" #define GUCEF_CORE_CCYCLICDYNAMICBUFFER_H #endif /* GUCEF_CORE_CCYCLICDYNAMICBUFFER_H ? */ #ifndef GUCEF_CORE_CTIMER_H #include "CTimer.h" #define GUCEF_CORE_CTIMER_H #endif /* GUCEF_CORE_CTIMER_H ? */ #ifndef GUCEF_COMCORE_CTCPCONNECTION_H #include "CTCPConnection.h" /* TCP connection base class */ #define GUCEF_COMCORE_CTCPCONNECTION_H #endif /* GUCEF_COMCORE_CTCPCONNECTION_H ? */ /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace COMCORE { /*-------------------------------------------------------------------------// // // // CLASSES // // // //-------------------------------------------------------------------------*/ struct STCPServerConData; /*-------------------------------------------------------------------------// // // // CLASSES // // // //-------------------------------------------------------------------------*/ /* * Forward declarations of classes used */ class CTCPServerSocket; /*-------------------------------------------------------------------------*/ /** * Class that represents a single connection on a TCP server socket */ class GUCEF_COMCORE_EXPORT_CPP CTCPServerConnection : public CTCPConnection { public: /** * Closes the connection to the client. * This can cause this object to be deleted by the parent server. * After a call to Close() the object should no longer be accessed * by the user. */ virtual void Close( void ) GUCEF_VIRTUAL_OVERRIDE; /** * Allows you to read data from the socket when using a blocking * socket approach. This member function always returns false for * non-blocking sockets. * */ bool Read( char *dest , UInt32 size , UInt32 &wbytes , Int32 timeout ); /** * Send data to client. */ virtual bool Send( const void* dataSource , const UInt32 dataSize ) GUCEF_VIRTUAL_OVERRIDE; bool Send( const CORE::CDynamicBuffer& content ); virtual bool IsActive( void ) const GUCEF_VIRTUAL_OVERRIDE; /** * Set's the maximum number of bytes to be read from the socket * received data buffer. A value of 0 means infinite. Setting this * value to non-zero allows you to avoid the server connection or * even the entire server socket (if the server socket is not using * a separate thread) from getting stuck reading data. If data is * being sent in such a fast rate that the continues stream will * be considered to be a single transmission the server will not * be able to stop reading. This is where the max read value comes * in. No matter how much new data is available the reading will * stop at the set number of bytes. If you have a fixed transmission * length then this is easy to deal with by using a factor of the * transmission length as the max read value. Otherwise you will * have to check what data you need and what data should be kept. * The data you think that should be kept will be prefixed to the * next data buffer. You can control this process by setting the * keepbytes value in the OnClientRead() event handler. * In short, this helps prevent a DOS attack on the software. */ void SetMaxRead( UInt32 mr ); /** * This returns the current max read value. * This represents the current setting for the maximum number of * bytes that will be read from the data buffer. */ UInt32 GetMaxRead( void ) const; virtual const CORE::CString& GetRemoteHostName( void ) const GUCEF_VIRTUAL_OVERRIDE; virtual UInt16 GetRemoteTCPPort( void ) const GUCEF_VIRTUAL_OVERRIDE; virtual CIPAddress GetRemoteIP( void ) const GUCEF_VIRTUAL_OVERRIDE; virtual CHostAddress GetRemoteHostAddress( void ) const; /** * Constructor, init vars */ CTCPServerConnection( CTCPServerSocket *tcp_serversock , UInt32 connection_idx ); virtual ~CTCPServerConnection(); UInt32 GetConnectionIndex( void ) const; /** * Allows you to set whether to use data coalescing on sends. * This is commonly refered to as the Nagle algorithm */ virtual bool SetUseTcpSendCoalescing( bool coaleseData ) GUCEF_VIRTUAL_OVERRIDE; virtual bool GetUseTcpSendCoalescing( void ) const GUCEF_VIRTUAL_OVERRIDE; virtual UInt32 GetBytesReceived( bool resetCounter ) GUCEF_VIRTUAL_OVERRIDE; virtual UInt32 GetBytesTransmitted( bool resetCounter ) GUCEF_VIRTUAL_OVERRIDE; void SetDisconnectIfIdle( bool disconnectIfIdle ); bool GetDisconnectIfIdle( void ) const; void SetMaxIdleDurationInMs( UInt32 maxIdleTimeInMs ); UInt32 GetMaxIdleDurationInMs( void ) const; protected: friend class CTCPServerSocket; /** * polls the socket ect. as needed and update stats. * * @param maxUpdatesPerCycle Max number of socket operation update cycles per pulse */ virtual void Update( UInt32 maxUpdatesPerCycle ); virtual bool Lock( UInt32 lockWaitTimeoutInMs = GUCEF_MT_DEFAULT_LOCK_TIMEOUT_IN_MS ) const GUCEF_VIRTUAL_OVERRIDE; virtual bool Unlock( void ) const GUCEF_VIRTUAL_OVERRIDE; private: void CheckRecieveBuffer( void ); void CloseImp( bool byUser, bool lock, bool updateActiveLists, bool notify ); void OnIdleTimerTriggered( CORE::CNotifier* notifier , const CORE::CEvent& eventId , CORE::CICloneable* eventData ); private: friend class CTCPServerSocket; typedef CORE::CTEventHandlerFunctor< CTCPServerConnection > TEventCallback; struct STCPServerConData* _data; bool _blocking; bool _active; CORE::CDynamicBuffer m_readbuffer; CORE::CCyclicDynamicBuffer m_sendBuffer; CORE::CDynamicBuffer m_sendOpBuffer; MT::CMutex _datalock; UInt32 m_maxreadbytes; UInt32 m_connectionidx; CTCPServerSocket* m_parentsock; bool m_coaleseDataSends; UInt32 m_bytesReceived; UInt32 m_bytesTransmitted; bool m_disconnectIfIdle; CORE::CTimer m_idleTimer; CTCPServerConnection( void ); /* private default constructor because we need data */ }; /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace COMCORE */ }; /* namespace GUCEF */ /*-------------------------------------------------------------------------*/ #endif /* GUCEF_COMCORE_CTCPSERVERCONNECTION_H ? */ /*-------------------------------------------------------------------------// // // // Info & Changes // // // //-------------------------------------------------------------------------// - 09-06-2007 : - Dinand: Finally got around to fixing this class and make it compatible with the infrastructure that is also used by the TCP client socket - 29-06-2004 : - Dinand: Fixed a bug in the set Max_Read(). An old check that made sure the mr value was > 0 was still present causing a problem with the new max read protection and could potentially cause data to 'drop'. - 20-01-2004 : - Dinand: Added the set and get for Max_Read(). This addition is meant to increase the resistance of the server to data spam-ing. - 13-01-2004 : - Dinand: This class now overrides the CSocket's mutex lock and unlock member functions so we can also lock the server socket. This prevents a deadlock from occurring between the two. - 11-01-2004 : - Dinand: Modified code so that this object also closes the NET2 socket itself. All code for manipulating the lower level socket functions for the connection is now located in this class. The server socket should delete this object in a connection closing member function or a loop will occur causing access of a deleted object. - 05-01-2004 : - Dinand: Modified the class code so that it will now process events for this connection itself instead of letting the parent server socket do it. This means setting the threading method for this connection now has an effect as intended. - Dinand: The socket will now close after an error occurred. - 23-09-2003 : - Dinand: Added this section. - Dinand: Added Wait_Untill_Read() in order to provide a method of operation similar to a blocking socket. Also added Read_Data() which will allow a blocking socket implementation to be used. You should only call these member functions from a thread other then the main application thread. -----------------------------------------------------------------------------*/
42.512545
120
0.518843
453b6a0aea2c3241077eda0d3b43600aecd8c1a5
835
h
C
System/Library/PrivateFrameworks/SpringBoardHome.framework/SBScaleIconZoomAnimationContaining.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/PrivateFrameworks/SpringBoardHome.framework/SBScaleIconZoomAnimationContaining.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/SpringBoardHome.framework/SBScaleIconZoomAnimationContaining.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Monday, September 28, 2020 at 5:55:10 PM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/SpringBoardHome.framework/SpringBoardHome * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @protocol SBScaleIconZoomAnimationContaining <SBIconZoomAnimationContaining> @optional -(id)searchGesture; -(id)targetIconContainerView; -(id)matchMoveSourceViewForIconView:(id)arg1; -(void)prepareForAnimation:(id)arg1 withTargetIcon:(id)arg2; -(void)setContentAlpha:(double)arg1; @required -(void)returnScalingView; -(id)borrowScalingView; @end
34.791667
114
0.665868
3ad7b5e8be29f55695b8c43db7d8733addb2ba52
1,657
h
C
zero_python/breakpoint_registry.h
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
2
2018-03-19T23:27:47.000Z
2018-06-24T16:15:19.000Z
zero_python/breakpoint_registry.h
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
null
null
null
zero_python/breakpoint_registry.h
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
1
2021-11-28T05:39:05.000Z
2021-11-28T05:39:05.000Z
#ifndef BREAKPOINT_REGISTRY_H__BBCA9C7E_3485_4525_96AB_94DE6B2EED2F #define BREAKPOINT_REGISTRY_H__BBCA9C7E_3485_4525_96AB_94DE6B2EED2F // // $Id$ // // ------------------------------------------------------------------------- // This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // ------------------------------------------------------------------------- // #include <map> #include "generic/singleton.h" #include "zdk/enum.h" #include "zdk/weak_ptr.h" class BreakPoint; class BreakPointAction; /** * Keep track of breakpoint actions, so that one * can refer to them by numberic IDs * * TODO better name: BreakPointActionRegistry? */ class ZDK_LOCAL BreakPointRegistry : public EnumCallback<volatile BreakPoint*> , private EnumCallback<BreakPointAction*> { typedef WeakPtr<BreakPointAction> ActionPtr; // map actions to numbers typedef std::map<ActionPtr, size_t> ActionToNumber; // map numbers to breakpoint actions typedef std::map<size_t, ActionPtr> NumberToAction; ActionToNumber actionToNumber_; NumberToAction numberToAction_; volatile BreakPoint* brkpnt_; public: BreakPointRegistry() : brkpnt_(NULL) { } ~BreakPointRegistry() throw() { } void notify(volatile BreakPoint*); void notify(BreakPointAction*); }; typedef Singleton<BreakPointRegistry> TheBreakPointRegistry; #endif // BREAKPOINT_REGISTRY_H__BBCA9C7E_3485_4525_96AB_94DE6B2EED2F // vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
28.084746
76
0.689801
d73a99b24eafadae43ff32c9b27e078afb87e0a3
1,581
c
C
LeetCodePractice/LeetCodePractice/Easy3/LC922.c
White-White/LeetCodePractice
2d6dd3745124d7b7ea5498acfcd6cf8440637c25
[ "MIT" ]
null
null
null
LeetCodePractice/LeetCodePractice/Easy3/LC922.c
White-White/LeetCodePractice
2d6dd3745124d7b7ea5498acfcd6cf8440637c25
[ "MIT" ]
null
null
null
LeetCodePractice/LeetCodePractice/Easy3/LC922.c
White-White/LeetCodePractice
2d6dd3745124d7b7ea5498acfcd6cf8440637c25
[ "MIT" ]
null
null
null
/* Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return any answer array that satisfies this condition. Example 1: Input: [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Note: 2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000 */ #include "LC922.h" int* sortArrayByParityII(int* A, int ASize, int* returnSize) { int evenDetector = 0; int oddDetector = 1; while (evenDetector < ASize && oddDetector < ASize) { while (evenDetector < ASize && A[evenDetector] % 2 == 0) { evenDetector += 2; } while (oddDetector < ASize && A[oddDetector] % 2 != 0) { oddDetector += 2; } if (evenDetector < ASize && oddDetector < ASize) { int temp = A[evenDetector]; A[evenDetector] = A[oddDetector]; A[oddDetector] = temp; } } *returnSize = ASize; return A; } //如果交换的成本很低 则下面的算法可能更快 int* sortArrayByParityIIAnother(int* A, int ASize, int* returnSize) { int e = 0; int o = 1; while (e < ASize && o < ASize) { if (A[e] % 2 != 0) { int temp = A[e]; A[e] = A[o]; A[o] = temp; o+=2; } else { e+=2; } } *returnSize = ASize; return A; }
21.364865
113
0.512966
ba5ca2e9abe8adb84c2c636e8385321a51ed2ebe
652
h
C
me2korea/UIElements/ToptenCell.h
dzstudio/ios-newsapp-practice
3e62a37226d762ac5333a367b7052c20af84ae72
[ "MIT" ]
null
null
null
me2korea/UIElements/ToptenCell.h
dzstudio/ios-newsapp-practice
3e62a37226d762ac5333a367b7052c20af84ae72
[ "MIT" ]
null
null
null
me2korea/UIElements/ToptenCell.h
dzstudio/ios-newsapp-practice
3e62a37226d762ac5333a367b7052c20af84ae72
[ "MIT" ]
null
null
null
// // ToptenCell.h // ios-newsapp-practice // // Created by DillonZhang on 15/5/31. // Copyright (c) 2015年 dillonzhang. All rights reserved. // #import <UIKit/UIKit.h> @interface ToptenCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *budgetIcon; @property (weak, nonatomic) IBOutlet UILabel *labelRank; @property (weak, nonatomic) IBOutlet UIImageView *thumImage; @property (weak, nonatomic) IBOutlet UILabel *labelTitle; @property (weak, nonatomic) IBOutlet UILabel *labelArtist; @property (weak, nonatomic) IBOutlet UIImageView *tipIcon; - (void)configCellWithRecord:(Toptenz *)record withType:(NSString *)type; @end
28.347826
73
0.757669
db80639a02ae129c8ad41af08e83f75c74ee9ffd
9,344
c
C
Member/SLM/Linux_code/ls-alR.c
xiyoulinuxgroup-2019-summer/TeamD
8195c67ab3f7ee9e2d18990ad105a1c62aa095d3
[ "MIT" ]
6
2019-07-19T01:09:18.000Z
2019-07-27T06:53:24.000Z
Member/SLM/Linux_code/ls-alR.c
xiyoulinuxgroup-2019-summer/TeamD
8195c67ab3f7ee9e2d18990ad105a1c62aa095d3
[ "MIT" ]
null
null
null
Member/SLM/Linux_code/ls-alR.c
xiyoulinuxgroup-2019-summer/TeamD
8195c67ab3f7ee9e2d18990ad105a1c62aa095d3
[ "MIT" ]
2
2019-07-23T11:15:30.000Z
2019-09-15T11:49:43.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <dirent.h> #include <unistd.h> #include <limits.h> #include <errno.h> #include <grp.h> #include <pwd.h> #define MAXROWLEN 80 //一行显示的最多字符数 void error(char *p,int line) //错误处理函数!! { printf("error!:%d",line); perror(p); exit(1); } void takeout(char *path,char *name) //从路径中解析出文件名 { int i,j; for(i=0;i<strlen(path);i++) { if(path[i]=='/') { j=0; continue; } name[j++]=path[i]; } name[j]='\0'; } void display_l(struct stat buf,char *name) //获取文件属性 打印 { //char buf_time[32]; int n; struct passwd *pw; struct group *gr; struct tm *t; switch(buf.st_mode & S_IFMT) //获取并转换之后打印文件类型 { case S_IFREG: printf("-"); break; case S_IFDIR: printf("d"); break; case S_IFCHR: printf("c"); break; case S_IFBLK: printf("b"); break; case S_IFIFO: printf("p"); break; case S_IFLNK: printf("l"); break; case S_IFSOCK: printf("s"); break; } for(n=8;n>=0;n--) //文件权限 { if(buf.st_mode & (1<<n)) { switch(n%3) { case 2: printf("r"); break; case 1: printf("w"); break; case 0: printf("x"); break; default: break; } } else printf("-"); } printf("%3d",buf.st_nlink); //硬链接数 pw=getpwuid(buf.st_uid); //所属用户名 gr=getgrgid(buf.st_gid); //所属用户组名 printf("%-6s %-6s",pw->pw_name,gr->gr_name); printf(" %5ld",buf.st_size); //字节数 t=localtime(&buf.st_mtime); //最后修改时间 printf(" %d-%d-%d %02d:%02d:%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); if(S_ISLNK(buf.st_mode)) //判断是否为链接文件 { printf("->"); readlink(name,link,100); printf("%s",link); } } // 根据 *命令行参数* & *完整路径名* 显示<目标文件> // 参数flag: 命令行参数 // 参数pathname: 包含了文件名的路径名 void display(int flag,char *pathname) { void display_R(int flag,char *path); int i,j; struct stat buf; char name[256]; if(lstat(pathname,&buf) == -1) { error("display",__LINE__); } takeout(pathname,name); switch(flag) { case 1: //没有 a l R 参数 if(name[0] != '.') printf("%-6s",name); break; case 3: // -a printf("%-6s",name); break; case 5: // -l if(name[0]!='.') { display_l(buf,name); printf("%s\n",name); } break; case 7: // -a -l display_l(buf,name); printf(" %-s\n",name); case 9: // -R display_R(flag,pathname); break; case 11: // -a -R printf(". ..\n"); display_R(flag,pathname); break; case 13: //-l -R display_l(buf,name); printf(" "); display_R(flag,pathname); case 15: //-a -l -R display_l(buf,"."); printf(".\n"); display_l(buf,".."); printf("..\n"); display_R(flag,pathname); break; } } void display_R(int flag,char *path) //-R参数 { struct stat buf; struct stat buff; DIR *dir; struct dirent * ptr; char allname[256][260],name[256][260],a[260]; int i,j,len,count; if(lstat(path,&buf)==-1) { if(errno==13) //permission denied :请求的<文件/文件夹>没有权限导致<服务器拒绝请求> { return ; } else { printf("error : %s\n",path); //error("display_R",__LINE__); return ; } } if(S_ISDIR(buf.st_mode)) //该文件为目录文件,含有<文件>/<子目录> { printf("\n%s\n",path); //打印目录名 count=0; dir = opendir(path); if(dir == NULL) { error("display_R",__LINE__); } i=0; //获取子目录下的文件目录名,并连接成绝对路径 while((ptr=readdir(dir))!=NULL) { len=0; count++; strncpy(allname[i],path,strlen(path)); allname[i][strlen(path)]='/'; allname[i][strlen(path)+1]='\0'; strncat(allname[i],ptr->d_name,strlen(ptr->d_name)); allname[i][strlen(allname[i])]='\0'; i++; } for(i=0;i<count;i++) takeout(allname[i],name[i]); for(i=0;i<count;i++) { if(name[i][0]!='.') { if(lstat(allname[i],&buff) == -1) printf("error242"); if(S_ISDIR(buff.st_mode)) //如果这个文件还是目录文件 { char *m=(char *)malloc(strlen(allname[i])*sizeof(char)); display_R(flag,m); // 递归 free(m); } else { if(flag>11) { display_l(buff,allname[i]); } printf(" %s\n",name[i]); } } else { printf("\n"); continue; } } } else { takeout(path,a); if(a[0] != '.') { if(flag > 11) { display_l(buff,allname[i]); } printf(" %-s\n",a); } } } void display_dir(int flag_param,char *path) { void display(int flag,char *pathname); DIR *dir; struct dirent *ptr; int count=0; char filename[256][260],fullname[256][260],name[256][260]; char temp[PATH_MAX]; //PATH_MAX包含在(stdlib.h) 在vc中它的值为260 //获取该目录下文件总数 dir=opendir(path); if(dir == -1) { error("opendir",__LINE__); } int i=0,j,k,len; while((ptr= readdir(dir))!=NULL) { len=0; count++; memset(filename[i],0,strlen(filename[i])); memcpy(filename[i],ptr->d_name,sizeof(ptr->d_name)); //strcpy(filename[i],ptr->d_name); len = strlen(ptr->d_name); filename[i][len]='\0'; i++; } closedir(dir); if(count>256) { error("opendir",__LINE__); } //按字典序排序 for(j=0;j<count-1;j++) { for(i=0;i<count-1-j;i++) { if(strcmp(filename[i],filename[i+1])>0) { strcpy(temp,filename[i]); strcpy(filename[i],filename[i+1]); strcpy(filename[i+1],temp); } } } for(i=0;i<count;i++) { strncat(fullname[i],path,strlen(path)); fullname[i][strlen(path)]='/'; fullname[i][strlen(path)+1]='\0'; strncat(fullname[i],filename[i],strlen(filename[i])); fullname[i][strlen(fullname[i])]='\0'; } for(i=0;i<count;i++) { takeout(fullname[i],name[i]); } for(i=0;i<count;i++) { if(flag_param ==9 || flag_param == 11 || flag_param == 13 || flag_param == 15) { int flag=1; if(name[i][0] == '.') flag=0; if(flag==1) display(flag_param,fullname[i]); } else display(flag_param,fullname[i]); printf("\n"); } } int main(int argc,char *argv[]) { struct stat buf; int i,j,k; char path[260]; char param[32]; //保存命令行参数,目标文件名和目录名不在 该数组 int flag_param=1; //参数种类,判断是否含有 -l -a -R 选项 //解析命令行参数 (让程序知道输入了哪些参数) j=0; for(i=0;i<argc;i++) { if(argv[i][0]=='-') { //注意这里!!!!××××××××××× //k<=strlen(argv[i])????????? // for(k=1;k<strlen(argv[i]);k++,j++) param[j]=argv[i][k]; //获取 - 后面的参数 保存到param数组 } } //只支持参数a l R 如果有其他选项就报错!! for(i=0;i<j;i++) { if(param[i]=='a') flag_param+=2; else if(param[i]=='l') flag_param+=4; else if(param[i]=='R') flag_param+=8; if(param[i]!='a' && param[i]!='l' && param[i]!='R') { printf("-myls don't have this functional-"); exit(1); } } param[i]='\0'; if(argc==1) //如果没有输入参数 直接执行./a.out 就等于路径为当前目录 { strcpy(path,'.'); display_dir(flag_param,path); return 0; } // 有点问题 else if(argc==2) { if(flag_param==1) { strcpy(path,argv[1]); } else { strcpy(path,'.'); } } // ???有点问题 else if(argc==3) { strcpy(path,argv[2]); } //如果目标文件或目录不存在,报错并退出程序 if(stat(path,&buf)==-1) { error("it doesn't exist",__LINE__); } if(S_ISDIR(buf.st_mode)) //是一个目录 display_dir(flag_param,path); else display(flag_param,path); return 0; }
21.236364
109
0.423801
807f8a19cd242327cab11405f33373b4d3afff7b
17,460
h
C
src/wayland.h
mariusor/nukebar
3e2b349dcec3fef6b777c07a1610fedee65afb73
[ "MIT" ]
null
null
null
src/wayland.h
mariusor/nukebar
3e2b349dcec3fef6b777c07a1610fedee65afb73
[ "MIT" ]
null
null
null
src/wayland.h
mariusor/nukebar
3e2b349dcec3fef6b777c07a1610fedee65afb73
[ "MIT" ]
null
null
null
#ifndef NUKEBAR_WAYLAND_H #define NUKEBAR_WAYLAND_H #include <fcntl.h> #include <stdbool.h> #include <string.h> #include <sys/mman.h> #include <time.h> #include <unistd.h> #include <wayland-client.h> #include <wayland-client-protocol.h> #include <wayland-egl.h> #include <linux/input-event-codes.h> #include "xdg-shell-client-protocol.h" #include "render.h" #define DEFAULT_WIDTH_PX 1920 #define DEFAULT_HEIGHT_PX 30 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t serial, wl_fixed_t x, wl_fixed_t y) { _trace2("pointer_motion[%p], pointer[%p] serial=%d [%d,%d]", data, pointer, serial, x, y); } static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t x, wl_fixed_t y) { _trace2("pointer_enter[%p], pointer[%p] serial=%d [%d,%d] surface[%p]", data, pointer, serial, x, y, surface); } static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) { _trace2("pointer_leave[%p], pointer[%p] serial=%d surface[%p]", data, pointer, serial, surface); } static void pointer_handle_axis(void *data, struct wl_pointer *pointer, uint32_t x, uint32_t y, wl_fixed_t pos) { _trace2("pointer_axis[%p], pointer[%p] pos=%d [%d,%d]", data, pointer, pos, x, y); } static void xdg_toplevel_handle_configure(void *data, struct xdg_toplevel *top, int32_t x, int32_t y, struct wl_array *list) { _trace2("xdg_toplevel_configure[%p], xdg_toplevel[%p] [%d,%d] arr[%p]", data, top, x, y, list); struct nukebar *bar = data; if (x != bar->width || y != bar->height) { bar->width = x; bar->height = y; } } static void xdg_surface_handle_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) { _trace2("xdg_surface_configure[%p], xdg_surface[%p] serial=%d", data, xdg_surface, serial); if (data == NULL) { return; } struct nukebar* bar = data; xdg_surface_ack_configure(xdg_surface, serial); wl_surface_commit(bar->surface); } static const struct xdg_surface_listener xdg_surface_listener = { .configure = xdg_surface_handle_configure, }; static void xdg_toplevel_handle_close(void *data, struct xdg_toplevel *xdg_toplevel) { _trace2("xdg_toplevel_close[%p] top_level[%p]", data, xdg_toplevel); if (data == NULL) { return; } struct nukebar *bar = data; bar->stop = true; } static const struct xdg_toplevel_listener xdg_toplevel_listener = { .configure = xdg_toplevel_handle_configure, .close = xdg_toplevel_handle_close, }; static void pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) { _trace2("pointer_button[%p], pointer[%p] serial=%d, time=%d, but=%d, state=%d", data, pointer, serial, time, button, state); /* struct nukebar *bar = data; if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) { xdg_toplevel_move(bar->xdg_toplevel, bar->seat, serial); } */ } 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, }; static void seat_handle_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities) { _trace2("seat_capabilities[%p], seat[%p], cap=%d", data, seat, capabilities); if (capabilities & WL_SEAT_CAPABILITY_POINTER) { struct wl_pointer *pointer = wl_seat_get_pointer(seat); wl_pointer_add_listener(pointer, &pointer_listener, data); } #if 0 if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) { struct wl_keyboard *keyboard = wl_seat_get_keyboard (seat); wl_keyboard_add_listener (keyboard, &nk_wayland_keyboard_listener, win); } #endif } static void seat_handle_name(void *data, struct wl_seat *seat, const char* name) { _trace2("seat_capabilities[%p], seat[%p], name=%s", data, seat, name); } static const struct wl_seat_listener seat_listener = { .capabilities = seat_handle_capabilities, .name = seat_handle_name, }; static void output_mode(void *data, struct wl_output *wl_output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) { // @todo(marius): here we add the screens that we want to display the bar on to _trace2("output_mode[%p] wl_output[%p] flags=%d, size:%dx%d refresh=%d", data, wl_output, flags, width, height, refresh); } static void output_done(void *data, struct wl_output *wl_output) { _trace2("output_done[%p] wl_output[%p]", data, wl_output); } static void output_scale(void *data, struct wl_output *wl_output, int32_t factor) { _trace2("output_scale[%p] wl_output[%p] factor=%d", data, wl_output, factor); #if 0 struct nukebar *bar = data; bar->scale = scale; if (output->state->run_display && output->width > 0 && output->height > 0) { render_frame(output); } #endif } static void output_geometry(void *data, struct wl_output *wl_output, int32_t x, int32_t y, int32_t width_mm, int32_t height_mm, int32_t subpixel, const char *make, const char *model, int32_t transform) { _trace2("output_geometry[%p] wl_output[%p] pos: %dx%d size(mm):%dx%d subpixel=%d, %s-%s-%s %d", data, wl_output, x, y, width_mm, height_mm, subpixel, make, model, transform); } struct wl_output_listener output_listener = { .geometry = output_geometry, .mode = output_mode, .done = output_done, .scale = output_scale, }; static void xdg_output_handle_logical_position(void *data, struct zxdg_output_v1 *xdg_output, int32_t x, int32_t y) { _trace2("xdg_output_local_position[%p] xdg_output[%p] pos: %dx%d", data, xdg_output, x, y); struct nukebar *bar = data; bar->x = x; bar->y = y; _debug("bar pos: %dx%d", x, y); } static void xdg_output_handle_logical_size(void *data, struct zxdg_output_v1 *xdg_output, int32_t width, int32_t height) { _trace2("xdg_output_local_size[%p] xdg_output[%p] size: %dx%d", data, xdg_output, width, height); struct nukebar *bar = data; // note(marius): we compute the width and height of the bar based on data from configuration bar->height = height; // bar->width = width; _debug("bar size: %dx%d", bar->width, bar->height); } static void destroy_layer_surface(struct nukebar *bar) { if (!bar->layer_surface) { return; } _trace2("destroy_layer_surface[%p] %p", bar); zwlr_layer_surface_v1_destroy(bar->layer_surface); wl_surface_attach(bar->surface, NULL, 0, 0); // detach buffer bar->layer_surface = NULL; bar->width = 0; //output->frame_scheduled = false; } static void layer_surface_closed(void *data, struct zwlr_layer_surface_v1 *surface) { struct nukebar *bar = data; destroy_layer_surface(bar); _trace2("layer_surface_closed[%p] %p", bar, surface); } static void set_output_dirty(struct nukebar* bar) { if (bar->surface) { //render(bar, 0); } } static void layer_surface_configure(void *data, struct zwlr_layer_surface_v1 *surface, uint32_t serial, uint32_t width, uint32_t height) { struct nukebar *bar = data; _trace2("layer_surface_configure[%p] layer_surface[%p] serial=%d w=%d h=%d", bar, surface, serial, width, height); bar->width = width; bar->height = height; zwlr_layer_surface_v1_ack_configure(surface, serial); set_output_dirty(bar); } struct zwlr_layer_surface_v1_listener layer_surface_listener = { .configure = layer_surface_configure, .closed = layer_surface_closed, }; static void add_layer_surface(struct nukebar *bar) { _trace("setting surface: %dx%d", bar->width, bar->height); bool overlay = true; enum zwlr_layer_shell_v1_layer layer = overlay ? ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY : ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM; bar->layer_surface = zwlr_layer_shell_v1_get_layer_surface(bar->layer_shell, bar->surface, bar->output, layer, "panel"); assert(bar->layer_surface); zwlr_layer_surface_v1_add_listener(bar->layer_surface, &layer_surface_listener, bar); if (overlay) { // Empty input region bar->input_region = wl_compositor_create_region(bar->compositor); assert(bar->input_region); wl_surface_set_input_region(bar->surface, bar->input_region); } zwlr_layer_surface_v1_set_anchor(bar->layer_surface, ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM); zwlr_layer_surface_v1_set_size(bar->layer_surface, bar->width, bar->height); zwlr_layer_surface_v1_set_margin(bar->layer_surface, 0, 0, 0, 0); if (overlay) { zwlr_layer_surface_v1_set_exclusive_zone(bar->layer_surface, -1); } wl_surface_commit(bar->surface); } static void xdg_output_handle_done(void *data, struct zxdg_output_v1 *xdg_output) { _trace2("xdg_output_done[%p] xdg_output[%p]", data, xdg_output); struct nukebar *bar = data; if (NULL == bar->surface) { bar->surface = wl_compositor_create_surface(bar->compositor); assert(bar->surface); } // Empty input region struct wl_region *input_region = wl_compositor_create_region(bar->compositor); assert(input_region); wl_surface_set_input_region(bar->surface, input_region); wl_region_destroy(input_region); add_layer_surface(bar); } static void xdg_output_handle_name(void *data, struct zxdg_output_v1 *xdg_output, const char *name) { _trace2("xdg_output_name[%p] xdg_output[%p] name=%s", data, xdg_output, name); } static void xdg_output_handle_description(void *data, struct zxdg_output_v1 *xdg_output, const char *description) { _trace2("xdg_output_description[%p] xdg_output[%p] description=%s", data, xdg_output, description); } struct zxdg_output_v1_listener xdg_output_listener = { .logical_position = xdg_output_handle_logical_position, .logical_size = xdg_output_handle_logical_size, .done = xdg_output_handle_done, .name = xdg_output_handle_name, .description = xdg_output_handle_description, }; static void add_xdg_output(struct nukebar *bar) { if (bar->xdg_output != NULL) { _trace2("skipping output"); return; } _trace("adding output"); bar->xdg_output = zxdg_output_manager_v1_get_xdg_output(bar->xdg_output_manager, bar->output); zxdg_output_v1_add_listener(bar->xdg_output, &xdg_output_listener, bar); } static void bar_xdg_wm_base_ping (void *data, struct xdg_wm_base *xdg_wm_base, uint32_t serial) { _trace2("xdg_wm_base pong"); xdg_wm_base_pong(xdg_wm_base, serial); } static void handle_global(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) { struct nukebar* bar = data; _trace2("%45s[%03d:%d]: bar[%p]", interface, name, version, data); if (bar->registry != registry) { _warn("different registry pointers: %p vs %p", bar->registry, registry); } version = (uint32_t)version; if (strcmp(interface, wl_compositor_interface.name) == 0) { bar->compositor = wl_registry_bind(registry, name, &wl_compositor_interface, 4); } else if (strcmp(interface, wl_seat_interface.name) == 0) { bar->seat = wl_registry_bind(registry, name, &wl_seat_interface, 3); wl_seat_add_listener(bar->seat, &seat_listener, bar); } else if (strcmp(interface, wl_output_interface.name) == 0) { // TODO(marius): this needs an array of outputs, because we should be able to draw the bar on // different ones. bar->output = wl_registry_bind(registry, name, &wl_output_interface, 1); wl_output_add_listener(bar->output, &output_listener, bar); if (bar->xdg_output_manager != NULL) { add_xdg_output(bar); } } else if (strcmp(interface, zwlr_layer_shell_v1_interface.name) == 0) { bar->layer_shell = wl_registry_bind(registry, name, &zwlr_layer_shell_v1_interface, 1); } else if (strcmp(interface, zxdg_output_manager_v1_interface.name) == 0) { bar->xdg_output_manager = wl_registry_bind(registry, name, &zxdg_output_manager_v1_interface, 2); } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { bar->xdg_wm_base = wl_registry_bind(registry, name, &xdg_wm_base_interface, 1); }else if (!strcmp(interface, wl_shm_interface.name)) { bar->wl_shm = wl_registry_bind (registry, name, &wl_shm_interface, 1); } } static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { _trace2("data pointer %p", data); struct nukebar *bar = data; registry = (void*)registry; if (bar->registry != registry) { _warn("registry pointers are different, %p vs %p", bar->registry, registry); } name = (uint32_t)name; #if 0 wl_list_for_each_safe(output, tmp, &bar->outputs, link) { if (output->wl_name == name) { swaybar_output_free(output); return; } } wl_list_for_each_safe(output, tmp, &bar->unused_outputs, link) { if (output->wl_name == name) { swaybar_output_free(output); return; } } struct swaybar_seat *seat, *tmp_seat; wl_list_for_each_safe(seat, tmp_seat, &bar->seats, link) { if (seat->wl_name == name) { swaybar_seat_free(seat); return; } } #endif } static const struct wl_registry_listener registry_listener = { .global = handle_global, .global_remove = handle_global_remove, }; #define DEFAULT_INIT_POS_X 300 #define DEFAULT_INIT_POS_Y 300 static void frame_handle_done(void *data, struct wl_callback *callback, uint32_t time) { _trace2("callback%p, time=%d", callback, time); time = time; wl_callback_destroy(callback); struct nukebar *bar = data; _trace2("redrawing.. "); #if 0 struct nk_color col_red = {0xFF,0x00,0x00,0xA0}; //r,g,b,a struct nk_color col_green = {0x00,0xFF,0x00,0xA0}; //r,g,b,a #endif wl_callback_destroy(bar->frame_callback); wl_surface_damage(bar->surface, 0, 0, bar->width, bar->height); bar->frame_callback = wl_surface_frame(bar->surface); wl_surface_attach(bar->surface, bar->front_buffer, 0, 0); wl_callback_add_listener(bar->frame_callback, &frame_listener, bar); if (!render(bar, time)) { _error("failed to render frame, stopping."); bar->stop = true; } wl_surface_commit(bar->surface); } static const struct wl_callback_listener frame_listener = { .done = frame_handle_done, }; static bool bar_init(struct nukebar* win) { const void *tex = {0}; win->font_tex.pixels = win->tex_scratch; win->font_tex.format = NK_FONT_ATLAS_ALPHA8; win->font_tex.w = win->font_tex.h = 0; if (0 == nk_init_default(&(win->ctx), 0)) { _error("unable to initialize nuklear"); return false; } _debug("initialized nuklear"); nk_font_atlas_init_default(&(win->atlas)); nk_font_atlas_begin(&(win->atlas)); tex = nk_font_atlas_bake(&(win->atlas), &(win->font_tex.w), &(win->font_tex.h), win->font_tex.format); if (!tex) { _error("unable to allocate font atlas"); return false; } switch(win->font_tex.format) { case NK_FONT_ATLAS_ALPHA8: win->font_tex.pitch = win->font_tex.w * 1; break; case NK_FONT_ATLAS_RGBA32: win->font_tex.pitch = win->font_tex.w * 4; break; }; /* Store the font texture in tex scratch memory */ memcpy(win->font_tex.pixels, tex, win->font_tex.pitch * win->font_tex.h); nk_font_atlas_end(&(win->atlas), nk_handle_ptr(NULL), NULL); if (win->atlas.default_font) nk_style_set_font(&(win->ctx), &(win->atlas.default_font->handle)); nk_style_load_all_cursors(&(win->ctx), win->atlas.cursors); bar_scissor(win, 0, 0, win->width, win->height); _trace2("initialized font"); return true; } bool wayland_init(struct nukebar *bar) { bar->width = DEFAULT_WIDTH_PX; bar->height = DEFAULT_HEIGHT_PX; bar->display = wl_display_connect(NULL); if (bar->display == NULL) { _error("no wayland display found, is a wayland composer running? \n"); return false; } bar->registry = wl_display_get_registry(bar->display); wl_registry_add_listener(bar->registry, &registry_listener, bar); wl_display_roundtrip(bar->display); wl_display_dispatch(bar->display); bar->surface = wl_compositor_create_surface(bar->compositor); if (bar->compositor == NULL || bar->layer_shell == NULL || bar->xdg_output_manager == NULL) { _error("Unable to connect to the compositor"); return false; } bar->xdg_surface = xdg_wm_base_get_xdg_surface(bar->xdg_wm_base, bar->surface); xdg_surface_add_listener(bar->xdg_surface, &xdg_surface_listener, bar); bar->xdg_toplevel = xdg_surface_get_toplevel(bar->xdg_surface); xdg_toplevel_add_listener(bar->xdg_toplevel, &xdg_toplevel_listener, bar); bar->frame_callback = wl_surface_frame(bar->surface); wl_surface_commit(bar->surface); size_t size = bar->width * bar->height * 4; char *xdg_runtime_dir = getenv ("XDG_RUNTIME_DIR"); int fd = open (xdg_runtime_dir, O_TMPFILE|O_RDWR|O_EXCL, 0600); ftruncate (fd, size); bar->data = mmap (NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); struct wl_shm_pool *pool = wl_shm_create_pool (bar->wl_shm, fd, size); bar->front_buffer = wl_shm_pool_create_buffer (pool, 0, bar->width, bar->height, bar->width*4, WL_SHM_FORMAT_XRGB8888); wl_shm_pool_destroy (pool); close (fd); wl_display_roundtrip(bar->display); //3. Clear window and start rendering loop bar_wayland_surf_clear(bar); wl_surface_set_buffer_scale(bar->surface, 1); wl_surface_attach (bar->surface, bar->front_buffer, 0, 0); wl_surface_damage_buffer(bar->surface, 0, 0, INT32_MAX, INT32_MAX); wl_surface_commit (bar->surface); //free(configs); return true; } void wayland_destroy(struct nukebar *bar) { nk_free(&(bar->ctx)); if (NULL != bar->xdg_toplevel) { xdg_toplevel_destroy(bar->xdg_toplevel); } if (NULL != bar->xdg_surface) { xdg_surface_destroy(bar->xdg_surface); } if (NULL != bar->surface) { wl_surface_destroy(bar->surface); } if (NULL != bar->compositor) { wl_compositor_destroy(bar->compositor); } if (NULL != bar->registry) { wl_registry_destroy(bar->registry); } if (NULL != bar->display) { wl_display_disconnect(bar->display); } _info("destroyed everything"); } #endif // NUKEBAR_WAYLAND_H
33.641618
201
0.740321
ce0693517bfb78656c8ab7e6af3e034b18b2c8c3
2,247
h
C
Encryptions/CAST256.h
kuma42/Kripto
86c3eb1b765e14b52d00b98890e13091658258f6
[ "MIT" ]
113
2015-04-26T16:48:54.000Z
2022-03-25T23:15:21.000Z
thirdparty/Encryptions/Encryptions/CAST256.h
Muller-Castro/Minesweeper
e4c3fb48e7181aff9637dc77cb829d16d293afdb
[ "Zlib", "MIT" ]
5
2019-01-24T02:46:15.000Z
2021-05-09T14:06:25.000Z
thirdparty/Encryptions/Encryptions/CAST256.h
Muller-Castro/Minesweeper
e4c3fb48e7181aff9637dc77cb829d16d293afdb
[ "Zlib", "MIT" ]
44
2015-12-17T02:29:19.000Z
2022-03-31T21:39:13.000Z
/* CAST256.h Copyright (c) 2013 - 2017 Jason Lee @ calccrypto at gmail.com 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. */ #ifndef __CAST256__ #define __CAST256__ #include <algorithm> #include <vector> #include "../common/cryptomath.h" #include "../common/includes.h" #include "SymAlg.h" #include "CAST_Const.h" class CAST256 : public SymAlg{ private: uint32_t A, B, C, D, a, b, c, d, e, f, g, h; std::vector <std::vector <uint8_t> > Kr, Tr; std::vector <std::vector <uint32_t> > Km, Tm; uint32_t F1(const uint32_t Data, const uint32_t Kmi, const uint8_t Kri); uint32_t F2(const uint32_t Data, const uint32_t Kmi, const uint8_t Kri); uint32_t F3(const uint32_t Data, const uint32_t Kmi, const uint8_t Kri); void W(const uint8_t i); std::vector <uint8_t> kr(); std::vector <uint32_t> km(); void Q(const uint8_t & i); void QBAR(const uint8_t & i); std::string run(const std::string & data); public: CAST256(); CAST256(const std::string & KEY); void setkey(std::string KEY); std::string encrypt(const std::string & DATA); std::string decrypt(const std::string & DATA); unsigned int blocksize() const; }; #endif
36.241935
80
0.70583
b43247eb4805f0afb86f3c25590c3c855f37c8db
14,383
c
C
tune/blas/gemv/MVNCASES/ATL_gemvN_v6x8_vsx.c
kevleyski/math-atlas
cc36aa7e0362c577739ac507378068882834825e
[ "BSD-3-Clause-Clear" ]
135
2015-01-08T20:35:35.000Z
2022-03-31T02:26:28.000Z
tune/blas/gemv/MVNCASES/ATL_gemvN_v6x8_vsx.c
kevleyski/math-atlas
cc36aa7e0362c577739ac507378068882834825e
[ "BSD-3-Clause-Clear" ]
25
2015-01-13T15:19:26.000Z
2021-06-05T20:00:27.000Z
tune/blas/gemv/MVNCASES/ATL_gemvN_v6x8_vsx.c
kevleyski/math-atlas
cc36aa7e0362c577739ac507378068882834825e
[ "BSD-3-Clause-Clear" ]
47
2015-01-27T06:22:57.000Z
2021-11-11T20:59:04.000Z
/* * (C) Copyright IBM Corporation 2010 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the ATLAS group or the names of its contributers may * not be used to endorse or promote products derived from this * software without specific 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 ATLAS GROUP OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef ATL_VSX #error "This routine requires VSX!" #endif #include <altivec.h> #include "atlas_misc.h" #define VEC_STEP (vec_step(vector TYPE)) /* GEMV with the following assumptions: * 1) alpha = 1 * 2) beta = 0 or 1 (controlled by BETA0/BETA1) * 3) incX = 1 and incY = 1 * 4) Column-major storage of A * * y = [0,1]*y + A*x, A is MxN, len(X) = N, len(Y) = M */ void ATL_UGEMV( const int M, const int N, const TYPE *A, const int lda, const TYPE *X, TYPE *Y) { long int i, j; #if defined BETA0 vector TYPE vzero = vec_splats( ((TYPE) 0.0) ); #endif long int mu = VEC_STEP*6; long int nu = 8; long int M1 = (M/mu)*mu; long int M2 = (M/VEC_STEP)*VEC_STEP; long int N1 = (N/nu)*nu; vector TYPE vy0, vy1, vy2, vy3, vy4, vy5; { TYPE *py0 = &Y[0]; for (i=0; i < M1; i+=mu) { #if defined BETA0 vy0 = vzero; vy1 = vzero; vy2 = vzero; vy3 = vzero; vy4 = vzero; vy5 = vzero; #else /* BETA1 */ vy0 = *((vector TYPE *)( py0+0*VEC_STEP )); vy1 = *((vector TYPE *)( py0+1*VEC_STEP )); vy2 = *((vector TYPE *)( py0+2*VEC_STEP )); vy3 = *((vector TYPE *)( py0+3*VEC_STEP )); vy4 = *((vector TYPE *)( py0+4*VEC_STEP )); vy5 = *((vector TYPE *)( py0+5*VEC_STEP )); #endif *((vector TYPE *)( py0+0*VEC_STEP )) = vy0; *((vector TYPE *)( py0+1*VEC_STEP )) = vy1; *((vector TYPE *)( py0+2*VEC_STEP )) = vy2; *((vector TYPE *)( py0+3*VEC_STEP )) = vy3; *((vector TYPE *)( py0+4*VEC_STEP )) = vy4; *((vector TYPE *)( py0+5*VEC_STEP )) = vy5; py0 += mu; } for (i=M1; i < M2; i+=VEC_STEP) { #if defined BETA0 vy0 = vzero; #else /* BETA1 */ vy0 = *((vector TYPE *)( py0 )); #endif *((vector TYPE *)( py0 )) = vy0; py0 += VEC_STEP; } for (i=M2; i < M; i++) { register TYPE y0; #if defined BETA0 y0 = 0.0; #else /* BETA1 */ y0 = *py0; #endif *py0 = y0; py0 += 1; } } TYPE *px = (TYPE *)X; for (j=0; j < N1; j+=nu) { TYPE *pa0 = (TYPE*)&A[(j+0)*lda]; TYPE *pa1 = (TYPE*)&A[(j+1)*lda]; TYPE *pa2 = (TYPE*)&A[(j+2)*lda]; TYPE *pa3 = (TYPE*)&A[(j+3)*lda]; TYPE *pa4 = (TYPE*)&A[(j+4)*lda]; TYPE *pa5 = (TYPE*)&A[(j+5)*lda]; TYPE *pa6 = (TYPE*)&A[(j+6)*lda]; TYPE *pa7 = (TYPE*)&A[(j+7)*lda]; vector TYPE vx0, vx1, vx2, vx3, vx4, vx5, vx6, vx7; vx0 = vec_splats( *((TYPE*)(px+0)) ); vx1 = vec_splats( *((TYPE*)(px+1)) ); vx2 = vec_splats( *((TYPE*)(px+2)) ); vx3 = vec_splats( *((TYPE*)(px+3)) ); vx4 = vec_splats( *((TYPE*)(px+4)) ); vx5 = vec_splats( *((TYPE*)(px+5)) ); vx6 = vec_splats( *((TYPE*)(px+6)) ); vx7 = vec_splats( *((TYPE*)(px+7)) ); px += nu; TYPE *py0 = &Y[0]; vector TYPE va00, va01, va02, va03, va04, va05; vector TYPE va10, va11, va12, va13, va14, va15; vector TYPE va20, va21, va22, va23, va24, va25; vector TYPE va30, va31, va32, va33, va34, va35; vector TYPE va40, va41, va42, va43, va44, va45; vector TYPE va50, va51, va52, va53, va54, va55; vector TYPE va60, va61, va62, va63, va64, va65; vector TYPE va70, va71, va72, va73, va74, va75; for (i=0; i < M1; i+=mu) { vy0 = *((vector TYPE *)( py0+0*VEC_STEP )); vy1 = *((vector TYPE *)( py0+1*VEC_STEP )); vy2 = *((vector TYPE *)( py0+2*VEC_STEP )); vy3 = *((vector TYPE *)( py0+3*VEC_STEP )); vy4 = *((vector TYPE *)( py0+4*VEC_STEP )); vy5 = *((vector TYPE *)( py0+5*VEC_STEP )); va00 = *((vector TYPE *)( pa0+0*VEC_STEP )); va01 = *((vector TYPE *)( pa0+1*VEC_STEP )); va02 = *((vector TYPE *)( pa0+2*VEC_STEP )); va03 = *((vector TYPE *)( pa0+3*VEC_STEP )); va04 = *((vector TYPE *)( pa0+4*VEC_STEP )); va05 = *((vector TYPE *)( pa0+5*VEC_STEP )); pa0 += mu; vy0 = vec_madd(va00, vx0, vy0); vy1 = vec_madd(va01, vx0, vy1); vy2 = vec_madd(va02, vx0, vy2); vy3 = vec_madd(va03, vx0, vy3); vy4 = vec_madd(va04, vx0, vy4); vy5 = vec_madd(va05, vx0, vy5); va10 = *((vector TYPE *)( pa1+0*VEC_STEP )); va11 = *((vector TYPE *)( pa1+1*VEC_STEP )); va12 = *((vector TYPE *)( pa1+2*VEC_STEP )); va13 = *((vector TYPE *)( pa1+3*VEC_STEP )); va14 = *((vector TYPE *)( pa1+4*VEC_STEP )); va15 = *((vector TYPE *)( pa1+5*VEC_STEP )); pa1 += mu; vy0 = vec_madd(va10, vx1, vy0); vy1 = vec_madd(va11, vx1, vy1); vy2 = vec_madd(va12, vx1, vy2); vy3 = vec_madd(va13, vx1, vy3); vy4 = vec_madd(va14, vx1, vy4); vy5 = vec_madd(va15, vx1, vy5); va20 = *((vector TYPE *)( pa2+0*VEC_STEP )); va21 = *((vector TYPE *)( pa2+1*VEC_STEP )); va22 = *((vector TYPE *)( pa2+2*VEC_STEP )); va23 = *((vector TYPE *)( pa2+3*VEC_STEP )); va24 = *((vector TYPE *)( pa2+4*VEC_STEP )); va25 = *((vector TYPE *)( pa2+5*VEC_STEP )); pa2 += mu; vy0 = vec_madd(va20, vx2, vy0); vy1 = vec_madd(va21, vx2, vy1); vy2 = vec_madd(va22, vx2, vy2); vy3 = vec_madd(va23, vx2, vy3); vy4 = vec_madd(va24, vx2, vy4); vy5 = vec_madd(va25, vx2, vy5); va30 = *((vector TYPE *)( pa3+0*VEC_STEP )); va31 = *((vector TYPE *)( pa3+1*VEC_STEP )); va32 = *((vector TYPE *)( pa3+2*VEC_STEP )); va33 = *((vector TYPE *)( pa3+3*VEC_STEP )); va34 = *((vector TYPE *)( pa3+4*VEC_STEP )); va35 = *((vector TYPE *)( pa3+5*VEC_STEP )); pa3 += mu; vy0 = vec_madd(va30, vx3, vy0); vy1 = vec_madd(va31, vx3, vy1); vy2 = vec_madd(va32, vx3, vy2); vy3 = vec_madd(va33, vx3, vy3); vy4 = vec_madd(va34, vx3, vy4); vy5 = vec_madd(va35, vx3, vy5); va40 = *((vector TYPE *)( pa4+0*VEC_STEP )); va41 = *((vector TYPE *)( pa4+1*VEC_STEP )); va42 = *((vector TYPE *)( pa4+2*VEC_STEP )); va43 = *((vector TYPE *)( pa4+3*VEC_STEP )); va44 = *((vector TYPE *)( pa4+4*VEC_STEP )); va45 = *((vector TYPE *)( pa4+5*VEC_STEP )); pa4 += mu; vy0 = vec_madd(va40, vx4, vy0); vy1 = vec_madd(va41, vx4, vy1); vy2 = vec_madd(va42, vx4, vy2); vy3 = vec_madd(va43, vx4, vy3); vy4 = vec_madd(va44, vx4, vy4); vy5 = vec_madd(va45, vx4, vy5); va50 = *((vector TYPE *)( pa5+0*VEC_STEP )); va51 = *((vector TYPE *)( pa5+1*VEC_STEP )); va52 = *((vector TYPE *)( pa5+2*VEC_STEP )); va53 = *((vector TYPE *)( pa5+3*VEC_STEP )); va54 = *((vector TYPE *)( pa5+4*VEC_STEP )); va55 = *((vector TYPE *)( pa5+5*VEC_STEP )); pa5 += mu; vy0 = vec_madd(va50, vx5, vy0); vy1 = vec_madd(va51, vx5, vy1); vy2 = vec_madd(va52, vx5, vy2); vy3 = vec_madd(va53, vx5, vy3); vy4 = vec_madd(va54, vx5, vy4); vy5 = vec_madd(va55, vx5, vy5); va60 = *((vector TYPE *)( pa6+0*VEC_STEP )); va61 = *((vector TYPE *)( pa6+1*VEC_STEP )); va62 = *((vector TYPE *)( pa6+2*VEC_STEP )); va63 = *((vector TYPE *)( pa6+3*VEC_STEP )); va64 = *((vector TYPE *)( pa6+4*VEC_STEP )); va65 = *((vector TYPE *)( pa6+5*VEC_STEP )); pa6 += mu; vy0 = vec_madd(va60, vx6, vy0); vy1 = vec_madd(va61, vx6, vy1); vy2 = vec_madd(va62, vx6, vy2); vy3 = vec_madd(va63, vx6, vy3); vy4 = vec_madd(va64, vx6, vy4); vy5 = vec_madd(va65, vx6, vy5); va70 = *((vector TYPE *)( pa7+0*VEC_STEP )); va71 = *((vector TYPE *)( pa7+1*VEC_STEP )); va72 = *((vector TYPE *)( pa7+2*VEC_STEP )); va73 = *((vector TYPE *)( pa7+3*VEC_STEP )); va74 = *((vector TYPE *)( pa7+4*VEC_STEP )); va75 = *((vector TYPE *)( pa7+5*VEC_STEP )); pa7 += mu; vy0 = vec_madd(va70, vx7, vy0); vy1 = vec_madd(va71, vx7, vy1); vy2 = vec_madd(va72, vx7, vy2); vy3 = vec_madd(va73, vx7, vy3); vy4 = vec_madd(va74, vx7, vy4); vy5 = vec_madd(va75, vx7, vy5); *((vector TYPE *)( py0+0*VEC_STEP )) = vy0; *((vector TYPE *)( py0+1*VEC_STEP )) = vy1; *((vector TYPE *)( py0+2*VEC_STEP )) = vy2; *((vector TYPE *)( py0+3*VEC_STEP )) = vy3; *((vector TYPE *)( py0+4*VEC_STEP )) = vy4; *((vector TYPE *)( py0+5*VEC_STEP )) = vy5; py0 += mu; } for (i=M1; i < M2; i+=VEC_STEP) { vy0 = *((vector TYPE *)( py0 )); va00 = *((vector TYPE *)( pa0 )); va10 = *((vector TYPE *)( pa1 )); va20 = *((vector TYPE *)( pa2 )); va30 = *((vector TYPE *)( pa3 )); va40 = *((vector TYPE *)( pa4 )); va50 = *((vector TYPE *)( pa5 )); va60 = *((vector TYPE *)( pa6 )); va70 = *((vector TYPE *)( pa7 )); pa0 += VEC_STEP; pa1 += VEC_STEP; pa2 += VEC_STEP; pa3 += VEC_STEP; pa4 += VEC_STEP; pa5 += VEC_STEP; pa6 += VEC_STEP; pa7 += VEC_STEP; vy0 = vec_madd(va00, vx0, vy0); vy0 = vec_madd(va10, vx1, vy0); vy0 = vec_madd(va20, vx2, vy0); vy0 = vec_madd(va30, vx3, vy0); vy0 = vec_madd(va40, vx4, vy0); vy0 = vec_madd(va50, vx5, vy0); vy0 = vec_madd(va60, vx6, vy0); vy0 = vec_madd(va70, vx7, vy0); *((vector TYPE *)( py0 )) = vy0; py0+=VEC_STEP; } for (i=M2; i < M; i++) { register TYPE y0; y0 = Y[i]; y0 += A[i+j*lda] * X[j]; y0 += A[i+(j+1)*lda] * X[j+1]; y0 += A[i+(j+2)*lda] * X[j+2]; y0 += A[i+(j+3)*lda] * X[j+3]; y0 += A[i+(j+4)*lda] * X[j+4]; y0 += A[i+(j+5)*lda] * X[j+5]; y0 += A[i+(j+6)*lda] * X[j+6]; y0 += A[i+(j+7)*lda] * X[j+7]; Y[i] = y0; } } for (j=N1; j < N; j++) { vector TYPE vx0; vx0 = vec_splats( *((TYPE*)(px)) ); px += 1; TYPE *py0 = &Y[0]; TYPE *pa0 = (TYPE*)&A[(j+0)*lda]; vector TYPE va00, va01, va02, va03, va04, va05; for (i=0; i < M1; i+=mu) { vy0 = *((vector TYPE *)( py0+0*VEC_STEP )); vy1 = *((vector TYPE *)( py0+1*VEC_STEP )); vy2 = *((vector TYPE *)( py0+2*VEC_STEP )); vy3 = *((vector TYPE *)( py0+3*VEC_STEP )); vy4 = *((vector TYPE *)( py0+4*VEC_STEP )); vy5 = *((vector TYPE *)( py0+5*VEC_STEP )); va00 = *((vector TYPE *)( pa0+0*VEC_STEP )); va01 = *((vector TYPE *)( pa0+1*VEC_STEP )); va02 = *((vector TYPE *)( pa0+2*VEC_STEP )); va03 = *((vector TYPE *)( pa0+3*VEC_STEP )); va04 = *((vector TYPE *)( pa0+4*VEC_STEP )); va05 = *((vector TYPE *)( pa0+5*VEC_STEP )); pa0 += mu; vy0 = vec_madd(va00, vx0, vy0); vy1 = vec_madd(va01, vx0, vy1); vy2 = vec_madd(va02, vx0, vy2); vy3 = vec_madd(va03, vx0, vy3); vy4 = vec_madd(va04, vx0, vy4); vy5 = vec_madd(va05, vx0, vy5); *((vector TYPE *)( py0+0*VEC_STEP )) = vy0; *((vector TYPE *)( py0+1*VEC_STEP )) = vy1; *((vector TYPE *)( py0+2*VEC_STEP )) = vy2; *((vector TYPE *)( py0+3*VEC_STEP )) = vy3; *((vector TYPE *)( py0+4*VEC_STEP )) = vy4; *((vector TYPE *)( py0+5*VEC_STEP )) = vy5; py0 += mu; } for (i=M1; i < M; i++) { register TYPE y0; y0 = Y[i]; y0 += A[i+j*lda] * X[j]; Y[i] = y0; } } }
35.426108
80
0.472502
f1f6b2f40c8e2e717239d0b91d9e25da48467be8
2,605
c
C
synchronize_game.c
AndreasMadsen/course-02616-game-of-life
f82c315644a2fac36f9ec25760ae5648529d7d61
[ "MIT" ]
null
null
null
synchronize_game.c
AndreasMadsen/course-02616-game-of-life
f82c315644a2fac36f9ec25760ae5648529d7d61
[ "MIT" ]
null
null
null
synchronize_game.c
AndreasMadsen/course-02616-game-of-life
f82c315644a2fac36f9ec25760ae5648529d7d61
[ "MIT" ]
null
null
null
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "initialize_game.h" #include "synchronize_game.h" static const int SEND_NORTH_TAG = 10; static const int SEND_NORTH_WEST_TAG = 11; static const int SEND_NORTH_EAST_TAG = 12; static const int SEND_SOUTH_TAG = 13; static const int SEND_SOUTH_WEST_TAG = 14; static const int SEND_SOUTH_EAST_TAG = 15; static const int SEND_EAST_TAG = 16; static const int SEND_WEST_TAG = 17; static inline void synchronize_direction( const GameInfo* const game, const struct TopologyDirection* const send, const struct TopologyDirection* const recv, MPI_Request* const restrict request_array, const int tag) { MPI_Isend(&game->current[send->send_offset], 1, send->send_type, send->rank, tag, game->communicator, &request_array[0]); MPI_Irecv(&game->current[recv->recv_offset], 1, recv->recv_type, recv->rank, tag, game->communicator, &request_array[1]); } void synchronize_game(const GameInfo* const game) { // north -> south synchronize_direction(game, &game->topology.north, &game->topology.south, &game->request[0], SEND_NORTH_TAG); // north west -> south east synchronize_direction(game, &game->topology.north_west, &game->topology.south_east, &game->request[2], SEND_NORTH_WEST_TAG); // north east -> south west synchronize_direction(game, &game->topology.north_east, &game->topology.south_west, &game->request[4], SEND_NORTH_EAST_TAG); // south -> north synchronize_direction(game, &game->topology.south, &game->topology.north, &game->request[6], SEND_SOUTH_TAG); // south west -> north east synchronize_direction(game, &game->topology.south_west, &game->topology.north_east, &game->request[8], SEND_SOUTH_WEST_TAG); // south east -> north west synchronize_direction(game, &game->topology.south_east, &game->topology.north_west, &game->request[10], SEND_SOUTH_EAST_TAG); // east -> west synchronize_direction(game, &game->topology.east, &game->topology.west, &game->request[12], SEND_EAST_TAG); // west -> east synchronize_direction(game, &game->topology.west, &game->topology.east, &game->request[14], SEND_WEST_TAG); MPI_Waitall(16, game->request, game->status); }
35.202703
79
0.629175