Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add solution for exercise 17.
/** Exercise 1.17 * Write a program to print all input lines that are longer than 80 characters. */ #include <stdio.h> #define MINLINE 80 main() { int i, buffer_printed; char buffer[MINLINE + 1]; char c; i = buffer_printed = 0; buffer[MINLINE] = '\0'; while ((c = getchar()) != EOF) { if (!buffer_printed) { buffer[i] = c; ++i; if (i > MINLINE) { printf("%s", buffer); buffer_printed = 1; } } else { putchar(c); } if (c == '\n') { i = 0; buffer_printed = 0; } } return 0; }
Update Clang to reflect the new home of IRBuilder.h as of r159421.
//===-- CGBuilder.h - Choose IRBuilder implementation ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_CODEGEN_CGBUILDER_H #define CLANG_CODEGEN_CGBUILDER_H #include "llvm/Support/IRBuilder.h" namespace clang { namespace CodeGen { // Don't preserve names on values in an optimized build. #ifdef NDEBUG typedef llvm::IRBuilder<false> CGBuilderTy; #else typedef llvm::IRBuilder<> CGBuilderTy; #endif } // end namespace CodeGen } // end namespace clang #endif
//===-- CGBuilder.h - Choose IRBuilder implementation ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef CLANG_CODEGEN_CGBUILDER_H #define CLANG_CODEGEN_CGBUILDER_H #include "llvm/IRBuilder.h" namespace clang { namespace CodeGen { // Don't preserve names on values in an optimized build. #ifdef NDEBUG typedef llvm::IRBuilder<false> CGBuilderTy; #else typedef llvm::IRBuilder<> CGBuilderTy; #endif } // end namespace CodeGen } // end namespace clang #endif
Add configure result checks on odbc, per Peter E.
/* File: connection.h * * Description: See "md.h" * * Comments: See "notice.txt" for copyright and license information. * */ #ifndef __MD5_H__ #define __MD5_H__ #include "psqlodbc.h" #include <stdlib.h> #include <string.h> #ifdef WIN32 #define MD5_ODBC #define FRONTEND #endif #define MD5_PASSWD_LEN 35 /* From c.h */ #ifndef __BEOS__ #ifndef __cplusplus #ifndef bool typedef char bool; #endif #ifndef true #define true ((bool) 1) #endif #ifndef false #define false ((bool) 0) #endif #endif /* not C++ */ #endif /* __BEOS__ */ /* #if SIZEOF_UINT8 == 0 Can't get this from configure */ typedef unsigned char uint8; /* == 8 bits */ typedef unsigned short uint16; /* == 16 bits */ typedef unsigned int uint32; /* == 32 bits */ /* #endif */ extern bool EncryptMD5(const char *passwd, const char *salt, size_t salt_len, char *buf); #endif
/* File: connection.h * * Description: See "md.h" * * Comments: See "notice.txt" for copyright and license information. * */ #ifndef __MD5_H__ #define __MD5_H__ #include "psqlodbc.h" #include <stdlib.h> #include <string.h> #ifdef WIN32 #define MD5_ODBC #define FRONTEND #endif #define MD5_PASSWD_LEN 35 /* From c.h */ #ifndef __BEOS__ #ifndef __cplusplus #ifndef bool typedef char bool; #endif #ifndef true #define true ((bool) 1) #endif #ifndef false #define false ((bool) 0) #endif #endif /* not C++ */ #endif /* __BEOS__ */ /* Also defined in include/c.h */ #if SIZEOF_UINT8 == 0 typedef unsigned char uint8; /* == 8 bits */ typedef unsigned short uint16; /* == 16 bits */ typedef unsigned int uint32; /* == 32 bits */ #endif /* SIZEOF_UINT8 == 0 */ extern bool EncryptMD5(const char *passwd, const char *salt, size_t salt_len, char *buf); #endif
Fix test (it was incorrectly succeeding).
// RUN: clang -emit-llvm < %s void* a(unsigned x) { return __builtin_return_address(0); } void* c(unsigned x) { return __builtin_frame_address(0); } // RUN: clang -emit-llvm < %s void* a(unsigned x) { return __builtin_return_address(0); } void* c(unsigned x) { return __builtin_frame_address(0); }
// RUN: clang -emit-llvm < %s | grep "llvm.returnaddress" // RUN: clang -emit-llvm < %s | grep "llvm.frameaddress" void* a(unsigned x) { return __builtin_return_address(0); } void* c(unsigned x) { return __builtin_frame_address(0); }
Implement internal representation of Color. This will help represent the component values of colors with respect to their colorspace
//****************************************************************************** // // Copyright (c) Microsoft. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //****************************************************************************** #pragma once #include <CoreGraphics/CGColor.h> struct __CGColorQuad { CGFloat r; CGFloat g; CGFloat b; CGFloat a; bool operator==(const __CGColorQuad& other) const { return (r == other.r) && (g == other.g) && (b == other.b) && (a == other.a); } void Clear() { r = g = b = a = 0.0f; } void SetColorComponents(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha) { r = red; g = green; b = blue; a = alpha; } };
Use triple /s replace double /s.
// // OCTClient+Issues.h // OctoKit // // Created by leichunfeng on 15/3/7. // Copyright (c) 2015年 GitHub. All rights reserved. // #import <OctoKit/OctoKit.h> @interface OCTClient (Issues) // Creates an issue. // // title - The title of the issue. This must not be nil. // body - The contents of the issue. This can be nil. // assignee - Login for the user that this issue should be assigned to. NOTE: // Only users with push access can set the assignee for new issues. // The assignee is silently dropped otherwise. This can be nil. // milestone - Milestone to associate this issue with. NOTE: Only users with // push access can set the milestone for new issues. The milestone // is silently dropped otherwise. This can be nil. // labels - Labels to associate with this issue. NOTE: Only users with push // access can set labels for new issues. Labels are silently dropped // otherwise. This can be nil. // repository - The repository in which to create the issue. This must not be nil. // // Returns a signal which will send the created `OCTIssue` then complete, or error. - (RACSignal *)createIssueWithTitle:(NSString *)title body:(NSString *)body assignee:(NSString *)assignee milestone:(NSUInteger)milestone labels:(NSArray *)labels inRepository:(OCTRepository *)repository; @end
// // OCTClient+Issues.h // OctoKit // // Created by leichunfeng on 15/3/7. // Copyright (c) 2015年 GitHub. All rights reserved. // #import <OctoKit/OctoKit.h> @interface OCTClient (Issues) /// Creates an issue. /// /// title - The title of the issue. This must not be nil. /// body - The contents of the issue. This can be nil. /// assignee - Login for the user that this issue should be assigned to. NOTE: /// Only users with push access can set the assignee for new issues. // The assignee is silently dropped otherwise. This can be nil. /// milestone - Milestone to associate this issue with. NOTE: Only users with /// push access can set the milestone for new issues. The milestone /// is silently dropped otherwise. This can be nil. /// labels - Labels to associate with this issue. NOTE: Only users with push /// access can set labels for new issues. Labels are silently dropped /// otherwise. This can be nil. /// repository - The repository in which to create the issue. This must not be nil. /// /// Returns a signal which will send the created `OCTIssue` then complete, or error. - (RACSignal *)createIssueWithTitle:(NSString *)title body:(NSString *)body assignee:(NSString *)assignee milestone:(NSUInteger)milestone labels:(NSArray *)labels inRepository:(OCTRepository *)repository; @end
UPDATE Door.h initialize standard values
#ifndef SSPAPPLICATION_ENTITIES_DOORENTITY_H #define SSPAPPLICATION_ENTITIES_DOORENTITY_H #include "Entity.h" class DoorEntity : public Entity { private: bool m_isOpened; float m_minRotation; float m_maxRotation; float m_rotateTime; float m_rotatePerSec; public: DoorEntity(); virtual ~DoorEntity(); int Initialize(int entityID, PhysicsComponent* pComp, GraphicsComponent* gComp, float minRotation, float maxRotation, float rotateTime); int Update(float dT, InputHandler* inputHandler); int React(int entityID, EVENT reactEvent); bool SetIsOpened(bool isOpened); bool GetIsOpened(); }; #endif
#ifndef SSPAPPLICATION_ENTITIES_DOORENTITY_H #define SSPAPPLICATION_ENTITIES_DOORENTITY_H #include "Entity.h" class DoorEntity : public Entity { private: bool m_isOpened; float m_minRotation; float m_maxRotation; float m_rotateTime; float m_rotatePerSec; public: DoorEntity(); virtual ~DoorEntity(); int Initialize(int entityID, PhysicsComponent* pComp, GraphicsComponent* gComp, float minRotation = 0.0f, float maxRotation = DirectX::XM_PI / 2, float rotateTime = 1.0f); int Update(float dT, InputHandler* inputHandler); int React(int entityID, EVENT reactEvent); bool SetIsOpened(bool isOpened); bool GetIsOpened(); }; #endif
Use the typedef read_function_t for readability
#ifndef LIBCWAP_H #define LIBCWAP_H #include <stddef.h> #include <inttypes.h> typedef uint32_t time_t; typedef size_t (*read_function_t)(char *, size_t); #define CWAP_TIME_REQUEST '\t' #define CWAP_TIME_SET 'T' #define CWAP_SET_ALARM_TIMESTAMP 'O' struct libcwap_functions { void (*time_request_function)(void); void (*time_set_function)(time_t); void (*alarm_set_timestamp)(uint8_t, time_t); // etc. }; void libcwap_action(size_t (*)(char *, size_t)); void libcwap_register(struct libcwap_functions *); #endif
#ifndef LIBCWAP_H #define LIBCWAP_H #include <stddef.h> #include <inttypes.h> typedef uint32_t time_t; typedef size_t (*read_function_t)(char *, size_t); #define CWAP_TIME_REQUEST '\t' #define CWAP_TIME_SET 'T' #define CWAP_SET_ALARM_TIMESTAMP 'O' struct libcwap_functions { void (*time_request_function)(void); void (*time_set_function)(time_t); void (*alarm_set_timestamp)(uint8_t, time_t); // etc. }; void libcwap_action(read_function_t); void libcwap_register(struct libcwap_functions *); #endif
Make a 32bit union for receiving data rather than shady casting
#include <stdlib.h> #include "libcwap.h" struct libcwap_functions * registered_functions = NULL; void libcwap_action(size_t (*read_function)(char *, size_t)) { char action; if (!read_function(&action, 1)) return; // Remember to increase the buffer if we want to receive larger packets. char data[4]; switch (action) { case 'T': if (!read_function(data, 4)) break; if (registered_functions->time_set_function != NULL) registered_functions->time_set_function(*(time_t *) data); // TODO verify these casts break; case 'O': if (!read_function(data, 4)) break; if (registered_functions->alarm_set_timestamp != NULL) registered_functions->alarm_set_timestamp(*(time_t *) data); break; // etc. default: ; // Assume the data was garbage. } } void libcwap_register(struct libcwap_functions * funs) { registered_functions = funs; }
#include <stdlib.h> #include "libcwap.h" struct libcwap_functions * registered_functions = NULL; typedef union { char chars[4]; uint32_t uinteger; int32_t integer; } data32_t; void libcwap_action(size_t (*read_function)(char *, size_t)) { char action; if (!read_function(&action, 1)) return; data32_t data32; switch (action) { case 'T': if (!read_function(data32.chars, 4)) break; if (registered_functions->time_set_function != NULL) registered_functions->time_set_function(data32.uinteger); // TODO verify these casts break; case 'O': if (!read_function(data32.chars, 4)) break; if (registered_functions->alarm_set_timestamp != NULL) registered_functions->alarm_set_timestamp(data32.uinteger); break; // etc. default: ; // Assume the data was garbage. } } void libcwap_register(struct libcwap_functions * funs) { registered_functions = funs; }
Update name of compiler-rt routine for setting filename
// Check that the -fprofile-instr-generate= form works. // RUN: %clang_cc1 -main-file-name c-generate.c %s -o - -emit-llvm -fprofile-instr-generate=c-generate-test.profraw | FileCheck %s // CHECK: private constant [24 x i8] c"c-generate-test.profraw\00" // CHECK: call void @__llvm_profile_set_filename_env_override(i8* getelementptr inbounds ([24 x i8], [24 x i8]* @0, i32 0, i32 0)) // CHECK: declare void @__llvm_profile_set_filename_env_override(i8*) int main(void) { return 0; }
// Check that the -fprofile-instr-generate= form works. // RUN: %clang_cc1 -main-file-name c-generate.c %s -o - -emit-llvm -fprofile-instr-generate=c-generate-test.profraw | FileCheck %s // CHECK: private constant [24 x i8] c"c-generate-test.profraw\00" // CHECK: call void @__llvm_profile_override_default_filename(i8* getelementptr inbounds ([24 x i8], [24 x i8]* @0, i32 0, i32 0)) // CHECK: declare void @__llvm_profile_override_default_filename(i8*) int main(void) { return 0; }
Simplify code to use get_at method with its get & create semantic
#include "../common.c" #include "m-dict.h" static inline bool oor_equal_p(unsigned int k, unsigned char n) { return k == (unsigned int)n; } static inline void oor_set(unsigned int *k, unsigned char n) { *k = (unsigned int)n; } DICT_OA_DEF2(dict_oa_uint, unsigned int, M_OPEXTEND(M_DEFAULT_OPLIST, OOR_EQUAL(oor_equal_p), OOR_SET(oor_set M_IPTR)), unsigned int, M_DEFAULT_OPLIST) void test_int(uint32_t n, uint32_t x0) { uint32_t i, x, z = 0; dict_oa_uint_t h; dict_oa_uint_init(h); for (i = 0, x = x0; i < n; ++i) { x = hash32(x); unsigned int key = get_key(n, x); unsigned int *ptr = dict_oa_uint_get(h, key); if (ptr) { (*ptr)++; z+= *ptr; } else { dict_oa_uint_set_at(h, key, 1); z+=1; } } fprintf(stderr, "# unique keys: %d; checksum: %u\n", (int) dict_oa_uint_size(h), z); dict_oa_uint_clear(h); }
#include "../common.c" #include "m-dict.h" static inline bool oor_equal_p(unsigned int k, unsigned char n) { return k == (unsigned int)n; } static inline void oor_set(unsigned int *k, unsigned char n) { *k = (unsigned int)n; } DICT_OA_DEF2(dict_oa_uint, unsigned int, M_OPEXTEND(M_DEFAULT_OPLIST, OOR_EQUAL(oor_equal_p), OOR_SET(oor_set M_IPTR)), unsigned int, M_DEFAULT_OPLIST) void test_int(uint32_t n, uint32_t x0) { uint32_t i, x, z = 0; dict_oa_uint_t h; dict_oa_uint_init(h); for (i = 0, x = x0; i < n; ++i) { x = hash32(x); unsigned int key = get_key(n, x); unsigned int *ptr = dict_oa_uint_get_at(h, key); (*ptr)++; z+= *ptr; } fprintf(stderr, "# unique keys: %d; checksum: %u\n", (int) dict_oa_uint_size(h), z); dict_oa_uint_clear(h); }
Fix file include bug (cocos Vector<T>)
#pragma once class StageInformation; class Collider; class Bullet; class Sling; class ColliderManager { public: ColliderManager() {} ~ColliderManager() {} void InitBullets(StageInformation* si); void ResetBullets(); Bullet* GetBulletToShot(Sling* sling); Vector<Collider*>& GetColliders(){ return colliders; } bool HasBullet(); void AddExplosion(Collider* explosion); void EraseCollider(Collider* collider); private: Vector<Collider*> colliders; int curBulletIndex; int defaultBulletNum; };
#pragma once #include "Collider.h" class StageInformation; class Bullet; class Sling; class ColliderManager { public: ColliderManager() {} ~ColliderManager() {} void InitBullets(StageInformation* si); void ResetBullets(); Bullet* GetBulletToShot(Sling* sling); Vector<Collider*>& GetColliders(){ return colliders; } bool HasBullet(); void AddExplosion(Collider* explosion); void EraseCollider(Collider* collider); private: Vector<Collider*> colliders; int curBulletIndex; int defaultBulletNum; };
Change on_key term event to on_key_press
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft_trm.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ncoden <ncoden@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/08 09:57:42 by ncoden #+# #+# */ /* Updated: 2015/05/11 18:53:58 by ncoden ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_TRM_H # define LIBFT_TRM_H # include <term.h> # include <termios.h> # include <curses.h> # include <sys/ioctl.h> # include <signal.h> typedef struct s_trm { struct termios *opts; t_ilst_evnt *on_key; t_evnt *on_resize; } t_trm; struct termios *ft_trmget(); t_bool ft_trmset(struct termios *trm); #endif
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft_trm.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ncoden <ncoden@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/08 09:57:42 by ncoden #+# #+# */ /* Updated: 2015/05/12 00:42:36 by ncoden ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_TRM_H # define LIBFT_TRM_H # include <term.h> # include <termios.h> # include <curses.h> # include <sys/ioctl.h> # include <signal.h> typedef struct s_trm { struct termios *opts; t_ilst_evnt *on_key_press; t_evnt *on_resize; } t_trm; struct termios *ft_trmget(); t_bool ft_trmset(struct termios *trm); #endif
Reorganize macros related to memory layout
#ifndef MEMLAYOUT_H #define MEMLAYOUT_H #include <stdint.h> #define KERNEL_START ((uint32_t)&kernel_start) #define KERNEL_END ((uint32_t)&kernel_end) #define KERNEL_SIZE (KERNEL_START - KERNEL_END) #define VIDEO_MEMORY_BEGIN 0xB8000 #define VIDEO_MEMORY_SIZE (80 * 24) #define VIRTUAL_TO_PHYSICAL(addr) ((uint32_t)(addr) - KERNEL_START) #define PHYSICAL_TO_VIRTUAL(addr) ((void *)(addr) + KERNEL_START) #endif
#ifndef MEMLAYOUT_H #define MEMLAYOUT_H #include <stdint.h> // These two variables are defined by the linker. They are located where you // would expect based on the names. extern uint32_t kernel_start; extern uint32_t kernel_end; #define KERNEL_END ((uint32_t)&kernel_end) #define KERNEL_START ((uint32_t)&kernel_start) #define KERNEL_END ((uint32_t)&kernel_end) #define KERNEL_SIZE (KERNEL_START - KERNEL_END) // Paging related #define PAGE_ALIGN(x) (((uintptr_t)(x)) & ~0xfff) #define NEXT_PAGE(x) (((uintptr_t)(x)+PAGE_SIZE) & ~0xfff) #define PAGE_DIRECTORY NEXT_PAGE(KERNEL_END) // Heap related #define KHEAP_PHYS_ROOT ((void*)0x100000) #define KHEAP_PHYS_END ((void*)NEXT_PAGE(KHEAP_PHYS_ROOT)) // Video memory related #define VIDEO_MEMORY_BEGIN 0xB8000 #define VIDEO_MEMORY_SIZE (80 * 24) #endif
Use stop_tone() if velocity set to 0
#ifndef F_CPU #define F_CPU F_OSC #endif #include <avr/io.h> #include <avr/interrupt.h> #include <ctype.h> #include <math.h> #include <stdint.h> #include <util/delay.h> #include "config.h" #include "nco.h" #include "uart.h" static void handle_midi(void); int main(void); __attribute__((optimize("unroll-loops"))) static void handle_midi(void) { uint8_t command; uint8_t channel; do { command = rx(); } while(!(command&0x80)); channel = command & 0x0F; command = (command >> 4) - 8; uint8_t p1, p2; if(channel != 0) { return; } switch(command) { case 0: p1 = rx(); p2 = rx(); stop_tone(p1, p2); break; case 1: p1 = rx(); p2 = rx(); start_tone(p1, p2); break; default: break; } } int main(void) { uart_init(38400); nco_init(); sei(); uint8_t i = 0; while(1) { handle_midi(); } return 0; }
#ifndef F_CPU #define F_CPU F_OSC #endif #include <avr/io.h> #include <avr/interrupt.h> #include <ctype.h> #include <math.h> #include <stdint.h> #include <util/delay.h> #include "config.h" #include "nco.h" #include "uart.h" static void handle_midi(void); int main(void); __attribute__((optimize("unroll-loops"))) static void handle_midi(void) { uint8_t command; uint8_t channel; do { command = rx(); } while(!(command&0x80)); channel = command & 0x0F; command = (command >> 4) - 8; uint8_t p1, p2; if(channel != 0) { return; } switch(command) { case 0: case 1: p1 = rx(); p2 = rx(); if(p2 != 0 && command != 0) { start_tone(p1, p2); } else { stop_tone(p1, p2); } break; default: break; } } int main(void) { uart_init(38400); nco_init(); sei(); uint8_t i = 0; while(1) { handle_midi(); } return 0; }
Fix itype int -> error.
/* -------------------------------------------------------------------------- * Name: walk.c * Purpose: Associative array implemented as a hash * ----------------------------------------------------------------------- */ #include <stdlib.h> #include "base/memento/memento.h" #include "base/errors.h" #include "datastruct/hash.h" #include "impl.h" error hash_walk(const hash_t *h, hash_walk_callback *cb, void *cbarg) { int i; for (i = 0; i < h->nbins; i++) { hash__node_t *n; hash__node_t *next; for (n = h->bins[i]; n != NULL; n = next) { int r; next = n->next; r = cb(&n->item, cbarg); if (r < 0) return r; } } return error_OK; }
/* -------------------------------------------------------------------------- * Name: walk.c * Purpose: Associative array implemented as a hash * ----------------------------------------------------------------------- */ #include <stdlib.h> #include "base/memento/memento.h" #include "base/errors.h" #include "datastruct/hash.h" #include "impl.h" error hash_walk(const hash_t *h, hash_walk_callback *cb, void *cbarg) { int i; for (i = 0; i < h->nbins; i++) { hash__node_t *n; hash__node_t *next; for (n = h->bins[i]; n != NULL; n = next) { error r; next = n->next; r = cb(&n->item, cbarg); if (r < 0) return r; } } return error_OK; }
Add test case checking that memcpy into an array invalidates it.
// Test case taken from sqlite3.c #include <string.h> typedef unsigned long u64; # define EXP754 (((u64)0x7ff)<<52) # define MAN754 ((((u64)1)<<52)-1) # define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0) static int sqlite3IsNaN(double x){ int rc; /* The value return */ u64 y; memcpy(&y,&x,sizeof(y)); // Goblint used to crash here rc = IsNaN(y); return rc; } int foo(){ int x = 23; int y; memcpy(&y, &x, sizeof(int)); __goblint_check(y == 23); return 0; } int main(){ sqlite3IsNaN(23.0); foo(); return 0; }
// Test case taken from sqlite3.c #include <string.h> typedef unsigned long u64; # define EXP754 (((u64)0x7ff)<<52) # define MAN754 ((((u64)1)<<52)-1) # define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0) static int sqlite3IsNaN(double x){ int rc; /* The value return */ u64 y; memcpy(&y,&x,sizeof(y)); // Goblint used to crash here rc = IsNaN(y); return rc; } int foo(){ int x = 23; int y; memcpy(&y, &x, sizeof(int)); __goblint_check(y == 23); return 0; } int bar(){ int arr[10]; double y; for(int i = 0; i < 10; i++){ arr[i] = 0; } __goblint_check(arr[0] == 0); __goblint_check(arr[3] == 0); memcpy(&arr, &y, sizeof(double)); __goblint_check(arr[0] == 0); //UNKNOWN! __goblint_check(arr[3] == 0); //UNKNOWN return 0; } int main(){ sqlite3IsNaN(23.0); foo(); bar(); return 0; }
Add escape sequences to make characters italic or bold
#include "stdio.h" __attribute__((constructor)) static void PrintReference() { printf(" ----------------------------------------------------------------------------\n" "| Welcome to ROBAST https://robast.github.io/ |\n" "| |\n" "| Please cite the following paper when you publish your ROBAST simulation. |\n" "| |\n" "| Akira Okumura, Koji Noda, Cameron Rulten (2016) |\n" "| \"ROBAST: Development of a ROOT-Based Ray-Tracing Library for Cosmic-Ray |\n" "| Telescopes and its Applications in the Cherenkov Telescope Array\" |\n" "| Astroparticle Physics 76 38-47 |\n" "| |\n" "| For support & FAQ, please visit https://robast.github.io/support.html |\n" "| |\n" "| ROBAST is developed by Akira Okumura (oxon@mac.com) |\n" " ----------------------------------------------------------------------------\n"); }
#include "stdio.h" __attribute__((constructor)) static void PrintReference() { printf(" ----------------------------------------------------------------------------\n" "| Welcome to ROBAST https://robast.github.io/ |\n" "| |\n" "| Please cite the following paper when you publish your ROBAST simulation. |\n" "| |\n" "| Akira Okumura, Koji Noda, Cameron Rulten (2016) |\n" "| \"ROBAST: Development of a ROOT-Based Ray-Tracing Library for Cosmic-Ray |\n" "| Telescopes and its Applications in the Cherenkov Telescope Array\" |\n" "| \e[3mAstroparticle Physics\e[0m \e[1m76\e[0m 38-47 |\n" "| |\n" "| For support & FAQ, please visit https://robast.github.io/support.html |\n" "| |\n" "| ROBAST is developed by Akira Okumura (oxon@mac.com) |\n" " ----------------------------------------------------------------------------\n"); }
Add missing file from previous commit
/* * libvirt-gconfig-domain-chardev-source-private.h: libvirt domain chardev configuration * * Copyright (C) 2013 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. * * Author: Daniel P. Berrange <berrange@redhat.com> */ #ifndef __LIBVIRT_GCONFIG_DOMAIN_CHARDEV_SOURCE_PRIVATE_H__ #define __LIBVIRT_GCONFIG_DOMAIN_CHARDEV_SOURCE_PRIVATE_H__ #include <libvirt-gconfig/libvirt-gconfig-xml-doc.h> G_BEGIN_DECLS GVirConfigDomainChardevSource * gvir_config_domain_chardev_source_new_from_tree(GVirConfigXmlDoc *doc, xmlNodePtr tree); GVirConfigDomainChardevSource * gvir_config_domain_chardev_source_pty_new_from_tree(GVirConfigXmlDoc *doc, xmlNodePtr tree); G_END_DECLS #endif /* __LIBVIRT_GCONFIG_DOMAIN_CHARDEV_SOURCE_PRIVATE_H__ */
Enable disabling warnings using pragmas only on MSVC++
#ifndef INICPP_DLL_H #define INICPP_DLL_H #ifdef INICPP_DLL #ifdef INICPP_EXPORT #define INICPP_API __declspec(dllexport) #else #define INICPP_API __declspec(dllimport) #endif #else #define INICPP_API #endif // Disable unwanted and not necessary MSVC++ warnings #pragma warning(disable:4800) #pragma warning(disable:4251) #endif // INICPP_DLL_H
#ifndef INICPP_DLL_H #define INICPP_DLL_H #ifdef INICPP_DLL #ifdef INICPP_EXPORT #define INICPP_API __declspec(dllexport) #else #define INICPP_API __declspec(dllimport) #endif #else #define INICPP_API #endif // Disable unwanted and not necessary MSVC++ warnings #ifdef _MSC_VER #pragma warning(disable:4800) #pragma warning(disable:4251) #endif #endif // INICPP_DLL_H
Disable canonical mode in terminal
#include <stdlib.h> #include <termios.h> #include <unistd.h> struct termios orig_termios; void disableRawMode() { tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); } void enableRawMode() { tcgetattr(STDIN_FILENO, &orig_termios); atexit(disableRawMode); struct termios raw = orig_termios; raw.c_lflag &= ~(ECHO); tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); } int main() { enableRawMode(); char c; while (read(STDIN_FILENO, &c, 1) == 1 && c!= 'q'); return 0; }
#include <stdlib.h> #include <termios.h> #include <unistd.h> struct termios orig_termios; void disableRawMode() { tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); } void enableRawMode() { tcgetattr(STDIN_FILENO, &orig_termios); atexit(disableRawMode); struct termios raw = orig_termios; raw.c_lflag &= ~(ECHO | ICANON); tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); } int main() { enableRawMode(); char c; while (read(STDIN_FILENO, &c, 1) == 1 && c!= 'q'); return 0; }
Add payload field to IPv4 header
#ifndef IPV4_H #define IPV4_H #include "syshead.h" #include "netdev.h" #define IPV4 0x04 #define ICMPV4 0x01 struct iphdr { uint8_t ihl : 4; /* TODO: Support Big Endian hosts */ uint8_t version : 4; uint8_t tos; uint16_t len; uint16_t id; uint16_t flags : 3; uint16_t frag_offset : 13; uint8_t ttl; uint8_t proto; uint16_t csum; uint32_t saddr; uint32_t daddr; } __attribute__((packed)); void ipv4_incoming(struct netdev *netdev, struct eth_hdr *hdr); #endif
#ifndef IPV4_H #define IPV4_H #include "syshead.h" #include "netdev.h" #define IPV4 0x04 #define ICMPV4 0x01 struct iphdr { uint8_t ihl : 4; /* TODO: Support Big Endian hosts */ uint8_t version : 4; uint8_t tos; uint16_t len; uint16_t id; uint16_t flags : 3; uint16_t frag_offset : 13; uint8_t ttl; uint8_t proto; uint16_t csum; uint32_t saddr; uint32_t daddr; uint8_t data[]; } __attribute__((packed)); void ipv4_incoming(struct netdev *netdev, struct eth_hdr *hdr); #endif
Use _exit() instead of exit() in child process
#include "../command.h" #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> pid_t cmd_execute(const char *path, const char *const argv[]) { pid_t pid = fork(); if (pid == -1) { perror("fork"); return -1; } if (pid == 0) { execvp(path, (char *const *)argv); perror("exec"); exit(1); } return pid; } SDL_bool cmd_terminate(pid_t pid) { return kill(pid, SIGTERM) != -1; } SDL_bool cmd_simple_wait(pid_t pid, int *exit_code) { int status; int code; if (waitpid(pid, &status, 0) == -1 || !WIFEXITED(status)) { // cannot wait, or exited unexpectedly, probably by a signal code = -1; } else { code = WEXITSTATUS(status); } if (exit_code) { *exit_code = code; } return !code; }
#include "../command.h" #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> pid_t cmd_execute(const char *path, const char *const argv[]) { pid_t pid = fork(); if (pid == -1) { perror("fork"); return -1; } if (pid == 0) { execvp(path, (char *const *)argv); perror("exec"); _exit(1); } return pid; } SDL_bool cmd_terminate(pid_t pid) { return kill(pid, SIGTERM) != -1; } SDL_bool cmd_simple_wait(pid_t pid, int *exit_code) { int status; int code; if (waitpid(pid, &status, 0) == -1 || !WIFEXITED(status)) { // cannot wait, or exited unexpectedly, probably by a signal code = -1; } else { code = WEXITSTATUS(status); } if (exit_code) { *exit_code = code; } return !code; }
Check for error when calling open()
#include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <unistd.h> #include "bmp.h" #define SIGNATURE_LENGTH 2 const char usage[] = "Usage: %s <filenname>\n"; int main(int argc, char *argv[]) { if (argc != 2) { printf(usage, argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); char buf[SIGNATURE_LENGTH]; ssize_t bytes = read(fd, buf, SIGNATURE_LENGTH); if (bytes == -1) { perror("error reading file"); return 1; } lseek(fd, 0, SEEK_SET); switch (buf[0] << 8 | buf[1]) { case BMP_SIGNATURE: return print_bmp(fd); default: puts("Error: unrecognized file format"); return 1; } }
#include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <unistd.h> #include "bmp.h" #define SIGNATURE_LENGTH 2 const char usage[] = "Usage: %s <filenname>\n"; int main(int argc, char *argv[]) { if (argc != 2) { printf(usage, argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); if (fd == -1) { perror("error opening file"); return 1; } char buf[SIGNATURE_LENGTH]; ssize_t bytes = read(fd, buf, SIGNATURE_LENGTH); if (bytes == -1) { perror("error reading file"); return 1; } lseek(fd, 0, SEEK_SET); switch (buf[0] << 8 | buf[1]) { case BMP_SIGNATURE: return print_bmp(fd); default: puts("Error: unrecognized file format"); return 1; } }
Add length as a parameter in command line.
#include <stdlib.h> #include <stdio.h> int main(int argc, char*argv[]) { int length = 8; for (int i = 0;i<length;i++) { for (int j = 0;j<=i;j++) { printf("*"); } printf("\n"); } return 0; }
/*Build: gcc -std=c99 -o xmas3 xmas3.c*/ #include <stdlib.h> #include <stdio.h> int main(int argc, char*argv[]) { if (argc != 2) { printf("USAGE: %s [length]\n", argv[0]); exit(-1); } int length = atoi(argv[1]); for (int i = 0;i<length;i++) { for (int j = 0;j<=i;j++) { printf("*"); } printf("\n"); } return 0; }
Add general tree optimizations for jumps and labels
#include "arch.h" #include "cc2.h" Node * optm(Node *np) { Node *dst; switch (np->op) { case OJMP: case OBRANCH: dst = np->u.sym->u.stmt; if (dst->op == OJMP) np->u.sym = dst->u.sym; break; } return np; }
#include <stddef.h> #include "arch.h" #include "cc2.h" Node * optm(Node *np) { Node *p, *dst, *next = np->next; Symbol *sym, *osym; switch (np->op) { case ONOP: if (next && next->op == ONOP) { sym = np->u.sym; osym = next->u.sym; osym->id = sym->id; osym->numid = sym->id; osym->u.stmt = sym->u.stmt; return NULL; } break; case OJMP: case OBRANCH: for (;;) { dst = np->u.sym->u.stmt; if (dst->op != OJMP) break; np->u.sym = dst->u.sym; } for (p = np->next; p; p = p->next) { if (p == dst) return NULL; if (p->op == ONOP || p->op == OBLOOP || p->op == OELOOP) { continue; } break; } break; } return np; }
Add simple function to test domain cpp:func
//! Function which takes two int arguments void f(int, int); //! Function which takes two double arguments void f(double, double); namespace test { //! Another function which takes two int arguments void g(int, int); //! Another function which takes two double arguments void g(double, double); } class MyType {}; class MyOtherType {}; //! Another function which takes a custom type void h(std::string, MyType); //! Another function which takes another custom type void h(std::string, MyOtherType); //! Another function which takes a basic type void h(std::string, int);
//! Non overloaded function void simplefunc(); //! Function which takes two int arguments void f(int, int); //! Function which takes two double arguments void f(double, double); namespace test { //! Another function which takes two int arguments void g(int, int); //! Another function which takes two double arguments void g(double, double); } class MyType {}; class MyOtherType {}; //! Another function which takes a custom type void h(std::string, MyType); //! Another function which takes another custom type void h(std::string, MyOtherType); //! Another function which takes a basic type void h(std::string, int);
Fix a compiler warning on FreeBSD
#include "sys/socket.h" #include "sys/uio.h" #define SIZE_OF_T(TYPE) \ do { \ if (0 == strcmp(type, #TYPE)) { \ return sizeof(TYPE); \ } \ } while (0) #define SIZE_OF_S(TYPE) \ do { \ if (0 == strcmp(type, #TYPE)) { \ return sizeof(struct TYPE); \ } \ } while (0) size_t size_of(const char* type) { // Builtin SIZE_OF_T(long); // sys/socket SIZE_OF_S(sockaddr_storage); // sys/uio SIZE_OF_S(iovec); return 0; }
#include <sys/socket.h> #include <sys/uio.h> #include <string.h> #define SIZE_OF_T(TYPE) \ do { \ if (0 == strcmp(type, #TYPE)) { \ return sizeof(TYPE); \ } \ } while (0) #define SIZE_OF_S(TYPE) \ do { \ if (0 == strcmp(type, #TYPE)) { \ return sizeof(struct TYPE); \ } \ } while (0) size_t size_of(const char* type) { // Builtin SIZE_OF_T(long); // sys/socket SIZE_OF_S(sockaddr_storage); // sys/uio SIZE_OF_S(iovec); return 0; }
Make RAM 128KB - big enough for any game
#pragma once #include <istream> #include <memory> #include <vector> #include "types.h" #include "mbc.h" class Cartridge { const static size_t max_rom_size = 0x400000; // 4 MB std::vector<u8> rom; std::vector<u8> ram; std::unique_ptr<MemoryBankController> mbc; public: Cartridge() : rom(max_rom_size), ram(0x2000), mbc(new MBC1(rom, ram)) {} void load_rom(std::istream& src) { src.read(reinterpret_cast<char *>(rom.data()), max_rom_size); } u8 get8(uint address) const { return mbc->get8(address); } void set8(uint address, u8 value) { mbc->set8(address, value); } };
#pragma once #include <istream> #include <memory> #include <vector> #include "types.h" #include "mbc.h" class Cartridge { const static size_t max_rom_size = 0x400000; // 4 MB std::vector<u8> rom; std::vector<u8> ram; std::unique_ptr<MemoryBankController> mbc; public: Cartridge() : rom(max_rom_size), ram(0x20000), mbc(new MBC1(rom, ram)) { } void load_rom(std::istream& src) { src.read(reinterpret_cast<char *>(rom.data()), max_rom_size); } u8 get8(uint address) const { return mbc->get8(address); } void set8(uint address, u8 value) { mbc->set8(address, value); } };
Add virtio 1.0 PCI ID to driver map
CHIPSET(0x0010, VIRTGL, VIRTGL)
CHIPSET(0x0010, VIRTGL, VIRTGL) CHIPSET(0x1050, VIRTGL, VIRTGL)
Update umbrella header with public interface
// // TangramMap.h // TangramMap // // Created by Matt Smollinger on 7/8/16. // // #import <UIKit/UIKit.h> /// Project version number for TangramMap. FOUNDATION_EXPORT double TangramMapVersionNumber; /// Project version string for TangramMap. FOUNDATION_EXPORT const unsigned char TangramMapVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <TangramMap/PublicHeader.h> #import <TangramMap/TGMapViewController.h>
// // TangramMap.h // TangramMap // // Created by Matt Smollinger on 7/8/16. // Updated by Karim Naaji on 2/28/17. // Copyright (c) 2017 Mapzen. All rights reserved. // #import <UIKit/UIKit.h> /// Project version number for TangramMap. FOUNDATION_EXPORT double TangramMapVersionNumber; /// Project version string for TangramMap. FOUNDATION_EXPORT const unsigned char TangramMapVersionString[]; #import <TangramMap/TGMapViewController.h> #import <TangramMap/TGMapData.h> #import <TangramMap/TGGeoPoint.h> #import <TangramMap/TGGeoPolygon.h> #import <TangramMap/TGGeoPolyline.h> #import <TangramMap/TGEaseType.h> #import <TangramMap/TGHttpHandler.h> #import <TangramMap/TGMarker.h> #import <TangramMap/TGMapData.h> #import <TangramMap/TGSceneUpdate.h> #import <TangramMap/TGMarkerPickResult.h> #import <TangramMap/TGLabelPickResult.h>
Add namespace and enum for signaling auto-disposing
/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #ifndef COMMON_TYPEDEFS_H #define COMMON_TYPEDEFS_H typedef unsigned char byte; typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; typedef unsigned int uint; typedef __int64 int64; typedef unsigned __int64 uint64; #endif
/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #ifndef COMMON_TYPEDEFS_H #define COMMON_TYPEDEFS_H typedef unsigned char byte; typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; typedef unsigned int uint; typedef __int64 int64; typedef unsigned __int64 uint64; namespace DisposeAfterUse { enum Flag { NO, YES }; } #endif
Set project_config back to defaults
// project-specific definitions for otaa sensor //#define CFG_eu868 1 //#define CFG_us915 1 //#define CFG_au921 1 #define CFG_as923 1 #define LMIC_COUNTRY_CODE LMIC_COUNTRY_CODE_JP //#define CFG_in866 1 #define CFG_sx1276_radio 1 //#define LMIC_USE_INTERRUPTS #define LMIC_DEBUG_LEVEL 2 #define LMIC_DEBUG_PRINTF_FN lmic_printf
// project-specific definitions for otaa sensor //#define CFG_eu868 1 #define CFG_us915 1 //#define CFG_au921 1 //#define CFG_as923 1 //#define CFG_in866 1 #define CFG_sx1276_radio 1 //#define LMIC_USE_INTERRUPTS
Add InAppMessage event to iOS
#if __has_include(<React/RCTBridgeModule.h>) #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> #import <React/RCTConvert.h> #import <React/RCTEventDispatcher.h> #import <React/RCTUtils.h> #elif __has_include("RCTBridgeModule.h") #import "RCTBridgeModule.h" #import "RCTEventEmitter.h" #import "RCTConvert.h" #import "RCTEventDispatcher.h" #import "RCTUtils.h" #endif typedef NS_ENUM(NSInteger, OSNotificationEventTypes) { NotificationReceived, NotificationOpened, IdsAvailable, EmailSubscriptionChanged }; #define OSNotificationEventTypesArray @[@"OneSignal-remoteNotificationReceived",@"OneSignal-remoteNotificationOpened",@"OneSignal-idsAvailable",@"OneSignal-emailSubscription"] #define OSEventString(enum) [OSNotificationEventTypesArray objectAtIndex:enum] @interface RCTOneSignalEventEmitter : RCTEventEmitter <RCTBridgeModule> + (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body; + (BOOL)hasSetBridge; @end
#if __has_include(<React/RCTBridgeModule.h>) #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> #import <React/RCTConvert.h> #import <React/RCTEventDispatcher.h> #import <React/RCTUtils.h> #elif __has_include("RCTBridgeModule.h") #import "RCTBridgeModule.h" #import "RCTEventEmitter.h" #import "RCTConvert.h" #import "RCTEventDispatcher.h" #import "RCTUtils.h" #endif typedef NS_ENUM(NSInteger, OSNotificationEventTypes) { NotificationReceived, NotificationOpened, IdsAvailable, EmailSubscriptionChanged, InAppMessageClicked }; #define OSNotificationEventTypesArray @[@"OneSignal-remoteNotificationReceived",@"OneSignal-remoteNotificationOpened",@"OneSignal-idsAvailable",@"OneSignal-emailSubscription",@"OneSignal-inAppMessageClicked"] #define OSEventString(enum) [OSNotificationEventTypesArray objectAtIndex:enum] @interface RCTOneSignalEventEmitter : RCTEventEmitter <RCTBridgeModule> + (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)body; + (BOOL)hasSetBridge; @end
Document the format of the TAQ file.
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef parse_taq_line_h #define parse_taq_line_h #include "taq.pb.h" #include <utility> namespace bigtable_api_samples { // Parse a line from a TAQ file and convert it to a quote. Quote parse_taq_line(int lineno, std::string const& line); } // namespace bigtable_api_samples #endif // parse_taq_line_h
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef parse_taq_line_h #define parse_taq_line_h #include "taq.pb.h" #include <utility> namespace bigtable_api_samples { // Parse a line from a TAQ file and convert it to a quote. // // TAQ files are delimiter (using '|' as the delimiter) separated text // files, using this format: // // timestamp|exchange|ticker|bid price|bid qty|offer price|offer qty|... // 093000123456789|K|GOOG|800.00|100|900.00|200|... // ... // END|20161024|78721395||||||||||||||||||||||||| // // The first line is a header, it defines the fields, each line // contains all the data for a quote, in this example we are only // interested in the first few fields, the last line is indicated by // the 'END' marker, it contains the date (timestamps are relative to // midnight on this date), and the total number of lines. Quote parse_taq_line(int lineno, std::string const& line); } // namespace bigtable_api_samples #endif // parse_taq_line_h
Add a tag (dummy) header file that will be updated whenever CINT's dictionaries need to be regenerated.
/*********************************************************************** * cint (C/C++ interpreter) ************************************************************************ * CINT header file cintdictversion.h ************************************************************************ * Description: * definition of the dictionary API version ************************************************************************ * Copyright(c) 1995~2008 Masaharu Goto (cint@pcroot.cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #ifndef INCLUDE_CINTDICTVERSION #define INCLUDE_CINTDICTVERSION #define G__CINTDICTVERSION 2008-01-21 #endif /* INCLUDE_CINTDICTVERSION */
Define WIN32 for MSVC compilers
/* Swephelp Copyright 2007-2014 Stanislas Marquis <smarquis@astrorigin.ch> Swephelp is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Swephelp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Swephelp. If not, see <http://www.gnu.org/licenses/>. */ /** @file swhwin.h ** @brief swephelp windowz specific header */ #ifndef SWHWIN_H #define SWHWIN_H #ifdef WIN32 #define lround(num) \ ((long)(num > 0 ? num + 0.5 : ceil(num - 0.5))) #endif /* WIN32 */ #endif /* SWHWIN_H */ /* vi: set fenc=utf8 ff=unix et sw=4 ts=4 sts=4 : */
/* Swephelp Copyright 2007-2014 Stanislas Marquis <smarquis@astrorigin.ch> Swephelp is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Swephelp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Swephelp. If not, see <http://www.gnu.org/licenses/>. */ /** @file swhwin.h ** @brief swephelp windowz specific header */ /* define WIN32 for MSVC compilers */ #ifdef _WIN32 #define WIN32 #endif #ifndef SWHWIN_H #define SWHWIN_H #ifdef WIN32 #define lround(num) \ ((long)(num > 0 ? num + 0.5 : ceil(num - 0.5))) #endif /* WIN32 */ #endif /* SWHWIN_H */ /* vi: set fenc=utf8 ff=unix et sw=4 ts=4 sts=4 : */
Use else in comparison chain
/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #ifndef VISTK_PROCESSES_HELPER_IMAGE_MACROS_H #define VISTK_PROCESSES_HELPER_IMAGE_MACROS_H #include <boost/cstdint.hpp> /** * \file macros.h * * \brief Macros to help manage templates. */ #define TYPE_CHECK(type, name, function) \ if (pixtype == pixtypes::pixtype_##name()) \ { \ return &function<type>; \ } #define SPECIFY_FUNCTION(function) \ TYPE_CHECK(bool, bool, function) \ TYPE_CHECK(uint8_t, byte, function) \ TYPE_CHECK(float, float, function) \ TYPE_CHECK(double, double, function) #endif // VISTK_PROCESSES_HELPER_IMAGE_MACROS_H
/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #ifndef VISTK_PROCESSES_HELPER_IMAGE_MACROS_H #define VISTK_PROCESSES_HELPER_IMAGE_MACROS_H #include <boost/cstdint.hpp> /** * \file macros.h * * \brief Macros to help manage templates. */ #define TYPE_CHECK(type, name, function) \ if (pixtype == pixtypes::pixtype_##name()) \ { \ return &function<type>; \ } #define SPECIFY_FUNCTION(function) \ TYPE_CHECK(bool, bool, function) \ else TYPE_CHECK(uint8_t, byte, function) \ else TYPE_CHECK(float, float, function) \ else TYPE_CHECK(double, double, function) #endif // VISTK_PROCESSES_HELPER_IMAGE_MACROS_H
Add function parameter qualifier type tests
// RUN: %ucc -fsyntax-only %s typedef int array[3]; const array yo; // int const yo[3]; // ^~ no const here h(array); // int h(int [3]); i(const array); // int i(int const [3]); // ^~ no const here j(int[const]); // int j(int *const); _Static_assert(_Generic(yo, const int[3]: 1) == 1, ""); _Static_assert(_Generic(&h, int (*)(int[3]): 1) == 1, ""); _Static_assert(_Generic(&h, int (*)(int const[3]): 1, default: 2) == 2, ""); _Static_assert(_Generic(&h, int (*)(int *const): 1) == 1, ""); _Static_assert(_Generic(&h, int (*)(int *): 1) == 1, ""); _Static_assert(_Generic(&i, int (*)(int const[3]): 1) == 1, ""); _Static_assert(_Generic(&i, int (*)(int [3]): 1, default: 2) == 2, ""); _Static_assert(_Generic(&i, int (*)(int const *): 1) == 1, ""); _Static_assert(_Generic(&i, int (*)(int const *const): 1) == 1, ""); _Static_assert(_Generic(&j, int (*)(int *const): 1) == 1, ""); _Static_assert(_Generic(&j, int (*)(int [const]): 1) == 1, ""); _Static_assert(_Generic(&j, int (*)(int const *const): 1, default: 2) == 2, ""); _Static_assert(_Generic(&j, int (*)(int const [const]): 1, default: 2) == 2, "");
Reduce the AsyncEvent struct size
#ifndef AL_EVENT_H #define AL_EVENT_H #include "AL/al.h" #include "AL/alc.h" struct EffectState; enum { /* End event thread processing. */ EventType_KillThread = 0, /* User event types. */ EventType_SourceStateChange = 1<<0, EventType_BufferCompleted = 1<<1, EventType_Error = 1<<2, EventType_Performance = 1<<3, EventType_Deprecated = 1<<4, EventType_Disconnected = 1<<5, /* Internal events. */ EventType_ReleaseEffectState = 65536, }; struct AsyncEvent { unsigned int EnumType{0u}; union { char dummy; struct { ALuint id; ALenum state; } srcstate; struct { ALuint id; ALsizei count; } bufcomp; struct { ALenum type; ALuint id; ALuint param; ALchar msg[1008]; } user; EffectState *mEffectState; } u{}; AsyncEvent() noexcept = default; constexpr AsyncEvent(unsigned int type) noexcept : EnumType{type} { } }; void StartEventThrd(ALCcontext *ctx); void StopEventThrd(ALCcontext *ctx); #endif
#ifndef AL_EVENT_H #define AL_EVENT_H #include "AL/al.h" #include "AL/alc.h" struct EffectState; enum { /* End event thread processing. */ EventType_KillThread = 0, /* User event types. */ EventType_SourceStateChange = 1<<0, EventType_BufferCompleted = 1<<1, EventType_Error = 1<<2, EventType_Performance = 1<<3, EventType_Deprecated = 1<<4, EventType_Disconnected = 1<<5, /* Internal events. */ EventType_ReleaseEffectState = 65536, }; struct AsyncEvent { unsigned int EnumType{0u}; union { char dummy; struct { ALuint id; ALenum state; } srcstate; struct { ALuint id; ALsizei count; } bufcomp; struct { ALenum type; ALuint id; ALuint param; ALchar msg[232]; } user; EffectState *mEffectState; } u{}; AsyncEvent() noexcept = default; constexpr AsyncEvent(unsigned int type) noexcept : EnumType{type} { } }; void StartEventThrd(ALCcontext *ctx); void StopEventThrd(ALCcontext *ctx); #endif
Disable error that forbids builds with gcc 4.2
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various compiler checks. */ #ifndef mozilla_Compiler_h_ #define mozilla_Compiler_h_ #if !defined(__clang__) && defined(__GNUC__) /* * This macro should simplify gcc version checking. For example, to check * for gcc 4.5.1 or later, check `#ifdef MOZ_GCC_VERSION_AT_LEAST(4, 5, 1)`. */ # define MOZ_GCC_VERSION_AT_LEAST(major, minor, patchlevel) \ ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ >= ((major) * 10000 + (minor) * 100 + (patchlevel))) #if !MOZ_GCC_VERSION_AT_LEAST(4, 4, 0) # error "mfbt (and Gecko) require at least gcc 4.4 to build." #endif #endif #endif /* mozilla_Compiler_h_ */
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Various compiler checks. */ #ifndef mozilla_Compiler_h_ #define mozilla_Compiler_h_ #if !defined(__clang__) && defined(__GNUC__) /* * This macro should simplify gcc version checking. For example, to check * for gcc 4.5.1 or later, check `#ifdef MOZ_GCC_VERSION_AT_LEAST(4, 5, 1)`. */ # define MOZ_GCC_VERSION_AT_LEAST(major, minor, patchlevel) \ ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ >= ((major) * 10000 + (minor) * 100 + (patchlevel))) #if !MOZ_GCC_VERSION_AT_LEAST(4, 4, 0) // RBA: Not true for servo! //# error "mfbt (and Gecko) require at least gcc 4.4 to build." #endif #endif #endif /* mozilla_Compiler_h_ */
Fix bug in TextInlineViews when using a deep nested hierarchy of Text and Images
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <limits> #include <react/components/text/BaseTextShadowNode.h> #include <react/components/text/TextProps.h> #include <react/components/view/ViewEventEmitter.h> #include <react/core/ConcreteShadowNode.h> namespace facebook { namespace react { extern const char TextComponentName[]; using TextEventEmitter = TouchEventEmitter; class TextShadowNode : public ConcreteShadowNode< TextComponentName, ShadowNode, TextProps, TextEventEmitter>, public BaseTextShadowNode { public: static ShadowNodeTraits BaseTraits() { auto traits = ConcreteShadowNode::BaseTraits(); #ifdef ANDROID traits.set(ShadowNodeTraits::Trait::FormsView); traits.set(ShadowNodeTraits::Trait::FormsStackingContext); #endif return traits; } using ConcreteShadowNode::ConcreteShadowNode; #ifdef ANDROID using BaseShadowNode = ConcreteShadowNode< TextComponentName, ShadowNode, TextProps, TextEventEmitter>; TextShadowNode( ShadowNodeFragment const &fragment, ShadowNodeFamily::Shared const &family, ShadowNodeTraits traits) : BaseShadowNode(fragment, family, traits), BaseTextShadowNode() { orderIndex_ = std::numeric_limits<decltype(orderIndex_)>::max(); } #endif }; } // namespace react } // namespace facebook
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <limits> #include <react/components/text/BaseTextShadowNode.h> #include <react/components/text/TextProps.h> #include <react/components/view/ViewEventEmitter.h> #include <react/core/ConcreteShadowNode.h> namespace facebook { namespace react { extern const char TextComponentName[]; using TextEventEmitter = TouchEventEmitter; class TextShadowNode : public ConcreteShadowNode< TextComponentName, ShadowNode, TextProps, TextEventEmitter>, public BaseTextShadowNode { public: static ShadowNodeTraits BaseTraits() { auto traits = ConcreteShadowNode::BaseTraits(); #ifdef ANDROID traits.set(ShadowNodeTraits::Trait::FormsView); #endif return traits; } using ConcreteShadowNode::ConcreteShadowNode; #ifdef ANDROID using BaseShadowNode = ConcreteShadowNode< TextComponentName, ShadowNode, TextProps, TextEventEmitter>; TextShadowNode( ShadowNodeFragment const &fragment, ShadowNodeFamily::Shared const &family, ShadowNodeTraits traits) : BaseShadowNode(fragment, family, traits), BaseTextShadowNode() { orderIndex_ = std::numeric_limits<decltype(orderIndex_)>::max(); } #endif }; } // namespace react } // namespace facebook
Add some color for console output
#ifndef KAI_PLATFORM_GAME_CONTROLLER_H #define KAI_PLATFORM_GAME_CONTROLLER_H #include KAI_PLATFORM_INCLUDE(GameController.h) #endif // SHATTER_PLATFORM_GAME_CONTROLLER_H //EOF
#ifndef KAI_PLATFORM_GAME_CONTROLLER_H #define KAI_PLATFORM_GAME_CONTROLLER_H #include KAI_PLATFORM_INCLUDE(GameController.h) #endif //EOF
Update instance variables, add getters
#pragma once #include <string> struct Version { public: const int major; const int minor; const int revision; Version(int major, int minor = 0, int revision = 0) : major(major), minor(minor), revision(revision) { } std::wstring ToString() { return std::to_wstring(major) + L"." + std::to_wstring(minor) + L"." + std::to_wstring(revision); } };
#pragma once #include <string> struct Version { public: Version(int major = 0, int minor = 0, int revision = 0) : _major(major), _minor(minor), _revision(revision) { } const int Major() { return _major; } const int Minor() { return _minor; } const int Revision() { return _revision; } } std::wstring ToString() { return std::to_wstring(_major) + L"." + std::to_wstring(_minor) + L"." + std::to_wstring(_revision); } private: int _major; int _minor; int _revision; };
Add empty test to prevent build system complaining.
/* Copyright (C) 2016 William Hart This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpz_mpoly.h" #include "ulong_extras.h" int main(void) { int i; FLINT_TEST_INIT(state); flint_printf("void...."); fflush(stdout); /* Check aliasing of a and c */ for (i = 0; i < 1000 * flint_test_multiplier(); i++) { } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
Add a test for llvm-gcc svn r104726.
// RUN: %llvmgcc %s -S -emit-llvm -o - | FileCheck %s // Radar 8026855 int test (void *src) { register int w0 asm ("0"); // CHECK: call i32 asm sideeffect asm ("ldr %0, [%1]": "=r" (w0): "r" (src)); // The asm to read the value of w0 has a sideeffect for a different reason // (see 2010-05-18-asmsched.c) but that's not what this is testing for. // CHECK: call i32 asm return w0; }
Correct *TST? callback in header file
#ifndef __SCPI_DEF_H_ #define __SCPI_DEF_H_ #include "scpi/scpi.h" extern scpi_t scpi_context; size_t SCPI_Write(scpi_t * context, const char * data, size_t len); int SCPI_Error(scpi_t * context, int_fast16_t err); scpi_result_t SCPI_Control(scpi_t * context, scpi_ctrl_name_t ctrl, scpi_reg_val_t val); scpi_result_t SCPI_Reset(scpi_t * context); scpi_result_t SCPI_Test(scpi_t * context); scpi_result_t SCPI_Flush(scpi_t * context); scpi_result_t SCPI_SystemCommTcpipControlQ(scpi_t * context); #endif // __SCPI_DEF_H_
#ifndef __SCPI_DEF_H_ #define __SCPI_DEF_H_ #include "scpi/scpi.h" extern scpi_t scpi_context; size_t SCPI_Write(scpi_t * context, const char * data, size_t len); int SCPI_Error(scpi_t * context, int_fast16_t err); scpi_result_t SCPI_Control(scpi_t * context, scpi_ctrl_name_t ctrl, scpi_reg_val_t val); scpi_result_t SCPI_Reset(scpi_t * context); int32_t SCPI_Test(scpi_t * context); scpi_result_t SCPI_Flush(scpi_t * context); scpi_result_t SCPI_SystemCommTcpipControlQ(scpi_t * context); #endif // __SCPI_DEF_H_
Use Lua for creating main window
#include <Arika/Arika.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { ARFuncs* arFuncs = ar_init("t2-output/macosx-clang-debug-default/libarika-qt.dylib"); if (!arFuncs) return 0; arFuncs->window_create_main(); for (;;) { if (!arFuncs->update()) break; } //arFuncs->close(); return 0; }
#include <Arika/Arika.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { ARFuncs* arFuncs = ar_init("t2-output/macosx-clang-debug-default/libarika-qt.dylib"); if (!arFuncs) return 0; if (!arFuncs->ui_load("examples/minimal/minimal.ar")) return 0; //arFuncs->window_create_main(); for (;;) { if (!arFuncs->update()) break; } //arFuncs->close(); return 0; }
Make TransactionData member vars private
/* * the continuation data assigned to each request along side with the functions * to manipulate them * * Vmon: June 2013 */ #ifndef BANJAX_CONTINUATION_H #define BANJAX_CONTINUATION_H #include "banjax.h" #include "banjax_filter.h" #include "transaction_muncher.h" class Banjax; class TransactionData{ public: std::shared_ptr<Banjax> banjax; TSHttpTxn txnp; TransactionMuncher transaction_muncher; FilterResponse response_info; ~TransactionData(); /** Constructor to set the default values */ TransactionData(std::shared_ptr<Banjax> banjax, TSHttpTxn cur_txn) : banjax(std::move(banjax)) , txnp(cur_txn) , transaction_muncher(cur_txn) { } static int handle_transaction_change(TSCont contp, TSEvent event, void *edata); private: void handle_request(); void handle_response(); void handle_http_close(Banjax::TaskQueue& current_queue); }; #endif /*banjax_continuation.h*/
/* * the continuation data assigned to each request along side with the functions * to manipulate them * * Vmon: June 2013 */ #ifndef BANJAX_CONTINUATION_H #define BANJAX_CONTINUATION_H #include "banjax.h" #include "banjax_filter.h" #include "transaction_muncher.h" class Banjax; class TransactionData{ public: /** Constructor to set the default values */ TransactionData(std::shared_ptr<Banjax> banjax, TSHttpTxn cur_txn) : banjax(std::move(banjax)) , txnp(cur_txn) , transaction_muncher(cur_txn) { } static int handle_transaction_change(TSCont contp, TSEvent event, void *edata); ~TransactionData(); private: std::shared_ptr<Banjax> banjax; TSHttpTxn txnp; TransactionMuncher transaction_muncher; FilterResponse response_info; private: void handle_request(); void handle_response(); void handle_http_close(Banjax::TaskQueue& current_queue); }; #endif /*banjax_continuation.h*/
Use the inline inverse sine function.
#include <math.h> #include <pal.h> static const float pi_2 = (float) M_PI / 2.f; /** * * Computes the inverse cosine (arc cosine) of the input vector 'a'. Input * values to acos must be in the range -1 to 1. The result values are in the * range 0 to pi. The function does not check for illegal input values. * * @param a Pointer to input vector * * @param c Pointer to output vector * * @param n Size of 'a' and 'c' vector. * * @return None * */ void p_acos_f32(const float *a, float *c, int n) { int i; float tmp; /* acos x = pi/2 - asin x */ p_asin_f32(a, c, n); for (i = 0; i < n; i++) { tmp = pi_2 - c[i]; c[i] = tmp; } }
#include <pal.h> #include "p_asin.h" /** * * Computes the inverse cosine (arc cosine) of the input vector 'a'. Input * values to acos must be in the range -1 to 1. The result values are in the * range 0 to pi. The function does not check for illegal input values. * * @param a Pointer to input vector * * @param c Pointer to output vector * * @param n Size of 'a' and 'c' vector. * * @return None * */ void p_acos_f32(const float *a, float *c, int n) { int i; /* acos x = pi/2 - asin x */ for (i = 0; i < n; i++) { c[i] = pi_2 - _p_asin(a[i]); } }
Add a simple untested example how to use the basics of the serial port class
/*- * Copyright (c) 2008 Benjamin Close <Benjamin.Close@clearchain.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** * This simple program will output hello world to the serial port * and read back a line of input from the port */ #include <stdio.h> #include <stdlib.h> #include <wcl/serial.h> #define DEVICE "/dev/ttyS0" #define BUFSIZE 4096 use namespace wcl; int main( int argc, char **args ) { // Create a serial object char buffer[BUFSIZE+1] = {0}; Serial s; // Open the serial port, checking that it opened if ( s.open( DEVICE, BAUD_115200, /* Use default for all other arguments */) == false ){ printf("Failed to open serial port\n"); exit(EXIT_FAILURE); } // Send hello world down the serial line if ( s.write( "Hello World!") == false ){ printf("Failed to write hello world\n"); exit(EXIT_FAILURE); } // Read back a line (about BUFSIZE characters from the port) if ( s.read( buffer, BUFSIZE )){ printf("Failed to read from device\n"); exit(EXIT_FAILURE); } printf("You got a message: %*s\n", buffer ) // Close the serial port and restore the previous state of the port s.close() return 0; }
Add inclusion of "syscall.aix32.h" or <syscall.h> depending on whether we are on an AIX machine where there is no <syscall.h>.
#ifndef _CONDOR_SYSCALLS_H #define _CONDOR_SYSCALLS_H typedef int BOOL; static const int SYS_LOCAL = 1; static const int SYS_REMOTE = 0; static const int SYS_RECORDED = 2; static const int SYS_MAPPED = 2; static const int SYS_UNRECORDED = 0; static const int SYS_UNMAPPED = 0; #if defined(__cplusplus) extern "C" { #endif int SetSyscalls( int mode ); BOOL LocalSysCalls(); BOOL RemoteSysCalls(); BOOL MappingFileDescriptors(); int REMOTE_syscall( int syscall_num, ... ); int syscall( int, ... ); #if defined(__cplusplus) } #endif #endif
#ifndef _CONDOR_SYSCALLS_H #define _CONDOR_SYSCALLS_H #if defined( AIX32) # include "syscall.aix32.h" #else # include <syscall.h> #endif typedef int BOOL; static const int SYS_LOCAL = 1; static const int SYS_REMOTE = 0; static const int SYS_RECORDED = 2; static const int SYS_MAPPED = 2; static const int SYS_UNRECORDED = 0; static const int SYS_UNMAPPED = 0; #if defined(__cplusplus) extern "C" { #endif int SetSyscalls( int mode ); BOOL LocalSysCalls(); BOOL RemoteSysCalls(); BOOL MappingFileDescriptors(); int REMOTE_syscall( int syscall_num, ... ); #if defined(AIX32) && defined(__cplusplus) int syscall( ... ); #else int syscall( int, ... ); #endif #if defined(__cplusplus) } #endif #endif
Remove unused flags field from request
#ifndef HTTP_H #define HTTP_H #include <stddef.h> #define HTTP_GET 1 #define HTTP_HEAD 2 #define HTTP_POST 3 #define HTTP_PUT 4 #define HTTP_DELETE 5 #define FIELD_HOST 1 #define FIELD_LENGTH 2 #define FIELD_TYPE 3 #define ERR_BAD_REQ 0 #define ERR_NOT_FOUND 1 #define ERR_METHOD 2 #define ERR_FORBIDDEN 3 #define ERR_INTERNAL 4 typedef struct { int method; /* request method */ char* path; /* requested path */ char* host; /* hostname field */ char* type; /* content-type */ size_t length; /* content-length */ int flags; } http_request; /* Write an error page (and header). Returns number of bytes written. */ size_t gen_error_page( int fd, int error ); /* Write 200 Ok header with content length and content type. Returns the number of bytes written, 0 on failure. */ size_t http_ok( int fd, const char* type, unsigned long size ); /* parse a HTTP request, returns non-zero on success, zero on failure */ int http_request_parse( char* buffer, http_request* request ); #endif /* HTTP_H */
#ifndef HTTP_H #define HTTP_H #include <stddef.h> #define HTTP_GET 1 #define HTTP_HEAD 2 #define HTTP_POST 3 #define HTTP_PUT 4 #define HTTP_DELETE 5 #define FIELD_HOST 1 #define FIELD_LENGTH 2 #define FIELD_TYPE 3 #define ERR_BAD_REQ 0 #define ERR_NOT_FOUND 1 #define ERR_METHOD 2 #define ERR_FORBIDDEN 3 #define ERR_INTERNAL 4 typedef struct { int method; /* request method */ char* path; /* requested path */ char* host; /* hostname field */ char* type; /* content-type */ size_t length; /* content-length */ } http_request; /* Write an error page (and header). Returns number of bytes written. */ size_t gen_error_page( int fd, int error ); /* Write 200 Ok header with content length and content type. Returns the number of bytes written, 0 on failure. */ size_t http_ok( int fd, const char* type, unsigned long size ); /* parse a HTTP request, returns non-zero on success, zero on failure */ int http_request_parse( char* buffer, http_request* request ); #endif /* HTTP_H */
Correct DIM service is DAQ_SOR_PHYSICS. In this case we get the trigger config from the logbook.
/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice * **************************************************************************/ #ifndef SORNOTIFIER_H #define SORNOTIFIER_H //______________________________________________________________________________ // // ECS Start-of-Run notifier // // This class "listens" to the SOR coming from the ECS. // // DIM #include <dic.hxx> class AliOnlineRecoTrigger; class SORNotifier: public DimUpdatedInfo { public: SORNotifier(AliOnlineRecoTrigger* trigger): DimUpdatedInfo("/LOGBOOK/SUBSCRIBE/ECS_SOR_PHYSICS", -1), fRun(-1), fTrigger(trigger) {} void infoHandler(); void errorHandler(int severity, int code, char *msg); int GetRun() const {return fRun;} private: SORNotifier(const SORNotifier& other); SORNotifier& operator = (const SORNotifier& other); int fRun; AliOnlineRecoTrigger* fTrigger; }; #endif
/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice * **************************************************************************/ #ifndef SORNOTIFIER_H #define SORNOTIFIER_H //______________________________________________________________________________ // // ECS Start-of-Run notifier // // This class "listens" to the SOR coming from the ECS. // // DIM #include <dic.hxx> class AliOnlineRecoTrigger; class SORNotifier: public DimUpdatedInfo { public: SORNotifier(AliOnlineRecoTrigger* trigger): DimUpdatedInfo("/LOGBOOK/SUBSCRIBE/DAQ_SOR_PHYSICS", -1), fRun(-1), fTrigger(trigger) {} void infoHandler(); void errorHandler(int severity, int code, char *msg); int GetRun() const {return fRun;} private: SORNotifier(const SORNotifier& other); SORNotifier& operator = (const SORNotifier& other); int fRun; AliOnlineRecoTrigger* fTrigger; }; #endif
Remove bogus NO_IRQ = -1 define
/* irq.h: FRV IRQ definitions * * Copyright (C) 2006 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _ASM_IRQ_H_ #define _ASM_IRQ_H_ /* this number is used when no interrupt has been assigned */ #define NO_IRQ (-1) #define NR_IRQS 48 #define IRQ_BASE_CPU (0 * 16) #define IRQ_BASE_FPGA (1 * 16) #define IRQ_BASE_MB93493 (2 * 16) /* probe returns a 32-bit IRQ mask:-/ */ #define MIN_PROBE_IRQ (NR_IRQS - 32) #ifndef __ASSEMBLY__ static inline int irq_canonicalize(int irq) { return irq; } #endif #endif /* _ASM_IRQ_H_ */
/* irq.h: FRV IRQ definitions * * Copyright (C) 2006 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _ASM_IRQ_H_ #define _ASM_IRQ_H_ #define NR_IRQS 48 #define IRQ_BASE_CPU (0 * 16) #define IRQ_BASE_FPGA (1 * 16) #define IRQ_BASE_MB93493 (2 * 16) /* probe returns a 32-bit IRQ mask:-/ */ #define MIN_PROBE_IRQ (NR_IRQS - 32) #ifndef __ASSEMBLY__ static inline int irq_canonicalize(int irq) { return irq; } #endif #endif /* _ASM_IRQ_H_ */
Add a link to an SO answer about platform detection
#include <stdio.h> #include <stdlib.h> /* I am intentionally not doing the Windows portability stuff here since I am doing this for the language-implementation aspect, rather than the portability aspect. If it turns out the portability stuff is a big deal, I will come back and add in that code. -MAW */ #include <editline/readline.h> int main(int argc, char **argv) { /* Print Version and Exit information */ puts("Lispy Version 0.0.0.0.1"); puts("Press Ctrl-C to exit\n"); while(1) { /* prompt: */ char *input = readline("lispy> "); /* add input to command history */ add_history(input); printf("No, you're a %s\n", input); /* input was dynamically allocated */ free(input); } return 0; }
#include <stdio.h> #include <stdlib.h> /* I am intentionally not doing the Windows portability stuff here since I am doing this for the language-implementation aspect, rather than the portability aspect. If it turns out the portability stuff is a big deal, I will come back and add in that code. -MAW */ /* Fun SO link on target platform detection: http://stackoverflow.com/a/5920028/3435397 */ #include <editline/readline.h> int main(int argc, char **argv) { /* Print Version and Exit information */ puts("Lispy Version 0.0.0.0.1"); puts("Press Ctrl-C to exit\n"); while(1) { /* prompt: */ char *input = readline("lispy> "); /* add input to command history */ add_history(input); printf("No, you're a %s\n", input); /* input was dynamically allocated */ free(input); } return 0; }
Fix a new Visual Studio unused variable build warning
/** * \file os_isfile.c * \brief Returns true if the given file exists on the file system. * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project */ #include <sys/stat.h> #include "premake.h" int os_isfile(lua_State* L) { const char* filename = luaL_checkstring(L, 1); lua_pushboolean(L, do_isfile(filename)); return 1; } int do_isfile(const char* filename) { struct stat buf; #if PLATFORM_WINDOWS DWORD attrib = GetFileAttributesA(filename); if (attrib != INVALID_FILE_ATTRIBUTES) { return (attrib & FILE_ATTRIBUTE_DIRECTORY) == 0; } #else if (stat(filename, &buf) == 0) { return ((buf.st_mode & S_IFDIR) == 0); } #endif return 0; }
/** * \file os_isfile.c * \brief Returns true if the given file exists on the file system. * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project */ #include <sys/stat.h> #include "premake.h" int os_isfile(lua_State* L) { const char* filename = luaL_checkstring(L, 1); lua_pushboolean(L, do_isfile(filename)); return 1; } int do_isfile(const char* filename) { #if PLATFORM_WINDOWS DWORD attrib = GetFileAttributesA(filename); if (attrib != INVALID_FILE_ATTRIBUTES) { return (attrib & FILE_ATTRIBUTE_DIRECTORY) == 0; } #else struct stat buf; if (stat(filename, &buf) == 0) { return ((buf.st_mode & S_IFDIR) == 0); } #endif return 0; }
Synchronize the mailbox after expunging messages to actually get them expunged.
/* Copyright (c) 2002-2008 Dovecot authors, see the included COPYING file */ #include "common.h" #include "commands.h" #include "imap-expunge.h" bool cmd_close(struct client_command_context *cmd) { struct client *client = cmd->client; struct mailbox *mailbox = client->mailbox; struct mail_storage *storage; if (!client_verify_open_mailbox(cmd)) return TRUE; storage = mailbox_get_storage(mailbox); client->mailbox = NULL; if (!imap_expunge(mailbox, NULL)) client_send_untagged_storage_error(client, storage); if (mailbox_close(&mailbox) < 0) client_send_untagged_storage_error(client, storage); client_update_mailbox_flags(client, NULL); client_send_tagline(cmd, "OK Close completed."); return TRUE; }
/* Copyright (c) 2002-2008 Dovecot authors, see the included COPYING file */ #include "common.h" #include "commands.h" #include "imap-expunge.h" bool cmd_close(struct client_command_context *cmd) { struct client *client = cmd->client; struct mailbox *mailbox = client->mailbox; struct mail_storage *storage; if (!client_verify_open_mailbox(cmd)) return TRUE; storage = mailbox_get_storage(mailbox); client->mailbox = NULL; if (!imap_expunge(mailbox, NULL)) client_send_untagged_storage_error(client, storage); else if (mailbox_sync(mailbox, 0, 0, NULL) < 0) client_send_untagged_storage_error(client, storage); if (mailbox_close(&mailbox) < 0) client_send_untagged_storage_error(client, storage); client_update_mailbox_flags(client, NULL); client_send_tagline(cmd, "OK Close completed."); return TRUE; }
Add some comments in the header file for understanding
#ifndef GPIOLIB_H #define GPIOLIB_H #define FORWARD 1 #define BACKWARD 0 namespace GPIO { int init(); int controlLeft(int direction,int speed); int controlRight(int direction,int speed); int stopLeft(); int stopRight(); int resetCounter(); void getCounter(int *countLeft,int *countRight); int turnTo(int angle); void delay(int milliseconds); } #endif
#ifndef GPIOLIB_H #define GPIOLIB_H #define FORWARD 1 #define BACKWARD 0 namespace GPIO { int init(); //direction is either FORWARD or BACKWARD. speed can be an integer ranging from 0 to 100. int controlLeft(int direction,int speed); int controlRight(int direction,int speed); int stopLeft(); int stopRight(); int resetCounter(); void getCounter(int *countLeft,int *countRight); //angle is available in the range of -90 to 90. int turnTo(int angle); void delay(int milliseconds); } #endif
Add a hash_combine function for mixing hash values.
/* * Utilities for working with hash values. * * Portions Copyright (c) 2017, PostgreSQL Global Development Group */ #ifndef HASHUTILS_H #define HASHUTILS_H /* * Combine two hash values, resulting in another hash value, with decent bit * mixing. * * Similar to boost's hash_combine(). */ static inline uint32 hash_combine(uint32 a, uint32 b) { a ^= b + 0x9e3779b9 + (a << 6) + (a >> 2); return a; } #endif /* HASHUTILS_H */
Fix obsolete cross-reference (this file isn't called alpha.c anymore)
/* Dummy file used for nothing at this point * * see alpha.h * $PostgreSQL: pgsql/src/backend/port/dynloader/osf.c,v 1.2 2006/03/11 04:38:31 momjian Exp $ */
/* * $PostgreSQL: pgsql/src/backend/port/dynloader/osf.c,v 1.3 2009/04/21 21:05:25 tgl Exp $ * * Dummy file used for nothing at this point * * see osf.h */
Make text in LabelState public.
#ifndef SRC_FORCES_LABEL_STATE_H_ #define SRC_FORCES_LABEL_STATE_H_ #include <Eigen/Core> #include <string> namespace Forces { /** * \brief * * */ class LabelState { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW LabelState(int id, std::string text, Eigen::Vector3f anchorPosition); const int id; const Eigen::Vector3f anchorPosition; Eigen::Vector3f labelPosition; Eigen::Vector2f anchorPosition2D; Eigen::Vector2f labelPosition2D; float labelPositionDepth; private: std::string text; }; } // namespace Forces #endif // SRC_FORCES_LABEL_STATE_H_
#ifndef SRC_FORCES_LABEL_STATE_H_ #define SRC_FORCES_LABEL_STATE_H_ #include <Eigen/Core> #include <string> namespace Forces { /** * \brief * * */ class LabelState { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW LabelState(int id, std::string text, Eigen::Vector3f anchorPosition); const int id; const Eigen::Vector3f anchorPosition; Eigen::Vector3f labelPosition; Eigen::Vector2f anchorPosition2D; Eigen::Vector2f labelPosition2D; float labelPositionDepth; const std::string text; }; } // namespace Forces #endif // SRC_FORCES_LABEL_STATE_H_
Use puts again in a better position, save one byte (143)
main(int u,char**a){for(char*c,y;y=u;u*=8)for(c=a[1];*c;)printf("%c%c%c%c",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32,*c?32:10);}
main(int u,char**a){for(char*c,y;y=u;u*=8,puts(""))for(c=a[1];*c;)printf("%c%c%c ",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32);}
Test class to check for ambiguities in the dictionary source code in case of non virtual diamonds
#ifndef DICT2_CLASSN_H #define DICT2_CLASSN_H #include "ClassI.h" #include "ClassL.h" class ClassN: /* public ClassI, */ public ClassL { public: ClassN() : fN('n') {} virtual ~ClassN() {} int n() { return fN; } void setN(int v) { fN = v; } private: int fN; }; #endif // DICT2_CLASSN_H
Add missing close for file descriptor
/* Exercise 5-3 */ #include <unistd.h> #include <fcntl.h> #include "tlpi_hdr.h" int main (int argc, char *argv[]) { if (argc < 3 || argc > 4) { usageErr("%s filename num-bytes [x]", argv[0]); } long n = getLong(argv[2], GN_NONNEG | GN_ANY_BASE, "num-bytes"); Boolean x = argc == 4 && strcmp(argv[3], "x") == 0; int flags = O_WRONLY | O_CREAT; if (!x) { flags |= O_APPEND; } int fd = open(argv[1], flags, S_IWUSR | S_IRUSR); if (fd == -1) { errExit("open"); } while (n-- > 0) { if (x) { if (lseek(fd, 0, SEEK_END) == -1) { errExit("seek"); } } if (write(fd, "a", 1) == -1) { errExit("write byte a"); } } }
/* Exercise 5-3 */ #include <unistd.h> #include <fcntl.h> #include "tlpi_hdr.h" int main (int argc, char *argv[]) { if (argc < 3 || argc > 4) { usageErr("%s filename num-bytes [x]", argv[0]); } long n = getLong(argv[2], GN_NONNEG | GN_ANY_BASE, "num-bytes"); Boolean x = argc == 4 && strcmp(argv[3], "x") == 0; int flags = O_WRONLY | O_CREAT; if (!x) { flags |= O_APPEND; } int fd = open(argv[1], flags, S_IWUSR | S_IRUSR); if (fd == -1) { errExit("open"); } while (n-- > 0) { if (x) { if (lseek(fd, 0, SEEK_END) == -1) { errExit("seek"); } } if (write(fd, "a", 1) == -1) { errExit("write byte a"); } } if (close(fd) == -1) { errExit("close output"); } exit(EXIT_SUCCESS); }
Add virtual destructor to class with virtual functions but non-virtual destructor
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #if FB_SONARKIT_ENABLED #pragma once #import <dispatch/dispatch.h> namespace facebook { namespace flipper { class DispatchQueue { public: virtual void async(dispatch_block_t block) = 0; }; class GCDQueue: public DispatchQueue { public: GCDQueue(dispatch_queue_t underlyingQueue) :_underlyingQueue(underlyingQueue) { } void async(dispatch_block_t block) override { dispatch_async(_underlyingQueue, block); } virtual ~GCDQueue() { } private: dispatch_queue_t _underlyingQueue; }; } } #endif
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #if FB_SONARKIT_ENABLED #pragma once #import <dispatch/dispatch.h> namespace facebook { namespace flipper { class DispatchQueue { public: virtual void async(dispatch_block_t block) = 0; virtual ~DispatchQueue() { } }; class GCDQueue: public DispatchQueue { public: GCDQueue(dispatch_queue_t underlyingQueue) :_underlyingQueue(underlyingQueue) { } void async(dispatch_block_t block) override { dispatch_async(_underlyingQueue, block); } virtual ~GCDQueue() { } private: dispatch_queue_t _underlyingQueue; }; } } #endif
Remove __UNUSED__ as it doesn't make sense here.
/* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_INT_CONFIG_MODULES_H #define E_INT_CONFIG_MODULES_H EAPI E_Config_Dialog *e_int_config_modules(E_Container *con, const char *params __UNUSED__); #endif #endif
/* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_INT_CONFIG_MODULES_H #define E_INT_CONFIG_MODULES_H EAPI E_Config_Dialog *e_int_config_modules(E_Container *con, const char *params); #endif #endif
Fix bug in ivory wrapper.
#include "freertos_task_wrapper.h" #include <FreeRTOS.h> #include <task.h> void ivory_freertos_task_create(void (*tsk)(void), uint32_t stacksize, uint8_t priority) { xTaskCreate((void (*)(void*)) tsk, /* this cast is undefined behavior */ NULL, stacksize, NULL, priority, NULL); } void ivory_freertos_task_delay(uint32_t time_ms) { vTaskDelay(time_ms); } void ivory_freertos_task_delayuntil(uint32_t *lastwaketime, uint32_t dt) { vTaskDelayUntil(lastwaketime, dt); } uint32_t ivory_freertos_task_getmilliscount(void) { return xTaskGetTickCount() / portTICK_RATE_MS; } uint32_t ivory_freertos_task_gettickcount(void) { return xTaskGetTickCount(); } uint32_t ivory_freertos_millistoticks(uint32_t ms) { return time * portTICK_RATE_MS; }
#include "freertos_task_wrapper.h" #include <FreeRTOS.h> #include <task.h> void ivory_freertos_task_create(void (*tsk)(void), uint32_t stacksize, uint8_t priority) { xTaskCreate((void (*)(void*)) tsk, /* this cast is undefined behavior */ NULL, stacksize, NULL, priority, NULL); } void ivory_freertos_task_delay(uint32_t time_ms) { vTaskDelay(time_ms); } void ivory_freertos_task_delayuntil(uint32_t *lastwaketime, uint32_t dt) { vTaskDelayUntil(lastwaketime, dt); } uint32_t ivory_freertos_task_getmilliscount(void) { return xTaskGetTickCount() / portTICK_RATE_MS; } uint32_t ivory_freertos_task_gettickcount(void) { return xTaskGetTickCount(); } uint32_t ivory_freertos_millistoticks(uint32_t ms) { return ms * portTICK_RATE_MS; }
Update files, Alura, Introdução a C, Aula 2.7
#include <stdio.h> int main() { // imprime o cabecalho do nosso jogo printf("******************************************\n"); printf("* Bem vindo ao nosso jogo de adivinhação *\n"); printf("******************************************\n"); int numerosecreto = 42; int chute; for(int i = 1; i <= 3; i++) { printf("Tentativa %d de 3\n", i); printf("Qual é o seu chute? "); scanf("%d", &chute); printf("Seu chute foi %d\n", chute); int acertou = chute == numerosecreto; if(acertou) { printf("Parabéns! Você acertou!\n"); printf("Jogue de novo, você é um bom jogador!\n"); break; } else { int maior = chute > numerosecreto; if(maior) { printf("Seu chute foi maior que o número secreto\n"); } else { printf("Seu chute foi menor que o número secreto\n"); } printf("Você errou!\n"); printf("Mas não desanime, tente de novo!\n"); } } printf("Fim de jogo!\n"); }
#include <stdio.h> #define NUMERO_DE_TENTATIVAS 5 int main() { // imprime o cabecalho do nosso jogo printf("******************************************\n"); printf("* Bem vindo ao nosso jogo de adivinhação *\n"); printf("******************************************\n"); int numerosecreto = 42; int chute; for(int i = 1; i <= NUMERO_DE_TENTATIVAS; i++) { printf("Tentativa %d de %d\n", i, NUMERO_DE_TENTATIVAS); printf("Qual é o seu chute? "); scanf("%d", &chute); printf("Seu chute foi %d\n", chute); int acertou = chute == numerosecreto; if(acertou) { printf("Parabéns! Você acertou!\n"); printf("Jogue de novo, você é um bom jogador!\n"); break; } else { int maior = chute > numerosecreto; if(maior) { printf("Seu chute foi maior que o número secreto\n"); } else { printf("Seu chute foi menor que o número secreto\n"); } printf("Você errou!\n"); printf("Mas não desanime, tente de novo!\n"); } } printf("Fim de jogo!\n"); }
Define an empty SODIUM_EXPORT if SODIUM_STATIC is defined.
#ifndef __SODIUM_EXPORT_H__ #define __SODIUM_EXPORT_H__ #ifndef __GNUC__ # ifdef __attribute__ # undef __attribute__ # endif # define __attribute__(a) #endif #ifndef SODIUM_STATIC # if defined(_MSC_VER) # ifdef DLL_EXPORT # define SODIUM_EXPORT __declspec(dllexport) # else # define SODIUM_EXPORT __declspec(dllimport) # endif # else # if defined(__SUNPRO_C) # define SODIUM_EXPORT __attribute__ __global # elif defined(_MSG_VER) # define SODIUM_EXPORT extern __declspec(dllexport) # else # define SODIUM_EXPORT __attribute__ ((visibility ("default"))) # endif # endif #endif #endif
#ifndef __SODIUM_EXPORT_H__ #define __SODIUM_EXPORT_H__ #ifndef __GNUC__ # ifdef __attribute__ # undef __attribute__ # endif # define __attribute__(a) #endif #ifdef SODIUM_STATIC # define SODIUM_EXPORT #else # if defined(_MSC_VER) # ifdef DLL_EXPORT # define SODIUM_EXPORT __declspec(dllexport) # else # define SODIUM_EXPORT __declspec(dllimport) # endif # else # if defined(__SUNPRO_C) # define SODIUM_EXPORT __attribute__ __global # elif defined(_MSG_VER) # define SODIUM_EXPORT extern __declspec(dllexport) # else # define SODIUM_EXPORT __attribute__ ((visibility ("default"))) # endif # endif #endif #endif
Remove leftover method in protocol
// // FTMutableDataSource.h // Fountain // // Created by Tobias Kraentzer on 15.09.15. // Copyright © 2015 Tobias Kräntzer. All rights reserved. // #import "FTDataSource.h" @protocol FTMutableDataSource <FTDataSource> #pragma mark Insertion - (BOOL)canInsertItem:(id)item; - (NSIndexPath *)insertItem:(id)item atProposedIndexPath:(NSIndexPath *)proposedIndexPath error:(NSError **)error; #pragma mark Editing - (BOOL)canEditItemAtIndexPath:(NSIndexPath *)indexPath; #pragma mark Deletion - (BOOL)canDeleteItemAtIndexPath:(NSIndexPath *)indexPath; - (void)deleteItemAtIndexPath:(NSIndexPath *)indexPath __attribute__((deprecated)); - (BOOL)deleteItemAtIndexPath:(NSIndexPath *)indexPath error:(NSError **)error; @end
// // FTMutableDataSource.h // Fountain // // Created by Tobias Kraentzer on 15.09.15. // Copyright © 2015 Tobias Kräntzer. All rights reserved. // #import "FTDataSource.h" @protocol FTMutableDataSource <FTDataSource> #pragma mark Insertion - (BOOL)canInsertItem:(id)item; - (NSIndexPath *)insertItem:(id)item atProposedIndexPath:(NSIndexPath *)proposedIndexPath error:(NSError **)error; #pragma mark Editing - (BOOL)canEditItemAtIndexPath:(NSIndexPath *)indexPath; #pragma mark Deletion - (BOOL)canDeleteItemAtIndexPath:(NSIndexPath *)indexPath; - (BOOL)deleteItemAtIndexPath:(NSIndexPath *)indexPath error:(NSError **)error; @end
Support for locating of debug items in frames.
//===-- llvm/CodeGen/MachineLocation.h --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // The MachineLocation class is used to represent a simple location in a machine // frame. Locations will be one of two forms; a register or an address formed // from a base address plus an offset. //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_MACHINELOCATION_H #define LLVM_CODEGEN_MACHINELOCATION_H namespace llvm { class MachineLocation { private: bool IsRegister; // True if location is a register. unsigned Register; // gcc/gdb register number. int Offset; // Displacement if not register. public: MachineLocation() : IsRegister(false) , Register(0) , Offset(0) {} MachineLocation(unsigned R) : IsRegister(true) , Register(R) , Offset(0) {} MachineLocation(unsigned R, int O) : IsRegister(false) , Register(R) , Offset(0) {} // Accessors bool isRegister() const { return IsRegister; } unsigned getRegister() const { return Register; } int getOffset() const { return Offset; } void setIsRegister(bool Is) { IsRegister = Is; } void setRegister(unsigned R) { Register = R; } void setOffset(int O) { Offset = O; } void set(unsigned R) { IsRegister = true; Register = R; Offset = 0; } void set(unsigned R, int O) { IsRegister = false; Register = R; Offset = O; } }; } // End llvm namespace #endif
Revert change that broke the build.
//===--- TargetBuiltins.h - Target specific builtin IDs -------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Anders Carlsson and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_TARGET_BUILTINS_H #define LLVM_CLANG_AST_TARGET_BUILTINS_H #include "clang/AST/Builtins.h" namespace clang { /// X86 builtins namespace X86 { enum { LastTIBuiltin = clang::Builtin::FirstTSBuiltin-1, #define BUILTIN(ID, TYPE, ATTRS) BI##ID, #include "X86Builtins.def" LastTSBuiltin }; } /// PPC builtins namespace PPC { enum { LastTIBuiltin = clang::Builtin::FirstTSBuiltin-1, #define BUILTIN(ID, TYPE, ATTRS) BI##ID, #include "PPCBuiltins.def" LastTSBuiltin }; } } #endif
//===--- TargetBuiltins.h - Target specific builtin IDs -------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Anders Carlsson and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_TARGET_BUILTINS_H #define LLVM_CLANG_AST_TARGET_BUILTINS_H #include "clang/AST/Builtins.h" /// X86 builtins namespace X86 { enum { LastTIBuiltin = clang::Builtin::FirstTSBuiltin-1, #define BUILTIN(ID, TYPE, ATTRS) BI##ID, #include "X86Builtins.def" LastTSBuiltin }; } /// PPC builtins namespace PPC { enum { LastTIBuiltin = clang::Builtin::FirstTSBuiltin-1, #define BUILTIN(ID, TYPE, ATTRS) BI##ID, #include "PPCBuiltins.def" LastTSBuiltin }; } #endif
Make the char * parameter as const char *
#ifndef LOG_H #define LOG_H #include <time.h> typedef struct data_struct { time_t time; char *string; } data_t; int addmsg(data_t data); void clearlog(void); char *getlog(void); int savelog(char *filename); #endif
#ifndef LOG_H #define LOG_H #include <time.h> typedef struct data_struct { time_t time; char *string; } data_t; int addmsg(data_t data); void clearlog(void); char *getlog(void); int savelog(const char *filename); #endif
Add lock to runq struct
/** * @file * @brief * * @date 06.03.2013 * @author Anton Bulychev */ #ifndef KERNEL_THREAD_SCHED_STRATEGY_H_ #define KERNEL_THREAD_SCHED_STRATEGY_H_ #include <kernel/sched/affinity.h> #include <kernel/sched/runq.h> #include <kernel/sched/sched_timing.h> #include <kernel/sched/sched_priority.h> struct runq { runq_t queue; }; struct sched_attr { runq_item_t runq_link; affinity_t affinity; sched_timing_t sched_time; thread_priority_t thread_priority; }; #endif /* KERNEL_THREAD_SCHED_STRATEGY_H_ */
/** * @file * @brief * * @date 06.03.2013 * @author Anton Bulychev */ #ifndef KERNEL_THREAD_SCHED_STRATEGY_H_ #define KERNEL_THREAD_SCHED_STRATEGY_H_ #include <kernel/spinlock.h> #include <kernel/sched/affinity.h> #include <kernel/sched/runq.h> #include <kernel/sched/sched_timing.h> #include <kernel/sched/sched_priority.h> struct runq { runq_t queue; spinlock_t lock; }; struct sched_attr { runq_item_t runq_link; affinity_t affinity; sched_timing_t sched_time; thread_priority_t thread_priority; }; #endif /* KERNEL_THREAD_SCHED_STRATEGY_H_ */
Comment out per-error logging, now only needed for logging
using StackExchange.Elastic; namespace StackExchange.Opserver { public class OpserverCore { // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so. public static void Init() { try { ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix; ElasticException.ExceptionOccurred += e => Current.LogException(e); } catch { } } } }
using StackExchange.Elastic; namespace StackExchange.Opserver { public class OpserverCore { // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so. public static void Init() { try { ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix; // We're going to get errors - that's kinda the point of monitoring // No need to log every one here unless for crazy debugging //ElasticException.ExceptionOccurred += e => Current.LogException(e); } catch { } } } }
Change Columns static method to return IReadOnlyList.
/* Copyright 2014 David Bordoley Copyright 2014 Zumero, 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. */ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; namespace SQLitePCL.pretty { public static class ResultSet { public static IEnumerable<IColumnInfo> Columns(this IReadOnlyList<IResultSetValue> rs) { Contract.Requires(rs != null); return rs.Select(value => value.ColumnInfo); } } }
/* Copyright 2014 David Bordoley Copyright 2014 Zumero, 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. */ using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; namespace SQLitePCL.pretty { public static class ResultSet { public static IReadOnlyList<IColumnInfo> Columns(this IReadOnlyList<IResultSetValue> rs) { Contract.Requires(rs != null); return new ResultSetColumnsListImpl(rs); } internal sealed class ResultSetColumnsListImpl : IReadOnlyList<IColumnInfo> { private readonly IReadOnlyList<IResultSetValue> rs; internal ResultSetColumnsListImpl(IReadOnlyList<IResultSetValue> rs) { this.rs = rs; } public IColumnInfo this[int index] { get { return rs[index].ColumnInfo; } } public int Count { get { return rs.Count; } } public IEnumerator<IColumnInfo> GetEnumerator() { return rs.Select(val => val.ColumnInfo).GetEnumerator(); } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } }
Add upload property to file
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Contentful.Core.Models { /// <summary> /// Represents information about the actual binary file of an <see cref="Asset"/>. /// </summary> public class File { /// <summary> /// The original name of the file. /// </summary> public string FileName { get; set; } /// <summary> /// The content type of the data contained within this file. /// </summary> public string ContentType { get; set; } /// <summary> /// An absolute URL to this file. /// </summary> public string Url { get; set; } /// <summary> /// Detailed information about the file stored by Contentful. /// </summary> public FileDetails Details { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Contentful.Core.Models { /// <summary> /// Represents information about the actual binary file of an <see cref="Asset"/>. /// </summary> public class File { /// <summary> /// The original name of the file. /// </summary> public string FileName { get; set; } /// <summary> /// The content type of the data contained within this file. /// </summary> public string ContentType { get; set; } /// <summary> /// An absolute URL to this file. /// </summary> public string Url { get; set; } /// <summary> /// The url to upload this file from. /// </summary> [JsonProperty("upload")] public string UploadUrl { get; set; } /// <summary> /// Detailed information about the file stored by Contentful. /// </summary> public FileDetails Details { get; set; } } }
Use same namespace for serializers
using System; using System.Collections.Generic; using ArcGIS.ServiceModel; using ArcGIS.ServiceModel.Operation; namespace ArcGIS.Test { public class JsonDotNetSerializer : ISerializer { static ISerializer _serializer = null; public static void Init() { _serializer = new JsonDotNetSerializer(); SerializerFactory.Get = (() => _serializer ?? new JsonDotNetSerializer()); } readonly Newtonsoft.Json.JsonSerializerSettings _settings; public JsonDotNetSerializer() { _settings = new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; } public Dictionary<String, String> AsDictionary<T>(T objectToConvert) where T : CommonParameters { var stringValue = Newtonsoft.Json.JsonConvert.SerializeObject(objectToConvert, _settings); var jobject = Newtonsoft.Json.Linq.JObject.Parse(stringValue); var dict = new Dictionary<String, String>(); foreach (var item in jobject) { dict.Add(item.Key, item.Value.ToString()); } return dict; } public T AsPortalResponse<T>(String dataToConvert) where T : IPortalResponse { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataToConvert, _settings); } } }
using System; using System.Collections.Generic; using ArcGIS.ServiceModel; using ArcGIS.ServiceModel.Operation; namespace ArcGIS.ServiceModel.Serializers { public class JsonDotNetSerializer : ISerializer { static ISerializer _serializer = null; public static void Init() { _serializer = new JsonDotNetSerializer(); SerializerFactory.Get = (() => _serializer ?? new JsonDotNetSerializer()); } readonly Newtonsoft.Json.JsonSerializerSettings _settings; public JsonDotNetSerializer() { _settings = new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }; } public Dictionary<String, String> AsDictionary<T>(T objectToConvert) where T : CommonParameters { var stringValue = Newtonsoft.Json.JsonConvert.SerializeObject(objectToConvert, _settings); var jobject = Newtonsoft.Json.Linq.JObject.Parse(stringValue); var dict = new Dictionary<String, String>(); foreach (var item in jobject) { dict.Add(item.Key, item.Value.ToString()); } return dict; } public T AsPortalResponse<T>(String dataToConvert) where T : IPortalResponse { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataToConvert, _settings); } } }
Use correct casing on public static field.
namespace XSerializer.Encryption { /// <summary> /// Provides a mechanism for an application to specify an instance of /// <see cref="IEncryptionMechanism"/> to be used by XSerializer when /// encrypting or decrypting data. /// </summary> public static class EncryptionMechanism { /// <summary> /// The default instance of <see cref="IEncryptionMechanism"/>. /// </summary> public static readonly IEncryptionMechanism _defaultEncryptionMechanism = new ClearTextEncryptionMechanism(); private static IEncryptionMechanism _current = _defaultEncryptionMechanism; /// <summary> /// Gets or sets the instance of <see cref="IEncryptionMechanism"/> /// to be used by XSerializer when encrypting or decrypting data. /// When setting this property, if <paramref name="value"/> is null, /// then <see cref="_defaultEncryptionMechanism"/> will be used instead. /// </summary> public static IEncryptionMechanism Current { internal get { return _current; } set { _current = value ?? _defaultEncryptionMechanism; } } } }
namespace XSerializer.Encryption { /// <summary> /// Provides a mechanism for an application to specify an instance of /// <see cref="IEncryptionMechanism"/> to be used by XSerializer when /// encrypting or decrypting data. /// </summary> public static class EncryptionMechanism { /// <summary> /// The default instance of <see cref="IEncryptionMechanism"/>. /// </summary> public static readonly IEncryptionMechanism DefaultEncryptionMechanism = new ClearTextEncryptionMechanism(); private static IEncryptionMechanism _current = DefaultEncryptionMechanism; /// <summary> /// Gets or sets the instance of <see cref="IEncryptionMechanism"/> /// to be used by XSerializer when encrypting or decrypting data. /// When setting this property, if <paramref name="value"/> is null, /// then <see cref="DefaultEncryptionMechanism"/> will be used instead. /// </summary> public static IEncryptionMechanism Current { internal get { return _current; } set { _current = value ?? DefaultEncryptionMechanism; } } } }
Rename some more nested classes
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osuTK; namespace osu.Framework.Graphics.UserInterface { public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay { protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new ComputerPiece(); protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new CurrentDisplayPiece(directory, displayName); public BasicDirectorySelectorBreadcrumbDisplay() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } protected class ComputerPiece : CurrentDisplayPiece { protected override IconUsage? Icon => null; public ComputerPiece() : base(null, "Computer") { } } protected class CurrentDisplayPiece : BasicDirectorySelectorDirectory { protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null; public CurrentDisplayPiece(DirectoryInfo directory, string displayName = null) : base(directory, displayName) { } [BackgroundDependencyLoader] private void load() { Flow.Add(new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = FontAwesome.Solid.ChevronRight, Size = new Vector2(FONT_SIZE / 2) }); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.IO; using osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osuTK; namespace osu.Framework.Graphics.UserInterface { public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay { protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new BreadcrumbDisplayComputer(); protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new BreadcrumbDisplayDirectory(directory, displayName); public BasicDirectorySelectorBreadcrumbDisplay() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } protected class BreadcrumbDisplayComputer : BreadcrumbDisplayDirectory { protected override IconUsage? Icon => null; public BreadcrumbDisplayComputer() : base(null, "Computer") { } } protected class BreadcrumbDisplayDirectory : BasicDirectorySelectorDirectory { protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null; public BreadcrumbDisplayDirectory(DirectoryInfo directory, string displayName = null) : base(directory, displayName) { } [BackgroundDependencyLoader] private void load() { Flow.Add(new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = FontAwesome.Solid.ChevronRight, Size = new Vector2(FONT_SIZE / 2) }); } } } }
Comment and fix on namespace
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KGP.Curves { public class ThresholdLinearCurve : ICurve { private float threshold; public float Threshold { get { return this.threshold; } set { this.threshold = value; } } public ThresholdLinearCurve(float threshold) { this.threshold = threshold; } public float Apply(float value) { float absval = Math.Abs(value); if (absval <= threshold) { return 0.0f; } else { float diff = (absval - threshold) / (1.0f - threshold); return diff * Math.Sign(value); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KGP { /// <summary> /// Linear threshold curve, clamp while absolute value is within threshold /// </summary> public class ThresholdLinearCurve : ICurve { private float threshold; /// <summary> /// Current threshold /// </summary> public float Threshold { get { return this.threshold; } set { this.threshold = value; } } /// <summary> /// Constructor /// </summary> /// <param name="threshold">Initial threshold value</param> public ThresholdLinearCurve(float threshold) { this.threshold = threshold; } /// <summary> ///Apply threshold curve /// </summary> /// <param name="value">Intial value</param> /// <returns>Value with curve applied</returns> public float Apply(float value) { float absval = Math.Abs(value); if (absval <= threshold) { return 0.0f; } else { float diff = (absval - threshold) / (1.0f - threshold); return diff * Math.Sign(value); } } } }
Add quotes and length of JSON packets being sent.
namespace Server { using System; using System.IO; using System.Text; internal partial class Program { class Dup : Stream { string _name; private Dup() { } public Dup(string name) { _name = name; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { DateTime now = DateTime.Now; StringBuilder sb = new StringBuilder(); sb.AppendLine("Raw message from " + _name + " " + now.ToString()); var truncated_array = new byte[count]; for (int i = offset; i < offset + count; ++i) truncated_array[i - offset] = buffer[i]; string str = System.Text.Encoding.Default.GetString(truncated_array); sb.AppendLine("data = '" + str); LoggerNs.Logger.Log.WriteLine(sb.ToString()); } } } }
namespace Server { using System; using System.IO; using System.Text; internal partial class Program { class Dup : Stream { string _name; private Dup() { } public Dup(string name) { _name = name; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { DateTime now = DateTime.Now; StringBuilder sb = new StringBuilder(); sb.AppendLine("Raw message from " + _name + " " + now.ToString()); var truncated_array = new byte[count]; for (int i = offset; i < offset + count; ++i) truncated_array[i - offset] = buffer[i]; string str = System.Text.Encoding.Default.GetString(truncated_array); sb.AppendLine("data (length " + str.Length + ")= '" + str + "'"); LoggerNs.Logger.Log.WriteLine(sb.ToString()); } } } }
Update documentation now that we can point to a concrete method
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { interface ICodeModelInstanceFactory { /// <summary> /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system. /// </summary> /// <remarks> /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another, /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/> /// member should be. The expectation is the implementer of this will do what is necessary and call back into the code model implementation /// with a parent object.</remarks> EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { interface ICodeModelInstanceFactory { /// <summary> /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system. /// </summary> /// <remarks> /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another, /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/> /// member should be. The expectation is the implementer of this will do what is necessary and call back into <see cref="IProjectCodeModel.GetOrCreateFileCodeModel(string, object)"/> /// handing it the appropriate parent.</remarks> EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath); } }
Test case renamed to be more accurate
using System; using Shouldly; using Spk.Common.Helpers.Service; using Xunit; namespace Spk.Common.Tests.Helpers.Service { public class ServiceResultTests { [Theory] [InlineData("test")] [InlineData("")] [InlineData(null)] public void SetData_SuccessShouldBeTrue(string value) { // Arrange var sr = new ServiceResult<string>(); // Act sr.SetData(value); // Assert sr.Success.ShouldBeTrue(); } [Theory] [InlineData("error")] public void GetFirstError_ShouldReturnFirstError(string error) { // Arrange var sr = new ServiceResult<string>(); // Act sr.AddError(error); // Assert sr.GetFirstError().ShouldBe(error); } [Fact] public void AddError_ShouldArgumentNullException_WhenNullError() { // Act & assert Assert.Throws<ArgumentNullException>(() => { var sr = new ServiceResult<string>(); sr.AddError(null); }); } } }
using System; using Shouldly; using Spk.Common.Helpers.Service; using Xunit; namespace Spk.Common.Tests.Helpers.Service { public class ServiceResultTests { [Theory] [InlineData("test")] [InlineData("")] [InlineData(null)] public void Success_ShouldBeTrue_WhenDataIsSet(string value) { // Arrange var sr = new ServiceResult<string>(); // Act sr.SetData(value); // Assert sr.Success.ShouldBeTrue(); } [Theory] [InlineData("error")] public void GetFirstError_ShouldReturnFirstError(string error) { // Arrange var sr = new ServiceResult<string>(); // Act sr.AddError(error); sr.AddError("bleh"); // Assert sr.GetFirstError().ShouldBe(error); } [Fact] public void AddError_ShouldArgumentNullException_WhenNullError() { // Act & assert Assert.Throws<ArgumentNullException>(() => { var sr = new ServiceResult<string>(); sr.AddError(null); }); } } }
Remove unused usings and make the target class internal
using System.Collections.Concurrent; using System.IO; using NLog; using NLog.Config; using NLog.Targets; namespace Microsoft.Azure.Commands.DataLakeStore.Models { /// <summary> /// NLog is used by the ADLS dataplane sdk to log debug messages. We can create a custom target /// which basically queues the debug data to the ConcurrentQueue for debug messages. /// https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target /// </summary> [Target("AdlsLogger")] public sealed class AdlsLoggerTarget : TargetWithLayout { internal ConcurrentQueue<string> DebugMessageQueue; public AdlsLoggerTarget() { } protected override void Write(LogEventInfo logEvent) { string logMessage = Layout.Render(logEvent); DebugMessageQueue?.Enqueue(logMessage); } } }
using System.Collections.Concurrent; using NLog; using NLog.Targets; namespace Microsoft.Azure.Commands.DataLakeStore.Models { /// <summary> /// NLog is used by the ADLS dataplane sdk to log debug messages. We can create a custom target /// which basically queues the debug data to the ConcurrentQueue for debug messages. /// https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target /// </summary> [Target("AdlsLogger")] internal sealed class AdlsLoggerTarget : TargetWithLayout { internal ConcurrentQueue<string> DebugMessageQueue; protected override void Write(LogEventInfo logEvent) { string logMessage = Layout.Render(logEvent); DebugMessageQueue?.Enqueue(logMessage); } } }
Return the given RemindOn date
using Simpler; using System; using Schedules.API.Models; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Tasks.Sending { public class PostRemindersEmailSend : InOutTask<PostRemindersEmailSend.Input, PostRemindersEmailSend.Output> { public class Input { public Send Send { get; set; } } public class Output { public Send Send { get; set; } } public FetchDueReminders FetchDueReminders { get; set; } public SendEmails SendEmails { get; set; } public override void Execute () { FetchDueReminders.In.RemindOn = In.Send.RemindOn; FetchDueReminders.Execute(); SendEmails.In.DueReminders = FetchDueReminders.Out.DueReminders; SendEmails.Execute(); Out.Send = new Send { Sent = SendEmails.Out.Sent, Errors = SendEmails.Out.Errors }; } } }
using Simpler; using System; using Schedules.API.Models; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Tasks.Sending { public class PostRemindersEmailSend : InOutTask<PostRemindersEmailSend.Input, PostRemindersEmailSend.Output> { public class Input { public Send Send { get; set; } } public class Output { public Send Send { get; set; } } public FetchDueReminders FetchDueReminders { get; set; } public SendEmails SendEmails { get; set; } public override void Execute () { FetchDueReminders.In.RemindOn = In.Send.RemindOn; FetchDueReminders.Execute(); SendEmails.In.DueReminders = FetchDueReminders.Out.DueReminders; SendEmails.Execute(); Out.Send = new Send { RemindOn = In.Send.RemindOn, Sent = SendEmails.Out.Sent, Errors = SendEmails.Out.Errors }; } } }
Store ContentId against the LinkedResource
using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Net.Mail; using System.Net.Mime; using RazorEngine.Text; namespace Essential.Templating.Razor.Email.Helpers { public static class ResourceTemplateHelperExtensions { public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType, TransferEncoding transferEncoding, CultureInfo culture = null) { Contract.Requires<ArgumentNullException>(helper != null); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType)); var resource = helper.Get(path, culture); if (resource == null) { var message = string.Format("Resource [{0}] was not found.", contentId); throw new TemplateHelperException(message); } var linkedResource = new LinkedResource(resource, mediaType) { TransferEncoding = transferEncoding }; helper.AddLinkedResource(linkedResource); var renderedResult = new RawString(string.Format("cid:{0}", contentId)); return renderedResult; } } }
using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Net.Mail; using System.Net.Mime; using RazorEngine.Text; namespace Essential.Templating.Razor.Email.Helpers { public static class ResourceTemplateHelperExtensions { public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType, TransferEncoding transferEncoding, CultureInfo culture = null) { Contract.Requires<ArgumentNullException>(helper != null); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId)); Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType)); var resource = helper.Get(path, culture); if (resource == null) { var message = string.Format("Resource [{0}] was not found.", contentId); throw new TemplateHelperException(message); } var linkedResource = new LinkedResource(resource, mediaType) { TransferEncoding = transferEncoding, ContentId = contentId }; helper.AddLinkedResource(linkedResource); var renderedResult = new RawString(string.Format("cid:{0}", contentId)); return renderedResult; } } }
Update with slider body changes
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Osu.Edit.Masks.SliderMasks.Components { public class SliderBodyPiece : CompositeDrawable { private readonly Slider slider; private readonly SliderBody body; public SliderBodyPiece(Slider slider) { this.slider = slider; InternalChild = body = new SliderBody(slider) { AccentColour = Color4.Transparent, PathWidth = slider.Scale * 64 }; slider.PositionChanged += _ => updatePosition(); } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; updatePosition(); } private void updatePosition() => Position = slider.StackedPosition; protected override void Update() { base.Update(); Size = body.Size; OriginPosition = body.PathOffset; // Need to cause one update body.UpdateProgress(0); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Osu.Edit.Masks.SliderMasks.Components { public class SliderBodyPiece : CompositeDrawable { private readonly Slider slider; private readonly SnakingSliderBody body; public SliderBodyPiece(Slider slider) { this.slider = slider; InternalChild = body = new SnakingSliderBody(slider) { AccentColour = Color4.Transparent, PathWidth = slider.Scale * 64 }; slider.PositionChanged += _ => updatePosition(); } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; updatePosition(); } private void updatePosition() => Position = slider.StackedPosition; protected override void Update() { base.Update(); Size = body.Size; OriginPosition = body.PathOffset; // Need to cause one update body.UpdateProgress(0); } } }
Add reply mode and a shortcut for getting admins
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace AlertRoster.Web.Models { public class Group { [Key] public int Id { get; private set; } [Required, StringLength(25)] public String DisplayName { get; set; } [StringLength(25)] public String PhoneNumber { get; set; } public virtual ICollection<MemberGroup> Members { get; private set; } public virtual ICollection<Message> Messages { get; private set; } // TODO Who are admins? // TODO Reply-mode : Reply-All, Reply-to-Admin, Reject? private Group() { // Parameter-less ctor for EF } public Group(String displayName) { this.DisplayName = displayName; this.Members = new List<MemberGroup>(); this.Messages = new List<Message>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace AlertRoster.Web.Models { public class Group { [Key] public int Id { get; private set; } [Required, StringLength(25)] public String DisplayName { get; set; } [StringLength(25)] public String PhoneNumber { get; set; } public virtual ICollection<MemberGroup> Members { get; private set; } public virtual IEnumerable<Member> Admins => Members.Where(_ => _.Role == MemberGroup.GroupRole.Administrator).Select(_ => _.Member); public virtual ICollection<Message> Messages { get; private set; } [Required] public ReplyMode Replies { get; set; } = ReplyMode.ReplyAll; private Group() { // Parameter-less ctor for EF } public Group(String displayName) { this.DisplayName = displayName; this.Members = new List<MemberGroup>(); this.Messages = new List<Message>(); } public enum ReplyMode : byte { ReplyAll = 0, ReplyToAdmins = 1, Reject = 2 } } }
Fix for native extension method name (not Android!)
// MvxColorExtensions.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Cirrious.CrossCore.UI; using MonoTouch.UIKit; namespace Cirrious.MvvmCross.Plugins.Color.Touch { public static class MvxColorExtensions { public static UIColor ToAndroidColor(this MvxColor color) { return MvxTouchColor.ToUIColor(color); } } }
// MvxColorExtensions.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Cirrious.CrossCore.UI; using MonoTouch.UIKit; namespace Cirrious.MvvmCross.Plugins.Color.Touch { public static class MvxColorExtensions { public static UIColor ToNativeColor(this MvxColor color) { return MvxTouchColor.ToUIColor(color); } } }
Update user info on opportunity.
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class OpportunityDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public string OpportunityLocatorId { get; set; } [DataMember] public Guid ProspectGuid { get; set; } [DataMember] public Guid CustomerGuid { get; set; } [DataMember] public Guid CurrentOfferGuid { get; set; } [DataMember] public Guid PartnerGuid { get; set; } [DataMember] public Guid CurrentStatusTrnGuid { get; set; } [DataMember] public OfferDto CurrentOffer { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class OpportunityDto { [DataMember] public Guid OpportunityGuid { get; set; } [DataMember] public string OpportunityLocatorId { get; set; } [DataMember] public Guid ProspectGuid { get; set; } [DataMember] public Guid CustomerGuid { get; set; } [DataMember] public Guid CurrentOfferGuid { get; set; } [DataMember] public Guid PartnerGuid { get; set; } [DataMember] public Guid CurrentStatusTrnGuid { get; set; } [DataMember] public OfferDto CurrentOffer { get; set; } [DataMember] public Guid UpdateUserGuid { get; set; } [DataMember] public string UpdateUsername { get; set; } [DataMember] public DateTimeOffset UpdateDate { get; set; } } }
Split Pascal cased property names into words
@using Piranha.Extend; @using Piranha.Manager.Manager; @model Block @foreach(var name in Model.GetFieldNames()) { <div class="form-group"> <label>@name</label> @Html.Editor(name) </div> }
@using Piranha.Extend; @using Piranha.Manager.Manager; @using System.Text.RegularExpressions; @model Block @foreach(var name in Model.GetFieldNames()) { var label = Regex.Replace(name, "(\\B[A-Z])", " $1"); <div class="form-group"> <label>@label</label> @Html.Editor(name) </div> }
Fix spelling mistake in error message
using System; using System.Collections.Generic; using System.Linq; using HandlebarsDotNet.Compiler.Lexer; using System.Linq.Expressions; namespace HandlebarsDotNet.Compiler { internal class ExpressionScopeConverter : TokenConverter { public static IEnumerable<object> Convert(IEnumerable<object> sequence) { return new ExpressionScopeConverter().ConvertTokens(sequence).ToList(); } private ExpressionScopeConverter() { } public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence) { var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { var item = enumerator.Current; if (item is StartExpressionToken) { var startExpression = item as StartExpressionToken; item = GetNext(enumerator); if ((item is Expression) == false) { throw new HandlebarsCompilerException( string.Format("Token '{0}' could not be converted to an expression", item)); } yield return HandlebarsExpression.Statement( (Expression)item, startExpression.IsEscaped); item = GetNext(enumerator); if ((item is EndExpressionToken) == false) { throw new HandlebarsCompilerException("Handlebars statement was not reduced to a single expression"); } if (((EndExpressionToken)item).IsEscaped != startExpression.IsEscaped) { throw new HandlebarsCompilerException("Starting and ending handleabars do not match"); } } else { yield return item; } } } private static object GetNext(IEnumerator<object> enumerator) { enumerator.MoveNext(); return enumerator.Current; } } }
using System; using System.Collections.Generic; using System.Linq; using HandlebarsDotNet.Compiler.Lexer; using System.Linq.Expressions; namespace HandlebarsDotNet.Compiler { internal class ExpressionScopeConverter : TokenConverter { public static IEnumerable<object> Convert(IEnumerable<object> sequence) { return new ExpressionScopeConverter().ConvertTokens(sequence).ToList(); } private ExpressionScopeConverter() { } public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence) { var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) { var item = enumerator.Current; if (item is StartExpressionToken) { var startExpression = item as StartExpressionToken; item = GetNext(enumerator); if ((item is Expression) == false) { throw new HandlebarsCompilerException( string.Format("Token '{0}' could not be converted to an expression", item)); } yield return HandlebarsExpression.Statement( (Expression)item, startExpression.IsEscaped); item = GetNext(enumerator); if ((item is EndExpressionToken) == false) { throw new HandlebarsCompilerException("Handlebars statement was not reduced to a single expression"); } if (((EndExpressionToken)item).IsEscaped != startExpression.IsEscaped) { throw new HandlebarsCompilerException("Starting and ending handlebars do not match"); } } else { yield return item; } } } private static object GetNext(IEnumerator<object> enumerator) { enumerator.MoveNext(); return enumerator.Current; } } }
Replace first TestObjectBuilderBuilder unit test with two tests to make the tests less brittle.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using TestObjectBuilder; namespace TestObjectBuilderTests.Tests { public class TestObjectBuilderBuilderTests { [TestFixture] public class CreateNewObject { [Test] public void CreatesProductWithoutPropertiesAndAZeroArgConstructor() { // Arrange ITestObjBuilder<ProductWithoutProperties> builder = TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject(); // Act ProductWithoutProperties product = builder.Build(); // Assert Assert.NotNull(product); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using TestObjectBuilder; namespace TestObjectBuilderTests.Tests { public class TestObjectBuilderBuilderTests { [TestFixture] public class CreateNewObject { [Test] public void ProductBuilderCreateBuildsObjectsOfTypeProduct() { // Arrange // Act ITestObjBuilder<ProductWithoutProperties> builder = TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject(); // Assert Assert.AreSame(typeof(ProductWithoutProperties), builder.GetType().GetMethod("Build").ReturnType); } [Test] public void ProductBuilderHasNoPropertiesWhenProductHasNoProperties() { // Arrange // Act ITestObjBuilder<ProductWithoutProperties> builder = TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject(); // Assert Assert.AreEqual(0, builder.GetType().GetProperties().Count()); } } } }
Fix incorrect namespace for UI component.
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGameUtils.Diagnostics; namespace PCGame.GameComponents { public class UIFPSCounter : DrawableGameComponent { private FPSCounter _fpsCounter = new FPSCounter(); private SpriteBatch _spriteBatch; private SpriteFont _font; private Vector2 _topLeftPoint; private Vector2 _avgFPSLocation; private readonly Color _fontColor = Color.Black; public UIFPSCounter(Game game, SpriteFont font, Vector2 topLeftPoint, SpriteBatch spriteBatch) : base(game) { _spriteBatch = spriteBatch; _font = font; _topLeftPoint = topLeftPoint; _avgFPSLocation = Vector2.Add(_topLeftPoint, new Vector2(0, 20)); } public override void Update(GameTime gameTime) { _fpsCounter.Update(gameTime); base.Update(gameTime); } public override void Draw(GameTime gameTime) { _spriteBatch.DrawString(_font, "Current FPS: " + _fpsCounter.CurrentFPS, _topLeftPoint, _fontColor); _spriteBatch.DrawString(_font, "Avg FPS: " + _fpsCounter.AverageFPS, _avgFPSLocation, _fontColor); base.Draw(gameTime); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MonoGameUtils.Diagnostics; namespace MonoGameUtils.UI.GameComponents { public class UIFPSCounter : DrawableGameComponent { private FPSCounter _fpsCounter = new FPSCounter(); private SpriteBatch _spriteBatch; private SpriteFont _font; private Vector2 _topLeftPoint; private Vector2 _avgFPSLocation; private readonly Color _fontColor = Color.Black; public UIFPSCounter(Game game, SpriteFont font, Vector2 topLeftPoint, SpriteBatch spriteBatch) : base(game) { _spriteBatch = spriteBatch; _font = font; _topLeftPoint = topLeftPoint; _avgFPSLocation = Vector2.Add(_topLeftPoint, new Vector2(0, 20)); } public override void Update(GameTime gameTime) { _fpsCounter.Update(gameTime); base.Update(gameTime); } public override void Draw(GameTime gameTime) { _spriteBatch.DrawString(_font, "Current FPS: " + _fpsCounter.CurrentFPS, _topLeftPoint, _fontColor); _spriteBatch.DrawString(_font, "Avg FPS: " + _fpsCounter.AverageFPS, _avgFPSLocation, _fontColor); base.Draw(gameTime); } } }
Add additional hole punch logging
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; namespace RebirthTracker.PacketHandlers { /// <summary> /// Request a game host try a hole punch /// </summary> [Opcode(26)] public class HolePunchPacketHandler : IPacketHandler { /// <summary> /// Constructor called through reflection in PacketHandlerFactory /// </summary> public HolePunchPacketHandler() { } /// <summary> /// Handle the packet /// </summary> public async Task Handle(UdpReceiveResult result) { var peer = result.RemoteEndPoint; await Logger.Log("Hole Punch").ConfigureAwait(false); ushort gameID = BitConverter.ToUInt16(result.Buffer, 1); await Logger.Log($"Got Game ID {gameID}"); Game game; using (var db = new GameContext()) { game = (await db.Games.Where(x => x.ID == gameID).ToListAsync().ConfigureAwait(false)).FirstOrDefault(); } Packet packet; if (game != null) { packet = new Packet(26, $"{peer.Address}/{peer.Port}"); await packet.Send(Globals.MainClient, game.Endpoint).ConfigureAwait(false); return; } packet = new Packet(27, gameID); await packet.Send(Globals.MainClient, peer).ConfigureAwait(false); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; namespace RebirthTracker.PacketHandlers { /// <summary> /// Request a game host try a hole punch /// </summary> [Opcode(26)] public class HolePunchPacketHandler : IPacketHandler { /// <summary> /// Constructor called through reflection in PacketHandlerFactory /// </summary> public HolePunchPacketHandler() { } /// <summary> /// Handle the packet /// </summary> public async Task Handle(UdpReceiveResult result) { var peer = result.RemoteEndPoint; await Logger.Log("Hole Punch").ConfigureAwait(false); ushort gameID = BitConverter.ToUInt16(result.Buffer, 1); await Logger.Log($"Got Game ID {gameID}").ConfigureAwait(false); Game game; using (var db = new GameContext()) { game = (await db.Games.Where(x => x.ID == gameID).ToListAsync().ConfigureAwait(false)).FirstOrDefault(); } Packet packet; if (game != null) { await Logger.Log("Sending hole punch packet").ConfigureAwait(false); packet = new Packet(26, $"{peer.Address}/{peer.Port}"); await packet.Send(Globals.MainClient, game.Endpoint).ConfigureAwait(false); return; } await Logger.Log("Couldn't fetch game").ConfigureAwait(false); packet = new Packet(27, gameID); await packet.Send(Globals.MainClient, peer).ConfigureAwait(false); } } }
Make sure that authorization of TraktCalendarAllDVDMoviesRequest is not required
namespace TraktApiSharp.Tests.Experimental.Requests.Calendars { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Calendars; using TraktApiSharp.Objects.Get.Calendars; [TestClass] public class TraktCalendarAllDVDMoviesRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsNotAbstract() { typeof(TraktCalendarAllDVDMoviesRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSealed() { typeof(TraktCalendarAllDVDMoviesRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSubclassOfATraktCalendarAllRequest() { typeof(TraktCalendarAllDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarAllRequest<TraktCalendarMovie>)).Should().BeTrue(); } } }
namespace TraktApiSharp.Tests.Experimental.Requests.Calendars { using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using TraktApiSharp.Experimental.Requests.Calendars; using TraktApiSharp.Objects.Get.Calendars; using TraktApiSharp.Requests; [TestClass] public class TraktCalendarAllDVDMoviesRequestTests { [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsNotAbstract() { typeof(TraktCalendarAllDVDMoviesRequest).IsAbstract.Should().BeFalse(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSealed() { typeof(TraktCalendarAllDVDMoviesRequest).IsSealed.Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestIsSubclassOfATraktCalendarAllRequest() { typeof(TraktCalendarAllDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarAllRequest<TraktCalendarMovie>)).Should().BeTrue(); } [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")] public void TestTraktCalendarAllDVDMoviesRequestHasAuthorizationNotRequired() { var request = new TraktCalendarAllDVDMoviesRequest(null); request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.NotRequired); } } }
Add user photo to users list
@using ForumModels; @{ string usersFile = Server.MapPath("~/App_Data/users.json"); var userList = new UserList(usersFile); } <table class="table"> <thead> <tr class="lead"> <th></th> <th>Name</th> <th>MSDN Name</th> <th>StackOverflow ID</th> </tr> </thead> @{int count = 0; } @foreach (var user in userList.Users) { count++; <tr class="lead"> <td>@count</td> <td>@user.Name</td> <td><a href="https://social.msdn.microsoft.com/Profile/@user.MSDNName/activity">@user.MSDNName</a></td> <td><a href="http://stackoverflow.com/users/@user.StackOverflowID?tab=reputation">@user.StackOverflowID</a></td> </tr> } </table>
@using ForumModels; @{ string usersFile = Server.MapPath("~/App_Data/users.json"); var userList = new UserList(usersFile); } <table class="table"> <thead> <tr class="lead"> <th></th> <th></th> <th>Name</th> <th>MSDN Name</th> <th>StackOverflow ID</th> </tr> </thead> @{int count = 0; } @foreach (var user in userList.Users) { count++; <tr class="lead"> <td width="20px">@count</td> <td width="20px"><img src="https://i1.social.s-msft.com/profile/u/avatar.jpg?displayname=@user.MSDNName" /></td> <td>@user.Name</td> <td><a href="https://social.msdn.microsoft.com/Profile/@user.MSDNName/activity">@user.MSDNName</a></td> <td><a href="http://stackoverflow.com/users/@user.StackOverflowID?tab=reputation">@user.StackOverflowID</a></td> </tr> } </table>
Disable playlist start button when attempts have been exhausted
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Components; namespace osu.Game.Screens.OnlinePlay.Playlists { public class PlaylistsReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset?> endDate { get; set; } [Resolved] private IBindable<WorkingBeatmap> gameBeatmap { get; set; } public PlaylistsReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } protected override void Update() { base.Update(); Enabled.Value = endDate.Value != null && DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(gameBeatmap.Value.Track.Length) < endDate.Value; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Components; namespace osu.Game.Screens.OnlinePlay.Playlists { public class PlaylistsReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset?> endDate { get; set; } [Resolved] private IBindable<WorkingBeatmap> gameBeatmap { get; set; } public PlaylistsReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } private bool hasRemainingAttempts = true; protected override void LoadComplete() { base.LoadComplete(); userScore.BindValueChanged(aggregate => { if (maxAttempts.Value == null) return; int remaining = maxAttempts.Value.Value - aggregate.NewValue.PlaylistItemAttempts.Sum(a => a.Attempts); hasRemainingAttempts = remaining > 0; }); } protected override void Update() { base.Update(); Enabled.Value = hasRemainingAttempts && enoughTimeLeft; } private bool enoughTimeLeft => // This should probably consider the length of the currently selected item, rather than a constant 30 seconds. endDate.Value != null && DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(gameBeatmap.Value.Track.Length) < endDate.Value; } }