hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
9a9cf5a24cc6d9b342c1376ca48df408c1e72641
2,250
h
C
y/y/concurrent/VectorLock.h
gan74/Yave
a35a68d388729d02f9793cc0fe9a530c010cf432
[ "MIT" ]
259
2016-12-02T03:06:19.000Z
2022-03-13T19:21:00.000Z
y/y/concurrent/VectorLock.h
gan74/Yave
a35a68d388729d02f9793cc0fe9a530c010cf432
[ "MIT" ]
3
2019-05-02T04:09:13.000Z
2021-12-27T02:27:33.000Z
y/y/concurrent/VectorLock.h
gan74/Yave
a35a68d388729d02f9793cc0fe9a530c010cf432
[ "MIT" ]
17
2019-01-04T10:07:23.000Z
2021-09-15T08:41:04.000Z
/******************************* Copyright (c) 2016-2021 Grégoire Angerand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **********************************/ #ifndef Y_CONCURRENT_VECTORLOCK_H #define Y_CONCURRENT_VECTORLOCK_H #include <y/core/Vector.h> namespace y { namespace concurrent { template<typename T> class VectorLock : NonCopyable { public: VectorLock(VectorLock&&) = default; VectorLock& operator=(VectorLock&&) = default; VectorLock(core::Vector<std::reference_wrapper<T>> locks) : _locks(std::move(locks)) { while(!try_lock_all()) { } } ~VectorLock() { for(usize i = 0; i != _locks.size(); ++i) { _locks[_locks.size() - i - 1].get().unlock(); } } private: bool try_lock_all() { for(usize i = 0; i != _locks.size(); ++i) { if(!_locks[i].get().try_lock()) { for(usize j = 0; j + 1 < i; ++j) { _locks[i - j - 1].get().unlock(); } return false; } } return true; } core::Vector<std::reference_wrapper<T>> _locks; }; } } #endif // Y_CONCURRENT_VECTORLOCK_H
32.142857
94
0.624889
82fdacf80799686f5b769f15b33d3f37c36e5f8e
2,142
h
C
connectionManager.h
IKhonakhbeeva/trik-desktop-gamepad
7d56c15b197676e8e7be031a4330e58b22d8e06d
[ "Apache-2.0" ]
null
null
null
connectionManager.h
IKhonakhbeeva/trik-desktop-gamepad
7d56c15b197676e8e7be031a4330e58b22d8e06d
[ "Apache-2.0" ]
null
null
null
connectionManager.h
IKhonakhbeeva/trik-desktop-gamepad
7d56c15b197676e8e7be031a4330e58b22d8e06d
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 Konstantin Batoev. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was modified by Konstantin Batoev to make it comply with the requirements of trikRuntime * project. See git revision history for detailed changes. */ #pragma once #include <QtNetwork/QTcpSocket> #include <QtCore/QIODevice> /// TODO description class ConnectionManager : public QObject { Q_OBJECT private: ConnectionManager(const ConnectionManager &other); ConnectionManager & operator=(const ConnectionManager &other); public: ConnectionManager(); ~ConnectionManager(); /// checks connection bool isConnected() const; /// sets camera ip void setCameraIp(const QString &value); /// returns camera ip QString getCameraIp() const; /// returns camera port QString getCameraPort() const; /// sets camera port void setCameraPort(const QString &value); /// sets gamepad ip void setGamepadIp(const QString &value); /// sets gamepad port void setGamepadPort(const quint16 &value); /// returns gamepad ip QString getGamepadIp() const; /// returns gamepad port quint16 getGamepadPort() const; public slots: /// TODO description void connectToHost(); /// TODO description void disconnectFromHost(); /// TODO description void write(const QString &); signals: /// TODO description void stateChanged(QAbstractSocket::SocketState socketState); /// TODO description void dataWasWritten(int); /// TODO description void connectionFailed(); private: QTcpSocket *socket; // TODO [Doesn't have | Has] ownership QString cameraIp; QString cameraPort; QString gamepadIp; quint16 gamepadPort; };
24.067416
101
0.746032
d2080dffdd074ff836de7f175b690aba5f62969b
1,877
h
C
hm_sdk_config.h
highmobility/hmkit-python-workspace
aeef9b65ae8e3fb657e38a367e073d7cd6dde173
[ "MIT" ]
null
null
null
hm_sdk_config.h
highmobility/hmkit-python-workspace
aeef9b65ae8e3fb657e38a367e073d7cd6dde173
[ "MIT" ]
null
null
null
hm_sdk_config.h
highmobility/hmkit-python-workspace
aeef9b65ae8e3fb657e38a367e073d7cd6dde173
[ "MIT" ]
null
null
null
/* The MIT License Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef HM_SDK_CONFIG_H #define HM_SDK_CONFIG_H #include <stdint.h> typedef struct { uint8_t serial[9]; uint8_t public_key[64]; uint8_t private_key[32]; } hm_car_t; void hm_sdk_config_get_device_cert_issuer_pub(uint8_t *pub); void hm_sdk_config_get_access_cert_issuer_pub(uint8_t *pub); void hm_sdk_config_get_issuer(uint8_t *issuer); hm_car_t hm_sdk_config_get_serial_public_private(void); void hm_sdk_config_get_device_certificate(uint8_t *device); char** hm_sdk_config_get_argv(void); uint8_t hm_sdk_config_is_usb(void); char* hm_sdk_config_get_uart_device(void); void hm_sdk_config_set_issuer_pub(uint8_t *pub); void hm_sdk_config_set_dev_prv(uint8_t *prv); void hm_sdk_config_set_device_certificate(uint8_t *device); #endif //HM_SDK_CONFIG_H
39.104167
77
0.811934
aaf2b8a37dc08d6ea94233747c2ff815806eb067
861
h
C
src/common/common.h
cnheider/xgboost
e7fbc8591fa7277ee4c474b7371c48c11b34cbde
[ "Apache-2.0" ]
769
2015-01-02T03:15:00.000Z
2022-03-30T11:22:52.000Z
src/common/common.h
cnheider/xgboost
e7fbc8591fa7277ee4c474b7371c48c11b34cbde
[ "Apache-2.0" ]
54
2015-01-01T01:12:39.000Z
2017-05-21T02:56:14.000Z
src/common/common.h
cnheider/xgboost
e7fbc8591fa7277ee4c474b7371c48c11b34cbde
[ "Apache-2.0" ]
372
2015-01-03T21:10:27.000Z
2022-03-03T03:46:36.000Z
/*! * Copyright 2015 by Contributors * \file common.h * \brief Common utilities */ #ifndef XGBOOST_COMMON_COMMON_H_ #define XGBOOST_COMMON_COMMON_H_ #include <vector> #include <string> #include <sstream> namespace xgboost { namespace common { /*! * \brief Split a string by delimiter * \param s String to be splitted. * \param delim The delimiter. */ inline std::vector<std::string> Split(const std::string& s, char delim) { std::string item; std::istringstream is(s); std::vector<std::string> ret; while (std::getline(is, item, delim)) { ret.push_back(item); } return ret; } // simple routine to convert any data to string template<typename T> inline std::string ToString(const T& data) { std::ostringstream os; os << data; return os.str(); } } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_COMMON_H_
21
73
0.699187
d2addac037a41345065453c5a8a4e590cc79d093
12,886
c
C
kernel/kernel/i386/iopb.c
eyadhamdan4/xMach
38272d98114715a10e77c2c014e16c9782f7807c
[ "BSD-3-Clause" ]
32
2015-02-02T06:45:21.000Z
2022-01-24T05:30:29.000Z
kernel/kernel/i386/iopb.c
eyadhamdan4/xMach
38272d98114715a10e77c2c014e16c9782f7807c
[ "BSD-3-Clause" ]
4
2015-02-28T20:56:54.000Z
2022-01-04T07:40:17.000Z
kernel/kernel/i386/iopb.c
eyadhamdan4/xMach
38272d98114715a10e77c2c014e16c9782f7807c
[ "BSD-3-Clause" ]
8
2015-02-15T11:32:02.000Z
2021-06-08T00:55:06.000Z
/* * Mach Operating System * Copyright (c) 1993,1992,1991,1990 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* * Code to manipulate IO permission bitmaps. */ #include <mach/boolean.h> #include <mach/kern_return.h> #include <ipc/ipc_port.h> #include <kern/kalloc.h> #include <kern/lock.h> #include <kern/queue.h> #include <kern/thread.h> #include <device/dev_hdr.h> #include "io_port.h" #include "iopb.h" #include "seg.h" #include "gdt.h" /* * A set of ports for an IO device. */ struct io_port { mach_device_t device; /* Mach device */ queue_chain_t dev_list; /* link in device list */ queue_chain_t io_use_list; /* List of threads that use it */ io_reg_t *io_port_list; /* list of IO ports that use it */ /* list ends with IO_REG_NULL */ }; typedef struct io_port *io_port_t; /* * Lookup table for device -> io_port mapping * (a linked list - I don't expect too many) */ queue_head_t device_to_io_port_list; /* * Cross-reference: * all threads that have IO ports mapped * all IO ports that have threads mapped */ struct io_use { queue_chain_t psq; /* Links from port set */ queue_chain_t tsq; /* links from tss */ io_port_t ps; /* Port set */ iopb_tss_t ts; /* Task segment */ }; typedef struct io_use *io_use_t; /* * Big lock for the whole mess. */ decl_simple_lock_data(, iopb_lock) /* * Initialize the package. */ void iopb_init(void) { queue_init(&device_to_io_port_list); simple_lock_init(&iopb_lock); } /* * Initialize bitmap (set all bits to OFF == 1) */ void io_bitmap_init( isa_iopb bp, boolean_t on_off) { register unsigned char *b = bp; register int s; unsigned char c; /* * Disallow access to ports 0x00 .. 0xff */ for (s = 0; s < (0xff+1)/8; s++) { *b++ = ~0; /* no access */ } if (on_off) c = 0; else c = ~0; for (; s < sizeof(isa_iopb); s++) { *b++ = c; } } /* * Set selected bits in bitmap to ON == 0 */ void io_bitmap_set( isa_iopb bp, io_reg_t *bit_list) { io_reg_t io_bit; while ((io_bit = *bit_list++) != IO_REG_NULL) { bp[io_bit>>3] &= ~(1 << (io_bit & 0x7)); } } /* * Set selected bits in bitmap to OFF == 1 */ void io_bitmap_clear( isa_iopb bp, io_reg_t *bit_list) { io_reg_t io_bit; while ((io_bit = *bit_list++) != IO_REG_NULL) { bp[io_bit>>3] |= (1 << (io_bit & 0x7)); } } /* * Lookup an io-port set by device */ io_port_t device_to_io_port_lookup( mach_device_t device) { register io_port_t io_port; queue_iterate(&device_to_io_port_list, io_port, io_port_t, dev_list) { if (io_port->device == device) { return io_port; } } return 0; } /* * [exported] * Create an io_port set */ void io_port_create( mach_device_t device, io_reg_t *io_port_list) { register io_port_t io_port; io_port = (io_port_t) kalloc(sizeof(struct io_port)); simple_lock(&iopb_lock); if (device_to_io_port_lookup(device) != 0) { simple_unlock(&iopb_lock); kfree((vm_offset_t) io_port, sizeof(struct io_port)); return; } io_port->device = device; queue_init(&io_port->io_use_list); io_port->io_port_list = io_port_list; /* * Enter in lookup list. */ queue_enter(&device_to_io_port_list, io_port, io_port_t, dev_list); simple_unlock(&iopb_lock); } /* * [exported] * Destroy an io port set, removing any IO mappings. */ void io_port_destroy( mach_device_t device) { io_port_t io_port; io_use_t iu; simple_lock(&iopb_lock); io_port = device_to_io_port_lookup(device); if (io_port == 0) { simple_unlock(&iopb_lock); return; } queue_iterate(&io_port->io_use_list, iu, io_use_t, psq) { iopb_tss_t io_tss; io_tss = iu->ts; io_bitmap_clear(io_tss->bitmap, io_port->io_port_list); queue_remove(&io_tss->io_port_list, iu, io_use_t, tsq); } queue_remove(&device_to_io_port_list, io_port, io_port_t, dev_list); simple_unlock(&iopb_lock); while (!queue_empty(&io_port->io_use_list)) { iu = (io_use_t) queue_first(&io_port->io_use_list); queue_remove(&io_port->io_use_list, iu, io_use_t, psq); kfree((vm_offset_t)iu, sizeof(struct io_use)); } kfree((vm_offset_t)io_port, sizeof(struct io_port)); } /* * Initialize an IO TSS. */ void io_tss_init( iopb_tss_t io_tss, boolean_t access_all) /* allow access or not */ { vm_offset_t addr = (vm_offset_t) io_tss; vm_size_t size = (char *)&io_tss->barrier - (char *)io_tss; bzero(&io_tss->tss, sizeof(struct i386_tss)); io_tss->tss.io_bit_map_offset = (char *)&io_tss->bitmap - (char *)io_tss; io_tss->tss.ss0 = KERNEL_DS; io_bitmap_init(io_tss->bitmap, access_all); io_tss->barrier = ~0; queue_init(&io_tss->io_port_list); io_tss->iopb_desc[0] = ((size-1) & 0xffff) | ((addr & 0xffff) << 16); io_tss->iopb_desc[1] = ((addr & 0x00ff0000) >> 16) | ((ACC_TSS|ACC_PL_K|ACC_P) << 8) | ((size-1) & 0x000f0000) | (addr & 0xff000000); } /* * [exported] * Create an IOPB_TSS */ iopb_tss_t iopb_create(void) { register iopb_tss_t ts; ts = (iopb_tss_t) kalloc(sizeof (struct iopb_tss)); io_tss_init(ts, TRUE); /* XXX */ return ts; } /* * [exported] * Destroy an IOPB_TSS */ void iopb_destroy( iopb_tss_t io_tss) { io_use_t iu; io_port_t io_port; simple_lock(&iopb_lock); queue_iterate(&io_tss->io_port_list, iu, io_use_t, tsq) { io_port = iu->ps; /* skip bitmap clear - entire bitmap will vanish */ queue_remove(&io_port->io_use_list, iu, io_use_t, psq); } simple_unlock(&iopb_lock); while (!queue_empty(&io_tss->io_port_list)) { iu = (io_use_t) queue_first(&io_tss->io_port_list); queue_remove(&io_tss->io_port_list, iu, io_use_t, tsq); kfree((vm_offset_t)iu, sizeof(struct io_use)); } kfree((vm_offset_t)io_tss, sizeof(struct iopb_tss)); } /* * Add an IO mapping to a thread. */ kern_return_t i386_io_port_add( thread_t thread, mach_device_t device) { pcb_t pcb; iopb_tss_t io_tss, new_io_tss; io_port_t io_port; io_use_t iu, old_iu; if (thread == THREAD_NULL || device == DEVICE_NULL) return KERN_INVALID_ARGUMENT; pcb = thread->pcb; new_io_tss = 0; iu = (io_use_t) kalloc(sizeof(struct io_use)); Retry: simple_lock(&iopb_lock); /* find the io_port_t for the device */ io_port = device_to_io_port_lookup(device); if (io_port == 0) { /* * Device does not have IO ports available. */ simple_unlock(&iopb_lock); if (new_io_tss) kfree((vm_offset_t)new_io_tss, sizeof(struct iopb_tss)); kfree((vm_offset_t) iu, sizeof(struct io_use)); return KERN_INVALID_ARGUMENT; } /* Have the IO port. */ /* Make sure the thread has a TSS. */ simple_lock(&pcb->lock); io_tss = pcb->ims.io_tss; if (io_tss == 0) { if (new_io_tss == 0) { /* * Allocate an IO-tss. */ simple_unlock(&pcb->lock); simple_unlock(&iopb_lock); new_io_tss = (iopb_tss_t) kalloc(sizeof(struct iopb_tss)); io_tss_init(new_io_tss, TRUE); /* XXX */ goto Retry; } io_tss = new_io_tss; pcb->ims.io_tss = io_tss; new_io_tss = 0; } /* * Have io_port and io_tss. * See whether device is already mapped. */ queue_iterate(&io_tss->io_port_list, old_iu, io_use_t, tsq) { if (old_iu->ps == io_port) { /* * Already mapped. */ simple_unlock(&pcb->lock); simple_unlock(&iopb_lock); kfree((vm_offset_t)iu, sizeof(struct io_use)); if (new_io_tss) kfree((vm_offset_t)new_io_tss, sizeof(struct iopb_tss)); return KERN_SUCCESS; } } /* * Add mapping. */ iu->ps = io_port; iu->ts = io_tss; queue_enter(&io_port->io_use_list, iu, io_use_t, psq); queue_enter(&io_tss->io_port_list, iu, io_use_t, tsq); io_bitmap_set(io_tss->bitmap, io_port->io_port_list); simple_unlock(&pcb->lock); simple_unlock(&iopb_lock); if (new_io_tss) kfree((vm_offset_t)new_io_tss, sizeof(struct iopb_tss)); return KERN_SUCCESS; } /* * Remove an IO mapping from a thread. */ kern_return_t i386_io_port_remove(thread, device) thread_t thread; mach_device_t device; { pcb_t pcb; iopb_tss_t io_tss; io_port_t io_port; io_use_t iu; if (thread == THREAD_NULL || device == DEVICE_NULL) return KERN_INVALID_ARGUMENT; pcb = thread->pcb; simple_lock(&iopb_lock); /* find the io_port_t for the device */ io_port = device_to_io_port_lookup(device); if (io_port == 0) { /* * Device does not have IO ports available. */ simple_unlock(&iopb_lock); return KERN_INVALID_ARGUMENT; } simple_lock(&pcb->lock); io_tss = pcb->ims.io_tss; if (io_tss == 0) { simple_unlock(&pcb->lock); simple_unlock(&iopb_lock); return KERN_INVALID_ARGUMENT; /* not mapped */ } /* * Find the mapping. */ queue_iterate(&io_tss->io_port_list, iu, io_use_t, tsq) { if (iu->ps == io_port) { /* * Found mapping. Remove it. */ io_bitmap_clear(io_tss->bitmap, io_port->io_port_list); queue_remove(&io_port->io_use_list, iu, io_use_t, psq); queue_remove(&io_tss->io_port_list, iu, io_use_t, tsq); simple_unlock(&pcb->lock); simple_unlock(&iopb_lock); kfree((vm_offset_t)iu, sizeof(struct io_use)); return KERN_SUCCESS; } } /* * No mapping. */ return KERN_INVALID_ARGUMENT; } /* * Return the IO ports mapped into a thread. */ extern ipc_port_t mach_convert_device_to_port(/* device_t */); kern_return_t i386_io_port_list(thread, list, list_count) thread_t thread; mach_device_t **list; unsigned int *list_count; { register pcb_t pcb; register iopb_tss_t io_tss; unsigned int count, alloc_count; mach_device_t *devices; vm_size_t size_needed, size; vm_offset_t addr; int i; if (thread == THREAD_NULL) return KERN_INVALID_ARGUMENT; pcb = thread->pcb; alloc_count = 16; /* a guess */ do { size_needed = alloc_count * sizeof(ipc_port_t); if (size_needed <= size) break; if (size != 0) kfree(addr,size); assert(size_needed > 0); size = size_needed; addr = kalloc(size); if (addr == 0) return KERN_RESOURCE_SHORTAGE; devices = (mach_device_t *)addr; count = 0; simple_lock(&iopb_lock); simple_lock(&pcb->lock); io_tss = pcb->ims.io_tss; if (io_tss != 0) { register io_use_t iu; queue_iterate(&io_tss->io_port_list, iu, io_use_t, tsq) { if (++count < alloc_count) { *devices = iu->ps->device; device_reference(*devices); devices++; } } } simple_unlock(&pcb->lock); simple_unlock(&iopb_lock); } while (count > alloc_count); if (count == 0) { /* * No IO ports */ *list = 0; *list_count = 0; if (size != 0) kfree(addr, size); } else { /* * If we allocated too much, must copy. */ size_needed = count * sizeof(ipc_port_t); if (size_needed < size) { vm_offset_t new_addr; new_addr = kalloc(size_needed); if (new_addr == 0) { for (i = 0; i < count; i++) device_deallocate(devices[i]); kfree(addr, size); return KERN_RESOURCE_SHORTAGE; } bcopy((void *)addr, (void *)new_addr, size_needed); kfree(addr, size); devices = (mach_device_t *)new_addr; } for (i = 0; i < count; i++) ((ipc_port_t *)devices)[i] = mach_convert_device_to_port(devices[i]); } *list = devices; *list_count = count; return KERN_SUCCESS; } /* * Check whether an IO device is mapped to a particular thread. * Used to support the 'iopl' device automatic mapping. */ boolean_t iopb_check_mapping(thread, device) thread_t thread; mach_device_t device; { pcb_t pcb; io_port_t io_port; io_use_t iu; pcb = thread->pcb; simple_lock(&iopb_lock); /* Find the io port for the device */ io_port = device_to_io_port_lookup(device); if (io_port == 0) { simple_unlock(&iopb_lock); return FALSE; } /* Look up the mapping in the device`s mapping list. */ queue_iterate(&io_port->io_use_list, iu, io_use_t, psq) { if (iu->ts == pcb->ims.io_tss) { /* * Device is mapped. */ simple_unlock(&iopb_lock); return TRUE; } } simple_unlock(&iopb_lock); return FALSE; }
20.918831
75
0.669797
fdc671a20563e24a43b8961ddaaf1733b34baa9a
1,884
h
C
System/Library/PrivateFrameworks/HomeSharing.framework/HSRequest.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
12
2019-06-02T02:42:41.000Z
2021-04-13T07:22:20.000Z
System/Library/PrivateFrameworks/HomeSharing.framework/HSRequest.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/HomeSharing.framework/HSRequest.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
3
2019-06-11T02:46:10.000Z
2019-12-21T14:58:16.000Z
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:45:32 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/HomeSharing.framework/HomeSharing * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @class NSDictionary, NSString, NSData; @interface HSRequest : NSObject { NSDictionary* _arguments; BOOL _concurrent; BOOL _acceptsGzipEncoding; NSString* _action; long long _method; NSData* _bodyData; } @property (nonatomic,readonly) NSString * action; //@synthesize action=_action - In the implementation block @property (getter=isConcurrent,nonatomic,readonly) BOOL concurrent; //@synthesize concurrent=_concurrent - In the implementation block @property (assign,nonatomic) long long method; //@synthesize method=_method - In the implementation block @property (nonatomic,readonly) double timeoutInterval; @property (nonatomic,copy) NSData * bodyData; //@synthesize bodyData=_bodyData - In the implementation block @property (assign,nonatomic) BOOL acceptsGzipEncoding; //@synthesize acceptsGzipEncoding=_acceptsGzipEncoding - In the implementation block +(id)request; -(NSData *)bodyData; -(double)timeoutInterval; -(void)setMethod:(long long)arg1 ; -(BOOL)acceptsGzipEncoding; -(id)canonicalResponseForResponse:(id)arg1 ; -(id)requestURLForBaseURL:(id)arg1 sessionID:(unsigned)arg2 ; -(id)URLRequestForBaseURL:(id)arg1 sessionID:(unsigned)arg2 ; -(void)setAcceptsGzipEncoding:(BOOL)arg1 ; -(void)setValue:(id)arg1 forArgument:(id)arg2 ; -(void)setBodyData:(NSData *)arg1 ; -(BOOL)isConcurrent; -(id)description; -(NSString *)action; -(id)initWithAction:(id)arg1 ; -(long long)method; @end
40.085106
165
0.721338
a9509d7f0357d9c52dad500d16160e72422e3d17
22,269
c
C
3pp/sources/packages/dialog/create-1.2-20140112-patch/dialog-1.2-20140112-new/fselect.c
radix-platform/build-system
d1bd9ba07d23f583be162866fdd13dedcda9afcf
[ "BSD-Source-Code" ]
3
2016-05-31T22:02:05.000Z
2019-11-25T19:24:00.000Z
3pp/sources/packages/dialog/create-1.2-20140112-patch/dialog-1.2-20140112-new/fselect.c
radix-platform/build-system
d1bd9ba07d23f583be162866fdd13dedcda9afcf
[ "BSD-Source-Code" ]
null
null
null
3pp/sources/packages/dialog/create-1.2-20140112-patch/dialog-1.2-20140112-new/fselect.c
radix-platform/build-system
d1bd9ba07d23f583be162866fdd13dedcda9afcf
[ "BSD-Source-Code" ]
null
null
null
/* * $Id: fselect.c,v 1.93 2012/12/30 20:52:25 tom Exp $ * * fselect.c -- implements the file-selector box * * Copyright 2000-2011,2012 Thomas E. Dickey * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License, version 2.1 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to * Free Software Foundation, Inc. * 51 Franklin St., Fifth Floor * Boston, MA 02110, USA. */ #include <dialog.h> #include <dlg_keys.h> #include <sys/types.h> #include <sys/stat.h> #if HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # if HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # if HAVE_SYS_DIR_H # include <sys/dir.h> # endif # if HAVE_NDIR_H # include <ndir.h> # endif #endif # if defined(_FILE_OFFSET_BITS) && defined(HAVE_STRUCT_DIRENT64) # if !defined(_LP64) && (_FILE_OFFSET_BITS == 64) # define DIRENT struct dirent64 # else # define DIRENT struct dirent # endif # else # define DIRENT struct dirent # endif #define EXT_WIDE 1 #define HDR_HIGH 1 #define BTN_HIGH (1 + 2 * MARGIN) /* Ok/Cancel, also input-box */ #define MIN_HIGH (HDR_HIGH - MARGIN + (BTN_HIGH * 2) + 4 * MARGIN) #define MIN_WIDE (2 * MAX(dlg_count_columns(d_label), dlg_count_columns(f_label)) + 6 * MARGIN + 2 * EXT_WIDE) #define MOUSE_D (KEY_MAX + 0) #define MOUSE_F (KEY_MAX + 10000) #define MOUSE_T (KEY_MAX + 20000) typedef enum { sDIRS = -3 ,sFILES = -2 ,sTEXT = -1 } STATES; typedef struct { WINDOW *par; /* parent window */ WINDOW *win; /* this window */ int length; /* length of the data[] array */ int offset; /* index of first item on screen */ int choice; /* index of the selection */ int mousex; /* base of mouse-code return-values */ unsigned allocd; char **data; } LIST; typedef struct { int length; char **data; } MATCH; static void init_list(LIST * list, WINDOW *par, WINDOW *win, int mousex) { list->par = par; list->win = win; list->length = 0; list->offset = 0; list->choice = 0; list->mousex = mousex; list->allocd = 0; list->data = 0; dlg_mouse_mkbigregion(getbegy(win), getbegx(win), getmaxy(win), getmaxx(win), mousex, 1, 1, 1 /* by lines */ ); } static char * leaf_of(char *path) { char *leaf = strrchr(path, '/'); if (leaf != 0) leaf++; else leaf = path; return leaf; } static char * data_of(LIST * list) { if (list != 0 && list->data != 0) return list->data[list->choice]; return 0; } static void free_list(LIST * list, int reinit) { int n; if (list->data != 0) { for (n = 0; list->data[n] != 0; n++) free(list->data[n]); free(list->data); list->data = 0; } if (reinit) init_list(list, list->par, list->win, list->mousex); } static void add_to_list(LIST * list, char *text) { unsigned need; need = (unsigned) (list->length + 1); if (need + 1 > list->allocd) { list->allocd = 2 * (need + 1); if (list->data == 0) { list->data = dlg_malloc(char *, list->allocd); } else { list->data = dlg_realloc(char *, list->allocd, list->data); } assert_ptr(list->data, "add_to_list"); } list->data[list->length++] = dlg_strclone(text); list->data[list->length] = 0; } static void keep_visible(LIST * list) { int high = getmaxy(list->win); if (list->choice < list->offset) { list->offset = list->choice; } if (list->choice - list->offset >= high) list->offset = list->choice - high + 1; } #define Value(c) (int)((c) & 0xff) static int find_choice(char *target, LIST * list) { int n; int choice = list->choice; int len_1, len_2, cmp_1, cmp_2; if (*target == 0) { list->choice = 0; } else { /* find the match with the longest length. If more than one has the * same length, choose the one with the closest match of the final * character. */ len_1 = 0; cmp_1 = 256; for (n = 0; n < list->length; n++) { char *a = target; char *b = list->data[n]; len_2 = 0; while ((*a != 0) && (*b != 0) && (*a == *b)) { a++; b++; len_2++; } cmp_2 = Value(*a) - Value(*b); if (cmp_2 < 0) cmp_2 = -cmp_2; if ((len_2 > len_1) || (len_1 == len_2 && cmp_2 < cmp_1)) { len_1 = len_2; cmp_1 = cmp_2; list->choice = n; } } } if (choice != list->choice) { keep_visible(list); } return (choice != list->choice); } static void display_list(LIST * list) { int n; int x; int y; int top; int bottom; if (list->win != 0) { dlg_attr_clear(list->win, getmaxy(list->win), getmaxx(list->win), item_attr); for (n = list->offset; n < list->length && list->data[n]; n++) { y = n - list->offset; if (y >= getmaxy(list->win)) break; (void) wmove(list->win, y, 0); if (n == list->choice) (void) wattrset(list->win, item_selected_attr); (void) waddstr(list->win, list->data[n]); (void) wattrset(list->win, item_attr); } (void) wattrset(list->win, item_attr); getparyx(list->win, y, x); top = y - 1; bottom = y + getmaxy(list->win); dlg_draw_scrollbar(list->par, (long) list->offset, (long) list->offset, (long) (list->offset + getmaxy(list->win)), (long) (list->length), x + 1, x + getmaxx(list->win), top, bottom, menubox_border2_attr, menubox_border_attr); (void) wmove(list->win, list->choice - list->offset, 0); (void) wnoutrefresh(list->win); } } /* FIXME: see arrows.c * This workaround is used to allow two lists to have scroll-tabs at the same * time, by reassigning their return-values to be different. Just for * readability, we use the names of keys with similar connotations, though all * that is really required is that they're distinct, so we can put them in a * switch statement. */ static void fix_arrows(LIST * list) { int x; int y; int top; int right; int bottom; if (list->win != 0) { getparyx(list->win, y, x); top = y - 1; right = getmaxx(list->win); bottom = y + getmaxy(list->win); mouse_mkbutton(top, x, right, ((list->mousex == MOUSE_D) ? KEY_PREVIOUS : KEY_PPAGE)); mouse_mkbutton(bottom, x, right, ((list->mousex == MOUSE_D) ? KEY_NEXT : KEY_NPAGE)); } } static int show_list(char *target, LIST * list, int keep) { int changed = keep || find_choice(target, list); display_list(list); return changed; } /* * Highlight the closest match to 'target' in the given list, setting offset * to match. */ static int show_both_lists(char *input, LIST * d_list, LIST * f_list, int keep) { char *leaf = leaf_of(input); return show_list(leaf, d_list, keep) | show_list(leaf, f_list, keep); } /* * Move up/down in the given list */ static bool change_list(int choice, LIST * list) { if (data_of(list) != 0) { int last = list->length - 1; choice += list->choice; if (choice < 0) choice = 0; if (choice > last) choice = last; list->choice = choice; keep_visible(list); display_list(list); return TRUE; } return FALSE; } static void scroll_list(int direction, LIST * list) { if (data_of(list) != 0) { int length = getmaxy(list->win); if (change_list(direction * length, list)) return; } beep(); } static int compar(const void *a, const void *b) { return strcmp(*(const char *const *) a, *(const char *const *) b); } static void match(char *name, LIST * d_list, LIST * f_list, MATCH * match_list) { char *test = leaf_of(name); size_t test_len = strlen(test); char **matches = dlg_malloc(char *, (size_t) (d_list->length + f_list->length)); size_t data_len = 0; int i; for (i = 2; i < d_list->length; i++) { if (strncmp(test, d_list->data[i], test_len) == 0) { matches[data_len++] = d_list->data[i]; } } for (i = 0; i < f_list->length; i++) { if (strncmp(test, f_list->data[i], test_len) == 0) { matches[data_len++] = f_list->data[i]; } } matches = dlg_realloc(char *, data_len + 1, matches); match_list->data = matches; match_list->length = (int) data_len; } static void free_match(MATCH * match_list) { free(match_list->data); match_list->length = 0; } static int complete(char *name, LIST * d_list, LIST * f_list, char **buff_ptr) { MATCH match_list; char *test; size_t test_len; size_t i; int j; char *buff; match(name, d_list, f_list, &match_list); if (match_list.length == 0) { *buff_ptr = NULL; return 0; } test = match_list.data[0]; test_len = strlen(test); buff = dlg_malloc(char, test_len + 2); if (match_list.length == 1) { strcpy(buff, test); i = test_len; if (test == data_of(d_list)) { buff[test_len] = '/'; i++; } } else { for (i = 0; i < test_len; i++) { char test_char = test[i]; if (test_char == '\0') break; for (j = 0; j < match_list.length; j++) { if (match_list.data[j][i] != test_char) { break; } } if (j == match_list.length) { (buff)[i] = test_char; } else break; } buff = dlg_realloc(char, i + 1, buff); } free_match(&match_list); buff[i] = '\0'; *buff_ptr = buff; return (i != 0); } static bool fill_lists(char *current, char *input, LIST * d_list, LIST * f_list, int keep) { bool result = TRUE; bool rescan = FALSE; DIR *dp; DIRENT *de; struct stat sb; int n; char path[MAX_LEN + 1]; char *leaf; /* check if we've updated the lists */ for (n = 0; current[n] && input[n]; n++) { if (current[n] != input[n]) break; } if (current[n] == input[n]) { result = FALSE; rescan = (n == 0 && d_list->length == 0); } else if (strchr(current + n, '/') == 0 && strchr(input + n, '/') == 0) { result = show_both_lists(input, d_list, f_list, keep); } else { rescan = TRUE; } if (rescan) { size_t have = strlen(input); if (have > MAX_LEN) have = MAX_LEN; memcpy(current, input, have); current[have] = '\0'; /* refill the lists */ free_list(d_list, TRUE); free_list(f_list, TRUE); memcpy(path, current, have); path[have] = '\0'; if ((leaf = strrchr(path, '/')) != 0) { *++leaf = 0; } else { strcpy(path, "./"); leaf = path + strlen(path); } dlg_trace_msg("opendir '%s'\n", path); if ((dp = opendir(path)) != 0) { while ((de = readdir(dp)) != 0) { strncpy(leaf, de->d_name, NAMLEN(de))[NAMLEN(de)] = 0; if (stat(path, &sb) == 0) { if ((sb.st_mode & S_IFMT) == S_IFDIR) add_to_list(d_list, leaf); else if (f_list->win) add_to_list(f_list, leaf); } } (void) closedir(dp); /* sort the lists */ if (d_list->data != 0 && d_list->length > 1) { qsort(d_list->data, (size_t) d_list->length, sizeof(d_list->data[0]), compar); } if (f_list->data != 0 && f_list->length > 1) { qsort(f_list->data, (size_t) f_list->length, sizeof(f_list->data[0]), compar); } } (void) show_both_lists(input, d_list, f_list, FALSE); d_list->offset = d_list->choice; f_list->offset = f_list->choice; result = TRUE; } return result; } static bool usable_state(int state, LIST * dirs, LIST * files) { bool result; switch (state) { case sDIRS: result = (dirs->win != 0) && (data_of(dirs) != 0); break; case sFILES: result = (files->win != 0) && (data_of(files) != 0); break; default: result = TRUE; break; } return result; } #define which_list() ((state == sFILES) \ ? &f_list \ : ((state == sDIRS) \ ? &d_list \ : 0)) #define NAVIGATE_BINDINGS \ DLG_KEYS_DATA( DLGK_FIELD_NEXT, KEY_RIGHT ), \ DLG_KEYS_DATA( DLGK_FIELD_NEXT, TAB ), \ DLG_KEYS_DATA( DLGK_FIELD_PREV, KEY_BTAB ), \ DLG_KEYS_DATA( DLGK_ITEM_NEXT, KEY_DOWN ), \ DLG_KEYS_DATA( DLGK_ITEM_NEXT, CHR_NEXT ), \ DLG_KEYS_DATA( DLGK_ITEM_NEXT, KEY_NEXT ), \ DLG_KEYS_DATA( DLGK_ITEM_PREV, CHR_PREVIOUS ), \ DLG_KEYS_DATA( DLGK_ITEM_PREV, KEY_UP ), \ DLG_KEYS_DATA( DLGK_PAGE_NEXT, KEY_NPAGE ), \ DLG_KEYS_DATA( DLGK_PAGE_PREV, KEY_PPAGE ) /* * Display a dialog box for entering a filename */ static int dlg_fselect(const char *title, const char *path, int height, int width, int dselect) { /* *INDENT-OFF* */ static DLG_KEYS_BINDING binding[] = { HELPKEY_BINDINGS, ENTERKEY_BINDINGS, NAVIGATE_BINDINGS, END_KEYS_BINDING }; static DLG_KEYS_BINDING binding2[] = { INPUTSTR_BINDINGS, HELPKEY_BINDINGS, ENTERKEY_BINDINGS, NAVIGATE_BINDINGS, END_KEYS_BINDING }; /* *INDENT-ON* */ #ifdef KEY_RESIZE int old_height = height; int old_width = width; bool resized = FALSE; #endif int tbox_y, tbox_x, tbox_width, tbox_height; int dbox_y, dbox_x, dbox_width, dbox_height; int fbox_y, fbox_x, fbox_width, fbox_height; int show_buttons = TRUE; int offset = 0; int key = 0; int fkey = FALSE; int code; int result = DLG_EXIT_UNKNOWN; int state = dialog_vars.default_button >= 0 ? dlg_default_button() : sTEXT; int button; int first = (state == sTEXT); int first_trace = TRUE; char *input; char *completed; char current[MAX_LEN + 1]; WINDOW *dialog = 0; WINDOW *w_text = 0; WINDOW *w_work = 0; const char **buttons = dlg_ok_labels(); const char *d_label = _("Directories"); const char *f_label = _("Files"); char *partial = 0; int min_wide = MIN_WIDE; int min_items = height ? 0 : 4; LIST d_list, f_list; dlg_does_output(); /* Set up the initial value */ input = dlg_set_result(path); offset = (int) strlen(input); *current = 0; dlg_button_layout(buttons, &min_wide); #ifdef KEY_RESIZE retry: #endif dlg_auto_size(title, (char *) 0, &height, &width, 6, 25); height += MIN_HIGH + min_items; if (width < min_wide) width = min_wide; dlg_print_size(height, width); dlg_ctl_size(height, width); dialog = dlg_new_window(height + 1, width, dlg_box_y_ordinate(height), dlg_box_x_ordinate(width)); dlg_register_window(dialog, "fselect", binding); dlg_register_buttons(dialog, "fselect", buttons); dlg_mouse_setbase(0, 0); dlg_draw_box2(dialog, 0, 0, height + 1, width, dialog_attr, border_attr, border2_attr); dlg_draw_bottom_box2(dialog, border_attr, border2_attr, dialog_attr); dlg_draw_title(dialog, title); (void) wattrset(dialog, dialog_attr); /* Draw the input field box */ tbox_height = 1; tbox_width = width - (4 * MARGIN + 2); tbox_y = height - (BTN_HIGH * 2) + MARGIN + 1; tbox_x = (width - tbox_width) / 2; w_text = derwin(dialog, tbox_height, tbox_width, tbox_y, tbox_x); if (w_text == 0) { result = DLG_EXIT_ERROR; goto finish; } (void) keypad(w_text, TRUE); dlg_draw_box(dialog, tbox_y - MARGIN, tbox_x - MARGIN, (2 * MARGIN + 1), tbox_width + (MARGIN + EXT_WIDE), menubox_border_attr, menubox_border2_attr); dlg_mouse_mkbigregion(getbegy(dialog) + tbox_y - MARGIN, getbegx(dialog) + tbox_x - MARGIN, 1 + (2 * MARGIN), tbox_width + (MARGIN + EXT_WIDE), MOUSE_T, 1, 1, 3 /* doesn't matter */ ); dlg_register_window(w_text, "fselect2", binding2); /* Draw the directory listing box */ if (dselect) dbox_width = (width - (6 * MARGIN)); else dbox_width = (width - (6 * MARGIN + 2 * EXT_WIDE)) / 2; dbox_height = height - MIN_HIGH; dbox_y = (2 * MARGIN + 2); dbox_x = tbox_x; w_work = derwin(dialog, dbox_height, dbox_width, dbox_y, dbox_x); if (w_work == 0) { result = DLG_EXIT_ERROR; goto finish; } (void) keypad(w_work, TRUE); (void) mvwaddstr(dialog, dbox_y - (MARGIN + 1), dbox_x - MARGIN, d_label); dlg_draw_box(dialog, dbox_y - MARGIN, dbox_x - MARGIN, dbox_height + (MARGIN + 1), dbox_width + (MARGIN + 1), menubox_border_attr, menubox_border2_attr); init_list(&d_list, dialog, w_work, MOUSE_D); if (!dselect) { /* Draw the filename listing box */ fbox_height = dbox_height; fbox_width = dbox_width; fbox_y = dbox_y; fbox_x = tbox_x + dbox_width + (2 * MARGIN); w_work = derwin(dialog, fbox_height, fbox_width, fbox_y, fbox_x); if (w_work == 0) { result = DLG_EXIT_ERROR; goto finish; } (void) keypad(w_work, TRUE); (void) mvwaddstr(dialog, fbox_y - (MARGIN + 1), fbox_x - MARGIN, f_label); dlg_draw_box(dialog, fbox_y - MARGIN, fbox_x - MARGIN, fbox_height + (MARGIN + 1), fbox_width + (MARGIN + 1), menubox_border_attr, menubox_border2_attr); init_list(&f_list, dialog, w_work, MOUSE_F); } else { memset(&f_list, 0, sizeof(f_list)); } while (result == DLG_EXIT_UNKNOWN) { if (fill_lists(current, input, &d_list, &f_list, state < sTEXT)) show_buttons = TRUE; #ifdef KEY_RESIZE if (resized) { resized = FALSE; dlg_show_string(w_text, input, offset, inputbox_attr, 0, 0, tbox_width, (bool) 0, (bool) first); } #endif /* * The last field drawn determines where the cursor is shown: */ if (show_buttons) { show_buttons = FALSE; button = (state < 0) ? 0 : state; dlg_draw_buttons(dialog, height - 1, 0, buttons, button, FALSE, width); } if (first_trace) { first_trace = FALSE; dlg_trace_win(dialog); } if (state < 0) { switch (state) { case sTEXT: dlg_set_focus(dialog, w_text); break; case sFILES: dlg_set_focus(dialog, f_list.win); break; case sDIRS: dlg_set_focus(dialog, d_list.win); break; } } if (first) { (void) wrefresh(dialog); } else { fix_arrows(&d_list); fix_arrows(&f_list); key = dlg_mouse_wgetch((state == sTEXT) ? w_text : dialog, &fkey); if (dlg_result_key(key, fkey, &result)) break; } if (!fkey && key == ' ') { key = DLGK_SELECT; fkey = TRUE; } if (fkey) { switch (key) { case DLGK_MOUSE(KEY_PREVIOUS): state = sDIRS; scroll_list(-1, which_list()); continue; case DLGK_MOUSE(KEY_NEXT): state = sDIRS; scroll_list(1, which_list()); continue; case DLGK_MOUSE(KEY_PPAGE): state = sFILES; scroll_list(-1, which_list()); continue; case DLGK_MOUSE(KEY_NPAGE): state = sFILES; scroll_list(1, which_list()); continue; case DLGK_PAGE_PREV: scroll_list(-1, which_list()); continue; case DLGK_PAGE_NEXT: scroll_list(1, which_list()); continue; case DLGK_ITEM_PREV: if (change_list(-1, which_list())) continue; /* FALLTHRU */ case DLGK_FIELD_PREV: show_buttons = TRUE; do { state = dlg_prev_ok_buttonindex(state, sDIRS); } while (!usable_state(state, &d_list, &f_list)); continue; case DLGK_ITEM_NEXT: if (change_list(1, which_list())) continue; /* FALLTHRU */ case DLGK_FIELD_NEXT: show_buttons = TRUE; do { state = dlg_next_ok_buttonindex(state, sDIRS); } while (!usable_state(state, &d_list, &f_list)); continue; case DLGK_SELECT: completed = 0; if (partial != 0) { free(partial); partial = 0; } if (state == sFILES && !dselect) { completed = data_of(&f_list); } else if (state == sDIRS) { completed = data_of(&d_list); } else { if (complete(input, &d_list, &f_list, &partial)) { completed = partial; } } if (completed != 0) { state = sTEXT; show_buttons = TRUE; strcpy(leaf_of(input), completed); offset = (int) strlen(input); dlg_show_string(w_text, input, offset, inputbox_attr, 0, 0, tbox_width, 0, first); if (partial != NULL) { free(partial); partial = 0; } continue; } else { /* if (state < sTEXT) */ (void) beep(); continue; } /* FALLTHRU */ case DLGK_ENTER: result = (state > 0) ? dlg_enter_buttoncode(state) : DLG_EXIT_OK; continue; #ifdef KEY_RESIZE case KEY_RESIZE: /* reset data */ height = old_height; width = old_width; show_buttons = TRUE; *current = 0; resized = TRUE; /* repaint */ dlg_clear(); dlg_del_window(dialog); refresh(); dlg_mouse_free_regions(); goto retry; #endif default: if (key >= DLGK_MOUSE(MOUSE_T)) { state = sTEXT; continue; } else if (key >= DLGK_MOUSE(MOUSE_F)) { if (f_list.win != 0) { state = sFILES; f_list.choice = (key - DLGK_MOUSE(MOUSE_F)) + f_list.offset; display_list(&f_list); } continue; } else if (key >= DLGK_MOUSE(MOUSE_D)) { if (d_list.win != 0) { state = sDIRS; d_list.choice = (key - DLGK_MOUSE(MOUSE_D)) + d_list.offset; display_list(&d_list); } continue; } else if (is_DLGK_MOUSE(key) && (code = dlg_ok_buttoncode(key - M_EVENT)) >= 0) { result = code; continue; } break; } } if (state < 0) { /* Input box selected if we're editing */ int edit = dlg_edit_string(input, &offset, key, fkey, first); if (edit) { dlg_show_string(w_text, input, offset, inputbox_attr, 0, 0, tbox_width, 0, first); first = FALSE; state = sTEXT; } } else if (state >= 0 && (code = dlg_char_to_button(key, buttons)) >= 0) { result = dlg_ok_buttoncode(code); break; } } dlg_unregister_window(w_text); dlg_del_window(dialog); dlg_mouse_free_regions(); free_list(&d_list, FALSE); free_list(&f_list, FALSE); finish: if (partial != 0) free(partial); return result; } /* * Display a dialog box for entering a filename */ int dialog_fselect(const char *title, const char *path, int height, int width) { return dlg_fselect(title, path, height, width, FALSE); } /* * Display a dialog box for entering a directory */ int dialog_dselect(const char *title, const char *path, int height, int width) { return dlg_fselect(title, path, height, width, TRUE); }
23.970936
110
0.614172
65586656e7c751b618bdd0b71fb82d0fcff4c8e2
1,601
h
C
shell/platform/common/client_wrapper/binary_messenger_impl.h
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
5,823
2015-09-20T02:43:18.000Z
2022-03-31T23:38:55.000Z
shell/platform/common/client_wrapper/binary_messenger_impl.h
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
20,081
2015-09-19T16:07:59.000Z
2022-03-31T23:33:26.000Z
shell/platform/common/client_wrapper/binary_messenger_impl.h
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
5,383
2015-09-24T22:49:53.000Z
2022-03-31T14:33:51.000Z
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_ #define FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_ #include <flutter_messenger.h> #include <map> #include <string> #include "include/flutter/binary_messenger.h" namespace flutter { // Wrapper around a FlutterDesktopMessengerRef that implements the // BinaryMessenger API. class BinaryMessengerImpl : public BinaryMessenger { public: explicit BinaryMessengerImpl(FlutterDesktopMessengerRef core_messenger); virtual ~BinaryMessengerImpl(); // Prevent copying. BinaryMessengerImpl(BinaryMessengerImpl const&) = delete; BinaryMessengerImpl& operator=(BinaryMessengerImpl const&) = delete; // |flutter::BinaryMessenger| void Send(const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) const override; // |flutter::BinaryMessenger| void SetMessageHandler(const std::string& channel, BinaryMessageHandler handler) override; private: // Handle for interacting with the C API. FlutterDesktopMessengerRef messenger_; // A map from channel names to the BinaryMessageHandler that should be called // for incoming messages on that channel. std::map<std::string, BinaryMessageHandler> handlers_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_COMMON_CLIENT_WRAPPER_BINARY_MESSENGER_IMPL_H_
31.392157
80
0.770768
6587d846fc80aa997b9d1b64842597b3cb70f9be
1,246
h
C
toolchain/riscv/Linux/lib/gcc/riscv64-unknown-elf/10.2.0/plugin/include/diagnostic-metadata.h
zhiqiang-hu/bl_iot_sdk
154ee677a8cc6a73e6a42a5ff12a8edc71e6d15d
[ "Apache-2.0" ]
21
2015-07-06T21:12:40.000Z
2022-03-18T02:44:13.000Z
toolchain/riscv/Linux/lib/gcc/riscv64-unknown-elf/10.2.0/plugin/include/diagnostic-metadata.h
zhiqiang-hu/bl_iot_sdk
154ee677a8cc6a73e6a42a5ff12a8edc71e6d15d
[ "Apache-2.0" ]
1
2022-03-11T14:00:45.000Z
2022-03-11T14:00:45.000Z
toolchain/riscv/Linux/lib/gcc/riscv64-unknown-elf/10.2.0/plugin/include/diagnostic-metadata.h
zhiqiang-hu/bl_iot_sdk
154ee677a8cc6a73e6a42a5ff12a8edc71e6d15d
[ "Apache-2.0" ]
30
2015-01-11T14:06:10.000Z
2022-03-05T06:10:44.000Z
/* Additional metadata for a diagnostic. Copyright (C) 2019-2020 Free Software Foundation, Inc. Contributed by David Malcolm <dmalcolm@redhat.com> This file is part of GCC. GCC 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 3, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_DIAGNOSTIC_METADATA_H #define GCC_DIAGNOSTIC_METADATA_H /* A bundle of additional metadata that can be associated with a diagnostic. Currently this only supports associating a CWE identifier with a diagnostic. */ class diagnostic_metadata { public: diagnostic_metadata () : m_cwe (0) {} void add_cwe (int cwe) { m_cwe = cwe; } int get_cwe () const { return m_cwe; } private: int m_cwe; }; #endif /* ! GCC_DIAGNOSTIC_METADATA_H */
28.976744
70
0.756822
bdc734d35838c9ff27025c5da57e12df053867df
1,794
h
C
libtbag/mq/nng/supplemental/tls/tls.h
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
21
2016-04-05T06:08:41.000Z
2022-03-28T10:20:22.000Z
libtbag/mq/nng/supplemental/tls/tls.h
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
null
null
null
libtbag/mq/nng/supplemental/tls/tls.h
osom8979/tbag
c31e2d884907d946df0836a70d8d5d69c4bf3c27
[ "MIT" ]
2
2019-07-16T00:37:21.000Z
2021-11-10T06:14:09.000Z
#ifndef NNG_SUPPLEMENTAL_TLS_TLS_H #define NNG_SUPPLEMENTAL_TLS_TLS_H #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdint.h> typedef struct nng_tls_config nng_tls_config; typedef enum nng_tls_mode { NNG_TLS_MODE_CLIENT = 0, NNG_TLS_MODE_SERVER = 1, } nng_tls_mode; typedef enum nng_tls_auth_mode { NNG_TLS_AUTH_MODE_NONE = 0, NNG_TLS_AUTH_MODE_OPTIONAL = 1, NNG_TLS_AUTH_MODE_REQUIRED = 2, } nng_tls_auth_mode; typedef enum nng_tls_version { NNG_TLS_1_0 = 0x301, NNG_TLS_1_1 = 0x302, NNG_TLS_1_2 = 0x303, NNG_TLS_1_3 = 0x304 } nng_tls_version; /*NNG_DECL int nng_tls_config_alloc(nng_tls_config **, nng_tls_mode);*/ /*NNG_DECL void nng_tls_config_hold(nng_tls_config *);*/ /*NNG_DECL void nng_tls_config_free(nng_tls_config *);*/ /*NNG_DECL int nng_tls_config_server_name(nng_tls_config *, const char *);*/ /*NNG_DECL int nng_tls_config_ca_chain( nng_tls_config *, const char *, const char *);*/ /*NNG_DECL int nng_tls_config_own_cert( nng_tls_config *, const char *, const char *, const char *);*/ /*NNG_DECL int nng_tls_config_key(nng_tls_config *, const uint8_t *, size_t);*/ /*NNG_DECL int nng_tls_config_pass(nng_tls_config *, const char *);*/ /*NNG_DECL int nng_tls_config_auth_mode(nng_tls_config *, nng_tls_auth_mode);*/ /*NNG_DECL int nng_tls_config_ca_file(nng_tls_config *, const char *);*/ /*NNG_DECL int nng_tls_config_cert_key_file( nng_tls_config *, const char *, const char *);*/ /*NNG_DECL int nng_tls_config_version( nng_tls_config *, nng_tls_version, nng_tls_version);*/ /*NNG_DECL const char *nng_tls_engine_name(void);*/ /*NNG_DECL const char *nng_tls_engine_description(void);*/ /*NNG_DECL bool nng_tls_engine_fips_mode(void);*/ #ifdef __cplusplus } #endif #endif // NNG_SUPPLEMENTAL_TLS_TLS_H
24.916667
79
0.765886
ec4db6dea479f9bf49f4cbf677008c9a2956a3e0
991
h
C
src/arch/e2k/include/asm/setjmp.h
KutuevVladimir/embox
2f247c2eb7b09cbf60e1f2a6f68db2b766a086bf
[ "BSD-2-Clause" ]
1
2018-07-22T10:47:08.000Z
2018-07-22T10:47:08.000Z
src/arch/e2k/include/asm/setjmp.h
KutuevVladimir/embox
2f247c2eb7b09cbf60e1f2a6f68db2b766a086bf
[ "BSD-2-Clause" ]
null
null
null
src/arch/e2k/include/asm/setjmp.h
KutuevVladimir/embox
2f247c2eb7b09cbf60e1f2a6f68db2b766a086bf
[ "BSD-2-Clause" ]
null
null
null
/** * @file * * @date Mar 16, 2018 * @author Anton Bondarev */ #ifndef SRC_ARCH_E2K_INCLUDE_ASM_SETJMP_H_ #define SRC_ARCH_E2K_INCLUDE_ASM_SETJMP_H_ #include <stdint.h> #define _JBRNUM 7 #if 0 #define E2K_JMBBUFF_THREAD_ (_JBRNUM + 0) #define E2K_JMBBUFF_SIGNAL_ (_JBRNUM + 1) #define E2K_JMBBUFF_SAVE_ (_JBRNUM + 2) #define E2K_JMBBUFF_SIGMASK_ (_JBRNUM + 3) #define E2K_JMBBUFF_KSTTOP (_JBRNUM + 4) #endif #define _JBLEN (_JBRNUM + 5) #ifndef __ASSEMBLER__ struct _jump_regs { uint64_t cr0_hi; uint64_t cr1_lo; uint64_t cr1_hi; uint64_t pcsp_hi; uint64_t psp_hi; uint64_t usd_lo; uint64_t usd_hi; }; typedef uint64_t __jmp_buf[_JBLEN]; #endif /* __ASSEMBLER__ */ #define E2K_JMBBUFF_CR0_HI 0x00 #define E2K_JMBBUFF_CR1_LO 0x08 #define E2K_JMBBUFF_CR1_HI 0x10 #define E2K_JMBBUFF_PCSP_HI 0x18 #define E2K_JMBBUFF_PSP_HI 0x20 #define E2K_JMBBUFF_USD_LO 0x28 #define E2K_JMBBUFF_USD_HI 0x30 #endif /* SRC_ARCH_E2K_INCLUDE_ASM_SETJMP_H_ */
19.431373
47
0.759839
eca4fe85b2a85cd6e32e7548b5d68f110f598544
388
c
C
kernel/rand.c
Syzco/os-concepts-xv6
11664eb68cbb10f1d859334139acd0765e26ec11
[ "Xnet", "X11" ]
null
null
null
kernel/rand.c
Syzco/os-concepts-xv6
11664eb68cbb10f1d859334139acd0765e26ec11
[ "Xnet", "X11" ]
null
null
null
kernel/rand.c
Syzco/os-concepts-xv6
11664eb68cbb10f1d859334139acd0765e26ec11
[ "Xnet", "X11" ]
null
null
null
#define SCHRAND_MAX ((1U << 31) - 1) #define SCHRAND_MULT 214013 #define SCHRAND_CONST 2531011 //Pseudo-random number generator made from a linear congruential generator. //Based on code and constants found at: //https://rosettacode.org/wiki/Linear_congruential_generator int rseed = 707606505; int rand(void) { return rseed = (rseed * SCHRAND_MULT + SCHRAND_CONST) % SCHRAND_MAX; }
25.866667
75
0.765464
08e17c5d807d2310042773f4b6ac7ab19716cde5
570
h
C
client-lite/src/util/safe_int.h
mdavis777/do-client
a815ce512b88e98afe47389d052673ea20bdfc26
[ "MIT" ]
10
2021-03-04T19:27:41.000Z
2021-12-29T13:55:52.000Z
client-lite/src/util/safe_int.h
mdavis777/do-client
a815ce512b88e98afe47389d052673ea20bdfc26
[ "MIT" ]
41
2021-03-02T23:14:51.000Z
2022-03-23T20:49:07.000Z
client-lite/src/util/safe_int.h
mdavis777/do-client
a815ce512b88e98afe47389d052673ea20bdfc26
[ "MIT" ]
7
2021-03-02T23:54:05.000Z
2022-02-11T08:27:54.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #define INTSAFE_E_ARITHMETIC_OVERFLOW ((HRESULT)0x80070216L) // 0x216 = 534 = ERROR_ARITHMETIC_OVERFLOW inline UINT64 UInt64Add(UINT64 ullAugend, UINT64 ullAddend) { THROW_HR_IF(INTSAFE_E_ARITHMETIC_OVERFLOW, (ullAugend + ullAddend) < ullAugend); return (ullAugend + ullAddend); } inline UINT64 UInt64Sub(UINT64 ullMinuend, UINT64 ullSubtrahend) { THROW_HR_IF(INTSAFE_E_ARITHMETIC_OVERFLOW, ullMinuend < ullSubtrahend); return (ullMinuend - ullSubtrahend); }
30
106
0.775439
8609c1a0777b21040f0a8f0127b2bde65fe299ad
21,802
c
C
Code/drivers/net/ppp/ppp_mppe.c
jonggyup/RequestOrganizer
6bb83a6711681d91d49e6f4f405d4a761d182d97
[ "MIT" ]
3
2020-11-06T05:17:03.000Z
2020-11-06T07:32:34.000Z
Code/drivers/net/ppp/ppp_mppe.c
jonggyup/RequestOrganizer
6bb83a6711681d91d49e6f4f405d4a761d182d97
[ "MIT" ]
null
null
null
Code/drivers/net/ppp/ppp_mppe.c
jonggyup/RequestOrganizer
6bb83a6711681d91d49e6f4f405d4a761d182d97
[ "MIT" ]
1
2020-11-06T07:32:55.000Z
2020-11-06T07:32:55.000Z
/* * ppp_mppe.c - interface MPPE to the PPP code. * This version is for use with Linux kernel 2.6.14+ * * By Frank Cusack <fcusack@fcusack.com>. * Copyright (c) 2002,2003,2004 Google, Inc. * All rights reserved. * * License: * Permission to use, copy, modify, and distribute this software and its * documentation is hereby granted, provided that the above copyright * notice appears in all copies. This software is provided without any * warranty, express or implied. * * ALTERNATIVELY, provided that this notice is retained in full, this product * may be distributed under the terms of the GNU General Public License (GPL), * in which case the provisions of the GPL apply INSTEAD OF those given above. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * * Changelog: * 08/12/05 - Matt Domsch <Matt_Domsch@dell.com> * Only need extra skb padding on transmit, not receive. * 06/18/04 - Matt Domsch <Matt_Domsch@dell.com>, Oleg Makarenko <mole@quadra.ru> * Use Linux kernel 2.6 arc4 and sha1 routines rather than * providing our own. * 2/15/04 - TS: added #include <version.h> and testing for Kernel * version before using * MOD_DEC_USAGE_COUNT/MOD_INC_USAGE_COUNT which are * deprecated in 2.6 */ #include <crypto/hash.h> #include <crypto/skcipher.h> #include <linux/err.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/ppp_defs.h> #include <linux/ppp-comp.h> #include <linux/scatterlist.h> #include <asm/unaligned.h> #include "ppp_mppe.h" MODULE_AUTHOR("Frank Cusack <fcusack@fcusack.com>"); MODULE_DESCRIPTION("Point-to-Point Protocol Microsoft Point-to-Point Encryption support"); MODULE_LICENSE("Dual BSD/GPL"); MODULE_ALIAS("ppp-compress-" __stringify(CI_MPPE)); MODULE_SOFTDEP("pre: arc4"); MODULE_VERSION("1.0.2"); static unsigned int setup_sg(struct scatterlist *sg, const void *address, unsigned int length) { sg_set_buf(sg, address, length); return length; } #define SHA1_PAD_SIZE 40 /* * kernel crypto API needs its arguments to be in kmalloc'd memory, not in the module * static data area. That means sha_pad needs to be kmalloc'd. */ struct sha_pad { unsigned char sha_pad1[SHA1_PAD_SIZE]; unsigned char sha_pad2[SHA1_PAD_SIZE]; }; static struct sha_pad *sha_pad; static inline void sha_pad_init(struct sha_pad *shapad) { memset(shapad->sha_pad1, 0x00, sizeof(shapad->sha_pad1)); memset(shapad->sha_pad2, 0xF2, sizeof(shapad->sha_pad2)); } /* * State for an MPPE (de)compressor. */ struct ppp_mppe_state { struct crypto_skcipher *arc4; struct shash_desc *sha1; unsigned char *sha1_digest; unsigned char master_key[MPPE_MAX_KEY_LEN]; unsigned char session_key[MPPE_MAX_KEY_LEN]; unsigned keylen; /* key length in bytes */ /* NB: 128-bit == 16, 40-bit == 8! */ /* If we want to support 56-bit, */ /* the unit has to change to bits */ unsigned char bits; /* MPPE control bits */ unsigned ccount; /* 12-bit coherency count (seqno) */ unsigned stateful; /* stateful mode flag */ int discard; /* stateful mode packet loss flag */ int sanity_errors; /* take down LCP if too many */ int unit; int debug; struct compstat stats; }; /* struct ppp_mppe_state.bits definitions */ #define MPPE_BIT_A 0x80 /* Encryption table were (re)inititalized */ #define MPPE_BIT_B 0x40 /* MPPC only (not implemented) */ #define MPPE_BIT_C 0x20 /* MPPC only (not implemented) */ #define MPPE_BIT_D 0x10 /* This is an encrypted frame */ #define MPPE_BIT_FLUSHED MPPE_BIT_A #define MPPE_BIT_ENCRYPTED MPPE_BIT_D #define MPPE_BITS(p) ((p)[4] & 0xf0) #define MPPE_CCOUNT(p) ((((p)[4] & 0x0f) << 8) + (p)[5]) #define MPPE_CCOUNT_SPACE 0x1000 /* The size of the ccount space */ #define MPPE_OVHD 2 /* MPPE overhead/packet */ #define SANITY_MAX 1600 /* Max bogon factor we will tolerate */ /* * Key Derivation, from RFC 3078, RFC 3079. * Equivalent to Get_Key() for MS-CHAP as described in RFC 3079. */ static void get_new_key_from_sha(struct ppp_mppe_state * state) { crypto_shash_init(state->sha1); crypto_shash_update(state->sha1, state->master_key, state->keylen); crypto_shash_update(state->sha1, sha_pad->sha_pad1, sizeof(sha_pad->sha_pad1)); crypto_shash_update(state->sha1, state->session_key, state->keylen); crypto_shash_update(state->sha1, sha_pad->sha_pad2, sizeof(sha_pad->sha_pad2)); crypto_shash_final(state->sha1, state->sha1_digest); } /* * Perform the MPPE rekey algorithm, from RFC 3078, sec. 7.3. * Well, not what's written there, but rather what they meant. */ static void mppe_rekey(struct ppp_mppe_state * state, int initial_key) { struct scatterlist sg_in[1], sg_out[1]; SKCIPHER_REQUEST_ON_STACK(req, state->arc4); skcipher_request_set_tfm(req, state->arc4); skcipher_request_set_callback(req, 0, NULL, NULL); get_new_key_from_sha(state); if (!initial_key) { crypto_skcipher_setkey(state->arc4, state->sha1_digest, state->keylen); sg_init_table(sg_in, 1); sg_init_table(sg_out, 1); setup_sg(sg_in, state->sha1_digest, state->keylen); setup_sg(sg_out, state->session_key, state->keylen); skcipher_request_set_crypt(req, sg_in, sg_out, state->keylen, NULL); if (crypto_skcipher_encrypt(req)) printk(KERN_WARNING "mppe_rekey: cipher_encrypt failed\n"); } else { memcpy(state->session_key, state->sha1_digest, state->keylen); } if (state->keylen == 8) { /* See RFC 3078 */ state->session_key[0] = 0xd1; state->session_key[1] = 0x26; state->session_key[2] = 0x9e; } crypto_skcipher_setkey(state->arc4, state->session_key, state->keylen); skcipher_request_zero(req); } /* * Allocate space for a (de)compressor. */ static void *mppe_alloc(unsigned char *options, int optlen) { struct ppp_mppe_state *state; struct crypto_shash *shash; unsigned int digestsize; if (optlen != CILEN_MPPE + sizeof(state->master_key) || options[0] != CI_MPPE || options[1] != CILEN_MPPE) goto out; state = kzalloc(sizeof(*state), GFP_KERNEL); if (state == NULL) goto out; state->arc4 = crypto_alloc_skcipher("ecb(arc4)", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(state->arc4)) { state->arc4 = NULL; goto out_free; } shash = crypto_alloc_shash("sha1", 0, 0); if (IS_ERR(shash)) goto out_free; state->sha1 = kmalloc(sizeof(*state->sha1) + crypto_shash_descsize(shash), GFP_KERNEL); if (!state->sha1) { crypto_free_shash(shash); goto out_free; } state->sha1->tfm = shash; state->sha1->flags = 0; digestsize = crypto_shash_digestsize(shash); if (digestsize < MPPE_MAX_KEY_LEN) goto out_free; state->sha1_digest = kmalloc(digestsize, GFP_KERNEL); if (!state->sha1_digest) goto out_free; /* Save keys. */ memcpy(state->master_key, &options[CILEN_MPPE], sizeof(state->master_key)); memcpy(state->session_key, state->master_key, sizeof(state->master_key)); /* * We defer initial key generation until mppe_init(), as mppe_alloc() * is called frequently during negotiation. */ return (void *)state; out_free: kfree(state->sha1_digest); if (state->sha1) { crypto_free_shash(state->sha1->tfm); kzfree(state->sha1); } crypto_free_skcipher(state->arc4); kfree(state); out: return NULL; } /* * Deallocate space for a (de)compressor. */ static void mppe_free(void *arg) { struct ppp_mppe_state *state = (struct ppp_mppe_state *) arg; if (state) { kfree(state->sha1_digest); crypto_free_shash(state->sha1->tfm); kzfree(state->sha1); crypto_free_skcipher(state->arc4); kfree(state); } } /* * Initialize (de)compressor state. */ static int mppe_init(void *arg, unsigned char *options, int optlen, int unit, int debug, const char *debugstr) { struct ppp_mppe_state *state = (struct ppp_mppe_state *) arg; unsigned char mppe_opts; if (optlen != CILEN_MPPE || options[0] != CI_MPPE || options[1] != CILEN_MPPE) return 0; MPPE_CI_TO_OPTS(&options[2], mppe_opts); if (mppe_opts & MPPE_OPT_128) state->keylen = 16; else if (mppe_opts & MPPE_OPT_40) state->keylen = 8; else { printk(KERN_WARNING "%s[%d]: unknown key length\n", debugstr, unit); return 0; } if (mppe_opts & MPPE_OPT_STATEFUL) state->stateful = 1; /* Generate the initial session key. */ mppe_rekey(state, 1); if (debug) { printk(KERN_DEBUG "%s[%d]: initialized with %d-bit %s mode\n", debugstr, unit, (state->keylen == 16) ? 128 : 40, (state->stateful) ? "stateful" : "stateless"); printk(KERN_DEBUG "%s[%d]: keys: master: %*phN initial session: %*phN\n", debugstr, unit, (int)sizeof(state->master_key), state->master_key, (int)sizeof(state->session_key), state->session_key); } /* * Initialize the coherency count. The initial value is not specified * in RFC 3078, but we can make a reasonable assumption that it will * start at 0. Setting it to the max here makes the comp/decomp code * do the right thing (determined through experiment). */ state->ccount = MPPE_CCOUNT_SPACE - 1; /* * Note that even though we have initialized the key table, we don't * set the FLUSHED bit. This is contrary to RFC 3078, sec. 3.1. */ state->bits = MPPE_BIT_ENCRYPTED; state->unit = unit; state->debug = debug; return 1; } static int mppe_comp_init(void *arg, unsigned char *options, int optlen, int unit, int hdrlen, int debug) { /* ARGSUSED */ return mppe_init(arg, options, optlen, unit, debug, "mppe_comp_init"); } /* * We received a CCP Reset-Request (actually, we are sending a Reset-Ack), * tell the compressor to rekey. Note that we MUST NOT rekey for * every CCP Reset-Request; we only rekey on the next xmit packet. * We might get multiple CCP Reset-Requests if our CCP Reset-Ack is lost. * So, rekeying for every CCP Reset-Request is broken as the peer will not * know how many times we've rekeyed. (If we rekey and THEN get another * CCP Reset-Request, we must rekey again.) */ static void mppe_comp_reset(void *arg) { struct ppp_mppe_state *state = (struct ppp_mppe_state *) arg; state->bits |= MPPE_BIT_FLUSHED; } /* * Compress (encrypt) a packet. * It's strange to call this a compressor, since the output is always * MPPE_OVHD + 2 bytes larger than the input. */ static int mppe_compress(void *arg, unsigned char *ibuf, unsigned char *obuf, int isize, int osize) { struct ppp_mppe_state *state = (struct ppp_mppe_state *) arg; SKCIPHER_REQUEST_ON_STACK(req, state->arc4); int proto; int err; struct scatterlist sg_in[1], sg_out[1]; /* * Check that the protocol is in the range we handle. */ proto = PPP_PROTOCOL(ibuf); if (proto < 0x0021 || proto > 0x00fa) return 0; /* Make sure we have enough room to generate an encrypted packet. */ if (osize < isize + MPPE_OVHD + 2) { /* Drop the packet if we should encrypt it, but can't. */ printk(KERN_DEBUG "mppe_compress[%d]: osize too small! " "(have: %d need: %d)\n", state->unit, osize, osize + MPPE_OVHD + 2); return -1; } osize = isize + MPPE_OVHD + 2; /* * Copy over the PPP header and set control bits. */ obuf[0] = PPP_ADDRESS(ibuf); obuf[1] = PPP_CONTROL(ibuf); put_unaligned_be16(PPP_COMP, obuf + 2); obuf += PPP_HDRLEN; state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; if (state->debug >= 7) printk(KERN_DEBUG "mppe_compress[%d]: ccount %d\n", state->unit, state->ccount); put_unaligned_be16(state->ccount, obuf); if (!state->stateful || /* stateless mode */ ((state->ccount & 0xff) == 0xff) || /* "flag" packet */ (state->bits & MPPE_BIT_FLUSHED)) { /* CCP Reset-Request */ /* We must rekey */ if (state->debug && state->stateful) printk(KERN_DEBUG "mppe_compress[%d]: rekeying\n", state->unit); mppe_rekey(state, 0); state->bits |= MPPE_BIT_FLUSHED; } obuf[0] |= state->bits; state->bits &= ~MPPE_BIT_FLUSHED; /* reset for next xmit */ obuf += MPPE_OVHD; ibuf += 2; /* skip to proto field */ isize -= 2; /* Encrypt packet */ sg_init_table(sg_in, 1); sg_init_table(sg_out, 1); setup_sg(sg_in, ibuf, isize); setup_sg(sg_out, obuf, osize); skcipher_request_set_tfm(req, state->arc4); skcipher_request_set_callback(req, 0, NULL, NULL); skcipher_request_set_crypt(req, sg_in, sg_out, isize, NULL); err = crypto_skcipher_encrypt(req); skcipher_request_zero(req); if (err) { printk(KERN_DEBUG "crypto_cypher_encrypt failed\n"); return -1; } state->stats.unc_bytes += isize; state->stats.unc_packets++; state->stats.comp_bytes += osize; state->stats.comp_packets++; return osize; } /* * Since every frame grows by MPPE_OVHD + 2 bytes, this is always going * to look bad ... and the longer the link is up the worse it will get. */ static void mppe_comp_stats(void *arg, struct compstat *stats) { struct ppp_mppe_state *state = (struct ppp_mppe_state *) arg; *stats = state->stats; } static int mppe_decomp_init(void *arg, unsigned char *options, int optlen, int unit, int hdrlen, int mru, int debug) { /* ARGSUSED */ return mppe_init(arg, options, optlen, unit, debug, "mppe_decomp_init"); } /* * We received a CCP Reset-Ack. Just ignore it. */ static void mppe_decomp_reset(void *arg) { /* ARGSUSED */ return; } /* * Decompress (decrypt) an MPPE packet. */ static int mppe_decompress(void *arg, unsigned char *ibuf, int isize, unsigned char *obuf, int osize) { struct ppp_mppe_state *state = (struct ppp_mppe_state *) arg; SKCIPHER_REQUEST_ON_STACK(req, state->arc4); unsigned ccount; int flushed = MPPE_BITS(ibuf) & MPPE_BIT_FLUSHED; struct scatterlist sg_in[1], sg_out[1]; if (isize <= PPP_HDRLEN + MPPE_OVHD) { if (state->debug) printk(KERN_DEBUG "mppe_decompress[%d]: short pkt (%d)\n", state->unit, isize); return DECOMP_ERROR; } /* * Make sure we have enough room to decrypt the packet. * Note that for our test we only subtract 1 byte whereas in * mppe_compress() we added 2 bytes (+MPPE_OVHD); * this is to account for possible PFC. */ if (osize < isize - MPPE_OVHD - 1) { printk(KERN_DEBUG "mppe_decompress[%d]: osize too small! " "(have: %d need: %d)\n", state->unit, osize, isize - MPPE_OVHD - 1); return DECOMP_ERROR; } osize = isize - MPPE_OVHD - 2; /* assume no PFC */ ccount = MPPE_CCOUNT(ibuf); if (state->debug >= 7) printk(KERN_DEBUG "mppe_decompress[%d]: ccount %d\n", state->unit, ccount); /* sanity checks -- terminate with extreme prejudice */ if (!(MPPE_BITS(ibuf) & MPPE_BIT_ENCRYPTED)) { printk(KERN_DEBUG "mppe_decompress[%d]: ENCRYPTED bit not set!\n", state->unit); state->sanity_errors += 100; goto sanity_error; } if (!state->stateful && !flushed) { printk(KERN_DEBUG "mppe_decompress[%d]: FLUSHED bit not set in " "stateless mode!\n", state->unit); state->sanity_errors += 100; goto sanity_error; } if (state->stateful && ((ccount & 0xff) == 0xff) && !flushed) { printk(KERN_DEBUG "mppe_decompress[%d]: FLUSHED bit not set on " "flag packet!\n", state->unit); state->sanity_errors += 100; goto sanity_error; } /* * Check the coherency count. */ if (!state->stateful) { /* Discard late packet */ if ((ccount - state->ccount) % MPPE_CCOUNT_SPACE > MPPE_CCOUNT_SPACE / 2) { state->sanity_errors++; goto sanity_error; } /* RFC 3078, sec 8.1. Rekey for every packet. */ while (state->ccount != ccount) { mppe_rekey(state, 0); state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; } } else { /* RFC 3078, sec 8.2. */ if (!state->discard) { /* normal state */ state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; if (ccount != state->ccount) { /* * (ccount > state->ccount) * Packet loss detected, enter the discard state. * Signal the peer to rekey (by sending a CCP Reset-Request). */ state->discard = 1; return DECOMP_ERROR; } } else { /* discard state */ if (!flushed) { /* ccp.c will be silent (no additional CCP Reset-Requests). */ return DECOMP_ERROR; } else { /* Rekey for every missed "flag" packet. */ while ((ccount & ~0xff) != (state->ccount & ~0xff)) { mppe_rekey(state, 0); state->ccount = (state->ccount + 256) % MPPE_CCOUNT_SPACE; } /* reset */ state->discard = 0; state->ccount = ccount; /* * Another problem with RFC 3078 here. It implies that the * peer need not send a Reset-Ack packet. But RFC 1962 * requires it. Hopefully, M$ does send a Reset-Ack; even * though it isn't required for MPPE synchronization, it is * required to reset CCP state. */ } } if (flushed) mppe_rekey(state, 0); } /* * Fill in the first part of the PPP header. The protocol field * comes from the decrypted data. */ obuf[0] = PPP_ADDRESS(ibuf); /* +1 */ obuf[1] = PPP_CONTROL(ibuf); /* +1 */ obuf += 2; ibuf += PPP_HDRLEN + MPPE_OVHD; isize -= PPP_HDRLEN + MPPE_OVHD; /* -6 */ /* net osize: isize-4 */ /* * Decrypt the first byte in order to check if it is * a compressed or uncompressed protocol field. */ sg_init_table(sg_in, 1); sg_init_table(sg_out, 1); setup_sg(sg_in, ibuf, 1); setup_sg(sg_out, obuf, 1); skcipher_request_set_tfm(req, state->arc4); skcipher_request_set_callback(req, 0, NULL, NULL); skcipher_request_set_crypt(req, sg_in, sg_out, 1, NULL); if (crypto_skcipher_decrypt(req)) { printk(KERN_DEBUG "crypto_cypher_decrypt failed\n"); osize = DECOMP_ERROR; goto out_zap_req; } /* * Do PFC decompression. * This would be nicer if we were given the actual sk_buff * instead of a char *. */ if ((obuf[0] & 0x01) != 0) { obuf[1] = obuf[0]; obuf[0] = 0; obuf++; osize++; } /* And finally, decrypt the rest of the packet. */ setup_sg(sg_in, ibuf + 1, isize - 1); setup_sg(sg_out, obuf + 1, osize - 1); skcipher_request_set_crypt(req, sg_in, sg_out, isize - 1, NULL); if (crypto_skcipher_decrypt(req)) { printk(KERN_DEBUG "crypto_cypher_decrypt failed\n"); osize = DECOMP_ERROR; goto out_zap_req; } state->stats.unc_bytes += osize; state->stats.unc_packets++; state->stats.comp_bytes += isize; state->stats.comp_packets++; /* good packet credit */ state->sanity_errors >>= 1; out_zap_req: skcipher_request_zero(req); return osize; sanity_error: if (state->sanity_errors < SANITY_MAX) return DECOMP_ERROR; else /* Take LCP down if the peer is sending too many bogons. * We don't want to do this for a single or just a few * instances since it could just be due to packet corruption. */ return DECOMP_FATALERROR; } /* * Incompressible data has arrived (this should never happen!). * We should probably drop the link if the protocol is in the range * of what should be encrypted. At the least, we should drop this * packet. (How to do this?) */ static void mppe_incomp(void *arg, unsigned char *ibuf, int icnt) { struct ppp_mppe_state *state = (struct ppp_mppe_state *) arg; if (state->debug && (PPP_PROTOCOL(ibuf) >= 0x0021 && PPP_PROTOCOL(ibuf) <= 0x00fa)) printk(KERN_DEBUG "mppe_incomp[%d]: incompressible (unencrypted) data! " "(proto %04x)\n", state->unit, PPP_PROTOCOL(ibuf)); state->stats.inc_bytes += icnt; state->stats.inc_packets++; state->stats.unc_bytes += icnt; state->stats.unc_packets++; } /************************************************************* * Module interface table *************************************************************/ /* * Procedures exported to if_ppp.c. */ static struct compressor ppp_mppe = { .compress_proto = CI_MPPE, .comp_alloc = mppe_alloc, .comp_free = mppe_free, .comp_init = mppe_comp_init, .comp_reset = mppe_comp_reset, .compress = mppe_compress, .comp_stat = mppe_comp_stats, .decomp_alloc = mppe_alloc, .decomp_free = mppe_free, .decomp_init = mppe_decomp_init, .decomp_reset = mppe_decomp_reset, .decompress = mppe_decompress, .incomp = mppe_incomp, .decomp_stat = mppe_comp_stats, .owner = THIS_MODULE, .comp_extra = MPPE_PAD, }; /* * ppp_mppe_init() * * Prior to allowing load, try to load the arc4 and sha1 crypto * libraries. The actual use will be allocated later, but * this way the module will fail to insmod if they aren't available. */ static int __init ppp_mppe_init(void) { int answer; if (!(crypto_has_skcipher("ecb(arc4)", 0, CRYPTO_ALG_ASYNC) && crypto_has_ahash("sha1", 0, CRYPTO_ALG_ASYNC))) return -ENODEV; sha_pad = kmalloc(sizeof(struct sha_pad), GFP_KERNEL); if (!sha_pad) return -ENOMEM; sha_pad_init(sha_pad); answer = ppp_register_compressor(&ppp_mppe); if (answer == 0) printk(KERN_INFO "PPP MPPE Compression module registered\n"); else kfree(sha_pad); return answer; } static void __exit ppp_mppe_cleanup(void) { ppp_unregister_compressor(&ppp_mppe); kfree(sha_pad); } module_init(ppp_mppe_init); module_exit(ppp_mppe_cleanup);
28.724638
90
0.677048
861ec23207b4bf656dab7c4df23b2f5179d6405a
2,389
h
C
components/sync/model/recording_model_type_change_processor.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/sync/model/recording_model_type_change_processor.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/sync/model/recording_model_type_change_processor.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SYNC_MODEL_RECORDING_MODEL_TYPE_CHANGE_PROCESSOR_H_ #define COMPONENTS_SYNC_MODEL_RECORDING_MODEL_TYPE_CHANGE_PROCESSOR_H_ #include <map> #include <memory> #include <set> #include <string> #include "components/sync/model/fake_model_type_change_processor.h" #include "components/sync/model/model_type_sync_bridge.h" namespace syncer { // Augmented FakeModelTypeChangeProcessor that accumulates all instructions in // members that can then be accessed for verification. class RecordingModelTypeChangeProcessor : public FakeModelTypeChangeProcessor { public: RecordingModelTypeChangeProcessor(); ~RecordingModelTypeChangeProcessor() override; // FakeModelTypeChangeProcessor overrides. void Put(const std::string& storage_key, std::unique_ptr<EntityData> entity_data, MetadataChangeList* metadata_changes) override; void Delete(const std::string& storage_key, MetadataChangeList* metadata_changes) override; void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; bool IsTrackingMetadata() override; void SetIsTrackingMetadata(bool is_tracking); const std::multimap<std::string, std::unique_ptr<EntityData>>& put_multimap() const { return put_multimap_; } const std::set<std::string>& delete_set() const { return delete_set_; } MetadataBatch* metadata() const { return metadata_.get(); } // Returns a callback that constructs a processor and assigns a raw pointer to // the given address. The caller must ensure that the address passed in is // still valid whenever the callback is run. This can be useful for tests that // want to verify the RecordingModelTypeChangeProcessor was given data by the // bridge they are testing. static ModelTypeSyncBridge::ChangeProcessorFactory FactoryForBridgeTest( RecordingModelTypeChangeProcessor** processor_address, bool expect_error = false); private: std::multimap<std::string, std::unique_ptr<EntityData>> put_multimap_; std::set<std::string> delete_set_; std::unique_ptr<MetadataBatch> metadata_; bool is_tracking_metadata_ = true; }; } // namespace syncer #endif // COMPONENTS_SYNC_MODEL_RECORDING_MODEL_TYPE_CHANGE_PROCESSOR_H_
37.328125
80
0.780661
2fc257331c07b05fe81b26c2ee5e81a362c2601c
10,123
c
C
sun.c
troglobit/sun
5fa5be284a82677ac6f48195a1fb8c1c938f61a8
[ "Unlicense" ]
24
2017-12-09T21:16:59.000Z
2021-11-03T14:42:37.000Z
sun.c
troglobit/sun
5fa5be284a82677ac6f48195a1fb8c1c938f61a8
[ "Unlicense" ]
2
2019-09-19T10:34:33.000Z
2019-09-28T07:23:29.000Z
sun.c
troglobit/sun
5fa5be284a82677ac6f48195a1fb8c1c938f61a8
[ "Unlicense" ]
4
2019-09-27T09:20:44.000Z
2021-04-10T05:01:17.000Z
/* Simple SUNRISET front-end application (c) Joachim Nilsson, 2017 Released to the public domain by Joachim Nilsson, December 2017 */ #include "config.h" #include <getopt.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include "tzalias.h" #include "sunriset.h" #define TIMEZONE "/etc/timezone" #define ZONETAB "/usr/share/zoneinfo/zone.tab" /* From The Practice of Programming, by Kernighan and Pike */ #define NELEMS(array) (sizeof(array) / sizeof(array[0])) #define PRINTF(fmt, args...) if (verbose > 0) printf(fmt, ##args) static time_t now; static struct tm *tm; static time_t offset = 0; static int utc = 0; static int verbose = 1; static int do_wait = 0; extern char *__progname; static time_t timediff(void) { static int done = 0; static time_t diff; if (done) return diff; // tzset(); // diff = -timezone; diff = tm->tm_gmtoff; done = 1; return diff; } /* * Converts the optional `-w TIME` offset to a relative offset. * Supports e.g.. 30m, -15m, 13s, 1h ... or just 3600 */ static time_t convert_offset(char *arg) { int mult = 1; long long val = 0; if (!arg) return 0; if (strpbrk(arg, "hH")) mult = 3600; if (strpbrk(arg, "mM")) mult = 60; sscanf(arg, "%lld", &val); val *= mult; /* MAX offset == +/- 6h, otherwise your location is wrong */ if (val < -6 * 3600) val = -6 * 3600; if (val > 6 * 3600) val = 6 * 3600; return val; } static void convert(double ut, int *h, int *m) { *h = (int)floor(ut); *m = (int)(60 * (ut - floor(ut))); *m += (timediff() % 3600)/60; *h += timediff() / 3600; } static char *lctime_r(double ut, char *buf, size_t len) { int h, m; convert(ut, &h, &m); snprintf(buf, len, "%02d:%02d", h, m); return buf; } static char *lctime(double ut) { static char buf[10]; return lctime_r(ut, buf, sizeof(buf)); } static int riset(int mode, double lat, double lon, int year, int month, int day) { double rise, set; // char bufr[10], bufs[10]; sun_rise_set(year, month, day, lon, lat, &rise, &set); if (mode) PRINTF("Sun rises %s", lctime(rise)); if (!mode) PRINTF("Sun sets %s", lctime(set)); if (mode == -1) PRINTF(", sets %s", lctime(set)); PRINTF(" %s\n", tm->tm_zone); // printf("Sun rises %s, sets %s %s\n", lctime_r(rise, bufr, sizeof(bufr)), // lctime_r(set, bufs, sizeof(bufs)), tm->tm_zone); if (do_wait > 0) { int h, m, s; time_t then, sec; if (mode) convert(rise, &h, &m); else convert(set, &h, &m); /* Adjust for sunset/sunrise regardless of timezone */ h = h - tm->tm_hour; if (h < 0) h += 24; m = m - tm->tm_min; if (m < 0) m += 60; then = now + 3600 * h + 60 * m; sec = then - now + offset; /* Pretty printing */ h = sec / 60 / 60; m = sec / 60 - h * 60; s = sec - m * 60 - h * 60 * 60; PRINTF("Sleeping %dh%dm%ds ...\n", h, m, s); sleep(sec); } return 0; } static int sunrise(double lat, double lon, int year, int month, int day) { return riset(1, lat, lon, year, month, day); } static int sunset(double lat, double lon, int year, int month, int day) { return riset(0, lat, lon, year, month, day); } static int all(double lat, double lon, int year, int month, int day) { double daylen, civlen, nautlen, astrlen; double rise, set, civ_start, civ_end, naut_start, naut_end; double astr_start, astr_end; int rs, civ, naut, astr; char bufr[10], bufs[10]; daylen = day_length(year, month, day, lon, lat); civlen = day_civil_twilight_length(year, month, day, lon, lat); nautlen = day_nautical_twilight_length(year, month, day, lon, lat); astrlen = day_astronomical_twilight_length(year, month, day, lon, lat); PRINTF("Day length: %5.2f hours\n", daylen); PRINTF("With civil twilight %5.2f hours\n", civlen); PRINTF("With nautical twilight %5.2f hours\n", nautlen); PRINTF("With astronomical twilight %5.2f hours\n", astrlen); PRINTF("Length of twilight: civil %5.2f hours\n", (civlen - daylen) / 2.0); PRINTF(" nautical %5.2f hours\n", (nautlen - daylen) / 2.0); PRINTF(" astronomical %5.2f hours\n", (astrlen - daylen) / 2.0); rs = sun_rise_set(year, month, day, lon, lat, &rise, &set); civ = civil_twilight(year, month, day, lon, lat, &civ_start, &civ_end); naut = nautical_twilight(year, month, day, lon, lat, &naut_start, &naut_end); astr = astronomical_twilight(year, month, day, lon, lat, &astr_start, &astr_end); PRINTF("Sun at south %s %s\n", lctime((rise + set) / 2.0), tm->tm_zone); switch (rs) { case 0: printf("Sun rises %s, sets %s %s\n", lctime_r(rise, bufr, sizeof(bufr)), lctime_r(set, bufs, sizeof(bufs)), tm->tm_zone); break; case +1: PRINTF("Sun above horizon\n"); break; case -1: PRINTF("Sun below horizon\n"); break; } switch (civ) { case 0: printf("Civil twilight starts %s, ends %s %s\n", lctime_r(civ_start, bufr, sizeof(bufr)), lctime_r(civ_end, bufs, sizeof(bufs)), tm->tm_zone); break; case +1: PRINTF("Never darker than civil twilight\n"); break; case -1: PRINTF("Never as bright as civil twilight\n"); break; } switch (naut) { case 0: printf("Nautical twilight starts %s, ends %s %s\n", lctime_r(naut_start, bufr, sizeof(bufr)), lctime_r(naut_end, bufs, sizeof(bufs)), tm->tm_zone); break; case +1: PRINTF("Never darker than nautical twilight\n"); break; case -1: PRINTF("Never as bright as nautical twilight\n"); break; } switch (astr) { case 0: printf("Astronomical twilight starts %s, ends %s %s\n", lctime_r(astr_start, bufr, sizeof(bufr)), lctime_r(astr_end, bufs, sizeof(bufs)), tm->tm_zone); break; case +1: PRINTF("Never darker than astronomical twilight\n"); break; case -1: PRINTF("Never as bright as astronomical twilight\n"); break; } return 0; } static void chomp(char *str) { size_t len; if (!str) return; len = strlen(str) - 1; while (len && str[len] == '\n') str[len--] = 0; } static int alias(char *tz, size_t len) { size_t i; for (i = 0; i < NELEMS(tzalias); i++) { if (strcmp(tzalias[i].name, tz)) continue; strncpy(tz, tzalias[i].alias, len); return 1; } return 0; } static int probe(double *lat, double *lon) { int found = 0, again = 0; FILE *fp; char *ptr, tz[42], buf[80]; ptr = getenv("TZ"); if (!ptr) { fp = fopen(TIMEZONE, "r"); if (!fp) return 0; if (fgets(tz, sizeof(tz), fp)) chomp(tz); fclose(fp); } else { strncpy(tz, ptr, sizeof(tz)); tz[sizeof(tz) - 1] = 0; } retry: // printf("tz: '%s'\n", tz); fp = fopen(ZONETAB, "r"); if (!fp) return 0; while ((fgets(buf, sizeof(buf), fp))) { ptr = strstr(buf, tz); if (!ptr) continue; *ptr = 0; ptr = buf; while (*ptr != ' ' && *ptr != ' ') ptr++; if (sscanf(ptr, "%lf%lf", lat, lon) == 2) { *lat /= 100.0; *lon /= 100.0; found = 1; } // printf("buf: '%s', lat: %lf, lon: %lf\n", ptr, *lat, *lon); break; } fclose(fp); if (!found) { // printf("Cannot find your coordinates using time zone: %s\n", tz); if (!again) { again++; if (alias(tz, sizeof(tz))) goto retry; } // puts(""); } return found; } static int interactive(double *lat, double *lon, int *year, int *month, int *day) { char buf[80]; printf("Latitude (+ is north) and longitude (+ is east) : "); if (fgets(buf, sizeof(buf), stdin)) sscanf(buf, "%lf %lf", lat, lon); printf("Input date ( yyyy mm dd ) (ctrl-C exits): "); if (fgets(buf, 80, stdin)) sscanf(buf, "%d %d %d", year, month, day); return 1; } static int usage(int code) { printf("Usage:\n" " %s [-ahirsw] [-o OFFSET] [+/-latitude +/-longitude]\n" "\n" "Options:\n" " -a Show all relevant times and exit\n" " -l Increased verbosity, enable log messages\n" " -h This help text\n" " -i Interactive mode\n" " -r Sunrise mode\n" " -s Sunset mode\n" " -u Use UTC everywhere, not local time\n" " -v Show program version and exit\n" " -w Wait until sunset or sunrise\n" " -o ARG Time offset to adjust wait, e.g. -o -30m\n" " maximum allowed offset: +/- 6h\n" "\n" "Bug report address: %s\n", __progname, PACKAGE_BUGREPORT); return code; } int main(int argc, char *argv[]) { int c, op = 0, ok = 0; int year, month, day; double lon = 0.0, lat; while ((c = getopt(argc, argv, "ahilo:rsuvw")) != EOF) { switch (c) { case 'h': return usage(0); case 'i': verbose++; ok = interactive(&lat, &lon, &year, &month, &day); break; case 'l': verbose++; break; case 'a': verbose++; do_wait--; /* fallthrough */ case 'r': case 's': op = c; break; case 'u': utc = 1; break; case 'v': puts(PACKAGE_VERSION); return 0; case 'o': offset = convert_offset(optarg); break; case 'w': verbose--; do_wait++; break; case ':': /* missing param for option */ case '?': /* unknown option */ default: return usage(1); } } now = time(NULL); if (utc) tm = gmtime(&now); else tm = localtime(&now); if (!ok) { if (optind < argc) lat = atof(argv[optind++]); if (optind < argc) lon = atof(argv[optind]); year = 1900 + tm->tm_year; month = 1 + tm->tm_mon; day = tm->tm_mday; // PRINTF("latitude %f longitude %f date %d-%02d-%02d %d:%d (%s)\n", // lat, lon, year, month, day, tm->tm_hour, tm->tm_min, tm->tm_zone); if (lon != 0.0) ok = 1; if (!ok) ok = probe(&lat, &lon); } else { tm->tm_year = year - 1900; tm->tm_mon = month - 1; tm->tm_mday = day; } if (!ok) return usage(1); switch (op) { case 'a': return all(lat, lon, year, month, day); case 'r': return sunrise(lat, lon, year, month, day); case 's': return sunset(lat, lon, year, month, day); default: verbose++; break; } return riset(-1, lat, lon, year, month, day); } /** * Local Variables: * indent-tabs-mode: t * c-file-style: "linux" * End: */
20.491903
82
0.586387
8aebad590333aeff54b8723d1274e9c9b75e8a5f
1,333
c
C
main/http_handler.c
donny681/ESP32_Weather_station
ac17d8df8f0b6554796210d9fee356e9e821cf89
[ "MIT" ]
5
2019-12-25T01:15:54.000Z
2020-12-29T07:44:22.000Z
main/http_handler.c
donny681/ESP32_Weather_station
ac17d8df8f0b6554796210d9fee356e9e821cf89
[ "MIT" ]
null
null
null
main/http_handler.c
donny681/ESP32_Weather_station
ac17d8df8f0b6554796210d9fee356e9e821cf89
[ "MIT" ]
2
2020-03-12T04:03:08.000Z
2020-05-18T14:31:29.000Z
/* * http_handler.c * * Created on: Dec 19, 2019 * Author: fyy */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_log.h" #include "esp_system.h" #include "nvs_flash.h" #include "protocol_examples_common.h" #include "esp_netif.h" #include "http_handler.h" #include "my_url_parser.h" #include "my_nvs.h" #include "https.h" void http_get_handler(char *url,char *data) { if(!strcmp(url,data)) { return ; } if (!strcmp(url,"/wifi.html")) { printf("http_get_handler\r\n"); char buf[128]={0}; GetTheKeyValue(data,"ssid",(unsigned char *)buf); printf("ssid=%s\r\n",buf); save_nvs_str("ssid",buf); memset(buf,0,128); read_nvs_str("ssid",buf); printf("read ssid=%s\r\n",buf); memset(buf,0,128); GetTheKeyValue(data,"pwd",(unsigned char *)buf); printf("pwd=%s\r\n",buf); save_nvs_str("pwd",buf); memset(buf,0,128); read_nvs_str("pwd",buf); printf("read pwd=%s\r\n",buf); }else if (!strcmp(url,"/city.html")){ char buf[128]={0}; GetTheKeyValue(data,"city",(unsigned char *)buf); printf("city=%s\r\n",buf); save_nvs_str("city",buf); memset(buf,0,128); read_nvs_str("city",buf); printf("read city=%s\r\n",buf); xSemaphoreGive(https_handle_t); } }
21.15873
51
0.657914
9cb1043b9b46613b13004b4e83b590aa0dd6f97c
1,373
h
C
output.h
mle86/csv-parser
f40fb2642ec05b81de1739be80cf6234b7fab50c
[ "MIT" ]
null
null
null
output.h
mle86/csv-parser
f40fb2642ec05b81de1739be80cf6234b7fab50c
[ "MIT" ]
null
null
null
output.h
mle86/csv-parser
f40fb2642ec05b81de1739be80cf6234b7fab50c
[ "MIT" ]
null
null
null
#ifndef OUTPUT_H #define OUTPUT_H /** * Output functions * and output mode-related definitions. * * This file is part of the 'csv-parser' project * (see https://github.com/mle86/csv-parser). * * SPDX-License-Identifier: MIT * Copyright © 2017-2020 Maximilian Eul */ #include <stdbool.h> #include "nstr.h" #include "const.h" #define SIMPLE_LINESEP "-\n" #define SIMPLE_KVSEP ": " #define CSV_FIELDSEP ',' #define CSV_FIELDENC '"' #define CSV_LINESEP "\r\n" // pretty-printing colors: #define PP_KEY Mgreen #define PP_SYM Myellow #define PP_ESC Mcyan #define PP_RST M0 // variable name templates: #define SHVAR_COLNAME "CSV_COLNAME_%zu" #define SHVAR_CELL "CSV_%zu_%zu" #define SHVAR_N_RECORDS "CSV_RECORDS" typedef enum outmode { OM_SIMPLE, OM_JSON, OM_JSON_NUMBERED, // special mode, only reachable with mode combination -ij. OM_JSON_COMPACT, OM_SHELL_VARS, OM_SHELL_VARS_NUMBERED, // special mode, only reachable with mode combination -iX. OM_CSV, OM_CSV_NUMBERED, // special mode, only reachable with mode combination -iC. } outmode_t; void set_output (outmode_t mode, bool do_flush, bool pretty, const char* shvar_prefix); void output_begin (void); void output_end (void); void output_empty (void); void output_line_begin (void); void output_line_end (void); void output_kv (const nstr* key, const nstr* value); #endif // OUTPUT_H
22.145161
87
0.742899
9cf4ddf9080b8ed378d9258033b90d871b23bc53
359
h
C
ios/bc3.1/Frameworks/TBAppLinkSDK.framework/Headers/TBNativeParam.h
RyanFu/DSJAPP
db6d8fa4719052dcb4de3557e966d633eeff8fcb
[ "BSD-3-Clause" ]
1
2019-03-13T15:46:58.000Z
2019-03-13T15:46:58.000Z
ios/bc3.1/Frameworks/TBAppLinkSDK.framework/Headers/TBNativeParam.h
RyanFu/DSJAPP
db6d8fa4719052dcb4de3557e966d633eeff8fcb
[ "BSD-3-Clause" ]
null
null
null
ios/bc3.1/Frameworks/TBAppLinkSDK.framework/Headers/TBNativeParam.h
RyanFu/DSJAPP
db6d8fa4719052dcb4de3557e966d633eeff8fcb
[ "BSD-3-Clause" ]
null
null
null
// // TBNativeParam.h // WopcMiniSDK // // Created by muhuai on 15/8/18. // Copyright (c) 2015年 TaoBao. All rights reserved. // #import "TBBasicParam.h" @interface TBNativeParam : TBBasicParam /** * 要跳转的模块 */ @property (nonatomic, strong) NSString *moduleFromApp; /** * 初始化,传入module */ -(instancetype)initWithModule:(NSString *)module; @end
15.608696
58
0.674095
e7acb7bf7a4a4a56ddd96d542fb6b88b206adf1a
43,992
c
C
src/gfx/drivers/gl1.c
basharast/RetroArch-ARM
33208e97b7eebae35cfce7831cf3fefc9d783d79
[ "MIT" ]
4
2021-12-03T14:58:12.000Z
2022-03-05T11:17:16.000Z
src/gfx/drivers/gl1.c
basharast/RetroArch-ARM
33208e97b7eebae35cfce7831cf3fefc9d783d79
[ "MIT" ]
2
2022-03-16T06:13:34.000Z
2022-03-26T06:44:50.000Z
src/gfx/drivers/gl1.c
basharast/RetroArch-ARM
33208e97b7eebae35cfce7831cf3fefc9d783d79
[ "MIT" ]
null
null
null
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * Copyright (C) 2011-2017 - Daniel De Matteis * Copyright (C) 2016-2019 - Brad Parker * * RetroArch 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch 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 RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ /* OpenGL 1.x driver. * * Minimum version : OpenGL 1.1 (1997) * * We are targeting a minimum of OpenGL 1.1 and the Microsoft * "GDI Generic" * software GL implementation. * Any additional features added for later 1.x versions should only be * enabled if they are detected at runtime. */ #include <stddef.h> #include <retro_miscellaneous.h> #include <formats/image.h> #include <string/stdstring.h> #include <retro_math.h> #include <gfx/video_frame.h> #include <gfx/scaler/pixconv.h> #ifdef HAVE_CONFIG_H #include "../../config.h" #endif #ifdef HAVE_MENU #include "../../menu/menu_driver.h" #endif #ifdef HAVE_GFX_WIDGETS #include "../gfx_widgets.h" #endif #include "../font_driver.h" #include "../../driver.h" #include "../../configuration.h" #include "../../retroarch.h" #include "../../verbosity.h" #include "../../frontend/frontend_driver.h" #include "../common/gl1_common.h" #if defined(_WIN32) && !defined(_XBOX) #include "../common/win32_common.h" #endif #ifdef HAVE_THREADS #include "../video_thread_wrapper.h" #endif #ifdef VITA #include <defines/psp_defines.h> static bool vgl_inited = false; #endif static struct video_ortho gl1_default_ortho = {0, 1, 0, 1, -1, 1}; /* Used for the last pass when rendering to the back buffer. */ static const GLfloat gl1_vertexes_flipped[] = { 0, 1, 1, 1, 0, 0, 1, 0 }; static const GLfloat gl1_vertexes[] = { 0, 0, 1, 0, 0, 1, 1, 1 }; static const GLfloat gl1_tex_coords[] = { 0, 0, 1, 0, 0, 1, 1, 1 }; static const GLfloat gl1_white_color[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; #define gl1_context_bind_hw_render(gl1, enable) \ if (gl1->shared_context_use) \ gl1->ctx_driver->bind_hw_render(gl1->ctx_data, enable) #ifdef HAVE_OVERLAY static void gl1_render_overlay(gl1_t *gl, unsigned width, unsigned height) { unsigned i; glEnable(GL_BLEND); if (gl->overlay_full_screen) glViewport(0, 0, width, height); gl->coords.vertex = gl->overlay_vertex_coord; gl->coords.tex_coord = gl->overlay_tex_coord; gl->coords.color = gl->overlay_color_coord; gl->coords.vertices = 4 * gl->overlays; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); for (i = 0; i < gl->overlays; i++) { glBindTexture(GL_TEXTURE_2D, gl->overlay_tex[i]); glDrawArrays(GL_TRIANGLE_STRIP, 4 * i, 4); } glDisable(GL_BLEND); gl->coords.vertex = gl->vertex_ptr; gl->coords.tex_coord = gl->tex_info.coord; gl->coords.color = gl->white_color_ptr; gl->coords.vertices = 4; if (gl->overlay_full_screen) glViewport(gl->vp.x, gl->vp.y, gl->vp.width, gl->vp.height); } static void gl1_free_overlay(gl1_t *gl) { glDeleteTextures(gl->overlays, gl->overlay_tex); free(gl->overlay_tex); free(gl->overlay_vertex_coord); free(gl->overlay_tex_coord); free(gl->overlay_color_coord); gl->overlay_tex = NULL; gl->overlay_vertex_coord = NULL; gl->overlay_tex_coord = NULL; gl->overlay_color_coord = NULL; gl->overlays = 0; } static void gl1_overlay_vertex_geom(void *data, unsigned image, float x, float y, float w, float h) { GLfloat *vertex = NULL; gl1_t *gl = (gl1_t*)data; if (!gl) return; if (image > gl->overlays) { RARCH_ERR("[GL]: Invalid overlay id: %u\n", image); return; } vertex = (GLfloat*)&gl->overlay_vertex_coord[image * 8]; /* Flipped, so we preserve top-down semantics. */ y = 1.0f - y; h = -h; vertex[0] = x; vertex[1] = y; vertex[2] = x + w; vertex[3] = y; vertex[4] = x; vertex[5] = y + h; vertex[6] = x + w; vertex[7] = y + h; } static void gl1_overlay_tex_geom(void *data, unsigned image, GLfloat x, GLfloat y, GLfloat w, GLfloat h) { GLfloat *tex = NULL; gl1_t *gl = (gl1_t*)data; if (!gl) return; tex = (GLfloat*)&gl->overlay_tex_coord[image * 8]; tex[0] = x; tex[1] = y; tex[2] = x + w; tex[3] = y; tex[4] = x; tex[5] = y + h; tex[6] = x + w; tex[7] = y + h; } #endif static bool is_pot(unsigned x) { return (x & (x - 1)) == 0; } static unsigned get_pot(unsigned x) { return (is_pot(x) ? x : next_pow2(x)); } static void *gl1_gfx_init(const video_info_t *video, input_driver_t **input, void **input_data) { unsigned full_x, full_y; void *ctx_data = NULL; const gfx_ctx_driver_t *ctx_driver = NULL; unsigned mode_width = 0; unsigned mode_height = 0; unsigned win_width = 0, win_height = 0; unsigned temp_width = 0, temp_height = 0; settings_t *settings = config_get_ptr(); bool video_smooth = settings->bools.video_smooth; bool video_font_enable = settings->bools.video_font_enable; const char *video_context_driver = settings->arrays.video_context_driver; gl1_t *gl1 = (gl1_t*)calloc(1, sizeof(*gl1)); const char *vendor = NULL; const char *renderer = NULL; const char *version = NULL; const char *extensions = NULL; int interval = 0; struct retro_hw_render_callback *hwr = NULL; if (!gl1) return NULL; *input = NULL; *input_data = NULL; gl1->video_width = video->width; gl1->video_height = video->height; gl1->rgb32 = video->rgb32; gl1->video_bits = video->rgb32 ? 32 : 16; if (video->rgb32) gl1->video_pitch = video->width * 4; else gl1->video_pitch = video->width * 2; ctx_driver = video_context_driver_init_first(gl1, video_context_driver, GFX_CTX_OPENGL_API, 1, 1, false, &ctx_data); if (!ctx_driver) goto error; if (ctx_data) gl1->ctx_data = ctx_data; gl1->ctx_driver = ctx_driver; video_context_driver_set((const gfx_ctx_driver_t*)ctx_driver); RARCH_LOG("[GL1]: Found GL1 context: \"%s\".\n", ctx_driver->ident); if (gl1->ctx_driver->get_video_size) gl1->ctx_driver->get_video_size(gl1->ctx_data, &mode_width, &mode_height); full_x = mode_width; full_y = mode_height; mode_width = 0; mode_height = 0; #ifdef VITA if (!vgl_inited) { vglInitExtended(0x1400000, full_x, full_y, RAM_THRESHOLD, SCE_GXM_MULTISAMPLE_4X); vglUseVram(GL_TRUE); vgl_inited = true; } #endif /* Clear out potential error flags in case we use cached context. */ glGetError(); if (string_is_equal(ctx_driver->ident, "null")) goto error; RARCH_LOG("[GL1]: Detecting screen resolution: %ux%u.\n", full_x, full_y); win_width = video->width; win_height = video->height; if (video->fullscreen && (win_width == 0) && (win_height == 0)) { win_width = full_x; win_height = full_y; } mode_width = win_width; mode_height = win_height; interval = video->swap_interval; if (ctx_driver->swap_interval) { bool adaptive_vsync_enabled = video_driver_test_all_flags( GFX_CTX_FLAGS_ADAPTIVE_VSYNC) && video->adaptive_vsync; if (adaptive_vsync_enabled && interval == 1) interval = -1; ctx_driver->swap_interval(gl1->ctx_data, interval); } if ( !gl1->ctx_driver->set_video_mode || !gl1->ctx_driver->set_video_mode(gl1->ctx_data, win_width, win_height, video->fullscreen)) goto error; gl1->fullscreen = video->fullscreen; mode_width = 0; mode_height = 0; if (gl1->ctx_driver->get_video_size) gl1->ctx_driver->get_video_size(gl1->ctx_data, &mode_width, &mode_height); temp_width = mode_width; temp_height = mode_height; /* Get real known video size, which might have been altered by context. */ if (temp_width != 0 && temp_height != 0) video_driver_set_size(temp_width, temp_height); video_driver_get_size(&temp_width, &temp_height); RARCH_LOG("[GL1]: Using resolution %ux%u.\n", temp_width, temp_height); vendor = (const char*)glGetString(GL_VENDOR); renderer = (const char*)glGetString(GL_RENDERER); version = (const char*)glGetString(GL_VERSION); extensions = (const char*)glGetString(GL_EXTENSIONS); if (!string_is_empty(version)) sscanf(version, "%d.%d", &gl1->version_major, &gl1->version_minor); if (!string_is_empty(extensions)) gl1->extensions = string_split(extensions, " "); RARCH_LOG("[GL1]: Vendor: %s, Renderer: %s.\n", vendor, renderer); RARCH_LOG("[GL1]: Version: %s.\n", version); RARCH_LOG("[GL1]: Extensions: %s\n", extensions); { char device_str[128]; device_str[0] = '\0'; if (!string_is_empty(vendor)) { strlcpy(device_str, vendor, sizeof(device_str)); strlcat(device_str, " ", sizeof(device_str)); } if (!string_is_empty(renderer)) strlcat(device_str, renderer, sizeof(device_str)); video_driver_set_gpu_device_string(device_str); if (!string_is_empty(version)) video_driver_set_gpu_api_version_string(version); } if (gl1->ctx_driver->input_driver) { const char *joypad_name = settings->arrays.input_joypad_driver; gl1->ctx_driver->input_driver( gl1->ctx_data, joypad_name, input, input_data); } if (video_font_enable) font_driver_init_osd(gl1, video, false, video->is_threaded, FONT_DRIVER_RENDER_OPENGL1_API); gl1->smooth = video_smooth; gl1->supports_bgra = string_list_find_elem(gl1->extensions, "GL_EXT_bgra"); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_STENCIL_TEST); glDisable(GL_SCISSOR_TEST); #ifndef VITA glPixelStorei(GL_UNPACK_ALIGNMENT, 1); #endif glGenTextures(1, &gl1->tex); glGenTextures(1, &gl1->menu_tex); hwr = video_driver_get_hw_context(); memcpy(gl1->tex_info.coord, gl1_tex_coords, sizeof(gl1->tex_info.coord)); gl1->vertex_ptr = hwr->bottom_left_origin ? gl1_vertexes : gl1_vertexes_flipped; gl1->textures = 4; gl1->white_color_ptr = gl1_white_color; gl1->coords.vertex = gl1->vertex_ptr; gl1->coords.tex_coord = gl1->tex_info.coord; gl1->coords.color = gl1->white_color_ptr; gl1->coords.lut_tex_coord = gl1_tex_coords; gl1->coords.vertices = 4; RARCH_LOG("[GL1]: Init complete.\n"); return gl1; error: video_context_driver_free(); if (gl1) { if (gl1->extensions) string_list_free(gl1->extensions); free(gl1); } return NULL; } static void gl1_set_projection(gl1_t *gl1, struct video_ortho *ortho, bool allow_rotate) { math_matrix_4x4 rot; /* Calculate projection. */ matrix_4x4_ortho(gl1->mvp_no_rot, ortho->left, ortho->right, ortho->bottom, ortho->top, ortho->znear, ortho->zfar); if (!allow_rotate) { gl1->mvp = gl1->mvp_no_rot; return; } matrix_4x4_rotate_z(rot, M_PI * gl1->rotation / 180.0f); matrix_4x4_multiply(gl1->mvp, rot, gl1->mvp_no_rot); } void gl1_gfx_set_viewport(gl1_t *gl1, unsigned viewport_width, unsigned viewport_height, bool force_full, bool allow_rotate) { settings_t *settings = config_get_ptr(); unsigned height = gl1->video_height; int x = 0; int y = 0; float device_aspect = (float)viewport_width / viewport_height; if (gl1->ctx_driver->translate_aspect) device_aspect = gl1->ctx_driver->translate_aspect( gl1->ctx_data, viewport_width, viewport_height); if (settings->bools.video_scale_integer && !force_full) { video_viewport_get_scaled_integer(&gl1->vp, viewport_width, viewport_height, video_driver_get_aspect_ratio(), gl1->keep_aspect); viewport_width = gl1->vp.width; viewport_height = gl1->vp.height; } else if (gl1->keep_aspect && !force_full) { float desired_aspect = video_driver_get_aspect_ratio(); #if defined(HAVE_MENU) if (settings->uints.video_aspect_ratio_idx == ASPECT_RATIO_CUSTOM) { const struct video_viewport *custom = video_viewport_get_custom(); /* GL has bottom-left origin viewport. */ x = custom->x; y = height - custom->y - custom->height; viewport_width = custom->width; viewport_height = custom->height; } else #endif { float delta; if (fabsf(device_aspect - desired_aspect) < 0.0001f) { /* If the aspect ratios of screen and desired aspect * ratio are sufficiently equal (floating point stuff), * assume they are actually equal. */ } else if (device_aspect > desired_aspect) { delta = (desired_aspect / device_aspect - 1.0f) / 2.0f + 0.5f; x = (int)roundf(viewport_width * (0.5f - delta)); viewport_width = (unsigned)roundf(2.0f * viewport_width * delta); } else { delta = (device_aspect / desired_aspect - 1.0f) / 2.0f + 0.5f; y = (int)roundf(viewport_height * (0.5f - delta)); viewport_height = (unsigned)roundf(2.0f * viewport_height * delta); } } gl1->vp.x = x; gl1->vp.y = y; gl1->vp.width = viewport_width; gl1->vp.height = viewport_height; } else { gl1->vp.x = gl1->vp.y = 0; gl1->vp.width = viewport_width; gl1->vp.height = viewport_height; } #if defined(RARCH_MOBILE) /* In portrait mode, we want viewport to gravitate to top of screen. */ if (device_aspect < 1.0f) gl1->vp.y *= 2; #endif glViewport(gl1->vp.x, gl1->vp.y, gl1->vp.width, gl1->vp.height); gl1_set_projection(gl1, &gl1_default_ortho, allow_rotate); /* Set last backbuffer viewport. */ if (!force_full) { gl1->vp_out_width = viewport_width; gl1->vp_out_height = viewport_height; } #if 0 RARCH_LOG("Setting viewport @ %ux%u\n", viewport_width, viewport_height); #endif } static void draw_tex(gl1_t *gl1, int pot_width, int pot_height, int width, int height, GLuint tex, const void *frame_to_copy) { uint8_t *frame = NULL; uint8_t *frame_rgba = NULL; /* FIXME: For now, everything is uploaded as BGRA8888, I could not get 444 or 555 to work, and there is no 565 support in GL 1.1 either. */ GLint internalFormat = GL_RGB8; GLenum format = gl1->supports_bgra ? GL_BGRA_EXT : GL_RGBA; GLenum type = GL_UNSIGNED_BYTE; float vertices[] = { -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; float colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; float norm_width = (1.0f / (float)pot_width) * (float)width; float norm_height = (1.0f / (float)pot_height) * (float)height; float texcoords[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; texcoords[1] = texcoords[5] = norm_height; texcoords[4] = texcoords[6] = norm_width; glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_STENCIL_TEST); glDisable(GL_SCISSOR_TEST); glEnable(GL_TEXTURE_2D); /* Multi-texture not part of GL 1.1 */ /*glActiveTexture(GL_TEXTURE0);*/ #ifndef VITA glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ROW_LENGTH, pot_width); #endif glBindTexture(GL_TEXTURE_2D, tex); frame = (uint8_t*)frame_to_copy; if (!gl1->supports_bgra) { frame_rgba = (uint8_t*)malloc(pot_width * pot_height * 4); if (frame_rgba) { int x, y; for (y = 0; y < pot_height; y++) { for (x = 0; x < pot_width; x++) { int index = (y * pot_width + x) * 4; frame_rgba[index + 2] = frame[index + 0]; frame_rgba[index + 1] = frame[index + 1]; frame_rgba[index + 0] = frame[index + 2]; frame_rgba[index + 3] = frame[index + 3]; } } frame = frame_rgba; } } glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, pot_width, pot_height, 0, format, type, frame); if (frame_rgba) free(frame_rgba); if (tex == gl1->tex) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (gl1->smooth ? GL_LINEAR : GL_NEAREST)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (gl1->smooth ? GL_LINEAR : GL_NEAREST)); } else if (tex == gl1->menu_tex) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (gl1->menu_smooth ? GL_LINEAR : GL_NEAREST)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (gl1->menu_smooth ? GL_LINEAR : GL_NEAREST)); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); if (gl1->rotation && tex == gl1->tex) glRotatef(gl1->rotation, 0.0f, 0.0f, 1.0f); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glColorPointer(4, GL_FLOAT, 0, colors); glVertexPointer(3, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, texcoords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } static void gl1_readback( gl1_t *gl1, unsigned alignment, unsigned fmt, unsigned type, void *src) { #ifndef VITA glPixelStorei(GL_PACK_ALIGNMENT, alignment); glPixelStorei(GL_PACK_ROW_LENGTH, 0); glReadBuffer(GL_BACK); #endif glReadPixels(gl1->vp.x, gl1->vp.y, gl1->vp.width, gl1->vp.height, (GLenum)fmt, (GLenum)type, (GLvoid*)src); } static bool gl1_gfx_frame(void *data, const void *frame, unsigned frame_width, unsigned frame_height, uint64_t frame_count, unsigned pitch, const char *msg, video_frame_info_t *video_info) { const void *frame_to_copy = NULL; unsigned mode_width = 0; unsigned mode_height = 0; unsigned width = video_info->width; unsigned height = video_info->height; bool draw = true; bool do_swap = false; gl1_t *gl1 = (gl1_t*)data; unsigned bits = gl1->video_bits; unsigned pot_width = 0; unsigned pot_height = 0; unsigned video_width = video_info->width; unsigned video_height = video_info->height; #ifdef HAVE_MENU bool menu_is_alive = video_info->menu_is_alive; #endif #ifdef HAVE_GFX_WIDGETS bool widgets_active = video_info->widgets_active; #endif bool hard_sync = video_info->hard_sync; struct font_params *osd_params = (struct font_params*) &video_info->osd_stat_params; bool overlay_behind_menu = video_info->overlay_behind_menu; /* FIXME: Force these settings off as they interfere with the rendering */ video_info->xmb_shadows_enable = false; video_info->menu_shader_pipeline = 0; gl1_context_bind_hw_render(gl1, false); if (gl1->should_resize) { gfx_ctx_mode_t mode; gl1->should_resize = false; mode.width = width; mode.height = height; if (gl1->ctx_driver->set_resize) gl1->ctx_driver->set_resize(gl1->ctx_data, mode.width, mode.height); gl1_gfx_set_viewport(gl1, video_width, video_height, false, true); } if ( !frame || frame == RETRO_HW_FRAME_BUFFER_VALID || ( frame_width == 4 && frame_height == 4 && (frame_width < width && frame_height < height)) ) draw = false; do_swap = frame || draw; if ( gl1->video_width != frame_width || gl1->video_height != frame_height || gl1->video_pitch != pitch) { if (frame_width > 4 && frame_height > 4) { gl1->video_width = frame_width; gl1->video_height = frame_height; gl1->video_pitch = pitch; pot_width = get_pot(frame_width); pot_height = get_pot(frame_height); if (draw) { if (gl1->video_buf) free(gl1->video_buf); gl1->video_buf = (unsigned char*)malloc(pot_width * pot_height * 4); } } } width = gl1->video_width; height = gl1->video_height; pitch = gl1->video_pitch; pot_width = get_pot(width); pot_height = get_pot(height); if (draw && gl1->video_buf) { if (bits == 32) { unsigned y; /* copy lines into top-left portion of larger (power-of-two) buffer */ for (y = 0; y < height; y++) memcpy(gl1->video_buf + ((pot_width * (bits / 8)) * y), (const unsigned char*)frame + (pitch * y), width * (bits / 8)); } else if (bits == 16) conv_rgb565_argb8888(gl1->video_buf, frame, width, height, pot_width * sizeof(unsigned), pitch); frame_to_copy = gl1->video_buf; } if (gl1->video_width != width || gl1->video_height != height) { gl1->video_width = width; gl1->video_height = height; } if (gl1->ctx_driver->get_video_size) gl1->ctx_driver->get_video_size(gl1->ctx_data, &mode_width, &mode_height); gl1->screen_width = mode_width; gl1->screen_height = mode_height; if (draw) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (frame_to_copy) draw_tex(gl1, pot_width, pot_height, width, height, gl1->tex, frame_to_copy); } #ifdef HAVE_MENU if (gl1->menu_frame && menu_is_alive) { frame_to_copy = NULL; width = gl1->menu_width; height = gl1->menu_height; pitch = gl1->menu_pitch; bits = gl1->menu_bits; pot_width = get_pot(width); pot_height = get_pot(height); do_swap = true; if (gl1->menu_size_changed) { gl1->menu_size_changed = false; if (gl1->menu_video_buf) free(gl1->menu_video_buf); gl1->menu_video_buf = NULL; } if (!gl1->menu_video_buf) gl1->menu_video_buf = (unsigned char*) malloc(pot_width * pot_height * 4); if (bits == 16 && gl1->menu_video_buf) { conv_rgba4444_argb8888(gl1->menu_video_buf, gl1->menu_frame, width, height, pot_width * sizeof(unsigned), pitch); frame_to_copy = gl1->menu_video_buf; if (gl1->menu_texture_full_screen) { glViewport(0, 0, video_width, video_height); draw_tex(gl1, pot_width, pot_height, width, height, gl1->menu_tex, frame_to_copy); glViewport(gl1->vp.x, gl1->vp.y, gl1->vp.width, gl1->vp.height); } else draw_tex(gl1, pot_width, pot_height, width, height, gl1->menu_tex, frame_to_copy); } } #ifdef HAVE_OVERLAY if (gl1->overlay_enable && overlay_behind_menu) gl1_render_overlay(gl1, video_width, video_height); #endif if (gl1->menu_texture_enable){ do_swap = true; #ifdef VITA glUseProgram(0); bool enabled = glIsEnabled(GL_DEPTH_TEST); if(enabled) glDisable(GL_DEPTH_TEST); #endif menu_driver_frame(menu_is_alive, video_info); #ifdef VITA if(enabled) glEnable(GL_DEPTH_TEST); #endif } else #endif if (video_info->statistics_show) { if (osd_params) { font_driver_render_msg(gl1, video_info->stat_text, osd_params, NULL); #if 0 osd_params->y = 0.350f; osd_params->scale = 0.75f; font_driver_render_msg(gl1, video_info->chat_text, (const struct font_params*)&video_info->osd_stat_params, NULL); #endif } } #ifdef HAVE_GFX_WIDGETS if (widgets_active) gfx_widgets_frame(video_info); #endif #ifdef HAVE_OVERLAY if (gl1->overlay_enable && !overlay_behind_menu) gl1_render_overlay(gl1, video_width, video_height); #endif if (msg) font_driver_render_msg(gl1, msg, NULL, NULL); if (gl1->ctx_driver->update_window_title) gl1->ctx_driver->update_window_title( gl1->ctx_data); /* Screenshots. */ if (gl1->readback_buffer_screenshot) gl1_readback(gl1, 4, GL_RGBA, GL_UNSIGNED_BYTE, gl1->readback_buffer_screenshot); if (do_swap && gl1->ctx_driver->swap_buffers) gl1->ctx_driver->swap_buffers(gl1->ctx_data); /* Emscripten has to do black frame insertion in its main loop */ #ifndef EMSCRIPTEN /* Disable BFI during fast forward, slow-motion, * and pause to prevent flicker. */ if ( video_info->black_frame_insertion && !video_info->input_driver_nonblock_state && !video_info->runloop_is_slowmotion && !video_info->runloop_is_paused && !gl1->menu_texture_enable) { unsigned n; for (n = 0; n < video_info->black_frame_insertion; ++n) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); if (gl1->ctx_driver->swap_buffers) gl1->ctx_driver->swap_buffers(gl1->ctx_data); } } #endif /* check if we are fast forwarding or in menu, if we are ignore hard sync */ if ( hard_sync && !video_info->input_driver_nonblock_state ) { glClear(GL_COLOR_BUFFER_BIT); glFinish(); } if (draw) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); } gl1_context_bind_hw_render(gl1, true); return true; } static void gl1_gfx_set_nonblock_state(void *data, bool state, bool adaptive_vsync_enabled, unsigned swap_interval) { int interval = 0; gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1_context_bind_hw_render(gl1, false); if (!state) interval = swap_interval; if (gl1->ctx_driver->swap_interval) { if (adaptive_vsync_enabled && interval == 1) interval = -1; gl1->ctx_driver->swap_interval(gl1->ctx_data, interval); } gl1_context_bind_hw_render(gl1, true); } static bool gl1_gfx_alive(void *data) { unsigned temp_width = 0; unsigned temp_height = 0; bool quit = false; bool resize = false; bool ret = false; gl1_t *gl1 = (gl1_t*)data; /* Needed because some context drivers don't track their sizes */ video_driver_get_size(&temp_width, &temp_height); gl1->ctx_driver->check_window(gl1->ctx_data, &quit, &resize, &temp_width, &temp_height); if (resize) gl1->should_resize = true; ret = !quit; if (temp_width != 0 && temp_height != 0) video_driver_set_size(temp_width, temp_height); return ret; } static bool gl1_gfx_focus(void *data) { gl1_t *gl = (gl1_t*)data; if (gl && gl->ctx_driver && gl->ctx_driver->has_focus) return gl->ctx_driver->has_focus(gl->ctx_data); return true; } static bool gl1_gfx_suppress_screensaver(void *data, bool enable) { (void)data; (void)enable; return false; } static void gl1_gfx_free(void *data) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1_context_bind_hw_render(gl1, false); if (gl1->menu_frame) free(gl1->menu_frame); gl1->menu_frame = NULL; if (gl1->video_buf) free(gl1->video_buf); gl1->video_buf = NULL; if (gl1->menu_video_buf) free(gl1->menu_video_buf); gl1->menu_video_buf = NULL; if (gl1->tex) { glDeleteTextures(1, &gl1->tex); gl1->tex = 0; } if (gl1->menu_tex) { glDeleteTextures(1, &gl1->menu_tex); gl1->menu_tex = 0; } #ifdef HAVE_OVERLAY gl1_free_overlay(gl1); #endif if (gl1->extensions) string_list_free(gl1->extensions); gl1->extensions = NULL; font_driver_free_osd(); if (gl1->ctx_driver && gl1->ctx_driver->destroy) gl1->ctx_driver->destroy(gl1->ctx_data); video_context_driver_free(); free(gl1); } static bool gl1_gfx_set_shader(void *data, enum rarch_shader_type type, const char *path) { (void)data; (void)type; (void)path; return false; } static void gl1_gfx_set_rotation(void *data, unsigned rotation) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->rotation = 90 * rotation; gl1_set_projection(gl1, &gl1_default_ortho, true); } static void gl1_gfx_viewport_info(void *data, struct video_viewport *vp) { unsigned width, height; unsigned top_y, top_dist; gl1_t *gl1 = (gl1_t*)data; video_driver_get_size(&width, &height); *vp = gl1->vp; vp->full_width = width; vp->full_height = height; /* Adjust as GL viewport is bottom-up. */ top_y = vp->y + vp->height; top_dist = height - top_y; vp->y = top_dist; } static bool gl1_gfx_read_viewport(void *data, uint8_t *buffer, bool is_idle) { unsigned num_pixels = 0; gl1_t *gl1 = (gl1_t*)data; if (!gl1) return false; gl1_context_bind_hw_render(gl1, false); num_pixels = gl1->vp.width * gl1->vp.height; gl1->readback_buffer_screenshot = malloc(num_pixels * sizeof(uint32_t)); if (!gl1->readback_buffer_screenshot) goto error; if (!is_idle) video_driver_cached_frame(); video_frame_convert_rgba_to_bgr( (const void*)gl1->readback_buffer_screenshot, buffer, num_pixels); free(gl1->readback_buffer_screenshot); gl1->readback_buffer_screenshot = NULL; gl1_context_bind_hw_render(gl1, true); return true; error: gl1_context_bind_hw_render(gl1, true); return false; } static void gl1_set_texture_frame(void *data, const void *frame, bool rgb32, unsigned width, unsigned height, float alpha) { settings_t *settings = config_get_ptr(); bool menu_linear_filter = settings->bools.menu_linear_filter; unsigned pitch = width * 2; gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->menu_smooth = menu_linear_filter; gl1_context_bind_hw_render(gl1, false); if (rgb32) pitch = width * 4; if (gl1->menu_frame) free(gl1->menu_frame); gl1->menu_frame = NULL; if ( !gl1->menu_frame || gl1->menu_width != width || gl1->menu_height != height || gl1->menu_pitch != pitch) { if (pitch && height) { if (gl1->menu_frame) free(gl1->menu_frame); /* FIXME? We have to assume the pitch has no * extra padding in it because that will * mess up the POT calculation when we don't * know how many bpp there are. */ gl1->menu_frame = (unsigned char*)malloc(pitch * height); } } if (gl1->menu_frame && frame && pitch && height) { memcpy(gl1->menu_frame, frame, pitch * height); gl1->menu_width = width; gl1->menu_height = height; gl1->menu_pitch = pitch; gl1->menu_bits = rgb32 ? 32 : 16; gl1->menu_size_changed = true; } gl1_context_bind_hw_render(gl1, true); } static void gl1_get_video_output_size(void *data, unsigned *width, unsigned *height, char *desc, size_t desc_len) { gl1_t *gl = (gl1_t*)data; if (!gl || !gl->ctx_driver || !gl->ctx_driver->get_video_output_size) return; gl->ctx_driver->get_video_output_size( gl->ctx_data, width, height, desc, desc_len); } static void gl1_get_video_output_prev(void *data) { gl1_t *gl = (gl1_t*)data; if (!gl || !gl->ctx_driver || !gl->ctx_driver->get_video_output_prev) return; gl->ctx_driver->get_video_output_prev(gl->ctx_data); } static void gl1_get_video_output_next(void *data) { gl1_t *gl = (gl1_t*)data; if (!gl || !gl->ctx_driver || !gl->ctx_driver->get_video_output_next) return; gl->ctx_driver->get_video_output_next(gl->ctx_data); } static void gl1_set_video_mode(void *data, unsigned width, unsigned height, bool fullscreen) { gl1_t *gl = (gl1_t*)data; if (gl->ctx_driver->set_video_mode) gl->ctx_driver->set_video_mode(gl->ctx_data, width, height, fullscreen); } static unsigned gl1_wrap_type_to_enum(enum gfx_wrap_type type) { switch (type) { case RARCH_WRAP_REPEAT: case RARCH_WRAP_MIRRORED_REPEAT: /* mirrored not actually supported */ return GL_REPEAT; default: return GL_CLAMP; } return 0; } static void gl1_load_texture_data( GLuint id, enum gfx_wrap_type wrap_type, enum texture_filter_type filter_type, unsigned alignment, unsigned width, unsigned height, const void *frame, unsigned base_size) { GLint mag_filter, min_filter; bool use_rgba = video_driver_supports_rgba(); bool rgb32 = (base_size == (sizeof(uint32_t))); GLenum wrap = gl1_wrap_type_to_enum(wrap_type); /* GL1.x does not have mipmapping support. */ switch (filter_type) { case TEXTURE_FILTER_MIPMAP_NEAREST: case TEXTURE_FILTER_NEAREST: min_filter = GL_NEAREST; mag_filter = GL_NEAREST; break; case TEXTURE_FILTER_MIPMAP_LINEAR: case TEXTURE_FILTER_LINEAR: default: min_filter = GL_LINEAR; mag_filter = GL_LINEAR; break; } gl1_bind_texture(id, wrap, mag_filter, min_filter); #ifndef VITA glPixelStorei(GL_UNPACK_ALIGNMENT, alignment); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); #endif glTexImage2D(GL_TEXTURE_2D, 0, (use_rgba || !rgb32) ? GL_RGBA : RARCH_GL1_INTERNAL_FORMAT32, width, height, 0, (use_rgba || !rgb32) ? GL_RGBA : RARCH_GL1_TEXTURE_TYPE32, (rgb32) ? RARCH_GL1_FORMAT32 : GL_UNSIGNED_BYTE, frame); } static void video_texture_load_gl1( struct texture_image *ti, enum texture_filter_type filter_type, uintptr_t *idptr) { GLuint id; unsigned width = 0; unsigned height = 0; const void *pixels = NULL; /* Generate the OpenGL texture object */ glGenTextures(1, &id); *idptr = id; if (ti) { width = ti->width; height = ti->height; pixels = ti->pixels; } gl1_load_texture_data(id, RARCH_WRAP_EDGE, filter_type, 4 /* TODO/FIXME - dehardcode */, width, height, pixels, sizeof(uint32_t) /* TODO/FIXME - dehardcode */ ); } #ifdef HAVE_THREADS static int video_texture_load_wrap_gl1(void *data) { uintptr_t id = 0; if (!data) return 0; video_texture_load_gl1((struct texture_image*)data, TEXTURE_FILTER_NEAREST, &id); return (int)id; } #endif static uintptr_t gl1_load_texture(void *video_data, void *data, bool threaded, enum texture_filter_type filter_type) { uintptr_t id = 0; #ifdef HAVE_THREADS if (threaded) { gl1_t *gl1 = (gl1_t*)video_data; custom_command_method_t func = video_texture_load_wrap_gl1; if (gl1->ctx_driver->make_current) gl1->ctx_driver->make_current(false); return video_thread_texture_load(data, func); } #endif video_texture_load_gl1((struct texture_image*)data, filter_type, &id); return id; } static void gl1_set_aspect_ratio(void *data, unsigned aspect_ratio_idx) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->keep_aspect = true; gl1->should_resize = true; } static void gl1_unload_texture(void *data, bool threaded, uintptr_t id) { GLuint glid; gl1_t *gl1 = (gl1_t*)data; if (!id) return; #ifdef HAVE_THREADS if (threaded) { if (gl1->ctx_driver->make_current) gl1->ctx_driver->make_current(false); } #endif glid = (GLuint)id; glDeleteTextures(1, &glid); } static float gl1_get_refresh_rate(void *data) { float refresh_rate = 0.0f; if (video_context_driver_get_refresh_rate(&refresh_rate)) return refresh_rate; return 0.0f; } static void gl1_set_texture_enable(void *data, bool state, bool full_screen) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->menu_texture_enable = state; gl1->menu_texture_full_screen = full_screen; } static uint32_t gl1_get_flags(void *data) { uint32_t flags = 0; BIT32_SET(flags, GFX_CTX_FLAGS_HARD_SYNC); BIT32_SET(flags, GFX_CTX_FLAGS_BLACK_FRAME_INSERTION); BIT32_SET(flags, GFX_CTX_FLAGS_MENU_FRAME_FILTERING); BIT32_SET(flags, GFX_CTX_FLAGS_OVERLAY_BEHIND_MENU_SUPPORTED); return flags; } static const video_poke_interface_t gl1_poke_interface = { gl1_get_flags, gl1_load_texture, gl1_unload_texture, gl1_set_video_mode, gl1_get_refresh_rate, NULL, gl1_get_video_output_size, gl1_get_video_output_prev, gl1_get_video_output_next, NULL, NULL, gl1_set_aspect_ratio, NULL, gl1_set_texture_frame, gl1_set_texture_enable, font_driver_render_msg, NULL, NULL, /* grab_mouse_toggle */ NULL, /* get_current_shader */ NULL, /* get_current_software_framebuffer */ NULL, /* get_hw_render_interface */ NULL, /* set_hdr_max_nits */ NULL, /* set_hdr_paper_white_nits */ NULL, /* set_hdr_contrast */ NULL /* set_hdr_expand_gamut */ }; static void gl1_gfx_get_poke_interface(void *data, const video_poke_interface_t **iface) { (void)data; *iface = &gl1_poke_interface; } #ifdef HAVE_GFX_WIDGETS static bool gl1_gfx_widgets_enabled(void *data) { (void)data; return true; } #endif static void gl1_gfx_set_viewport_wrapper(void *data, unsigned viewport_width, unsigned viewport_height, bool force_full, bool allow_rotate) { gl1_t *gl1 = (gl1_t*)data; gl1_gfx_set_viewport(gl1, viewport_width, viewport_height, force_full, allow_rotate); } #ifdef HAVE_OVERLAY static unsigned gl1_get_alignment(unsigned pitch) { if (pitch & 1) return 1; if (pitch & 2) return 2; if (pitch & 4) return 4; return 8; } static bool gl1_overlay_load(void *data, const void *image_data, unsigned num_images) { unsigned i, j; gl1_t *gl = (gl1_t*)data; const struct texture_image *images = (const struct texture_image*)image_data; if (!gl) return false; gl1_context_bind_hw_render(gl, false); gl1_free_overlay(gl); gl->overlay_tex = (GLuint*) calloc(num_images, sizeof(*gl->overlay_tex)); if (!gl->overlay_tex) { gl1_context_bind_hw_render(gl, true); return false; } gl->overlay_vertex_coord = (GLfloat*) calloc(2 * 4 * num_images, sizeof(GLfloat)); gl->overlay_tex_coord = (GLfloat*) calloc(2 * 4 * num_images, sizeof(GLfloat)); gl->overlay_color_coord = (GLfloat*) calloc(4 * 4 * num_images, sizeof(GLfloat)); if ( !gl->overlay_vertex_coord || !gl->overlay_tex_coord || !gl->overlay_color_coord) return false; gl->overlays = num_images; glGenTextures(num_images, gl->overlay_tex); for (i = 0; i < num_images; i++) { unsigned alignment = gl1_get_alignment(images[i].width * sizeof(uint32_t)); gl1_load_texture_data(gl->overlay_tex[i], RARCH_WRAP_EDGE, TEXTURE_FILTER_LINEAR, alignment, images[i].width, images[i].height, images[i].pixels, sizeof(uint32_t)); /* Default. Stretch to whole screen. */ gl1_overlay_tex_geom(gl, i, 0, 0, 1, 1); gl1_overlay_vertex_geom(gl, i, 0, 0, 1, 1); for (j = 0; j < 16; j++) gl->overlay_color_coord[16 * i + j] = 1.0f; } gl1_context_bind_hw_render(gl, true); return true; } static void gl1_overlay_enable(void *data, bool state) { gl1_t *gl = (gl1_t*)data; if (!gl) return; gl->overlay_enable = state; if (gl->fullscreen && gl->ctx_driver->show_mouse) gl->ctx_driver->show_mouse(gl->ctx_data, state); } static void gl1_overlay_full_screen(void *data, bool enable) { gl1_t *gl = (gl1_t*)data; if (gl) gl->overlay_full_screen = enable; } static void gl1_overlay_set_alpha(void *data, unsigned image, float mod) { GLfloat *color = NULL; gl1_t *gl = (gl1_t*)data; if (!gl) return; color = (GLfloat*)&gl->overlay_color_coord[image * 16]; color[ 0 + 3] = mod; color[ 4 + 3] = mod; color[ 8 + 3] = mod; color[12 + 3] = mod; } static const video_overlay_interface_t gl1_overlay_interface = { gl1_overlay_enable, gl1_overlay_load, gl1_overlay_tex_geom, gl1_overlay_vertex_geom, gl1_overlay_full_screen, gl1_overlay_set_alpha, }; static void gl1_get_overlay_interface(void *data, const video_overlay_interface_t **iface) { (void)data; *iface = &gl1_overlay_interface; } #endif static bool gl1_has_windowed(void *data) { gl1_t *gl = (gl1_t*)data; if (gl && gl->ctx_driver) return gl->ctx_driver->has_windowed; return false; } video_driver_t video_gl1 = { gl1_gfx_init, gl1_gfx_frame, gl1_gfx_set_nonblock_state, gl1_gfx_alive, gl1_gfx_focus, gl1_gfx_suppress_screensaver, gl1_has_windowed, gl1_gfx_set_shader, gl1_gfx_free, "gl1", gl1_gfx_set_viewport_wrapper, gl1_gfx_set_rotation, gl1_gfx_viewport_info, gl1_gfx_read_viewport, NULL, /* read_frame_raw */ #ifdef HAVE_OVERLAY gl1_get_overlay_interface, #endif #ifdef HAVE_VIDEO_LAYOUT NULL, #endif gl1_gfx_get_poke_interface, gl1_wrap_type_to_enum, #ifdef HAVE_GFX_WIDGETS gl1_gfx_widgets_enabled #endif };
26.517179
142
0.618726
5311715ab422cf777ab59453243a8b5fc296a7bd
4,311
h
C
HunterSkill/game/classes.h
SmoLL-iCe/HunterSkill
1b6d56045f6f29b9da9e15e84e4214667400dd60
[ "MIT" ]
4
2021-07-16T03:18:35.000Z
2021-07-30T21:04:01.000Z
HunterSkill/game/classes.h
SmoLL-iCe/HunterSkill
1b6d56045f6f29b9da9e15e84e4214667400dd60
[ "MIT" ]
null
null
null
HunterSkill/game/classes.h
SmoLL-iCe/HunterSkill
1b6d56045f6f29b9da9e15e84e4214667400dd60
[ "MIT" ]
null
null
null
#pragma once #include <Windows.h> #include <iostream> #include <vector> #include "shared_config.h" #include "../utils/mem.h" struct vec3 final { float x = 0, y = 0, z = 0; vec3( ) {}; vec3( const float x, const float y, const float z ) : x( x ), y( y ), z( z ) {} vec3 operator + ( const vec3& rhs ) const { return vec3( x + rhs.x, y + rhs.y, z + rhs.z ); } vec3 operator - ( const vec3& rhs ) const { return vec3( x - rhs.x, y - rhs.y, z - rhs.z ); } vec3 operator * ( const float& rhs ) const { return vec3( x * rhs, y * rhs, z * rhs ); } vec3 operator / ( const float& rhs ) const { return vec3( x / rhs, y / rhs, z / rhs ); } bool operator == ( const vec3& rhs ) const { return x == rhs.x && y == rhs.y && z == rhs.z; } vec3& operator += ( const vec3& rhs ) { return *this = *this + rhs; } vec3& operator -= ( const vec3& rhs ) { return *this = *this - rhs; } vec3& operator *= ( const float& rhs ) { return *this = *this * rhs; } vec3& operator /= ( const float& rhs ) { return *this = *this / rhs; } float length( ) const { return sqrtf( x * x + y * y + z * z ); } vec3 normalize( ) const { return *this * ( 1 / length( ) ); } float distance( const vec3* rhs ) const { if ( !rhs ) return 0; return ( *this - *rhs ).length( ); } float dis_x( const vec3* rhs ) const { if ( !rhs ) return 0; const auto sub_x = ( this->x - rhs->x ); return sqrtf( sub_x * sub_x ); } float dis_y( const vec3* rhs ) const { if ( !rhs ) return 0; const auto sub_y = ( this->y - rhs->y ); return sqrtf( sub_y * sub_y ); } float dis_z( const vec3* rhs ) const { if ( !rhs ) return 0; const auto sub_z = ( this->z - rhs->z ); return sqrtf( sub_z * sub_z ); } float distance_horizontal( const vec3* rhs ) const { if ( !rhs ) return 0; const auto sub_x = ( this->x - rhs->x ); const auto sub_z = ( this->z - rhs->z ); return sqrtf( sub_x * sub_x + sub_z * sub_z ); } float distance_vertical( const vec3* rhs ) const { if ( !rhs ) return 0; const auto sub_y = ( this->y - rhs->y ); return sqrtf( sub_y * sub_y ); } void Invert( ) { *this *= -1; } bool empty( ) const { return ( x == 0.f && y == 0.f && z == 0.f ); } }; namespace game { class c_entity { public: bool is_boss( ) { return ( *reinterpret_cast<uintptr_t*>( uintptr_t( this ) + options::reversed::i( )->offset.is_boss ) == 0x1 ); } bool is_valid( ) { if ( !mem::is_valid_read( uintptr_t( this ) ) || !mem::is_valid_read( uintptr_t( this ) + options::reversed::i( )->offset.sub_to_health ) ) return false; return *r_cast<uint32_t*>( uintptr_t( this ) + 0xC ) == 8 && *r_cast<uint8_t*>( uintptr_t( this ) + 0x14 ) & 1; } vec3 get_pos( ) { return *reinterpret_cast<vec3*>( uintptr_t( this ) + options::reversed::i( )->offset.pos ); } float get_health( ) { auto sub = *r_cast<uintptr_t*>( uintptr_t( this ) + options::reversed::i( )->offset.sub_to_health ); if ( !sub ) return 0.f; return *r_cast<float*>( sub + 0x64 ); } float get_max_health( ) { auto sub = *r_cast<uintptr_t*>( uintptr_t( this ) + options::reversed::i( )->offset.sub_to_health ); if ( !sub ) return 0.f; return *r_cast<float*>( sub + 0x60 ); } }; struct s_boss_entity { c_entity* ptr = nullptr; float health = 0.f; float max_health = 0.f; vec3 pos{ }; char file[ 100 ]{ }; }; struct s_player { int type_ = -1; bool valid = false; vec3 pos{ }; char name[ 100 ]{ }; c_entity* ptr = nullptr; }; struct s_caused_damage { uintptr_t entity = 0; float best_hit = 0; float last_hit = 0; float low_hit = 0; int hit_count = 0; float total_damage = 0; int type = 0; }; struct s_monster_damage { uintptr_t target_ptr = 0; char name[ 100 ]{ }; std::vector<s_caused_damage> who_caused_damage{ }; float hp_max = 0; float hp = 0.f; }; #pragma pack(push, 1) struct s_body { bool head = false; bool chest = false; bool arms = false; bool waist = false; bool foot = false; bool fail = true; }; struct s_body_ids { uint32_t head = 0xFFFFFFFF; uint32_t chest = 0xFFFFFFFF;; uint32_t arms = 0xFFFFFFFF; uint32_t waist = 0xFFFFFFFF; uint32_t foot = 0xFFFFFFFF; uint32_t fail = 0xFFFFFFFF; }; #pragma pack(pop) struct s_skin { uint32_t id = 0; game::s_body b; }; }
24.494318
142
0.593598
1b2c3abfd17191bb22f7b703ba45d3a870b7130d
549
h
C
legacy/TL/TL/TLRPCphone_requestCall.h
we11cheng/WCTelegram
8d6e098be215ea6e8c4f557a8e5a03620c0fad61
[ "MIT" ]
3
2018-08-28T12:37:54.000Z
2021-11-19T03:23:26.000Z
legacy/TL/TL/TLRPCphone_requestCall.h
we11cheng/WCTelegram
8d6e098be215ea6e8c4f557a8e5a03620c0fad61
[ "MIT" ]
null
null
null
legacy/TL/TL/TLRPCphone_requestCall.h
we11cheng/WCTelegram
8d6e098be215ea6e8c4f557a8e5a03620c0fad61
[ "MIT" ]
4
2020-02-24T15:32:39.000Z
2021-11-19T03:23:20.000Z
#import <Foundation/Foundation.h> #import "TLObject.h" #import "TLMetaRpc.h" @class TLInputUser; @class TLPhoneCallProtocol; @class TLphone_PhoneCall; @interface TLRPCphone_requestCall : TLMetaRpc @property (nonatomic, retain) TLInputUser *user_id; @property (nonatomic) int32_t random_id; @property (nonatomic, retain) NSData *g_a; @property (nonatomic, retain) TLPhoneCallProtocol *protocol; - (Class)responseClass; - (int)impliedResponseSignature; @end @interface TLRPCphone_requestCall$phone_requestCall : TLRPCphone_requestCall @end
19.607143
76
0.795993
120b1a74fe2b22c1fb82eaef88357517e939d3a1
3,941
c
C
fmt/src/string_array_find_exact.c
josborne-noaa/PyFerret
8496508e9902c0184898522e9f89f6caea6d4539
[ "Unlicense" ]
44
2016-03-18T22:05:31.000Z
2021-12-23T01:50:09.000Z
fmt/src/string_array_find_exact.c
josborne-noaa/PyFerret
8496508e9902c0184898522e9f89f6caea6d4539
[ "Unlicense" ]
88
2016-08-19T08:05:37.000Z
2022-03-28T23:29:21.000Z
fmt/src/string_array_find_exact.c
josborne-noaa/PyFerret
8496508e9902c0184898522e9f89f6caea6d4539
[ "Unlicense" ]
24
2016-02-07T18:12:06.000Z
2022-02-19T09:06:17.000Z
/* * * This software was developed by the Thermal Modeling and Analysis * Project(TMAP) of the National Oceanographic and Atmospheric * Administration's (NOAA) Pacific Marine Environmental Lab(PMEL), * hereafter referred to as NOAA/PMEL/TMAP. * * Access and use of this software shall impose the following * obligations and understandings on the user. The user is granted the * right, without any fee or cost, to use, copy, modify, alter, enhance * and distribute this software, and any derivative works thereof, and * its supporting documentation for any purpose whatsoever, provided * that this entire notice appears in all copies of the software, * derivative works and supporting documentation. Further, the user * agrees to credit NOAA/PMEL/TMAP in any publications that result from * the use of this software or in any product that includes this * software. The names TMAP, NOAA and/or PMEL, however, may not be used * in any advertising or publicity to endorse or promote any products * or commercial entity unless specific written permission is obtained * from NOAA/PMEL/TMAP. The user also understands that NOAA/PMEL/TMAP * is not obligated to provide the user with any support, consulting, * training or assistance of any kind with regard to the use, operation * and performance of this software nor to provide the user with any * updates, revisions, new versions or "bug fixes". * * THIS SOFTWARE IS PROVIDED BY NOAA/PMEL/TMAP "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 NOAA/PMEL/TMAP BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF * CONTRACT, NEGLIGENCE OR OTHER TORTUOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. * */ /* 06/04 *ywei* Created to find a string in a string array fast. The matching method is exactly equal. 4/06 *kob* change type of 1st argument to double, for 64-bit build */ #include <Python.h> /* make sure Python.h is first */ #include <stdio.h> #include <stdlib.h> #include "fmtprotos.h" #include "string_array.h" void FORTRAN(string_array_find_exact)(void **string_array_header, char *test_string, int *test_len, int *result_array, int *result_array_size, int *num_indices) { int i,j=0; int true_test_len, true_model_len, array_size, string_size, hash_value, result_array_size1; SA_Head * head; List_Node *bucket, *p; char * model_string; int match=0; head = *string_array_header; if( head != NULL ) { array_size = head->array_size; string_size = head->string_size; FORTRAN(tm_get_strlen)(&true_test_len, test_len, test_string); hash_value = string_array_hash(test_string, true_test_len, 0, array_size); if(true_test_len ==0){ result_array_size1 = 5; } else { result_array_size1 = *result_array_size; } bucket = head->hash_table[hash_value]; for(p=bucket; p; p=p->next) { model_string=&(head->string_array[(p->index-1)*string_size]); FORTRAN(string_array_get_strlen)(string_array_header, &(p->index), &true_model_len); match = 0; if(true_model_len == true_test_len){ match = 1; for( i=0; i<true_model_len; i++){ if(test_string[i]!=model_string[i]){ match = 0; break; } } } if(match==1){ if(j<result_array_size1){ result_array[j]=p->index; j++; } else{ break; } } } } else{ printf("\nString array not initialized yet (string_array_find_exact)!\n"); } *num_indices = j; }
34.269565
100
0.683837
494f89b62d13b7925914f9f1e57bafad2e3cfdb3
62,786
h
C
libs/quicktime/include/OSA.h
jegun/openFrameworks
79d43f249b50eb36ddcbc093dfea2c0a4bf20aa5
[ "MIT" ]
18
2015-01-18T22:34:22.000Z
2020-09-06T20:30:30.000Z
libs/quicktime/include/OSA.h
nmbakfm/club_projection_mapping
95dd0d7604fce397fcdf058d09085fb32b184257
[ "MIT" ]
6
2015-01-05T04:34:43.000Z
2015-04-25T03:48:00.000Z
libs/quicktime/include/OSA.h
nmbakfm/club_projection_mapping
95dd0d7604fce397fcdf058d09085fb32b184257
[ "MIT" ]
10
2015-01-18T23:46:10.000Z
2019-08-25T12:10:04.000Z
/* File: OSA.h Contains: Open Scripting Architecture Client Interfaces. Version: Technology: AppleScript 1.4 Release: QuickTime 6.0.2 Copyright: (c) 1992-2001 by Apple Computer, Inc., all rights reserved Bugs?: For bug reports, consult the following page on the World Wide Web: http://developer.apple.com/bugreporter/ */ #ifndef __OSA__ #define __OSA__ #ifndef __MACERRORS__ #include <MacErrors.h> #endif #ifndef __APPLEEVENTS__ #include <AppleEvents.h> #endif #ifndef __AEOBJECTS__ #include <AEObjects.h> #endif #ifndef __COMPONENTS__ #include <Components.h> #endif #ifndef __MACERRORS__ #include <MacErrors.h> #endif #if PRAGMA_ONCE #pragma once #endif #ifdef __cplusplus extern "C" { #endif #if PRAGMA_IMPORT #pragma import on #endif #if PRAGMA_STRUCT_ALIGN #pragma options align=mac68k #elif PRAGMA_STRUCT_PACKPUSH #pragma pack(push, 2) #elif PRAGMA_STRUCT_PACK #pragma pack(2) #endif /************************************************************************** Types and Constants **************************************************************************/ /* The componenent manager type code for components that support the OSA interface defined here. */ /* 0x6f736120 */ enum { kOSAComponentType = FOUR_CHAR_CODE('osa ') }; /* 0x73637074 */ enum { kOSAGenericScriptingComponentSubtype = FOUR_CHAR_CODE('scpt') }; /* Type of script document files. */ /* 0x6f736173 */ enum { kOSAFileType = FOUR_CHAR_CODE('osas') }; /* Suite and event code of the RecordedText event. (See OSAStartRecording, below.) */ /* 0x61736372 */ enum { kOSASuite = FOUR_CHAR_CODE('ascr') }; /* 0x72656364 */ enum { kOSARecordedText = FOUR_CHAR_CODE('recd') }; /* Selector returns boolean */ /* 0x6d6f6469 */ enum { kOSAScriptIsModified = FOUR_CHAR_CODE('modi') }; /* Selector returns boolean */ /* 0x63736372 */ enum { kOSAScriptIsTypeCompiledScript = FOUR_CHAR_CODE('cscr') }; /* Selector returns boolean */ /* 0x76616c75 */ enum { kOSAScriptIsTypeScriptValue = FOUR_CHAR_CODE('valu') }; /* Selector returns boolean */ /* 0x636e7478 */ enum { kOSAScriptIsTypeScriptContext = FOUR_CHAR_CODE('cntx') }; /* Selector returns a DescType which may be passed to OSACoerceToDesc */ /* 0x62657374 */ enum { kOSAScriptBestType = FOUR_CHAR_CODE('best') }; /* This selector is used to determine whether a script has source associated with it that when given to OSAGetSource, the call will not fail. The selector returns a boolean. */ /* 0x67737263 */ enum { kOSACanGetSource = FOUR_CHAR_CODE('gsrc') }; enum { typeOSADialectInfo = FOUR_CHAR_CODE('difo'), /* 0x6469666f */ keyOSADialectName = FOUR_CHAR_CODE('dnam'), /* 0x646e616d */ keyOSADialectCode = FOUR_CHAR_CODE('dcod'), /* 0x64636f64 */ keyOSADialectLangCode = FOUR_CHAR_CODE('dlcd'), /* 0x646c6364 */ keyOSADialectScriptCode = FOUR_CHAR_CODE('dscd') /* 0x64736364 */ }; typedef ComponentResult OSAError; /* Under the Open Scripting Architecture all error results are longs */ typedef unsigned long OSAID; /* OSAIDs allow transparent manipulation of scripts associated with various scripting systems. */ enum { kOSANullScript = 0L }; /* No -script constant. */ enum { kOSANullMode = 0, /* sounds better */ kOSAModeNull = 0 /* tastes consistent */ }; /* Some routines take flags that control their execution. This constant declares default mode settings are used. */ typedef CALLBACK_API( OSErr , OSACreateAppleEventProcPtr )(AEEventClass theAEEventClass, AEEventID theAEEventID, const AEAddressDesc *target, short returnID, long transactionID, AppleEvent *result, long refCon); typedef CALLBACK_API( OSErr , OSASendProcPtr )(const AppleEvent *theAppleEvent, AppleEvent *reply, AESendMode sendMode, AESendPriority sendPriority, long timeOutInTicks, AEIdleUPP idleProc, AEFilterUPP filterProc, long refCon); typedef STACK_UPP_TYPE(OSACreateAppleEventProcPtr) OSACreateAppleEventUPP; typedef STACK_UPP_TYPE(OSASendProcPtr) OSASendUPP; #if OPAQUE_UPP_TYPES EXTERN_API(OSACreateAppleEventUPP) NewOSACreateAppleEventUPP (OSACreateAppleEventProcPtr userRoutine); EXTERN_API(OSASendUPP) NewOSASendUPP (OSASendProcPtr userRoutine); EXTERN_API(void) DisposeOSACreateAppleEventUPP (OSACreateAppleEventUPP userUPP); EXTERN_API(void) DisposeOSASendUPP (OSASendUPP userUPP); EXTERN_API(OSErr) InvokeOSACreateAppleEventUPP (AEEventClass theAEEventClass, AEEventID theAEEventID, const AEAddressDesc * target, short returnID, long transactionID, AppleEvent * result, long refCon, OSACreateAppleEventUPP userUPP); EXTERN_API(OSErr) InvokeOSASendUPP (const AppleEvent * theAppleEvent, AppleEvent * reply, AESendMode sendMode, AESendPriority sendPriority, long timeOutInTicks, AEIdleUPP idleProc, AEFilterUPP filterProc, long refCon, OSASendUPP userUPP); #else enum { uppOSACreateAppleEventProcInfo = 0x000FEFE0 }; /* pascal 2_bytes Func(4_bytes, 4_bytes, 4_bytes, 2_bytes, 4_bytes, 4_bytes, 4_bytes) */ enum { uppOSASendProcInfo = 0x003FEFE0 }; /* pascal 2_bytes Func(4_bytes, 4_bytes, 4_bytes, 2_bytes, 4_bytes, 4_bytes, 4_bytes, 4_bytes) */ #define NewOSACreateAppleEventUPP(userRoutine) (OSACreateAppleEventUPP)NewRoutineDescriptor((ProcPtr)(userRoutine), uppOSACreateAppleEventProcInfo, GetCurrentArchitecture()) #define NewOSASendUPP(userRoutine) (OSASendUPP)NewRoutineDescriptor((ProcPtr)(userRoutine), uppOSASendProcInfo, GetCurrentArchitecture()) #define DisposeOSACreateAppleEventUPP(userUPP) DisposeRoutineDescriptor(userUPP) #define DisposeOSASendUPP(userUPP) DisposeRoutineDescriptor(userUPP) #define InvokeOSACreateAppleEventUPP(theAEEventClass, theAEEventID, target, returnID, transactionID, result, refCon, userUPP) (OSErr)CALL_SEVEN_PARAMETER_UPP((userUPP), uppOSACreateAppleEventProcInfo, (theAEEventClass), (theAEEventID), (target), (returnID), (transactionID), (result), (refCon)) #define InvokeOSASendUPP(theAppleEvent, reply, sendMode, sendPriority, timeOutInTicks, idleProc, filterProc, refCon, userUPP) (OSErr)CALL_EIGHT_PARAMETER_UPP((userUPP), uppOSASendProcInfo, (theAppleEvent), (reply), (sendMode), (sendPriority), (timeOutInTicks), (idleProc), (filterProc), (refCon)) #endif /* support for pre-Carbon UPP routines: NewXXXProc and CallXXXProc */ #define NewOSACreateAppleEventProc(userRoutine) NewOSACreateAppleEventUPP(userRoutine) #define NewOSASendProc(userRoutine) NewOSASendUPP(userRoutine) #define CallOSACreateAppleEventProc(userRoutine, theAEEventClass, theAEEventID, target, returnID, transactionID, result, refCon) InvokeOSACreateAppleEventUPP(theAEEventClass, theAEEventID, target, returnID, transactionID, result, refCon, userRoutine) #define CallOSASendProc(userRoutine, theAppleEvent, reply, sendMode, sendPriority, timeOutInTicks, idleProc, filterProc, refCon) InvokeOSASendUPP(theAppleEvent, reply, sendMode, sendPriority, timeOutInTicks, idleProc, filterProc, refCon, userRoutine) /************************************************************************** OSA Interface Descriptions ************************************************************************** The OSA Interface is broken down into a required interface, and several optional interfaces to support additional functionality. A given scripting component may choose to support only some of the optional interfaces in addition to the basic interface. The OSA Component Flags may be used to query the Component Manager to find a scripting component with a particular capability, or determine if a particular scripting component supports a particular capability. **************************************************************************/ /* OSA Component Flags: */ enum { kOSASupportsCompiling = 0x0002, kOSASupportsGetSource = 0x0004, kOSASupportsAECoercion = 0x0008, kOSASupportsAESending = 0x0010, kOSASupportsRecording = 0x0020, kOSASupportsConvenience = 0x0040, kOSASupportsDialects = 0x0080, kOSASupportsEventHandling = 0x0100 }; /* Component Selectors: */ enum { kOSASelectLoad = 0x0001, kOSASelectStore = 0x0002, kOSASelectExecute = 0x0003, kOSASelectDisplay = 0x0004, kOSASelectScriptError = 0x0005, kOSASelectDispose = 0x0006, kOSASelectSetScriptInfo = 0x0007, kOSASelectGetScriptInfo = 0x0008, kOSASelectSetActiveProc = 0x0009, kOSASelectGetActiveProc = 0x000A }; /* Compiling: */ enum { kOSASelectScriptingComponentName = 0x0102, kOSASelectCompile = 0x0103, kOSASelectCopyID = 0x0104 }; /* GetSource: */ enum { kOSASelectGetSource = 0x0201 }; /* AECoercion: */ enum { kOSASelectCoerceFromDesc = 0x0301, kOSASelectCoerceToDesc = 0x0302 }; /* AESending: */ enum { kOSASelectSetSendProc = 0x0401, kOSASelectGetSendProc = 0x0402, kOSASelectSetCreateProc = 0x0403, kOSASelectGetCreateProc = 0x0404, kOSASelectSetDefaultTarget = 0x0405 }; /* Recording: */ enum { kOSASelectStartRecording = 0x0501, kOSASelectStopRecording = 0x0502 }; /* Convenience: */ enum { kOSASelectLoadExecute = 0x0601, kOSASelectCompileExecute = 0x0602, kOSASelectDoScript = 0x0603 }; /* Dialects: */ enum { kOSASelectSetCurrentDialect = 0x0701, kOSASelectGetCurrentDialect = 0x0702, kOSASelectAvailableDialects = 0x0703, kOSASelectGetDialectInfo = 0x0704, kOSASelectAvailableDialectCodeList = 0x0705 }; /* Event Handling: */ enum { kOSASelectSetResumeDispatchProc = 0x0801, kOSASelectGetResumeDispatchProc = 0x0802, kOSASelectExecuteEvent = 0x0803, kOSASelectDoEvent = 0x0804, kOSASelectMakeContext = 0x0805 }; /* scripting component specific selectors are added beginning with this value */ enum { kOSASelectComponentSpecificStart = 0x1001 }; /* Mode Flags: Warning: These should not conflict with the AESend mode flags in AppleEvents.h, because we may want to use them as OSA mode flags too. */ /* This mode flag may be passed to OSALoad, OSAStore or OSACompile to instruct the scripting component to not retain the "source" of an expression. This will cause the OSAGetSource call to return the error errOSASourceNotAvailable if used. However, some scripting components may not retain the source anyway. This is mainly used when either space efficiency is desired, or a script is to be "locked" so that its implementation may not be viewed. */ enum { kOSAModePreventGetSource = 0x00000001 }; /* These mode flags may be passed to OSACompile, OSAExecute, OSALoadExecute OSACompileExecute, OSADoScript, OSAExecuteEvent, or OSADoEvent to indicate whether or not the script may interact with the user, switch layer or reconnect if necessary. Any AppleEvents will be sent with the corresponding AESend mode supplied. */ enum { kOSAModeNeverInteract = kAENeverInteract, kOSAModeCanInteract = kAECanInteract, kOSAModeAlwaysInteract = kAEAlwaysInteract, kOSAModeDontReconnect = kAEDontReconnect }; /* This mode flag may be passed to OSACompile, OSAExecute, OSALoadExecute OSACompileExecute, OSADoScript, OSAExecuteEvent, or OSADoEvent to indicate whether or not AppleEvents should be sent with the kAECanSwitchLayer mode flag sent or not. NOTE: This flag is exactly the opposite sense of the AppleEvent flag kAECanSwitchLayer. This is to provide a more convenient default, i.e. not supplying any mode (kOSAModeNull) means to send events with kAECanSwitchLayer. Supplying the kOSAModeCantSwitchLayer mode flag will cause AESend to be called without kAECanSwitchLayer. */ enum { kOSAModeCantSwitchLayer = 0x00000040 }; /* This mode flag may be passed to OSACompile, OSAExecute, OSALoadExecute OSACompileExecute, OSADoScript, OSAExecuteEvent, or OSADoEvent to indicate whether or not AppleEvents should be sent with the kAEDontRecord mode flag sent or not. NOTE: This flag is exactly the opposite sense of the AppleEvent flag kAEDontRecord. This is to provide a more convenient default, i.e. not supplying any mode (kOSAModeNull) means to send events with kAEDontRecord. Supplying the kOSAModeDoRecord mode flag will cause AESend to be called without kAEDontRecord. */ enum { kOSAModeDoRecord = 0x00001000 }; /* This is a mode flag for OSACompile that indicates that a context should be created as the result of compilation. All handler definitions are inserted into the new context, and variables are initialized by evaluating their initial values in a null context (i.e. they must be constant expressions). */ enum { kOSAModeCompileIntoContext = 0x00000002 }; /* This is a mode flag for OSACompile that indicates that the previous script ID (input to OSACompile) should be augmented with any new definitions in the sourceData rather than replaced with a new script. This means that the previous script ID must designate a context. The presence of this flag causes the kOSAModeCompileIntoContext flag to be implicitly used, causing any new definitions to be initialized in a null context. */ enum { kOSAModeAugmentContext = 0x00000004 }; /* This mode flag may be passed to OSADisplay or OSADoScript to indicate that output only need be human-readable, not re-compilable by OSACompile. If used, output may be arbitrarily "beautified", e.g. quotes may be left off of string values, long lists may have elipses, etc. */ enum { kOSAModeDisplayForHumans = 0x00000008 }; /* This mode flag may be passed to OSAStore in the case where the scriptID is a context. This causes the context to be saved, but not the context's parent context. When the stored context is loaded back in, the parent will be kOSANullScript. */ enum { kOSAModeDontStoreParent = 0x00010000 }; /* This mode flag may be passed to OSAExecuteEvent to cause the event to be dispatched to the direct object of the event. The direct object (or subject attribute if the direct object is a non-object specifier) will be resolved, and the resulting script object will be the recipient of the message. The context argument to OSAExecuteEvent will serve as the root of the lookup/resolution process. */ enum { kOSAModeDispatchToDirectObject = 0x00020000 }; /* This mode flag may be passed to OSAExecuteEvent to indicate that components do not have to get the data of object specifier arguments. */ enum { kOSAModeDontGetDataForArguments = 0x00040000 }; /************************************************************************** OSA Basic Scripting Interface ************************************************************************** Scripting components must at least support the Basic Scripting interface. **************************************************************************/ /* Loading and Storing Scripts: These routines allow scripts to be loaded and stored in their internal (possibly compiled, non-text) representation. */ /* Resource type for scripts */ enum { kOSAScriptResourceType = kOSAGenericScriptingComponentSubtype }; /* Default type given to OSAStore which creates "generic" loadable script data descriptors. */ enum { typeOSAGenericStorage = kOSAScriptResourceType }; EXTERN_API( OSAError ) OSALoad (ComponentInstance scriptingComponent, const AEDesc * scriptData, long modeFlags, OSAID * resultingScriptID) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0001, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectLoad, 12); Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSABadStorageType: scriptData not for this scripting component errOSACorruptData: data seems to be corrupt errOSADataFormatObsolete script data format is no longer supported errOSADataFormatTooNew script data format is from a newer version ModeFlags: kOSAModePreventGetSource */ EXTERN_API( OSAError ) OSAStore (ComponentInstance scriptingComponent, OSAID scriptID, DescType desiredType, long modeFlags, AEDesc * resultingScriptData) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0002, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectStore, 16); Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errOSABadStorageType: desiredType not for this scripting component ModeFlags: kOSAModePreventGetSource kOSAModeDontStoreParent */ /* Executing Scripts: */ EXTERN_API( OSAError ) OSAExecute (ComponentInstance scriptingComponent, OSAID compiledScriptID, OSAID contextID, long modeFlags, OSAID * resultingScriptValueID) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0003, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectExecute, 16); This call runs a script. The contextID represents the environment with which global variables in the script are resolved. The constant kOSANullScript may be used for the contextID if the application wishes to not deal with context directly (a default one is associated with each scripting component instance). The resultingScriptValueID is the result of evaluation, and contains a value which may be displayed using the OSAGetSource call. The modeFlags convey scripting component specific information. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errOSAScriptError: the executing script got an error ModeFlags: kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord */ /* Displaying results: */ EXTERN_API( OSAError ) OSADisplay (ComponentInstance scriptingComponent, OSAID scriptValueID, DescType desiredType, long modeFlags, AEDesc * resultingText) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0004, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectDisplay, 16); This call is used to convert results (script value IDs) into displayable text. The desiredType should be at least typeChar, and modeFlags are scripting system specific flags to control the formatting of the resulting text. This call differs from OSAGetSource in that (1) it always produces at least typeChar, (2) is only works on script values, (3) it may display it's output in non-compilable form (e.g. without string quotes, elipses inserted in long and/or circular lists, etc.) and (4) it is required by the basic scripting interface. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errAECoercionFail: desiredType not supported by scripting component ModeFlags: kOSAModeDisplayForHumans */ /* Getting Error Information: */ EXTERN_API( OSAError ) OSAScriptError (ComponentInstance scriptingComponent, OSType selector, DescType desiredType, AEDesc * resultingErrorDescription) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0005, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectScriptError, 12); Whenever script execution returns errOSAExecutionError, this routine may be used to get information about that error. The selector describes the type of information desired about the error (various selectors are listed below). The desiredType indicates the data type of the result desired for that selector. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSABadSelector: selector not supported by scripting component errAECoercionFail: desiredType not supported by scripting component */ /* OSAScriptError selectors: */ /* This selector is used to determine the error number of a script error. These error numbers may be either system error numbers, or error numbers that are scripting component specific. Required desiredTypes: typeShortInteger */ enum { kOSAErrorNumber = keyErrorNumber }; /* This selector is used to determine the full error message associated with the error number. It should include the name of the application which caused the error, as well as the specific error that occurred. This selector is sufficient for simple error reporting (but see kOSAErrorBriefMessage, below). Required desiredTypes: typeChar error message string */ enum { kOSAErrorMessage = keyErrorString }; /* This selector is used to determine a brief error message associated with the error number. This message and should not mention the name of the application which caused the error, any partial results or offending object (see kOSAErrorApp, kOSAErrorPartialResult and kOSAErrorOffendingObject, below). Required desiredTypes: typeChar brief error message string */ /* 0x65727262 */ enum { kOSAErrorBriefMessage = FOUR_CHAR_CODE('errb') }; /* This selector is used to determine which application actually got the error (if it was the result of an AESend), or the current application if .... Required desiredTypes: typeProcessSerialNumber PSN of the errant application typeChar name of the errant application */ /* 0x65726170 */ enum { kOSAErrorApp = FOUR_CHAR_CODE('erap') }; /* This selector is used to determine any partial result returned by an operation. If an AESend call failed, but a partial result was returned, then the partial result may be returned as an AEDesc. Required desiredTypes: typeBest AEDesc of any partial result */ /* 0x70746c72 */ enum { kOSAErrorPartialResult = FOUR_CHAR_CODE('ptlr') }; /* This selector is used to determine any object which caused the error that may have been indicated by an application. The result is an AEDesc. Required desiredTypes: typeBest AEDesc of any offending object */ /* 0x65726f62 */ enum { kOSAErrorOffendingObject = FOUR_CHAR_CODE('erob') }; /* This selector is used to determine the type expected by a coercion operation if a type error occurred. */ /* 0x65727274 */ enum { kOSAErrorExpectedType = FOUR_CHAR_CODE('errt') }; /* This selector is used to determine the source text range (start and end positions) of where the error occurred. Required desiredTypes: typeOSAErrorRange */ /* 0x65726e67 */ enum { kOSAErrorRange = FOUR_CHAR_CODE('erng') }; /* An AERecord type containing keyOSASourceStart and keyOSASourceEnd fields of type short. */ /* 0x65726e67 */ enum { typeOSAErrorRange = FOUR_CHAR_CODE('erng') }; /* Field of a typeOSAErrorRange record of typeShortInteger */ /* 0x73726373 */ enum { keyOSASourceStart = FOUR_CHAR_CODE('srcs') }; /* Field of a typeOSAErrorRange record of typeShortInteger */ /* 0x73726365 */ enum { keyOSASourceEnd = FOUR_CHAR_CODE('srce') }; /* Disposing Script IDs: */ EXTERN_API( OSAError ) OSADispose (ComponentInstance scriptingComponent, OSAID scriptID) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0006, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectDispose, 4); Disposes a script or context. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID */ /* Getting and Setting Script Information: */ EXTERN_API( OSAError ) OSASetScriptInfo (ComponentInstance scriptingComponent, OSAID scriptID, OSType selector, long value) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0007, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectSetScriptInfo, 12); Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errOSABadSelector: selector not supported by scripting component or selector not for this scriptID */ EXTERN_API( OSAError ) OSAGetScriptInfo (ComponentInstance scriptingComponent, OSAID scriptID, OSType selector, long * result) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0008, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetScriptInfo, 12); Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errOSABadSelector: selector not supported by scripting component or selector not for this scriptID */ /* Manipulating the ActiveProc: Scripting systems will supply default values for these procedures if they are not set by the client: */ typedef CALLBACK_API( OSErr , OSAActiveProcPtr )(long refCon); typedef STACK_UPP_TYPE(OSAActiveProcPtr) OSAActiveUPP; #if OPAQUE_UPP_TYPES EXTERN_API(OSAActiveUPP) NewOSAActiveUPP (OSAActiveProcPtr userRoutine); EXTERN_API(void) DisposeOSAActiveUPP (OSAActiveUPP userUPP); EXTERN_API(OSErr) InvokeOSAActiveUPP (long refCon, OSAActiveUPP userUPP); #else enum { uppOSAActiveProcInfo = 0x000000E0 }; /* pascal 2_bytes Func(4_bytes) */ #define NewOSAActiveUPP(userRoutine) (OSAActiveUPP)NewRoutineDescriptor((ProcPtr)(userRoutine), uppOSAActiveProcInfo, GetCurrentArchitecture()) #define DisposeOSAActiveUPP(userUPP) DisposeRoutineDescriptor(userUPP) #define InvokeOSAActiveUPP(refCon, userUPP) (OSErr)CALL_ONE_PARAMETER_UPP((userUPP), uppOSAActiveProcInfo, (refCon)) #endif /* support for pre-Carbon UPP routines: NewXXXProc and CallXXXProc */ #define NewOSAActiveProc(userRoutine) NewOSAActiveUPP(userRoutine) #define CallOSAActiveProc(userRoutine, refCon) InvokeOSAActiveUPP(refCon, userRoutine) EXTERN_API( OSAError ) OSASetActiveProc (ComponentInstance scriptingComponent, OSAActiveUPP activeProc, long refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0009, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectSetActiveProc, 8); If activeProc is nil, the default activeProc is used. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSAGetActiveProc (ComponentInstance scriptingComponent, OSAActiveUPP * activeProc, long * refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x000A, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetActiveProc, 8); Errors: badComponentInstance invalid scripting component instance errOSASystemError */ /************************************************************************** OSA Optional Compiling Interface ************************************************************************** Scripting components that support the Compiling interface have the kOSASupportsCompiling bit set in it's ComponentDescription. **************************************************************************/ EXTERN_API( OSAError ) OSAScriptingComponentName (ComponentInstance scriptingComponent, AEDesc * resultingScriptingComponentName) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0102, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectScriptingComponentName, 4); Given a scripting component, this routine returns the name of that scripting component in a type that is coercable to text (typeChar). The generic scripting component returns the name of the default scripting component. This name should be sufficient to convey to the user the kind of script (syntax) he is expected to write. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSACompile (ComponentInstance scriptingComponent, const AEDesc * sourceData, long modeFlags, OSAID * previousAndResultingScriptID) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0103, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectCompile, 12); Coerces input desc (possibly text) into a script's internal format. Once compiled, the script is ready to run. The modeFlags convey scripting component specific information. The previous script ID (result parameter) is made to refer to the newly compiled script, unless it was originally kOSANullScript. In this case a new script ID is created and used. Errors: badComponentInstance invalid scripting component instance errOSASystemError errAECoercionFail: sourceData is not compilable errOSAScriptError: sourceData was a bad script (syntax error) errOSAInvalidID: previousAndResultingCompiledScriptID was not valid on input ModeFlags: kOSAModePreventGetSource kOSAModeCompileIntoContext kOSAModeAugmentContext kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord */ EXTERN_API( OSAError ) OSACopyID (ComponentInstance scriptingComponent, OSAID fromID, OSAID * toID) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0104, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectCopyID, 8); If toID is a reference to kOSANullScript then it is updated to have a new scriptID value. This call can be used to perform undo or revert operations on scripts. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID */ /************************************************************************** OSA Optional GetSource Interface ************************************************************************** Scripting components that support the GetSource interface have the kOSASupportsGetSource bit set in it's ComponentDescription. **************************************************************************/ EXTERN_API( OSAError ) OSAGetSource (ComponentInstance scriptingComponent, OSAID scriptID, DescType desiredType, AEDesc * resultingSourceData) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0201, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetSource, 12); This routine causes a compiled script to be output in a form (possibly text) such that it is suitable to be passed back to OSACompile. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errOSASourceNotAvailable can't get source for this scriptID */ /************************************************************************** OSA Optional AECoercion Interface ************************************************************************** Scripting components that support the AECoercion interface have the kOSASupportsAECoercion bit set in it's ComponentDescription. **************************************************************************/ EXTERN_API( OSAError ) OSACoerceFromDesc (ComponentInstance scriptingComponent, const AEDesc * scriptData, long modeFlags, OSAID * resultingScriptID) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0301, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectCoerceFromDesc, 12); This routine causes script data to be coerced into a script value. If the scriptData is an AppleEvent, then the resultingScriptID is a compiled script ID (mode flags for OSACompile may be used in this case). Other scriptData descriptors create script value IDs. Errors: badComponentInstance invalid scripting component instance errOSASystemError ModeFlags: kOSAModePreventGetSource kOSAModeCompileIntoContext kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord */ EXTERN_API( OSAError ) OSACoerceToDesc (ComponentInstance scriptingComponent, OSAID scriptID, DescType desiredType, long modeFlags, AEDesc * result) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0302, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectCoerceToDesc, 16); This routine causes a script value to be coerced into any desired form. If the scriptID denotes a compiled script, then it may be coerced to typeAppleEvent. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID */ /************************************************************************** OSA Optional AESending Interface ************************************************************************** Scripting components that support the AESending interface have the kOSASupportsAESending bit set in their ComponentDescription. **************************************************************************/ /* Scripting systems will supply default values for these procedures if they are not set by the client: */ EXTERN_API( OSAError ) OSASetSendProc (ComponentInstance scriptingComponent, OSASendUPP sendProc, long refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0401, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectSetSendProc, 8); If sendProc is nil, the default sendProc is used. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSAGetSendProc (ComponentInstance scriptingComponent, OSASendUPP * sendProc, long * refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0402, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetSendProc, 8); Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSASetCreateProc (ComponentInstance scriptingComponent, OSACreateAppleEventUPP createProc, long refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0403, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectSetCreateProc, 8); If createProc is nil, the default createProc is used. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSAGetCreateProc (ComponentInstance scriptingComponent, OSACreateAppleEventUPP * createProc, long * refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0404, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetCreateProc, 8); Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSASetDefaultTarget (ComponentInstance scriptingComponent, const AEAddressDesc * target) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0405, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectSetDefaultTarget, 4); This routine sets the default target application for AE sending. It also establishes the default target from which terminologies come. It is effectively like having an AppleScript "tell" statement around the entire program. If this routine is not called, or if the target is a null AEDesc, then the current application is the default target. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ /************************************************************************** OSA Optional Recording Interface ************************************************************************** Scripting components that support the Recording interface have the kOSASupportsRecording bit set in their ComponentDescription. **************************************************************************/ EXTERN_API( OSAError ) OSAStartRecording (ComponentInstance scriptingComponent, OSAID * compiledScriptToModifyID) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0501, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectStartRecording, 4); Starts recording. If compiledScriptToModifyID is kOSANullScript, a new script ID is created and returned. If the current application has a handler for the kOSARecordedText event, then kOSARecordedText events are sent to the application containing the text of each AppleEvent recorded. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errOSARecordingIsAlreadyOn */ EXTERN_API( OSAError ) OSAStopRecording (ComponentInstance scriptingComponent, OSAID compiledScriptID) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0502, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectStopRecording, 4); If compiledScriptID is not being recorded into or recording is not currently on, no error is returned. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID */ /************************************************************************** OSA Optional Convenience Interface ************************************************************************** Scripting components that support the Convenience interface have the kOSASupportsConvenience bit set in their ComponentDescription. **************************************************************************/ EXTERN_API( OSAError ) OSALoadExecute (ComponentInstance scriptingComponent, const AEDesc * scriptData, OSAID contextID, long modeFlags, OSAID * resultingScriptValueID) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0601, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectLoadExecute, 16); This routine is effectively equivalent to calling OSALoad followed by OSAExecute. After execution, the compiled source is disposed. Only the resulting value ID is retained. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSABadStorageType: scriptData not for this scripting component errOSACorruptData: data seems to be corrupt errOSADataFormatObsolete script data format is no longer supported errOSADataFormatTooNew script data format is from a newer version errOSAInvalidID errOSAScriptError: the executing script got an error ModeFlags: kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord */ EXTERN_API( OSAError ) OSACompileExecute (ComponentInstance scriptingComponent, const AEDesc * sourceData, OSAID contextID, long modeFlags, OSAID * resultingScriptValueID) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0602, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectCompileExecute, 16); This routine is effectively equivalent to calling OSACompile followed by OSAExecute. After execution, the compiled source is disposed. Only the resulting value ID is retained. Errors: badComponentInstance invalid scripting component instance errOSASystemError errAECoercionFail: sourceData is not compilable errOSAScriptError: sourceData was a bad script (syntax error) errOSAInvalidID: previousAndResultingCompiledScriptID was not valid on input errOSAScriptError: the executing script got an error ModeFlags: kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord */ EXTERN_API( OSAError ) OSADoScript (ComponentInstance scriptingComponent, const AEDesc * sourceData, OSAID contextID, DescType desiredType, long modeFlags, AEDesc * resultingText) FIVEWORDINLINE(0x2F3C, 0x0014, 0x0603, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectDoScript, 20); This routine is effectively equivalent to calling OSACompile followed by OSAExecute and then OSADisplay. After execution, the compiled source and the resulting value are is disposed. Only the resultingText descriptor is retained. If a script error occur during processing, the resultingText gets the error message of the error, and errOSAScriptError is returned. OSAScriptError may still be used to extract more information about the particular error. Errors: badComponentInstance invalid scripting component instance errOSASystemError errAECoercionFail: sourceData is not compilable or desiredType not supported by scripting component errOSAScriptError: sourceData was a bad script (syntax error) errOSAInvalidID: previousAndResultingCompiledScriptID was not valid on input errOSAScriptError: the executing script got an error ModeFlags: kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord kOSAModeDisplayForHumans */ /************************************************************************** OSA Optional Dialects Interface ************************************************************************** Scripting components that support the Dialects interface have the kOSASupportsDialects bit set in their ComponentDescription. **************************************************************************/ /* These calls allows an scripting component that supports different dialects to dynamically switch between those dialects. Although this interface is specified, the particular dialect codes are scripting component dependent. */ EXTERN_API( OSAError ) OSASetCurrentDialect (ComponentInstance scriptingComponent, short dialectCode) FIVEWORDINLINE(0x2F3C, 0x0002, 0x0701, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectSetCurrentDialect, 2); Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSANoSuchDialect: invalid dialectCode */ EXTERN_API( OSAError ) OSAGetCurrentDialect (ComponentInstance scriptingComponent, short * resultingDialectCode) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0702, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetCurrentDialect, 4); Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSAAvailableDialects (ComponentInstance scriptingComponent, AEDesc * resultingDialectInfoList) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0703, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectAvailableDialects, 4); This call return an AEList containing information about each of the currently available dialects of a scripting component. Each item is an AERecord of typeOSADialectInfo that contains at least the fields keyOSADialectName, keyOSADialectCode, KeyOSADialectLangCode and keyOSADialectScriptCode. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSAGetDialectInfo (ComponentInstance scriptingComponent, short dialectCode, OSType selector, AEDesc * resultingDialectInfo) FIVEWORDINLINE(0x2F3C, 0x000A, 0x0704, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetDialectInfo, 10); This call gives information about the specified dialect of a scripting component. It returns an AEDesc whose type depends on the selector specified. Available selectors are the same as the field keys for a dialect info record. The type of AEDesc returned is the same as the type of the field that has same key as the selector. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSABadSelector errOSANoSuchDialect: invalid dialectCode */ EXTERN_API( OSAError ) OSAAvailableDialectCodeList (ComponentInstance scriptingComponent, AEDesc * resultingDialectCodeList) FIVEWORDINLINE(0x2F3C, 0x0004, 0x0705, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectAvailableDialectCodeList, 4); This is alternative to OSAGetAvailableDialectCodeList. Use this call and OSAGetDialectInfo to get information on dialects. This call return an AEList containing dialect code for each of the currently available dialects of a scripting component. Each dialect code is a short integer of type typeShortInteger. Errors: badComponentInstance invalid scripting component instance errOSASystemError Type of a dialect info record containing at least keyOSADialectName and keyOSADialectCode fields. keys for dialect info record, also used as selectors to OSAGetDialectInfo. Field of a typeOSADialectInfo record of typeChar. Field of a typeOSADialectInfo record of typeShortInteger. Field of a typeOSADialectInfo record of typeShortInteger. Field of a typeOSADialectInfo record of typeShortInteger. */ /************************************************************************** OSA Optional Event Handling Interface ************************************************************************** Scripting components that support the Event Handling interface have the kOSASupportsEventHandling bit set in their ComponentDescription. **************************************************************************/ EXTERN_API( OSAError ) OSASetResumeDispatchProc (ComponentInstance scriptingComponent, AEEventHandlerUPP resumeDispatchProc, long refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0801, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectSetResumeDispatchProc, 8); This function is used to set the ResumeDispatchProc that will be used by OSAExecuteEvent and OSADoEvent if either no event handler can be found in the context, or the context event hander "continues" control onward. The two constants kOSAUseStandardDispatch and kOSANoDispatch may also be passed to this routine indicating that the handler registered in the application with AEInstallEventHandler should be used, or no dispatch should occur, respectively. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ enum { kOSAUseStandardDispatch = kAEUseStandardDispatch }; /* Special ResumeDispatchProc constant which may be passed to OSASetResumeDispatchProc indicating that the handler registered in the application with AEInstallEventHandler should be used. NOTE: Had to remove the cast (AEEventHandlerUPP). The C compiler doesn't allow pointer types to be assigned to an enum. All constants must be assigned as enums to translate properly to Pascal. */ enum { kOSANoDispatch = kAENoDispatch }; /* Special ResumeDispatchProc constant which may be passed to OSASetResumeDispatchProc indicating that no dispatch should occur. NOTE: Had to remove the cast (AEEventHandlerUPP). The C compiler doesn't allow pointer types to be assigned to an enum. All constants must be assigned as enums to translate properly to Pascal. */ enum { kOSADontUsePhac = 0x0001 }; /* Special refCon constant that may be given to OSASetResumeDispatchProc only when kOSAUseStandardDispatch is used as the ResumeDispatchProc. This causes the standard dispatch to be performed, except the phac handler is not called. This is useful during tinkerability, when the phac handler is used to lookup a context associated with an event's direct parameter, and call OSAExecuteEvent or OSADoEvent. Failure to bypass the phac handler would result in an infinite loop. */ EXTERN_API( OSAError ) OSAGetResumeDispatchProc (ComponentInstance scriptingComponent, AEEventHandlerUPP * resumeDispatchProc, long * refCon) FIVEWORDINLINE(0x2F3C, 0x0008, 0x0802, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectGetResumeDispatchProc, 8); Returns the registered ResumeDispatchProc. If no ResumeDispatchProc has been registered, then kOSAUseStandardDispatch (the default) is returned. Errors: badComponentInstance invalid scripting component instance errOSASystemError */ EXTERN_API( OSAError ) OSAExecuteEvent (ComponentInstance scriptingComponent, const AppleEvent * theAppleEvent, OSAID contextID, long modeFlags, OSAID * resultingScriptValueID) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0803, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectExecuteEvent, 16); This call is similar to OSAExecute except the initial command to execute comes in the form of an AppleEvent. If the contextID defines any event handlers for that event, they are used to process the event. If no event handler can be found in the context errAEEventNotHandled is returned. If an event handler is found and the hander "continues" control onward, the ResumeDispatchProc (registered with OSASetResumeDispatchProc, above) is called given the AppleEvent. The result is returned as a scriptValueID. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errOSAScriptError: the executing script got an error errAEEventNotHandled: no handler for event in contextID ModeFlags: kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord */ EXTERN_API( OSAError ) OSADoEvent (ComponentInstance scriptingComponent, const AppleEvent * theAppleEvent, OSAID contextID, long modeFlags, AppleEvent * reply) FIVEWORDINLINE(0x2F3C, 0x0010, 0x0804, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectDoEvent, 16); This call is similar to OSADoScript except the initial command to execute comes in the form of an AppleEvent, and the result is an AppleEvent reply record. If the contextID defines any event handlers for that event, they are used to process the event. If no event handler can be found in the context errAEEventNotHandled is returned. If an event handler is found and the hander "continues" control onward, the ResumeDispatchProc (registered with OSASetResumeDispatchProc, above) is called given the AppleEvent. The result is returned in the form of an AppleEvent reply descriptor. If at any time the script gets an error, or if the ResumeDispatchProc returns a reply event indicating an error, then the OSADoEvent call itself returns an error reply (i.e. OSADoEvent should never return errOSAScriptError). Any error result returned by the ResumeDispatchProc will be returned by OSADoEvent. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errAEEventNotHandled: no handler for event in contextID ModeFlags: kOSAModeNeverInteract kOSAModeCanInteract kOSAModeAlwaysInteract kOSAModeCantSwitchLayer kOSAModeDontReconnect kOSAModeDoRecord */ EXTERN_API( OSAError ) OSAMakeContext (ComponentInstance scriptingComponent, const AEDesc * contextName, OSAID parentContext, OSAID * resultingContextID) FIVEWORDINLINE(0x2F3C, 0x000C, 0x0805, 0x7000, 0xA82A); /* OSAComponentFunctionInline(kOSASelectMakeContext, 12); Makes a new empty context which may be passed to OSAExecute or OSAExecuteEvent. If contextName is typeNull, an unnamed context is created. If parentContext is kOSANullScript then the resulting context does not inherit bindings from any other context. Errors: badComponentInstance invalid scripting component instance errOSASystemError errOSAInvalidID errAECoercionFail: contextName is invalid */ #if PRAGMA_STRUCT_ALIGN #pragma options align=reset #elif PRAGMA_STRUCT_PACKPUSH #pragma pack(pop) #elif PRAGMA_STRUCT_PACK #pragma pack() #endif #ifdef PRAGMA_IMPORT_OFF #pragma import off #elif PRAGMA_IMPORT #pragma import reset #endif #ifdef __cplusplus } #endif #endif /* __OSA__ */
43.00411
301
0.59843
6fa4712e306e2b2d9ed6bfaf8e16e5273d5bd23e
342
h
C
Example/Pods/Target Support Files/XKViewFactory/XKViewFactory-umbrella.h
YoungXKing/XKViewFactory
c3dba1020677938a6d14880ae14947de117bfb92
[ "MIT" ]
1
2021-03-03T09:01:22.000Z
2021-03-03T09:01:22.000Z
Example/Pods/Target Support Files/XKViewFactory/XKViewFactory-umbrella.h
YoungXKing/XKViewFactory
c3dba1020677938a6d14880ae14947de117bfb92
[ "MIT" ]
null
null
null
Example/Pods/Target Support Files/XKViewFactory/XKViewFactory-umbrella.h
YoungXKing/XKViewFactory
c3dba1020677938a6d14880ae14947de117bfb92
[ "MIT" ]
null
null
null
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "XKViewMaker.h" FOUNDATION_EXPORT double XKViewFactoryVersionNumber; FOUNDATION_EXPORT const unsigned char XKViewFactoryVersionString[];
19
67
0.824561
6ff9ff7537b72c8f8e7c96ef25d15efa88272f43
7,239
c
C
Proj4/lib4.c
NighttimeDriver50000/ice
b60612aba37ad239ce8409d57138441555d99741
[ "MIT" ]
null
null
null
Proj4/lib4.c
NighttimeDriver50000/ice
b60612aba37ad239ce8409d57138441555d99741
[ "MIT" ]
null
null
null
Proj4/lib4.c
NighttimeDriver50000/ice
b60612aba37ad239ce8409d57138441555d99741
[ "MIT" ]
null
null
null
#include "lib4.h" #include "sensing.h" #include "driving.h" #include "oi.h" #include "fixedqueue.h" #include "irobserial.h" #include "irchar.h" #include "irobled.h" #define PID_DT (IROB_PERIOD_MS) #define PRED (irPrevRegion() & IR_MASK_RED_BUOY) #define PGREEN (irPrevRegion() & IR_MASK_GREEN_BUOY) #define PFIELD (irPrevRegion() & IR_MASK_FORCE_FIELD) #define PANY (PRED || PGREEN || PFIELD) #define PALL (PRED && PGREEN && PFIELD) #define RED (irRegion() & IR_MASK_RED_BUOY) #define GREEN (irRegion() & IR_MASK_GREEN_BUOY) #define FIELD (irRegion() & IR_MASK_FORCE_FIELD) #define ANY (RED || GREEN || FIELD) #define ALL (RED && GREEN && FIELD) //#define CHARGING (getSensorInt16(SenCurr1) >= CURRENTTHOLD) #define CHARGING (getSensorUint8(SenChAvailable)) int16_t utk = 0; int16_t etk = 0; int16_t etk_1 = 0; int16_t esum = 0; FixedQueue esumQueue = 0; uint8_t bumpDrop = 0; uint8_t prevBumpDrop = 0; uint8_t started = 0; uint8_t docking = 0; uint8_t comingFromFront = 0; uint8_t dockingFinal = 0; uint8_t onDock = 0; int16_t jimmyAngle = 0; /** * initilaization function for a pid controller. */ void pidSetup(void) { while (esumQueue == 0) { esumQueue = newFixedQueue(PID_QSIZE); } } /** * A function to clear the value of the esumQueue * which is used in the integral calculations for * the PID controller. */ void pidCleanup(void) { if (esumQueue != 0) { freeFixedQueue(esumQueue); esumQueue = 0; } } /** * Takes the next input for the pid controler * utilizes constants: * PID_SET_POINT - the set point or goal * PID_KP - the multiplier for the current distance * PID_KI - the multiplier for the "integral" term * PID_KD - the multiplier for the "derivative" term * This then sets utk which is essentially the result * of this calculation * Important notes: * The derivative terms only look at this and the previous value * the integral term currently has no time mitigation and uses * a fixed size queue (now has damping based on size) * * @param vtk the current value for the pid controller */ void pidStep(uint16_t vtk) { etk_1 = etk; etk = ((int16_t)vtk) - PID_SET_POINT; esum += etk; esum -= pushPop(esumQueue, etk); int16_t p = PID_KP*etk; int16_t i = PID_KI*esum*PID_DT / PID_QSIZE; // damping int16_t d = PID_KD*(etk-etk_1)/PID_DT; irobprintf("etk_1: %d\netk: %d\nesum: %d\nutk: %d\np: %d\ni: %d\nd: %d\n", etk_1, etk, esum, utk, p, i, d); utk = p + i + d; } /** * A drive function which utilizes the utk value (modified in pidStep) * this also utilizes * DRIVE_DIVISOR - directly mitigates UTK * SPEED - the default speed */ void updateMotors(void) { int16_t deltaDrive = utk / DRIVE_DIVISOR; driveDirect(SPEED - deltaDrive, SPEED + deltaDrive); } // Do while turning after bump void doWhileTurning(void) { updateSensors(); uint8_t bumpDrop = getSensorUint8(SenBumpDrop); if (bumpDrop & MASK_WHEEL_DROP) { driveStop(); } if (docking) { updateIR(); dockingDiagnostics(); } } void move(int16_t distance) { int16_t speed = docking ? DOCKING_SPEED : SPEED; driveDistanceTFunc(speed, distance, &doWhileTurning, UPDATE_SENSOR_DELAY_PERIOD, UPDATE_SENSOR_DELAY_CUTOFF); } void turn(int16_t radius, int16_t angle) { int16_t speed = docking ? DOCKING_SPEED : SPEED; driveAngleTFunc(speed, radius, angle, &doWhileTurning, UPDATE_SENSOR_DELAY_PERIOD, UPDATE_SENSOR_DELAY_CUTOFF); } uint8_t noBump(void) { return !(getSensorUint8(SenBumpDrop) & MASK_BUMP) && notCharging(); } void jimmyBump(void) { // Drive forward until bump drivePredicateFunc(JIMMY_SPEED, RadStraight, &noBump, &doWhileTurning, UPDATE_SENSOR_DELAY_PERIOD, UPDATE_SENSOR_DELAY_CUTOFF); } uint8_t notCharging(void) { return !CHARGING; } void jimmyTurn(int16_t radius) { // Turn until charging driveAnglePFunc(JIMMY_SPEED, radius, jimmyAngle, &notCharging, &doWhileTurning, UPDATE_SENSOR_DELAY_PERIOD, UPDATE_SENSOR_DELAY_CUTOFF); } void jimmy(void) { // Increase angle every time jimmyAngle += JIMMY_ANGLE; // Turn right, then back to center jimmyTurn(RadCW); jimmyTurn(RadCCW); // Bump the dock jimmyBump(); // Turn left, then back to center jimmyTurn(RadCCW); jimmyTurn(RadCW); // Bump the dock jimmyBump(); } void dock(void) { if (!dockingFinal && !PGREEN && GREEN) { // Move an extra robot radius move(IROB_RAD_TURN); // Turn to line up turn(RadCW, FIELD_TURN); dockingFinal = 1; } else if (dockingFinal && RED && !GREEN) { // Course correction drive(DOCKING_SPEED, RadCCW); } else if (dockingFinal && !RED && GREEN) { // Course correction drive(DOCKING_SPEED, RadCW); } else { // Normally just go straight drive(DOCKING_SPEED, RadStraight); } } void dockingDiagnostics(void) { // Robot LEDs for IR fields robotLedSetBits(NEITHER_ROBOT_LED); powerLedSet(POWER_LED_ORANGE, 0); if (smoothRed() > 0x60) robotLedOn(PLAY_ROBOT_LED); if (smoothGreen() > 0x60) robotLedOn(ADVANCE_ROBOT_LED); if (irRegion() & IR_MASK_FORCE_FIELD) powerLedSet(POWER_LED_ORANGE, 0xFF); // Command module LEDs for charging. cmdLED1Set(0); cmdLED2Set(0); if (CHARGING) { cmdLED1Set(1); } else { cmdLED2Set(1); } } // Called by irobPeriodic void iroblifePeriodic(void) { // Get bump & wheel drop sensor prevBumpDrop = bumpDrop; bumpDrop = getSensorUint8(SenBumpDrop); // IR updateIR(); dockingDiagnostics(); if (onDock) { // Final connection on dock if (CHARGING) { driveStop(); } else { jimmy(); } } else if (bumpDrop & MASK_WHEEL_DROP) { // Cliff driveStop(); } else if (bumpDrop & MASK_BUMP) { if (dockingFinal) { // We are now on the dock driveStop(); onDock = 1; } else { // Turn until no longer bumping drive(SPEED, RadCCW); started = 1; } } else if (prevBumpDrop & MASK_BUMP) { turn(RadCCW, OVERTURN); } else if (docking) { dock(); } else if (!docking && FIELD) { // Begin docking // If we were already in red, we're coming from front. comingFromFront = PRED; turn(RadCCW, FIELD_TURN); if (!comingFromFront) { // Turn again to be perpendicular move(FIELD_CLEARANCE); turn(RadCW, FIELD_TURN); } // We are now docking docking = 1; } else if (!started) { // Go straight until wall drive(SPEED, RadStraight); } else { // PID #ifdef LOG_OVER_USB setSerialDestination(SERIAL_USB); #endif uint16_t wallSignal = getSensorUint16(SenWallSig1); pidStep(wallSignal); #ifdef LOG_OVER_USB irobprintf("wallSignal: %u\ndeltaDrive: %d\n\n", utk / DRIVE_DIVISOR); setSerialDestination(SERIAL_CREATE); #endif updateMotors(); } }
28.277344
78
0.637933
c0ba4853ca4ff98459fa49c6583ec318abee2360
136
h
C
Nanpy/freeram.h
Max5254/nanpy-firmware
b56870f8ec272f1f07403689accde932c38c03ad
[ "MIT" ]
39
2015-01-13T20:11:28.000Z
2021-09-24T09:57:48.000Z
Nanpy/freeram.h
Max5254/nanpy-firmware
b56870f8ec272f1f07403689accde932c38c03ad
[ "MIT" ]
23
2015-01-17T21:53:57.000Z
2018-12-13T10:20:18.000Z
Nanpy/freeram.h
Max5254/nanpy-firmware
b56870f8ec272f1f07403689accde932c38c03ad
[ "MIT" ]
46
2015-02-08T13:17:49.000Z
2021-01-01T13:39:53.000Z
#pragma once #ifdef __cplusplus extern "C" { #endif int free_ram1(); int free_ram2(); int free_ram3(); #ifdef __cplusplus } #endif
8.5
19
0.698529
a5f65cb1003ac0e3ad2bfa77c054541d3cd3d358
1,093
h
C
chrome/browser/ui/cocoa/chrome_event_processing_window.h
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/ui/cocoa/chrome_event_processing_window.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/ui/cocoa/chrome_event_processing_window.h
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_COCOA_CHROME_EVENT_PROCESSING_WINDOW_H_ #define CHROME_BROWSER_UI_COCOA_CHROME_EVENT_PROCESSING_WINDOW_H_ #import <Cocoa/Cocoa.h> #import "base/mac/scoped_nsobject.h" #import "ui/base/cocoa/command_dispatcher.h" #import "ui/base/cocoa/underlay_opengl_hosting_window.h" @class ChromeCommandDispatcherDelegate; // Override NSWindow to access unhandled keyboard events (for command // processing); subclassing NSWindow is the only method to do // this. @interface ChromeEventProcessingWindow : UnderlayOpenGLHostingWindow<CommandDispatchingWindow> // Checks if |event| is a window, delayed window, or browser keyboard shortcut. // (See global_keyboard_shortcuts_mac.h for details). If so, execute the // associated command. Returns YES if the event was handled. - (BOOL)handleExtraKeyboardShortcut:(NSEvent*)event; @end #endif // CHROME_BROWSER_UI_COCOA_CHROME_EVENT_PROCESSING_WINDOW_H_
36.433333
79
0.810613
a5fa91fcd951344d8755e188712437fa521471d8
14,900
h
C
Ve2D/F_ShapeGen.h
m3hdiii/sfinge
b2d8f59956b63c97a0b999673e069ae9410ec7c0
[ "MIT" ]
10
2017-05-31T18:13:31.000Z
2022-02-19T05:51:17.000Z
Ve2D/F_ShapeGen.h
zikohcth/sfinge
b2d8f59956b63c97a0b999673e069ae9410ec7c0
[ "MIT" ]
null
null
null
Ve2D/F_ShapeGen.h
zikohcth/sfinge
b2d8f59956b63c97a0b999673e069ae9410ec7c0
[ "MIT" ]
7
2018-07-04T08:32:12.000Z
2021-09-28T02:35:19.000Z
#pragma once namespace Ve2D { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for F_ShapeGen /// </summary> public ref class F_ShapeGen : public System::Windows::Forms::Form { public: F_ShapeGen(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~F_ShapeGen() { if (components) { delete components; } } private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::SplitContainer^ splitContainer1; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::Label^ label11; private: System::Windows::Forms::Label^ label10; private: System::Windows::Forms::Label^ label9; private: System::Windows::Forms::Label^ label8; private: System::Windows::Forms::Label^ label7; private: System::Windows::Forms::TrackBar^ trackBar5; private: System::Windows::Forms::TrackBar^ trackBar4; private: System::Windows::Forms::TrackBar^ trackBar3; private: System::Windows::Forms::TrackBar^ trackBar2; private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::ComboBox^ comboBox1; private: System::Windows::Forms::TrackBar^ trackBar1; private: System::Windows::Forms::Label^ label5; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::GroupBox^ groupBox2; private: System::Windows::Forms::PictureBox^ pictureBox1; protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->label1 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->splitContainer1 = (gcnew System::Windows::Forms::SplitContainer()); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->label11 = (gcnew System::Windows::Forms::Label()); this->trackBar5 = (gcnew System::Windows::Forms::TrackBar()); this->label10 = (gcnew System::Windows::Forms::Label()); this->trackBar4 = (gcnew System::Windows::Forms::TrackBar()); this->label9 = (gcnew System::Windows::Forms::Label()); this->trackBar3 = (gcnew System::Windows::Forms::TrackBar()); this->label8 = (gcnew System::Windows::Forms::Label()); this->trackBar2 = (gcnew System::Windows::Forms::TrackBar()); this->label7 = (gcnew System::Windows::Forms::Label()); this->trackBar1 = (gcnew System::Windows::Forms::TrackBar()); this->label6 = (gcnew System::Windows::Forms::Label()); this->comboBox1 = (gcnew System::Windows::Forms::ComboBox()); this->label5 = (gcnew System::Windows::Forms::Label()); this->label4 = (gcnew System::Windows::Forms::Label()); this->label3 = (gcnew System::Windows::Forms::Label()); this->groupBox2 = (gcnew System::Windows::Forms::GroupBox()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->splitContainer1))->BeginInit(); this->splitContainer1->Panel1->SuspendLayout(); this->splitContainer1->Panel2->SuspendLayout(); this->splitContainer1->SuspendLayout(); this->groupBox1->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar5))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar4))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar3))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar2))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar1))->BeginInit(); this->groupBox2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->BeginInit(); this->SuspendLayout(); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(11, 59); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(26, 13); this->label1->TabIndex = 1; this->label1->Text = L"Top"; // // label2 // this->label2->AutoSize = true; this->label2->Location = System::Drawing::Point(11, 110); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(40, 13); this->label2->TabIndex = 2; this->label2->Text = L"Bottom"; // // splitContainer1 // this->splitContainer1->Location = System::Drawing::Point(12, 12); this->splitContainer1->Name = L"splitContainer1"; // // splitContainer1.Panel1 // this->splitContainer1->Panel1->Controls->Add(this->groupBox1); // // splitContainer1.Panel2 // this->splitContainer1->Panel2->Controls->Add(this->groupBox2); this->splitContainer1->Size = System::Drawing::Size(753, 419); this->splitContainer1->SplitterDistance = 251; this->splitContainer1->TabIndex = 3; // // groupBox1 // this->groupBox1->Controls->Add(this->label11); this->groupBox1->Controls->Add(this->label10); this->groupBox1->Controls->Add(this->label9); this->groupBox1->Controls->Add(this->label8); this->groupBox1->Controls->Add(this->label7); this->groupBox1->Controls->Add(this->trackBar5); this->groupBox1->Controls->Add(this->trackBar4); this->groupBox1->Controls->Add(this->trackBar3); this->groupBox1->Controls->Add(this->trackBar2); this->groupBox1->Controls->Add(this->label6); this->groupBox1->Controls->Add(this->comboBox1); this->groupBox1->Controls->Add(this->trackBar1); this->groupBox1->Controls->Add(this->label5); this->groupBox1->Controls->Add(this->label4); this->groupBox1->Controls->Add(this->label3); this->groupBox1->Controls->Add(this->label1); this->groupBox1->Controls->Add(this->label2); this->groupBox1->Location = System::Drawing::Point(0, 0); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(252, 419); this->groupBox1->TabIndex = 0; this->groupBox1->TabStop = false; this->groupBox1->Text = L"Tùy chỉnh"; // // label11 // this->label11->AutoSize = true; this->label11->Location = System::Drawing::Point(233, 263); this->label11->Name = L"label11"; this->label11->Size = System::Drawing::Size(19, 13); this->label11->TabIndex = 21; this->label11->Text = L"50"; // // trackBar5 // this->trackBar5->LargeChange = 10; this->trackBar5->Location = System::Drawing::Point(52, 263); this->trackBar5->Maximum = 100; this->trackBar5->Minimum = 10; this->trackBar5->Name = L"trackBar5"; this->trackBar5->Size = System::Drawing::Size(140, 45); this->trackBar5->TabIndex = 16; this->trackBar5->Value = 50; this->trackBar5->Scroll += gcnew System::EventHandler(this, &F_ShapeGen::trackBar5_Scroll); // // label10 // this->label10->AutoSize = true; this->label10->Location = System::Drawing::Point(233, 212); this->label10->Name = L"label10"; this->label10->Size = System::Drawing::Size(19, 13); this->label10->TabIndex = 20; this->label10->Text = L"50"; // // trackBar4 // this->trackBar4->LargeChange = 10; this->trackBar4->Location = System::Drawing::Point(52, 212); this->trackBar4->Maximum = 100; this->trackBar4->Minimum = 10; this->trackBar4->Name = L"trackBar4"; this->trackBar4->Size = System::Drawing::Size(140, 45); this->trackBar4->TabIndex = 15; this->trackBar4->Value = 50; this->trackBar4->Scroll += gcnew System::EventHandler(this, &F_ShapeGen::trackBar4_Scroll); // // label9 // this->label9->AutoSize = true; this->label9->Location = System::Drawing::Point(233, 161); this->label9->Name = L"label9"; this->label9->Size = System::Drawing::Size(19, 13); this->label9->TabIndex = 19; this->label9->Text = L"50"; // // trackBar3 // this->trackBar3->LargeChange = 10; this->trackBar3->Location = System::Drawing::Point(52, 161); this->trackBar3->Maximum = 100; this->trackBar3->Minimum = 10; this->trackBar3->Name = L"trackBar3"; this->trackBar3->Size = System::Drawing::Size(140, 45); this->trackBar3->TabIndex = 14; this->trackBar3->Value = 50; this->trackBar3->ValueChanged += gcnew System::EventHandler(this, &F_ShapeGen::trackBar3_ValueChanged); // // label8 // this->label8->AutoSize = true; this->label8->Location = System::Drawing::Point(233, 110); this->label8->Name = L"label8"; this->label8->Size = System::Drawing::Size(19, 13); this->label8->TabIndex = 18; this->label8->Text = L"50"; // // trackBar2 // this->trackBar2->LargeChange = 10; this->trackBar2->Location = System::Drawing::Point(52, 110); this->trackBar2->Maximum = 100; this->trackBar2->Minimum = 10; this->trackBar2->Name = L"trackBar2"; this->trackBar2->Size = System::Drawing::Size(140, 45); this->trackBar2->TabIndex = 13; this->trackBar2->Value = 50; this->trackBar2->ValueChanged += gcnew System::EventHandler(this, &F_ShapeGen::trackBar2_ValueChanged); // // label7 // this->label7->AutoSize = true; this->label7->Location = System::Drawing::Point(233, 59); this->label7->Name = L"label7"; this->label7->Size = System::Drawing::Size(19, 13); this->label7->TabIndex = 17; this->label7->Text = L"50"; // // trackBar1 // this->trackBar1->LargeChange = 10; this->trackBar1->Location = System::Drawing::Point(52, 59); this->trackBar1->Maximum = 100; this->trackBar1->Minimum = 10; this->trackBar1->Name = L"trackBar1"; this->trackBar1->Size = System::Drawing::Size(140, 45); this->trackBar1->TabIndex = 10; this->trackBar1->Value = 50; this->trackBar1->ValueChanged += gcnew System::EventHandler(this, &F_ShapeGen::trackBar1_ValueChanged); // // label6 // this->label6->AutoSize = true; this->label6->Location = System::Drawing::Point(11, 22); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(93, 13); this->label6->TabIndex = 12; this->label6->Text = L"Mẫu dạng vân tay"; // // comboBox1 // this->comboBox1->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->comboBox1->FormattingEnabled = true; this->comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(5) {L"Ngón cái", L"Ngón trỏ", L"Ngón giữa", L"Ngón nhẫn", L"Ngón út"}); this->comboBox1->Location = System::Drawing::Point(110, 19); this->comboBox1->Name = L"comboBox1"; this->comboBox1->Size = System::Drawing::Size(136, 21); this->comboBox1->TabIndex = 11; // // label5 // this->label5->AutoSize = true; this->label5->Location = System::Drawing::Point(11, 263); this->label5->Name = L"label5"; this->label5->Size = System::Drawing::Size(38, 13); this->label5->TabIndex = 6; this->label5->Text = L"Middle"; // // label4 // this->label4->AutoSize = true; this->label4->Location = System::Drawing::Point(11, 212); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(32, 13); this->label4->TabIndex = 5; this->label4->Text = L"Right"; // // label3 // this->label3->AutoSize = true; this->label3->Location = System::Drawing::Point(11, 161); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(25, 13); this->label3->TabIndex = 4; this->label3->Text = L"Left"; // // groupBox2 // this->groupBox2->Controls->Add(this->pictureBox1); this->groupBox2->Location = System::Drawing::Point(3, 0); this->groupBox2->Name = L"groupBox2"; this->groupBox2->Size = System::Drawing::Size(495, 419); this->groupBox2->TabIndex = 0; this->groupBox2->TabStop = false; this->groupBox2->Text = L"Hình dạng vân tay"; // // pictureBox1 // this->pictureBox1->Location = System::Drawing::Point(7, 20); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(482, 393); this->pictureBox1->TabIndex = 0; this->pictureBox1->TabStop = false; // // F_ShapeGen // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(777, 443); this->Controls->Add(this->splitContainer1); this->Name = L"F_ShapeGen"; this->Text = L"Sinh hình dạng vân tay"; this->splitContainer1->Panel1->ResumeLayout(false); this->splitContainer1->Panel2->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->splitContainer1))->EndInit(); this->splitContainer1->ResumeLayout(false); this->groupBox1->ResumeLayout(false); this->groupBox1->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar5))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar4))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar3))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar2))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->trackBar1))->EndInit(); this->groupBox2->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->EndInit(); this->ResumeLayout(false); } #pragma endregion private: System::Void trackBar1_ValueChanged(System::Object^ sender, System::EventArgs^ e) { this->label7->Text = System::Convert::ToString(this->trackBar1->Value); } private: System::Void trackBar2_ValueChanged(System::Object^ sender, System::EventArgs^ e) { this->label8->Text = System::Convert::ToString(this->trackBar2->Value); } private: System::Void trackBar3_ValueChanged(System::Object^ sender, System::EventArgs^ e) { this->label9->Text = System::Convert::ToString(this->trackBar3->Value); } private: System::Void trackBar4_Scroll(System::Object^ sender, System::EventArgs^ e) { this->label10->Text = System::Convert::ToString(this->trackBar4->Value); } private: System::Void trackBar5_Scroll(System::Object^ sender, System::EventArgs^ e) { this->label11->Text = System::Convert::ToString(this->trackBar5->Value); } }; }
39.107612
131
0.667919
4fa92be0e4a3cb7df2c30105c5f63995917c4a7e
271
h
C
src/SettingServer.h
katsumin/EchonetTimer
5e8e9dc28d81679347e87a19f7e7278c72674276
[ "MIT" ]
null
null
null
src/SettingServer.h
katsumin/EchonetTimer
5e8e9dc28d81679347e87a19f7e7278c72674276
[ "MIT" ]
null
null
null
src/SettingServer.h
katsumin/EchonetTimer
5e8e9dc28d81679347e87a19f7e7278c72674276
[ "MIT" ]
null
null
null
#ifndef _SETTING_SERVER_H_ #define _SETTING_SERVER_H_ #include "WebServer.h" #include "Preferences.h" #include <vector> #include "DataStore.h" class SettingServer { private: public: SettingServer(); void begin(DataStore *ds); void exec(); }; #endif
15.055556
28
0.704797
a03fea667f0f2db196ae89fd07dfff8d6ebf839a
2,399
h
C
EngineLayer/CrosslinkSearch/CrosslinkedPeptides.h
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
2
2020-09-10T19:14:20.000Z
2021-09-11T16:36:56.000Z
EngineLayer/CrosslinkSearch/CrosslinkedPeptides.h
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
null
null
null
EngineLayer/CrosslinkSearch/CrosslinkedPeptides.h
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
3
2020-09-11T01:19:47.000Z
2021-09-02T02:05:01.000Z
#pragma once #include <unordered_map> #include <unordered_set> #include <vector> #include <algorithm> #include <tuple> #include <utility> //C# TO C++ CONVERTER NOTE: Forward class declarations: namespace EngineLayer { namespace CrosslinkSearch { class Crosslinker; } } #include "MassSpectrometry/MassSpectrometry.h" using namespace MassSpectrometry; #include "Proteomics/Proteomics.h" using namespace Proteomics; using namespace Proteomics::Fragmentation; using namespace Proteomics::ProteolyticDigestion; namespace EngineLayer { namespace CrosslinkSearch { // Having a std::tuple as the key of a std::unordered_map is not directly allowed // in C++. // See https://stackoverflow.com/questions/11408934/using-a-stdtuple-as-key-for-stdunordered-map // for how to handle this. typedef std::tuple<int, int> XLTuple; struct XLTuple_hash: public std::unary_function<XLTuple, std::size_t>{ std::size_t operator() (const XLTuple& k ) const { size_t h1= std::hash<int>{}(std::get<0>(k)); size_t h2= std::hash<int>{}(std::get<1>(k)); return h1 ^ (h2 << 1); } }; struct XLTuple_equal: public std::binary_function<XLTuple, XLTuple, bool>{ bool operator() (const XLTuple& lhs, const XLTuple& rhs) const { return std::get<0>(lhs) == std::get<0>(rhs) && std::get<1>(lhs) == std::get<1>(rhs); } }; typedef std::unordered_map<XLTuple, std::vector<Product *>, XLTuple_hash, XLTuple_equal> XLumap; class CrosslinkedPeptide { public: static std::vector<std::tuple<int, std::vector<Product*>>> XlGetTheoreticalFragments(DissociationType dissociationType, Crosslinker *crosslinker, std::vector<int> &possibleCrosslinkerPositions, double otherPeptideMass, PeptideWithSetModifications *peptide); static XLumap XlLoopGetTheoreticalFragments(DissociationType dissociationType, Modification *loopMass, std::vector<int> &modPos, PeptideWithSetModifications *peptide); }; } }
38.079365
179
0.591496
85f6085209a8751932ff1bf74cfdfdcf296623ad
23,604
c
C
sdk-6.5.20/src/soc/dnx/dbal/dbal_init/auto_generated/dbal_init_cb_tables_hard_logic_tm_hl_tm_sch_definition.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/soc/dnx/dbal/dbal_init/auto_generated/dbal_init_cb_tables_hard_logic_tm_hl_tm_sch_definition.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/soc/dnx/dbal/dbal_init/auto_generated/dbal_init_cb_tables_hard_logic_tm_hl_tm_sch_definition.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #include <src/soc/dnx/dbal/dbal_internal.h> #include <soc/dnx/dnx_data/auto_generated/dnx_data.h> shr_error_e sch_region_odd_even_mode_odd_even_mode_arrayoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { uint32 instance_idx; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_INSTANCE_IDX(unit, current_mapped_field_id, instance_idx); *offset = instance_idx/32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_region_odd_even_mode_odd_even_mode_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { uint32 instance_idx; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_INSTANCE_IDX(unit, current_mapped_field_id, instance_idx); *offset = instance_idx%32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_shared_shaper_shared_shaper_mode_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__flow_octet_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_FLOW_OCTET_ID, key_value__flow_octet_id); *offset = key_value__flow_octet_id/8-dnx_data_sch.flow.first_se_flow_id_get(unit)/64; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_shared_shaper_shared_shaper_mode_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__flow_octet_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_FLOW_OCTET_ID, key_value__flow_octet_id); *offset = key_value__flow_octet_id%8*2; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_scheduler_composite_enable_table_is_composite_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__flow_id_pair; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_FLOW_ID_PAIR, key_value__flow_id_pair); *offset = key_value__flow_id_pair/16; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_scheduler_composite_enable_table_is_composite_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__flow_id_pair; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_FLOW_ID_PAIR, key_value__flow_id_pair); *offset = key_value__flow_id_pair%16; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_flow_shaper_dynamic_table_token_count_arrayoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id%8; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_flow_shaper_dynamic_table_token_count_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id/8; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_shaper_descriptor_table_rate_man_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id%8*dnx_data_sch.dbal.flow_shaper_descr_bits_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_shaper_descriptor_table_rate_exp_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id%8*dnx_data_sch.dbal.flow_shaper_descr_bits_get(unit)+dnx_data_sch.dbal.flow_shaper_mant_bits_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_shaper_descriptor_table_max_burst_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id%8*dnx_data_sch.dbal.flow_shaper_descr_bits_get(unit)+dnx_data_sch.dbal.flow_shaper_mant_bits_get(unit)+4; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_shaper_descriptor_table_slow_rate_2_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id%8*dnx_data_sch.dbal.flow_shaper_descr_bits_get(unit)+dnx_data_sch.dbal.flow_shaper_mant_bits_get(unit)+4+9; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_slow_rate_table_rate_man_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__slow_level; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SLOW_LEVEL, key_value__slow_level); *offset = key_value__slow_level; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_flow_slow_status_flow_slow_status_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id%8*2; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_bw_profile_biasing_probability_uninstall_threshold_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__rci_level; uint32 key_value__is_fabric; uint32 key_value__is_high_prio; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_RCI_LEVEL, key_value__rci_level); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_IS_FABRIC, key_value__is_fabric); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_IS_HIGH_PRIO, key_value__is_high_prio); *offset = key_value__rci_level+key_value__is_fabric*8+key_value__is_high_prio*16; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_flow_attr_is_slow_enable_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id/4; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_flow_attr_is_slow_enable_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_flow_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_FLOW_ID, key_value__sch_flow_id); *offset = key_value__sch_flow_id%4; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_se_color_group_group_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__se_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SE_ID, key_value__se_id); *offset = key_value__se_id/8; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_se_color_group_group_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__se_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SE_ID, key_value__se_id); *offset = key_value__se_id%8*2; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_se_color_group_group_entryoffset_1_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__se_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SE_ID, key_value__se_id); *offset = key_value__se_id/8-dnx_data_sch.flow.hr_se_id_min_get(unit)/8; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_hr_is_port_is_port_hr_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__hr_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_HR_ID, key_value__hr_id); *offset = key_value__hr_id/8; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_hr_is_port_is_port_hr_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__hr_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_HR_ID, key_value__hr_id); *offset = key_value__hr_id%8; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_hr_force_fc_force_fc_arrayoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__hr_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_HR_ID, key_value__hr_id); *offset = key_value__hr_id/32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_hr_force_fc_force_fc_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__hr_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_HR_ID, key_value__hr_id); *offset = key_value__hr_id%32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_hr_to_tcg_tcg_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__hr_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_HR_ID, key_value__hr_id); *offset = key_value__hr_id%8*3; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tcg_weight_valid_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__ps_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_PS_ID, key_value__ps_id); *offset = key_value__ps_id; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tcg_weight_valid_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__tcg_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_TCG_ID, key_value__tcg_id); *offset = key_value__tcg_id; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tcg_weight_weight_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__tcg_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_TCG_ID, key_value__tcg_id); *offset = key_value__tcg_id*10; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tc_shaper_quanta_to_add_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__hr_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_HR_ID, key_value__hr_id); *offset = key_value__hr_id%8*dnx_data_sch.dbal.ps_shaper_bits_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tc_shaper_max_burst_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__hr_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_HR_ID, key_value__hr_id); *offset = key_value__hr_id%8*dnx_data_sch.dbal.ps_shaper_bits_get(unit)+dnx_data_sch.dbal.ps_shaper_quanta_bits_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tcg_shaper_quanta_to_add_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__global_tcg_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_GLOBAL_TCG_ID, key_value__global_tcg_id); *offset = key_value__global_tcg_id/8; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tcg_shaper_quanta_to_add_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__global_tcg_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_GLOBAL_TCG_ID, key_value__global_tcg_id); *offset = key_value__global_tcg_id%8*dnx_data_sch.dbal.ps_shaper_bits_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_tcg_shaper_max_burst_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__global_tcg_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_GLOBAL_TCG_ID, key_value__global_tcg_id); *offset = key_value__global_tcg_id%8*dnx_data_sch.dbal.ps_shaper_bits_get(unit)+dnx_data_sch.dbal.ps_shaper_quanta_bits_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_priority_nof_ps_priorities_arrayoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__ps_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_PS_ID, key_value__ps_id); *offset = key_value__ps_id/32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_port_priority_nof_ps_priorities_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__ps_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_PS_ID, key_value__ps_id); *offset = key_value__ps_id%32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_interface_priority_nof_priority_propagation_priorities_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__if_group; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_IF_GROUP, key_value__if_group); *offset = key_value__if_group; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_interface_force_pause_force_arrayoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_interface_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_INTERFACE_ID, key_value__sch_interface_id); *offset = key_value__sch_interface_id/32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_interface_force_pause_force_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_interface_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_INTERFACE_ID, key_value__sch_interface_id); *offset = key_value__sch_interface_id%32; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_egq_to_sch_if_map_sch_interface_id_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__egq_interface_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_EGQ_INTERFACE_ID, key_value__egq_interface_id); *offset = key_value__egq_interface_id; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_egq_to_sch_if_map_sch_interface_id_entryoffset_1_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__egq_interface_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_EGQ_INTERFACE_ID, key_value__egq_interface_id); *offset = key_value__egq_interface_id+dnx_data_sch.interface.nof_sch_interfaces_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_non_channelized_if_shaper_credit_rate_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__sch_if_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SCH_IF_ID, key_value__sch_if_id); *offset = key_value__sch_if_id-dnx_data_sch.interface.nof_channelized_calendars_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_if_big_calendar_hr_id_groupoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__cal_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_CAL_ID, key_value__cal_id); *offset = key_value__cal_id/2; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_if_big_calendar_hr_id_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__entry; uint32 key_value__select; uint32 key_value__cal_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_ENTRY, key_value__entry); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SELECT, key_value__select); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_CAL_ID, key_value__cal_id); *offset = key_value__entry+key_value__select*1024+key_value__cal_id%2*2048; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_if_regular_calendar_hr_id_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__entry; uint32 key_value__select; uint32 key_value__cal_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_ENTRY, key_value__entry); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_SELECT, key_value__select); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_CAL_ID, key_value__cal_id); *offset = key_value__entry+key_value__select*256+key_value__cal_id%2*512; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_qpair_to_hr_map_hr_id_entryoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__qpair; uint32 key_value__egq_core; uint32 key_value__core_id; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_QPAIR, key_value__qpair); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_EGQ_CORE, key_value__egq_core); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_CORE_ID, key_value__core_id); *offset = key_value__qpair/16+(key_value__egq_core^key_value__core_id)*dnx_data_egr_queuing.params.nof_q_pairs_get(unit)/16; SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_qpair_to_hr_map_hr_id_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__qpair; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_QPAIR, key_value__qpair); *offset = key_value__qpair%16*(dnx_data_sch.dbal.hr_bits_get(unit)+1); SHR_EXIT(); exit: SHR_FUNC_EXIT; } shr_error_e sch_qpair_to_hr_map_valid_dataoffset_0_cb( int unit, void * entry_handle, dbal_fields_e current_mapped_field_id, uint32 * offset) { dbal_entry_handle_t * eh = (dbal_entry_handle_t *) entry_handle; uint32 key_value__qpair; SHR_FUNC_INIT_VARS(unit); DBAL_FORMULA_CB_GET_KEY_VALUE(unit, eh, DBAL_FIELD_QPAIR, key_value__qpair); *offset = key_value__qpair%16*(dnx_data_sch.dbal.hr_bits_get(unit)+1)+dnx_data_sch.dbal.hr_bits_get(unit); SHR_EXIT(); exit: SHR_FUNC_EXIT; }
30.378378
144
0.793044
5fd5641defe3dfd208388e9219b01e2ae92c6ea2
974
h
C
UserLand/Applications/DisplaySettings/DisplaySettings.h
EGOTree/pranaOS
3f0a6900e7ca3430c30e84fb51fb0c8fe04b78a5
[ "BSD-2-Clause" ]
11
2021-03-31T08:25:57.000Z
2021-06-09T10:48:07.000Z
UserLand/Applications/DisplaySettings/DisplaySettings.h
pro-hacker64/prana-os
b16506e674c0fd48beef802e890a6ad57740cfff
[ "BSD-2-Clause" ]
14
2021-06-11T06:07:08.000Z
2021-06-29T05:51:06.000Z
UserLand/Applications/DisplaySettings/DisplaySettings.h
pro-hacker64/prana-os
b16506e674c0fd48beef802e890a6ad57740cfff
[ "BSD-2-Clause" ]
15
2021-04-13T12:08:24.000Z
2021-06-10T12:02:04.000Z
#pragma once // includes #include "MonitorWidget.h" #include <LibCore/Timer.h> #include <LibGUI/ColorInput.h> #include <LibGUI/ComboBox.h> #include <LibGUI/RadioButton.h> class DisplaySettingsWidget : public GUI::Widget { C_OBJECT(DisplaySettingsWidget); public: DisplaySettingsWidget(); private: void create_frame(); void create_wallpaper_list(); void create_resolution_list(); void load_current_settings(); void send_settings_to_window_server(); // Apply the settings to the Window Server Vector<String> m_wallpapers; Vector<String> m_modes; Vector<Gfx::IntSize> m_resolutions; RefPtr<DisplaySettings::MonitorWidget> m_monitor_widget; RefPtr<GUI::ComboBox> m_wallpaper_combo; RefPtr<GUI::ComboBox> m_mode_combo; RefPtr<GUI::ComboBox> m_resolution_combo; RefPtr<GUI::RadioButton> m_display_scale_radio_1x; RefPtr<GUI::RadioButton> m_display_scale_radio_2x; RefPtr<GUI::ColorInput> m_color_input; };
27.828571
85
0.752567
38a64cdf388236857216a1c739a5663ff8656172
3,535
h
C
src/venus-protocol/vn_protocol_renderer_info.h
AOF-Dev/virglrenderer-android
b6593144c5a5c7ff691c3414ce7d23aeea89faa8
[ "MIT" ]
3
2021-09-24T16:53:22.000Z
2022-01-18T11:21:55.000Z
src/venus-protocol/vn_protocol_renderer_info.h
AOF-Dev/virglrenderer-android
b6593144c5a5c7ff691c3414ce7d23aeea89faa8
[ "MIT" ]
null
null
null
src/venus-protocol/vn_protocol_renderer_info.h
AOF-Dev/virglrenderer-android
b6593144c5a5c7ff691c3414ce7d23aeea89faa8
[ "MIT" ]
null
null
null
/* This file is generated by venus-protocol git-e05ae158. */ /* * Copyright 2020 Google LLC * SPDX-License-Identifier: MIT */ #ifndef VN_PROTOCOL_RENDERER_INFO_H #define VN_PROTOCOL_RENDERER_INFO_H #include "vn_protocol_renderer_defines.h" static inline uint32_t vn_info_wire_format_version(void) { return 0; } static inline uint32_t vn_info_vk_xml_version(void) { return VK_MAKE_VERSION(1, 2, 168); } static inline int vn_info_extension_compare(const void *a, const void *b) { return strcmp(a, *(const char **)b); } static inline uint32_t vn_info_extension_spec_version(const char *name) { static uint32_t ext_count = 51; static const char *ext_names[51] = { "VK_EXT_command_serialization", "VK_EXT_descriptor_indexing", "VK_EXT_host_query_reset", "VK_EXT_image_drm_format_modifier", "VK_EXT_sampler_filter_minmax", "VK_EXT_scalar_block_layout", "VK_EXT_separate_stencil_usage", "VK_EXT_shader_viewport_index_layer", "VK_EXT_transform_feedback", "VK_KHR_16bit_storage", "VK_KHR_8bit_storage", "VK_KHR_bind_memory2", "VK_KHR_buffer_device_address", "VK_KHR_create_renderpass2", "VK_KHR_dedicated_allocation", "VK_KHR_depth_stencil_resolve", "VK_KHR_descriptor_update_template", "VK_KHR_device_group", "VK_KHR_device_group_creation", "VK_KHR_draw_indirect_count", "VK_KHR_driver_properties", "VK_KHR_external_fence", "VK_KHR_external_fence_capabilities", "VK_KHR_external_memory", "VK_KHR_external_memory_capabilities", "VK_KHR_external_semaphore", "VK_KHR_external_semaphore_capabilities", "VK_KHR_get_memory_requirements2", "VK_KHR_get_physical_device_properties2", "VK_KHR_image_format_list", "VK_KHR_imageless_framebuffer", "VK_KHR_maintenance1", "VK_KHR_maintenance2", "VK_KHR_maintenance3", "VK_KHR_multiview", "VK_KHR_relaxed_block_layout", "VK_KHR_sampler_mirror_clamp_to_edge", "VK_KHR_sampler_ycbcr_conversion", "VK_KHR_separate_depth_stencil_layouts", "VK_KHR_shader_atomic_int64", "VK_KHR_shader_draw_parameters", "VK_KHR_shader_float16_int8", "VK_KHR_shader_float_controls", "VK_KHR_shader_subgroup_extended_types", "VK_KHR_spirv_1_4", "VK_KHR_storage_buffer_storage_class", "VK_KHR_timeline_semaphore", "VK_KHR_uniform_buffer_standard_layout", "VK_KHR_variable_pointers", "VK_KHR_vulkan_memory_model", "VK_MESA_venus_protocol", }; static const uint32_t ext_versions[51] = { 0, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 3, 14, 1, 1, 1, 1, 4, 1, 1, 1, 2, 1, 1, 3, 0, }; const char **found; found = bsearch(name, ext_names, ext_count, sizeof(ext_names[0]), vn_info_extension_compare); return found ? ext_versions[found - ext_names] : 0; } #endif /* VN_PROTOCOL_RENDERER_INFO_H */
23.566667
69
0.605658
8aa12666cfeba25d7a54ab33d02f1a7c4a4c167c
249
h
C
DictionaryAutoCompleteObject.h
eballeste/RCTAutoComplete
9efe9ac88405e875bc5ebb639ca5b1dab0205cdd
[ "MIT" ]
197
2015-06-26T01:10:30.000Z
2021-11-04T04:50:24.000Z
DictionaryAutoCompleteObject.h
eballeste/RCTAutoComplete
9efe9ac88405e875bc5ebb639ca5b1dab0205cdd
[ "MIT" ]
63
2015-07-10T00:26:26.000Z
2019-06-20T13:13:19.000Z
DictionaryAutoCompleteObject.h
eballeste/RCTAutoComplete
9efe9ac88405e875bc5ebb639ca5b1dab0205cdd
[ "MIT" ]
31
2015-07-28T10:19:09.000Z
2020-02-14T12:12:49.000Z
#import <Foundation/Foundation.h> #import "MLPAutoCompletionObject.h" @interface DictionaryAutoCompleteObject : NSObject <MLPAutoCompletionObject> @property (strong) NSDictionary *json; - (id)initWithDictionnary:(NSDictionary *)json; @end
27.666667
76
0.783133
3da74a8e6f1148a481a5ee436d7846963ace17b2
817
h
C
client/client.h
jacpy/fim
36124e33331f2cdc40d20b3f5e1ac4635b084e81
[ "Apache-2.0" ]
null
null
null
client/client.h
jacpy/fim
36124e33331f2cdc40d20b3f5e1ac4635b084e81
[ "Apache-2.0" ]
null
null
null
client/client.h
jacpy/fim
36124e33331f2cdc40d20b3f5e1ac4635b084e81
[ "Apache-2.0" ]
null
null
null
#ifndef CLIENT_H #define CLIENT_H #include <QDataStream> #include <QDialog> #include <QTcpSocket> class QComboBox; class QLabel; class QLineEdit; class QPushButton; class QTcpSocket; class QNetworkSession; class Client : public QDialog { Q_OBJECT public: explicit Client(QWidget *parent = nullptr); private slots: void requestNewFortune(); void readFortune(); void displayError(QAbstractSocket::SocketError socketError); void enableGetFortuneButton(); void sessionOpened(); private: QComboBox *hostCombo = nullptr; QLineEdit *portLineEdit = nullptr; QLabel *statusLabel = nullptr; QPushButton *getFortuneButton = nullptr; QTcpSocket *tcpSocket = nullptr; QDataStream in; QString currentFortune; QNetworkSession *networkSession = nullptr; }; #endif
19
64
0.736842
cde53aa8642f1cd56d1644f66ada9b187d2ecce4
900
h
C
OpenNeighborhood/src/Core/Log.h
ClementDreptin/OpenNeighborhood
595768263a03d5d2640cf5111a0492311c15a3a0
[ "Apache-2.0" ]
7
2021-07-03T20:58:01.000Z
2021-11-03T18:04:20.000Z
OpenNeighborhood/src/Core/Log.h
ClementDreptin/OpenNeighborhood
595768263a03d5d2640cf5111a0492311c15a3a0
[ "Apache-2.0" ]
2
2021-06-17T14:50:53.000Z
2021-06-18T21:18:05.000Z
OpenNeighborhood/src/Core/Log.h
ClementDreptin/OpenNeighborhood
595768263a03d5d2640cf5111a0492311c15a3a0
[ "Apache-2.0" ]
null
null
null
#pragma once class Log { public: template<typename ...Args> static void Info(Args && ...args) { (std::cout << ... << args) << std::endl; } template<typename ...Args> static void Warn(Args && ...args) { std::cout << "\033[33m"; (std::cout << ... << args) << "\033[0m" << std::endl; } template<typename ...Args> static void Success(Args && ...args) { std::cout << "\033[32m"; (std::cout << ... << args) << "\033[0m" << std::endl; } template<typename ...Args> static void Error(Args && ...args) { std::cout << "\033[31m"; (std::cout << ... << args) << "\033[0m" << std::endl; } }; #define LOG_INFO(...) ::Log::Info(__VA_ARGS__) #define LOG_WARN(...) ::Log::Warn(__VA_ARGS__) #define LOG_SUCCESS(...) ::Log::Success(__VA_ARGS__) #define LOG_ERROR(...) ::Log::Error(__VA_ARGS__)
23.076923
61
0.508889
b4f81f84d12721769f78a3ab8df7bb45e6fd84b8
384
c
C
tests/com.oracle.truffle.llvm.tests.sulong/c/truffle-c/structTest/structCopy2.c
pointhi/sulong
5446c54d360f486f9e97590af5f466cf1f5cd1f7
[ "BSD-3-Clause" ]
1
2021-01-20T08:07:04.000Z
2021-01-20T08:07:04.000Z
tests/com.oracle.truffle.llvm.tests.sulong/c/truffle-c/structTest/structCopy2.c
pointhi/sulong
5446c54d360f486f9e97590af5f466cf1f5cd1f7
[ "BSD-3-Clause" ]
null
null
null
tests/com.oracle.truffle.llvm.tests.sulong/c/truffle-c/structTest/structCopy2.c
pointhi/sulong
5446c54d360f486f9e97590af5f466cf1f5cd1f7
[ "BSD-3-Clause" ]
1
2018-11-06T21:38:57.000Z
2018-11-06T21:38:57.000Z
struct test { int a[3]; char b[2]; long c; }; int sum(struct test *t) { int sum = 0; sum += t->a[0] + t->a[1] + t->a[2]; sum += t->b[0] + t->b[1]; sum += t->c; return sum; } int main() { struct test t1 = {.a = { 1, 2, 3 }, .b = { 'a', 'c' }, .c = -1 }; struct test t2 = t1; t2.b[0] = 32; t2.a[0] = 12; t2.a[2] = 1; return (sum(&t1) + sum(&t2)) % 256; }
16
67
0.424479
3717fba32850494b1ad9a1082bbd02827b2ddcd8
821
h
C
include/SpringBoard/SBAppBrightnessChangeLogger.h
ItHertzSoGood/DragonBuild
1aaf6133ab386ba3a5165a4b29c080ca8d814b52
[ "MIT" ]
3
2020-06-20T02:53:25.000Z
2020-11-07T08:39:13.000Z
include/SpringBoard/SBAppBrightnessChangeLogger.h
ItHertzSoGood/DragonBuild
1aaf6133ab386ba3a5165a4b29c080ca8d814b52
[ "MIT" ]
null
null
null
include/SpringBoard/SBAppBrightnessChangeLogger.h
ItHertzSoGood/DragonBuild
1aaf6133ab386ba3a5165a4b29c080ca8d814b52
[ "MIT" ]
1
2020-07-26T02:16:06.000Z
2020-07-26T02:16:06.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 22 2020 01:47:48). // // Copyright (C) 1997-2019 Steve Nygard. // #import <objc/NSObject.h> @class NSDate, NSString; @interface SBAppBrightnessChangeLogger : NSObject { NSString *_bundleID; long long _brightnessLevel; NSDate *_eventTimestamp; } + (id)sharedInstance; @property(copy, nonatomic) NSDate *eventTimestamp; // @synthesize eventTimestamp=_eventTimestamp; @property(nonatomic) long long brightnessLevel; // @synthesize brightnessLevel=_brightnessLevel; @property(copy, nonatomic) NSString *bundleID; // @synthesize bundleID=_bundleID; // - (void).cxx_destruct; - (void)_screenLocked; - (void)_publishMetrics; - (void)_publishMetricsIfNeeded; - (void)noteApp:(id)arg1 setScreenBrightness:(double)arg2; - (id)init; @end
26.483871
97
0.742996
81df1c3b995f2b2d9491db1dfc9635f27e3a7fe8
1,075
h
C
gui/FiltersWindow.h
zhyvchyky/filters
7158aa8a05fb004cdea63fdbd7d31111a1f4c796
[ "MIT" ]
null
null
null
gui/FiltersWindow.h
zhyvchyky/filters
7158aa8a05fb004cdea63fdbd7d31111a1f4c796
[ "MIT" ]
2
2020-11-26T21:08:23.000Z
2020-12-03T15:22:09.000Z
gui/FiltersWindow.h
zhyvchyky/filters
7158aa8a05fb004cdea63fdbd7d31111a1f4c796
[ "MIT" ]
null
null
null
// // Created by noxin on 12/28/20. // #ifndef FILTERS_FILTERSWINDOW_H #define FILTERS_FILTERSWINDOW_H #include <QTabWidget> #include <QtWidgets/QPushButton> #include <Filters.h> #include <gui/cards/ConveyorManagerCard.h> #include "FiltersScene.h" #include "FiltersView.h" class FiltersWindow : public QTabWidget, public IObserver<ConveyorManager>{ Q_OBJECT public: FiltersWindow(QWidget *parent = nullptr); void resizeEvent(QResizeEvent *) override; void notify(std::shared_ptr<ConveyorManager>) override; void setFilters(std::shared_ptr<Filters>); private slots: void handleRunButton(); void handleCloseRequest(int); void handleAddButton(); private: std::map<size_t, size_t> tabIndexToConveyorIndex; std::map<size_t, size_t> conveyorIndexToTabIndex; std::map<size_t, std::shared_ptr<FiltersScene>> scenes; std::map<size_t, FiltersView*> sceneViews; std::shared_ptr<Filters> filters; std::set<size_t> conveyors; QPushButton *runButton; QPushButton *addConveyorButton; }; #endif //FILTERS_FILTERSWINDOW_H
24.431818
75
0.746977
7209507ff443fd2beb170110d37be841a60544f8
1,866
h
C
util/concurrency/threadlocal.h
awshepard/mongo
3c712b18936a7d3e2f74e7bb9c8d6cbbe076ba10
[ "Apache-2.0" ]
2
2017-03-01T01:16:55.000Z
2020-02-13T20:53:31.000Z
util/concurrency/threadlocal.h
awshepard/mongo
3c712b18936a7d3e2f74e7bb9c8d6cbbe076ba10
[ "Apache-2.0" ]
null
null
null
util/concurrency/threadlocal.h
awshepard/mongo
3c712b18936a7d3e2f74e7bb9c8d6cbbe076ba10
[ "Apache-2.0" ]
null
null
null
#pragma once /** * Copyright (C) 2011 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/thread/tss.hpp> namespace mongo { #if defined(_WIN32) || (defined(__GNUC__) && defined(__linux__)) template< class T > struct TSP { boost::thread_specific_ptr<T> tsp; public: T* get() const; void reset(T* v); }; # if defined(_WIN32) # define TSP_DECLARE(T,p) extern TSP<T> p; # define TSP_DEFINE(T,p) __declspec( thread ) T* _ ## p; \ TSP<T> p; \ template<> T* TSP<T>::get() const { return _ ## p; } \ void TSP<T>::reset(T* v) { \ tsp.reset(v); \ _ ## p = v; \ } # else # define TSP_DECLARE(T,p) \ extern __thread T* _ ## p; \ template<> inline T* TSP<T>::get() const { return _ ## p; } \ extern TSP<T> p; # define TSP_DEFINE(T,p) \ __thread T* _ ## p; \ template<> void TSP<T>::reset(T* v) { \ tsp.reset(v); \ _ ## p = v; \ } \ TSP<T> p; # endif #else template< class T > struct TSP { thread_specific_ptr<T> tsp; public: T* get() const { return tsp.get(); } void reset(T* v) { tsp.reset(v); } }; # define TSP_DECLARE(T,p) extern TSP<T> p; # define TSP_DEFINE(T,p) TSP<T> p; #endif }
24.233766
77
0.593783
896b78dc07840704a44841d534bea6a611d60ca5
3,323
c
C
libopenbarcode/libdmtx/dmtxvector2.c
TrevorMellon/openbarcode
bb0be48d28dccf831e46e05d85dea6f48940587a
[ "MIT" ]
40
2016-02-18T18:47:04.000Z
2022-03-22T07:03:33.000Z
libopenbarcode/libdmtx/dmtxvector2.c
TrevorMellon/openbarcode
bb0be48d28dccf831e46e05d85dea6f48940587a
[ "MIT" ]
3
2017-06-23T16:25:08.000Z
2017-10-26T15:54:41.000Z
libopenbarcode/libdmtx/dmtxvector2.c
TrevorMellon/openbarcode
bb0be48d28dccf831e46e05d85dea6f48940587a
[ "MIT" ]
15
2017-06-16T22:36:56.000Z
2021-06-22T07:48:33.000Z
/** * libdmtx - Data Matrix Encoding/Decoding Library * Copyright 2008, 2009 Mike Laughton. All rights reserved. * * See LICENSE file in the main project directory for full * terms of use and distribution. * * Contact: Mike Laughton <mike@dragonflylogic.com> * * \file dmtxvector2.c * \brief 2D Vector math */ /** * * */ extern DmtxVector2 * dmtxVector2AddTo(DmtxVector2 *v1, const DmtxVector2 *v2) { v1->X += v2->X; v1->Y += v2->Y; return v1; } /** * * */ extern DmtxVector2 * dmtxVector2Add(DmtxVector2 *vOut, const DmtxVector2 *v1, const DmtxVector2 *v2) { *vOut = *v1; return dmtxVector2AddTo(vOut, v2); } /** * * */ extern DmtxVector2 * dmtxVector2SubFrom(DmtxVector2 *v1, const DmtxVector2 *v2) { v1->X -= v2->X; v1->Y -= v2->Y; return v1; } /** * * */ extern DmtxVector2 * dmtxVector2Sub(DmtxVector2 *vOut, const DmtxVector2 *v1, const DmtxVector2 *v2) { *vOut = *v1; return dmtxVector2SubFrom(vOut, v2); } /** * * */ extern DmtxVector2 * dmtxVector2ScaleBy(DmtxVector2 *v, double s) { v->X *= s; v->Y *= s; return v; } /** * * */ extern DmtxVector2 * dmtxVector2Scale(DmtxVector2 *vOut, const DmtxVector2 *v, double s) { *vOut = *v; return dmtxVector2ScaleBy(vOut, s); } /** * * */ extern double dmtxVector2Cross(const DmtxVector2 *v1, const DmtxVector2 *v2) { return (v1->X * v2->Y) - (v1->Y * v2->X); } /** * * */ extern double dmtxVector2Norm(DmtxVector2 *v) { double mag; mag = dmtxVector2Mag(v); if(mag <= DmtxAlmostZero) return -1.0; /* XXX this doesn't look clean */ dmtxVector2ScaleBy(v, 1/mag); return mag; } /** * * */ extern double dmtxVector2Dot(const DmtxVector2 *v1, const DmtxVector2 *v2) { return (v1->X * v2->X) + (v1->Y * v2->Y); } /** * * */ extern double dmtxVector2Mag(const DmtxVector2 *v) { return sqrt(v->X * v->X + v->Y * v->Y); } /** * * */ extern double dmtxDistanceFromRay2(const DmtxRay2 *r, const DmtxVector2 *q) { DmtxVector2 vSubTmp; /* Assumes that v is a unit vector */ assert(fabs(1.0 - dmtxVector2Mag(&(r->v))) <= DmtxAlmostZero); return dmtxVector2Cross(&(r->v), dmtxVector2Sub(&vSubTmp, q, &(r->p))); } /** * * */ extern double dmtxDistanceAlongRay2(const DmtxRay2 *r, const DmtxVector2 *q) { DmtxVector2 vSubTmp; #ifdef DEBUG /* Assumes that v is a unit vector */ if(fabs(1.0 - dmtxVector2Mag(&(r->v))) > DmtxAlmostZero) { ; /* XXX big error goes here */ } #endif return dmtxVector2Dot(dmtxVector2Sub(&vSubTmp, q, &(r->p)), &(r->v)); } /** * * */ extern DmtxPassFail dmtxRay2Intersect(DmtxVector2 *point, const DmtxRay2 *p0, const DmtxRay2 *p1) { double numer, denom; DmtxVector2 w; denom = dmtxVector2Cross(&(p1->v), &(p0->v)); if(fabs(denom) <= DmtxAlmostZero) return DmtxFail; dmtxVector2Sub(&w, &(p1->p), &(p0->p)); numer = dmtxVector2Cross(&(p1->v), &w); return dmtxPointAlongRay2(point, p0, numer/denom); } /** * * */ extern DmtxPassFail dmtxPointAlongRay2(DmtxVector2 *point, const DmtxRay2 *r, double t) { DmtxVector2 vTmp; /* Ray should always have unit length of 1 */ assert(fabs(1.0 - dmtxVector2Mag(&(r->v))) <= DmtxAlmostZero); dmtxVector2Scale(&vTmp, &(r->v), t); dmtxVector2Add(point, &(r->p), &vTmp); return DmtxPass; }
15.899522
79
0.627144
47309c258654c4d9cd71920e41a8de74fe54dfe3
2,441
h
C
Source/Core/Engine/world_server.h
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
Source/Core/Engine/world_server.h
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
Source/Core/Engine/world_server.h
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
#ifndef HIKARI_WORLDSERVER_H #define HIKARI_WORLDSERVER_H #include "Core/Networking/server_connection.h" #include "Core/Networking/client_connection.h" #include "Core/Networking/net_message.h" #include <vector> #include "Core/Engine/game_engine.h" #include <tuple> #include "Core/Networking/player.h" #include "Core/Controller/world_server_network_controller.h" #include "Core/Task/ws_establish_client_connection_task.h" namespace Hikari { typedef std::tuple<int, NetMessage*> ClientNetMessage; class ClientNetworkController; class WorldServer { private: WorldServerNetworkController* mWorldServerNetworkController; Hikari::ServerConnection* mGameServerConnection; /*** Client ***/ Hikari::ClientConnection* mClientConnection; std::unordered_map<int, ClientConnectionData> mConnectedClients; std::unordered_map<int, ClientNetworkController*> mClientNetworkControllers; /*** Messages ***/ std::vector<NetMessage*> mIncomingGameServerMessages; std::vector<ClientNetMessage> mIncomingClientMessages; std::vector<NetMessage*> mOutgoingGameServerMessages; std::vector<ClientNetMessage> mOutgoingClientMessages; std::unordered_set<NetMessage*> mPendingDeleteNetMessages; /** Task responsible for setting up a connection to the client. */ std::unordered_map<std::string, WSEstablishClientConnectionTask*> mEstablishClientConnectionTasks; public: WorldServer(); ~WorldServer(); void Initialise(); bool ConnectToGameServer(); void Update(); /** Sends a message to client, with the given client ID. */ void SendMessageToClient(int arg_clientid, NetMessage* arg_message); /** Sends a message to all connected clients. */ void SendMessageToAllClients(NetMessage* arg_message); /** * Registers a client. Will create a ClientNetworkController and add client to list of connected clients. * @param arg_conndata Connection Data for the client. * @param arg_netguid NetGUID for the client. */ void RegisterClient(const ClientConnectionData& arg_conndata, NetGUID arg_netguid); /** Sends a message to the GameServer */ void SendMessageToGameServer(NetMessage* arg_message); std::unordered_map<int, ClientConnectionData> GetConnectedClients() { return mConnectedClients; } ClientNetworkController* GetClientNetworkController(int arg_clientid); WorldServerNetworkController* GetWorldServerNetworkController() { return mWorldServerNetworkController; } }; } #endif
30.898734
107
0.788202
88007e8504397f458a7125f3028721798f34bdcd
1,115
h
C
Frameworks/TestsFoundation/Sources/PrivateHeaders/Classdump/XCTestCore/Xcode_13_0/Xcode_13_0_XCTWaiterManager.h
antigp/Mixbox
b787fa76b0d861e05dd6a467039f63e1dc931ff0
[ "MIT" ]
121
2018-08-06T19:14:05.000Z
2022-03-29T05:10:57.000Z
Frameworks/TestsFoundation/Sources/PrivateHeaders/Classdump/XCTestCore/Xcode_13_0/Xcode_13_0_XCTWaiterManager.h
antigp/Mixbox
b787fa76b0d861e05dd6a467039f63e1dc931ff0
[ "MIT" ]
14
2018-07-27T17:13:09.000Z
2022-03-30T06:37:33.000Z
Frameworks/TestsFoundation/Sources/PrivateHeaders/Classdump/XCTestCore/Xcode_13_0/Xcode_13_0_XCTWaiterManager.h
avito-tech/Mixbox
0a83920e55f455de0f877da421c7b0d31522a093
[ "MIT" ]
23
2018-08-16T18:11:50.000Z
2022-03-29T10:46:44.000Z
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000 && __IPHONE_OS_VERSION_MAX_ALLOWED < 160000 #import "Xcode_13_0_XCTestCore_CDStructures.h" #import "Xcode_13_0_SharedHeader.h" #import <Foundation/Foundation.h> // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // @interface XCTWaiterManager : NSObject { NSMutableArray *_waiterStack; NSThread *_thread; NSObject *_queue; NSMutableSet *_interruptionCompletionHandlers; } + (id)threadLocalManager; @property(readonly) NSMutableSet *interruptionCompletionHandlers; // @synthesize interruptionCompletionHandlers=_interruptionCompletionHandlers; @property(readonly) NSObject *queue; // @synthesize queue=_queue; @property NSThread *thread; // @synthesize thread=_thread; @property(retain) NSMutableArray *waiterStack; // @synthesize waiterStack=_waiterStack; - (void)waiterDidFinishWaiting:(id)arg1; - (void)waiterTimedOutWhileWaiting:(id)arg1 withCompletion:(CDUnknownBlockType)arg2; - (void)waiterWillBeginWaiting:(id)arg1; - (id)init; - (void)dealloc; @end #endif
32.794118
144
0.777578
fd088882c8470fc7f5d5ebecf1958fc6318c6b03
1,160
h
C
custom_conf/etc/calamares/src/libcalamaresui/utils/Paste.h
ix-os/IXOS
840abf7e022f46073d898fed5adb667bb5cb7166
[ "CC0-1.0" ]
null
null
null
custom_conf/etc/calamares/src/libcalamaresui/utils/Paste.h
ix-os/IXOS
840abf7e022f46073d898fed5adb667bb5cb7166
[ "CC0-1.0" ]
13
2020-07-30T19:55:36.000Z
2020-12-07T16:57:23.000Z
custom_conf/etc/calamares/src/libcalamaresui/utils/Paste.h
ix-os/IXOS
840abf7e022f46073d898fed5adb667bb5cb7166
[ "CC0-1.0" ]
null
null
null
/* === This file is part of Calamares - <https://github.com/calamares> === * * Copyright 2019, Bill Auger * * Calamares 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 3 of the License, or * (at your option) any later version. * * Calamares 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 Calamares. If not, see <http://www.gnu.org/licenses/>. */ #ifndef UTILS_PASTE_H #define UTILS_PASTE_H #include <qglobal.h> // for quint16 class QObject; class QString; namespace CalamaresUtils { /** @brief Send the current log file to a pastebin * * Returns the (string) URL that the pastebin gives us. */ QString sendLogToPastebin( QObject* parent, const QString& ficheHost, quint16 fichePort ); } // namespace CalamaresUtils #endif
29.74359
90
0.724138
e64936b6796964fd89ad72cdfaee810586f4552e
145
h
C
test/DreadedParser.h
yepher/pegkit
67f9c7966df5fadd4bb2b6e47345172fd2bddf8b
[ "MIT" ]
251
2015-01-05T08:34:47.000Z
2022-01-24T09:43:34.000Z
test/DreadedParser.h
yepher/pegkit
67f9c7966df5fadd4bb2b6e47345172fd2bddf8b
[ "MIT" ]
30
2015-02-28T20:42:30.000Z
2020-03-21T17:44:43.000Z
test/DreadedParser.h
yepher/pegkit
67f9c7966df5fadd4bb2b6e47345172fd2bddf8b
[ "MIT" ]
39
2015-02-19T16:40:48.000Z
2022-02-07T04:00:36.000Z
#import <PEGKit/PKParser.h> enum { DREADED_TOKEN_KIND_A = 14, DREADED_TOKEN_KIND_B = 15, }; @interface DreadedParser : PKParser @end
12.083333
35
0.703448
0a937b53fc08a1c5670683986911e823d503fd8b
3,293
h
C
Custom Game Launcher (C++, OpenGL y ImGUI)/Custom Game Launcher/Src/AppSettings.h
rafatyn/Proyectos
d080e040a2b1205b7b15f5ada82fb759e3cd2869
[ "MIT" ]
null
null
null
Custom Game Launcher (C++, OpenGL y ImGUI)/Custom Game Launcher/Src/AppSettings.h
rafatyn/Proyectos
d080e040a2b1205b7b15f5ada82fb759e3cd2869
[ "MIT" ]
null
null
null
Custom Game Launcher (C++, OpenGL y ImGUI)/Custom Game Launcher/Src/AppSettings.h
rafatyn/Proyectos
d080e040a2b1205b7b15f5ada82fb759e3cd2869
[ "MIT" ]
null
null
null
#pragma once class AppSettings { // Launcher variables float gameInitialHorizontalMargin; float gameInitialVerticalMargin; float gameLineMargin; float gameCoverMinSize; float gameCoverMargin; float gameCoverRatio; short gameCoverOrientation; short gameCoverBorder; short gameNameLength; // Launcher variables float launcherInitialHorizontalMargin; float launcherInitialVerticalMargin; float launcherCoverMinSize = 150.0f; float launcherCoverMargin; float launcherLineMargin; void loadCoverConfig(short config) { switch (config) { case 0: gameInitialHorizontalMargin = 4.5f / 100.0f; gameInitialVerticalMargin = 40.0f; gameLineMargin = 40.0f; gameCoverMinSize = 250.0f; gameCoverMargin = 2.5f / 100.0f; gameCoverRatio = 1.85f; gameCoverOrientation = 0; gameCoverBorder = -1; gameNameLength = 25; launcherInitialHorizontalMargin = 4.5f / 100.0f; launcherInitialVerticalMargin = 40.0f; launcherCoverMargin = 2.5f / 100.0f; launcherLineMargin = 40.0f; break; case 1: gameInitialHorizontalMargin = 4.0f / 100.0f; gameInitialVerticalMargin = 40.0f; gameLineMargin = 40.0f; gameCoverMinSize = 150.0f; gameCoverMargin = 2.5f / 100.0f; gameCoverRatio = 0.7067f; gameCoverOrientation = 1; gameCoverBorder = -1; gameNameLength = 20; launcherInitialHorizontalMargin = 4.0f / 100.0f; launcherInitialVerticalMargin = 40.0f; launcherCoverMargin = 2.5f / 100.0f; launcherLineMargin = 40.0f; break; case 2: gameInitialHorizontalMargin = 0.0f; gameInitialVerticalMargin = 0.0f; gameLineMargin = 0.0f; gameCoverMinSize = 150.0f; gameCoverMargin = 0.0f; gameCoverRatio = 0.7067f; gameCoverOrientation = 1; gameCoverBorder = 0; gameNameLength = 23; launcherInitialHorizontalMargin = 0.0f; launcherInitialVerticalMargin = 0.0f; launcherCoverMargin = 0.0f; launcherLineMargin = 0.0f; break; default: break; } } public: AppSettings(short coverConfig) { loadCoverConfig(coverConfig); } void changeCoverType(short coverConfig) { loadCoverConfig(coverConfig); } inline float getGameInitialHorizontalMargin() { return gameInitialHorizontalMargin; } inline float getGameInitialVerticalMargin() { return gameInitialVerticalMargin; } inline float getGameLineMargin() { return gameLineMargin; } inline float getGameCoverMinSize() { return gameCoverMinSize; } inline float getGameCoverMargin() { return gameCoverMargin; } inline float getGameCoverRatio() { return gameCoverRatio; } inline short getGameCoverOrientation() { return gameCoverOrientation; } inline short getGameCoverBorder() { return gameCoverBorder; } inline short getGameNameLength() { return gameNameLength; } inline float* getGameCoverMinSizePointer() { return &gameCoverMinSize; } inline float* getLauncherCoverMinSizePointer() { return &launcherCoverMinSize; } inline float getLauncherCoverMinSize() { return launcherCoverMinSize; } inline float getLauncherInitialHorizontalMargin() { return launcherInitialHorizontalMargin; } inline float getLauncherInitialVerticalMargin() { return launcherInitialVerticalMargin; } inline float getLauncherCoverMargin() { return launcherCoverMargin; } inline float getLauncherLineMargin() { return launcherLineMargin; } };
29.936364
94
0.762223
520ec48c952bbce52c663b296fcef0291ea68ea3
1,167
h
C
Sources/TripKitObjc/include/TripKitObjc/TKPermissionManager.h
skedgo/tripkit-ios
c25d9af9df42e69b4fbbd56069701b0c1844988e
[ "Apache-2.0" ]
4
2018-10-22T22:16:24.000Z
2019-10-30T23:32:30.000Z
Sources/TripKitObjc/include/TripKitObjc/TKPermissionManager.h
skedgo/tripkit-ios
c25d9af9df42e69b4fbbd56069701b0c1844988e
[ "Apache-2.0" ]
23
2017-09-18T10:26:45.000Z
2022-01-25T03:01:00.000Z
Sources/TripKitObjc/include/TripKitObjc/TKPermissionManager.h
skedgo/tripkit-ios
c25d9af9df42e69b4fbbd56069701b0c1844988e
[ "Apache-2.0" ]
1
2019-06-14T13:17:31.000Z
2019-06-14T13:17:31.000Z
// // TKPermissionManager.h // Welcome // // Created by Adrian Schoenig on 4/09/12. // Copyright (c) 2012 Adrian Schoenig. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef void (^TKPermissionCompletionBlock)(BOOL enabled); typedef void(^TKPermissionsOpenSettingsHandler)(void); typedef NS_CLOSED_ENUM(NSInteger, TKAuthorizationStatus) { TKAuthorizationStatusNotDetermined = 0, TKAuthorizationStatusRestricted, TKAuthorizationStatusDenied, TKAuthorizationStatusAuthorized }; FOUNDATION_EXPORT NSString *const TKPermissionsChangedNotification; @interface TKPermissionManager : NSObject @property (nonatomic, strong, nullable) TKPermissionsOpenSettingsHandler openSettingsHandler; // these are the main interface methods /** * Is the app capable and authorized to use these kind of permissions? */ - (BOOL)isAuthorized; // subclasses need to implement these - (BOOL)featureIsAvailable; - (void)askForPermission:(TKPermissionCompletionBlock)completion; - (BOOL)authorizationRestrictionsApply; - (TKAuthorizationStatus)authorizationStatus; - (NSString *)authorizationAlertText; @end NS_ASSUME_NONNULL_END
25.369565
93
0.807198
da4493519755eb55a294993ffebdea10cc74db8a
1,072
h
C
MCSDK.framework/Headers/MCSDK.h
trs-mobile/MCSDK
570c23e533f227828e81e3f952ecd564d8891ad4
[ "MIT" ]
null
null
null
MCSDK.framework/Headers/MCSDK.h
trs-mobile/MCSDK
570c23e533f227828e81e3f952ecd564d8891ad4
[ "MIT" ]
null
null
null
MCSDK.framework/Headers/MCSDK.h
trs-mobile/MCSDK
570c23e533f227828e81e3f952ecd564d8891ad4
[ "MIT" ]
null
null
null
// // MCSDK.h // MediaCloud // // Created by TRS on 2019/6/27. // Copyright © 2019 TRS. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface MCSDK : NSObject /** * @brief 注册MCSDK组件服务 * @param url 采编地址 */ + (void)initMCSDKWithUrl:(NSString *)url; /** * @brief 获取栏目数 * @param siteId 站点ID * @param completion 操作结果回调 */ + (void)getChannelsBySiteId:(NSInteger)siteId completion:(void(^)(BOOL success, NSDictionary* response, NSError *error))completion; /** * @brief 获取栏目列表 * @param pageNo 当前页数 * @param pageSize 页数大小 * @param completion 操作结果回调 */ + (void)getChnlDocs:(NSInteger)channelId pageNo:(NSInteger)pageNo pageSize:(NSInteger)pageSize completion:(void(^)(BOOL success, NSDictionary* response, NSError *error))completion; /** * @brief 获取稿件详情 * param docId 稿件ID * @param completion 操作结果回调 */ + (void)getDocument:(NSInteger)docId completion:(void(^)(BOOL success, NSDictionary* response, NSError *error))completion; @end NS_ASSUME_NONNULL_END
21.019608
102
0.679104
0a30922d08400f5aee083dd71f3ebf6e22e5fdde
1,683
h
C
Source/Utility/SnowyStream/Resource/SkeletonResource.h
paintdream/PaintsNow
52e14de651b56c100caac0ce2b14348441543e1a
[ "MIT" ]
15
2016-09-17T16:29:42.000Z
2021-11-24T06:21:27.000Z
Source/Utility/SnowyStream/Resource/SkeletonResource.h
paintdream/PaintsNow
52e14de651b56c100caac0ce2b14348441543e1a
[ "MIT" ]
null
null
null
Source/Utility/SnowyStream/Resource/SkeletonResource.h
paintdream/PaintsNow
52e14de651b56c100caac0ce2b14348441543e1a
[ "MIT" ]
3
2017-04-07T13:33:57.000Z
2021-03-31T02:04:48.000Z
// SkeletonResource.h // PaintDream (paintdream@paintdream.com) // 2018-3-10 // #pragma once #include "RenderResourceBase.h" #include "../../../General/Interface/IAsset.h" namespace PaintsNow { class SkeletonResource : public TReflected<SkeletonResource, RenderResourceBase> { public: SkeletonResource(ResourceManager& manager, const String& uniqueID); TObject<IReflect>& operator () (IReflect& reflect) override; void Download(IRender& device, void* deviceContext) override; void Upload(IRender& device, void* deviceContext) override; void Attach(IRender& device, void* deviceContext) override; void Detach(IRender& device, void* deviceContext) override; typedef IAsset::BoneAnimation BoneAnimation; typedef IAsset::BoneAnimation::Joint Joint; typedef IAsset::TransSequence TransSequence; typedef IAsset::RotSequence RotSequence; typedef IAsset::ScalingSequence ScalingSequence; float Snapshot(std::vector<MatrixFloat4x4>& transforms, uint32_t clipIndex, float time, bool repeat); const BoneAnimation& GetBoneAnimation() const; const std::vector<MatrixFloat4x4>& GetOffsetTransforms() const; void UpdateBoneMatrixBuffer(IRender& render, IRender::Queue* queue, IRender::Resource*& buffer, const std::vector<MatrixFloat4x4>& data); void ClearBoneMatrixBuffer(IRender& render, IRender::Queue* queue, IRender::Resource*& buffer); protected: void PrepareTransform(std::vector<MatrixFloat4x4>& transforms, size_t i); void PrepareOffsetTransform(size_t i); protected: BoneAnimation boneAnimation; std::vector<MatrixFloat4x4> offsetMatrices; std::vector<MatrixFloat4x4> offsetMatricesInv; }; }
39.139535
140
0.759952
ddcb15e1996b67e700d5ce1c5bda71f79175491e
313
c
C
02/fgetc.c
coeykee/System-Programming
0be94e8b7bfff2c1fe84edc9c9f4713122456165
[ "MIT" ]
null
null
null
02/fgetc.c
coeykee/System-Programming
0be94e8b7bfff2c1fe84edc9c9f4713122456165
[ "MIT" ]
null
null
null
02/fgetc.c
coeykee/System-Programming
0be94e8b7bfff2c1fe84edc9c9f4713122456165
[ "MIT" ]
1
2018-07-11T06:15:36.000Z
2018-07-11T06:15:36.000Z
#include<string.h> #include<stdio.h> int main(){ FILE *stream; char string[] = "\n This is a Test"; char ch; stream = fopen("DUMMY.FIL","w+"); fwrite(string,strlen(string),1,stream); fseek(stream,0,SEEK_SET); do{ ch= fgetc(stream); putchar(ch); }while(ch!=EOF); fclose(stream); return 0; }
14.227273
40
0.626198
20c01861b9e8291454245fbe9b9312565f560c20
20,145
c
C
funcs.c
andi8086/65simc
e73443808fa811a3d0d8d6f01e081f41b192cc7f
[ "MIT" ]
null
null
null
funcs.c
andi8086/65simc
e73443808fa811a3d0d8d6f01e081f41b192cc7f
[ "MIT" ]
null
null
null
funcs.c
andi8086/65simc
e73443808fa811a3d0d8d6f01e081f41b192cc7f
[ "MIT" ]
null
null
null
/*************************************************************** * MOS 6502 System Emulator * v 0.1 * * (c) 2017 Andreas J. Reichel * * h o m e b a s e _ a r (a|t]> w e b . d e * * License: MIT (see LICENSE.txt) ***************************************************************/ #include <stdio.h> #include "6502.h" #include "mem.h" #define STACK_STORE16(x) \ memory[0x100 + cpu.S--] = x >> 8; \ memory[0x100 + cpu.S--] = x & 0xFF; #define STACK_STORE8(x) \ memory[0x100 + cpu.S--] = x; #define STACK_LOAD16(x) \ x = memory[0x100 + ++cpu.S]; \ x |= memory[0x100 + ++cpu.S] << 8; #define STACK_LOAD8(x) \ x = memory[0x100 + ++cpu.S]; uint8_t *addrDecode(enum amode a) { uint8_t idx_lo, idx_hi; uint16_t addr; switch(a) { case aNULL: return NULL; case aimm: /* #$00 */ cpu.PC += 1; // Address points to immediate byte after opcode // which can be source only return &memory[cpu.PC - 1]; case azp: /* $00 */ cpu.PC += 1; // Byte after opcode is zero page index idx_lo = memory[cpu.PC - 1]; // Return address of this memory cell mem_addr = idx_lo; return &memory[idx_lo]; case aabs: /* $0000 */ cpu.PC += 2; // Word after opcode is absolute address idx_lo = memory[cpu.PC - 2]; idx_hi = memory[cpu.PC - 1]; // Return address of this memory cell mem_addr = (uint16_t) idx_hi << 8 | idx_lo; return &memory[mem_addr]; case arel: /* PC + $0000 */ return 0; case azpx: /* $00, X */ cpu.PC += 1; // Byte after opcode is zero page index idx_lo = memory[cpu.PC - 1]; // X-Register is added to this index // This wraps around to stay in zero page mem_addr = (uint16_t) (cpu.X + idx_lo) & 0xFF; return &memory[mem_addr]; case azpy: /* $00, Y */ cpu.PC += 1; // Byte after opcode is zero page index idx_lo = memory[cpu.PC - 1]; // Y-Register is added to this index // This wraps around to stay in zero page mem_addr = (cpu.Y + idx_lo) & 0xFF; return &memory[mem_addr]; case aabx: /* $0000, X */ cpu.PC += 2; // Word after opcode is absolute address idx_lo = memory[cpu.PC - 2]; idx_hi = memory[cpu.PC - 1]; // X-Register is added to this absolute address mem_addr = (uint16_t) idx_hi << 8 | idx_lo + cpu.X; return &memory[mem_addr]; case aaby: /* $0000, Y */ cpu.PC += 2; // Word after opcode is absolute address idx_lo = memory[cpu.PC - 2]; idx_hi = memory[cpu.PC - 1]; // Y-Register is added to this absolute address mem_addr = (uint16_t) idx_hi << 8 | idx_lo + cpu.Y; return &memory[mem_addr]; case aind: /* ($0000) */ cpu.PC += 2; idx_lo = memory[cpu.PC - 2]; idx_hi = memory[cpu.PC - 1]; // Word after opcode is a pointer to the address addr = memory[(uint16_t) idx_hi << 8 | idx_lo]; // Return address to where this address points mem_addr = addr; return &memory[addr]; case aizx: /* ($00, X) */ cpu.PC += 1; // Byte after offset is an index into zero page addr = memory[cpu.PC - 1]; // Fetch a word from there and add the X register // This word forms itself an address word idx_lo = memory[(addr + cpu.X) & 0xFF]; idx_hi = memory[(addr + cpu.X + 1) & 0xFF]; // Return address to where this address word points mem_addr = (uint16_t) idx_hi << 8 | idx_lo; return &memory[mem_addr]; case aizy: /* ($00), Y */ cpu.PC += 1; // Byte after offset is an index into zero page addr = memory[cpu.PC - 1]; // Fetch word from this address to get new address idx_lo = memory[addr]; idx_hi = memory[(addr + 1) & 0xFF]; // To this indirect address add the Y-Register to get // the final address mem_addr = (uint16_t) idx_hi << 8 | idx_lo + cpu.Y; return &memory[mem_addr]; case aA: return &cpu.A; case aS: return &cpu.S; case aX: return &cpu.X; } } void group0(int a, uint8_t idx) { uint16_t ret_addr; cpu.PC++; switch(idx) { case 0: // BRK; // calculate return address = PC+2 // Store PC(hi) // Store PC(lo) // Store P ret_addr = cpu.PC + 2; STACK_STORE16(ret_addr); STACK_STORE8(cpu.P); // Fetch PC(lo) from $FFFE // Fetch PC(hi) from $FFFF cpu.PC = *((uint16_t *) &memory[0xFFFE]); return; case 2: // PHP STACK_STORE8(cpu.P); printf("PHP = %02X", cpu.P); return; case 4: // BPL if (!(cpu.P & F_N)) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BPL [true]"); } else { printf("BPL [false]"); } cpu.PC++; return; case 6: // CLC cpu.P &= ~ (uint8_t) F_C; printf("CLC"); return; } } void group1(int a, uint8_t idx) { uint8_t *op; uint16_t ret_addr; cpu.PC++; switch(idx) { case 0: // JSR abs ret_addr = cpu.PC + 2; STACK_STORE16(ret_addr); cpu.PC = *((uint16_t*) &memory[cpu.PC]); printf("JSR"); return; case 1: // BIT zp case 3: // BIT abs op = addrDecode(a); printf("BIT %02X, %02X", cpu.A, op); if (!(*op & cpu.A)) { cpu.P |= F_Z; } // transfer topmost two bits to flags cpu.P = cpu.P & 0x3F; cpu.P |= *op & 0xC0; mem_rwb = 1; mem_sync = true; return; case 2: // PLP STACK_LOAD8(cpu.P); return; case 4: // BMI rel if (cpu.P & F_N) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BMI [true]"); } else { printf("BMI [false]"); } cpu.PC++; return; case 6: // SEC cpu.P |= F_C; printf("SEC"); return; } } void group2(int a, uint8_t idx) { cpu.PC++; switch(idx) { case 0: // RTI STACK_LOAD8(cpu.P); STACK_LOAD16(cpu.PC); printf("RTI"); return; case 2: // PHA STACK_STORE8(cpu.A); printf("PHA = %02X", cpu.A); return; case 3: // JMP abs cpu.PC = *((uint16_t*) &memory[cpu.PC]); printf("JMP"); return; case 4: // BVC if (!(cpu.P & F_V)) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BVC [true]"); } else { printf("BVC [false]"); } cpu.PC++; return; case 6: // CLI cpu.P &= ~ (uint8_t) F_I; printf("CLI"); return; } } void group3(int a, uint8_t idx) { uint16_t addr; cpu.PC++; switch(idx) { case 0: // RTS STACK_LOAD16(cpu.PC); printf("RTS"); return; case 2: // PLA STACK_LOAD8(cpu.A); printf("PLA"); return; case 3: // JMP ind addr = *((uint16_t*) addrDecode(a)); cpu.PC = addr; printf("JMP"); return; case 4: // BVS if (cpu.P & F_V) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BVS [true]"); } else { printf("BVS [false]"); } cpu.PC++; return; case 6: // SEI cpu.P |= F_I; printf("SEI"); return; } } void group4(int a, uint8_t idx) { uint8_t *addr; cpu.PC++; switch(idx) { case 2: // DEY cpu.Y--; cpu.P &= F_MASK_NZ; cpu.P |= cpu.Y & 0x80; if (!cpu.Y) { cpu.P &= F_Z; } printf("DEY"); return; case 4: // BCC if (!(cpu.P & F_C)) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BCC [true]"); } else { printf("BCC [false]"); } cpu.PC++; return; default: // STY, TYA addr = addrDecode(a); *addr = cpu.Y; if (addr != &cpu.A) { mem_rwb = 0; mem_sync = true; } cpu.P &= F_MASK_NZ; // set N flag cpu.P |= cpu.Y & 0x80; // set Z flag if (!cpu.Y) { cpu.P |= F_Z; } printf("STY / TYA"); return; } } void group5(int a, uint8_t idx) { uint8_t *addr; cpu.PC++; switch(idx) { case 4: // BCS if (cpu.P & F_C) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BCS [true]"); } else { printf("BCS [false]"); } cpu.PC++; return; case 6: // CLV cpu.P &= F_MASK_V; printf("CLV"); return; default: // LDY, TAY addr = addrDecode(a); if (addr != &cpu.A) { mem_rwb = 1; mem_sync = true; } cpu.Y = *addr; cpu.P &= F_MASK_NZ; // set N flag cpu.P |= cpu.Y & 0x80; // set Z flag if (!cpu.Y) { cpu.P |= F_Z; } printf("LDY / TAY"); return; } } void group6(int a, uint8_t idx) { int16_t erg; uint8_t op; cpu.PC++; switch(idx) { case 2: // INY cpu.Y++; cpu.P &= F_MASK_NZ; cpu.P |= cpu.Y & 0x80; if (!cpu.Y) { cpu.P &= F_Z; } printf("INY"); return; case 4: // BNE if (!(cpu.P & F_Z)) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BNE [true]"); } else { printf("BNE [false]"); } cpu.PC++; return; case 6: // CLD cpu.P &= ~ (uint8_t) F_D; printf("CLD"); return; default: // CPY op = *addrDecode(a); erg = (int16_t) cpu.Y - op; cpu.P &= F_MASK_NZC; // set N flag if (erg < 0) cpu.P |= F_N; // set Z flag if (!erg) { cpu.P |= F_Z; } // set C flag if (erg >= 0) { cpu.P |= F_C; } mem_rwb = 1; mem_sync = true; printf("CPY =%02X", op); return; } } void group7(int a, uint8_t idx) { cpu.PC++; int16_t erg; uint8_t op; switch(idx) { case 2: // INX cpu.X++; cpu.P &= F_MASK_NZ; cpu.P |= cpu.X & 0x80; if (!cpu.X) { cpu.P &= F_Z; } printf("INX"); return; case 4: // BEQ if (cpu.P & F_Z) { cpu.PC += (int8_t) memory[cpu.PC]; printf("BEQ [true]"); } else { printf("BEQ [false]"); } cpu.PC++; return; case 6: // SED cpu.P |= F_D; printf("SED"); return; default: // CPX op = *addrDecode(a); erg = (int16_t) cpu.X - op; cpu.P &= F_MASK_NZC; // set N flag if (erg < 0) cpu.P |= F_N; // set Z flag if (!erg) { cpu.P |= F_Z; } // set C flag if (erg >= 0) { cpu.P |= F_C; } mem_rwb = 1; mem_sync = true; printf("CPX =%02X", op); return; } } void groupORA(int a, uint8_t idx) { cpu.PC++; uint8_t *op = addrDecode(a); printf("ORA %02X, %02X", cpu.A, *op); cpu.A |= *op; cpu.P &= F_MASK_NZ; cpu.P |= cpu.A & 0x80; if (!cpu.A) { cpu.P |= F_Z; } mem_rwb = 1; mem_sync = true; } void groupAND(int a, uint8_t idx) { cpu.PC++; uint8_t *op = addrDecode(a); printf("AND %02X, %02X", cpu.A, *op); cpu.A &= *op; cpu.P &= F_MASK_NZ; cpu.P |= cpu.A & 0x80; if (!cpu.A) { cpu.P |= F_Z; } mem_rwb = 1; mem_sync = true; } void groupEOR(int a, uint8_t idx) { cpu.PC++; uint8_t *op = addrDecode(a); printf("EOR %02X, %02X", cpu.A, *op); cpu.A ^= *op; cpu.P &= F_MASK_NZ; cpu.P |= cpu.A & 0x80; if (!cpu.A) { cpu.P |= F_Z; } mem_rwb = 1; mem_sync = true; } void groupADC(int a, uint8_t idx) { // This shall simulate all flags for bin and BCD correctly, // even for invalid arguments, for MOS 6502 only ! cpu.PC = cpu.PC + 1; uint8_t *mem = addrDecode(a); uint8_t A = cpu.A; printf("ADC %02X, %02X", A, *mem); bool decimal_mode = cpu.P & F_D; uint8_t c = cpu.P & F_C; uint16_t erg = (A & 0x0F) + ((*mem) & 0x0F) + (cpu.P & F_C); if ((erg >= 0x0A) && decimal_mode) { erg = ((erg + 0x06) & 0x0F) + 0x10; } erg += (A & 0xF0) + ((*mem) & 0xF0); cpu.P &= F_MASK_NVZC; // Calculate N and V here for 6502 // set negative flag if (erg & 0x80) cpu.P |= F_N; // set overflow flag //printf("\n%d %d %d\n", (int8_t) A, (int8_t) *mem, (uint8_t) erg); if (((int8_t) A >= 0) && ((int8_t) *mem >= 0) && (erg >= 0x80)) { cpu.P |= F_V; } else if (((int8_t) A < 0) && ((int8_t) *mem < 0) && ((erg & 0xFF) < 0x80)) { cpu.P |= F_V; } if ((erg >= 0xA0) && decimal_mode) { erg += 0x60; } // set carry flag if (erg >= 0x100) { cpu.P |= F_C; } if (!(A + (*mem) + c)) { cpu.P |= F_Z; } cpu.A = erg & 0xFF; mem_rwb = 1; mem_sync = true; } void groupSTA(int a, uint8_t idx) { cpu.PC = cpu.PC + 1; uint8_t *op = addrDecode(a); *op = cpu.A; mem_rwb = 0; mem_sync = true; printf("STA =%02X", cpu.A); } void groupLDA(int a, uint8_t idx) { cpu.PC = cpu.PC + 1; uint8_t *op = addrDecode(a); cpu.A = *op; printf("LDA =%02X", cpu.A); cpu.P &= F_MASK_NZ; cpu.P |= cpu.A & 0x80; if (!cpu.A) { cpu.P |= F_Z; } mem_rwb = 1; mem_sync = true; } void groupCMP(int a, uint8_t idx) { cpu.PC++; int16_t erg; uint8_t m = *addrDecode(a); erg = (int16_t) cpu.A - m; cpu.P &= F_MASK_NZC; // set N flag if (erg < 0) cpu.P |= F_N; // set Z flag if (!erg) { cpu.P |= F_Z; } // set C flag if (erg >= 0) { cpu.P |= F_C; } mem_rwb = 1; mem_sync = true; printf("CMP %02X, %02X", cpu.A, m); } void groupSBC(int a, uint8_t idx) { // This shall simulate all flags for bin and BCD correctly, // even for invalid arguments, for MOS 6502 only ! cpu.PC++; uint8_t *mem = addrDecode(a); uint8_t A = cpu.A; printf("SBC %02X, %02X", A, *mem); bool decimal_mode = cpu.P & F_D; int16_t erg = (A & 0x0F) - (*mem & 0x0F) + (cpu.P & F_C) - 1; if ((erg < 0) && decimal_mode) { erg = ((erg - 0x06) & 0x0F) - 0x10; } erg += (A & 0xF0) - (*mem & 0xF0); if ((erg < 0) && decimal_mode) { erg -= 0x60; } uint8_t c = cpu.P & F_C; int16_t x = (int8_t) cpu.A; int16_t y = (int8_t) *mem; int16_t e = x - y + (cpu.P & F_C) - 1; cpu.P &= F_MASK_NVZC; // Calculate N and V here for 6502 // set overflow flag if (e < -128 || e > 127) { cpu.P |= F_V; } // set negative flag if (e < 0) cpu.P |= F_N; // calculate carry uint16_t cz = (uint16_t) A - *mem + c - 1; if (cz <= 0xFF) { cpu.P |= F_C; } if (cz == 0) { cpu.P |= F_Z; } cpu.A = erg & 0xFF; mem_rwb = 1; mem_sync = true; } void groupASL(int a, uint8_t idx) { uint8_t *m; uint8_t val; cpu.PC++; switch(idx) { case 6: // NOP printf("NOP"); return; default: m = addrDecode(a); // get highest bit into carry cpu.P &= F_MASK_NZC; cpu.P |= (*m & 0x80) >> 7; val = *m; mem_rwb = 2; if (m != &cpu.A) mem_sync = true; while(mem_sync); val <<= 1; *m = val; if (m != &cpu.A) mem_sync = true; // set N flag cpu.P |= *m & 0x80; // set Z flag if (!*m) { cpu.P |= F_Z; } printf("ASL"); return; } } void groupROL(int a, uint8_t idx) { uint8_t *m; uint8_t c; uint8_t val; cpu.PC++; m = addrDecode(a); c = (*m & 0x80) >> 7; val = *m; mem_rwb = 2; if (m != &cpu.A) mem_sync = true; while(mem_sync); val <<= 1; val |= cpu.P & F_C; *m = val; if (m != &cpu.A) mem_sync = true; cpu.P &= F_MASK_NZC; // set C flag cpu.P |= c; // set N flag cpu.P |= *m & 0x80; // set Z flag if (!*m) { cpu.P |= F_Z; } printf("ROL"); } void groupLSR(int a, uint8_t idx) { uint8_t val; cpu.PC++; uint8_t *m = addrDecode(a); cpu.P &= F_MASK_ZC; // set C flag val = *m; mem_rwb = 2; if (m != &cpu.A) mem_sync = true; while(mem_sync); cpu.P |= val & 1; val >>= 1; *m = val; if (m != &cpu.A) mem_sync = true; // set Z flag if (!*m) { cpu.P |= F_Z; } printf("LSR"); } void groupROR(int a, uint8_t idx) { uint8_t *m; uint8_t c, val; cpu.PC++; m = addrDecode(a); val = *m; mem_rwb = 2; if (m != &cpu.A) mem_sync = true; while(mem_sync); c = val & 1; val >>= 1; val |= (cpu.P & F_C) << 7; *m = val; if (m != &cpu.A) mem_sync = true; cpu.P &= F_MASK_NZC; // N flag is C flag cpu.P |= *m & 0x80; cpu.P |= c; if (!*m) { cpu.P |= F_Z; } printf("ROR"); } void groupSX(int a, uint8_t idx) { cpu.PC++; *addrDecode(a) = cpu.X; // TXS (idx == 6) and TXA (id == 2) affect flags, STX (idx == 1,3,5) does not if (idx == 6 || idx == 2) { printf("TXS/TXA =%02X", cpu.X); cpu.P &= F_MASK_NZ; // set N flag cpu.P |= cpu.X & 0x80; if (!cpu.X) { // set Z flag cpu.P |= F_Z; } } else { mem_rwb = 0; mem_sync = true; printf("STX =%02X", cpu.X); } } void groupLX(int a, uint8_t idx) { cpu.PC++; cpu.X = *addrDecode(a); // TSX (idx == 6) and TAX (id == 2) affect flags, LDX (idx = 0, 1, 3, 5, 7) does not if (idx == 6 || idx == 2) { printf("TSX/TAX =%02X", cpu.X); cpu.P &= F_MASK_NZ; // set N flag cpu.P |= cpu.X & 0x80; if (!cpu.X) { // set Z flag cpu.P |= F_Z; } } else { mem_rwb = 1; mem_sync = true; printf("LDX =%02X", cpu.X); } } void groupDEC(int a, uint8_t idx) { cpu.PC++; uint8_t *m = addrDecode(a); uint8_t val; val = *m; mem_rwb = 2; if (m != &cpu.X) mem_sync = true; while(mem_sync); val--; *m = val; if (m != &cpu.X) mem_sync = true; cpu.P &= F_MASK_NZ; // set N flag cpu.P |= *m & 0x80; if (!*m) { // set Z flag cpu.P |= F_Z; } printf("DEC =%02X", *m); } void groupINC(int a, uint8_t idx) { cpu.PC++; uint8_t val; if (idx == 2) { // NOP printf("NOP"); return; } uint8_t *m = addrDecode(a); printf("INC =%02X", *m); val = *m; mem_rwb = 2; mem_sync = true; while(mem_sync); val++; *m = val; mem_sync = true; cpu.P &= F_MASK_NZ; // set N flag cpu.P |= *m & 0x80; if (!*m) { // set Z flag cpu.P |= F_Z; } } void groupSLO(int a, uint8_t idx) { } void groupRLA(int a, uint8_t idx) { } void groupSRE(int a, uint8_t idx) { } void groupRRA(int a, uint8_t idx) { } void groupSAX(int a, uint8_t idx) { } void groupLAX(int a, uint8_t idx) { } void groupDCP(int a, uint8_t idx) { } void groupISC(int a, uint8_t idx) { }
22.433185
88
0.446562
20c96fe04dec630601ec3b58e788a55f36467f6d
74
h
C
randomgen/src/xoroshiro128/xoroshiro128plus.orig.h
amrali-eg/randomgen
ea45e16d4e8ff701a705f5f5ec3592f656170f39
[ "NCSA", "BSD-3-Clause" ]
73
2018-03-28T19:40:23.000Z
2022-02-06T18:30:17.000Z
randomgen/src/xoroshiro128/xoroshiro128plus.orig.h
amrali-eg/randomgen
ea45e16d4e8ff701a705f5f5ec3592f656170f39
[ "NCSA", "BSD-3-Clause" ]
209
2018-03-22T05:52:50.000Z
2022-03-23T02:07:58.000Z
randomgen/src/xoroshiro128/xoroshiro128plus.orig.h
amrali-eg/randomgen
ea45e16d4e8ff701a705f5f5ec3592f656170f39
[ "NCSA", "BSD-3-Clause" ]
22
2018-05-22T11:21:19.000Z
2022-02-28T03:27:48.000Z
#include <stdint.h> uint64_t s[2]; uint64_t next(void); void jump(void);
12.333333
20
0.702703
dd27d4fb9d3c8281920c6d5d83c14973d7701c5a
504
h
C
Client/MusicCloud/MusicCloud/SongTableViewCell.h
hanvo/MusicCloud
b91b9481df087955fcb09f472308c9ad1a94ba94
[ "BSD-3-Clause" ]
null
null
null
Client/MusicCloud/MusicCloud/SongTableViewCell.h
hanvo/MusicCloud
b91b9481df087955fcb09f472308c9ad1a94ba94
[ "BSD-3-Clause" ]
null
null
null
Client/MusicCloud/MusicCloud/SongTableViewCell.h
hanvo/MusicCloud
b91b9481df087955fcb09f472308c9ad1a94ba94
[ "BSD-3-Clause" ]
null
null
null
// // SongTableViewCell.h // MusicCloud // // Created by Josh on 4/16/14. // Copyright (c) 2014 CS252. All rights reserved. // #import <UIKit/UIKit.h> @interface SongTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *albumImageView; @property (weak, nonatomic) IBOutlet UILabel *nameLabel; @property (weak, nonatomic) IBOutlet UILabel *artistLabel; @property (weak, nonatomic) IBOutlet UILabel *voteLabel; @property (weak, nonatomic) IBOutlet UILabel *idLabel; @end
26.526316
65
0.751984
976c5fec80890d6c7fe2a326a28d9b8512075002
137
c
C
Exercise5.c
arif98741/basic-c-programming-codes
a75a5215ea182374ab9bf9126248df20a795cd9d
[ "Apache-2.0" ]
2
2016-06-04T11:25:26.000Z
2021-11-08T11:39:10.000Z
Exercise5.c
arif98741/basic-c-programming-codes
a75a5215ea182374ab9bf9126248df20a795cd9d
[ "Apache-2.0" ]
1
2016-06-04T08:02:16.000Z
2017-11-17T22:29:02.000Z
Exercise5.c
arif98741/basic-c-programming-codes
a75a5215ea182374ab9bf9126248df20a795cd9d
[ "Apache-2.0" ]
1
2019-08-07T06:43:42.000Z
2019-08-07T06:43:42.000Z
#include <stdio.h> int main() { int a=12; float b=34.455; b=(int)b; printf("%f",b); return 0; }
9.785714
21
0.416058
5ab61298cee6a02107fc21b7e010c378d5ae37c0
370
c
C
srcpkgs/fortune-mod/files/error.c
plantenos/plan10-packages
e313ff4e018fe45f8b36d4d145b48aedfc13afa5
[ "BSD-2-Clause" ]
null
null
null
srcpkgs/fortune-mod/files/error.c
plantenos/plan10-packages
e313ff4e018fe45f8b36d4d145b48aedfc13afa5
[ "BSD-2-Clause" ]
null
null
null
srcpkgs/fortune-mod/files/error.c
plantenos/plan10-packages
e313ff4e018fe45f8b36d4d145b48aedfc13afa5
[ "BSD-2-Clause" ]
null
null
null
#include <stdarg.h> #include <stdio.h> #define _GNU_SOURCE #include <errno.h> plan10 error(int status, int errnum, const char* format, ...) { va_list ap; fflush(stdout); fprintf(stderr, "%s: ", program_invocation_name); va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); if (errnum) fprintf(stderr, ":%d", errnum); if (status) exit(status); }
18.5
61
0.678378
2d98822ec4e2f77df19e9c8032457561e7c0099d
1,089
h
C
starfield.h
thales17/BBBBBB
b61abae50c5e39dd3b5be5c2787b43dfa5889a1c
[ "BSD-3-Clause" ]
16
2020-02-23T23:25:35.000Z
2021-08-19T10:30:28.000Z
starfield.h
thales17/BBBBBB
b61abae50c5e39dd3b5be5c2787b43dfa5889a1c
[ "BSD-3-Clause" ]
null
null
null
starfield.h
thales17/BBBBBB
b61abae50c5e39dd3b5be5c2787b43dfa5889a1c
[ "BSD-3-Clause" ]
1
2020-02-23T23:25:53.000Z
2020-02-23T23:25:53.000Z
#ifndef STARFIELD_H #define STARFIELD_H #include <time.h> #include <stdlib.h> #include <SDL2/SDL.h> #define STAR_COUNT 50 #define STAR_MAXSIZE 10 SDL_Rect stars[STAR_COUNT]; int width; int height; void setup_starfield(int w, int h) { int i; width = w; height = h; srand(time(NULL)); for (i = 0; i < STAR_COUNT; i++) { int s = rand() % STAR_MAXSIZE; stars[i].x = rand() % width; stars[i].y = rand() % height; stars[i].w = s; stars[i].h = s; } } void update_starfield() { int i; for (i = 0; i < STAR_COUNT; i++) { int speed = 1; if (stars[i].w > (STAR_MAXSIZE / 3)) { speed++; } if (stars[i].w > 2 * (STAR_MAXSIZE / 3)) { speed++; } stars[i].x += speed; stars[i].x %= width; } } void draw_starfield(SDL_Renderer *renderer) { SDL_Rect r; int i; r.x = 0; r.y = 0; r.w = width; r.h = height; SDL_SetRenderDrawColor(renderer, 0x0B, 0x0B, 0x0B, 0xFF); SDL_RenderFillRect(renderer, &r); SDL_SetRenderDrawColor(renderer, 0xCC, 0xCC, 0xCC, 0xFF); for (i = 0; i < STAR_COUNT; i++) { SDL_RenderFillRect(renderer, &stars[i]); } } #endif
15.782609
58
0.615243
442368ab816abbdb69efcbb67593d0f32a90c5cd
674
h
C
YSYPhotoBrowser/Additions/UIColor+YSYAddition.h
yaoshaoyu/YSYPhotoBrowser
797ae0db417cadf4ecc46a2e83ac3796ed7adcb6
[ "MIT" ]
1
2017-04-11T03:39:47.000Z
2017-04-11T03:39:47.000Z
YSYPhotoBrowser/Additions/UIColor+YSYAddition.h
yaoshaoyu/YSYPhotoBrowser
797ae0db417cadf4ecc46a2e83ac3796ed7adcb6
[ "MIT" ]
null
null
null
YSYPhotoBrowser/Additions/UIColor+YSYAddition.h
yaoshaoyu/YSYPhotoBrowser
797ae0db417cadf4ecc46a2e83ac3796ed7adcb6
[ "MIT" ]
null
null
null
// // UIColor+YSYAddition.h // AdditionsDemo // // Created by 吕成翘 on 17/1/11. // Copyright © 2017年 Weitac. All rights reserved. // #import <UIKit/UIKit.h> @interface UIColor (YSYAddition) /** 使用16进制创建颜色 @param hex 16进制无符号32位整数 @param alpha 透明度 @return 颜色 */ + (instancetype)ysy_colorWithHex:(uint32_t)hex alpha:(float)alpha; /** 使用RGB创建颜色 @param red 红色 @param green 绿色 @param blue 蓝色 @param alpha 透明度 @return 颜色 */ + (instancetype)ysy_colorWithRed:(uint8_t)red green:(uint8_t)green blue:(uint8_t)blue alpha:(float)alpha; /** 创建随机色 @return 随机色 */ + (instancetype)ysy_randomColor; /** 创建主颜色 @return 主颜色 */ + (instancetype)ysy_baseColor; @end
13.755102
105
0.694362
db5847b6f17c30b7de0a299ae80f53ba51417b7a
483
c
C
learn/clang/basic/demoStruct.c
alicfeng/learncode
a2bab291b96135c6beef39662f8366de1246bf7d
[ "Apache-2.0" ]
1
2018-03-07T13:27:56.000Z
2018-03-07T13:27:56.000Z
learn/clang/basic/demoStruct.c
alicfeng/learncode
a2bab291b96135c6beef39662f8366de1246bf7d
[ "Apache-2.0" ]
null
null
null
learn/clang/basic/demoStruct.c
alicfeng/learncode
a2bab291b96135c6beef39662f8366de1246bf7d
[ "Apache-2.0" ]
1
2018-12-24T03:53:59.000Z
2018-12-24T03:53:59.000Z
/** * Created by alic(AlicFeng) on 17-7-27 from CLion. * Email is alic@samego.com */ //结构体 #include <stdio.h> /*定义一个结构体*/ struct User{ int age; char *name; }; int main(){ struct User user; user.age = 20; user.name = "alicfeng"; //复制一个结构体变量 但是新的变量已经分配新的内存空间 struct User user1 = user; //对user的成员改变不会影响user1的值 user.age = 21; printf("%s age is %d\n",user.name,user.age); printf("%s age is %d\n",user1.name,user1.age); return 0; }
16.1
51
0.602484
71b2b81a0f62ca6d320e79d83f6a0d270e1925be
541
h
C
Game/Source/SpecialPlatform.h
AdriaSeSa/LaboratoryGame
11c787f1785d0c8706431c25cfae96253f6a7c89
[ "MIT" ]
null
null
null
Game/Source/SpecialPlatform.h
AdriaSeSa/LaboratoryGame
11c787f1785d0c8706431c25cfae96253f6a7c89
[ "MIT" ]
null
null
null
Game/Source/SpecialPlatform.h
AdriaSeSa/LaboratoryGame
11c787f1785d0c8706431c25cfae96253f6a7c89
[ "MIT" ]
null
null
null
#pragma once #include "MobilePlatform.h" #define MAX_FIRENUM 20 class FireTrap; class SpecialPlatform : public MobilePlatform { public: SpecialPlatform(iPoint position, std::string name, std::string tag, Application* app, int lenght = 2, iPoint moveDistance = { 0,0 }, float moveSpeed = 1.0f, int stopTime = 0); void Reset(); void Update() override; void PostUpdate() override; void OnCollisionEnter(PhysBody* col); void CleanUp() override; private: FireTrap* fireTraps[MAX_FIRENUM] = { nullptr }; int fireStep = 0; };
17.451613
176
0.720887
9c3cd589e9e0a73dc3404854179326f1f1d911a3
441
h
C
Source/Core/Equipment/VesselEffects/PassiveVesselEffects/TargetData/MagentaTargetData.h
Lawrence-JD/Space-Egypt
f8aa37f1fbd1a26b662bb59ed7a9580ef3853854
[ "MIT" ]
null
null
null
Source/Core/Equipment/VesselEffects/PassiveVesselEffects/TargetData/MagentaTargetData.h
Lawrence-JD/Space-Egypt
f8aa37f1fbd1a26b662bb59ed7a9580ef3853854
[ "MIT" ]
null
null
null
Source/Core/Equipment/VesselEffects/PassiveVesselEffects/TargetData/MagentaTargetData.h
Lawrence-JD/Space-Egypt
f8aa37f1fbd1a26b662bb59ed7a9580ef3853854
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "PassiveTargetData.h" #include "MagentaTargetData.generated.h" UCLASS(BlueprintType, meta = (BlueprintSpawnableComponent), NonTransient) class SPEEGYPT_API UMagentaTargetData : public UPassiveTargetData { GENERATED_BODY() public: UPROPERTY(VisibleAnywhere, BlueprintReadOnly) bool bIsFixed = false; };
21
78
0.793651
d523b125bde43189fbc0b32946f752df976c894b
177,810
c
C
printscan/print/spooler/localspl/util.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/print/spooler/localspl/util.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/print/spooler/localspl/util.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1990 - 1995 Microsoft Corporation Module Name: util.c Abstract: This module provides all the utility functions for the Routing Layer and the local Print Providor Author: Dave Snipp (DaveSn) 15-Mar-1991 Revision History: Felix Maxa (amaxa) 18-Jun-2000 Added utility functions for cluster spoolers. Part of the DCR regarding installation of printer drivers on cluster spoolers Muhunthan Sivapragasam ( MuhuntS ) 5-June-1995 Moved from printer.c: RegSetBinaryData RegSetString RegSetDWord Wrote: SameMultiSz RegGetValue Matthew A Felton ( MattFe ) 23-mar-1995 DeleteAllFilesAndDirectory DeleteAllFilesInDirectory CreateDirectoryWithoutImpersonatingUser --*/ #include <precomp.h> #pragma hdrstop #include <winddiui.h> #include <lm.h> #include <aclapi.h> #include <winsta.h> #include "clusspl.h" typedef LONG (WINAPI *pfnWinStationSendWindowMessage)( HANDLE hServer, ULONG sessionID, ULONG timeOut, ULONG hWnd, ULONG Msg, WPARAM wParam, LPARAM lParam, LONG *pResponse); extern BOOL (*pfnOpenPrinter)(LPTSTR, LPHANDLE, LPPRINTER_DEFAULTS); extern BOOL (*pfnClosePrinter)(HANDLE); extern LONG (*pfnDocumentProperties)(HWND, HANDLE, LPWSTR, PDEVMODE, PDEVMODE, DWORD); #define DEFAULT_MAX_TIMEOUT 300000 // 5 minute timeout. CRITICAL_SECTION SpoolerSection; PDBG_POINTERS gpDbgPointers = NULL; pfnWinStationSendWindowMessage pfWinStationSendWindowMessage = NULL; VOID RunForEachSpooler( HANDLE h, PFNSPOOLER_MAP pfnMap ) { PINISPOOLER pIniSpooler; PINISPOOLER pIniNextSpooler; SplInSem(); if( pLocalIniSpooler ){ INCSPOOLERREF( pLocalIniSpooler ); for( pIniSpooler = pLocalIniSpooler; pIniSpooler; pIniSpooler = pIniNextSpooler ){ if( (*pfnMap)( h, pIniSpooler ) ){ pIniNextSpooler = pIniSpooler->pIniNextSpooler; } else { pIniNextSpooler = NULL; } if( pIniNextSpooler ){ INCSPOOLERREF( pIniNextSpooler ); } DECSPOOLERREF( pIniSpooler ); } } } VOID RunForEachPrinter( PINISPOOLER pIniSpooler, HANDLE h, PFNPRINTER_MAP pfnMap ) { PINIPRINTER pIniPrinter; PINIPRINTER pIniNextPrinter; SplInSem(); pIniPrinter = pIniSpooler->pIniPrinter; if( pIniPrinter ){ INCPRINTERREF( pIniPrinter ); for( ; pIniPrinter; pIniPrinter = pIniNextPrinter ){ if( (*pfnMap)( h, pIniPrinter ) ){ pIniNextPrinter = pIniPrinter->pNext; } else { pIniNextPrinter = NULL; } if( pIniNextPrinter ){ INCPRINTERREF( pIniNextPrinter ); } DECPRINTERREF( pIniPrinter ); DeletePrinterCheck( pIniPrinter ); } } } #if DBG HANDLE hcsSpoolerSection = NULL; VOID SplInSem( VOID ) { if( hcsSpoolerSection ){ SPLASSERT( gpDbgPointers->pfnInsideCritSec( hcsSpoolerSection )); } else { SPLASSERT( SpoolerSection.OwningThread == (HANDLE)(ULONG_PTR)(GetCurrentThreadId( ))); } } VOID SplOutSem( VOID ) { if( hcsSpoolerSection ){ SPLASSERT( gpDbgPointers->pfnOutsideCritSec( hcsSpoolerSection )); } else { SPLASSERT( SpoolerSection.OwningThread != (HANDLE)((ULONG_PTR)GetCurrentThreadId( ))); } } #endif // DBG VOID EnterSplSem( VOID ) { #if DBG if( hcsSpoolerSection ){ gpDbgPointers->pfnEnterCritSec( hcsSpoolerSection ); } else { EnterCriticalSection( &SpoolerSection ); } #else EnterCriticalSection( &SpoolerSection ); #endif } VOID LeaveSplSem( VOID ) { #if DBG if( hcsSpoolerSection ){ gpDbgPointers->pfnLeaveCritSec( hcsSpoolerSection ); } else { LeaveCriticalSection( &SpoolerSection ); } #else LeaveCriticalSection( &SpoolerSection ); #endif } BOOL IsThreadInSem( DWORD ThreadID ) { BOOL bInSem = FALSE; #if DBG if (hcsSpoolerSection) { bInSem = gpDbgPointers->pfnInsideCritSec(hcsSpoolerSection); } else { bInSem = SpoolerSection.OwningThread == (HANDLE)(ULONG_PTR)ThreadID; } #else bInSem = SpoolerSection.OwningThread == (HANDLE)(ULONG_PTR)ThreadID; #endif return bInSem; } PDEVMODE AllocDevMode( PDEVMODE pDevMode ) { PDEVMODE pDevModeAlloc = NULL; DWORD Size; if (pDevMode) { Size = pDevMode->dmSize + pDevMode->dmDriverExtra; if(pDevModeAlloc = AllocSplMem(Size)) { memcpy(pDevModeAlloc, pDevMode, Size); } } return pDevModeAlloc; } BOOL FreeDevMode( PDEVMODE pDevMode ) { if (pDevMode) { FreeSplMem((PVOID)pDevMode); return TRUE; } else { return FALSE; } } PINIENTRY FindName( PINIENTRY pIniKey, LPWSTR pName ) { if (pName) { while (pIniKey) { if (!lstrcmpi(pIniKey->pName, pName)) { return pIniKey; } pIniKey=pIniKey->pNext; } } return FALSE; } BOOL FileExists( LPWSTR pFileName ) { if( GetFileAttributes( pFileName ) == 0xffffffff ){ return FALSE; } return TRUE; } BOOL DirectoryExists( LPWSTR pDirectoryName ) { DWORD dwFileAttributes; dwFileAttributes = GetFileAttributes( pDirectoryName ); if ( dwFileAttributes != 0xffffffff && dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { return TRUE; } return FALSE; } BOOL CheckSepFile( IN LPWSTR pFileName ) { BOOL bRetval = FALSE; // // NULL or "" is OK: // if (!pFileName || !*pFileName) { bRetval = TRUE; } else { // // If the name is not NULL or "" then the name must be less // than MAX_PATH and exist. // if ((wcslen(pFileName) < MAX_PATH-1) && FileExists(pFileName)) { bRetval = TRUE; } } return bRetval; } DWORD GetFullNameFromId( IN PINIPRINTER pIniPrinter, IN DWORD JobId, IN BOOL fJob, IN PWSTR pFileName, IN SIZE_T cchFileName, IN BOOL Remote ) { DWORD i; // // We don't have a decent return path from this error function. Make sure // that all callers use a buffer size at least bigger than 9. // SPLASSERT(cchFileName > 9); // // MAX_PATH - 9 is tha maximum number of chars that we want to store in pFileName since we // want to concatenate the SPL/SHD file // If GetPrinterDirectory fails i is 0. // The right way to fix this is that the caller of GetFullNameFromId chackes for the return value // which is not the case. // i = GetPrinterDirectory(pIniPrinter, Remote, pFileName, (DWORD)(cchFileName-9), pIniPrinter->pIniSpooler); StringCchPrintf(&pFileName[i], cchFileName - i, L"\\%05d.%ws", JobId, fJob ? L"SPL" : L"SHD"); #ifdef PREVIOUS for (i = 5; i--;) { pFileName[i++] = (CHAR)((JobId % 10) + '0'); JobId /= 10; } #endif while (pFileName[i++]) ; return i-1; } DWORD GetPrinterDirectory( PINIPRINTER pIniPrinter, // Can be NULL BOOL Remote, LPWSTR pDir, DWORD MaxLength, PINISPOOLER pIniSpooler ) { DWORD i=0; LPWSTR psz; if (Remote) { DBGMSG(DBG_ERROR, ("GetPrinterDirectory called remotely. Not currently supported.")); return 0; } if ((pIniPrinter == NULL) || (pIniPrinter->pSpoolDir == NULL) ) { if (pIniSpooler->pDefaultSpoolDir == NULL) { // // No default directory, then create a default. For cluster spoolers, // the default directory is N:\Spool, where N is the shared drive letter // if( StrNCatBuff(pDir, MaxLength, pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER ? pIniSpooler->pszClusResDriveLetter : pIniSpooler->pDir, L"\\", pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER ? szClusterPrinterDir : szPrinterDir, NULL) != ERROR_SUCCESS ) { return 0; } pIniSpooler->pDefaultSpoolDir = AllocSplStr(pDir); } else { // // Give Caller the Default // if (!BoolFromHResult(StringCchCopy(pDir, MaxLength, pIniSpooler->pDefaultSpoolDir))) { return 0; } } } else { // // Have Per Printer Directory // if (!BoolFromHResult(StringCchCopy(pDir, MaxLength, pIniPrinter->pSpoolDir))) { return 0; } } return (wcslen(pDir)); } DWORD GetDriverDirectory( LPWSTR pDir, DWORD MaxLength, PINIENVIRONMENT pIniEnvironment, LPWSTR lpRemotePath, PINISPOOLER pIniSpooler ) { LPWSTR psz; if (lpRemotePath) { if( StrNCatBuff(pDir, MaxLength, lpRemotePath, L"\\", pIniSpooler->pszDriversShare, L"\\", pIniEnvironment->pDirectory, NULL) != ERROR_SUCCESS ) { return 0; } } else { if( StrNCatBuff( pDir, MaxLength, pIniSpooler->pDir, L"\\", szDriverDir, L"\\", pIniEnvironment->pDirectory, NULL) != ERROR_SUCCESS ) { return 0; } } return wcslen(pDir); } DWORD GetProcessorDirectory( LPWSTR *pDir, LPWSTR pEnvironment, PINISPOOLER pIniSpooler ) { return StrCatAlloc(pDir, pIniSpooler->pDir, L"\\", szPrintProcDir, L"\\", pEnvironment, NULL); } PINIENTRY FindIniKey( PINIENTRY pIniEntry, LPWSTR pName ) { if ( pName == NULL ) { return NULL; } SplInSem(); while ( pIniEntry && lstrcmpi( pName, pIniEntry->pName )) pIniEntry = pIniEntry->pNext; return pIniEntry; } BOOL CreateCompleteDirectory( LPWSTR pDir ) { LPWSTR pBackSlash=pDir; do { pBackSlash = wcschr( pBackSlash, L'\\' ); if ( pBackSlash != NULL ) *pBackSlash = 0; CreateDirectory(pDir, NULL); if ( pBackSlash ) *pBackSlash++=L'\\'; } while ( pBackSlash ); // BUBUG Always returns TRUE return TRUE; } LPCWSTR FindFileName( LPCWSTR pPathName ) /*++ Routine Description: Retrieve the filename portion of a path. This will can the input string until it finds the last backslash, then return the portion of the string immediately following it. If the string terminates with a backslash, then NULL is returned. Note: this can return illegal file names; no validation is done. Arguments: pPathName - Path name to parse. Return Value: Last portion of file name or NULL if none available. --*/ { LPCWSTR pSlash; LPCWSTR pTemp; if( !pPathName ){ return NULL; } pTemp = pPathName; while( pSlash = wcschr( pTemp, L'\\' )) { pTemp = pSlash+1; } if( !*pTemp ){ return NULL; } return pTemp; } VOID CreatePrintProcDirectory( LPWSTR pEnvironment, PINISPOOLER pIniSpooler ) { SIZE_T cb; LPWSTR pEnd; LPWSTR pPathName; cb = wcslen(pIniSpooler->pDir)*sizeof(WCHAR) + wcslen(pEnvironment)*sizeof(WCHAR) + wcslen(szPrintProcDir)*sizeof(WCHAR) + 4*sizeof(WCHAR); if (pPathName=AllocSplMem((DWORD)(cb))) { StringCbCopyEx(pPathName, cb, pIniSpooler->pDir, &pEnd, &cb, 0); if(CreateDirectory(pPathName, NULL) || (GetLastError() == ERROR_ALREADY_EXISTS)) { StringCbCopyEx(pEnd, cb, L"\\", &pEnd, &cb, 0); StringCbCopyEx(pEnd, cb, szPrintProcDir, &pEnd, &cb, 0); if(CreateDirectory(pPathName, NULL) || (GetLastError() == ERROR_ALREADY_EXISTS)) { StringCbCopyEx(pEnd, cb, L"\\", &pEnd, &cb, 0); StringCbCopyEx(pEnd, cb, pEnvironment, &pEnd, &cb, 0); if (CreateDirectory(pPathName, NULL) || (GetLastError() == ERROR_ALREADY_EXISTS)) { } } } FreeSplMem(pPathName); } } BOOL RemoveFromList( PINIENTRY *ppIniHead, PINIENTRY pIniEntry ) { while (*ppIniHead && *ppIniHead != pIniEntry) { ppIniHead = &(*ppIniHead)->pNext; } if (*ppIniHead) *ppIniHead = (*ppIniHead)->pNext; return(TRUE); } PKEYDATA CreateTokenList( LPWSTR pKeyData ) { DWORD cTokens; DWORD cb; PKEYDATA pResult; LPWSTR pDest; LPWSTR psz = pKeyData; LPWSTR *ppToken; if (!psz || !*psz) return NULL; cTokens=1; // Scan through the string looking for commas, // ensuring that each is followed by a non-NULL character: while ((psz = wcschr(psz, L',')) && psz[1]) { cTokens++; psz++; } cb = sizeof(KEYDATA) + (cTokens-1) * sizeof(LPWSTR) + wcslen(pKeyData)*sizeof(WCHAR) + sizeof(WCHAR); if (!(pResult = (PKEYDATA)AllocSplMem(cb))) return NULL; // Initialise pDest to point beyond the token pointers: pDest = (LPWSTR)((LPBYTE)pResult + sizeof(KEYDATA) + (cTokens-1) * sizeof(LPWSTR)); // // Then copy the key data buffer there: // StringCbCopy(pDest, cb - ((BYTE *)pDest - (BYTE *)pResult), pKeyData); ppToken = pResult->pTokens; psz = pDest; do { *ppToken++ = psz; if ( psz = wcschr(psz, L',') ) *psz++ = L'\0'; } while (psz); pResult->cTokens = cTokens; return( pResult ); } VOID FreePortTokenList( PKEYDATA pKeyData ) { PINIPORT pIniPort; DWORD i; if ( pKeyData ) { if ( pKeyData->bFixPortRef ) { for ( i = 0 ; i < pKeyData->cTokens ; ++i ) { pIniPort = (PINIPORT)pKeyData->pTokens[i]; DECPORTREF(pIniPort); } } FreeSplMem(pKeyData); } } VOID GetPrinterPorts( PINIPRINTER pIniPrinter, LPWSTR pszPorts, DWORD *pcbNeeded ) { PINIPORT pIniPort; BOOL Comma; DWORD i; DWORD cbNeeded = 0; DWORD cbAvailable = 0; SPLASSERT(pcbNeeded); cbAvailable = *pcbNeeded; // Determine required size Comma = FALSE; for ( i = 0 ; i < pIniPrinter->cPorts ; ++i ) { pIniPort = pIniPrinter->ppIniPorts[i]; if ( pIniPort->Status & PP_FILE ) continue; if ( Comma ) cbNeeded += wcslen(szComma)*sizeof(WCHAR); cbNeeded += wcslen(pIniPort->pName)*sizeof(WCHAR); Comma = TRUE; } // // Add in size of NULL // cbNeeded += sizeof(WCHAR); if (pszPorts && cbNeeded <= cbAvailable) { // // If we are given a buffer & buffer is big enough, then fill it // Comma = FALSE; for ( i = 0 ; i < pIniPrinter->cPorts ; ++i ) { pIniPort = pIniPrinter->ppIniPorts[i]; if ( pIniPort->Status & PP_FILE ) continue; if ( Comma ) { StringCbCat(pszPorts, cbAvailable, szComma); StringCbCat(pszPorts, cbAvailable, pIniPort->pName); } else { StringCbCopy(pszPorts, cbAvailable, pIniPort->pName); } Comma = TRUE; } } *pcbNeeded = cbNeeded; } BOOL MyName( LPWSTR pName, PINISPOOLER pIniSpooler ) { EnterSplSem(); if (CheckMyName(pName, pIniSpooler)) { LeaveSplSem(); return TRUE; } SetLastError(ERROR_INVALID_NAME); LeaveSplSem(); return FALSE; } BOOL CheckMyName( LPWSTR pName, PINISPOOLER pIniSpooler ) { DWORD dwIndex = 0; if (!pName || !*pName) return TRUE; if (*pName == L'\\' && *(pName+1) == L'\\') { if (!lstrcmpi(pName, pIniSpooler->pMachineName)) { return TRUE; } if (pIniSpooler->pszFullMachineName && !lstrcmpi(pName + 2, pIniSpooler->pszFullMachineName)) { return TRUE; } return CacheIsNameInNodeList(pIniSpooler->pMachineName + 2, pName + 2) == S_OK; } return FALSE; } BOOL GetSid( PHANDLE phToken ) { if (!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_QUERY, TRUE, phToken)) { DBGMSG(DBG_WARNING, ("OpenThreadToken failed: %d\n", GetLastError())); return FALSE; } else return TRUE; } BOOL SetCurrentSid( HANDLE hToken ) { #if DBG WCHAR UserName[256]; DWORD cbUserName=256; if( MODULE_DEBUG & DBG_TRACE ) GetUserName(UserName, &cbUserName); DBGMSG(DBG_TRACE, ("SetCurrentSid BEFORE: user name is %ws\n", UserName)); #endif // // Normally the function SetCurrentSid is not supposed to change the last error // of the routine where it is called. NtSetInformationThread conveniently returns // a status and does not touch the last error. // NtSetInformationThread(NtCurrentThread(), ThreadImpersonationToken, &hToken, sizeof(hToken)); #if DBG cbUserName = 256; if( MODULE_DEBUG & DBG_TRACE ) GetUserName(UserName, &cbUserName); DBGMSG(DBG_TRACE, ("SetCurrentSid AFTER: user name is %ws\n", UserName)); #endif return TRUE; } LPWSTR GetErrorString( DWORD Error ) { WCHAR Buffer1[512]; LPWSTR pErrorString=NULL; DWORD dwFlags; HANDLE hModule = NULL; if ((Error >= NERR_BASE) && (Error <= MAX_NERR)) { dwFlags = FORMAT_MESSAGE_FROM_HMODULE; hModule = LoadLibrary(szNetMsgDll); } else { dwFlags = FORMAT_MESSAGE_FROM_SYSTEM; hModule = NULL; } // // Only display out of paper and device disconnected errors. // if ((Error == ERROR_NOT_READY || Error == ERROR_OUT_OF_PAPER || Error == ERROR_DEVICE_REINITIALIZATION_NEEDED || Error == ERROR_DEVICE_REQUIRES_CLEANING || Error == ERROR_DEVICE_DOOR_OPEN || Error == ERROR_DEVICE_NOT_CONNECTED) && FormatMessage(dwFlags, hModule, Error, 0, Buffer1, COUNTOF(Buffer1), NULL)) { EnterSplSem(); pErrorString = AllocSplStr(Buffer1); LeaveSplSem(); } if (hModule) { FreeLibrary(hModule); } return pErrorString; } #define NULL_TERMINATED 0 INT AnsiToUnicodeString( LPSTR pAnsi, LPWSTR pUnicode, DWORD StringLength ) /*++ Routine Description: Converts an Ansi String to a UnicodeString Arguments: pAnsi - A valid source ANSI string. pUnicode - A pointer to a buffer large enough to accommodate the converted string. StringLength - The length of the source ANSI string. If 0 (NULL_TERMINATED), the string is assumed to be null-terminated. Return Value: The return value from MultiByteToWideChar, the number of wide characters returned. --*/ { if( StringLength == NULL_TERMINATED ) StringLength = strlen( pAnsi ); return MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, pAnsi, StringLength + 1, pUnicode, StringLength + 1 ); } INT Message( HWND hwnd, DWORD Type, int CaptionID, int TextID, ...) { /*++ Routine Description: Displays a message by loading the strings whose IDs are passed into the function, and substituting the supplied variable argument list using the varargs macros. Arguments: hwnd Window Handle Type CaptionID TextId Return Value: --*/ WCHAR MsgText[512]; WCHAR MsgFormat[256]; WCHAR MsgCaption[40]; va_list vargs; if( ( LoadString( hInst, TextID, MsgFormat, sizeof MsgFormat / sizeof *MsgFormat ) > 0 ) && ( LoadString( hInst, CaptionID, MsgCaption, sizeof MsgCaption / sizeof *MsgCaption ) > 0 ) ) { va_start( vargs, TextID ); StringCchVPrintf(MsgText, COUNTOF(MsgText), MsgFormat, vargs ); va_end( vargs ); return MessageBox(hwnd, MsgText, MsgCaption, Type); } else return 0; } typedef struct { DWORD Message; WPARAM wParam; LPARAM lParam; } MESSAGE, *PMESSAGE; // The Broadcasts are done on a separate thread, the reason it CSRSS // will create a server side thread when we call user and we don't want // that to be paired up with the RPC thread which is in the spooss server. // We want it to go away the moment we have completed the SendMessage. // We also call SendNotifyMessage since we don't care if the broadcasts // are syncronous this uses less resources since usually we don't have more // than one broadcast. // // TESTING // DWORD dwSendFormMessage = 0; VOID SplBroadcastChange( HANDLE hPrinter, DWORD Message, WPARAM wParam, LPARAM lParam ) { PSPOOL pSpool = (PSPOOL)hPrinter; PINISPOOLER pIniSpooler; if (ValidateSpoolHandle( pSpool, 0 )) { pIniSpooler = pSpool->pIniSpooler; BroadcastChange(pIniSpooler, Message, wParam, lParam); } } VOID BroadcastChange( IN PINISPOOLER pIniSpooler, IN DWORD Message, IN WPARAM wParam, IN LPARAM lParam ) { if (( pIniSpooler != NULL ) && ( pIniSpooler->SpoolerFlags & SPL_BROADCAST_CHANGE )) { BOOL bIsTerminalServerInstalled = (USER_SHARED_DATA->SuiteMask & (1 << TerminalServer)); // // Currently we cannot determine if the TermService process is running, so at the momemt // we assume it is always running. // BOOL bIsTerminalServerRunning = TRUE; // // If terminal server is installed and enabled then load the winsta.dll if not already // loaded and get the send window message function. // if ( bIsTerminalServerInstalled && !pfWinStationSendWindowMessage ) { // // The winstadllhandle is shared among other files in the spooler, so don't // load the dll again if it is already loaded. Note: we are not in a critical // section because winsta.dll is never unload, hence if there are two threads // that execute this code at the same time we may potenially load the library // twice. // if ( !WinStaDllHandle ) { UINT uOldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS); WinStaDllHandle = LoadLibrary(L"winsta.dll"); SetErrorMode(uOldErrorMode); } if ( WinStaDllHandle ) { pfWinStationSendWindowMessage = (pfnWinStationSendWindowMessage)GetProcAddress( WinStaDllHandle, "WinStationSendWindowMessage" ); } } if ( pfWinStationSendWindowMessage ) { // // Only send the message to the session that orginated // the call, this will go to the console session when a // change is made by a remote client. // LONG Response = 0; LONG lRetval = FALSE; HANDLE hToken = NULL; ULONG uSession= 0; if (GetClientSessionData(&uSession)) { // // It appears the WinStationSendWindowMessage function has to // be in system context if the impersonating user is not an // an admin on the machine. // hToken = RevertToPrinterSelf(); lRetval = pfWinStationSendWindowMessage( SERVERNAME_CURRENT, uSession, 1, // Wait at most one second HandleToULong(HWND_BROADCAST), Message, wParam, lParam, &Response ); ImpersonatePrinterClient(hToken); } } // // We send the message normally if we have a null pfWinstationSendWindowMessage // function or if terminal server is not running. // if ( !pfWinStationSendWindowMessage || !bIsTerminalServerRunning ){ SendNotifyMessage( HWND_BROADCAST, Message, wParam, lParam ); } } else { DBGMSG(DBG_TRACE, ("BroadCastChange Ignoring Change\n")); } } VOID MyMessageBeep( DWORD fuType, PINISPOOLER pIniSpooler ) { if ( pIniSpooler->dwBeepEnabled != 0 ) { MessageBeep(fuType); } } // Recursively delete any subkeys of a given key. // Assumes that RevertToPrinterSelf() has been called. DWORD DeleteSubkeys( HKEY hKey, PINISPOOLER pIniSpooler ) { DWORD cchData; WCHAR SubkeyName[MAX_PATH]; HKEY hSubkey; LONG Status; cchData = COUNTOF( SubkeyName ); while ((Status = SplRegEnumKey( hKey, 0, SubkeyName, &cchData, NULL, pIniSpooler )) == ERROR_SUCCESS ) { Status = SplRegCreateKey( hKey, SubkeyName, 0, KEY_READ | KEY_WRITE, NULL, &hSubkey, NULL, pIniSpooler ); if( Status == ERROR_SUCCESS ) { Status = DeleteSubkeys( hSubkey, pIniSpooler ); SplRegCloseKey( hSubkey, pIniSpooler); if( Status == ERROR_SUCCESS ) SplRegDeleteKey( hKey, SubkeyName, pIniSpooler ); } // // N.B. Don't increment since we've deleted the zeroth item. // cchData = COUNTOF( SubkeyName ); } if( Status == ERROR_NO_MORE_ITEMS ) Status = ERROR_SUCCESS; return Status; } long Myatol(LPWSTR nptr) { int c; // current char long total; // current total int sign; // if '-', then negative, otherwise positive // skip whitespace while (isspace(*nptr)) ++nptr; c = *nptr++; sign = c; // save sign indication if (c == '-' || c == '+') c = *nptr++; // skip sign total = 0; while (isdigit(c)) { total = 10 * total + (c - '0'); // accumulate digit c = *nptr++; // get next char } if (sign == '-') return -total; else return total; // return result, negated if necessary } ULONG_PTR atox( LPCWSTR psz ) /*++ Routine Description: Converts a string to a hex value, skipping any leading white space. Cannot be uppercase, cannot contain leading 0x. Arguments: psz - pointer to hex string that needs to be converted. This string can have leading characters, but MUST be lowercase. Return Value: DWORD value. --*/ { ULONG_PTR Value = 0; ULONG_PTR Add; _wcslwr((LPWSTR)psz); while( isspace( *psz )){ ++psz; } for( ;; ++psz ){ if( *psz >= TEXT( '0' ) && *psz <= TEXT( '9' )){ Add = *psz - TEXT( '0' ); } else if( *psz >= TEXT( 'a' ) && *psz <= TEXT( 'f' )){ Add = *psz - TEXT( 'a' ) + 0xa; } else { break; } Value *= 0x10; Value += Add; } return Value; } BOOL ValidateSpoolHandle( PSPOOL pSpool, DWORD dwDisallowMask ) { BOOL ReturnValue; try { // // Zombied handles should return back error. The client // side will see ERROR_INVALID_HANDLE, close it and revalidate. // if (( pSpool == NULL ) || ( pSpool == INVALID_HANDLE_VALUE ) || ( pSpool->Status & SPOOL_STATUS_ZOMBIE ) || ( pSpool->signature != SJ_SIGNATURE ) || ( pSpool->TypeofHandle & dwDisallowMask ) || ( pSpool->TypeofHandle & PRINTER_HANDLE_XCV_PORT ) || ( pSpool->pIniSpooler->signature != ISP_SIGNATURE ) || ( ( pSpool->TypeofHandle & PRINTER_HANDLE_PRINTER ) && ( pSpool->pIniPrinter->signature !=IP_SIGNATURE ) )) { ReturnValue = FALSE; } else { ReturnValue = TRUE; } }except (1) { ReturnValue = FALSE; } if ( !ReturnValue ) SetLastError( ERROR_INVALID_HANDLE ); return ReturnValue; } BOOL UpdateString( LPWSTR* ppszCur, LPWSTR pszNew) { // // !! LATER !! // // Replace with non-nls wcscmp since we want byte comparison and // only care if the strings are different (ignore ordering). // if ((!*ppszCur || !**ppszCur) && (!pszNew || !*pszNew)) return FALSE; if (!*ppszCur || !pszNew || wcscmp(*ppszCur, pszNew)) { ReallocSplStr(ppszCur, pszNew); return TRUE; } return FALSE; } BOOL CreateDirectoryWithoutImpersonatingUser( LPWSTR pDirectory ) /*++ Routine Description: This routine stops impersonating the user and creates a directory Arguments: pDirectory - Fully Qualified path of directory. Return Value: TRUE - Success FALSE - failed ( call GetLastError ) --*/ { HANDLE hToken = INVALID_HANDLE_VALUE; BOOL bReturnValue; SPLASSERT( pDirectory != NULL ); hToken = RevertToPrinterSelf(); bReturnValue = CreateDirectory(pDirectory, NULL); if ( bReturnValue == FALSE ) { DBGMSG( DBG_WARNING, ("CreateDirectoryWithoutImpersonatingUser failed CreateDirectory %ws error %d\n", pDirectory, GetLastError() )); } if ( hToken != INVALID_HANDLE_VALUE ) { ImpersonatePrinterClient(hToken); } return bReturnValue; } BOOL DeleteAllFilesInDirectory( LPWSTR pDirectory, BOOL bWaitForReboot ) /*++ Routine Description: Deletes all files the specified directory If it can't be deleted it gets marked for deletion on next reboot. Arguments: pDirectory - Fully Qualified path of directory. bWaitForReboot - Don't delete the files until a reboot Return Value: TRUE - Success FALSE - failed something major, like allocating memory. --*/ { BOOL bReturnValue = FALSE; HANDLE hFindFile; WIN32_FIND_DATA FindData; WCHAR ScratchBuffer[ MAX_PATH ]; DBGMSG( DBG_TRACE, ("DeleteAllFilesInDirectory: bWaitForReboot = %\n", bWaitForReboot )); SPLASSERT( pDirectory != NULL ); if (StrNCatBuff(ScratchBuffer, COUNTOF(ScratchBuffer), pDirectory, L"\\*", NULL) != ERROR_SUCCESS) return FALSE; hFindFile = FindFirstFile( ScratchBuffer, &FindData ); if ( hFindFile != INVALID_HANDLE_VALUE ) { do { // // Don't Attempt to Delete Directories // if ( !( FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) { // // Fully Qualified Path // if (StrNCatBuff( ScratchBuffer, COUNTOF(ScratchBuffer), pDirectory, L"\\", FindData.cFileName, NULL) == ERROR_SUCCESS) { if ( bWaitForReboot || !DeleteFile( ScratchBuffer ) ) { DBGMSG( DBG_WARNING, ("DeleteAllFilesInDirectory failed DeleteFile( %ws ) error %d\n", ScratchBuffer, GetLastError() )); if (!MoveFileEx( ScratchBuffer, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) { DBGMSG( DBG_WARNING, ("DeleteAllFilesInDirectory failed MoveFileEx %ws error %d\n", ScratchBuffer, GetLastError() )); } else { DBGMSG( DBG_TRACE, ("MoveFileEx %ws Delay until reboot OK\n", ScratchBuffer )); } } else { DBGMSG( DBG_TRACE, ("Deleted %ws OK\n", ScratchBuffer )); } } } } while( FindNextFile( hFindFile, &FindData ) ); bReturnValue = FindClose( hFindFile ); } else { DBGMSG( DBG_WARNING, ("DeleteOldDrivers failed findfirst ( %ws ), error %d\n", ScratchBuffer, GetLastError() )); } return bReturnValue; } BOOL DeleteAllFilesAndDirectory( LPWSTR pDirectory, BOOL bWaitForReboot ) /*++ Routine Description: Deletes all files the specified directory, then deletes the directory. If the Directory cannot be deleted right away, it is set to be deleted at reboot time. Security NOTE - This routine runs as SYSTEM, not imperonating the user Arguments: pDirectory - Fully Qualified path of directory. Return Value: TRUE - Success FALSE - failed something major, like allocating memory. --*/ { BOOL bReturnValue; HANDLE hToken = INVALID_HANDLE_VALUE; DBGMSG( DBG_TRACE, ("DeleteAllFilesAndDirectory: bWaitForReboot = %d\n", bWaitForReboot )); hToken = RevertToPrinterSelf(); if( bReturnValue = DeleteAllFilesInDirectory( pDirectory, bWaitForReboot ) ) { if ( bWaitForReboot || !RemoveDirectory( pDirectory )) { if (!SplMoveFileEx( pDirectory, NULL, MOVEFILE_DELAY_UNTIL_REBOOT )) { DBGMSG( DBG_WARNING, ("DeleteAllFilesAndDirectory failed to delete %ws until reboot %d\n", pDirectory, GetLastError() )); } else { DBGMSG( DBG_TRACE, ( "DeleteAllFilesAndDirectory: MoveFileEx Delay until reboot OK\n" )); } } else { DBGMSG( DBG_TRACE, ("DeleteAllFilesAndDirectory deleted %ws OK\n", pDirectory )); } } if ( hToken != INVALID_HANDLE_VALUE ) { ImpersonatePrinterClient(hToken); } return bReturnValue; } VOID DeleteDirectoryRecursively( LPCWSTR pszDirectory, BOOL bWaitForReboot ) /*++ Routine Name: DeleteDirectoryRecursively Routine Description: Recursively Deletes the specified directory If it can't be deleted it gets marked for deletion on next reboot. Arguments: pDirectory - Fully Qualified path of directory. bWaitForReboot - Don't delete the files until a reboot Return Value: Nothing. --*/ { HANDLE hFindFile; WIN32_FIND_DATA FindData; WCHAR ScratchBuffer[ MAX_PATH ]; if ( pszDirectory && StrNCatBuff(ScratchBuffer, COUNTOF(ScratchBuffer), pszDirectory, L"\\*", NULL) == ERROR_SUCCESS ) { hFindFile = FindFirstFile(ScratchBuffer, &FindData); if ( hFindFile != INVALID_HANDLE_VALUE ) { do { // // Don't delete current and parent directory. // if (wcscmp(FindData.cFileName, L".") != 0 && wcscmp(FindData.cFileName, L"..") != 0 && StrNCatBuff( ScratchBuffer, COUNTOF(ScratchBuffer), pszDirectory, L"\\", FindData.cFileName, NULL) == ERROR_SUCCESS) { if (!(FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { if (bWaitForReboot || !DeleteFile(ScratchBuffer)) { // // Delete the file on reboot if asked or if deletion failed. // SplMoveFileEx(ScratchBuffer, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); } } else { // // Delete subdirectory // DeleteAllFilesAndDirectory(ScratchBuffer, bWaitForReboot); } } } while (FindNextFile(hFindFile, &FindData)); FindClose(hFindFile); if (bWaitForReboot || !RemoveDirectory(pszDirectory)) { // // Delete the directory on reboot if asked or if deletion failed. // SplMoveFileEx(pszDirectory, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); } } } return; } DWORD CreateNumberedTempDirectory( IN LPCWSTR pszDirectory, OUT LPWSTR *ppszTempDirectory ) /*++ Routine Name: CreateNumberedTempDirectory Routine Description: Creates a temporary subdirectory named 1... 500 The lenght of ppTempDirectory cannot be bigger than MAX_PATH Returns the number of directory created or -1 for failure Arguments: pszDirectory - directory where to created temporary ppszTempDirectory - path of the new temporary directory Return Value: If success, returns the number of directory created. Returns -1 if a failure occurs. --*/ { DWORD dwIndex, dwTempDir; WCHAR szTempDir[4]; WCHAR *pszTemporary = NULL; dwTempDir = -1; if (pszDirectory && ppszTempDirectory) { *ppszTempDirectory = NULL; if (pszTemporary = AllocSplMem((wcslen(pszDirectory) + COUNTOF(szTempDir) + 1) * sizeof(WCHAR))) { for (dwIndex = 1; dwIndex < 500; ++dwIndex) { StringCchPrintf(szTempDir, COUNTOF(szTempDir), L"%d", dwIndex); if (StrNCatBuff(pszTemporary, MAX_PATH, pszDirectory, L"\\", szTempDir, NULL) == ERROR_SUCCESS && !DirectoryExists(pszTemporary) && CreateDirectory(pszTemporary, NULL)) { dwTempDir = dwIndex; break; } } } } if (dwTempDir != -1) { *ppszTempDirectory = pszTemporary; } else { SetLastError(ERROR_NO_SYSTEM_RESOURCES); FreeSplMem(pszTemporary); } return dwTempDir; } int wstrcmpEx( LPCWSTR s1, LPCWSTR s2, BOOL bCaseSensitive ) { if ( s1 && *s1 ) { if ( s2 && *s2 ) { return bCaseSensitive ? wcscmp(s1, s2) : _wcsicmp(s1, s2); } else { return 1; } } else { if ( s2 && *s2 ) { return -1; } else { return 0; } } } BOOL RegSetString( HANDLE hKey, LPWSTR pValueName, LPWSTR pStringValue, PDWORD pdwLastError, PINISPOOLER pIniSpooler ) { BOOL bReturnValue; LPWSTR pString; DWORD cbString; DWORD Status; if ( pStringValue ) { pString = pStringValue; cbString = ( wcslen( pStringValue ) + 1 )*sizeof(WCHAR); } else { pString = szNull; cbString = sizeof(WCHAR); } Status = SplRegSetValue( hKey, pValueName, REG_SZ, (LPBYTE)pString, cbString, pIniSpooler ); if ( Status != ERROR_SUCCESS ) { DBGMSG( DBG_WARNING, ("RegSetString value %ws string %ws error %d\n", pValueName, pString, Status )); *pdwLastError = Status; bReturnValue = FALSE; } else { bReturnValue = TRUE; } return bReturnValue; } BOOL RegSetDWord( HANDLE hKey, LPWSTR pValueName, DWORD dwParam, PDWORD pdwLastError, PINISPOOLER pIniSpooler ) { BOOL bReturnValue; LPWSTR pString; DWORD Status; Status = SplRegSetValue( hKey, pValueName, REG_DWORD, (LPBYTE)&dwParam, sizeof(DWORD), pIniSpooler ); if ( Status != ERROR_SUCCESS ) { DBGMSG( DBG_WARNING, ("RegSetDWord value %ws DWORD %x error %d\n", pValueName, dwParam, Status )); *pdwLastError = Status; bReturnValue = FALSE; } else { bReturnValue = TRUE; } return bReturnValue; } BOOL RegSetBinaryData( HKEY hKey, LPWSTR pValueName, LPBYTE pData, DWORD cbData, PDWORD pdwLastError, PINISPOOLER pIniSpooler ) { DWORD Status; BOOL bReturnValue; Status = SplRegSetValue( hKey, pValueName, REG_BINARY, pData, cbData, pIniSpooler ); if ( Status != ERROR_SUCCESS ) { DBGMSG( DBG_WARNING, ("RegSetBinaryData Value %ws pData %x cbData %d error %d\n", pValueName, pData, cbData, Status )); bReturnValue = FALSE; *pdwLastError = Status; } else { bReturnValue = TRUE; } return bReturnValue; } BOOL RegSetMultiString( HANDLE hKey, LPWSTR pValueName, LPWSTR pStringValue, DWORD cchString, PDWORD pdwLastError, PINISPOOLER pIniSpooler ) { BOOL bReturnValue; DWORD Status; LPWSTR pString; WCHAR szzNull[2]; if ( pStringValue ) { pString = pStringValue; cchString *= sizeof(WCHAR); } else { szzNull[0] = szzNull[1] = '\0'; pString = szNull; cchString = 2 * sizeof(WCHAR); } Status = SplRegSetValue( hKey, pValueName, REG_MULTI_SZ, (LPBYTE)pString, cchString, pIniSpooler ); if ( Status != ERROR_SUCCESS ) { DBGMSG( DBG_WARNING, ("RegSetMultiString value %ws string %ws error %d\n", pValueName, pString, Status )); *pdwLastError = Status; bReturnValue = FALSE; } else { bReturnValue = TRUE; } return bReturnValue; } BOOL RegGetString( HANDLE hKey, LPWSTR pValueName, LPWSTR *ppValue, LPDWORD pcchValue, PDWORD pdwLastError, BOOL bFailIfNotFound, PINISPOOLER pIniSpooler ) /*++ Routine Description: Allocates memory and reads a value from Registry for a value which was earlier set by calling RegSetValueEx. Arguments: hKey : currently open key to be used to query the registry pValueName : value to be used to query the registry ppValue : on return value of TRUE *ppValue (memory allocated by the routine) will have the value pdwLastError : on failure *dwLastError will give the error bFailIfNotFound : Tells if the field is mandatory (if not found error) Return Value: TRUE : value is found and succesfully read. Memory will be allocated to hold the value FALSE: Value was not read. If bFailIfNotFound was TRUE error code will be set. History: Written by MuhuntS (Muhunthan Sivapragasam)June 95 --*/ { BOOL bReturnValue = TRUE; LPWSTR pString; DWORD cbValue; DWORD Status, Type; // // First query to find out size // cbValue = 0; Status = SplRegQueryValue( hKey, pValueName, &Type, NULL, &cbValue, pIniSpooler ); if ( Status != ERROR_SUCCESS ) { // Set error code only if it is a required field if ( bFailIfNotFound ) *pdwLastError = Status; bReturnValue = FALSE; } else if ( (Type == REG_SZ && cbValue > sizeof(WCHAR) ) || (Type == REG_MULTI_SZ && cbValue > 2*sizeof(WCHAR)) ) { // // Something (besides \0 or \0\0) to read // if ( !(*ppValue=AllocSplMem(cbValue) ) ) { *pdwLastError = GetLastError(); bReturnValue = FALSE; } else { Status = SplRegQueryValue( hKey, pValueName, &Type, (LPBYTE)*ppValue, &cbValue, pIniSpooler ); if ( Status != ERROR_SUCCESS ) { DBGMSG( DBG_WARNING, ("RegGetString value %ws string %ws error %d\n", pValueName, **ppValue, Status )); *pdwLastError = Status; bReturnValue = FALSE; } else { *pcchValue = cbValue / sizeof(WCHAR); bReturnValue = TRUE; } } } return bReturnValue; } BOOL RegGetMultiSzString( HANDLE hKey, LPWSTR pValueName, LPWSTR *ppValue, LPDWORD pcchValue, PDWORD pdwLastError, BOOL bFailIfNotFound, PINISPOOLER pIniSpooler ) /*++ Routine Description: Duplicate function for RegGetString. Handles multi-sz strings so that Spooler doesn't crash. Arguments: hKey : currently open key to be used to query the registry pValueName : value to be used to query the registry ppValue : on return value of TRUE *ppValue (memory allocated by the routine) will have the value pdwLastError : on failure *dwLastError will give the error bFailIfNotFound : Tells if the field is mandatory (if not found error) Return Value: TRUE : value is found and succesfully read. Memory will be allocated to hold the value FALSE: Value was not read. If bFailIfNotFound was TRUE error code will be set. History: This function is a fix for the case when 3rd party applications install drivers by writing registry string values instead of multi-sz. This causes Spooler to AV because it will handle a string as a multi-sz string. The goal of having this function was to provide a quick fix/low regression risk for XP RC2 release. A bug was opened for rewriting RegGetMultiSzString and RegGetString in BlackComb timeframe. --*/ { BOOL bReturnValue = TRUE; LPWSTR pString; DWORD cbValue; DWORD Status, Type; // // First query to find out size // cbValue = 0; Status = SplRegQueryValue( hKey, pValueName, &Type, NULL, &cbValue, pIniSpooler ); if ( Status != ERROR_SUCCESS ) { // Set error code only if it is a required field if ( bFailIfNotFound ) *pdwLastError = Status; bReturnValue = FALSE; } else if ( (Type == REG_SZ && cbValue > sizeof(WCHAR) ) || (Type == REG_MULTI_SZ && cbValue > 2*sizeof(WCHAR)) ) { // // Something (besides \0 or \0\0) to read // // // We expect a REG_MULTI_SZ string. Add an extra zero so Spooler doesn't crash. // XP RC2 fix. // if (Type == REG_SZ) { cbValue += sizeof(WCHAR); } if ( !(*ppValue=AllocSplMem(cbValue) ) ) { *pdwLastError = GetLastError(); bReturnValue = FALSE; } else { Status = SplRegQueryValue( hKey, pValueName, &Type, (LPBYTE)*ppValue, &cbValue, pIniSpooler ); if ( Status != ERROR_SUCCESS ) { DBGMSG( DBG_WARNING, ("RegGetString value %ws string %ws error %d\n", pValueName, **ppValue, Status )); *pdwLastError = Status; bReturnValue = FALSE; // // Caller will must the memory regardless of success or failure. // } else { *pcchValue = cbValue / sizeof(WCHAR); bReturnValue = TRUE; } } } return bReturnValue; } VOID FreeStructurePointers( LPBYTE lpStruct, LPBYTE lpStruct2, LPDWORD lpOffsets) /*++ Routine Description: This routine frees memory allocated to all the pointers in the structure If lpStruct2 is specified only pointers in lpStruct which are different than the ones in lpStruct will be freed Arguments: lpStruct: Pointer to the structure lpStruct2: Pointer to the structure to compare with (optional) lpOffsets: An array of DWORDS (terminated by -1) givings offsets in the structure which have memory which needs to be freed Return Value: nothing --*/ { register INT i; if ( lpStruct2 ) { for( i=0; lpOffsets[i] != 0xFFFFFFFF; ++i ) { if ( *(LPBYTE *) (lpStruct+lpOffsets[i]) && *(LPBYTE *) (lpStruct+lpOffsets[i]) != *(LPBYTE *) (lpStruct2+lpOffsets[i]) ) FreeSplMem(*(LPBYTE *) (lpStruct+lpOffsets[i])); } } else { for( i=0; lpOffsets[i] != 0xFFFFFFFF; ++i ) { if ( *(LPBYTE *) (lpStruct+lpOffsets[i]) ) FreeSplMem(*(LPBYTE *) (lpStruct+lpOffsets[i])); } } } /*++ Routine Name: AllocOrUpdateStringAndTestSame Routine Description: This routine can be used to do an atomic update of values in a structure. Create a temporary structure and copy the old structure to it. Then call this routine for all LPWSTR fields to check and update strings If the value changes: This routine will allocate memory and assign pointer in the temporary structure. Arguments: ppString : Points to a pointer in the temporary sturucture pNewValue : New value to be set pOldValue : Value in the original strucutre bCaseSensitive : Determines whether case-sensitive string compare is performed pbFail : On error set this to TRUE (Note: it could already be TRUE) *pbIdentical : If the strings are diferent this is set to FALSE. (Could already be false). Return Value: TRUE on success, else FALSE --*/ BOOL AllocOrUpdateStringAndTestSame( IN LPWSTR *ppString, IN LPCWSTR pNewValue, IN LPCWSTR pOldValue, IN BOOL bCaseSensitive, IN OUT BOOL *pbFail, IN OUT BOOL *pbIdentical ) { BOOL bReturn = TRUE; int iReturn; if ( *pbFail ) return FALSE; if (wstrcmpEx(pNewValue, pOldValue, bCaseSensitive)) { *pbIdentical = FALSE; if ( pNewValue && *pNewValue ) { if ( !(*ppString = AllocSplStr(pNewValue)) ) { *pbFail = TRUE; bReturn = FALSE; } } else { *ppString = NULL; } } return bReturn; } /*++ Routine Name: AllocOrUpdateString Routine Description: This routine can be used to do an atomic update of values in a structure. Create a temporary structure and copy the old structure to it. Then call this routine for all LPWSTR fields to check and update strings If the value changes: This routine will allocate memory and assign pointer in the temporary structure. Arguments: ppString : Points to a pointer in the temporary sturucture pNewValue : New value to be set pOldValue : Value in the original strucutre bCaseSensitive : Determines whether case-sensitive string compare is performed pbFail : On error set this to TRUE (Note: it could already be TRUE) Return Value: TRUE on success, else FALSE --*/ BOOL AllocOrUpdateString( IN LPWSTR *ppString, IN LPCWSTR pNewValue, IN LPCWSTR pOldValue, IN BOOL bCaseSensitive, IN OUT BOOL *pbFail ) { BOOL bIdentical = FALSE; return AllocOrUpdateStringAndTestSame(ppString, pNewValue, pOldValue, bCaseSensitive, pbFail, &bIdentical); } VOID CopyNewOffsets( LPBYTE pStruct, LPBYTE pTempStruct, LPDWORD lpOffsets) /*++ Routine Description: This routine can be used to do an atomic update of values in a structure. Create a temporary structure and allocate memory for values which are being updated in it, and set the remaining pointers to those in the original. This routine is called at the end to update the structure. Arguments: pStruct: Pointer to the structure pTempStruct: Pointer to the temporary structure lpOffsets: An array of DWORDS givings offsets within the stuctures Return Value: nothing --*/ { register INT i; for( i=0; lpOffsets[i] != 0xFFFFFFFF; ++i ) { if ( *(LPBYTE *) (pStruct+lpOffsets[i]) != *(LPBYTE *) (pTempStruct+lpOffsets[i]) ) { if ( *(LPBYTE *) (pStruct+lpOffsets[i]) ) FreeSplMem(*(LPBYTE *) (pStruct+lpOffsets[i])); *(LPBYTE *) (pStruct+lpOffsets[i]) = *(LPBYTE *) (pTempStruct+lpOffsets[i]); } } } DWORD GetIniDriverAndDirForThisMachine( IN PINIPRINTER pIniPrinter, OUT LPWSTR pszDriverDir, OUT PINIDRIVER *ppIniDriver ) /*++ Description: Gets the path to the driver directory for the printer on the local machine Arguments: pIniPrinter - Points to IniPrinter pszDriverDir - A buffer of size MAX_PATH to get the directory path Return Vlaue: Number of characters copied (0 on failure) --*/ { PINIVERSION pIniVersion = NULL; PINIENVIRONMENT pIniEnvironment; PINISPOOLER pIniSpooler = pIniPrinter->pIniSpooler; DWORD dwIndex; EnterSplSem(); // // Find driver file for the given driver and then get it's fullpath // SPLASSERT(pIniPrinter && pIniPrinter->pIniDriver && pIniPrinter->pIniDriver->pName); pIniEnvironment = FindEnvironment(szEnvironment, pIniSpooler); *ppIniDriver = FindCompatibleDriver(pIniEnvironment, &pIniVersion, pIniPrinter->pIniDriver->pName, dwMajorVersion, dwUpgradeFlag); SPLASSERT(*ppIniDriver); dwIndex = GetDriverVersionDirectory(pszDriverDir, MAX_PATH - 2, pIniPrinter->pIniSpooler, pIniEnvironment, pIniVersion, *ppIniDriver, NULL); pszDriverDir[dwIndex++] = L'\\'; pszDriverDir[dwIndex] = L'\0'; LeaveSplSem(); return dwIndex; } LPWSTR GetConfigFilePath( IN PINIPRINTER pIniPrinter ) /*++ Description: Gets the full path to the config file (driver ui file) associated with the driver. Memory is allocated Arguments: pIniPrinter - Points to IniPrinter Return Vlaue: Pointer to the printer name buffer (NULL on error) --*/ { DWORD dwIndex; WCHAR szDriverPath[MAX_PATH + 1]; PWSTR pszConfigFile = NULL; PINIDRIVER pIniDriver; if ( dwIndex = GetIniDriverAndDirForThisMachine(pIniPrinter, szDriverPath, &pIniDriver) ) { if (BoolFromHResult(StringCchCopy(szDriverPath + dwIndex, COUNTOF(szDriverPath) - dwIndex, pIniDriver->pConfigFile))) { pszConfigFile = AllocSplStr(szDriverPath); } } return pszConfigFile; } PDEVMODE ConvertDevModeToSpecifiedVersion( IN PINIPRINTER pIniPrinter, IN PDEVMODE pDevMode, IN LPWSTR pszConfigFile, OPTIONAL IN LPWSTR pszPrinterNameWithToken, OPTIONAL IN BOOL bNt35xVersion ) /*++ Description: Calls driver UI routines to get the default devmode and then converts given devmode to that version. If the input devmode is in IniPrinter routine makes a copy before converting it. This routine needs to be called from inside spooler semaphore Arguments: pIniPrinter - Points to IniPrinter pDevMode - Devmode to convert to current version pConfigFile - Full path to driver UI file to do LoadLibrary (optional) pszPrinterNameWithToken - Name of printer with token (optional) bToNt3xVersion - If TRUE devmode is converted to Nt3x format, else to current version Return Vlaue: Pointer to new devmode on success, NULL on failure --*/ { LPWSTR pszLocalConfigFile = pszConfigFile; LPWSTR pszLocalPrinterNameWithToken = pszPrinterNameWithToken; LPDEVMODE pNewDevMode = NULL, pOldDevMode = NULL; DWORD dwNeeded, dwLastError; LONG lNeeded; HANDLE hDevModeConvert = NULL,hPrinter = NULL; BOOL bCallDocumentProperties = FALSE; SplInSem(); // // If ConfigFile or PrinterNameWithToken is not given allocate it locally // if ( !pszLocalConfigFile ) { pszLocalConfigFile = GetConfigFilePath(pIniPrinter); if ( !pszLocalConfigFile ) goto Cleanup; } if ( !pszLocalPrinterNameWithToken ) { pszLocalPrinterNameWithToken = pszGetPrinterName( pIniPrinter, TRUE, pszLocalOnlyToken ); if ( !pszLocalPrinterNameWithToken ) goto Cleanup; } // // If we are trying to convert pIniPrinter->pDevMode make a copy since we are going to leave SplSem // if ( pDevMode ) { if ( pDevMode == pIniPrinter->pDevMode ) { dwNeeded = pDevMode->dmSize + pDevMode->dmDriverExtra; SPLASSERT(dwNeeded == pIniPrinter->cbDevMode); pOldDevMode = AllocSplMem(dwNeeded); if ( !pOldDevMode ) goto Cleanup; CopyMemory((LPBYTE)pOldDevMode, (LPBYTE)pDevMode, dwNeeded); } else { pOldDevMode = pDevMode; } } // // Driver is going to call OpenPrinter, so leave SplSem // LeaveSplSem(); SplOutSem(); hDevModeConvert = LoadDriverFiletoConvertDevmode(pszLocalConfigFile); if ( !hDevModeConvert ) { // If the function is not exported and 3.5x conversion is not required // the devmode can be got from DocumentProperties if ( bNt35xVersion != NT3X_VERSION ) { bCallDocumentProperties = TRUE; } goto CleanupFromOutsideSplSem; } dwNeeded = 0; if ( bNt35xVersion == NT3X_VERSION ) { // // Call CallDrvDevModeConversion to allocate memory and return 351 devmode // dwLastError = CallDrvDevModeConversion(hDevModeConvert, pszLocalPrinterNameWithToken, (LPBYTE)pOldDevMode, (LPBYTE *)&pNewDevMode, &dwNeeded, CDM_CONVERT351, TRUE); SPLASSERT(dwLastError == ERROR_SUCCESS || !pNewDevMode); } else { // // Call CallDrvDevModeConversion to allocate memory and give default devmode dwLastError = CallDrvDevModeConversion(hDevModeConvert, pszLocalPrinterNameWithToken, NULL, (LPBYTE *)&pNewDevMode, &dwNeeded, CDM_DRIVER_DEFAULT, TRUE); if ( dwLastError != ERROR_SUCCESS ) { SPLASSERT(!pNewDevMode); // Call DocumentProperties to get the default devmode bCallDocumentProperties = TRUE; goto CleanupFromOutsideSplSem; } // // If we have an input devmode to convert to current mode call driver again // if ( pOldDevMode ) { dwLastError = CallDrvDevModeConversion(hDevModeConvert, pszLocalPrinterNameWithToken, (LPBYTE)pOldDevMode, (LPBYTE *)&pNewDevMode, &dwNeeded, CDM_CONVERT, FALSE); // // If call failed free devmode which was allocated by previous call // if ( dwLastError != ERROR_SUCCESS ) { // Call DocumentProperties to get the default devmode bCallDocumentProperties = TRUE; goto CleanupFromOutsideSplSem; } } } CleanupFromOutsideSplSem: if (bCallDocumentProperties) { // Get a client side printer handle to pass to the driver if (!(* pfnOpenPrinter)(pszLocalPrinterNameWithToken, &hPrinter, NULL)) { goto ReEnterSplSem; } if (!pNewDevMode) { // Get the default devmode lNeeded = (* pfnDocumentProperties)(NULL, hPrinter, pszLocalPrinterNameWithToken, NULL, NULL, 0); if (lNeeded <= 0 || !(pNewDevMode = (LPDEVMODEW) AllocSplMem(lNeeded)) || (* pfnDocumentProperties)(NULL, hPrinter, pszLocalPrinterNameWithToken, pNewDevMode, NULL, DM_OUT_BUFFER) < 0) { if (pNewDevMode) { FreeSplMem(pNewDevMode); pNewDevMode = NULL; goto ReEnterSplSem; } } } if (pOldDevMode) { // Convert to Current mode if ((* pfnDocumentProperties)(NULL, hPrinter, pszLocalPrinterNameWithToken, pNewDevMode, pOldDevMode, DM_IN_BUFFER | DM_OUT_BUFFER) < 0) { FreeSplMem(pNewDevMode); pNewDevMode = NULL; goto ReEnterSplSem; } } } ReEnterSplSem: if (hPrinter) { (* pfnClosePrinter)(hPrinter); } SplOutSem(); EnterSplSem(); Cleanup: if ( hDevModeConvert ) UnloadDriverFile(hDevModeConvert); if ( pszLocalConfigFile != pszConfigFile ) FreeSplStr(pszLocalConfigFile); if ( pszPrinterNameWithToken != pszLocalPrinterNameWithToken ) FreeSplStr(pszLocalPrinterNameWithToken); if ( pOldDevMode != pDevMode ) FreeSplMem(pOldDevMode); return pNewDevMode; } BOOL IsPortType( LPWSTR pPort, LPWSTR pPrefix ) { DWORD dwLen; SPLASSERT(pPort && *pPort && pPrefix && *pPrefix); dwLen = wcslen(pPrefix); if ( wcslen(pPort) < dwLen ) { return FALSE; } if ( _wcsnicmp(pPort, pPrefix, dwLen) ) { return FALSE; } // // wcslen guarenteed >= 3 // return pPort[ wcslen( pPort ) - 1 ] == L':'; } LPWSTR AnsiToUnicodeStringWithAlloc( LPSTR pAnsi ) /*++ Description: Convert ANSI string to UNICODE. Routine allocates memory from the heap which should be freed by the caller. Arguments: pAnsi - Points to the ANSI string Return Vlaue: Pointer to UNICODE string --*/ { LPWSTR pUnicode; DWORD rc; rc = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pAnsi, -1, NULL, 0); rc *= sizeof(WCHAR); if ( !rc || !(pUnicode = (LPWSTR) AllocSplMem(rc)) ) return NULL; rc = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pAnsi, -1, pUnicode, rc); if ( rc ) return pUnicode; else { FreeSplMem(pUnicode); return NULL; } } /*++ Routine Name: UnicodeToAnsiString Routine Description: This allocates an ANSI string and converts it using the thread's codepage. Arguments: pszUnicode - The incoming, non-NULL, NULL terminated unicode string. ppszAnsi - The returned ANSI string. Return Value: An HRESULT --*/ HRESULT UnicodeToAnsiString( IN PWSTR pszUnicode, OUT PSTR *ppszAnsi ) { HRESULT hRetval = E_FAIL; PSTR pszAnsi = NULL; INT AnsiStringLength = 0; hRetval = pszUnicode && ppszAnsi ? S_OK : E_INVALIDARG; if (ppszAnsi) { *ppszAnsi = NULL; } if (SUCCEEDED(hRetval)) { AnsiStringLength = WideCharToMultiByte(CP_THREAD_ACP, 0, pszUnicode, -1, NULL, 0, NULL, NULL); hRetval = AnsiStringLength != 0 ? S_OK : GetLastErrorAsHResult(); } if (SUCCEEDED(hRetval)) { pszAnsi = AllocSplMem(AnsiStringLength); hRetval = pszAnsi ? S_OK : E_OUTOFMEMORY; } if (SUCCEEDED(hRetval)) { hRetval = WideCharToMultiByte(CP_THREAD_ACP, 0, pszUnicode, -1, pszAnsi, AnsiStringLength, NULL, NULL) != 0 ? S_OK : GetLastErrorAsHResult(); } if (SUCCEEDED(hRetval)) { *ppszAnsi = pszAnsi; pszAnsi = NULL; } FreeSplMem(pszAnsi); return hRetval; } BOOL SplMonitorIsInstalled( LPWSTR pMonitorName ) { BOOL bRet; EnterSplSem(); bRet = FindMonitor(pMonitorName, pLocalIniSpooler) != NULL; LeaveSplSem(); return bRet; } BOOL PrinterDriverEvent( PINIPRINTER pIniPrinter, INT PrinterEvent, LPARAM lParam, DWORD *pdwReturnedError ) /*++ --*/ { BOOL ReturnValue = FALSE; LPWSTR pPrinterName = NULL; BOOL InSpoolSem = TRUE; SplOutSem(); EnterSplSem(); // // We have to Clone the name string, incase someone does a // rename whilst outside criticalsection. // pPrinterName = pszGetPrinterName( pIniPrinter, TRUE, pszLocalsplOnlyToken); LeaveSplSem(); SplOutSem(); if ( (pIniPrinter->pIniSpooler->SpoolerFlags & SPL_PRINTER_DRIVER_EVENT) && pPrinterName != NULL ) { ReturnValue = SplDriverEvent( pPrinterName, PrinterEvent, lParam, pdwReturnedError ); } FreeSplStr( pPrinterName ); return ReturnValue; } BOOL SplDriverEvent( LPWSTR pName, INT PrinterEvent, LPARAM lParam, DWORD *pdwReturnedError ) { BOOL ReturnValue = FALSE; if ( pfnPrinterEvent != NULL ) { SplOutSem(); SPLASSERT( pName && PrinterEvent ); DBGMSG(DBG_INFO, ("SplDriverEvent %ws %d %x\n", pName, PrinterEvent, lParam)); ReturnValue = (*pfnPrinterEvent)( pName, PrinterEvent, PRINTER_EVENT_FLAG_NO_UI, lParam, pdwReturnedError ); } return ReturnValue; } DWORD OpenPrinterKey( PINIPRINTER pIniPrinter, REGSAM samDesired, HANDLE *phKey, LPCWSTR pKeyName, BOOL bOpen ) /*++ Description: OpenPrinterKey Opens "Printers" and IniPrinter->pName keys, then opens specified subkey "pKeyName" if pKeyName is not NULL This routine needs to be called from inside spooler semaphore Arguments: pIniPrinter - Points to IniPrinter *phPrinterRootKey - Handle to "Printers" key on return *phPrinterKey - Handle to IniPrinter->pName key on return *hKey - Handle to pKeyName key on return pKeyName - Points to SubKey to open Return Value: Success or failure status Author: Steve Wilson (NT) --*/ { LPWSTR pThisKeyName = NULL; LPWSTR pPrinterKeyName = NULL; DWORD cbKeyNameLen = 0; DWORD rc = ERROR_INVALID_FUNCTION; PINISPOOLER pIniSpooler = pIniPrinter->pIniSpooler; SplInSem(); if (!(pPrinterKeyName = SubChar(pIniPrinter->pName, L'\\', L','))) { rc = GetLastError(); goto error; } if (pKeyName && *pKeyName){ rc = StrCatAlloc(&pThisKeyName, pPrinterKeyName, L"\\", pKeyName, NULL); } else { pThisKeyName = pPrinterKeyName; } if (bOpen) { // Open rc = SplRegOpenKey( pIniSpooler->hckPrinters, pThisKeyName, samDesired, phKey, pIniSpooler ); } else { // Create rc = SplRegCreateKey( pIniSpooler->hckPrinters, pThisKeyName, 0, samDesired, NULL, phKey, NULL, pIniSpooler ); } error: if (pThisKeyName != pPrinterKeyName) { FreeSplMem(pThisKeyName); } FreeSplStr(pPrinterKeyName); return rc; } BOOL SplGetDriverDir( HANDLE hIniSpooler, LPWSTR pszDir, LPDWORD pcchDir ) { DWORD cchSize; PINISPOOLER pIniSpooler = (PINISPOOLER)hIniSpooler; SPLASSERT(pIniSpooler && pIniSpooler->signature == ISP_SIGNATURE); cchSize = *pcchDir; *pcchDir = wcslen(pIniSpooler->pDir) + wcslen(szDriverDir) + 2; if ( *pcchDir > cchSize ) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } StringCchPrintf(pszDir, cchSize, L"%ws\\%ws", pIniSpooler->pDir, szDriverDir); return TRUE; } VOID GetRegistryLocation( IN HANDLE hKey, IN LPCWSTR pszPath, OUT PHANDLE phKeyOut, OUT LPCWSTR *ppszPathOut ) /*++ Routine Description: Take a registry path and detect whether it should be absolute (rooted from HKEY_LOCAL_MACHINE), or if it should be branched off of the subkey that is passed in hKey. By convention, if it starts with "\" then it is an absolute path. Otherwise it is relative off hKey. Arguments: hKey - Print hKey pszPath - Path to parse. If the pszPath starts with a backslash, then it is absolute. phKeyOut - New key that should be used. ppszPathOut - New path that should be used. Return Value: --*/ { if( pszPath && ( pszPath[0] == TEXT( '\\' ))){ *phKeyOut = HKEY_LOCAL_MACHINE; *ppszPathOut = &pszPath[1]; return; } *phKeyOut = hKey; *ppszPathOut = pszPath; } PWSTR FixDelim( PCWSTR pszInBuffer, WCHAR wcDelim ) /*++ Routine Description: Removes duplicate delimiters from a set of delimited strings Arguments: pszInBuffer - Input list of comma delimited strings wcDelim - The delimit character Return Value: Returns a fixed string --*/ { PWSTR pszIn, pszOut, pszOutBuffer; BOOL bFoundDelim = TRUE; pszOutBuffer = (PWSTR) AllocSplMem((wcslen(pszInBuffer) + 1)*sizeof(WCHAR)); if (pszOutBuffer) { for(pszOut = pszOutBuffer, pszIn = (PWSTR) pszInBuffer ; *pszIn ; ++pszIn) { if (*pszIn == wcDelim) { if (!bFoundDelim) { bFoundDelim = TRUE; *pszOut++ = *pszIn; } } else { bFoundDelim = FALSE; *pszOut++ = *pszIn; } } // Check for trailing delimiter if (pszOut != pszOutBuffer && *(pszOut - 1) == wcDelim) { *(pszOut - 1) = L'\0'; } *pszOut = L'\0'; } return pszOutBuffer; } PWSTR Array2DelimString( PSTRINGS pStringArray, WCHAR wcDelim ) /*++ Routine Description: Converts a PSTRINGS structure to a set of delimited strings Arguments: pStringArray - Input PSTRINGS structure wcDelim - The delimit character Return Value: Delimited string buffer --*/ { DWORD i, nBytes; PWSTR pszDelimString; WCHAR szDelimString[2]; if (!pStringArray || pStringArray->nElements == 0) return NULL; szDelimString[0] = wcDelim; szDelimString[1] = L'\0'; // Determine memory requirement for (i = nBytes = 0 ; i < pStringArray->nElements ; ++i) { // // allocate extra space for the delimiter // if (pStringArray->ppszString[i]) nBytes += (wcslen(pStringArray->ppszString[i]) + 1)*sizeof (WCHAR); } pszDelimString = (PWSTR) AllocSplMem(nBytes); if (pszDelimString) { for (i = 0 ; i < pStringArray->nElements - 1 ; ++i) { if (pStringArray->ppszString[i]) { StringCbCat(pszDelimString, nBytes, pStringArray->ppszString[i]); StringCbCat(pszDelimString, nBytes, szDelimString); } } if (pStringArray->ppszString[i]) StringCbCat(pszDelimString, nBytes, pStringArray->ppszString[i]); } return pszDelimString; } PSTRINGS ShortNameArray2LongNameArray( PSTRINGS pShortNames ) /*++ Routine Description: Converts a PSTRINGS structure containing short names to a PSTRINGS struct containing the dns equivalents Arguments: pStringArray - Input PSTRINGS structure Return Value: PSTRINGS struct containing the dns equivalents of the input short name PSTRINGS struct. --*/ { PSTRINGS pLongNames; DWORD i; if (!pShortNames) { SetLastError(ERROR_INVALID_PARAMETER); return NULL; } // Allocate LongNameArray pLongNames = AllocStringArray(pShortNames->nElements); if (!pLongNames) return NULL; for (i = 0 ; i < pShortNames->nElements ; ++i) { // GetDNSMachineName may fail, leaving the LongNameArray element empty. This is okay. GetDNSMachineName(pShortNames->ppszString[i], &pLongNames->ppszString[i]); } pLongNames->nElements = pShortNames->nElements; return pLongNames; } PSTRINGS DelimString2Array( PCWSTR pszDelimString, WCHAR wcDelim ) /*++ Routine Description: Converts a delimited string to a PSTRINGS structure Arguments: pszDelimString - Input, delimited strings wcDelim - The delimit character Return Value: PSTRINGS structure --*/ { PWSTR psz, pszDelim; PSTRINGS pStrings = NULL; ULONG i, cChar, nStrings; // // Get number of names // for (psz = (PWSTR) pszDelimString, nStrings = 0 ; psz++ ; psz = wcschr(psz, wcDelim)) ++nStrings; pStrings = AllocStringArray(nStrings); if (!pStrings) goto error; // // Copy delimited string to array // for (i = 0, psz = (PWSTR) pszDelimString ; i < nStrings && psz ; ++i, psz = pszDelim + 1) { pszDelim = wcschr(psz, wcDelim); if (pszDelim) { cChar = (ULONG) (pszDelim - psz) + 1; } else { cChar = wcslen(psz) + 1; } pStrings->ppszString[i] = (PWSTR) AllocSplMem(cChar * sizeof(WCHAR)); if (!pStrings->ppszString[i]) { pStrings->nElements = i; FreeStringArray(pStrings); pStrings = NULL; goto error; } StringCchCopy(pStrings->ppszString[i], cChar, psz); } pStrings->nElements = nStrings; error: return pStrings; } VOID FreeStringArray( PSTRINGS pString ) /*++ Routine Description: Frees a PSTRINGS structure Arguments: pString - PSTRINGS structure to free Return Value: --*/ { DWORD i; if (pString) { for (i = 0 ; i < pString->nElements ; ++i) { if (pString->ppszString[i]) FreeSplMem(pString->ppszString[i]); } FreeSplMem(pString); } } PSTRINGS AllocStringArray( DWORD nStrings ) /*++ Routine Description: Allocates a PSTRINGS structure Arguments: nStrings - number of strings in the structure Return Value: pointer to allocated PSTRINGS structure, if any --*/ { PSTRINGS pStrings; // Allocate the STRINGS struct pStrings = (PSTRINGS) AllocSplMem(sizeof(STRINGS) + (nStrings - 1)*sizeof *pStrings->ppszString); return pStrings; } BOOL SplDeleteFile( LPCTSTR lpFileName ) /*++ Routine Name SplDeleteFile Routine Description: Removes SFP protection and Deletes a file. If the file is protected and I fail to remove protection, the user will get warned with a system pop up. Arguments: lpFileName - file full path requested Return Value: DeleteFile's return value --*/ { HANDLE RpcHandle = INVALID_HANDLE_VALUE; RpcHandle = SfcConnectToServer( NULL ); if( RpcHandle != INVALID_HANDLE_VALUE ){ SfcFileException( RpcHandle, (PWSTR)lpFileName, FILE_ACTION_REMOVED ); SfcClose(RpcHandle); } // // SfcFileException might fail with ERROR_FILE_NOT_FOUND because the file is // not in the protected file list.That's why I call DeleteFile anyway. // return DeleteFile( lpFileName ); } BOOL SplMoveFileEx( LPCTSTR lpExistingFileName, LPCTSTR lpNewFileName, DWORD dwFlags ) /*++ Routine Name SplMoveFileEx Routine Description: Removes SFP protection and move a file; If the file is protected and I fail to remove protection, the user will get warned with a system pop up. Arguments: lpExistingFileName - pointer to the name of the existing file lpNewFileName - pointer to the new name for the file dwFlags - flag that specifies how to move file Return Value: MoveFileEx's return value --*/ { HANDLE RpcHandle = INVALID_HANDLE_VALUE; RpcHandle = SfcConnectToServer( NULL ); if( RpcHandle != INVALID_HANDLE_VALUE ){ SfcFileException( RpcHandle, (PWSTR)lpExistingFileName, FILE_ACTION_REMOVED ); SfcClose(RpcHandle); } // // SfcFileException might fail with ERROR_FILE_NOT_FOUND because the file is // not in the protected file list.That's why I call MoveFileEx anyway. // return MoveFileEx( lpExistingFileName, lpNewFileName, dwFlags ); } DWORD GetDefaultForKMPrintersBlockedPolicy ( ) { DWORD Default = KM_PRINTERS_ARE_BLOCKED; BOOL bIsNTWorkstation; NT_PRODUCT_TYPE NtProductType; // // DEFAULT_KM_PRINTERS_ARE_BLOCKED is "blocked" // if ( RtlGetNtProductType(&NtProductType) ) { bIsNTWorkstation = NtProductType == NtProductWinNt; Default = bIsNTWorkstation ? WKS_DEFAULT_KM_PRINTERS_ARE_BLOCKED : SERVER_DEFAULT_KM_PRINTERS_ARE_BLOCKED; } return Default; } DWORD GetServerInstallTimeOut( ) { HKEY hKey; DWORD dwDummy; DWORD dwTimeOut = DEFAULT_MAX_TIMEOUT; DWORD dwSize = sizeof(dwTimeOut); LPCWSTR cszPrintKey = L"SYSTEM\\CurrentControlSet\\Control\\Print"; LPCWSTR cszTimeOut = L"ServerInstallTimeOut"; if( RegOpenKeyEx(HKEY_LOCAL_MACHINE, cszPrintKey, 0, KEY_READ, &hKey) == ERROR_SUCCESS ) { if(RegQueryValueEx( hKey, cszTimeOut, 0, &dwDummy, (LPBYTE)&dwTimeOut, &dwSize ) != ERROR_SUCCESS) { dwTimeOut = DEFAULT_MAX_TIMEOUT; } RegCloseKey( hKey ); } return dwTimeOut; } ULONG_PTR AlignToRegType( IN ULONG_PTR Data, IN DWORD RegType ) { // // Alings the value if Data to the boundary // dictated by the type of data read from registry. // ULONG_PTR Boundary; switch ( RegType ) { // // Binary data could store any kind of data. The pointer is casted // to LPDWORD or LPBOOL so make sure it is native aligned. // case REG_BINARY: { Boundary = sizeof(ULONG_PTR); } break; case REG_SZ: case REG_EXPAND_SZ: case REG_MULTI_SZ: { Boundary = sizeof(WCHAR); } break; case REG_DWORD: case REG_DWORD_BIG_ENDIAN: { Boundary = sizeof(DWORD32); } break; case REG_QWORD: { Boundary = sizeof(DWORD64); } break; case REG_NONE: default: { Boundary = sizeof(ULONG_PTR); } } return (Data + (Boundary - 1))&~(Boundary - 1); } /*++ Routine Name BuildAclStruct Routine Description: Helper function. Builds a vector of ACEs to allow all access to administrators and system. The caller has to free the pstrName fields Arguments: cElements - number of elements in the array pExplAcc - vector of aces Return Value: WIN32 error code --*/ DWORD BuildAclStruct( IN DWORD cElements, IN OUT EXPLICIT_ACCESS *pExplAcc ) { DWORD dwError = ERROR_INVALID_PARAMETER; if (pExplAcc && cElements==2) { PSID pAdminSid = NULL; PSID pSystemSid = NULL; SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; // // Get SID for the built in system account // dwError = AllocateAndInitializeSid(&NtAuthority, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid) && AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdminSid) ? ERROR_SUCCESS : GetLastError(); if (dwError == ERROR_SUCCESS) { // // Initialize the EXPLICIT_ACCESS with information about administrators // pExplAcc[0].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; pExplAcc[0].Trustee.pMultipleTrustee = NULL; pExplAcc[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; pExplAcc[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; pExplAcc[0].Trustee.ptstrName = (PTSTR)pAdminSid; pExplAcc[0].grfAccessMode = GRANT_ACCESS; pExplAcc[0].grfAccessPermissions = GENERIC_ALL; pExplAcc[0].grfInheritance = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; // // Initialize the EXPLICIT_ACCESS with information about the system // pExplAcc[1].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; pExplAcc[1].Trustee.pMultipleTrustee = NULL; pExplAcc[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; pExplAcc[1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; pExplAcc[1].Trustee.ptstrName = (PTSTR)pSystemSid; pExplAcc[1].grfAccessMode = GRANT_ACCESS; pExplAcc[1].grfAccessPermissions = GENERIC_ALL; pExplAcc[1].grfInheritance = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE; } else { // // Note that we never end up here and have pAdminSid not NULL. However, for the // sake of consisentcy and extensibility we attempt to clean up both strcutures // if (pSystemSid) FreeSid(pSystemSid); if (pAdminSid) FreeSid(pAdminSid); } } return dwError; } /*++ Routine Name CreateProtectedDirectory Routine Description: Creates a directory with full access only to admins and to the system. Contained objects inherit these permissions. Arguments: pszDir - directory name Return Value: WIN32 error code --*/ DWORD CreateProtectedDirectory( IN LPCWSTR pszDir ) { DWORD dwError = ERROR_INVALID_PARAMETER; if (pszDir) { SECURITY_DESCRIPTOR SecDesc; SECURITY_ATTRIBUTES SecAttr; PACL pDacl = NULL; EXPLICIT_ACCESS ExplicitAccessVector[2] = {0}; if ((dwError = InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION) ? ERROR_SUCCESS : GetLastError()) == ERROR_SUCCESS && // // Initialize the ExplicitAccessVector // (dwError = BuildAclStruct(COUNTOF(ExplicitAccessVector), ExplicitAccessVector)) == ERROR_SUCCESS && // // Initialize the DACL // (dwError = SetEntriesInAcl(COUNTOF(ExplicitAccessVector), ExplicitAccessVector, NULL, &pDacl)) == ERROR_SUCCESS && // // Set the DACL in the security descriptor // (dwError = SetSecurityDescriptorDacl(&SecDesc, TRUE, pDacl, FALSE) ? ERROR_SUCCESS : GetLastError()) == ERROR_SUCCESS && // // Check if the security descriptor is valid. Function does not set last error // (dwError = IsValidSecurityDescriptor(&SecDesc) ? ERROR_SUCCESS : ERROR_INVALID_SECURITY_DESCR) == ERROR_SUCCESS) { // // Put the security descriptor in the security attribute // SecAttr.bInheritHandle = FALSE; SecAttr.nLength = sizeof(SecAttr); SecAttr.lpSecurityDescriptor = &SecDesc; dwError = CreateDirectory(pszDir, &SecAttr) ? ERROR_SUCCESS : GetLastError(); } // // The ptstrName here points to a sid obtained via AllocAndInitializeSid // if (ExplicitAccessVector[0].Trustee.ptstrName) { FreeSid(ExplicitAccessVector[0].Trustee.ptstrName); } // // The ptstrName here points to a sid obtained via AllocAndInitializeSid // if (ExplicitAccessVector[1].Trustee.ptstrName) { FreeSid((PSID)ExplicitAccessVector[1].Trustee.ptstrName); } } DBGMSG(DBG_CLUSTER, ("CreateProtectedDirectory returns Win32 error %u\n", dwError)); return dwError; } /*++ Routine Name CopyFileToDirectory Routine Description: Copies a file to a directory. File is fully qualified. The function takes a pszDestDir and up to 3 directories. It will create the dir: pszRoot\pszDir1\pszDir2\pszDir3 and copy the file over there. This is a helper function for installing drivers on clusters. The directory strcuture is created with special privileges. Only the system and administrators have access to it. Arguments: pssDestDirt - destination directory pszDir1 - optional pszDir2 - optional pszdir3 - optional pszFullFileName - qualified file path Return Value: WIN32 error code --*/ DWORD CopyFileToDirectory( IN LPCWSTR pszFullFileName, IN LPCWSTR pszDestDir, IN LPCWSTR pszDir1, IN LPCWSTR pszDir2, IN LPCWSTR pszDir3 ) { DWORD dwError = ERROR_INVALID_PARAMETER; LPWSTR pszFile = NULL; // // Our pszfullFileName must contain at least one "\" // if (pszFullFileName && pszDestDir && (pszFile = wcsrchr(pszFullFileName, L'\\'))) { LPCWSTR ppszArray[] = {pszDir1, pszDir2, pszDir3}; WCHAR szNewPath[MAX_PATH]; DWORD uIndex; DBGMSG(DBG_CLUSTER, ("CopyFileToDirectory\n\tpszFullFile "TSTR"\n\tpszDest "TSTR"\n\tDir1 "TSTR"\n\tDir2 "TSTR"\n\tDir3 "TSTR"\n", pszFullFileName, pszDestDir, pszDir1, pszDir2, pszDir3)); // // Prepare buffer for the loop (initialize to pszDestDir) // Create destination root directory, if not existing // if ((dwError = StrNCatBuff(szNewPath, MAX_PATH, pszDestDir, NULL)) == ERROR_SUCCESS && (DirectoryExists((LPWSTR)pszDestDir) || (dwError = CreateProtectedDirectory(pszDestDir)) == ERROR_SUCCESS)) { for (uIndex = 0; uIndex < COUNTOF(ppszArray) && dwError == ERROR_SUCCESS; uIndex++) { // // Append the first directory to the path and // Create the directory if not existing // if (ppszArray[uIndex] && (dwError = StrNCatBuff(szNewPath, MAX_PATH, szNewPath, L"\\", ppszArray[uIndex], NULL)) == ERROR_SUCCESS && !DirectoryExists(szNewPath) && !CreateDirectoryWithoutImpersonatingUser(szNewPath)) { dwError = GetLastError(); } } // // Create the destination file full name and copy the file // if (dwError == ERROR_SUCCESS && (dwError = StrNCatBuff(szNewPath, MAX_PATH, szNewPath, pszFile, NULL)) == ERROR_SUCCESS) { dwError = CopyFile(pszFullFileName, szNewPath, FALSE) ? ERROR_SUCCESS : GetLastError(); } DBGMSG(DBG_CLUSTER, ("CopyFileToDirectory szNewPath "TSTR"\n", szNewPath)); } } DBGMSG(DBG_CLUSTER, ("CopyFileToDirectory returns Win32 error %u\n", dwError)); return dwError; } /*++ Routine Name PropagateMonitorToCluster Routine Description: For a cluster we keep the following printing resources in the cluster data base: drivers, printers, ports, procs. We can also have cluster aware port monitors. When the spooler initializes those objects, it reads the data from the cluster data base. When we write those objects we pass a handle to a key to some spooler functions. (Ex WriteDriverIni) The handle is either to the local registry or to the cluster database. This procedure is not safe with language monitors. LMs keep data in the registry so you need to supply a handle to a key in the reg. They don't work with clusters. This function will do this: 1) write an association key in the cluster data base. We will have information like (lm name, dll name) (see below where we store this) 2) copy the lm dll to the cluster disk. When we fail over we have all it take to install the lm on the local node if needed. Theoretically this function works for both language and port monitors. But it is useless when applied to port monitors. Arguments: pszName - monitor name pszDllName - dll name of the monitor pszEnvName - envionment string Ex "Windows NT x86" pszEnvDir - the path on disk for the environement Ex w32x86 pIniSpooler - cluster spooler Return Value: WIN32 error code --*/ DWORD PropagateMonitorToCluster( IN LPCWSTR pszName, IN LPCWSTR pszDLLName, IN LPCWSTR pszEnvName, IN LPCWSTR pszEnvDir, IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_INVALID_PARAMETER; HKEY hKeyEnvironments; HKEY hKeyCurrentEnv; HKEY hKeyMonitors; HKEY hKeyCurrentMon; SPLASSERT(pIniSpooler->SpoolerFlags & SPL_PRINT && pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER); if (pszName && pszDLLName && pszEnvName && pszEnvDir) { // // Check if we added an entry for this lang monitor already // The cluster database for the spooler resource looks like: // // Parameters // | // +- Environments // | | // | +- Windows NT x86 // | // +- OtherMonitors // | // +- Foo // | | // | +- Driver = Foo.dll // | // +- Bar // | // +- Driver = Bar.dll // if ((dwError = SplRegCreateKey(pIniSpooler->hckRoot, ipszClusterDatabaseEnvironments, 0, KEY_READ | KEY_WRITE, NULL, &hKeyEnvironments, NULL, pIniSpooler)) == ERROR_SUCCESS) { if ((dwError = SplRegCreateKey(hKeyEnvironments, pszEnvName, 0, KEY_READ | KEY_WRITE, NULL, &hKeyCurrentEnv, NULL, pIniSpooler)) == ERROR_SUCCESS) { if ((dwError = SplRegCreateKey(hKeyCurrentEnv, szClusterNonAwareMonitors, 0, KEY_READ | KEY_WRITE, NULL, &hKeyMonitors, NULL, pIniSpooler)) == ERROR_SUCCESS) { if ((dwError = SplRegCreateKey(hKeyMonitors, pszName, 0, KEY_READ | KEY_WRITE, NULL, &hKeyCurrentMon, NULL, pIniSpooler)) == ERROR_SUCCESS) { DWORD cbNeeded = 0; // // Check if this driver already exists in the database // if ((dwError=SplRegQueryValue(hKeyCurrentMon, L"Driver", NULL, NULL, &cbNeeded, pIniSpooler))==ERROR_MORE_DATA) { DBGMSG(DBG_CLUSTER, ("CopyMonitorToClusterDisks "TSTR" already exists in cluster DB\n", pszName)); } else { if (RegSetString(hKeyCurrentMon, (LPWSTR)L"Driver", (LPWSTR)pszDLLName, &dwError, pIniSpooler)) { // // Copy monitor file to cluster disk // WCHAR szMonitor[MAX_PATH]; WCHAR szDestDir[MAX_PATH]; if (GetSystemDirectory(szMonitor, COUNTOF(szMonitor))) { if ((dwError = StrNCatBuff(szMonitor, COUNTOF(szMonitor), szMonitor, L"\\", pszDLLName, NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szDestDir, COUNTOF(szDestDir), pIniSpooler->pszClusResDriveLetter, L"\\", szClusterDriverRoot, NULL)) == ERROR_SUCCESS) { dwError = CopyFileToDirectory(szMonitor, szDestDir, pszEnvDir, NULL, NULL); } } else { dwError = GetLastError(); } } // // If anything failed, delete the entry from the database // if (dwError != ERROR_SUCCESS) { dwError = SplRegDeleteKey(hKeyMonitors, pszName, pIniSpooler); DBGMSG(DBG_CLUSTER, ("CopyMonitorToClusterDisks Error %u cleaned up cluster DB\n", dwError)); } } SplRegCloseKey(hKeyCurrentMon, pIniSpooler); } SplRegCloseKey(hKeyMonitors, pIniSpooler); } SplRegCloseKey(hKeyCurrentEnv, pIniSpooler); } SplRegCloseKey(hKeyEnvironments, pIniSpooler); } } DBGMSG(DBG_CLUSTER, ("PropagateMonitorToCluster returns Win32 error %u\n", dwError)); return dwError; } /*++ Routine Name InstallMonitorFromCluster Routine Description: For a cluster we keep the following printing resources in the cluster data base: drivers, printers, ports, procs. We can also have cluster aware port monitors. When the spooler initializes those objects, it reads the data from the cluster data base. When we write those objects we pass a handle to a key to some spooler functions. (Ex WriteDriverIni) The handle is either to the local registry or to the cluster database. This procedure is not safe with language monitors. LMs keep data in the registry so you need to supply a handle to a key in the reg. They don't work with clusters. This function will do this: 1) read an association key in the cluster data base. We will have information like (lm name, dll name) (see below where we store this) 2) copy the lm dll from the cluster disk to the local disk. 3) install the monitor with the local spooler Theoretically this function works for both language and port monitors. But it is useless when applied to port monitors. Arguments: pszName - monitor name pszEnvName - envionment string Ex "Windows NT x86" pszEnvDir - the path on disk for the environement Ex w32x86 pIniSpooler - cluster spooler Return Value: WIN32 error code --*/ DWORD InstallMonitorFromCluster( IN LPCWSTR pszName, IN LPCWSTR pszEnvName, IN LPCWSTR pszEnvDir, IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_INVALID_PARAMETER; HKEY hKeyParent; HKEY hKeyMon; SPLASSERT(pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER); if (pszName && pszEnvName && pszEnvDir) { HKEY hKeyEnvironments; HKEY hKeyCurrentEnv; HKEY hKeyMonitors; HKEY hKeyCurrentMon; // // Check if we added an entry for this lang monitor already // The cluster database for the spooler resource looks like: // // Parameters // | // +- Environments // | | // | +- Windows NT x86 // | // +- OtherMonitors // | // +- Foo // | | // | +- Driver = Foo.dll // | // +- Bar // | // +- Driver = Bar.dll // if ((dwError = SplRegOpenKey(pIniSpooler->hckRoot, ipszClusterDatabaseEnvironments, KEY_READ, &hKeyEnvironments, pIniSpooler)) == ERROR_SUCCESS) { if ((dwError = SplRegOpenKey(hKeyEnvironments, pszEnvName, KEY_READ, &hKeyCurrentEnv, pIniSpooler)) == ERROR_SUCCESS) { if ((dwError = SplRegOpenKey(hKeyCurrentEnv, szClusterNonAwareMonitors, KEY_READ, &hKeyMonitors, pIniSpooler)) == ERROR_SUCCESS) { if ((dwError = SplRegOpenKey(hKeyMonitors, pszName, KEY_READ, &hKeyCurrentMon, pIniSpooler)) == ERROR_SUCCESS) { LPWSTR pszDLLName = NULL; DWORD cchDLLName = 0; if (RegGetString(hKeyCurrentMon, (LPWSTR)L"Driver", &pszDLLName, &cchDLLName, &dwError, TRUE, pIniSpooler)) { // // We found the monitor entry in the cluster DB // WCHAR szSource[MAX_PATH]; WCHAR szDest[MAX_PATH]; if (GetSystemDirectory(szDest, COUNTOF(szDest))) { if ((dwError = StrNCatBuff(szDest, COUNTOF(szDest), szDest, L"\\", pszDLLName, NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szSource, COUNTOF(szSource), pIniSpooler->pszClusResDriveLetter, L"\\", szClusterDriverRoot, L"\\", pszEnvDir, L"\\", pszDLLName, NULL)) == ERROR_SUCCESS) { // // Copy file from K:\PrinterDrivers\W32x86\foo.dll to // WINDIR\system32\foo.dll // if (CopyFile(szSource, szDest, FALSE)) { MONITOR_INFO_2 Monitor; Monitor.pDLLName = pszDLLName; Monitor.pName = (LPWSTR)pszName; Monitor.pEnvironment = (LPWSTR)pszEnvName; DBGMSG(DBG_CLUSTER, ("InstallMonitorFromCluster "TSTR" copied\n", pszDLLName)); // // Call AddMonitor to the local spooler // if (!SplAddMonitor(NULL, 2, (LPBYTE)&Monitor, pLocalIniSpooler)) { dwError = GetLastError(); } } else { dwError = GetLastError(); } } } else { dwError = GetLastError(); } } SplRegCloseKey(hKeyCurrentMon, pIniSpooler); } SplRegCloseKey(hKeyMonitors, pIniSpooler); } SplRegCloseKey(hKeyCurrentEnv, pIniSpooler); } SplRegCloseKey(hKeyEnvironments, pIniSpooler); } } DBGMSG(DBG_CLUSTER, ("InstallMonitorFromCluster returns Win32 error %u\n", dwError)); return dwError; } /*++ Routine Name CopyNewerOrOlderFiles Routine Description: Copies all newer or older files from the source directory to the dest dir. If you supply a bool function that takes 2 parameters, it will apply that function for each copied file. func(NULL, file.) This is useful when I have to caopy over ICM profiles. Then I can resuse this function and have it install those profiles as it copies them. Arguments: pszSourceDir - source directory string pszDestDir - destination directory string pfn - optional functin to be applied on each copied file Return Value: WIN32 error code --*/ DWORD CopyNewerOrOlderFiles( IN LPCWSTR pszSourceDir, IN LPCWSTR pszDestDir, IN BOOL (WINAPI *pfn)(LPWSTR, LPWSTR) ) { DWORD dwError = ERROR_INVALID_PARAMETER; if (pszSourceDir && pszDestDir) { WCHAR szSearchPath[MAX_PATH]; // // Build the search path. We look for all files // if ((dwError = StrNCatBuff(szSearchPath, COUNTOF(szSearchPath), pszSourceDir, L"\\*", NULL)) == ERROR_SUCCESS) { WIN32_FIND_DATA SourceFindData; HANDLE hSourceFind; // // Find first file that meets the criteria // if ((hSourceFind = FindFirstFile(szSearchPath, &SourceFindData)) != INVALID_HANDLE_VALUE) { do { WCHAR szMasterPath[MAX_PATH]; // // Search for the rest of the files. We are interested in files that are not directories // if (!(SourceFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (dwError = StrNCatBuff(szMasterPath, COUNTOF(szMasterPath), pszDestDir, L"\\", SourceFindData.cFileName, NULL)) == ERROR_SUCCESS) { WIN32_FIND_DATA MasterFindData; HANDLE hMasterFind; BOOL bCopyFile = TRUE; WCHAR szFile[MAX_PATH]; // // Check if the file found in source dir exists in the dest dir // if ((hMasterFind = FindFirstFile(szMasterPath, &MasterFindData)) != INVALID_HANDLE_VALUE) { // // Do not copy file if source and dest have same time stamp // if (!CompareFileTime(&SourceFindData.ftLastWriteTime, &MasterFindData.ftLastWriteTime)) { bCopyFile = FALSE; } FindClose(hMasterFind); } // // File either not found in dest dir, or it has a different timp stamp // if (bCopyFile && (dwError = StrNCatBuff(szFile, COUNTOF(szFile), pszSourceDir, L"\\", SourceFindData.cFileName, NULL)) == ERROR_SUCCESS && (dwError = CopyFile(szFile, szMasterPath, FALSE) ? ERROR_SUCCESS : GetLastError()) == ERROR_SUCCESS && pfn) { dwError = (*pfn)(NULL, szFile) ? ERROR_SUCCESS : GetLastError(); } } } while (dwError == ERROR_SUCCESS && FindNextFile(hSourceFind, &SourceFindData)); FindClose(hSourceFind); } else if ((dwError = GetLastError()) == ERROR_PATH_NOT_FOUND || dwError == ERROR_FILE_NOT_FOUND) { // // No directory or files, success // dwError = ERROR_SUCCESS; } } } DBGMSG(DBG_CLUSTER, ("CopyNewerOrOlderFiles returns Win32 error %u\n", dwError)); return dwError; } /*++ Routine Name CopyICMFromClusterDiskToLocalDisk Routine Description: Copies all newer or older files from the source directory to the destination directory. The source directory is the ICM directory on the cluster disk and the destination is the ICM directory on the local machine for the cluster spooler. This function will also install the icm profiles with the local machine/ Arguments: pIniSpooler - pointer to cluster spooler structure Return Value: WIN32 error code --*/ DWORD CopyICMFromClusterDiskToLocalDisk( IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_SUCCESS; WCHAR szSource[MAX_PATH]; WCHAR szDest[MAX_PATH]; SPLASSERT(pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER); if ((dwError = StrNCatBuff(szDest, COUNTOF(szDest), pIniSpooler->pDir, L"\\Drivers\\Color", NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szSource, COUNTOF(szSource), pIniSpooler->pszClusResDriveLetter, L"\\", szClusterDriverRoot, L"\\", L"Color", NULL)) == ERROR_SUCCESS) { HMODULE hLib; typedef BOOL (WINAPI *PFN)(LPWSTR, LPWSTR); PFN pfn; // // Make sure the directory on the local disk exists. We will copy files // from K:\Printerdrivers\Color to // WINDIR\system32\spool\drivers\clus-spl-guid\drivers\color // CreateCompleteDirectory(szDest); if ((hLib = LoadLibrary(L"mscms.dll")) && (pfn = (PFN)GetProcAddress(hLib, "InstallColorProfileW"))) { dwError = CopyNewerOrOlderFiles(szSource, szDest, pfn); } else { dwError = GetLastError(); } if (hLib) { FreeLibrary(hLib); } DBGMSG(DBG_CLUSTER, ("CopyICMFromClusterDiskToLocalDisk "TSTR" "TSTR" Error %u\n", szSource, szDest, dwError)); } return dwError; } /*++ Routine Name CopyICMFromLocalDiskToClusterDisk Routine Description: Copies all newer or older files from the source directory to the destination directory. The source directory is the ICM directory on the local machine for the cluster spooler. The destination is the ICM directory on the cluster disk Arguments: pIniSpooler - pointer to cluster spooler structure Return Value: WIN32 error code --*/ DWORD CopyICMFromLocalDiskToClusterDisk( IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_SUCCESS; WCHAR szSource[MAX_PATH]; WCHAR szDest[MAX_PATH]; SPLASSERT(pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER); if ((dwError = StrNCatBuff(szSource, COUNTOF(szSource), pIniSpooler->pDir, L"\\Drivers\\Color", NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szDest, COUNTOF(szDest), pIniSpooler->pszClusResDriveLetter, L"\\", szClusterDriverRoot, L"\\", L"Color", NULL)) == ERROR_SUCCESS && // // Make sure the destination on the cluster disk exists. We need to create // it with special access rights. (only admins and system can read/write) // ((dwError = CreateProtectedDirectory(szDest)) == ERROR_SUCCESS || dwError == ERROR_ALREADY_EXISTS)) { dwError = CopyNewerOrOlderFiles(szSource, szDest, NULL); DBGMSG(DBG_CLUSTER, ("CopyICMFromLocalDiskToClusterDisk "TSTR" "TSTR" Error %u\n", szSource, szDest, dwError)); } return dwError; } /*++ Routine Name CreateClusterSpoolerEnvironmentsStructure Routine Description: A pIniSpooler needs a list of all possible pIniEnvironemnts. For the local spooler the setup creates the necessary environments keys in the registry under HKLM\System\CCS\Control\Print\Environments. We need to propagate the same structure for each cluster spooler in the cluster data base. Relies on the fact that pLocalIniSpooler is initialized fisrt (among all pinispoolers) This function builds the following strucutre in the cluster database Parameters | +- Environments | | | +- Windows NT x86 | | (Directory = w32x86) | | | +- Windows 4.0 | | (Directory = win40) | | Arguments: pIniSpooler - pointer to cluster spooler structure Return Value: WIN32 error code --*/ DWORD CreateClusterSpoolerEnvironmentsStructure( IN PINISPOOLER pIniSpooler ) { HKEY hEnvironmentsKey; DWORD dwError; SPLASSERT(pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER); if ((dwError = SplRegCreateKey(pIniSpooler->hckRoot, pIniSpooler->pszRegistryEnvironments, 0, KEY_WRITE, NULL, &hEnvironmentsKey, NULL, pIniSpooler)) == ERROR_SUCCESS) { PINIENVIRONMENT pIniEnvironment; // // Loop through the environments of the local spooler // for (pIniEnvironment = pLocalIniSpooler->pIniEnvironment; pIniEnvironment && dwError == ERROR_SUCCESS; pIniEnvironment = pIniEnvironment->pNext) { HKEY hKeyCurrentEnv; if ((dwError = SplRegCreateKey(hEnvironmentsKey, pIniEnvironment->pName, 0, KEY_WRITE, NULL, &hKeyCurrentEnv, NULL, pIniSpooler)) == ERROR_SUCCESS) { HKEY hKeyPrtProc; // // Set the value Directory (ex. = W32X86) and create // the print processor key // if (RegSetString(hKeyCurrentEnv, szDirectory, pIniEnvironment->pDirectory, &dwError, pIniSpooler) && (dwError = SplRegCreateKey(hKeyCurrentEnv, szPrintProcKey, 0, KEY_WRITE, NULL, &hKeyPrtProc, NULL, pIniSpooler)) == ERROR_SUCCESS) { SplRegCloseKey(hKeyPrtProc, pIniSpooler); } SplRegCloseKey(hKeyCurrentEnv, pIniSpooler); } } SplRegCloseKey(hEnvironmentsKey, pIniSpooler); } DBGMSG(DBG_CLUSTER, ("CreateClusterSpoolerEnvironmentsStructure returns dwError %u\n\n", dwError)); return dwError; } /*++ Routine Name AddLocalDriverToClusterSpooler Routine Description: Adds a driver that exists on the local inispooler to the cluster spooler. It will also add all versions of that driver. We use this function in the upgrade scenario. For a certain printer, we need to propage the driver (and all the versions of that driver) to the cluster data base and cluster disk. Arguments: pIniSpooler - pointer to cluster spooler structure Return Value: WIN32 error code --*/ DWORD AddLocalDriverToClusterSpooler( IN LPCWSTR pszDriver, IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_SUCCESS; PINIENVIRONMENT pIniEnv; PINIVERSION pIniVer; SplInSem(); // // Traverse all environments and versions // for (pIniEnv=pLocalIniSpooler->pIniEnvironment; pIniEnv; pIniEnv=pIniEnv->pNext) { for (pIniVer=pIniEnv->pIniVersion; pIniVer; pIniVer=pIniVer->pNext) { PINIDRIVER pIniDriver = (PINIDRIVER)FindIniKey((PINIENTRY)pIniVer->pIniDriver, (LPWSTR)pszDriver); if (pIniDriver) { DRIVER_INFO_6 DriverInfo = {0}; WCHAR szDriverFile[MAX_PATH]; WCHAR szDataFile[MAX_PATH]; WCHAR szConfigFile[MAX_PATH]; WCHAR szHelpFile[MAX_PATH]; WCHAR szPrefix[MAX_PATH]; LPWSTR pszzDependentFiles = NULL; // // Get fully qualified driver file paths. We will call add printer // driver without using the scratch directory // if ((dwError = StrNCatBuff(szDriverFile, COUNTOF(szDriverFile), pLocalIniSpooler->pDir, szDriversDirectory, L"\\", pIniEnv->pDirectory, L"\\", pIniVer->szDirectory, L"\\", pIniDriver->pDriverFile, NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szDataFile, COUNTOF(szDataFile), pLocalIniSpooler->pDir, szDriversDirectory, L"\\", pIniEnv->pDirectory, L"\\", pIniVer->szDirectory, L"\\", pIniDriver->pDataFile, NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szConfigFile, COUNTOF(szConfigFile), pLocalIniSpooler->pDir, szDriversDirectory, L"\\", pIniEnv->pDirectory, L"\\", pIniVer->szDirectory, L"\\", pIniDriver->pConfigFile, NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szHelpFile, COUNTOF(szHelpFile), pLocalIniSpooler->pDir, szDriversDirectory, L"\\", pIniEnv->pDirectory, L"\\", pIniVer->szDirectory, L"\\", pIniDriver->pHelpFile, NULL)) == ERROR_SUCCESS && (dwError = StrNCatBuff(szPrefix, COUNTOF(szPrefix), pLocalIniSpooler->pDir, szDriversDirectory, L"\\", pIniEnv->pDirectory, L"\\", pIniVer->szDirectory, L"\\", NULL)) == ERROR_SUCCESS && (dwError = StrCatPrefixMsz(szPrefix, pIniDriver->pDependentFiles, &pszzDependentFiles)) == ERROR_SUCCESS) { DBGMSG(DBG_CLUSTER, ("AddLocalDrv szDriverFile "TSTR"\n", szDriverFile)); DBGMSG(DBG_CLUSTER, ("AddLocalDrv szDataFile "TSTR"\n", szDataFile)); DBGMSG(DBG_CLUSTER, ("AddLocalDrv szConfigFile "TSTR"\n", szConfigFile)); DBGMSG(DBG_CLUSTER, ("AddLocalDrv szHelpFile "TSTR"\n", szHelpFile)); DBGMSG(DBG_CLUSTER, ("AddLocalDrv szPrefix "TSTR"\n", szPrefix)); DriverInfo.pDriverPath = szDriverFile; DriverInfo.pName = pIniDriver->pName; DriverInfo.pEnvironment = pIniEnv->pName; DriverInfo.pDataFile = szDataFile; DriverInfo.pConfigFile = szConfigFile; DriverInfo.cVersion = pIniDriver->cVersion; DriverInfo.pHelpFile = szHelpFile; DriverInfo.pMonitorName = pIniDriver->pMonitorName; DriverInfo.pDefaultDataType = pIniDriver->pDefaultDataType; DriverInfo.pDependentFiles = pszzDependentFiles; DriverInfo.pszzPreviousNames = pIniDriver->pszzPreviousNames; DriverInfo.pszMfgName = pIniDriver->pszMfgName; DriverInfo.pszOEMUrl = pIniDriver->pszOEMUrl; DriverInfo.pszHardwareID = pIniDriver->pszHardwareID; DriverInfo.pszProvider = pIniDriver->pszProvider; DriverInfo.dwlDriverVersion = pIniDriver->dwlDriverVersion; DriverInfo.ftDriverDate = pIniDriver->ftDriverDate; LeaveSplSem(); if (!SplAddPrinterDriverEx(NULL, 6, (LPBYTE)&DriverInfo, APD_COPY_NEW_FILES, pIniSpooler, FALSE, DO_NOT_IMPERSONATE_USER)) { dwError = GetLastError(); } EnterSplSem(); } FreeSplMem(pszzDependentFiles); DBGMSG(DBG_CLUSTER, ("AddLocalDrv Env "TSTR" Ver "TSTR" Name "TSTR" Error %u\n", pIniEnv->pName, pIniVer->pName, pszDriver, dwError)); } } } return dwError; } /*++ Routine Name StrCatPerfixMsz Routine Description: Take a prefix which is a string Ex "C:\windows\" and a multi sz Ex: "a0b00" It will create: c:\windows\a0c:\windows\b00 The prefix must have a trailing "\". Arguments: pszPrefix - string to prefix all the strings in the msz pszzFiles - msz of files ppszzFullPathFiles - out param Return Value: WIN32 error code --*/ DWORD StrCatPrefixMsz( IN LPCWSTR pszPrefix, IN LPWSTR pszzFiles, OUT LPWSTR *ppszzFullPathFiles ) { DWORD dwError = ERROR_INVALID_PARAMETER; if (pszPrefix && ppszzFullPathFiles) { *ppszzFullPathFiles = NULL; if (pszzFiles) { WCHAR szNewPath[MAX_PATH] = {0}; LPWSTR psz; LPWSTR pszReturn; LPWSTR pszTemp; DWORD cbNeeded = 0; SIZE_T cchStrings = 0; DWORD dwPrifxLen = wcslen(pszPrefix); // // We count the number of character of the string // that we need to allocate // for (psz = pszzFiles; psz && *psz;) { DWORD dwLen = wcslen(psz); cbNeeded += dwPrifxLen + dwLen + 1; psz += dwLen + 1; } // // Count the number of strings needed to do the string cat, not // counting the null (since we will always append it but allocate // one more). // cchStrings = cbNeeded; // // Final \0 of the multi sz // cbNeeded++; // // Convert to number of bytes // cbNeeded *= sizeof(WCHAR); if (pszReturn = AllocSplMem(cbNeeded)) { for (psz = pszzFiles, pszTemp = pszReturn; psz && *psz; ) { StringCchCopyEx(pszTemp, cchStrings, pszPrefix, &pszTemp, &cchStrings, 0); StrCchCopyMultipleStr(pszTemp, cchStrings, psz, &pszTemp, &cchStrings); psz += wcslen(psz) + 1; } // // Outgoing, we have preallocated this final NULL. // pszTemp = L'\0'; // // Set out param // *ppszzFullPathFiles = pszReturn; dwError = ERROR_SUCCESS; } else { dwError = GetLastError(); } } else { // // NULL input multi sz, nothing to do // dwError = ERROR_SUCCESS; } } DBGMSG(DBG_CLUSTER, ("StrCatPerfixMsz returns %u\n", dwError)); return dwError; } /*++ Routine Name ClusterSplReadUpgradeKey Routine Description: After the first reboot following an upgrade of a node, the cluster service informs the resdll that a version change occured. At this time out spooler resource may be running on another node or may not be actie at all. Thus the resdll writes a value in the local registry. The vaue name is the GUID for the spooler resource, the value is DWORD 1. When the cluster spooler resource fails over on this machine it (i.e. now) it queries for that value to know if it needs to preform post upgrade operations, like upgrading the printer drivers. Arguments: pszResource - string respresenation of GUID for the cluster resource pdwVlaue - will contain the value in the registry for the GUID Return Value: WIN32 error code --*/ DWORD ClusterSplReadUpgradeKey( IN LPCWSTR pszResourceID, OUT LPDWORD pdwValue ) { DWORD dwError = ERROR_INVALID_PARAMETER; HKEY hkRoot = NULL; HKEY hkUpgrade = NULL; if (pszResourceID && pdwValue) { *pdwValue = 0; if ((dwError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, SPLREG_CLUSTER_LOCAL_ROOT_KEY, 0, KEY_READ, &hkRoot)) == ERROR_SUCCESS && (dwError = RegOpenKeyEx(hkRoot, SPLREG_CLUSTER_UPGRADE_KEY, 0, KEY_READ, &hkUpgrade)) == ERROR_SUCCESS) { DWORD cbNeeded = sizeof(DWORD); dwError = RegQueryValueEx(hkUpgrade, pszResourceID, NULL, NULL, (LPBYTE)pdwValue, &cbNeeded); } if (hkUpgrade) RegCloseKey(hkUpgrade); if (hkRoot) RegCloseKey(hkRoot); // // Regardless of what happened, return success // dwError = ERROR_SUCCESS; } return dwError; } /*++ Routine Name ClusterSplReadUpgradeKey Routine Description: After the first reboot following an upgrade of a node, the cluster service informs the resdll that a version change occured. At this time out spooler resource may be running on another node or may not be actie at all. Thus the resdll writes a value in the local registry. The vaue name is the GUID for the spooler resource, the value is DWORD 1. When the cluster spooler resource fails over on this machine it (i.e. now) it queries for that value to know if it needs to preform post upgrade operations, like upgrading the printer drivers. After the spooler preforms upgrade taks, it will delete the value corresponding to its GUID. Also if that value is the only one under the SPLREG_CLUSTER_UPGRADE_KEY key, it will delete that key. Arguments: pszResource - string respresenation of GUID for the cluster resource Return Value: WIN32 error code --*/ DWORD ClusterSplDeleteUpgradeKey( IN LPCWSTR pszResourceID ) { DWORD dwError = ERROR_INVALID_PARAMETER; HKEY hkRoot = NULL; HKEY hkUpgrade = NULL; if ((dwError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, SPLREG_CLUSTER_LOCAL_ROOT_KEY, 0, KEY_READ, &hkRoot)) == ERROR_SUCCESS && (dwError = RegOpenKeyEx(hkRoot, SPLREG_CLUSTER_UPGRADE_KEY, 0, KEY_READ | KEY_WRITE, &hkUpgrade)) == ERROR_SUCCESS) { DWORD cValues = 0; dwError = RegDeleteValue(hkUpgrade, pszResourceID); if (RegQueryInfoKey(hkUpgrade, NULL, NULL, NULL, NULL, NULL, NULL, &cValues, NULL, NULL, NULL, NULL) == ERROR_SUCCESS && !cValues) { RegDeleteKey(hkRoot, SPLREG_CLUSTER_UPGRADE_KEY); } if (hkUpgrade) RegCloseKey(hkUpgrade); if (hkRoot) RegCloseKey(hkRoot); } return dwError; } /*++ Routine Name RunProcess Routine Description: Creates a process. Waits for it to terminate. Arguments: pszExe - program to execute (muist be fully qualfied) pszCommand - command line to execute dwTimeOut - time to wait for the process to terminate pszExitCode - pointer to reveice exit code of process Return Value: WIN32 error code --*/ DWORD RunProcess( IN LPCWSTR pszExe, IN LPCWSTR pszCommand, IN DWORD dwTimeOut, OUT LPDWORD pdwExitCode OPTIONAL ) { DWORD dwError = ERROR_INVALID_PARAMETER; if (pszCommand && pszExe) { HANDLE hToken = RevertToPrinterSelf(); if (hToken) { PROCESS_INFORMATION ProcInfo = {0}; STARTUPINFO StartInfo = {0}; StartInfo.cb = sizeof(StartInfo); StartInfo.dwFlags = 0; if (!CreateProcess(pszExe, (LPWSTR)pszCommand, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &StartInfo, &ProcInfo)) { dwError = GetLastError(); } else { if (WaitForSingleObject(ProcInfo.hProcess, dwTimeOut) == WAIT_OBJECT_0) { // // Process executed fine // dwError = ERROR_SUCCESS; } if (pdwExitCode && !GetExitCodeProcess(ProcInfo.hProcess, pdwExitCode)) { *pdwExitCode = 0; } CloseHandle(ProcInfo.hThread); CloseHandle(ProcInfo.hProcess); } if (!ImpersonatePrinterClient(hToken)) { dwError = GetLastError(); } } else { dwError = GetLastError(); } } return dwError; } /*++ Routine Name GetLocalArchEnv Routine Description: Helper function. Returns a pointer to the environment that matches the architecture of the local machine. The environemnt is taken off the pInSpooler passed as argument Arguments: pIniSpooler - pointer to spooler structure Return Value: PINIENVIRONMENT --*/ PINIENVIRONMENT GetLocalArchEnv( IN PINISPOOLER pIniSpooler ) { SplInSem(); // // The local spooler and cluster spooler do not share the same Environment structures. // return pIniSpooler && pIniSpooler->SpoolerFlags & SPL_TYPE_CLUSTER ? FindEnvironment(szEnvironment, pIniSpooler) : pThisEnvironment; } /*++ Routine Name ClusterFindLanguageMonitor Routine Description: If a valid monitor name is specified and the monitor is not found in the specified pIniSpooler, then the function will try to install the monitor from the cluster disk. Arguments: pszMonitor - monitor name pszEnvName - name of environment of the lm pIniSpooler - pointer to cluster spooler structure Return Value: Win32 error code --*/ DWORD ClusterFindLanguageMonitor( IN LPCWSTR pszMonitor, IN LPCWSTR pszEnvName, IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_SUCCESS; // // This is the moment where we check if we need to add the monitor // if (pszMonitor && *pszMonitor) { PINIMONITOR pIniLangMonitor; EnterSplSem(); // // We need to find the language monitor in pLocalIniSpooler // LMs are not cluster aware, so the cluster pIniSpooler doesn't know about them // pIniLangMonitor = FindMonitor(pszMonitor, pLocalIniSpooler); LeaveSplSem(); if (!pIniLangMonitor) { PINIENVIRONMENT pIniEnvironment; EnterSplSem(); pIniEnvironment = FindEnvironment(pszEnvName, pIniSpooler); LeaveSplSem(); if (pIniEnvironment) { DBGMSG(DBG_CLUSTER, ("ClusterFindLanguageMonitor Trying to install LangMonitor "TSTR"\n", pszMonitor)); // // We try to install the monitor from the cluster disk to the local spooler // dwError = InstallMonitorFromCluster(pszMonitor, pIniEnvironment->pName, pIniEnvironment->pDirectory, pIniSpooler); } else { dwError = ERROR_INVALID_ENVIRONMENT; } } } DBGMSG(DBG_CLUSTER, ("ClusterFindLanguageMonitor LangMonitor "TSTR" return Win32 error %u\n", pszMonitor, dwError)); return dwError; } /*++ Routine Name WriteTimeStamp Routine Description: Opens the key hkRoot\pszSubkey1\...\pszSubKey5 and writes the value of szClusDrvTimeStamp (binary data representing a system time) Arguments: hkRoot - handle to driver key SysTime - system time structure pszSubKey1 - subkey of the root key pszSubKey2 - subkey of key1, can be null pszSubKey3 - subkey of key2, can be null pszSubKey4 - subkey of key3, can be null pszSubKey5 - subkey of key4, can be null pIniSpooler - spooler, can be NULL Return Value: WIN32 error code --*/ DWORD WriteTimeStamp( IN HKEY hkRoot, IN SYSTEMTIME SysTime, IN LPCWSTR pszSubKey1, IN LPCWSTR pszSubKey2, IN LPCWSTR pszSubKey3, IN LPCWSTR pszSubKey4, IN LPCWSTR pszSubKey5, IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_INVALID_PARAMETER; if (hkRoot) { LPCWSTR ppszKeyNames[] = {NULL, pszSubKey1, pszSubKey2, pszSubKey3, pszSubKey4, pszSubKey5}; HKEY pKeyHandles[] = {hkRoot, NULL, NULL, NULL, NULL, NULL}; DWORD uIndex; dwError = ERROR_SUCCESS; // // Open all the keys // for (uIndex = 1; uIndex < COUNTOF(ppszKeyNames) && dwError == ERROR_SUCCESS && ppszKeyNames[uIndex]; uIndex++) { DBGMSG(DBG_CLUSTER, ("KEY "TSTR"\n", ppszKeyNames[uIndex])); dwError = SplRegCreateKey(pKeyHandles[uIndex-1], ppszKeyNames[uIndex], 0, KEY_WRITE, NULL, &pKeyHandles[uIndex], NULL, pIniSpooler); } // // If we opened successfully the keys that we wanted, write the value // if (dwError == ERROR_SUCCESS && !RegSetBinaryData(pKeyHandles[uIndex-1], szClusDrvTimeStamp, (LPBYTE)&SysTime, sizeof(SysTime), &dwError, pIniSpooler)) { dwError = GetLastError(); } // // Close any keys that we opened // for (uIndex = 1; uIndex < COUNTOF(ppszKeyNames); uIndex++) { if (pKeyHandles[uIndex]) { SplRegCloseKey(pKeyHandles[uIndex], pIniSpooler); } } } DBGMSG(DBG_CLUSTER, ("WriteTimeStamp returns Win32 error %u\n", dwError)); return dwError; } /*++ Routine Name ReadTimeStamp Routine Description: Opens the key hkRoot\pszSubkey1\...\pszSubKey5 and reads the value of szClusDrvTimeStamp (binary data representing a system time) Arguments: hkRoot - handle to driver key pSysTime - pointer to allocated system time structure pszSubKey1 - subkey of the root key pszSubKey2 - subkey of key1, can be null pszSubKey3 - subkey of key2, can be null pszSubKey4 - subkey of key3, can be null pszSubKey5 - subkey of key4, can be null pIniSpooler - spooler, can be NULL Return Value: WIN32 error code --*/ DWORD ReadTimeStamp( IN HKEY hkRoot, IN OUT SYSTEMTIME *pSysTime, IN LPCWSTR pszSubKey1, IN LPCWSTR pszSubKey2, IN LPCWSTR pszSubKey3, IN LPCWSTR pszSubKey4, IN LPCWSTR pszSubKey5, IN PINISPOOLER pIniSpooler ) { DWORD dwError = ERROR_INVALID_PARAMETER; if (hkRoot && pSysTime) { LPCWSTR ppszKeyNames[] = {NULL, pszSubKey1, pszSubKey2, pszSubKey3, pszSubKey4, pszSubKey5}; HKEY pKeyHandles[] = {hkRoot, NULL, NULL, NULL, NULL, NULL}; DWORD uIndex; dwError = ERROR_SUCCESS; // // Open all the keys // for (uIndex = 1; uIndex < COUNTOF(ppszKeyNames) && dwError == ERROR_SUCCESS && ppszKeyNames[uIndex]; uIndex++) { dwError = SplRegCreateKey(pKeyHandles[uIndex-1], ppszKeyNames[uIndex], 0, KEY_WRITE | KEY_READ, NULL, &pKeyHandles[uIndex], NULL, pIniSpooler); } // // If we opened successfully the keys that we wanted, write the value // if (dwError == ERROR_SUCCESS) { DWORD cbSize = sizeof(SYSTEMTIME); dwError = SplRegQueryValue(pKeyHandles[uIndex-1], szClusDrvTimeStamp, NULL, (LPBYTE)pSysTime, &cbSize, pIniSpooler); } // // Close any keys that we opened // for (uIndex = 1; uIndex < COUNTOF(ppszKeyNames); uIndex++) { if (pKeyHandles[uIndex]) { SplRegCloseKey(pKeyHandles[uIndex], pIniSpooler); } } } DBGMSG(DBG_CLUSTER, ("ReadTimeStamp returns Win32 error %u\n", dwError)); return dwError; } /*++ Routine Name ClusterCheckDriverChanged Routine Description: Helper function for spooler start up. When we have a cluster spooler and we build the environments and drivers, we need to check if the drivers on the local machine (in print$\GUID) are in sync with the drivers on the cluster disk. We store a time stamp in the cluster data base. The time stamp indicate when the last update on the driver occured. The same type of time stamp is stroed in the lcoal registry (for our cluster spooler). If the 2 time stamp are different, then we need to call an add printer driver and use data from the cluster disk. The drivers on the cluster spooler were updated while it was running on a different node. Arguments: hClusterVersionKey - handle to the driver version key pszDriver - driver name pszEnv - driver environment name pszVer - driver version name pIniSpooler - spooler Return Value: TRUE - if the driver on the cluster disk is updated and we need to call add printer driver. If anything fails in this function, then we also return TRUE, to force our caller to update/add the driver in question. FALSE - if the drivers on the local mahcine and the cluster spooler are in sync --*/ BOOL ClusterCheckDriverChanged( IN HKEY hClusterVersionKey, IN LPCWSTR pszDriver, IN LPCWSTR pszEnv, IN LPCWSTR pszVer, IN PINISPOOLER pIniSpooler ) { BOOL bReturn = TRUE; if (hClusterVersionKey && pszDriver && pszEnv && pszVer) { SYSTEMTIME ClusterTime; SYSTEMTIME NodeTime; if (ReadTimeStamp(hClusterVersionKey, &ClusterTime, pszDriver, NULL, NULL, NULL, NULL, pIniSpooler) == ERROR_SUCCESS && ReadTimeStamp(HKEY_LOCAL_MACHINE, &NodeTime, ipszRegistryClusRepository, pIniSpooler->pszClusResID, pszEnv, pszVer, pszDriver, NULL) == ERROR_SUCCESS && !memcmp(&ClusterTime, &NodeTime, sizeof(SYSTEMTIME))) { bReturn = FALSE; } } DBGMSG(DBG_CLUSTER, ("ClusterCheckDriverChanged returns bool %u\n", bReturn)); return bReturn; } /*++ Routine Name IsLocalFile Routine Description: Checks if a file is on the local machine. If the file path is "\\machinename\sharename\...\filename" then machinename is checked against pIniSpooler->pMachineName and alternate names for pIniSpooler->pMachineName. Arguments: pszFileName - file name pIniSpooler - INISPOOLER structure Return Value: TRUE if the file is placed locally. FALSE if the file is placed remotely. --*/ BOOL IsLocalFile ( IN LPCWSTR pszFileName, IN PINISPOOLER pIniSpooler ) { LPWSTR pEndOfMachineName, pMachineName; BOOL bRetValue = TRUE; if (pszFileName && *pszFileName == L'\\' && *(pszFileName+1) == L'\\') { // // If first 2 charactes in pszFileName are '\\', // then search for the next '\\'. If found, then set it to 0, // to isolate the machine name. // pMachineName = (LPWSTR)pszFileName; if (pEndOfMachineName = wcschr(pszFileName + 2, L'\\')) { *pEndOfMachineName = 0; } bRetValue = CheckMyName(pMachineName, pIniSpooler); // // Restore pszFileName. // if (pEndOfMachineName) { *pEndOfMachineName = L'\\'; } } return bRetValue; } /*++ Routine Name IsEXEFile Routine Description: Checks if a file is a executable. The check is made against file extension, which isn't quite accurate. Arguments: pszFileName - file name Return Value: TRUE if the file extension is either .EXE or .DLL --*/ BOOL IsEXEFile( IN LPCWSTR pszFileName ) { BOOL bRetValue = FALSE; DWORD dwLength; LPWSTR pszExtension; if (pszFileName && *pszFileName) { dwLength = wcslen(pszFileName); if (dwLength > COUNTOF(L".EXE") - 1) { pszExtension = (LPWSTR)pszFileName + dwLength - (COUNTOF(L".EXE") - 1); if (_wcsicmp(pszExtension , L".EXE") == 0 || _wcsicmp(pszExtension , L".DLL") == 0) { bRetValue = TRUE; } } } return bRetValue; } /*++ Routine Name PackStringToEOB Routine Description: Copies a string to the end of buffer. The buffer must be big enough so that it can hold the string. This function is called by Get/Enum APIs that build BLOB buffers to send them with RPC. Arguments: pszSource - string to by copied to the end of buffer pEnd - a pointer to the end of a pre-allocated buffer. Return Value: The pointer to the end of buffer after the sting was appended. NULL if an error occured. --*/ LPBYTE PackStringToEOB( IN LPWSTR pszSource, IN LPBYTE pEnd ) { DWORD cbStr; // // Align the end of buffer to WORD boundaries. // WORD_ALIGN_DOWN(pEnd); if (pszSource && pEnd) { cbStr = (wcslen(pszSource) + 1) * sizeof(WCHAR); pEnd -= cbStr; CopyMemory(pEnd, pszSource, cbStr); } else { pEnd = NULL; } return pEnd; } LPVOID MakePTR ( IN LPVOID pBuf, IN DWORD Quantity ) /*++ Routine Name MakePTR Routine Description: Makes a pointer by adding a quantity to the beginning of a buffer. Arguments: pBuf - pointer to buffer DWORD - quantity Return Value: LPVOID pointer --*/ { return (LPVOID)((ULONG_PTR)pBuf + (ULONG_PTR)Quantity); } DWORD MakeOffset ( IN LPVOID pFirst, IN LPVOID pSecond ) /*++ Routine Name MakeOffset Routine Description: Substarcts two pointers. Arguments: pFirst - pointer to buffer pSecond - pointer to buffer Return Value: DWORD --*/ { return (DWORD)((ULONG_PTR)pFirst - (ULONG_PTR)pSecond); } /*++ Routine Name IsValidPrinterName Routine Description: Checks if a string is a valid printer name. Arguments: pszPrinter - pointer to string cchMax - max number of chars to scan Return Value: TRUE - the string is a valid printer name FALSE - the string is a invalid printer name. The function set the last error to ERROR_INVALID_PRINTER_NAME in this case --*/ BOOL IsValidPrinterName( IN LPCWSTR pszPrinter, IN DWORD cchMax ) { DWORD Error = ERROR_INVALID_PRINTER_NAME; // // A printer name is of the form: // // \\s\p or p // // The name cannot contain the , character. Note that the add printer // wizard doesn't accept "!" as a valid printer name. We wanted to do // the same here, but we regressed in app compat with 9x apps. // The number of \ in the name is 0 or 3 // If the name contains \, then the fist 2 chars must be \. // The printer name cannot end in \. // After leading "\\" then next char must not be \ // The minimum length is 1 character // The maximum length is MAX_UNC_PRINTER_NAME // if (pszPrinter && !IsBadStringPtr(pszPrinter, cchMax) && *pszPrinter) { UINT uSlashCount = 0; UINT uLen = 0; LPCWSTR p; Error = ERROR_SUCCESS; // // Count characters // for (p = pszPrinter; *p && uLen <= cchMax; p++, uLen++) { if (*p == L',') { Error = ERROR_INVALID_PRINTER_NAME; break; } else if (*p == L'\\') { uSlashCount++; } } // // Perform validation // if (Error == ERROR_SUCCESS && // // Validate length // (uLen > cchMax || // // The printer name has either no \, or exactly 3 \. // uSlashCount && uSlashCount != 3 || // // A printer name that contains 3 \, must have the first 2 chars \ and the 3 not \. // The last char cannot be \. // Ex "\Foo", "F\oo", "\\\Foo", "\\Foo\" are invalid. // Ex. "\\srv\bar" is valid. // uSlashCount == 3 && (pszPrinter[0] != L'\\' || pszPrinter[1] != L'\\' || pszPrinter[2] == L'\\' || pszPrinter[uLen-1] == L'\\'))) { Error = ERROR_INVALID_PRINTER_NAME; } } SetLastError(Error); return Error == ERROR_SUCCESS; } /*++ Routine Name SplPowerEvent Routine Description: Checks if the spooler is ready for power management events like hibernation/stand by. If we have printing jobs that are not in an error state or offline, then we deny the powering down request. Arguments: Event - power management event Return Value: TRUE - the spooler allowed the system to be powered down FALSE - the spooler denies the request for powering down --*/ BOOL SplPowerEvent( DWORD Event ) { BOOL bAllow = TRUE; EnterSplSem(); switch (Event) { case PBT_APMQUERYSUSPEND: { PINISPOOLER pIniSpooler; for (pIniSpooler = pLocalIniSpooler; pIniSpooler && bAllow; pIniSpooler = pIniSpooler->pIniNextSpooler) { PINIPRINTER pIniPrinter; for (pIniPrinter = pIniSpooler->pIniPrinter; pIniPrinter && bAllow; pIniPrinter = pIniPrinter->pNext) { PINIJOB pIniJob; for (pIniJob = pIniPrinter->pIniFirstJob; pIniJob && bAllow; pIniJob = pIniJob->pIniNextJob) { if (pIniJob->Status & JOB_PRINTING && !(pIniJob->Status & JOB_ERROR | pIniJob->Status & JOB_OFFLINE)) { bAllow = FALSE; } } } } // // If we allow system power down, then we need to stop scheduling jobs // if (bAllow) { ResetEvent(PowerManagementSignal); } break; } case PBT_APMQUERYSUSPENDFAILED: case PBT_APMRESUMESUSPEND: case PBT_APMRESUMEAUTOMATIC: // // Set the event to allow the spooler to continue scheudling jobs // SetEvent(PowerManagementSignal); break; default: // // We ignore any other power management event // break; } LeaveSplSem(); return bAllow; } /*++ Routine Name IsCallViaRPC Routine Description: Checks if the caller of this function came in the spooler server via RPC or not. Arguments: None Return Value: TRUE - the caller came in via RPC FALSE - the caller did not come via RPC --*/ BOOL IsCallViaRPC( IN VOID ) { UINT uType; return I_RpcBindingInqTransportType(NULL, &uType) == RPC_S_NO_CALL_ACTIVE ? FALSE : TRUE; } /*++ Routine Name MergeMultiSz Routine Description: This merges two multisz strings such that there is a resulting multisz string that has no duplicate strings internally. This algorithm is currently N^2 which could be improved. It is currently being called from the driver code and the dependent files are not a large set. Arguments: pszMultiSz1 - The first multi-sz string. cchMultiSz1 - The length of the multi-sz string. pszMultiSz2 - The second multi-sz string. cchMultiSz2 - The length of the second multi-sz string. ppszMultiSzMerge - The merged multi-sz string. pcchMultiSzMerge - The number of characters in the merge, this could be less than the allocated buffer size. Return Value: FALSE on failure, LastError is set. --*/ BOOL MergeMultiSz( IN PCWSTR pszMultiSz1, IN DWORD cchMultiSz1, IN PCWSTR pszMultiSz2, IN DWORD cchMultiSz2, OUT PWSTR *ppszMultiSzMerge, OUT DWORD *pcchMultiSzMerge OPTIONAL ) { BOOL bRet = FALSE; PWSTR pszNewMultiSz = NULL; DWORD cchNewMultiSz = 0; *ppszMultiSzMerge = NULL; if (pcchMultiSzMerge) { *pcchMultiSzMerge = 0; } if (cchMultiSz1 || cchMultiSz2) { // // Code assumes that these are at least 1 in the allocation size. // cchMultiSz1 = cchMultiSz1 == 0 ? 1 : cchMultiSz1; cchMultiSz2 = cchMultiSz2 == 0 ? 1 : cchMultiSz2; // // The merged strings will be at most the size of both of them (if there are // no duplicates). // pszNewMultiSz = AllocSplMem((cchMultiSz1 + cchMultiSz2 - 1) * sizeof(WCHAR)); bRet = pszNewMultiSz != NULL; if (bRet) { // // Ensure that the multi-sz string is at least empty. // *pszNewMultiSz = L'\0'; } if (bRet && pszMultiSz1) { bRet = AddMultiSzNoDuplicates(pszMultiSz1, pszNewMultiSz, cchMultiSz1 + cchMultiSz2 - 1); } if (bRet && pszMultiSz2) { bRet = AddMultiSzNoDuplicates(pszMultiSz2, pszNewMultiSz, cchMultiSz1 + cchMultiSz2 - 1); } if (bRet) { cchNewMultiSz = GetMultiSZLen(pszNewMultiSz); } } if (bRet) { *ppszMultiSzMerge = pszNewMultiSz; if (pcchMultiSzMerge) { *pcchMultiSzMerge = cchNewMultiSz; } pszNewMultiSz = NULL; } FreeSplMem(pszNewMultiSz); return bRet; } /*++ Routine Name AddMultiSzNoDuplicates Routine Description: This adds all of the strings in a multisz string to a buffer (the buffer must be guaranteed to be large enough to accept the strings), it makes sure that there are no case insensitive duplicates in the list. Arguments: pszMultiSzIn - The multi-sz whose elements are being added. pszNewMultiSz - The buffer in which we are filling up the multi-sz cchMultiSz - The size of the multi-sz buffer. Return Value: None. --*/ BOOL AddMultiSzNoDuplicates( IN PCWSTR pszMultiSzIn, IN OUT PWSTR pszNewMultiSz, IN DWORD cchMultiSz ) { PCWSTR pszIn = NULL; BOOL bRet = TRUE; for(pszIn = pszMultiSzIn; *pszIn; pszIn += wcslen(pszIn) + 1) { BOOL bStringFound = FALSE; PWSTR pszMerge = NULL; SIZE_T cchNewMultiSz= cchMultiSz; // // For each input string, run the merged multi-sz string and add it if // it is not already there. // for(pszMerge = pszNewMultiSz; *pszMerge; pszMerge += wcslen(pszMerge) + 1, cchNewMultiSz -= wcslen(pszMerge) + 1) { if (!_wcsicmp(pszIn, pszMerge)) { bStringFound = TRUE; break; } } // // If the string was not found in the multisz string, then add it to the end. // if (!bStringFound) { SIZE_T cchRemaining = 0; // // Copy it in, we have one less character because of the final NULL termination. // bRet = BoolFromHResult(StrCchCopyMultipleStr(pszMerge, cchNewMultiSz - 1, pszIn, &pszMerge, &cchRemaining)); if (bRet) { // // Add the extra null terminator for now. // *pszMerge = '\0'; } } } return bRet; } /*++ Routine Name GetMultiSZLen Routine Description: This returns the number of characters in a multisz string, including NULLs. Arguments: pMultiSzSrc - The multisz string to search. Return Value: The number of characters in the string. --*/ DWORD GetMultiSZLen( IN LPWSTR pMultiSzSrc ) { DWORD dwLen = 0; LPWSTR pTmp = pMultiSzSrc; while( TRUE ) { dwLen += wcslen(pTmp) + 1; // Incude the terminating NULL char pTmp = pMultiSzSrc + dwLen; // Point to the beginning of the next string in the MULTI_SZ if( !*pTmp ) return ++dwLen; // Reached the end of the MULTI_SZ string. Add 1 to the count for the last NULL char. } } /*++ Routine Name LogPrintProcError Routine Description: Helper function. It logs an error event when the print function in the print processor fails. The only reason for having this function is to make the code in the caller cleaner. Arguments: Error - Error returned by the print processor. pIniJob - pIniJob structure for the job which failed to print. Return Value: None. --*/ VOID LogPrintProcError( IN DWORD Error, IN PINIJOB pIniJob ) { // // The print function in the print processor sets the last error. For better understaning // of the underlying problem, we log both the Win32 error code and the description of it. // LPWSTR pszDescription = NULL; WCHAR szError[40] = {0}; StringCchPrintf(szError, COUNTOF(szError), L"%u", Error); // // We do not care if FormatMessage fails. In that case pszDescription remains NULL, // and LocalFree knows how to handle NULL. // FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, Error, 0, (LPWSTR)&pszDescription, 0, NULL); // // Impersonate so the user's name appears in the event log // SetCurrentSid(pIniJob->hToken); SplLogEvent(pIniJob->pIniPrinter->pIniSpooler, LOG_ERROR, MSG_PRINT_ON_PROC_FAILED, FALSE, pIniJob->pDocument, pIniJob->pUser, pIniJob->pIniPrinter->pName, szError, pszDescription ? pszDescription : L"", NULL); SetCurrentSid(NULL); LocalFree(pszDescription); } LONG InterlockedAnd ( IN OUT LONG volatile *Target, IN LONG Set ) { LONG i; LONG j; j = *Target; do { i = j; j = InterlockedCompareExchange(Target, i & Set, i); } while (i != j); return j; } LONG InterlockedOr ( IN OUT LONG volatile *Target, IN LONG Set ) { LONG i; LONG j; j = *Target; do { i = j; j = InterlockedCompareExchange(Target, i | Set, i); } while (i != j); return j; } /*++ Routine Name: StrCchCopyMultipleStr Description: This routine is a simple wrapper that allows multiple strings to be copied into a buffer. It uses the normal StringCchCopyEx function, but then advances one more if it is safe to do so. If it cannot advance, it returns an error. Arguments: pszBuffer - The buffer we are writing the string into. cchBuffer - The number of characters in the buffer. pszSource - The source of the buffer. ppszNext - The pointer after this string in the buffer. pcchRemaining - The number of characters remaining. Returns: An HRESULT, HRESULT_FROM_WIN23(ERROR_INSUFFICIENT_BUFFER) if we are out of room. --*/ EXTERN_C HRESULT StrCchCopyMultipleStr( IN PWSTR pszBuffer, IN SIZE_T cchBuffer, IN PCWSTR pszSource, OUT PWSTR *ppszNext, OUT SIZE_T *pcchRemaining ) { // // Unlike the strsafe function, we require both parameters. // HRESULT hr = ppszNext && pcchRemaining ? S_OK : HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); if (SUCCEEDED(hr)) { size_t cchRemaining = 0; hr = StringCchCopyExW(pszBuffer, cchBuffer, pszSource, ppszNext, &cchRemaining, 0); *pcchRemaining = cchRemaining; // // If this succeeds, then advance the pointer, otherwise, there is no // room and the string will be NULL terminated anyway. // if (SUCCEEDED(hr)) { hr = *pcchRemaining ? S_OK : HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } if (SUCCEEDED(hr)) { (*pcchRemaining)--; (*ppszNext)++; } } return hr; } /*++ Routine Name: StrCbCopyMultipleStr Description: This is the equivalent to StrCchCopyMultipleStr for byte buffers. --*/ EXTERN_C HRESULT StrCbCopyMultipleStr( IN PWSTR pszBuffer, IN SIZE_T cbBuffer, IN PCWSTR pszSource, OUT PWSTR *ppszNext, OUT SIZE_T *pcbRemaining ) { HRESULT hr = ppszNext && pcbRemaining ? S_OK : HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); if (SUCCEEDED(hr)) { size_t cbRemaining = 0; hr = StringCbCopyExW(pszBuffer, cbBuffer, pszSource, ppszNext, &cbRemaining, 0); *pcbRemaining = cbRemaining; // // If this succeeds, then advance the pointer, otherwise, there is no // room and the string will be NULL terminated anyway. // if (SUCCEEDED(hr)) { // // We must have at least 2 bytes remaining to advance the string. // hr = *pcbRemaining > 1 ? S_OK : HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } if (SUCCEEDED(hr)) { (*pcbRemaining) -= 2; (*ppszNext)++; } } return hr; } /*++ Routine Name: IsStringNullTerminatedInBuffer Description: This routine checks to see whether the string in the given buffer is NULL terminated. Arguments: pszBuffer - The buffer that should contain a NULL terminated string. cchBuffer - The number of characters in the buffer. Returns: TRUE if there is a NULL termination within the buffer. --*/ BOOL IsStringNullTerminatedInBuffer( IN PWSTR pszBuffer, IN SIZE_T cchBuffer ) { for(;cchBuffer > 0; cchBuffer--, pszBuffer++) { if (!*pszBuffer) { break; } } return cchBuffer > 0; } /*++ Routine Name IsPrinterSharingAllowed Routine Description: This checks if Spooler allows printer sharing. Arguments: None Return Value: TRUE if Spooler allows printer sharing. --*/ BOOL IsPrinterSharingAllowed( VOID ) { return gRemoteRPCEndPointPolicy != RpcEndPointPolicyDisabled; }
27.031012
150
0.501586
d7f211aadf0d055a47582242756698ca3e6d4d15
6,174
h
C
tech/Reflection/Property.h
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Reflection/Property.h
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Reflection/Property.h
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (c) 2015 Teardrop Games Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #if !defined (PROPERTY_INCLUDED) #define PROPERTY_INCLUDED #include "Util/StringUtil.h" #include "Util/_String.h" #include <vector> #include <assert.h> namespace Teardrop { namespace Reflection { class Object; /* Base templated property definition class. This is where the actual field is declared inside the containing class (via the PROPERTY family of macros). */ template <class _T> class PropertyDefImpl { public: PropertyDefImpl() { } ~PropertyDefImpl() { } void toString(String& sVal) { StringUtil::toString(m_val, sVal); } void fromString(const String& sVal) { StringUtil::fromString(sVal, m_val); } operator _T& () { return m_val; } operator const _T& () const { return m_val; } _T& operator=(const _T& other) { m_val = other.m_val; return m_val; } bool operator==(_T& other) { return *this == other; } bool operator==(const _T& other) const { return m_val == other; } bool operator!=(_T& other) { return !(*this == other); } bool operator!=(const _T& other) const { return !(*this == other); } _T& operator=(_T& other) { m_val = other.m_val; return m_val; } _T& get() { return m_val; } void set(_T val) { m_val = val; } protected: _T m_val; }; template <class _T> class NestedPropertyDefImpl { public: NestedPropertyDefImpl() { } ~NestedPropertyDefImpl() { } void toString(String& sVal) { } void fromString(const String& sVal) { } operator _T& () { return m_val; } operator const _T& () const { return m_val; } _T& get() { return m_val; } protected: _T m_val; }; /* Base templated pointer property definition class. This is where the actual pointer field is declared inside the containing class (via the PROPERTY family of macros). */ template<class T> class PointerPropertyDefImpl { T* m_p; public: PointerPropertyDefImpl() { m_p = 0; } PointerPropertyDefImpl(T* pP) { m_p = pP; } PointerPropertyDefImpl(const PointerPropertyDefImpl<T>& other) { *this = other; } T* operator=(T* other) { m_p = other; return m_p; } T& operator=(T& other) { m_p = other.m_p; return *this; } operator T*() { return m_p; } operator T const *() { return m_p; } T* operator->() { return m_p; } bool isNull() { return m_p == 0; } T& operator*() { assert(m_p); return *m_p; } T* get() { return m_p; } void set(T* p) { m_p = p; } }; /* Base templated pointer property definition class. This is where the actual pointer field is declared inside the containing class (via the PROPERTY family of macros). */ template<typename T> class EnumPropertyDefImpl { T mVal; public: EnumPropertyDefImpl() { } EnumPropertyDefImpl(T val) { mVal = val; } EnumPropertyDefImpl(const EnumPropertyDefImpl<T>& other) { *this = other; } EnumPropertyDefImpl<T>& operator=(const EnumPropertyDefImpl<T>& other) { mVal = other.mVal; return *this; } operator T() { return mVal; } T get() { return mVal; } void set(T val) { mVal = val; } }; class CollectionPropertyBase { public: virtual bool setAtFromString(size_t index, const String& strVal) = 0; virtual void resize(size_t count) = 0; }; template <class T> class CollectionPropertyType : public CollectionPropertyBase { public: typedef std::vector<T> ContainerType; private: ContainerType _coll; public: CollectionPropertyType() { } ContainerType& getContainer() { return _coll; } void add(const T& val) { _coll.push_back(val); } void clear() { _coll.clear(); } size_t getCount() { return _coll.size(); } size_t getCapacity() { return _coll.capacity(); } void resize(size_t count) { _coll.resize(count); } void reserve(size_t count) { _coll.reserve(count); } bool getAt(size_t index, T& /*inout*/ val) { assert(index < _coll.size()); if (index >= _coll.size()) return false; val = _coll[index]; return true; } bool setAt(size_t index, const T& /*in*/ val) { assert(index < _coll.capacity()); if (index >= _coll.capacity()) return false; _coll[index] = val; return true; } bool setAtFromString(size_t index, const String& strVal) { T val; StringUtil::fromString(strVal, val); return setAt(index, val); } }; template<typename T> class PointerCollectionPropertyType : public CollectionPropertyType<T*> { public: bool setAtFromString(size_t /*index*/, const String& /*strVal*/) { return false; } }; } // namespace Reflection } // namespace Teardrop #endif // PROPERTY_INCLUDED
18.93865
81
0.622449
ccaf42a5a9c0c7af57312bf7ca01809a321927da
4,292
h
C
Unreal/CtaCpp/Runtime/Scripts/Dotnet/JsonUtils.h
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
3
2021-06-02T16:44:02.000Z
2022-01-24T20:20:10.000Z
Unreal/CtaCpp/Runtime/Scripts/Dotnet/JsonUtils.h
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
null
null
null
Unreal/CtaCpp/Runtime/Scripts/Dotnet/JsonUtils.h
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
null
null
null
#pragma once #include "FileUtils.h" #include <string> //C# TO C++ CONVERTER NOTE: Forward class declarations: namespace Newtonsoft::Json { class JsonSerializerSettings; } /* The MIT License (MIT) Copyright 2021 Adam Reilly, Call to Action Software LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using namespace Newtonsoft::Json; namespace Cta { /// <summary> /// Utilty class for working with JSON files. Uses Newtonsoft.JSON MIT library /// </summary> class JsonUtils final { private: static JsonSerializerSettings *const m_jsonSerializerSettings; //public static readonly JsonSerializerSettings JsonNoRefHandlingSettings = new JsonSerializerSettings //{ // ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // PreserveReferencesHandling = PreserveReferencesHandling.None, // Formatting = Formatting.Indented, // TypeNameHandling = TypeNameHandling.None, // https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm // TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple, //}; public: static JsonSerializerSettings *GetJsonConfig(); /// <summary> /// Json Serializes the data to a file /// </summary> /// <typeparam name="T">The type of data to serialize</typeparam> /// <param name="data">The data</param> /// <param name="path">The file path where the json will be written</param> template<typename T> static void JsonSerializeToFile(T data, const std::wstring &path) { JsonSerializeToFile(data, path, GetJsonConfig()); } /// <summary> /// Json Serializes the data to a file /// </summary> /// <typeparam name="T">The type of data to serialize</typeparam> /// <param name="data">The data</param> /// <param name="path">The file path where the json will be written</param> template<typename T> static void JsonSerializeToFile(T data, const std::wstring &path, JsonSerializerSettings *settings) { FileUtils::WriteAllText(path, JsonSerialize(data, settings)); } /// <summary> /// Serializes the data to a json string /// </summary> /// <typeparam name="T">The type of data</typeparam> /// <param name="data">The data</param> /// <returns>The json string representing the data</returns> template<typename T> static std::wstring JsonSerialize(T data) { return JsonSerialize(data, GetJsonConfig()); } /// <summary> /// Serializes the data to a json string /// </summary> /// <typeparam name="T">The type of data</typeparam> /// <param name="data">The data to serialize</param> /// <param name="settings">The json configuration settings to use in the serialization process</param> /// <returns>The json string representing the data</returns> template<typename T> static std::wstring JsonSerialize(T data, JsonSerializerSettings *settings) { return JsonConvert::SerializeObject(data, settings); } /// <summary> /// Deserializes the json string to the given data type /// </summary> /// <typeparam name="T">The type of data to conver to</typeparam> /// <param name="json">The json formatted string</param> /// <returns>The data structure represented by the json</returns> template<typename T> static T JsonDeserialize(const std::wstring &json) { return JsonConvert::DeserializeObject<T>(json); } }; }
40.11215
460
0.732293
62e73827d7270b12b48372c4dda2a2df9d66a1ad
35,482
h
C
Source/Interface/Array/NSArray+FunkyUtilities.h
tevelee/Funky
0bd22c7ae443a56a9c0fba8114342c30421c24fa
[ "MIT" ]
43
2017-05-07T13:29:08.000Z
2021-08-02T02:25:54.000Z
Source/Interface/Array/NSArray+FunkyUtilities.h
tevelee/Funky
0bd22c7ae443a56a9c0fba8114342c30421c24fa
[ "MIT" ]
1
2018-02-11T03:44:18.000Z
2018-02-12T09:23:44.000Z
Source/Interface/Array/NSArray+FunkyUtilities.h
tevelee/Funky
0bd22c7ae443a56a9c0fba8114342c30421c24fa
[ "MIT" ]
5
2017-05-10T18:57:21.000Z
2018-09-01T20:59:58.000Z
// // NSArray+Utilities.h // Pods // // Created by László Teveli on 2017. 03. 21.. // // #import <Foundation/Foundation.h> /** * This extension provides simple and easy to use functional and general utilities for NSArray. * If you need to prefix the extension methods in this category, you should import `NSArray+FunkyPrefixedUtilities.h`, where every utility method is prefixed with the `funky_` keyword for compatiblitiy reasons. * * @see Prefixed counterpart `NSArray(FunkyPrefixedUtilities)` * @see Mutable counterpart `NSMutableArray(FunkyUtilities)` */ @interface NSArray <__covariant ObjectType> (FunkyUtilities) #pragma mark - Check /** * Returns whether the condition matches all elements in the array * * @param block The condition given as a BOOL expression * @return YES if condition matches all elements, NO otherwise * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_all:]` */ - (BOOL)all:(BOOL(^)(ObjectType item))block; /** * Returns whether the condition matches no elements in the array * * @param block The condition given as a BOOL expression * @return NO if condition matches any of the elements, YES otherwise * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_none:]` */ - (BOOL)none:(BOOL(^)(ObjectType item))block; /** * Returns whether the condition matches at least one element in the array * * @param block The condition given as a BOOL expression * @return YES if condition matches any of the elements, NO otherwise * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_contains:]` */ - (BOOL)contains:(BOOL(^)(ObjectType item))block; #pragma mark - Count /** * Returns the number of elements the given condition matches in the array, like if you would filter the array. * * @param block The condition given as a BOOL expression * @return Number of occasions where the condition matches in the array * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_count:]` */ - (NSUInteger)count:(BOOL(^)(ObjectType item))block; #pragma mark - Map /** * Returns a new NSArray instance with the same amount of elements, where each element is transformed to another by returning a new object in the block parameter. * * @param block The transformator code which should return a new value based on the existing one. * @return A new NSArray instance where each element is formed by the result of the block calls * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_map:]` */ - (NSArray*)map:(id(^)(ObjectType item))block; /** * Returns a new NSArray instance where each element is transformed to another by returning a new object in the block parameter. It ignores the nil parameters returned from the block. * * @param block The transformator code which should return a new value based on the existing one. * @return A new NSArray instance where each element is formed by the result of the block calls * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_nilTolerantMap:]` */ - (NSArray*)nilTolerantMap:(id(^)(ObjectType item))block; /** * Same as map, but the block contains the index of the current element. * * @param block The transformator code which should return a new value based on the index and the existing item. * @return A new NSArray instance where each element is formed by the result of the block calls * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_mapWithIndex:]` */ - (NSArray*)mapWithIndex:(id(^)(NSUInteger index, ObjectType item))block; /** * Same as nil-tolerant map, but the block contains the index of the current element. * * @param block The transformator code which should return a new value based on the index and the existing item. * @return A new NSArray instance where each element is formed by the result of the block calls * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_mapWithIndex:]` */ - (NSArray*)nilTolerantMapWithIndex:(id(^)(NSUInteger index, ObjectType item))block; /** * Returns a new NSArray instance with the same amount of elements, where each element is transformed to another by returning a new object in the block parameter. Same as map, but the result is going to be flattened, so if you return an NSArray any iteration, it is going to be converted into a flat structure, not an array of arrays. * * @param block The transformator code which should return a new value based on the existing one. * @return A new NSArray instance where each element is formed by the result of the flattened block calls * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_flatMap:]` */ - (NSArray*)flatMap:(id(^)(ObjectType item))block; /** * Same as flatMap, but the block contains the index of the current element. * * @param block The transformator code which should return a new value based on the index and the existing item. * @return A new NSArray instance where each element is formed by the result of the flattened block calls * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_flatMapWithIndex:]` */ - (NSArray*)flatMapWithIndex:(id(^)(NSUInteger index, ObjectType item))block; #pragma mark - Filter /** * Returns a new NSArray instance with the element, that are passing the returned expression in the original array. * * @param block The filtering predicate given as a BOOL expression * @return A new NSArray instance where each element is selected from the original one where the block returned YES * @see Mutable counterpart `-[NSMutableArray(FunkyUtilities) filter:]` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_filtered:]` */ - (NSArray<ObjectType>*)filtered:(BOOL(^)(ObjectType item))block; #pragma mark - Flatten /** * Flattens the array, meaning that if it consisted of Array items, they are going to be flattened into one flat structure of elements. An array of arrays will transform to an array of elements from each of the previous arrays. This computation is performed deeply, meaning that it contontued flattening elements, until they produce a flat structure. * * @return A new NSArray instance where the elements don't contain NSArrays * @see Mutable counterpart `-[NSMutableArray(FunkyUtilities) flatten]` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_flattened]` */ - (NSArray<ObjectType>*)flattened; #pragma mark - Merge /** * Returns a new NSArray instance, in which concatenates the two arrays by putting the existing elements first, and the elements in the provided array after them. * * @param array The other collection to merge with * @return A new NSArray which contains the elements of both arrays (self and the `array` parameter) * @see Mutable counterpart `-[NSMutableArray(FunkyUtilities) merge:]` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_merged:]` */ - (NSArray*)merged:(NSArray*)array; #pragma mark - For each /** * Calls every element of the array once. * * @param block A block, giving the current item in each iteration. * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_forEach:]` */ - (void)forEach:(void(^)(ObjectType item))block; /** * Calls every element of the array once. Same as forEach, but the block contains the index of the current element as well. * * @param block A block, giving the current item and its index in each iteration. * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_forEachWithIndex:]` */ - (void)forEachWithIndex:(void(^)(NSUInteger index, ObjectType item))block; #pragma mark - Grouping /** * Groups elements to an NSDictionary, where the returned element serves as a key, and the objects as the value. If multiple elements are returned with the same key, this function will use the first matching element. * * @param block A block which returns a key (based on the passed element) used as the key in the dictionary for that element. * @return An NSDictionary where keys are produced by the result of the block call, and the values are the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_groupByUsingFirst:]` */ - (NSDictionary<id, ObjectType>*)groupByUsingFirst:(id(^)(ObjectType item))block; /** * Groups elements to an NSDictionary, where the returned element serves as a key, and the objects as the value. If multiple elements are returned with the same key, this function will use the last matching element. * * @param block A block which returns a key (based on the passed element) used as the key in the dictionary for that element. * @return An NSDictionary where keys are produced by the result of the block call, and the values are the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_groupByUsingLast:]` */ - (NSDictionary<id, ObjectType>*)groupByUsingLast:(id(^)(ObjectType item))block; /** * Groups elements to an NSDictionary, where the returned element serves as a key, and the objects as the value. The elements in the resulting Dictionary are arrays, so if multiple elements return the same keys, all of them are going to be included in the value. * * @param block A block which returns a key (based on the passed element) used as the key in the dictionary. * @return An NSDictionary where keys are produced by the result of the blocks, and the values are an array of original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_associateBy:]` */ - (NSDictionary<id, NSArray<ObjectType>*>*)associateBy:(id(^)(ObjectType item))block; #pragma mark - Compute /** * Produces an aggregated value based on the elements of the array. * * @param start The value to start with. At first this is going to be the rolling value. * @param block The computation logic, which takes the rolling value and the current item and aggregates them using some custom logic. * @return A custom value which is produced by computing all the elements with a custom logic, returned in `block` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_reduce:withInitialValue:]` */ - (id)reduce:(id(^)(id value, ObjectType item))block withInitialValue:(id)start; /** * A special use-case of reduce, which summarises the returned double values for each element in the array. * * @param block A block which returns double value, based on the current element. * @return The sum of all elements, where the numbers are computed are transformed based on the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_sum:]` */ - (double)sum:(double(^)(ObjectType item))block; /** * A special use-case of reduce, which takes the average value of the returned double values for each element in the array. * * @param block A block which returns double value, based on the current element. * @return The average of all elements, where the numbers are computed are transformed based on the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_average:]` */ - (double)average:(double(^)(ObjectType item))block; #pragma mark - Min/Max /** * A special use-case of reduce, which takes the minimum of the returned double values for each element in the array. * * @param block A block which returns double value, based on the current element. * @return The minimum of all elements, where the numbers are computed are transformed based on the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_minValue:]` */ - (double)minValue:(double(^)(ObjectType item))block; /** * A special use-case of reduce, which takes the maximum of the returned double values for each element in the array. * * @param block A block which returns double value, based on the current element. * @return The maximum of all elements, where the numbers are computed are transformed based on the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_maxValue:]` */ - (double)maxValue:(double(^)(ObjectType item))block; /** * Returns an array with all the minimal value elements in the array, where the minimum was computed by the returned double value for each element in the array. * * @param block A block which returns double value, based on the current element. * @return The array of elements with the minimal value, where the numbers are computed are transformed based on the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_minItems:]` */ - (NSArray<ObjectType>*)minItems:(double(^)(ObjectType item))block; /** * Returns an array with all the maximal value elements in the array, where the maximum was computed by the returned double value for each element in the array. * * @param block A block which returns double value, based on the current element. * @return The array of elements with the maximal value, where the numbers are computed are transformed based on the original elements * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_maxItems:]` */ - (NSArray<ObjectType>*)maxItems:(double(^)(ObjectType item))block; #pragma mark - First/Last /** * Returns the first index of the array: 0 * * @return the first index of the array * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_firstIndex]` */ - (NSUInteger)firstIndex; /** * Returns the last index of the array: count - 1 * * @return the last index of the array * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_lastIndex]` */ - (NSUInteger)lastIndex; /** * Returns the first element, where the predicate matches * * @param block The condition provided as a BOOL expression. * @return The first element where the block returns YES * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_first:]` */ - (id)first:(BOOL(^)(ObjectType item))block; /** * Returns the index of the first element, where the predicate matches * * @param block The condition provided as a BOOL expression. * @return The index of the first element where the block returns YES * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_firstIndex:]` */ - (NSUInteger)firstIndex:(BOOL(^)(ObjectType item))block; /** * Returns the last element, where the predicate matches * * @param block The condition provided as a BOOL expression. * @return The index of the first element where the block returns YES * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_last:]` */ - (id)last:(BOOL(^)(ObjectType item))block; /** * Returns the index of the last element, where the predicate matches * * @param block The condition provided as a BOOL expression. * @return The index of the last element where the block returns YES * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_lastIndex:]` */ - (NSUInteger)lastIndex:(BOOL(^)(ObjectType item))block; #pragma mark - Take /** * Returns an array of the values where the predicate matches, but only until it's a consecutive sequence. Once the predicate returns NO, those elements are going to be dropped. * * @param block The condition provided as a BOOL expression. * @return The first subsequence of elements until the block returns YES * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_take:]` */ - (NSArray<ObjectType>*)take:(BOOL(^)(ObjectType item))block; /** * Returns an array of the values where the predicate matches, but only the last consecutive sequence of these element. Same as take, but from the end of the array. * * @param block The condition provided as a BOOL expression. * @return The last subsequence of elements from where the block returns YES * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_takeLast:]` */ - (NSArray<ObjectType>*)takeLast:(BOOL(^)(ObjectType item))block; #pragma mark - from-until /** * Returns an array of the values starting from the given object, not including the object itself. If the given object does not exist in the array, the result is going to be an empty NSArray. * * @param value The signaling object. * @return A subsequence of elements starting from the first occurence of the given object * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromValueExclusive:]` */ - (NSArray<ObjectType>*)fromValueExclusive:(id)value; /** * Returns an array of the values starting from the given object, including the object itself. If the given object does not exist in the array, the result is going to be an empty NSArray. * * @param value The signaling value, which is going to be represent in the array as the first element. * @return A subsequence of elements starting from the first occurence of the given object * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromValueInclusive:]` */ - (NSArray<ObjectType>*)fromValueInclusive:(id)value; /** * Returns an array of the values starting from the given index, not including the object at the given index. If the given index does not exist in the array, the result is going to be an empty NSArray. * * @param index The starting index. * @return A subsequence of elements starting from the given index * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromIndexExclusive:]` */ - (NSArray<ObjectType>*)fromIndexExclusive:(NSInteger)index; /** * Returns an array of the values starting from the given index, including the object at the fiven index. If the given index does not exist in the array, the result is going to be an empty NSArray. * * @param index The signaling index, where the element at the index is going to be represent in the array as the first element. * @return A subsequence of elements starting from the given index * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromIndexInclusive:]` */ - (NSArray<ObjectType>*)fromIndexInclusive:(NSInteger)index; /** * Returns an array of the values until the given object, not including the object itself. If the given object does not exist in the array, the result is going to be an empty NSArray. * * @param value The signaling object. * @return A subsequence of elements until the first occurence of the given object * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_untilValueExclusive:]` */ - (NSArray<ObjectType>*)untilValueExclusive:(id)value; /** * Returns an array of the values until the given object, including the object itself. If the given object does not exist in the array, the result is going to be an empty NSArray. * * @param value The signaling value, which is going to be represent in the array as the last element. * @return A subsequence of elements until the first occurence of the given object * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_untilValueInclusive:]` */ - (NSArray<ObjectType>*)untilValueInclusive:(id)value; /** * Returns an array of the values until the given index, not including the object at the given index. If the given index does not exist in the array, the result is going to be an empty NSArray. * * @param index The starting index. * @return A subsequence of elements until the given index * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_untilIndexExclusive:]` */ - (NSArray<ObjectType>*)untilIndexExclusive:(NSInteger)index; /** * Returns an array of the values until the given index, including the object at the fiven index. If the given index does not exist in the array, the result is going to be an empty NSArray. * * @param index The signaling index, where the element at the index is going to be represent in the array as the last element. * @return A subsequence of elements until the given index * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_untilIndexInclusive:]` */ - (NSArray<ObjectType>*)untilIndexInclusive:(NSInteger)index; /** * Returns an array of the values between the given two input objects, excluding both from the result set. * If the starting object does not exist in the array, it's equivalent to the matching untilValue expression. * If the ending object does not exist in the array, it's equivalent to the matching fromValue expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting object. * @param until The ending object. * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromValueExclusive:untilValueExclusive:]` * @return A subsequence of elements between the first occurences given objects */ - (NSArray<ObjectType>*)fromValueExclusive:(id)from untilValueExclusive:(id)until; /** * Returns an array of the values between the given two input objects, excluding `from`, including `until` from the result set. * If the starting object does not exist in the array, it's equivalent to the matching untilValue expression. * If the ending object does not exist in the array, it's equivalent to the matching fromValue expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting object. * @param until The ending object. * @return A subsequence of elements between the first occurences given objects * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromValueExclusive:untilValueInclusive:]` */ - (NSArray<ObjectType>*)fromValueExclusive:(id)from untilValueInclusive:(id)until; /** * Returns an array of the values between the given two input objects, including `from`, excluding `until` from the result set. * If the starting object does not exist in the array, it's equivalent to the matching untilValue expression. * If the ending object does not exist in the array, it's equivalent to the matching fromValue expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting object. * @param until The ending object. * @return A subsequence of elements between the first occurences given objects * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromValueInclusive:untilValueExclusive:]` */ - (NSArray<ObjectType>*)fromValueInclusive:(id)from untilValueExclusive:(id)until; /** * Returns an array of the values between the given two input objects, including both from the result set. * If the starting object does not exist in the array, it's equivalent to the matching untilValue expression. * If the ending object does not exist in the array, it's equivalent to the matching fromValue expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting object. * @param until The ending object. * @return A subsequence of elements between the first occurences given objects * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromValueInclusive:untilValueInclusive:]` */ - (NSArray<ObjectType>*)fromValueInclusive:(id)from untilValueInclusive:(id)until; /** * Returns an array of the values between the given two indices, excluding both objects (at the given indices) from the result set. * If the starting index does not exist in the array, it's equivalent to the matching untilIndex expression. * If the ending index does not exist in the array, it's equivalent to the matching fromIndex expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting index. * @param until The ending index. * @return A subsequence of elements between the first occurences given indices * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromIndexExclusive:untilIndexExclusive:]` */ - (NSArray<ObjectType>*)fromIndexExclusive:(NSInteger)from untilIndexExclusive:(NSInteger)until; /** * Returns an array of the values between the given two indices, excluding the object at the index `from`, including the one at the index `until` from the result set. * If the starting index does not exist in the array, it's equivalent to the matching untilIndex expression. * If the ending index does not exist in the array, it's equivalent to the matching fromIndex expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting index. * @param until The ending index. * @return A subsequence of elements between the first occurences given indices * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromIndexExclusive:untilIndexInclusive:]` */ - (NSArray<ObjectType>*)fromIndexExclusive:(NSInteger)from untilIndexInclusive:(NSInteger)until; /** * Returns an array of the values between the given two indices, including the object at the index `from`, excluding the one at the index `until` from the result set. * If the starting index does not exist in the array, it's equivalent to the matching untilIndex expression. * If the ending index does not exist in the array, it's equivalent to the matching fromIndex expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting index. * @param until The ending index. * @return A subsequence of elements between the first occurences given indices * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromIndexInclusive:untilIndexExclusive:]` */ - (NSArray<ObjectType>*)fromIndexInclusive:(NSInteger)from untilIndexExclusive:(NSInteger)until; /** * Returns an array of the values between the given two indices, including both objects (at the given indices) from the result set. * If the starting index does not exist in the array, it's equivalent to the matching untilIndex expression. * If the ending index does not exist in the array, it's equivalent to the matching fromIndex expression. * If neither one exists, the result is an empty NSArray. * * @param from The starting index. * @param until The ending index. * @return A subsequence of elements between the first occurences given indices * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_fromIndexInclusive:untilIndexInclusive:]` */ - (NSArray<ObjectType>*)fromIndexInclusive:(NSInteger)from untilIndexInclusive:(NSInteger)until; #pragma mark - Transform /** * Returns an array where is object is unique, so the resulting array does not contain any duplicates. * It checks equality using the `-isEqual:` method * * @return A new NSArray consisting of unique objects * @see Mutable counterpart `-[NSMutableArray(FunkyUtilities) removeDuplicates]` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_unique]` */ - (NSArray<ObjectType>*)unique; /** * Returns an array where the items are in a reversed order. * * @return A new NSArray in reverese order compared to the original one * @see Mutable counterpart `-[NSMutableArray(FunkyUtilities) reverse]` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_reversed]` */ - (NSArray<ObjectType>*)reversed; /** * Returns an array where the items are shuffled randomly. * * @return A new NSArray consisting of the original objects in a shuffled order * @see Mutable counterpart `-[NSMutableArray(FunkyUtilities) shuffle]` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_shuffled]` */ - (NSArray<ObjectType>*)shuffled; #pragma mark - Sort /** * Returns an array sorted using the given comparator. * * @param comparator An NSComparator block to define the sort order. * @return A new NSArray sorted by the comparator * @see Mutable counterpart `-[NSMutableArray(FunkyUtilities) sort:]` * @see Prefixed counterpart `-[NSArray(FunkyPrefixedUtilities) funky_sorted:]` */ - (NSArray<ObjectType>*)sorted:(NSComparator)comparator; #pragma mark - Constructor /** * Creates an array by repeating the same `item` by `repeat` number of times. The size of the array is going to be qual to `repeat`, only consisting of `item` objects. * * @param item The item to repeat * @param repeat Number of times to repeat the `item` parameter * @return A new NSArray instance with the given item repeated * @see Mutable counterpart `+[NSMutableArray(FunkyUtilities) arrayWithItem:repeated:]` * @see Prefixed counterpart `+[NSArray(FunkyPrefixedUtilities) funky_arrayWithItem:repeated:]` */ + (NSArray<ObjectType>*)arrayWithItem:(id)item repeated:(NSUInteger)repeat; /** * Creates an array by taking an initial `array` and computing the next items by repeatedly putting the result of `block` by `repeated` number of times. * * @param array Initial array * @param block The block to compute the next item in the resulting array * @param repeat Number of times to repeat calling the `block` parameter * @return A new NSArray instance with items returned by the block * @see Mutable counterpart `+[NSMutableArray(FunkyUtilities) arrayWithArray:nextItem:repeated:]` * @see Prefixed counterpart `+[NSArray(FunkyPrefixedUtilities) funky_arrayWithArray:nextItem:repeated:]` */ + (NSArray<ObjectType>*)arrayWithArray:(NSArray<ObjectType>*)array nextItem:(id(^)(NSArray* array))block repeated:(NSUInteger)repeat; /** * Creates an array by taking an initial `array` and computing the next items by repeatedly putting the result of `block` by until the block parameter `until` returns YES. * * @param array Initial array * @param block The block to compute the next item in the resulting array * @param until Logic until the iteration should be repeated. Until the block returns YES, the constructor repeatedly callis the `block` parameter * @return A new NSArray instance with items returned by the block * @see Mutable counterpart `+[NSMutableArray(FunkyUtilities) arrayWithArray:nextItem:until:]` * @see Prefixed counterpart `+[NSArray(FunkyPrefixedUtilities) funky_arrayWithArray:nextItem:until:]` */ + (NSArray<ObjectType>*)arrayWithArray:(NSArray<ObjectType>*)array nextItem:(id(^)(NSArray* array))block until:(BOOL(^)(NSArray* array))until; @end /** * This extension provides simple and easy to use functional and general utilities for NSMutableArray. * If you need to prefix the extension methods in this category, you should import `NSArray+FunkyPrefixedUtilities.h`, where every utility method is prefixed with the `funky_` keyword for compatiblitiy reasons. * * @see Prefixed counterpart `NSMutableArray(FunkyPrefixedUtilities)` * @see Immutable counterpart `NSArray(FunkyUtilities)` */ @interface NSMutableArray <ObjectType> (FunkyUtilities) #pragma mark - Flatten /** * Makes the array structure a squence with flat elements, containing no NSArrays * * @see Immutable counterpart `-[NSArray(FunkyUtilities) flattened]` * @see Prefixed counterpart `-[NSMutableArray(FunkyPrefixedUtilities) funky_flatten]` */ - (void)flatten; #pragma mark - Transform /** * Puts the containing items (in place) in a reversed order. * * @see Immutable counterpart `-[NSArray(FunkyUtilities) reversed]` * @see Prefixed counterpart `-[NSMutableArray(FunkyPrefixedUtilities) funky_reverse]` */ - (void)reverse; /** * Shuffles the containing items (in place) in a random fashion. * * @see Immutable counterpart `-[NSArray(FunkyUtilities) shuffled]` * @see Prefixed counterpart `-[NSMutableArray(FunkyPrefixedUtilities) funky_shuffle]` */ - (void)shuffle; /** * Makes the array unique (in place) by removing the duplicated items from the containing items. The method does this keeping the first occurence and removes the further duplications. * It checks equality using the `-isEqual:` method * * @see Immutable counterpart `-[NSArray(FunkyUtilities) unique]` * @see Prefixed counterpart `-[NSMutableArray(FunkyPrefixedUtilities) funky_removeDuplicates]` */ - (void)removeDuplicates; #pragma mark - Merge /** * Concatenates the current array (in place) with the one given in the parameter. It does this by putting the existing elements first, and the elements in the provided array afterwards. * * @param array The other collection to merge with * @see Immutable counterpart `-[NSArray(FunkyUtilities) merged:]` * @see Prefixed counterpart `-[NSMutableArray(FunkyPrefixedUtilities) funky_merge:]` */ - (void)merge:(NSArray<ObjectType>*)array; #pragma mark - Sort /** * Sorts the array (in place) using the given comparator. * * @param comparator An NSComparator block to define the sort order. * @see Immutable counterpart `-[NSArray(FunkyUtilities) sorted:]` * @see Prefixed counterpart `-[NSMutableArray(FunkyPrefixedUtilities) funky_sort:]` */ - (void)sort:(NSComparator)comparator; #pragma mark - Filter /** * Filters the array using the given predicate, keeping the elements that are passing the test. * * @param block The predicate used to filter the results. * @see Immutable counterpart `-[NSArray(FunkyUtilities) filtered:]` * @see Prefixed counterpart `-[NSMutableArray(FunkyPrefixedUtilities) funky_filter:]` */ - (void)filter:(BOOL(^)(ObjectType item))block; #pragma mark - Constructor /** * Creates a mutable array by repeating the same `item` by `repeat` number of times. The size of the array is going to be qual to `repeat`, only consisting of `item` objects. * * @param item The item to repeat * @param repeat Number of times to repeat the `item` parameter * @return A new NSMutableArray instance with the given item repeated * @see Immutable counterpart `+[NSArray(FunkyUtilities) arrayWithItem:repeated:]` * @see Prefixed counterpart `+[NSMutableArray(FunkyPrefixedUtilities) funky_arrayWithItem:repeated:]` */ + (NSMutableArray<ObjectType>*)arrayWithItem:(id)item repeated:(NSUInteger)repeat; /** * Creates a mutable array by taking an initial `array` and computing the next items by repeatedly putting the result of `block` by `repeated` number of times. * * @param array Initial array * @param block The block to compute the next item in the resulting array * @param repeat Number of times to repeat calling the `block` parameter * @return A new NSMutableArray instance with items returned by the block * @see Immutable counterpart `+[NSArray(FunkyUtilities) arrayWithArray:nextItem:repeated:]` * @see Prefixed counterpart `+[NSMutableArray(FunkyPrefixedUtilities) funky_arrayWithArray:nextItem:repeated:]` */ + (NSMutableArray<ObjectType>*)arrayWithArray:(NSArray<ObjectType>*)array nextItem:(id(^)(NSMutableArray* array))block repeated:(NSUInteger)repeat; /** * Creates a mutable array by taking an initial `array` and computing the next items by repeatedly putting the result of `block` by until the block parameter `until` returns YES. * * @param array Initial array * @param block The block to compute the next item in the resulting array * @param until Logic until the iteration should be repeated. Until the block returns YES, the constructor repeatedly callis the `block` parameter * @return A new NSMutableArray instance with items returned by the block * @see Immutable counterpart `+[NSArray(FunkyUtilities) arrayWithArray:nextItem:until:]` * @see Prefixed counterpart `+[NSMutableArray(FunkyPrefixedUtilities) funky_arrayWithArray:nextItem:until:]` */ + (NSMutableArray<ObjectType>*)arrayWithArray:(NSArray<ObjectType>*)array nextItem:(id(^)(NSMutableArray* array))block until:(BOOL(^)(NSArray* array))until; @end
49.555866
351
0.75582
2bc92dcb849ab1d68ec06ee367024e5cbc8a771c
17,016
h
C
rute/qt_cpp/auto/painter_ffi.h
emoon/Rute
b8981fa9fb0508691399b0aa9a565686ebcc0a69
[ "Apache-2.0", "MIT" ]
42
2018-05-04T08:57:57.000Z
2021-11-08T13:05:23.000Z
rute/qt_cpp/auto/painter_ffi.h
emoon/Rute
b8981fa9fb0508691399b0aa9a565686ebcc0a69
[ "Apache-2.0", "MIT" ]
18
2018-05-31T12:11:35.000Z
2021-02-08T04:14:55.000Z
rute/qt_cpp/auto/painter_ffi.h
emoon/ui_gen
b8981fa9fb0508691399b0aa9a565686ebcc0a69
[ "Apache-2.0", "MIT" ]
2
2019-04-17T04:54:15.000Z
2021-03-19T17:38:05.000Z
// This file is auto-generated by rute_gen. DO NOT EDIT! #pragma once #include <stdbool.h> #include <stdint.h> #include "../rute_base.h" #ifdef __cplusplus extern "C" { #endif #include "brush_ffi.h" #include "font_ffi.h" #include "paint_device_ffi.h" #include "paint_engine_ffi.h" #include "pen_ffi.h" #include "point_ffi.h" #include "rect_f_ffi.h" #include "rect_ffi.h" #include "region_ffi.h" #include "transform_ffi.h" struct RUPainterFuncs; struct RUPainter; typedef struct RUPainterFuncs { void (*destroy)(struct RUBase* self); struct RUPaintDevice (*device)(struct RUBase* self_c); bool (*begin)(struct RUBase* self_c, struct RUBase* arg0); bool (*end)(struct RUBase* self_c); bool (*is_active)(struct RUBase* self_c); void (*init_from)(struct RUBase* self_c, struct RUBase* device); void (*set_composition_mode)(struct RUBase* self_c, uint32_t mode); uint32_t (*composition_mode)(struct RUBase* self_c); struct RUFont (*font)(struct RUBase* self_c); void (*set_font)(struct RUBase* self_c, struct RUBase* f); void (*set_pen)(struct RUBase* self_c, struct RUBase* color); void (*set_pen_2)(struct RUBase* self_c, struct RUBase* pen); void (*set_pen_3)(struct RUBase* self_c, uint32_t style); struct RUPen (*pen)(struct RUBase* self_c); void (*set_brush)(struct RUBase* self_c, struct RUBase* brush); void (*set_brush_2)(struct RUBase* self_c, uint32_t style); struct RUBrush (*brush)(struct RUBase* self_c); void (*set_background_mode)(struct RUBase* self_c, uint32_t mode); uint32_t (*background_mode)(struct RUBase* self_c); struct RUPoint (*brush_origin)(struct RUBase* self_c); void (*set_brush_origin)(struct RUBase* self_c, int x, int y); void (*set_brush_origin_2)(struct RUBase* self_c, struct RUBase* arg0); void (*set_brush_origin_3)(struct RUBase* self_c, struct RUBase* arg0); void (*set_background)(struct RUBase* self_c, struct RUBase* bg); struct RUBrush (*background)(struct RUBase* self_c); float (*opacity)(struct RUBase* self_c); void (*set_opacity)(struct RUBase* self_c, float opacity); struct RURegion (*clip_region)(struct RUBase* self_c); void (*set_clip_rect)(struct RUBase* self_c, struct RUBase* arg0, uint32_t op); void (*set_clip_rect_2)(struct RUBase* self_c, struct RUBase* arg0, uint32_t op); void (*set_clip_rect_3)(struct RUBase* self_c, int x, int y, int w, int h, uint32_t op); void (*set_clip_region)(struct RUBase* self_c, struct RUBase* arg0, uint32_t op); void (*set_clipping)(struct RUBase* self_c, bool enable); bool (*has_clipping)(struct RUBase* self_c); struct RURectF (*clip_bounding_rect)(struct RUBase* self_c); void (*save)(struct RUBase* self_c); void (*restore)(struct RUBase* self_c); void (*set_transform)(struct RUBase* self_c, struct RUBase* transform, bool combine); struct RUTransform (*device_transform)(struct RUBase* self_c); void (*reset_transform)(struct RUBase* self_c); void (*set_world_transform)(struct RUBase* self_c, struct RUBase* matrix, bool combine); struct RUTransform (*world_transform)(struct RUBase* self_c); struct RUTransform (*combined_transform)(struct RUBase* self_c); void (*scale)(struct RUBase* self_c, float sx, float sy); void (*shear)(struct RUBase* self_c, float sh, float sv); void (*rotate)(struct RUBase* self_c, float a); struct RURect (*window)(struct RUBase* self_c); void (*set_window)(struct RUBase* self_c, struct RUBase* window); void (*set_window_2)(struct RUBase* self_c, int x, int y, int w, int h); struct RURect (*viewport)(struct RUBase* self_c); void (*set_viewport)(struct RUBase* self_c, struct RUBase* viewport); void (*set_viewport_2)(struct RUBase* self_c, int x, int y, int w, int h); void (*set_view_transform_enabled)(struct RUBase* self_c, bool enable); bool (*view_transform_enabled)(struct RUBase* self_c); void (*draw_point)(struct RUBase* self_c, struct RUBase* pt); void (*draw_point_2)(struct RUBase* self_c, struct RUBase* p); void (*draw_point_3)(struct RUBase* self_c, int x, int y); void (*draw_points)(struct RUBase* self_c, struct RUBase* points, int point_count); void (*draw_points_2)(struct RUBase* self_c, struct RUBase* points); void (*draw_points_3)(struct RUBase* self_c, struct RUBase* points, int point_count); void (*draw_points_4)(struct RUBase* self_c, struct RUBase* points); void (*draw_line)(struct RUBase* self_c, struct RUBase* line); void (*draw_line_2)(struct RUBase* self_c, struct RUBase* line); void (*draw_line_3)(struct RUBase* self_c, int x1, int y1, int x2, int y2); void (*draw_line_4)(struct RUBase* self_c, struct RUBase* p1, struct RUBase* p2); void (*draw_line_5)(struct RUBase* self_c, struct RUBase* p1, struct RUBase* p2); void (*draw_lines)(struct RUBase* self_c, struct RUBase* lines, int line_count); void (*draw_lines_3)(struct RUBase* self_c, struct RUBase* point_pairs, int line_count); void (*draw_lines_7)(struct RUBase* self_c, struct RUBase* point_pairs, int line_count); void (*draw_rect)(struct RUBase* self_c, struct RUBase* rect); void (*draw_rect_2)(struct RUBase* self_c, int x1, int y1, int w, int h); void (*draw_rect_3)(struct RUBase* self_c, struct RUBase* rect); void (*draw_rects)(struct RUBase* self_c, struct RUBase* rects, int rect_count); void (*draw_rects_3)(struct RUBase* self_c, struct RUBase* rects, int rect_count); void (*draw_ellipse)(struct RUBase* self_c, struct RUBase* r); void (*draw_ellipse_2)(struct RUBase* self_c, struct RUBase* r); void (*draw_ellipse_3)(struct RUBase* self_c, int x, int y, int w, int h); void (*draw_ellipse_4)(struct RUBase* self_c, struct RUBase* center, float rx, float ry); void (*draw_ellipse_5)(struct RUBase* self_c, struct RUBase* center, int rx, int ry); void (*draw_polyline)(struct RUBase* self_c, struct RUBase* points, int point_count); void (*draw_polyline_2)(struct RUBase* self_c, struct RUBase* polyline); void (*draw_polyline_3)(struct RUBase* self_c, struct RUBase* points, int point_count); void (*draw_polyline_4)(struct RUBase* self_c, struct RUBase* polygon); void (*draw_polygon)(struct RUBase* self_c, struct RUBase* points, int point_count, uint32_t fill_rule); void (*draw_polygon_2)(struct RUBase* self_c, struct RUBase* polygon, uint32_t fill_rule); void (*draw_polygon_3)(struct RUBase* self_c, struct RUBase* points, int point_count, uint32_t fill_rule); void (*draw_polygon_4)(struct RUBase* self_c, struct RUBase* polygon, uint32_t fill_rule); void (*draw_convex_polygon)(struct RUBase* self_c, struct RUBase* points, int point_count); void (*draw_convex_polygon_2)(struct RUBase* self_c, struct RUBase* polygon); void (*draw_convex_polygon_3)(struct RUBase* self_c, struct RUBase* points, int point_count); void (*draw_convex_polygon_4)(struct RUBase* self_c, struct RUBase* polygon); void (*draw_arc)(struct RUBase* self_c, struct RUBase* rect, int a, int alen); void (*draw_arc_2)(struct RUBase* self_c, struct RUBase* arg0, int a, int alen); void (*draw_arc_3)(struct RUBase* self_c, int x, int y, int w, int h, int a, int alen); void (*draw_pie)(struct RUBase* self_c, struct RUBase* rect, int a, int alen); void (*draw_pie_2)(struct RUBase* self_c, int x, int y, int w, int h, int a, int alen); void (*draw_pie_3)(struct RUBase* self_c, struct RUBase* arg0, int a, int alen); void (*draw_chord)(struct RUBase* self_c, struct RUBase* rect, int a, int alen); void (*draw_chord_2)(struct RUBase* self_c, int x, int y, int w, int h, int a, int alen); void (*draw_chord_3)(struct RUBase* self_c, struct RUBase* arg0, int a, int alen); void (*draw_rounded_rect)(struct RUBase* self_c, struct RUBase* rect, float x_radius, float y_radius, uint32_t mode); void (*draw_rounded_rect_2)(struct RUBase* self_c, int x, int y, int w, int h, float x_radius, float y_radius, uint32_t mode); void (*draw_rounded_rect_3)(struct RUBase* self_c, struct RUBase* rect, float x_radius, float y_radius, uint32_t mode); void (*draw_round_rect)(struct RUBase* self_c, struct RUBase* r, int xround, int yround); void (*draw_round_rect_2)(struct RUBase* self_c, int x, int y, int w, int h, int arg0, int arg1); void (*draw_round_rect_3)(struct RUBase* self_c, struct RUBase* r, int xround, int yround); void (*draw_tiled_pixmap)(struct RUBase* self_c, struct RUBase* rect, struct RUBase* pm, struct RUBase* offset); void (*draw_tiled_pixmap_2)(struct RUBase* self_c, int x, int y, int w, int h, struct RUBase* arg0, int sx, int sy); void (*draw_tiled_pixmap_3)(struct RUBase* self_c, struct RUBase* arg0, struct RUBase* arg1, struct RUBase* arg2); void (*draw_pixmap)(struct RUBase* self_c, struct RUBase* target_rect, struct RUBase* pixmap, struct RUBase* source_rect); void (*draw_pixmap_2)(struct RUBase* self_c, struct RUBase* target_rect, struct RUBase* pixmap, struct RUBase* source_rect); void (*draw_pixmap_3)(struct RUBase* self_c, int x, int y, int w, int h, struct RUBase* pm, int sx, int sy, int sw, int sh); void (*draw_pixmap_4)(struct RUBase* self_c, int x, int y, struct RUBase* pm, int sx, int sy, int sw, int sh); void (*draw_pixmap_5)(struct RUBase* self_c, struct RUBase* p, struct RUBase* pm, struct RUBase* sr); void (*draw_pixmap_6)(struct RUBase* self_c, struct RUBase* p, struct RUBase* pm, struct RUBase* sr); void (*draw_pixmap_7)(struct RUBase* self_c, struct RUBase* p, struct RUBase* pm); void (*draw_pixmap_8)(struct RUBase* self_c, struct RUBase* p, struct RUBase* pm); void (*draw_pixmap_9)(struct RUBase* self_c, int x, int y, struct RUBase* pm); void (*draw_pixmap_10)(struct RUBase* self_c, struct RUBase* r, struct RUBase* pm); void (*draw_pixmap_11)(struct RUBase* self_c, int x, int y, int w, int h, struct RUBase* pm); void (*draw_image)(struct RUBase* self_c, struct RUBase* target_rect, struct RUBase* image, struct RUBase* source_rect, uint32_t flags); void (*draw_image_2)(struct RUBase* self_c, struct RUBase* target_rect, struct RUBase* image, struct RUBase* source_rect, uint32_t flags); void (*draw_image_3)(struct RUBase* self_c, struct RUBase* p, struct RUBase* image, struct RUBase* sr, uint32_t flags); void (*draw_image_4)(struct RUBase* self_c, struct RUBase* p, struct RUBase* image, struct RUBase* sr, uint32_t flags); void (*draw_image_5)(struct RUBase* self_c, struct RUBase* r, struct RUBase* image); void (*draw_image_6)(struct RUBase* self_c, struct RUBase* r, struct RUBase* image); void (*draw_image_7)(struct RUBase* self_c, struct RUBase* p, struct RUBase* image); void (*draw_image_8)(struct RUBase* self_c, struct RUBase* p, struct RUBase* image); void (*draw_image_9)(struct RUBase* self_c, int x, int y, struct RUBase* image, int sx, int sy, int sw, int sh, uint32_t flags); void (*set_layout_direction)(struct RUBase* self_c, uint32_t direction); uint32_t (*layout_direction)(struct RUBase* self_c); void (*draw_text)(struct RUBase* self_c, struct RUBase* p, const char* s); void (*draw_text_2)(struct RUBase* self_c, struct RUBase* p, const char* s); void (*draw_text_3)(struct RUBase* self_c, int x, int y, const char* s); void (*draw_text_4)(struct RUBase* self_c, struct RUBase* p, const char* str, int tf, int justification_padding); void (*draw_text_5)(struct RUBase* self_c, struct RUBase* r, int flags, const char* text, struct RUBase* br); void (*draw_text_6)(struct RUBase* self_c, struct RUBase* r, int flags, const char* text, struct RUBase* br); void (*draw_text_7)(struct RUBase* self_c, int x, int y, int w, int h, int flags, const char* text, struct RUBase* br); struct RURectF (*bounding_rect)(struct RUBase* self_c, struct RUBase* rect, int flags, const char* text); struct RURect (*bounding_rect_2)(struct RUBase* self_c, struct RUBase* rect, int flags, const char* text); struct RURect (*bounding_rect_3)(struct RUBase* self_c, int x, int y, int w, int h, int flags, const char* text); void (*fill_rect)(struct RUBase* self_c, struct RUBase* arg0, struct RUBase* arg1); void (*fill_rect_2)(struct RUBase* self_c, int x, int y, int w, int h, struct RUBase* arg0); void (*fill_rect_3)(struct RUBase* self_c, struct RUBase* arg0, struct RUBase* arg1); void (*fill_rect_4)(struct RUBase* self_c, struct RUBase* arg0, struct RUBase* color); void (*fill_rect_5)(struct RUBase* self_c, int x, int y, int w, int h, struct RUBase* color); void (*fill_rect_6)(struct RUBase* self_c, struct RUBase* arg0, struct RUBase* color); void (*fill_rect_7)(struct RUBase* self_c, int x, int y, int w, int h, uint32_t c); void (*fill_rect_8)(struct RUBase* self_c, struct RUBase* r, uint32_t c); void (*fill_rect_9)(struct RUBase* self_c, struct RUBase* r, uint32_t c); void (*fill_rect_10)(struct RUBase* self_c, int x, int y, int w, int h, uint32_t style); void (*fill_rect_11)(struct RUBase* self_c, struct RUBase* r, uint32_t style); void (*fill_rect_12)(struct RUBase* self_c, struct RUBase* r, uint32_t style); void (*erase_rect)(struct RUBase* self_c, struct RUBase* arg0); void (*erase_rect_2)(struct RUBase* self_c, int x, int y, int w, int h); void (*erase_rect_3)(struct RUBase* self_c, struct RUBase* arg0); void (*set_render_hint)(struct RUBase* self_c, uint32_t hint, bool on); void (*set_render_hints)(struct RUBase* self_c, uint32_t hints, bool on); uint32_t (*render_hints)(struct RUBase* self_c); bool (*test_render_hint)(struct RUBase* self_c, uint32_t hint); struct RUPaintEngine (*paint_engine)(struct RUBase* self_c); void (*set_redirected)(struct RUBase* self_c, struct RUBase* device, struct RUBase* replacement, struct RUBase* offset); struct RUPaintDevice (*redirected)(struct RUBase* self_c, struct RUBase* device, struct RUBase* offset); void (*restore_redirected)(struct RUBase* self_c, struct RUBase* device); void (*begin_native_painting)(struct RUBase* self_c); void (*end_native_painting)(struct RUBase* self_c); } RUPainterFuncs; typedef struct RUPainterAllFuncs { struct RUPainterFuncs* painter_funcs; } RUPainterAllFuncs; typedef struct RUPainter { RUBase* qt_data; RUBase* host_data; struct RUPainterAllFuncs* all_funcs; } RUPainter; extern RUPainterFuncs s_painter_funcs; extern RUPainterAllFuncs s_painter_all_funcs; #ifdef __cplusplus } #endif
56.344371
80
0.616302
2bf7a539ec0ddfdd480d72c6d5b160989d23268b
12,649
c
C
thirdparty/glut/progs/tiff/scalebias.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
null
null
null
thirdparty/glut/progs/tiff/scalebias.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
null
null
null
thirdparty/glut/progs/tiff/scalebias.c
ShiroixD/pag_zad_2
cdb6ccf48402cf4dbf1284827a4e281d3b12a64b
[ "MIT" ]
null
null
null
/* Copyright (c) Mark J. Kilgard, 1997. */ /* This program is freely distributable without licensing fees and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ /* X compile line: cc -o scalebias scalebias.c -ltiff -lglut -lGLU -lGL -lXmu -lXext -lX11 -lm */ /* This program requires Sam Leffler's libtiff library and GLUT. */ /* scalebias demonstrates how an "in place" scale & bias of pixels in the frame buffer can often be accomplished faster with OpenGL blending extensions instead of using the naive glCopyPixels with glPixelTransfer used to do the scale and bias. The blending approach requires the "blend subtract" EXT extension in order to perform negative biases. You could use this approach without the "blend subtract" extension if you never need to do negative biases. NOTE: This blending approach does not allow negative scales. The blending approach also fails if the partial scaling or biasing results leave the 0.0 to 1.0 range (example, scale=5.47, bias=-1.2). This technique can be valuable when you want to perform post-texture filtering scaling and biasing (say for volume rendering or image processing), but your hardware lacks texture lookup tables. To give you an idea of the speed advantage of this "in place" blending technique for doing scales and biases, on an SGI O2, this program runs 8 to 40 times faster with a greater than 1.0 scaling factor when using the blending mode instead of using glCopyPixels. The performance improvement depends on the number of pixels scaled or biased. */ #include <stdlib.h> #include <string.h> #include <math.h> #include <GL/glut.h> #include <tiffio.h> /* Sam Leffler's libtiff library. */ TIFFRGBAImage img; uint32 *raster, *texture; tsize_t npixels; int imgwidth, imgheight; int tw, th; int hasABGR = 0, hasBlendSubtract = 0; int doubleBuffer = 1; char *filename = NULL; int ax = 10, ay = -10; int luminance = 0; int useBlend = 1; int timing = 0; int height; GLfloat scale = 1.0, bias = 0.0, zoom = 1.0; void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, w, 0, h); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); height = h; } void drawImage(void) { glPushMatrix(); glTranslatef(ax, -ay + imgheight * zoom, 0); glScalef(zoom * imgwidth, zoom * imgheight, 1); glBegin(GL_QUADS); glTexCoord2i(0, 0); glVertex2i(0, 0); glTexCoord2i(1, 0); glVertex2i(1, 0); glTexCoord2i(1, -1); glVertex2i(1, -1); glTexCoord2i(0, -1); glVertex2i(0, -1); glEnd(); glPopMatrix(); } void display(void) { int start, end; /* Clear the color buffer. */ glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 1.0, 1.0); /* Modulate texture with white. */ glEnable(GL_TEXTURE_2D); drawImage(); if (timing) { /* Avoid timing the clear and original draw image speed. */ glFinish(); start = glutGet(GLUT_ELAPSED_TIME); } /* Scale and bias via . */ if (bias != 0.0 || scale != 1.0) { glDisable(GL_TEXTURE_2D); /* Other things you might want to make sure are disabled. */ /* glDisable(GL_LIGHTING); */ /* glDisable(GL_DEPTH_TEST); */ if (useBlend && hasBlendSubtract) { /* NOTE: The blending approach does not allow negative scales. The blending approach also fails if the partial scaling or biasing results leave the 0.0 to 1.0 range (example, scale=5.47, bias=-1.2). */ glEnable(GL_BLEND); if (scale > 1.0) { float remainingScale; remainingScale = scale; #ifdef GL_EXT_blend_subtract glBlendEquationEXT(GL_FUNC_ADD_EXT); #endif glBlendFunc(GL_DST_COLOR, GL_ONE); if (remainingScale > 2.0) { /* Clever cascading approach. Example: if the scaling factor was 9.5, do 3 "doubling" blends (8x), then scale by the remaining 1.1875. */ glColor4f(1, 1, 1, 1); while (remainingScale > 2.0) { drawImage(); remainingScale /= 2.0; } } glColor4f(remainingScale - 1, remainingScale - 1, remainingScale - 1, 1); drawImage(); glBlendFunc(GL_ONE, GL_ONE); if (bias != 0) { if (bias > 0) { glColor4f(bias, bias, bias, 0.0); } else { #ifdef GL_EXT_blend_subtract glBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT); #endif glColor4f(-bias, -bias, -bias, 0.0); } drawImage(); } } else { if (bias > 0) { #ifdef GL_EXT_blend_subtract glBlendEquationEXT(GL_FUNC_ADD_EXT); #endif glColor4f(bias, bias, bias, scale); } else { #ifdef GL_EXT_blend_subtract glBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT); #endif glColor4f(-bias, -bias, -bias, scale); } glBlendFunc(GL_ONE, GL_SRC_ALPHA); drawImage(); } glDisable(GL_BLEND); } else { glPixelTransferf(GL_RED_SCALE, scale); glPixelTransferf(GL_GREEN_SCALE, scale); glPixelTransferf(GL_BLUE_SCALE, scale); glPixelTransferf(GL_RED_BIAS, bias); glPixelTransferf(GL_GREEN_BIAS, bias); glPixelTransferf(GL_BLUE_BIAS, bias); glRasterPos2i(0, 0); glBitmap(0, 0, 0, 0, ax, -ay, NULL); glCopyPixels(ax, -ay, ceil(imgwidth * zoom), ceil(imgheight * zoom), GL_COLOR); glPixelTransferf(GL_RED_SCALE, 1.0); glPixelTransferf(GL_GREEN_SCALE, 1.0); glPixelTransferf(GL_BLUE_SCALE, 1.0); glPixelTransferf(GL_RED_BIAS, 0.0); glPixelTransferf(GL_GREEN_BIAS, 0.0); glPixelTransferf(GL_BLUE_BIAS, 0.0); } } if (timing) { glFinish(); end = glutGet(GLUT_ELAPSED_TIME); printf("time = %d milliseconds\n", end - start); } /* Swap the buffers if necessary. */ if (doubleBuffer) { glutSwapBuffers(); } else { glFlush(); } } static int moving = 0, ox, oy; void mouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON) { if (state == GLUT_DOWN) { /* Left mouse button press. Update last seen mouse position. And set "moving" true since button is pressed. */ ox = x; oy = y; moving = 1; } else { /* Left mouse button released; unset "moving" since button no longer pressed. */ moving = 0; } } } void motion(int x, int y) { /* If there is mouse motion with the left button held down. */ if (moving) { /* Figure out offset from the last mouse position seen. */ ax += (x - ox); ay += (y - oy); /* Request a window redraw. */ glutPostRedisplay(); /* Update last seen mouse position. */ ox = x; oy = y; } } void updateTitle(void) { char title[200]; sprintf(title, "Scale (%.2f) & Bias (%.1f) via %s", scale, bias, useBlend ? "Blend" : "Copy"); glutSetWindowTitle(title); } void option(int value) { switch (value) { case 6: bias += 0.1; break; case 7: bias -= 0.1; break; case 8: scale *= 1.1; break; case 9: scale *= 0.9; break; case 10: scale = 1.0; bias = 0.0; break; case 11: if (hasBlendSubtract) { useBlend = 1 - useBlend; } break; case 12: zoom += 0.2; break; case 13: zoom -= 0.2; break; case 14: timing = 1 - timing; break; case 666: exit(0); break; } updateTitle(); glutPostRedisplay(); } /* ARGSUSED1 */ void special(int key, int x, int y) { switch (key) { case GLUT_KEY_UP: option(6); break; case GLUT_KEY_DOWN: option(7); break; case GLUT_KEY_LEFT: option(9); break; case GLUT_KEY_RIGHT: option(8); break; case GLUT_KEY_HOME: option(10); break; case GLUT_KEY_INSERT: option(11); break; case GLUT_KEY_PAGE_UP: option(12); break; case GLUT_KEY_PAGE_DOWN: option(13); break; } } int main(int argc, char **argv) { TIFF *tif; char emsg[1024]; int i; glutInit(&argc, argv); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-sb")) { doubleBuffer = 0; } else { filename = argv[i]; } } if (filename == NULL) { fprintf(stderr, "usage: scalebias [GLUT-options] [-sb] TIFF-file\n"); exit(1); } tif = TIFFOpen(filename, "r"); if (tif == NULL) { fprintf(stderr, "Problem showing %s\n", filename); exit(1); } if (TIFFRGBAImageBegin(&img, tif, 0, emsg)) { npixels = (tsize_t) (img.width * img.height); raster = (uint32 *) _TIFFmalloc(npixels * (tsize_t) sizeof(uint32)); if (raster != NULL) { if (TIFFRGBAImageGet(&img, raster, img.width, img.height) == 0) { TIFFError(filename, emsg); exit(1); } } TIFFRGBAImageEnd(&img); } else { TIFFError(filename, emsg); exit(1); } if (doubleBuffer) { glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); } else { glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); } imgwidth = (int) img.width; imgheight = (int) img.height; glutInitWindowSize(imgwidth * 1.5, imgheight * 1.5); glutCreateWindow(""); glutReshapeFunc(reshape); glutDisplayFunc(display); glutMouseFunc(mouse); glutMotionFunc(motion); glutSpecialFunc(special); #ifdef GL_EXT_abgr if (glutExtensionSupported("GL_EXT_abgr")) { hasABGR = 1; } #endif #ifdef GL_EXT_blend_subtract if (glutExtensionSupported("GL_EXT_blend_subtract")) { hasBlendSubtract = 1; } #endif if (!hasBlendSubtract) { printf("\nThis program needs the blend subtract extension for\n"); printf("fast blending-base in-place scaling & biasing. Since\n"); printf("the extension is not available, using the slower\n"); printf("glCopyPixels approach.\n\n"); useBlend = 0; } /* If cannot directly display ABGR format, we need to reverse the component ordering in each pixel. :-( */ if (!hasABGR) { int i; for (i = 0; i < npixels; i++) { register unsigned char *cp = (unsigned char *) &raster[i]; int t; t = cp[3]; cp[3] = cp[0]; cp[0] = t; t = cp[2]; cp[2] = cp[1]; cp[1] = t; } } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* Linear sampling within a mipmap level. */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); /* A TIFF file could be any size; OpenGL textures are allowed to have a width and height that is a power of two (32, 64, 128, etc.). To maximize the use of available texture memory, we scale the image to gluScaleImage to the next larger power of 2 width or height dimension (not exceeding 512, don't want to use too much texture memory!). This rescaling can result in a bit of image bluring because of the resampling done by gluScaleImage. An alternative would be to change the texture coordinates to only use a portion texture area. */ tw = 1 << (int) ceil(log(img.width) / log(2.0)); th = 1 << (int) ceil(log(img.height) / log(2.0)); if (tw > 512) tw = 512; if (th > 512) th = 512; texture = (uint32 *) malloc(sizeof(GLubyte) * 4 * tw * th); #ifdef GL_EXT_abgr #define APPROPRIATE_FORMAT (hasABGR ? GL_ABGR_EXT : GL_RGBA) #else #define APPROPRIATE_FORMAT GL_RGBA #endif gluScaleImage(APPROPRIATE_FORMAT, (GLsizei) img.width, (GLsizei) img.height, GL_UNSIGNED_BYTE, raster, tw, th, GL_UNSIGNED_BYTE, texture); /* Build mipmaps for the texture image. Since we are not scaling the image (we easily could by calling glScalef), creating mipmaps is not really useful, but it is done just to show how easily creating mipmaps is. */ gluBuild2DMipmaps(GL_TEXTURE_2D, 4, tw, th, APPROPRIATE_FORMAT, GL_UNSIGNED_BYTE, texture); glutCreateMenu(option); glutAddMenuEntry("Increase bias (Up)", 6); glutAddMenuEntry("Decrease bias (Down)", 7); glutAddMenuEntry("Increase scale (Right)", 8); glutAddMenuEntry("Decrease scale (Left)", 9); glutAddMenuEntry("Reset scale & bias (Home)", 10); if (hasBlendSubtract) { glutAddMenuEntry("Toggle blend/copy (Insert)", 11); } glutAddMenuEntry("Zoom up (PageUp)", 12); glutAddMenuEntry("Zoom down (PageDown)", 13); glutAddMenuEntry("Toggle timing", 14); glutAddMenuEntry("Quit", 666); glutAttachMenu(GLUT_RIGHT_BUTTON); /* Use a gray background so TIFF images with black backgrounds will show against textiff's background. */ glClearColor(0.2, 0.2, 0.2, 1.0); updateTitle(); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
26.188406
97
0.635702
f39ac3ecf8e03e8d33624da79c58c6ba91c8f752
1,015
c
C
waitPIDTest.c
wsull001/ourXv6
3c3688e741248e2edc029d5d3f2c12601e1e04b9
[ "MIT-0" ]
null
null
null
waitPIDTest.c
wsull001/ourXv6
3c3688e741248e2edc029d5d3f2c12601e1e04b9
[ "MIT-0" ]
null
null
null
waitPIDTest.c
wsull001/ourXv6
3c3688e741248e2edc029d5d3f2c12601e1e04b9
[ "MIT-0" ]
null
null
null
#include "types.h" #include "stat.h" #include "user.h" #include "fs.h" int main(int argc, char** argv) { int p1 = fork(); if(p1 == 0) { printf(1, "Process 1 returns: %d\n", 3); exit(3); } int p2 = fork(); if (p2 == 0) { printf(1, "Process 2 returns: %d\n", 4); exit(4); } int p3 = fork(); if (p3 == 0) { printf(1, "Process 3 returns: %d\n", 5); exit(5); } printf(1, "Wait for process three, identified by return of 5:\n"); int status; //to keep track of each process's return status and print waitpid(p3, &status, 0); printf(1, "exit status: %d\n", status); printf(1, "\nWait for process two, identified by return of 4:\n"); waitpid(p2, &status, 0); printf(1, "exit status: %d\n", status); int t = waitpid(p2, &status, 0); printf(1, "Should return -1 because p2 has already been collected: %d\n", t); printf(1, "\nWait for process one, identified by return of 3:\n"); waitpid(p1, &status, 0); printf(1, "exit status: %d\n", status); exit(0); }
26.710526
79
0.591133
1ab0b23d162cc02a9bdf877ddce48c2787493caa
562
h
C
MCAlbum/Code/Vender/GCD/GCDTimer.h
poholo/MCAlbum
4d7a2e8fbdf2e293360364cba89724523ae1d29e
[ "MIT" ]
1
2018-12-06T01:48:33.000Z
2018-12-06T01:48:33.000Z
MCAlbum/Code/Vender/GCD/GCDTimer.h
poholo/MCAlbum
4d7a2e8fbdf2e293360364cba89724523ae1d29e
[ "MIT" ]
1
2021-09-29T03:06:42.000Z
2021-09-29T03:06:42.000Z
MCAlbum/Code/Vender/GCD/GCDTimer.h
poholo/MCAlbum
4d7a2e8fbdf2e293360364cba89724523ae1d29e
[ "MIT" ]
null
null
null
// // GCD // Reservation // // Created by 江明 赵 on 8/25/14. // Copyright (c) 2014 江明 赵. All rights reserved. // #import <Foundation/Foundation.h> @class GCDQueue; @interface GCDTimer : NSObject @property(strong, readonly, nonatomic) dispatch_source_t dispatchSource; #pragma 初始化 - (instancetype)init; - (instancetype)initInQueue:(GCDQueue *)queue; #pragma mark - 用法 - (void)event:(dispatch_block_t)block timeInterval:(uint64_t)interval; - (void)event:(dispatch_block_t)block timeIntervalWithSecs:(float)secs; - (void)start; - (void)destroy; @end
16.529412
72
0.724199
063e8e0f5ab7c284f6269466655fa0dcf74786b0
1,167
h
C
include/bteifgl_net.h
cr88192/bgbtech_engine2
e6c0e11f0b70ac8544895a10133a428d5078d413
[ "MIT" ]
1
2016-12-28T05:46:24.000Z
2016-12-28T05:46:24.000Z
include/bteifgl_net.h
cr88192/bgbtech_engine2
e6c0e11f0b70ac8544895a10133a428d5078d413
[ "MIT" ]
null
null
null
include/bteifgl_net.h
cr88192/bgbtech_engine2
e6c0e11f0b70ac8544895a10133a428d5078d413
[ "MIT" ]
null
null
null
#ifndef BTEIFGL_NET_H #define BTEIFGL_NET_H typedef struct { byte data1[4]; byte data2[2]; byte data3[2]; byte data4[8]; }VGUID; #define PROTO_IPV4 (1<<8) #define PROTO_IPV6 (2<<8) #define PROTO_TCP 1 #define PROTO_UDP 2 #define PROTO_UNDEFINED 0 #define PROTO_IPV4UDP (PROTO_IPV4|PROTO_UDP) #define PROTO_IPV4TCP (PROTO_IPV4|PROTO_TCP) #define PROTO_IPV6UDP (PROTO_IPV6|PROTO_UDP) #define PROTO_IPV6TCP (PROTO_IPV6|PROTO_TCP) /* these may be loaded in the lower 8 flag bits for send and similar */ #define PROTO_PF_UNDEFINED 0 #define PROTO_PF_IPV4 4 #define PROTO_PF_TCP 6 #define PROTO_PF_UDP 17 #define PROTO_PF_IPV6 41 #define PROTO_PF_IPV6ROUTE 43 #define PROTO_PF_IPV6FRAG 44 #define PROTO_PF_IPV6ICMP 58 #define PROTO_PF_IPV6NONXT 59 #define PROTO_PF_IPV6OPTS 60 typedef union VADDR_u VADDR; union VADDR_u { int proto; struct { int proto; int flags; /* lower 8 bits=netmask count */ unsigned short port; unsigned long addr; }ipv4; struct { int proto; int flags; /* lower 8 bits=netmask count */ unsigned short port; byte addr[16]; }ipv6; }; typedef struct { VGUID nodeid; VADDR addr; u32 nodefl; int id; }BTEIFGL_PeerInfo; #endif
18.234375
71
0.762639
d26d33d4b3f6d21d9515df1bb3c5a19d2f6a4aee
290
c
C
src/cmd/map/libmap/azequidist.c
newluhux/plan9port
f403539d479c1ecb60988e6d87f9031b1435f794
[ "MIT" ]
1,391
2015-01-02T22:15:05.000Z
2022-03-31T04:53:12.000Z
src/cmd/map/libmap/azequidist.c
Acidburn0zzz/plan9port
da8a485fc143aa323845fafcf0f0f836c76a116b
[ "LPL-1.02" ]
441
2015-01-03T07:11:09.000Z
2022-03-31T13:12:22.000Z
src/cmd/map/libmap/azequidist.c
Acidburn0zzz/plan9port
da8a485fc143aa323845fafcf0f0f836c76a116b
[ "LPL-1.02" ]
404
2015-01-03T13:00:57.000Z
2022-03-18T09:43:37.000Z
#include <u.h> #include <libc.h> #include "map.h" int Xazequidistant(struct place *place, double *x, double *y) { double colat; colat = PI/2 - place->nlat.l; *x = -colat * place->wlon.s; *y = -colat * place->wlon.c; return(1); } proj azequidistant(void) { return(Xazequidistant); }
14.5
57
0.648276
9a9e44fb1a5eb1582a20a7c447e1304b9cdcc968
1,790
h
C
stonne/include/MultiplierNetwork.h
AndreasKaratzas/stonne
2915fcc46cc94196303d81abbd1d79a56d6dd4a9
[ "MIT" ]
40
2021-06-01T07:37:59.000Z
2022-03-25T01:42:09.000Z
stonne/include/MultiplierNetwork.h
AndreasKaratzas/stonne
2915fcc46cc94196303d81abbd1d79a56d6dd4a9
[ "MIT" ]
14
2021-06-01T11:52:46.000Z
2022-03-25T02:13:08.000Z
stonne/include/MultiplierNetwork.h
AndreasKaratzas/stonne
2915fcc46cc94196303d81abbd1d79a56d6dd4a9
[ "MIT" ]
7
2021-07-20T19:34:26.000Z
2022-03-13T21:07:36.000Z
#ifndef __MULTIPLIERNETWORK__H__ #define __MULTIPLIERNETWORK__H__ #include "Connection.h" #include "MSwitch.h" #include "DSwitch.h" #include "Unit.h" #include <iostream> #include "CompilerMSN.h" #include "Tile.h" #include "DNNLayer.h" #include <assert.h> #include <map> class MultiplierNetwork : public Unit{ public: /* By the default the implementation of the MS just receives a single element, calculate a single psum and/or send a single input activation to the neighbour. This way, the parameters input_ports, output_ports and forwarding_ports will be set as the single data size. If this implementation change for future tests, this can be change easily bu mofifying these three parameters. */ MultiplierNetwork(id_t id, std::string name) : Unit(id, name){} //set connections from the distribution network to the multiplier network virtual void setInputConnections(std::map<int, Connection*> input_connections) {assert(false);} //Set connections from the Multiplier Network to the Reduction Network virtual void setOutputConnections(std::map<int, Connection*> output_connections) {assert(false);} virtual void cycle() {assert(false);} virtual void configureSignals(Tile* current_tile, DNNLayer* dnn_layer, unsigned int ms_size, unsigned int n_folding) {assert(false);} virtual void configureSparseSignals(std::vector<SparseVN> sparseVNs, DNNLayer* dnn_layer, unsigned int ms_size) {assert(false);} virtual void resetSignals() {assert(false);} virtual void printConfiguration(std::ofstream& out, unsigned int indent) {assert(false);} virtual void printStats(std::ofstream &out, unsigned int indent) {assert(false);} virtual void printEnergy(std::ofstream& out, unsigned int indent) {assert(false);} }; #endif
47.105263
201
0.756425
9aab427dee22463d6572bd34fc97aebf16e362af
6,756
h
C
qt-creator-opensource-src-4.6.1/src/shared/qbs/src/lib/corelib/buildgraph/buildgraphloader.h
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
Src/shared/qbs/src/lib/corelib/buildgraph/buildgraphloader.h
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
null
null
null
Src/shared/qbs/src/lib/corelib/buildgraph/buildgraphloader.h
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QBS_BUILDGRAPHLOADER_H #define QBS_BUILDGRAPHLOADER_H #include "forward_decls.h" #include "artifact.h" #include "rescuableartifactdata.h" #include <language/forward_decls.h> #include <logging/logger.h> #include <tools/setupprojectparameters.h> #include <QtCore/qprocess.h> #include <QtCore/qvariant.h> namespace qbs { namespace Internal { class FileDependency; class FileResourceBase; class FileTime; class Property; class BuildGraphLoadResult { public: TopLevelProjectPtr newlyResolvedProject; TopLevelProjectPtr loadedProject; }; class BuildGraphLoader { public: BuildGraphLoader(const Logger &logger); ~BuildGraphLoader(); BuildGraphLoadResult load(const TopLevelProjectPtr &existingProject, const SetupProjectParameters &parameters, const RulesEvaluationContextPtr &evalContext); static TopLevelProjectConstPtr loadProject(const QString &bgFilePath); private: void loadBuildGraphFromDisk(); bool checkBuildGraphCompatibility(const TopLevelProjectConstPtr &project); void trackProjectChanges(); bool probeExecutionForced(const TopLevelProjectConstPtr &restoredProject, const QList<ResolvedProductPtr> &restoredProducts) const; bool hasEnvironmentChanged(const TopLevelProjectConstPtr &restoredProject) const; bool hasCanonicalFilePathResultChanged(const TopLevelProjectConstPtr &restoredProject) const; bool hasFileExistsResultChanged(const TopLevelProjectConstPtr &restoredProject) const; bool hasDirectoryEntriesResultChanged(const TopLevelProjectConstPtr &restoredProject) const; bool hasFileLastModifiedResultChanged(const TopLevelProjectConstPtr &restoredProject) const; bool hasProductFileChanged(const QList<ResolvedProductPtr> &restoredProducts, const FileTime &referenceTime, Set<QString> &remainingBuildSystemFiles, QList<ResolvedProductPtr> &productsWithChangedFiles); bool hasBuildSystemFileChanged(const Set<QString> &buildSystemFiles, const FileTime &referenceTime); void checkAllProductsForChanges(const QList<ResolvedProductPtr> &restoredProducts, const QMap<QString, ResolvedProductPtr> &newlyResolvedProductsByName, QList<ResolvedProductPtr> &changedProducts); bool checkProductForChanges(const ResolvedProductPtr &restoredProduct, const ResolvedProductPtr &newlyResolvedProduct); bool checkProductForInstallInfoChanges(const ResolvedProductPtr &restoredProduct, const ResolvedProductPtr &newlyResolvedProduct); bool checkForPropertyChanges(const ResolvedProductPtr &restoredProduct, const ResolvedProductPtr &newlyResolvedProduct); bool checkTransformersForChanges(const ResolvedProductPtr &restoredProduct, const ResolvedProductPtr &newlyResolvedProduct); void onProductRemoved(const ResolvedProductPtr &product, ProjectBuildData *projectBuildData, bool removeArtifactsFromDisk = true); bool checkForPropertyChanges(const TransformerPtr &restoredTrafo, const ResolvedProductPtr &freshProduct); bool checkForEnvChanges(const TransformerPtr &restoredTrafo); bool checkForPropertyChange(const Property &restoredProperty, const QVariantMap &newProperties); void replaceFileDependencyWithArtifact(const ResolvedProductPtr &fileDepProduct, FileDependency *filedep, Artifact *artifact); bool checkConfigCompatibility(); struct ChildrenInfo { ChildrenInfo() {} ChildrenInfo(const ArtifactSet &c1, const ArtifactSet &c2) : children(c1), childrenAddedByScanner(c2) {} ArtifactSet children; ArtifactSet childrenAddedByScanner; }; typedef QHash<const Artifact *, ChildrenInfo> ChildListHash; void rescueOldBuildData(const ResolvedProductConstPtr &restoredProduct, const ResolvedProductPtr &newlyResolvedProduct, const ChildListHash &childLists, const AllRescuableArtifactData &existingRad); RulesEvaluationContextPtr m_evalContext; SetupProjectParameters m_parameters; BuildGraphLoadResult m_result; Logger m_logger; QStringList m_artifactsRemovedFromDisk; qint64 m_wildcardExpansionEffort; qint64 m_propertyComparisonEffort; // These must only be deleted at the end so we can still peek into the old look-up table. QList<FileResourceBase *> m_objectsToDelete; bool m_envChange = false; }; } // namespace Internal } // namespace qbs #endif // Include guard.
44.447368
97
0.713884
3c181c29344037cca8d9ccc62d2d53096453a347
6,087
h
C
dynet/sig.h
allenai/dynet
d1a754641cf712c418a338d7eecf9465d2ec52f2
[ "Apache-2.0" ]
1
2021-05-26T22:28:06.000Z
2021-05-26T22:28:06.000Z
dynet/sig.h
allenai/dynet
d1a754641cf712c418a338d7eecf9465d2ec52f2
[ "Apache-2.0" ]
26
2017-01-09T17:02:11.000Z
2018-09-27T10:43:14.000Z
dynet/sig.h
allenai/dynet
d1a754641cf712c418a338d7eecf9465d2ec52f2
[ "Apache-2.0" ]
2
2016-11-14T18:30:50.000Z
2018-01-15T16:03:57.000Z
#ifndef DYNET_SIG_H #define DYNET_SIG_H #define DYNET_MAX_SIG 100 #include <unordered_map> #include <map> namespace dynet { namespace nt { enum NodeType { tanh=1, sqrt, abs, erf, square, cube, exp, loggamma, log, nobackprop, flipgradient, identity, negate, rectify, logistic, softsign, plus_const, concat, cmult, sum, squared_distance, softmax, pnls, pickrange, scalar_mult, input, scalar_input, lookup, COMPLEX, affine, matmul, vanilla_lstm_gates, vanilla_lstm_h, vanilla_lstm_c, }; } struct SigYoav { SigYoav(short which) : which(which), nn(0), nd(0) { } SigYoav() : which(0), nn(0), nd(0) { } const unsigned short which; unsigned short nn; unsigned short nd; Dim dims[10]; unsigned node_ids[10]; void add_node(unsigned i) { node_ids[nn++]=i; } // TODO add_dim is NOT SAME as dim.print_profile(oss) void add_dim(const Dim &d) { dims[nd++]=d; } }; inline bool operator==(const SigYoav& a, const SigYoav& b) { if (a.which == b.which && a.nn == b.nn && a.nd == b.nd) { for (int i = 0; i < a.nn; ++i) { if (a.node_ids[i] != b.node_ids[i]) return false; } for (int i = 0; i < a.nd; ++i) { if (a.dims[i] != b.dims[i]) return false; } return true; } else { return false; } } struct SigString { SigString(int which) : which(which), tail(data) { } SigString() : which(0), tail(data) { } int which; int data[DYNET_MAX_SIG]; int* tail; void add_node(unsigned i) { *(tail++) = -(int)i; } void add_dim(const Dim &d) { *(tail++) = -(int)d.nd; memcpy(tail, d.d, d.nd * sizeof(unsigned int)); tail += d.nd; /* * sizeof(unsigned int) / sizeof(int) */ } }; inline bool operator<(const SigString& a, const SigString& b) { if(a.which != b.which) return a.which < b.which; ptrdiff_t a_size = (ptrdiff_t)(a.tail - a.data), b_size = (ptrdiff_t)(b.tail - b.data); if(a_size != b_size) return a_size < b_size; return memcmp(a.data, b.data, a_size * sizeof(int)) < 0; } inline bool operator==(const SigString& a, const SigString& b) { if(a.which != b.which) return false; ptrdiff_t a_size = a.tail - a.data; if(a_size != (ptrdiff_t)(b.tail - b.data)) return false; return memcmp(a.data, b.data, a_size * sizeof(int)) == 0; } inline bool operator!=(const SigString& a, const SigString& b) { return !(a == b); } struct SigHash { SigHash(int which) : hash((int)0xcc9e2d51 ^ which), which(which) { } SigHash() : hash((int)0xcc9e2d51a), which(0) { } int hash; int which; // sbdm hash inline void add_int(int i) { hash = i + (hash << 6) + (hash << 16) - hash; } inline void add_float(float i) { assert(sizeof(int) >= sizeof(float)); int temp_val = 0; memcpy(&temp_val, &i, sizeof(float)); hash = temp_val + (hash << 6) + (hash << 16) - hash; } void add_node(unsigned i) { add_int((int)i); } void add_dim(const Dim &d) { add_int(-(int)d.nd); for(size_t i = 0; i < d.nd; ++i) add_int((int)d.d[i]); } }; inline bool operator<(const SigHash& a, const SigHash& b) { return a.hash < b.hash; } inline bool operator==(const SigHash& a, const SigHash& b) { return a.hash == b.hash; } inline bool operator!=(const SigHash& a, const SigHash& b) { return a.hash != b.hash; } template <class Sig> struct SigLinearMap { SigLinearMap() { sigs.reserve(50); whiches.reserve(50); Sig s; sigs.push_back(s); whiches.push_back(s.which); } int get_idx(Sig &s) { for (unsigned i=0; i<sigs.size(); ++i) { if (sigs[i]==s) return i; } sigs.push_back(s); whiches.push_back(s.which); return sigs.size()-1; } int sig2type(int sig) { return whiches[sig]; } int size() { return sigs.size(); } std::vector<Sig> sigs; std::vector<int> whiches; }; template <class Sig> struct SigLinearSortedMap { SigLinearSortedMap() : sorted(false), found(0) { sigs.reserve(50); whiches.reserve(50); Sig s; sigs.push_back(std::pair<Sig,int>(s,0)); whiches.push_back(s.which); } int get_idx(Sig &s) { if (sorted) { // search and return auto loc = std::lower_bound(sigs.begin(), sigs.end(), std::pair<Sig, int>(s,0), [](const std::pair<Sig, int> &s1, const std::pair<Sig, int> &s2) { return s1.first<s2.first; }); if (loc != sigs.end() && loc->first==s) { return loc->second; } // not found, continue to add. } else { // linear scan for (unsigned i=0; i<sigs.size(); ++i) { if (sigs[i].first==s) { const int res=sigs[i].second; found++; if (found > 50 && !sorted) sort(); return res; } } } found=0; sorted=false; sigs.push_back(std::pair<Sig, int>(s, (int)sigs.size())); whiches.push_back(s.which); return (int)sigs.size()-1; } void clear() { sigs.clear(); whiches.clear(); sorted=false; } void sort() { if (sorted) { return; } std::sort(sigs.begin(), sigs.end(), [](std::pair<Sig, int> s1, std::pair<Sig, int> s2) {return s1.first < s2.first;}); sorted=true; } int sig2type(int sig) { return whiches[sig]; } int size() { return sigs.size(); } std::vector<std::pair<Sig,int> > sigs; std::vector<int> whiches; bool sorted; int found; }; struct SigHasher { size_t operator()(const SigHash& k) const { return k.hash; } }; template <class Sig> struct SigTreeMap { SigTreeMap() { } int get_idx(Sig &s) { auto it = sigs.find(s); if(it != sigs.end()) return it->second; sigs.insert(std::make_pair(s, (int)sigs.size())); return sigs.size()-1; } int size() { return sigs.size(); } std::map<Sig, int> sigs; }; template <class Sig> struct SigHashMap { SigHashMap() { sigs.reserve(50); } int get_idx(Sig &s) { auto it = sigs.find(s); if(it != sigs.end()) return it->second; sigs.insert(std::make_pair(s, (int)sigs.size())); return sigs.size()-1; } int size() { return sigs.size(); } std::unordered_map<Sig, int, SigHasher> sigs; }; typedef SigHash Sig; //typedef SigLinearMap<Sig> SigMap; typedef SigLinearSortedMap<Sig> SigMap; } // namespace dynet #endif
28.985714
182
0.608839
d29bc7a405ad57fb768343aec83aa05da14306a3
687
c
C
d/attaya/seneca/road39.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/attaya/seneca/road39.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/attaya/seneca/road39.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> #include "short.h" inherit CITYOUT; void create() { ::create(); set_terrain(CITY); set_travel(PAVED_ROAD); set_property("light", 2); set_short("North Road in Seneca"); set_long( @DESC This is the North Road that leads around the edge of the city of Seneca. Made from cobblestone, the stone surface of the street has stood up to a lot of wear. The yard outside the %^CYAN%^Bank%^RESET%^ is to the south. DESC ); set_items( ([ "cobblestones" : "These are cobblestones.", ]) ); set_exits( ([ "east" : "/d/attaya/seneca/street1", "west" : "/d/attaya/seneca/road38", "south" : "/d/attaya/seneca/bankyard" ]) ); }
23.689655
57
0.637555
c5d80ab26eba86aa6e1351970e4cff11a2c63ea6
5,591
h
C
VTKHeaders/vtkGenericCell.h
jmah/OsiriX-Quad-Buffered-Stereo
096491358a5d4d8a0928dc03d7183ec129720c56
[ "MIT", "Unlicense" ]
2
2017-07-11T15:00:45.000Z
2017-08-09T15:44:22.000Z
VTKHeaders/vtkGenericCell.h
jmah/OsiriX-Quad-Buffered-Stereo
096491358a5d4d8a0928dc03d7183ec129720c56
[ "MIT", "Unlicense" ]
null
null
null
VTKHeaders/vtkGenericCell.h
jmah/OsiriX-Quad-Buffered-Stereo
096491358a5d4d8a0928dc03d7183ec129720c56
[ "MIT", "Unlicense" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkGenericCell.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkGenericCell - provides thread-safe access to cells // .SECTION Description // vtkGenericCell is a class that provides access to concrete types of cells. // It's main purpose is to allow thread-safe access to cells, supporting // the vtkDataSet::GetCell(vtkGenericCell *) method. vtkGenericCell acts // like any type of cell, it just dereferences an internal representation. // The SetCellType() methods use #define constants; these are defined in // the file vtkCellType.h. // .SECTION See Also // vtkCell vtkDataSet #ifndef __vtkGenericCell_h #define __vtkGenericCell_h #include "vtkCell.h" class VTK_FILTERING_EXPORT vtkGenericCell : public vtkCell { public: // Description: // Create handle to any type of cell; by default a vtkEmptyCell. static vtkGenericCell *New(); vtkTypeRevisionMacro(vtkGenericCell,vtkCell); void PrintSelf(ostream& os, vtkIndent indent); // Description: // See the vtkCell API for descriptions of these methods. void ShallowCopy(vtkCell *c); void DeepCopy(vtkCell *c); int GetCellType(); int GetCellDimension(); int IsLinear(); int RequiresInitialization(); void Initialize(); int GetNumberOfEdges(); int GetNumberOfFaces(); vtkCell *GetEdge(int edgeId); vtkCell *GetFace(int faceId); int CellBoundary(int subId, double pcoords[3], vtkIdList *pts); int EvaluatePosition(double x[3], double* closestPoint, int& subId, double pcoords[3], double& dist2, double *weights); void EvaluateLocation(int& subId, double pcoords[3], double x[3], double *weights); void Contour(double value, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *verts, vtkCellArray *lines, vtkCellArray *polys, vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd); void Clip(double value, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *connectivity, vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd, int insideOut); int IntersectWithLine(double p1[3], double p2[3], double tol, double& t, double x[3], double pcoords[3], int& subId); int Triangulate(int index, vtkIdList *ptIds, vtkPoints *pts); void Derivatives(int subId, double pcoords[3], double *values, int dim, double *derivs); int GetParametricCenter(double pcoords[3]); double *GetParametricCoords(); int IsPrimaryCell(); // Description: // This method is used to support the vtkDataSet::GetCell(vtkGenericCell *) // method. It allows vtkGenericCell to act like any cell type by // dereferencing an internal instance of a concrete cell type. When // you set the cell type, you are resetting a pointer to an internal // cell which is then used for computation. void SetCellType(int cellType); void SetCellTypeToEmptyCell() {this->SetCellType(VTK_EMPTY_CELL);} void SetCellTypeToVertex() {this->SetCellType(VTK_VERTEX);} void SetCellTypeToPolyVertex() {this->SetCellType(VTK_POLY_VERTEX);} void SetCellTypeToLine() {this->SetCellType(VTK_LINE);} void SetCellTypeToPolyLine() {this->SetCellType(VTK_POLY_LINE);} void SetCellTypeToTriangle() {this->SetCellType(VTK_TRIANGLE);} void SetCellTypeToTriangleStrip() {this->SetCellType(VTK_TRIANGLE_STRIP);} void SetCellTypeToPolygon() {this->SetCellType(VTK_POLYGON);} void SetCellTypeToPixel() {this->SetCellType(VTK_PIXEL);} void SetCellTypeToQuad() {this->SetCellType(VTK_QUAD);} void SetCellTypeToTetra() {this->SetCellType(VTK_TETRA);} void SetCellTypeToVoxel() {this->SetCellType(VTK_VOXEL);} void SetCellTypeToHexahedron() {this->SetCellType(VTK_HEXAHEDRON);} void SetCellTypeToWedge() {this->SetCellType(VTK_WEDGE);} void SetCellTypeToPyramid() {this->SetCellType(VTK_PYRAMID);} void SetCellTypeToPentagonalPrism() {this->SetCellType(VTK_PENTAGONAL_PRISM);} void SetCellTypeToHexagonalPrism() {this->SetCellType(VTK_HEXAGONAL_PRISM);} void SetCellTypeToConvexPointSet() {this->SetCellType(VTK_CONVEX_POINT_SET);} void SetCellTypeToQuadraticEdge() {this->SetCellType(VTK_QUADRATIC_EDGE);} void SetCellTypeToQuadraticTriangle() {this->SetCellType(VTK_QUADRATIC_TRIANGLE);} void SetCellTypeToQuadraticQuad() {this->SetCellType(VTK_QUADRATIC_QUAD);} void SetCellTypeToQuadraticTetra() {this->SetCellType(VTK_QUADRATIC_TETRA);} void SetCellTypeToQuadraticHexahedron() {this->SetCellType(VTK_QUADRATIC_HEXAHEDRON);} void SetCellTypeToQuadraticWedge() {this->SetCellType(VTK_QUADRATIC_WEDGE);} void SetCellTypeToQuadraticPyramid() {this->SetCellType(VTK_QUADRATIC_PYRAMID);} protected: vtkGenericCell(); ~vtkGenericCell(); vtkCell *Cell; private: vtkGenericCell(const vtkGenericCell&); // Not implemented. void operator=(const vtkGenericCell&); // Not implemented. }; #endif
44.023622
88
0.717045
cf38f7863aee7eef92620011ef48f319c29461a6
34,102
h
C
cocos3d/cocos3d/Nodes/CC3Light.h
apportable/cocos3d
ea51fe4261f0314e5224ce4ce8cc51071f9a6b8a
[ "MIT" ]
null
null
null
cocos3d/cocos3d/Nodes/CC3Light.h
apportable/cocos3d
ea51fe4261f0314e5224ce4ce8cc51071f9a6b8a
[ "MIT" ]
null
null
null
cocos3d/cocos3d/Nodes/CC3Light.h
apportable/cocos3d
ea51fe4261f0314e5224ce4ce8cc51071f9a6b8a
[ "MIT" ]
null
null
null
/* * CC3Light.h * * cocos3d 2.0.0 * Author: Bill Hollings * Copyright (c) 2010-2013 The Brenwill Workshop Ltd. All rights reserved. * http://www.brenwill.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://en.wikipedia.org/wiki/MIT_License */ /** @file */ // Doxygen marker #import "CC3Node.h" #import "CC3MeshNode.h" @protocol CC3ShadowProtocol; @class CC3ShadowCastingVolume, CC3CameraShadowVolume, CC3StencilledShadowPainterNode; /** Constant indicating that the light is not directional. */ static const GLfloat kCC3SpotCutoffNone = 180.0f; /** Default ambient light color. */ static const ccColor4F kCC3DefaultLightColorAmbient = { 0.0, 0.0, 0.0, 1.0 }; /** Default diffuse light color. */ static const ccColor4F kCC3DefaultLightColorDiffuse = { 1.0, 1.0, 1.0, 1.0 }; /** Default specular light color. */ static const ccColor4F kCC3DefaultLightColorSpecular = { 1.0, 1.0, 1.0, 1.0 }; /** Default light attenuation coefficients */ static const CC3AttenuationCoefficients kCC3DefaultLightAttenuationCoefficients = {1.0, 0.0, 0.0}; #pragma mark - #pragma mark CC3Light /** * CC3Light represents the light in the 3D scene. * * CC3Light is a type of CC3Node, and can therefore participate in a structural node * assembly. An instance can be the child of another node, and the light itself can * have child nodes. For example, a light can be mounted on a boom object or camera, * and will move along with the parent node. * * CC3Light can be pointed so that it shines in a particular direction, or can be * made to track a target node as that node moves. * * To turn a CC3Light on or off, set the visible property. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. * * Lights in different scenes (different instances of CC3Scene) can have the same * GL lightIndex value. Applications that make use of multiple CC3Scenes, either as * a sequence of scenes, or as multiple scenes (and multiple CC3Layers) displayed * on the screen at once, can reuse a light index across the scenes. * The shouldCopyLightIndex property can be used to help copy lights across scenes. * * If the application uses lights in the 2D scene as well, the indexes of those lights * can be reserved by invoking the class method setLightPoolStartIndex:. Light indexes * reserved for use by the 2D scene will not be used by the 3D scene. */ @interface CC3Light : CC3Node { CC3ShadowCastingVolume* shadowCastingVolume; CC3CameraShadowVolume* cameraShadowVolume; CC3StencilledShadowPainterNode* stencilledShadowPainter; CCArray* shadows; ccColor4F ambientColor; ccColor4F diffuseColor; ccColor4F specularColor; CC3AttenuationCoefficients _attenuation; GLfloat spotExponent; GLfloat spotCutoffAngle; GLfloat shadowIntensityFactor; GLuint lightIndex; BOOL isDirectionalOnly : 1; BOOL shouldCopyLightIndex : 1; BOOL shouldCastShadowsWhenInvisible : 1; } /** Returns whether this node is a light. Returns YES. */ @property(nonatomic, readonly) BOOL isLight; /** * The index of this light to identify it to the GL engine. This is automatically assigned * during instance initialization. The value of lightIndex will be between zero and one * less than the maximium number of available lights, inclusive. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ @property(nonatomic, readonly) GLuint lightIndex; /** The ambient color of this light. Initially set to kCC3DefaultLightColorAmbient. */ @property(nonatomic, assign) ccColor4F ambientColor; /** The diffuse color of this light. Initially set to kCC3DefaultLightColorDiffuse. */ @property(nonatomic, assign) ccColor4F diffuseColor; /** The specular color of this light. Initially set to kCC3DefaultLightColorSpecular. */ @property(nonatomic, assign) ccColor4F specularColor; /** * Indicates whether this light is directional and without a specified location. * Directional-only light is good for modeling sunlight, or other flat overhead * lighting. Positional lighting is good for point-source lights like a single * bulb, flare, etc. * * The value of this property impacts features like attenuation, and the angle * of reflection to the user view. A directional-only light is not subject to * attenuation over distance, where an absolutely located light is. In addition, * directional-only light bounces off a flat surface at a single angle, whereas * the angle for a point-source light also depends on the location of the camera. * * The value of this property also impacts performance. Because positional light * involves significantly more calculations within the GL engine, setting this * property to YES (the initial value) will improve lighting performance. * You should only set this property to NO if you need to make use of the * positional features described above. * * The initial value is YES, indicating directional-only lighting. */ @property(nonatomic, assign) BOOL isDirectionalOnly; /** * The position of this light in a global 4D homogeneous coordinate space. * * The X, Y & Z components of the returned 4D vector are the same as those in the globalLocation * property. The W-component will be zero if the isDirectionalOnly property is set to YES, indicating * that this position represents a direction. The W-component will be one if the isDirectionalOnly * property is set to NO, indicating that this position represents a specific location. */ @property(nonatomic, readonly) CC3Vector4 globalHomogeneousPosition; /** * Indicates the intensity distribution of the light. * * Effective light intensity is attenuated by the cosine of the angle between the * direction of the light and the direction from the light to the vertex being lighted, * raised to the power of the value of this property. Thus, higher spot exponents result * in a more focused light source, regardless of the value of the spotCutoffAngle property. * * The value of this property must be in the range [0, 128], and is clamped to that * range if an attempt is made to set the value outside this range. * * The initial value of this property is zero, indicating a uniform light distribution. */ @property(nonatomic, assign) GLfloat spotExponent; /** * Indicates the angle, in degrees, of dispersion of the light from the direction of the light. * Setting this value to any angle between zero and 90 degrees, inclusive, will cause this light * to be treated as a spotlight whose direction is set by the forwardDirection property of this * light, and whose angle of dispersion is controlled by this property. Setting this property to * any value above 90 degrees will cause this light to be treated as an omnidirectional light. * * This property is initially set to kCC3SpotCutoffNone (180 degrees). */ @property(nonatomic, assign) GLfloat spotCutoffAngle; /** * The coefficients of the attenuation function that reduces the intensity of the light * based on the distance from the light source. The intensity of the light is attenuated * according to the formula 1/sqrt(a + b * r + c * r * r), where r is the radial distance * from the light source, and a, b and c are the coefficients from this property. * * The initial value of this property is kCC3DefaultLightAttenuationCoefficients. */ @property(nonatomic, assign) CC3AttenuationCoefficients attenuation; /** @deprecated Property renamed to attenuation */ @property(nonatomic, assign) CC3AttenuationCoefficients attenuationCoefficients DEPRECATED_ATTRIBUTE; /** * When a copy is made of this node, indicates whether this node should copy the value * of the lightIndex property to the new node when performing a copy of this node. * * The initial value of this property is NO. * * When this property is set to NO, and this light node is copied, the new copy will * be assigned its own lightIndex, to identify it to the GL engine. This allows both * lights to illuminate the same scene (instance of CC3Scene), and is the most common * mechanism for assigning the lightIndex property. * * OpenGL ES limits the number of lights available to illuminate a single scene. * Once that limit is reached, additional lights cannot be created, and attempting * to copy this node will fail, returning a nil node. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. * * When this property is set to YES, and this light node is copied, the new copy will * be assigned the same lightIndex as this node. This means that the copy may not be * used in the same scene as the original light, but it may be used in another scene * (another CC3Scene instance). * * Applications that make use of multiple CC3Scenes, either as a sequence of scenes, * or as multiple scenes (and multiple CC3Layers) displayed on the screen at once, * can set this property to YES when making copies of a light to be placed in * different CC3Scene instances. */ @property(nonatomic, assign) BOOL shouldCopyLightIndex; /** * The direction in which this light is pointing, relative to the coordinate * system of this light, which is relative to the parent's rotation. * * The initial value of this property is kCC3VectorUnitZNegative, pointing * down the negative Z-axis in the local coordinate system of this light. * When this light is rotated, the original negative-Z axis of the camera's * local coordinate system will point in this direction. * * This orientation is opposite that for most other nodes, whose forwardDirection * property orients the positve Z-axis of the node's coordinate system in * the stated direction. This arrangement allows unrotated nodes to face the * light in a natural stance, and allows the unrotated light to face the nodes. * * See further notes in the notes for this property in the CC3Node class. */ @property(nonatomic, assign) CC3Vector forwardDirection; #pragma mark Allocation and initialization /** * Initializes this unnamed instance with an automatically generated unique tag value. * The tag value will be generated automatically via the method nextTag. * * The lightIndex property will be set to the next available GL light index. * This method will return nil if all GL light indexes have been consumed. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) init; /** * Initializes this unnamed instance with the specified tag. * * The lightIndex property will be set to the next available GL light index. * This method will return nil if all GL light indexes have been consumed. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) initWithTag: (GLuint) aTag; /** * Initializes this instance with the specified name and an automatically generated unique * tag value. The tag value will be generated automatically via the method nextTag. * * The lightIndex property will be set to the next available GL light index. * This method will return nil if all GL light indexes have been consumed. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) initWithName: (NSString*) aName; /** * Initializes this instance with the specified tag and name. * * The lightIndex property will be set to the next available GL light index. * This method will return nil if all GL light indexes have been consumed. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) initWithTag: (GLuint) aTag withName: (NSString*) aName; /** * Initializes this unnamed instance with the specified GL light index, and an * automatically generated unique tag value. The tag value will be generated * automatically via the method nextTag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) initWithLightIndex: (GLuint) ltIndx; /** * Initializes this unnamed instance with the specified GL light index, and the * specified tag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) initWithTag: (GLuint) aTag withLightIndex: (GLuint) ltIndx; /** * Initializes this instance with the specified GL light index, the specified name, * and an automatically generated unique tag value. The tag value will be generated * automatically via the method nextTag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) initWithName: (NSString*) aName withLightIndex: (GLuint) ltIndx; /** * Initializes this instance with the specified GL light index, the specified name, * and the specified tag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ -(id) initWithTag: (GLuint) aTag withName: (NSString*) aName withLightIndex: (GLuint) ltIndx; /** * Allocates and initializes an autoreleased unnamed instance with the specified * GL light index, and an automatically generated unique tag value. The tag value * will be generated automatically via the method nextTag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ +(id) lightWithLightIndex: (GLuint) ltIndx; /** * Allocates and initializes an autoreleased unnamed instance with the specified * GL light index, and the specified tag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ +(id) lightWithTag: (GLuint) aTag withLightIndex: (GLuint) ltIndx; /** * Allocates and initializes an autoreleased instance with the specified GL light * index, the specified name, and an automatically generated unique tag value. * The tag value will be generated automatically via the method nextTag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ +(id) lightWithName: (NSString*) aName withLightIndex: (GLuint) ltIndx; /** * Allocates and initializes an autoreleased instance with the specified GL light * index, the specified name, and the specified tag. * * If multiple lights are used to illumniate a scene (a CC3Scene instance), * each light must have its own GL light index. Do not assign the same light * index to more than one light in a scene. * * This method will return nil if the specified light index is not less than the * maximum number of lights available. * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ +(id) lightWithTag: (GLuint) aTag withName: (NSString*) aName withLightIndex: (GLuint) ltIndx; #pragma mark Shadows /** * Indicates whether this light should cast shadows even when invisible. * * Normally, when a light is turned off, any shadows cast by that light should * disappear as well. However, there are certain lighting situations where you * might want a light to cast shadows, even when turned off, such as using one * light to accent the shadows cast by another light that has different ambient * or diffuse lighting characteristics. * * The initial value of this propety is NO. * * Setting this value sets the same property on any descendant mesh and light nodes. */ @property(nonatomic, assign) BOOL shouldCastShadowsWhenInvisible; /** * The shadows cast by this light. * * If this light is casting no shadows, this property will be nil. */ @property(nonatomic, readonly) CCArray* shadows; /** * Adds a shadow to the shadows cast by this light. * * This method is invoked automatically when a shadow is added to a mesh node. * Usually, the application never needs to invoke this method directly. */ -(void) addShadow: (id<CC3ShadowProtocol>) shadowNode; /** Removes a shadow from the shadows cast by this light. */ -(void) removeShadow: (id<CC3ShadowProtocol>) shadowNode; /** * Returns whether this light is casting shadows. * * It is if any shadows have been added and not yet removed. */ @property(nonatomic, readonly) BOOL hasShadows; /** Update the shadows that are cast by this light. */ -(void) updateShadows; /** Draws any shadows cast by this light. */ -(void) drawShadowsWithVisitor: (CC3NodeDrawingVisitor*) visitor; /** * A specialized bounding volume that encloses a volume that includes the camera * frustum plus the space between the camera frustum and this light. * * Nodes that intersect this volume will cast a shadow from this light into the * camera frustum, and that shadow will be visible. Shadows cast by nodes outside * this volume will not intersect the frustum and will not be visible. * * This volume is used to cull the updating and drawing of shadows that will not * be visible, to enhance performance. * * If not set directly, this property is lazily created when a shadow is added. * If no shadow has been added, this property will return nil. */ @property(nonatomic, retain) CC3ShadowCastingVolume* shadowCastingVolume; /** * A specialized bounding volume that encloses a pyramidal volume between the * view plane (near clipping plane) of the camera, and this light. * * Nodes that intersect this volume will cast a shadow from that light across * the camera. The shadow volume of nodes that cast a shadow across the camera * view plane are rendered differently than shadow volumes for nodes that do * not cast their shadow across the camera. * * If not set directly, this property is lazily created when a shadow is added. * If no shadow has been added, this property will return nil. */ @property(nonatomic, retain) CC3CameraShadowVolume* cameraShadowVolume; /** * The mesh node used to draw the shadows cast by any shadow volumes that have * been added to mesh nodes for this light. * * Shadow volumes are used to define a stencil that is then used to draw dark * areas onto the viewport where mesh nodes are casting shadows. This painter * is used to draw those dark areas where the stencil indicates. * * If not set directly, this property is lazily created when a shadow is added. * If no shadow has been added, this property will return nil. */ @property(nonatomic, retain) CC3StencilledShadowPainterNode* stencilledShadowPainter; /** * This property is used to adjust the shadow intensity as calculated when the * updateRelativeIntensityFrom: method is invoked. This property increases * flexibility by allowing the shadow intensity to be ajusted relative to that * calculated value to improve realisim. * * The intensity of shadows cast by this light is calculated by comparing the * intensity of the diffuse component of this light against the total ambient * and diffuse illumination from all lights, to get a measure of the fraction * of total scene illumination that is contributed by this light. * * Using this technique, the presence of multiple lights, or strong ambient * light, will serve to lighten the shadows cast by any single light. A single * light with no ambient light will cast completely opaque, black shadows. * * That fraction, representing the fraction of overall light coming from this * light, is then multiplied by the value of this property to determine the * intensity (opacity) of the shadows cast by this light. * * This property must be zero or a positive value. A value between zero and * one will serve to to lighten the shadow, relative to the shadow intensity * (opacity) calculated from the relative intensity of this light, and a value * of greater than one will serve to darken the shadow, relative to that * calculated intensity. * * The initial value of this property is one, meaning that the shadow intensity * calculated from the relative intensity of this light will be used without adjustment. */ @property(nonatomic, assign) GLfloat shadowIntensityFactor; /** * Updates the relative intensity of this light, as compared to the specified * total scene illumination. * * Certain characteristics, such as shadow intensities, depend on the relative * intensity of this light, relative to the total intensity of all lights in * the scene. * * Sets the intensity of shadows cast by this light by comparing the intensity of * the diffuse component of this light against the total ambient and diffuse * illumination from all lights, to get a measure of the fraction of total scene * illumination that is contributed by this light. * * Using this technique, the presence of multiple lights, or strong ambient light, * will serve to lighten the shadows cast by any single light. A single light with * no ambient light will cast completely black opaque shadows. * * That calculated fraction is then multiplied by the value of the shadowIntensityFactor * property to determine the intensity (opacity) of the shadows cast by this light. * The shadowIntensityFactor increases flexibility by allowing the shadow intensity * to be adjusted relative to the calculated value to improve realisim. * * This method is invoked automatically when any of the the ambientColor, diffuseColor, * visible, or shadowIntensityFactor properties of any light in the scene is changed, * or if the ambientLight property of the CC3Scene is changed. */ -(void) updateRelativeIntensityFrom: (ccColor4F) totalLight; #pragma mark Drawing /** * If this light is visible, turns it on by enabling this light in the GL engine, * and then applies the properties of this light to the GL engine. * * This method is invoked automatically by CC3Scene near the beginning of each frame * drawing cycle. Usually, the application never needs to invoke this method directly. */ -(void) turnOnWithVisitor: (CC3NodeDrawingVisitor*) visitor; /** * Turns this light off on by disabling this light in the GL engine. * * This method is invoked automatically by CC3Scene at the end of each frame drawing cycle. * Usually, the application never needs to invoke this method directly. */ -(void) turnOffWithVisitor: (CC3NodeDrawingVisitor*) visitor; #pragma mark Managing the pool of available GL lights /** * Returns the number of lights that have already been instantiated (and not yet deallocated). * * The maximum number of lights available is determined by the platform. That number can be retrieved * from the CC3OpenGL.sharedGL.maxNumberOfLights property. All platforms support at least eight lights. */ +(GLuint) lightCount; /** * Indicates the smallest index number to assign to a 3D light. * * See the description of the setLightPoolStartIndex: method for more information on this value. */ +(GLuint) lightPoolStartIndex; /** * Sets the smallest index number to assign to a 3D light. This value should be between * zero inclusive and CC3OpenGL.sharedGL.maxNumberOfLights exclusive. * * If the 2D scene uses lights, setting this value to a number above zero will reserve * the indexes below this number for the 2D scene and those indexes will not be used in * lights in the 3D scene. * * This value defaults to zero. If your application requires light indexes to be reserved * and not assigned in the 3D scene, set this value. */ +(void) setLightPoolStartIndex: (GLuint) newStartIndex; /** * Disables the lights that were reserved for the 2D scene by setLightPoolStartIndex:. * * This method is invoked automatically by CC3Scene near the beginning of each frame * drawing cycle. Usually, the application never needs to invoke this method directly. */ +(void) disableReservedLightsWithVisitor: (CC3NodeDrawingVisitor*) visitor; @end #pragma mark - #pragma mark CC3ShadowProtocol /** * The behaviour required by objects that represent shadows cast by a light. * * CAUTION: The signature of this protocol may evolve as additional shadowing * techniques are introduced. */ @protocol CC3ShadowProtocol <CC3NodeTransformListenerProtocol> /** The light casting this shadow. */ @property(nonatomic, assign) CC3Light* light; /** * Updates the shape and location of the shadow. * * This is invoked automatically by the light during each update frame * to udpate the shape and location of the shadow. */ -(void) updateShadow; @end #pragma mark - #pragma mark CC3LightCameraBridgeVolume /** * A bounding volume that encloses a volume between a light and all or part of * the frustum of the camera. This is an abstract class. Subclasses will define * the actual appropriate bounding volume. * * As a bounding volume, this class supports methods for testing whether * locations, rays, shapes, and other bounding volumes intersect its volume. */ @interface CC3LightCameraBridgeVolume : CC3BoundingVolume <CC3NodeTransformListenerProtocol> { CC3Frustum* cameraFrustum; CC3Light* light; } /** * Returns the number of vertices in the array returned by the vertices property. * * The value returned depends on whether the light has a specific location, * or is directional. If the light is directional, the location of the light * is at infinity, and is not used when comparing the vertices with other * bounding volumes. * * Consequently, if the light has a specific location, that location will be * included in the array returned by the vertices property, and the value * returned by this property will reflect that. If the light is directional, * the light location will not be included in the array returned by the vertices * property, and the value returned by this property reflects that, and will be * one less than if the light has a specific location. */ @property(nonatomic, readonly) GLuint vertexCount; @end #pragma mark - #pragma mark CC3ShadowCastingVolume /** * A bounding volume that encloses a volume that includes the camera frustum plus * the space between the camera frustum and a light. * * Nodes that intersect this volume will cast a shadow from that light into the frustum, * and that shadow will be visible. Shadows cast by nodes outside this volume will not * intersect the frustum and will not be visible. This volume is used to cull the * updating and drawing of shadows, that will not be visible, to improve performance. * * The number of planes in this bounding volume will be between six and eleven, depending * on where the light is located. The number of vertices will be between five and nine. * * The shadow casting volume is a type of bounding volume and therefore supports methods for * testing whether locations, rays, shapes, and other bounding volumes intersect its volume. */ @interface CC3ShadowCastingVolume : CC3LightCameraBridgeVolume { CC3Plane planes[11]; CC3Vector vertices[9]; GLuint planeCount; GLuint vertexCount; } @end #pragma mark - #pragma mark CC3CameraShadowVolume /** * A bounding volume that encloses a pyramidal volume between the view plane * (near clipping plane) of the camera, and a light. * * Nodes that intersect this volume will cast a shadow from that light across the camera. * The shadow volume of nodes that cast a shadow across the camera view plane are rendered * differently than shadow volumes for nodes that do not cast their shadow across the camera. * * The camera shadow volume is a type of bounding volume and therefore supports methods for * testing whether locations, rays, shapes, and other bounding volumes intersect its volume. */ @interface CC3CameraShadowVolume : CC3LightCameraBridgeVolume { CC3Plane planes[6]; CC3Vector vertices[5]; } /** The frustum vertex on the near clipping plane of the camera, at the intersection of the top and left sides. */ @property(nonatomic, readonly) CC3Vector topLeft; /** The frustum vertex on the near clipping plane of the camera, at the intersection of the top and right sides. */ @property(nonatomic, readonly) CC3Vector topRight; /** The frustum vertex on the near clipping plane of the camera, at the intersection of the bottom and left sides. */ @property(nonatomic, readonly) CC3Vector bottomLeft; /** The frustum vertex on the near clipping plane of the camera, at the intersection of the bottom and right sides. */ @property(nonatomic, readonly) CC3Vector bottomRight; /** The clip plane at the top of this frustum, in global coordinates. */ @property(nonatomic, readonly) CC3Plane topPlane; /** The clip plane at the bottom of this frustum, in global coordinates. */ @property(nonatomic, readonly) CC3Plane bottomPlane; /** The clip plane at the left side of this frustum, in global coordinates. */ @property(nonatomic, readonly) CC3Plane leftPlane; /** The clip plane at the right side of this frustum, in global coordinates. */ @property(nonatomic, readonly) CC3Plane rightPlane; /** The clip plane at the near end of this frustum, in global coordinates. */ @property(nonatomic, readonly) CC3Plane nearPlane; /** The clip plane at the far end of this frustum, in global coordinates. */ @property(nonatomic, readonly) CC3Plane farPlane; @end #pragma mark - #pragma mark CC3Node extension for lights @interface CC3Node (Lighting) /** Returns whether this node is a light. * * This implementation returns NO. Subclasses that are lights will override to return YES. */ @property(nonatomic, readonly) BOOL isLight; @end
43.331639
118
0.766671
cf9008c74e532cb766ac0e068d81c32253f02c28
17,431
h
C
IO/XML/vtkXMLWriter.h
michaelchanwahyan/vtk-7.0.0
770166bbe1f28a99d776b47624c6f6955b9aaaec
[ "BSD-3-Clause" ]
1
2019-04-22T09:09:17.000Z
2019-04-22T09:09:17.000Z
IO/XML/vtkXMLWriter.h
michaelchanwahyan/vtk-7.0.0
770166bbe1f28a99d776b47624c6f6955b9aaaec
[ "BSD-3-Clause" ]
null
null
null
IO/XML/vtkXMLWriter.h
michaelchanwahyan/vtk-7.0.0
770166bbe1f28a99d776b47624c6f6955b9aaaec
[ "BSD-3-Clause" ]
1
2020-06-23T09:33:24.000Z
2020-06-23T09:33:24.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkXMLWriter.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkXMLWriter - Superclass for VTK's XML file writers. // .SECTION Description // vtkXMLWriter provides methods implementing most of the // functionality needed to write VTK XML file formats. Concrete // subclasses provide actual writer implementations calling upon this // functionality. #ifndef vtkXMLWriter_h #define vtkXMLWriter_h #include "vtkIOXMLModule.h" // For export macro #include "vtkAlgorithm.h" #include <sstream> // For ostringstream ivar class vtkAbstractArray; class vtkArrayIterator; //BTX template <class T> class vtkArrayIteratorTemplate; //ETX class vtkCellData; class vtkDataArray; class vtkDataCompressor; class vtkDataSet; class vtkDataSetAttributes; class vtkOutputStream; class vtkPointData; class vtkPoints; class vtkFieldData; class vtkXMLDataHeader; //BTX class vtkStdString; class OffsetsManager; // one per piece/per time class OffsetsManagerGroup; // array of OffsetsManager class OffsetsManagerArray; // array of OffsetsManagerGroup //ETX class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm { public: vtkTypeMacro(vtkXMLWriter,vtkAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); //BTX // Description: // Enumerate big and little endian byte order settings. enum { BigEndian, LittleEndian }; //ETX //BTX // Description: // Enumerate the supported data modes. // Ascii = Inline ascii data. // Binary = Inline binary data (base64 encoded, possibly compressed). // Appended = Appended binary data (possibly compressed and/or base64). enum { Ascii, Binary, Appended }; //ETX //BTX // Description: // Enumerate the supported vtkIdType bit lengths. // Int32 = File stores 32-bit values for vtkIdType. // Int64 = File stores 64-bit values for vtkIdType. enum { Int32=32, Int64=64 }; // Description: // Enumerate the supported binary data header bit lengths. // UInt32 = File stores 32-bit binary data header elements. // UInt64 = File stores 64-bit binary data header elements. enum { UInt32=32, UInt64=64 }; //ETX // Description: // Get/Set the byte order of data written to the file. The default // is the machine's hardware byte order. vtkSetMacro(ByteOrder, int); vtkGetMacro(ByteOrder, int); void SetByteOrderToBigEndian(); void SetByteOrderToLittleEndian(); // Description: // Get/Set the binary data header word type. The default is UInt32. // Set to UInt64 when storing arrays requiring 64-bit indexing. virtual void SetHeaderType(int); vtkGetMacro(HeaderType, int); void SetHeaderTypeToUInt32(); void SetHeaderTypeToUInt64(); // Description: // Get/Set the size of the vtkIdType values stored in the file. The // default is the real size of vtkIdType. virtual void SetIdType(int); vtkGetMacro(IdType, int); void SetIdTypeToInt32(); void SetIdTypeToInt64(); // Description: // Get/Set the name of the output file. vtkSetStringMacro(FileName); vtkGetStringMacro(FileName); // Description: // Enable writing to an OutputString instead of the default, a file. vtkSetMacro(WriteToOutputString,int); vtkGetMacro(WriteToOutputString,int); vtkBooleanMacro(WriteToOutputString,int); std::string GetOutputString() { return this->OutputString; } // Description: // Get/Set the compressor used to compress binary and appended data // before writing to the file. Default is a vtkZLibDataCompressor. virtual void SetCompressor(vtkDataCompressor*); vtkGetObjectMacro(Compressor, vtkDataCompressor); //BTX enum CompressorType { NONE, ZLIB }; //ETX // Description: // Convenience functions to set the compressor to certain known types. void SetCompressorType(int compressorType); void SetCompressorTypeToNone() { this->SetCompressorType(NONE); } void SetCompressorTypeToZLib() { this->SetCompressorType(ZLIB); } // Description: // Get/Set the block size used in compression. When reading, this // controls the granularity of how much extra information must be // read when only part of the data are requested. The value should // be a multiple of the largest scalar data type. virtual void SetBlockSize(size_t blockSize); vtkGetMacro(BlockSize, size_t); // Description: // Get/Set the data mode used for the file's data. The options are // vtkXMLWriter::Ascii, vtkXMLWriter::Binary, and // vtkXMLWriter::Appended. vtkSetMacro(DataMode, int); vtkGetMacro(DataMode, int); void SetDataModeToAscii(); void SetDataModeToBinary(); void SetDataModeToAppended(); // Description: // Get/Set whether the appended data section is base64 encoded. If // encoded, reading and writing will be slower, but the file will be // fully valid XML and text-only. If not encoded, the XML // specification will be violated, but reading and writing will be // fast. The default is to do the encoding. vtkSetMacro(EncodeAppendedData, int); vtkGetMacro(EncodeAppendedData, int); vtkBooleanMacro(EncodeAppendedData, int); // Description: // Assign a data object as input. Note that this method does not // establish a pipeline connection. Use SetInputConnection() to // setup a pipeline connection. void SetInputData(vtkDataObject *); void SetInputData(int, vtkDataObject*); vtkDataObject *GetInput(int port); vtkDataObject *GetInput() { return this->GetInput(0); }; // Description: // Get the default file extension for files written by this writer. virtual const char* GetDefaultFileExtension()=0; // Description: // Invoke the writer. Returns 1 for success, 0 for failure. int Write(); // See the vtkAlgorithm for a description of what these do virtual int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); // Description: // Which TimeStep to write. vtkSetMacro(TimeStep, int); vtkGetMacro(TimeStep, int); // Description: // Which TimeStepRange to write. vtkGetVector2Macro(TimeStepRange, int); vtkSetVector2Macro(TimeStepRange, int); // Description: // Set the number of time steps vtkGetMacro(NumberOfTimeSteps,int); vtkSetMacro(NumberOfTimeSteps,int); // Description: // API to interface an outside the VTK pipeline control void Start(); void Stop(); void WriteNextTime(double time); protected: vtkXMLWriter(); ~vtkXMLWriter(); virtual int RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); // The name of the output file. char* FileName; // The output stream to which the XML is written. ostream* Stream; // Whether this object is writing to a string or a file. // Default is 0: write to file. int WriteToOutputString; // The output string. std::string OutputString; // The output byte order. int ByteOrder; // The output binary header word type. int HeaderType; // The output vtkIdType. int IdType; // The form of binary data to write. Used by subclasses to choose // how to write data. int DataMode; // Whether to base64-encode the appended data section. int EncodeAppendedData; // The stream position at which appended data starts. vtkTypeInt64 AppendedDataPosition; // appended data offsets for field data OffsetsManagerGroup *FieldDataOM; //one per array //BTX // We need a 32 bit signed integer type to which vtkIdType will be // converted if Int32 is specified for the IdType parameter to this // writer. # if VTK_SIZEOF_SHORT == 4 typedef short Int32IdType; # elif VTK_SIZEOF_INT == 4 typedef int Int32IdType; # elif VTK_SIZEOF_LONG == 4 typedef long Int32IdType; # else # error "No native data type can represent a signed 32-bit integer." # endif //ETX // Buffer for vtkIdType conversion. Int32IdType* Int32IdTypeBuffer; // The byte swapping buffer. unsigned char* ByteSwapBuffer; // Compression information. vtkDataCompressor* Compressor; size_t BlockSize; size_t CompressionBlockNumber; vtkXMLDataHeader* CompressionHeader; vtkTypeInt64 CompressionHeaderPosition; // The output stream used to write binary and appended data. May // transparently encode the data. vtkOutputStream* DataStream; // Allow subclasses to set the data stream. virtual void SetDataStream(vtkOutputStream*); vtkGetObjectMacro(DataStream, vtkOutputStream); // Method to drive most of actual writing. virtual int WriteInternal(); // Method defined by subclasses to write data. Return 1 for // success, 0 for failure. virtual int WriteData() {return 1;}; // Method defined by subclasses to specify the data set's type name. virtual const char* GetDataSetName()=0; // Methods to define the file's major and minor version numbers. virtual int GetDataSetMajorVersion(); virtual int GetDataSetMinorVersion(); // Utility methods for subclasses. vtkDataSet* GetInputAsDataSet(); virtual int StartFile(); virtual void WriteFileAttributes(); virtual int EndFile(); void DeleteAFile(); void DeleteAFile(const char* name); virtual int WritePrimaryElement(ostream &os, vtkIndent indent); virtual void WritePrimaryElementAttributes(ostream &os, vtkIndent indent); void StartAppendedData(); void EndAppendedData(); // Write enough space to go back and write the given attribute with // at most "length" characters in the value. Returns the stream // position at which attribute should be later written. The default // length of 20 is enough for a 64-bit integer written in decimal or // a double-precision floating point value written to 13 digits of // precision (the other 7 come from a minus sign, decimal place, and // a big exponent like "e+300"). vtkTypeInt64 ReserveAttributeSpace(const char* attr, size_t length=20); vtkTypeInt64 GetAppendedDataOffset(); void WriteAppendedDataOffset(vtkTypeInt64 streamPos, vtkTypeInt64 &lastoffset, const char* attr=0); void ForwardAppendedDataOffset(vtkTypeInt64 streamPos, vtkTypeInt64 offset, const char* attr=0); void ForwardAppendedDataDouble(vtkTypeInt64 streamPos, double value, const char* attr); int WriteScalarAttribute(const char* name, int data); int WriteScalarAttribute(const char* name, float data); int WriteScalarAttribute(const char* name, double data); #ifdef VTK_USE_64BIT_IDS int WriteScalarAttribute(const char* name, vtkIdType data); #endif int WriteVectorAttribute(const char* name, int length, int* data); int WriteVectorAttribute(const char* name, int length, float* data); int WriteVectorAttribute(const char* name, int length, double* data); #ifdef VTK_USE_64BIT_IDS int WriteVectorAttribute(const char* name, int length, vtkIdType* data); #endif int WriteDataModeAttribute(const char* name); int WriteWordTypeAttribute(const char* name, int dataType); int WriteStringAttribute(const char* name, const char* value); void WriteArrayHeader(vtkAbstractArray* a, vtkIndent indent, const char* alternateName, int writeNumTuples, int timestep); virtual void WriteArrayFooter(ostream &os, vtkIndent indent, vtkAbstractArray *a, int shortFormat); virtual void WriteArrayInline(vtkAbstractArray* a, vtkIndent indent, const char* alternateName=0, int writeNumTuples=0); virtual void WriteInlineData(vtkAbstractArray* a, vtkIndent indent); void WriteArrayAppended(vtkAbstractArray* a, vtkIndent indent, OffsetsManager &offs, const char* alternateName=0, int writeNumTuples=0, int timestep=0); int WriteAsciiData(vtkAbstractArray* a, vtkIndent indent); int WriteBinaryData(vtkAbstractArray* a); int WriteBinaryDataInternal(vtkAbstractArray* a); void WriteArrayAppendedData(vtkAbstractArray* a, vtkTypeInt64 pos, vtkTypeInt64 &lastoffset); // Methods for writing points, point data, and cell data. void WriteFieldData(vtkIndent indent); void WriteFieldDataInline(vtkFieldData* fd, vtkIndent indent); void WritePointDataInline(vtkPointData* pd, vtkIndent indent); void WriteCellDataInline(vtkCellData* cd, vtkIndent indent); void WriteFieldDataAppended(vtkFieldData* fd, vtkIndent indent, OffsetsManagerGroup *fdManager); void WriteFieldDataAppendedData(vtkFieldData* fd, int timestep, OffsetsManagerGroup *fdManager); void WritePointDataAppended(vtkPointData* pd, vtkIndent indent, OffsetsManagerGroup *pdManager); void WritePointDataAppendedData(vtkPointData* pd, int timestep, OffsetsManagerGroup *pdManager); void WriteCellDataAppended(vtkCellData* cd, vtkIndent indent, OffsetsManagerGroup *cdManager); void WriteCellDataAppendedData(vtkCellData* cd, int timestep, OffsetsManagerGroup *cdManager); void WriteAttributeIndices(vtkDataSetAttributes* dsa, char** names); void WritePointsAppended(vtkPoints* points, vtkIndent indent, OffsetsManager *manager); void WritePointsAppendedData(vtkPoints* points, int timestep, OffsetsManager *pdManager); void WritePointsInline(vtkPoints* points, vtkIndent indent); void WriteCoordinatesInline(vtkDataArray* xc, vtkDataArray* yc, vtkDataArray* zc, vtkIndent indent); void WriteCoordinatesAppended(vtkDataArray* xc, vtkDataArray* yc, vtkDataArray* zc, vtkIndent indent, OffsetsManagerGroup *coordManager); void WriteCoordinatesAppendedData(vtkDataArray* xc, vtkDataArray* yc, vtkDataArray* zc, int timestep, OffsetsManagerGroup *coordManager); void WritePPointData(vtkPointData* pd, vtkIndent indent); void WritePCellData(vtkCellData* cd, vtkIndent indent); void WritePPoints(vtkPoints* points, vtkIndent indent); void WritePArray(vtkAbstractArray* a, vtkIndent indent, const char* alternateName=0); void WritePCoordinates(vtkDataArray* xc, vtkDataArray* yc, vtkDataArray* zc, vtkIndent indent); // Internal utility methods. int WriteBinaryDataBlock(unsigned char* in_data, size_t numWords, int wordType); void PerformByteSwap(void* data, size_t numWords, size_t wordSize); int CreateCompressionHeader(size_t size); int WriteCompressionBlock(unsigned char* data, size_t size); int WriteCompressionHeader(); size_t GetWordTypeSize(int dataType); const char* GetWordTypeName(int dataType); size_t GetOutputWordTypeSize(int dataType); char** CreateStringArray(int numStrings); void DestroyStringArray(int numStrings, char** strings); // The current range over which progress is moving. This allows for // incrementally fine-tuned progress updates. virtual void GetProgressRange(float range[2]); virtual void SetProgressRange(const float range[2], int curStep, int numSteps); virtual void SetProgressRange(const float range[2], int curStep, const float* fractions); virtual void SetProgressPartial(float fraction); virtual void UpdateProgressDiscrete(float progress); float ProgressRange[2]; ofstream* OutFile; std::ostringstream* OutStringStream; int OpenStream(); int OpenFile(); int OpenString(); void CloseStream(); void CloseFile(); void CloseString(); // The timestep currently being written int TimeStep; int CurrentTimeIndex; int NumberOfTimeSteps; // Store the range of time steps int TimeStepRange[2]; // Dummy boolean var to start/stop the continue executing: // when using the Start/Stop/WriteNextTime API int UserContinueExecuting; //can only be -1 = invalid, 0 = stop, 1 = start // This variable is used to ease transition to new versions of VTK XML files. // If data that needs to be written satisfies certain conditions, // the writer can use the previous file version version. // For version change 0.1 -> 2.0 (UInt32 header) and 1.0 -> 2.0 // (UInt64 header), if data does not have a vtkGhostType array, // the file is written with version: 0.1/1.0. bool UsePreviousVersion; vtkTypeInt64 *NumberOfTimeValues; //one per piece / per timestep //BTX friend class vtkXMLWriterHelper; //ETX private: vtkXMLWriter(const vtkXMLWriter&); // Not implemented. void operator=(const vtkXMLWriter&); // Not implemented. }; #endif
36.1639
101
0.714818
45969dcf150996748744f73f2bc3bcb1da5aabb6
2,595
h
C
src/selection/model_selection.h
m-colombo/cppML
2f1b3b5ab3487ea47263fbd774af9d5a17779c96
[ "MIT" ]
null
null
null
src/selection/model_selection.h
m-colombo/cppML
2f1b3b5ab3487ea47263fbd774af9d5a17779c96
[ "MIT" ]
null
null
null
src/selection/model_selection.h
m-colombo/cppML
2f1b3b5ab3487ea47263fbd774af9d5a17779c96
[ "MIT" ]
null
null
null
// // model_selection.h // XAA1 // // Created by Michele Colombo on 22/12/2015. // Copyright (c) 2015 Michele Colombo. All rights reserved. // #ifndef __XAA1__model_selection__ #define __XAA1__model_selection__ #include "../data/samples.h" #include "../learners/backprop_learner.h" #include "../data/data_normalization.h" #include "../selection/scorers/scorer.hpp" #include<functional> class GridSearchHoldOutCV{ public: std::string results_dir; //Search parameters std::shared_ptr<Loss> targetLoss; int trials = 1; std::shared_ptr<Scorer::IScorer> modelScoreMethod; //When stop criteria depends on the normalization methods they can be generated std::function<std::deque<std::shared_ptr<Stop::Criteria>>(SamplesSP normalized_selection, std::shared_ptr<DenormalizedLoss> dloss)> stopCriteriaGen; std::deque<std::shared_ptr<Stop::Criteria>> stopCriteria; //TODO allow observers //Hyper parameters to select std::deque<SampleNormalizer> normalizers; std::deque<std::shared_ptr<FeedforwardNetwork>> topologies; std::deque<std::pair<double,double>> initialWeights; std::deque<std::shared_ptr<DifLoss>> gradientLoss; std::deque<double> batchRatios, learningRates, momentums, weightDecays; //Data to use SamplesSP train, selection; //Split data in training and selection GridSearchHoldOutCV(Samples const& original_data, double train_ratio, std::string const& results_dir); GridSearchHoldOutCV(std::shared_ptr<Samples> train, std::shared_ptr<Samples> selection, std::string const& results_dir); template<class T_LOSS> void setTargetLoss(T_LOSS const & loss){ targetLoss = std::make_shared<T_LOSS>(loss); } template<class T_IN, class T_OUT> void addNormalizer(T_IN const& input_protoype, T_OUT const& output_prototype){ SampleNormalizer sn; sn.initialize(*train, input_protoype, output_prototype); normalizers.push_back(sn); } template<class T_HIDDEN, class T_OUT> void addTopologies (std::deque<std::deque<int>> const& hidden_layers){ for(auto& h : hidden_layers) topologies.push_back(FeedforwardNetwork::build<T_HIDDEN, T_OUT>(train->at(0).input.size(), h, (int)train->at(0).output.size())); } template<class T_LOSS> void addGradientLoss(){ gradientLoss.push_back(std::make_shared<T_LOSS>()); } size_t getTotalModels(); void search(int process_number=0,int process_total = 1); }; #endif /* defined(__XAA1__model_selection__) */
32.848101
152
0.703661
45b63f5475bc945b4493dfecdc10f9a87d9f472e
51
c
C
test/_test/inputs/check_exec.c
RusuGabriel/E.L.F-Executable-Loader
6820ec4e36deb317fc177bd7716f73732827319f
[ "MIT" ]
5
2021-05-29T15:20:00.000Z
2022-03-16T23:55:49.000Z
test/_test/inputs/check_exec.c
RusuGabriel/E.L.F-Executable-Loader
6820ec4e36deb317fc177bd7716f73732827319f
[ "MIT" ]
1
2021-04-21T18:19:50.000Z
2021-04-21T18:19:50.000Z
test/_test/inputs/check_exec.c
RusuGabriel/E.L.F-Executable-Loader
6820ec4e36deb317fc177bd7716f73732827319f
[ "MIT" ]
3
2021-04-23T13:34:03.000Z
2022-02-24T06:54:03.000Z
void exit(int); void _start() { exit(0); }
7.285714
16
0.509804
a9e0c1f138c05fb2b40a357f707aebf79316f43f
378
h
C
OutPutHeaders/TPIDKeyboardButton.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
106
2016-04-09T01:16:14.000Z
2021-06-04T00:20:24.000Z
OutPutHeaders/TPIDKeyboardButton.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
2
2017-06-13T09:41:29.000Z
2018-03-26T03:32:07.000Z
OutPutHeaders/TPIDKeyboardButton.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
58
2016-04-28T09:52:08.000Z
2021-12-25T06:42:14.000Z
/** * This header is generated by class-dump-z 0.2a. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: (null) */ #import <XXUnknownSuperclass.h> // Unknown library @class UILabel; @interface TPIDKeyboardButton : XXUnknownSuperclass { UILabel* subtitleLabel; } @property(retain, nonatomic) UILabel* subtitleLabel; -(void)dealloc; @end
19.894737
72
0.724868
aa8e2655729fc4891c087328260e304667b80d89
492
h
C
sources/include/dangless/common.h
shdnx/dangless-malloc
7a028546cdb38c6658931c8928c59355e5b8eaa5
[ "BSD-3-Clause" ]
9
2018-06-04T07:04:23.000Z
2021-04-26T15:01:05.000Z
sources/include/dangless/common.h
shdnx/dangless-malloc
7a028546cdb38c6658931c8928c59355e5b8eaa5
[ "BSD-3-Clause" ]
2
2018-10-17T01:52:45.000Z
2019-11-28T00:41:44.000Z
sources/include/dangless/common.h
shdnx/dangless-malloc
7a028546cdb38c6658931c8928c59355e5b8eaa5
[ "BSD-3-Clause" ]
1
2020-05-03T10:30:21.000Z
2020-05-03T10:30:21.000Z
#ifndef DANGLESS_COMMON_H #define DANGLESS_COMMON_H #include "dangless/common/types.h" #include "dangless/common/dprintf.h" #include "dangless/common/assert.h" #include "dangless/common/util.h" // These are probably not useful enough to keep around. #define KB (1024uL) #define MB (1024uL * KB) #define GB (1024uL * MB) // For some reason, when compiling in release mode, off_t is undefined in libdune/dune.h. #if DANGLESS_CONFIG_PROFILE == release typedef ptrdiff_t off_t; #endif #endif
24.6
89
0.76626
a63d4de63f509a46aab6789fe76cd0db1322122d
17,918
c
C
OLD_COMPILER/shiltiumcomp58/portable/parse_statement.c
gregoryc/democracy
40bdc1a0783039290a622c083e8c809e3a7b0d0e
[ "BSD-2-Clause", "MIT" ]
null
null
null
OLD_COMPILER/shiltiumcomp58/portable/parse_statement.c
gregoryc/democracy
40bdc1a0783039290a622c083e8c809e3a7b0d0e
[ "BSD-2-Clause", "MIT" ]
null
null
null
OLD_COMPILER/shiltiumcomp58/portable/parse_statement.c
gregoryc/democracy
40bdc1a0783039290a622c083e8c809e3a7b0d0e
[ "BSD-2-Clause", "MIT" ]
null
null
null
/* Shiltiumcomp -- the first Shiltolang compiler Copyright (C) 2010 Gregory Cohen <gregorycohen2@gmail.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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef __cplusplus #include <cctype> #else #include <ctype.h> #endif #include "../global_headers/headers.h" #include "ensure_type_is_valid_otherwise_give_type_error.h" #include "insert_variable_into_scope.h" #include "show_tokens.h" #include "line_number.h" #include "read_char.h" #undef unsigned #undef short static Variable* get_variable(ParserState* cr state, const String* cr name) { Scope* scope; assert_comparison(state, !=, NULL, ParserState* cr, void*); assert_comparison(name, !=, NULL, const String* cr, void*); scope = &state->scope; while (scope) { bool in_hash_table; Variable* variable; variable = (Variable*)DEREF( hash_table_get_value_from_string_key( &scope->variables_in_scope, ARROW(name, string), ARROW(name, length), &in_hash_table ) ); if (in_hash_table) { return variable; } scope = ARROW(scope, parent_scope); } return NULL; } static Subroutine* get_subroutine(ParserState* cr state, const char* subroutine_name, const u length_of_subroutine_name) { Scope* scope; assert_comparison(state, !=, NULL, ParserState* cr, void*); assert_comparison(subroutine_name, !=, NULL, const char*, void*); assert_comparison(length_of_subroutine_name, !=, 0, const u, u); scope = &state->scope; while (scope) { bool in_hash_table; Subroutine* subroutine; subroutine = (Subroutine*)DEREF( hash_table_get_value_from_string_key( &scope->subroutines_in_scope, subroutine_name, length_of_subroutine_name, &in_hash_table ) ); if (in_hash_table) { return subroutine; } scope = ARROW(scope, parent_scope); } return NULL; } attr_nonnull static void ensure_that_argument_counts_are_equal_otherwise_give_type_error( const Subroutine* cr subroutine, const u length ) { assert_comparison(subroutine, !=, NULL, const Subroutine* cr, void*); if (unlikely(length != ARROW(subroutine, length_of_argument_type_list))) { output_nullt_string("Type error: gave "); putu(length); output_nullt_string(" argument"); if (length != 1) { output_char('s'); } output_nullt_string(" but "); putu(ARROW(subroutine, length_of_argument_type_list)); output_nullt_string(" are expected\n"); exit_program(); } } static Variable* create_variable_from_argument_expression( ParserState* cr state, Token** const tokens, const u first_argument_expression_index, const u last_argument_expression_index ) { Variable* variable; variable = (Variable*)m_alloc(sizeof(Variable)); if (unlikely(!variable)) { output_nullt_string("Unable to allocate a temporary variable for an expression in an argument list.\n"); exit_program(); } #if DEBUG /* This is set to point to -1 so that the program will definitely crash if it's used. It's set to this to prevent a debugging nightmare, or even worse, the program working in DEBUG mode but not working in release mode. */ ARROW_ASSIGN(variable, statement_declared_on) = (Statement*)-1; #endif ARROW_ASSIGN(variable, line_declared_on) = ARROW(ARRAY_INDEX(tokens, first_argument_expression_index), line_number); ARROW_ASSIGN(variable, name).string = NULL; ARROW_ASSIGN(variable, name).length = 0; parse_expression( variable, tokens, last_argument_expression_index, first_argument_expression_index, &state->scope.variables_in_scope, TYPE_FLOAT ); translate_expression_into_mid_level_instructions(ARROW(state, dac), ARROW(state, mli), variable, ARROW(state, stack_offset)); return variable; } __attribute__((nonnull (1, 4))) static void create_variables_from_argument_expressions_and_push_them_onto_the_stack( ParserState* cr state, Subroutine* cr subroutine, SubroutineForwardReference* cr subroutine_forward_reference, Token** const tokens, const u number_of_tokens ) { MidLevelInstruction* mid_level_instruction; u beginning_of_argument_expression_index; LinkedListHead argument_type_list_head; bool previous_token_is_a_comma; Variable* variable; u i; u length; assert_comparison(state, !=, NULL, ParserState* cr, void*); assert_comparison(tokens, !=, NULL, Token** const, void*); if (subroutine) { length = 0; if (!number_of_tokens) { ensure_that_argument_counts_are_equal_otherwise_give_type_error(subroutine, length); return; } } else { /* If this is removed, gcc gives an error. */ argument_type_list_head = NULL; if (!number_of_tokens) return; } if (unlikely( ARROW(ARRAY_INDEX(tokens, 0), string).length == 1 && DEREF(ARROW(ARRAY_INDEX(tokens, 0), string).string) == ',' )) { output_nullt_string("Syntax error: an argument list cannot begin with a comma\n"); exit_program(); } if (subroutine) { argument_type_list_head = ARROW(subroutine, argument_type_list); } previous_token_is_a_comma = false; beginning_of_argument_expression_index = false; for (i = 0; i < number_of_tokens; ++i) { /* if token is a comma */ if ( ARROW(ARRAY_INDEX(tokens, i), string).length == 1 && DEREF(ARROW(ARRAY_INDEX(tokens, i), string).string) == ',' ) { if (unlikely(previous_token_is_a_comma)) { output_nullt_string("Syntax error: two commas in a row in an argument list\n"); exit_program(); } in: variable = create_variable_from_argument_expression(state, tokens, beginning_of_argument_expression_index, i); if (subroutine) { if (likely(argument_type_list_head)) { if (unlikely((Type)(u)ARROW(argument_type_list_head, value) != TYPE_FLOAT)) { output_nullt_string("Type error: argument needs to be a float\n"); exit_program(); } } else { output_nullt_string("Type error: calling subroutine with too many arguments.\n"); exit_program(); } ++length; } else { linked_list_append(&subroutine_forward_reference->argument_type_list, (void*)TYPE_FLOAT); ARROW_ASSIGN(subroutine_forward_reference, length_of_argument_type_list)++; } mid_level_instruction = (MidLevelInstruction*)m_alloc(sizeof(MidLevelInstruction)); if (unlikely(!mid_level_instruction)) { output_nullt_string( "Memory error: unable to allocate memory for a " OPENING_QUOTE "push_argument" CLOSING_QUOTE " mid-level instruction.\n" ); } ARROW_ASSIGN(mid_level_instruction, opcode) = MLI_OPCODE_PUSH_ARGUMENT; ARROW_ASSIGN(mid_level_instruction, argument1) = variable; mid_level_instructions_append(ARROW(state, mli), mid_level_instruction, ARROW(state, dac)); beginning_of_argument_expression_index = i + 1; previous_token_is_a_comma = true; } else { previous_token_is_a_comma = false; } } if ( i == number_of_tokens && !( ARROW(ARRAY_INDEX(tokens, number_of_tokens - 1), string).length == 1 && DEREF(ARROW(ARRAY_INDEX(tokens, number_of_tokens - 1), string).string) == ',' ) ) { goto in; } if (subroutine) { ensure_that_argument_counts_are_equal_otherwise_give_type_error(subroutine, length); } } attr_nonnull static void variable_free_function(void* cr variable_) { Variable* variable; assert_comparison(variable_, !=, NULL, void*, void*); variable = (Variable*)variable_; if (unlikely(!ARROW(variable, evaluated))) { output_nullt_string("Variable error: unused variable " OPENING_QUOTE); output_string(ARROW(variable, name).string, ARROW(variable, name).length); output_nullt_string(CLOSING_QUOTE " (it was declared on line "); putu(ARROW(variable, line_declared_on)); output_nullt_string(")\n"); output_source_lines(ARROW(variable, statement_declared_on), ARROW(variable, line_declared_on)); exit_program(); } operand_linked_list_del(&variable->operands); operator_linked_list_del(&variable->operators); m_free(variable); } attr_nonnull void parse_statement(ParserState* cr state, Statement* cr statement) { #if DEBUG && SHOW_TOKENS u j; #endif /* just easier names to refer to */ Token** tokens; u number_of_tokens; assert_comparison(state, !=, NULL, ParserState* cr, void*); if (unlikely(!ARROW(state, in_subroutine))) { output_syntax_error_beginning_text(get_line_number(state), 0); output_nullt_string("normal statement not in subroutine\n"); exit_program(); } number_of_tokens = ARROW(statement, length_of_tokens); tokens = ARROW(statement, tokens); #if DEBUG && SHOW_TOKENS output_nullt_string("Tokens in statement:\n"); for (j = 0; j < number_of_tokens; ++j) { output_nullt_string(" "); output_string(ARROW(ARRAY_INDEX(tokens, j), string).string, ARROW(ARRAY_INDEX(tokens, j), string).length); output_newline(); } #endif /* This branch handles declaring initialized variables, for example: i = 0; */ if (number_of_tokens >= 4 && ARROW(ARRAY_INDEX(tokens, 2), string).length == 1 && ARROW(ARRAY_INDEX(tokens, 2), string).string[0] == '=') { Variable* variable; ensure_type_is_valid_otherwise_give_type_error( &ARRAY_INDEX(tokens, 0)->string, ARROW(ARRAY_INDEX(tokens, 0), line_number) ); if (unlikely(!is_valid_identifier(ARROW(ARRAY_INDEX(tokens, 1), string).string, ARROW(ARRAY_INDEX(tokens, 1), string).length))) { output_nullt_string("Identifier error on line "); putu(ARROW(ARRAY_INDEX(tokens, 1), line_number)); output_nullt_string(": invalid variable name " OPENING_QUOTE); output_string(ARROW(ARRAY_INDEX(tokens, 1), string).string, ARROW(ARRAY_INDEX(tokens, 1), string).length); output_nullt_string(CLOSING_QUOTE "\n"); exit_program(); } variable = (Variable*)m_alloc(sizeof(Variable)); if (unlikely(!variable)) { output_nullt_string("Memory error: Unable to allocate memory for variable.\n"); exit_program(); } free_list_append(ARROW(state, free_list_head), variable, variable_free_function); ARROW_ASSIGN(variable, statement_declared_on) = statement; ARROW_ASSIGN(variable, line_declared_on) = ARROW(ARRAY_INDEX(tokens, 1), line_number); ARROW_ASSIGN(variable, name).string = ARROW(ARRAY_INDEX(tokens, 1), string).string; ARROW_ASSIGN(variable, name).length = ARROW(ARRAY_INDEX(tokens, 1), string).length; ARROW_ASSIGN(variable, evaluated) = false; insert_variable_into_scope( state, ARROW(ARRAY_INDEX(tokens, 1), string).string, ARROW(ARRAY_INDEX(tokens, 1), string).length, variable ); switch (DEREF(ARROW(ARRAY_INDEX(tokens, 0), string).string)) { case 'u': { ARROW_ASSIGN(variable, type) = TYPE_UINT; parse_expression( variable, tokens, ARROW(statement, length_of_tokens), 3, &state->scope.variables_in_scope, TYPE_UINT ); break; } case 'f': { ARROW_ASSIGN(variable, type) = TYPE_FLOAT; parse_expression( variable, tokens, ARROW(statement, length_of_tokens), 3, &state->scope.variables_in_scope, TYPE_FLOAT ); break; } default: output_nullt_string("Not implemented yet. Please fix this.\n"); exit_program(); } } else if ( number_of_tokens == 2 && strnequal(ARROW(ARRAY_INDEX(tokens, 0), string).string, "output", ARROW(ARRAY_INDEX(tokens, 0), string).length, 6) ) { MidLevelInstruction* mid_level_instruction; Variable* variable; variable = get_variable(state, &ARRAY_INDEX(tokens, 1)->string); if (unlikely(!variable)) { output_nullt_string("Name error on line "); putu(ARROW(ARRAY_INDEX(tokens, 1), line_number)); output_nullt_string(": " OPENING_QUOTE); output_string(ARROW(ARRAY_INDEX(tokens, 1), string).string, ARROW(ARRAY_INDEX(tokens, 1), string).length); output_nullt_string(CLOSING_QUOTE " undeclared\n"); exit_program(); } mid_level_instruction = (MidLevelInstruction*)m_alloc(sizeof(MidLevelInstruction)); if (unlikely(!mid_level_instruction)) { output_nullt_string("Unable to allocate memory for " OPENING_QUOTE "send_message_to_ui" CLOSING_QUOTE " mid-level instruction.\n"); exit_program(); } if (!ARROW(variable, evaluated)) { translate_expression_into_mid_level_instructions(ARROW(state, dac), ARROW(state, mli), variable, ARROW(state, stack_offset)); } switch (ARROW(variable, type)) { case TYPE_UINT: ARROW_ASSIGN(mid_level_instruction, opcode) = MLI_OPCODE_SEND_OUTPUT_UINT_MESSAGE_TO_UI; break; case TYPE_SINT: output_nullt_string("SINT\n"); exit_program(); case TYPE_FLOAT: ARROW_ASSIGN(mid_level_instruction, opcode) = MLI_OPCODE_SEND_OUTPUT_FLOAT_MESSAGE_TO_UI; break; case TYPE_BOOL: output_nullt_string("SINT\n"); exit_program(); break; default: assert_comparison(0, !=, 0, u, u); } ARROW_ASSIGN(mid_level_instruction, argument1) = (void*)DEREF(ARROW(state, stack_offset)); ARROW_ASSIGN(mid_level_instruction, argument2) = (void*)variable; DEREF_ASSIGN(ARROW(state, stack_offset)) += sizeof(f) * 2; mid_level_instructions_append(ARROW(state, mli), mid_level_instruction, ARROW(state, dac)); } else if ( number_of_tokens == 1 && strnequal(ARROW(ARRAY_INDEX(tokens, 0), string).string, "hello_world", ARROW(ARRAY_INDEX(tokens, 0), string).length, 11) ) { MidLevelInstruction* mid_level_instruction = (MidLevelInstruction*)m_alloc(sizeof(MidLevelInstruction)); if (unlikely(!mid_level_instruction)) { output_nullt_string("Unable to allocate memory for mid-level instruction.\n"); exit_program(); } ARROW_ASSIGN(mid_level_instruction, opcode) = MLI_OPCODE_SEND_HELLO_WORLD_MESSAGE_TO_UI; ARROW_ASSIGN(mid_level_instruction, argument1) = (void*)DEREF(ARROW(state, stack_offset)); mid_level_instructions_append(ARROW(state, mli), mid_level_instruction, ARROW(state, dac)); DEREF_ASSIGN(ARROW(state, stack_offset)) += 8; } /* This branch handles calling subroutines. */ else if ( number_of_tokens >= 3 && ARROW(ARRAY_INDEX(tokens, 1), string).length == 1 && DEREF(ARROW(ARRAY_INDEX(tokens, 1), string).string) == '(' && ARROW(ARRAY_INDEX(tokens, number_of_tokens - 1), string).length == 1 && DEREF(ARROW(ARRAY_INDEX(tokens, number_of_tokens - 1), string).string) == ')' ) { MidLevelInstruction* mid_level_instruction; Subroutine* subroutine; mid_level_instruction = (MidLevelInstruction*)m_alloc(sizeof(MidLevelInstruction)); if (unlikely(!mid_level_instruction)) { output_nullt_string( "Memory error: unable to allocate memory for a " OPENING_QUOTE "call_subroutine" CLOSING_QUOTE " mid-level instruction.\n" ); exit_program(); } subroutine = get_subroutine(state, ARROW(ARRAY_INDEX(tokens, 0), string).string, ARROW(ARRAY_INDEX(tokens, 0), string).length); /* if the subroutine has already been defined */ if (subroutine) { create_variables_from_argument_expressions_and_push_them_onto_the_stack( state, subroutine, NULL, tokens + 2, number_of_tokens - 3 ); ARROW_ASSIGN(subroutine, used) = true; ARROW_ASSIGN(mid_level_instruction, argument1) = (void*)ARROW(subroutine, code_offset); } else { SubroutineForwardReference* subroutine_forward_reference = NULL; void** new_value; hash_table_insert_with_string_key( ARROW(state, subroutine_forward_references), ARROW(ARRAY_INDEX(tokens, 0), string).string, ARROW(ARRAY_INDEX(tokens, 0), string).length, NULL, false, &new_value ); if (!DEREF(new_value)) { /* m_zero_initialized_alloc() is called because all of the members of the SubroutineForwardReference struct should be initialized to zero. */ subroutine_forward_reference = (SubroutineForwardReference*)m_zero_initialized_alloc(sizeof(SubroutineForwardReference)); if (unlikely(!subroutine_forward_reference)) { output_nullt_string("Memory error: unable to allocate memory for a SubroutineForwardReference\n"); exit_program(); } DEREF_ASSIGN(new_value) = subroutine_forward_reference; } create_variables_from_argument_expressions_and_push_them_onto_the_stack( state, NULL, subroutine_forward_reference, tokens + 2, number_of_tokens - 3 ); linked_list_append(&subroutine_forward_reference->mid_level_instruction_list, mid_level_instruction); } ARROW_ASSIGN(mid_level_instruction, opcode) = MLI_OPCODE_CALL_SUBROUTINE; mid_level_instructions_append(ARROW(state, mli), mid_level_instruction, ARROW(state, dac)); } else if ( number_of_tokens == 2 && strnequal(ARROW(ARRAY_INDEX(tokens, 0), string).string, "import", ARROW(ARRAY_INDEX(tokens, 0), string).length, 6) ) { char* argv[3]; char* string; void real_main(char** const argv); string = m_alloc(ARROW(ARRAY_INDEX(tokens, 1), string).length + 1); memcpy(string, ARROW(ARRAY_INDEX(tokens, 1), string).string, ARROW(ARRAY_INDEX(tokens, 1), string).length); ARRAY_INDEX_ASSIGN(string, ARROW(ARRAY_INDEX(tokens, 1), string).length) = '\0'; argv[0] = NULL; argv[1] = string; argv[2] = NULL; real_main(argv); m_free(string); } /* Unknown syntax error */ else { output_syntax_error_beginning_text(ARROW(ARRAY_INDEX(tokens, 0), line_number), ARROW(ARRAY_INDEX(tokens, number_of_tokens - 1), line_number)); output_newline(); output_source_lines(statement, ARROW(ARRAY_INDEX(tokens, 0), line_number)); output_newline(); exit_program(); } }
30.681507
144
0.724858
c8f743476a8f85220ba43ea99515d7aae9075ba3
222
h
C
targets/stm32l432/src/sense.h
jolo1581/solo
4467b5570e414ce08f41a5fabe299dbfeaebc879
[ "Apache-2.0", "MIT" ]
1,671
2019-01-09T01:55:00.000Z
2022-03-06T13:03:05.000Z
targets/stm32l432/src/sense.h
jolo1581/solo
4467b5570e414ce08f41a5fabe299dbfeaebc879
[ "Apache-2.0", "MIT" ]
448
2019-01-07T21:58:09.000Z
2022-03-07T11:33:52.000Z
targets/stm32l432/src/sense.h
jolo1581/solo
4467b5570e414ce08f41a5fabe299dbfeaebc879
[ "Apache-2.0", "MIT" ]
241
2019-01-09T01:55:18.000Z
2022-02-17T19:43:21.000Z
#ifndef _SENSE_H_ #define _SENSE_H_ #include <stdint.h> void tsc_init(void); int tsc_sensor_exists(void); // Read button0 or button1 // Returns 1 if pressed, 0 if not. uint32_t tsc_read_button(uint32_t index); #endif
14.8
41
0.756757
0c133cc632dc6522653269e4564066610758c5fc
4,382
c
C
modules/hal/core/src/hal_common.c
bmdk/bmos
ad0556390bb822078aa26f921e16b31122c7a617
[ "MIT" ]
1
2021-11-08T08:30:49.000Z
2021-11-08T08:30:49.000Z
modules/hal/core/src/hal_common.c
bmdk/bmos
ad0556390bb822078aa26f921e16b31122c7a617
[ "MIT" ]
null
null
null
modules/hal/core/src/hal_common.c
bmdk/bmos
ad0556390bb822078aa26f921e16b31122c7a617
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2022 Brian Thomas Murphy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <shell.h> #include "io.h" #include "common.h" #include "xassert.h" #include "hal_common.h" #include "hal_board.h" #if ARCH_STM32 #include "stm32_flash.h" #include "stm32_hal.h" #endif extern unsigned int _fsdata, _rsdata, _redata, _sbss, _ebss, _stack_end; extern unsigned int _flash_start, _flash_end, _ram_start, _end; #if CONFIG_COPY_ISR extern unsigned int _isr_start, _isr_end; #endif static unsigned int sbrk_next = (unsigned int)&_end; void _data_init(void) { unsigned int *si, *s, *e; #if CONFIG_COPY_ISR si = &_flash_start; s = &_isr_start; /* copy initialized data from flash to ram */ if (s != si) { e = &_isr_end; while (s < e) *s++ = *si++; } #endif si = &_fsdata; s = &_rsdata; /* copy initialized data from flash to ram */ if (s != si) { e = &_redata; while (s < e) *s++ = *si++; } s = &_sbss; e = &_ebss; while (s < e) *s++ = 0; } static int cmd_mem(int argc, char *argv[]) { unsigned int data_start = (unsigned int)&_rsdata; unsigned int data_start_flash = (unsigned int)&_fsdata; unsigned int data_size = (unsigned int)&_redata - (unsigned int)&_rsdata; if (data_start == data_start_flash) { xprintf(" code: %08x - %08x: %6d\n", (unsigned int)&_flash_start, (unsigned int)data_start, (unsigned int)data_start - (unsigned int)&_flash_start); } xprintf(" ram: %08x - %08x: %6d\n", (unsigned int)&_ram_start, (unsigned int)&_stack_end, (unsigned int)&_stack_end - (unsigned int)&_ram_start); xprintf(" data: %08x - %08x: %6d\n", data_start, data_start + data_size, data_size); xprintf(" bss: %08x - %08x: %6d\n", (unsigned int)&_sbss, (unsigned int)&_ebss, (unsigned int)&_ebss - (unsigned int)&_sbss); xprintf(" heap: %08x - %08x: %6d\n", (unsigned int)&_end, sbrk_next, sbrk_next - (unsigned int)&_end); xprintf(" free: %08x - %08x: %6d\n", sbrk_next, (unsigned int)&_stack_end, (unsigned int)&_stack_end - sbrk_next); if (data_start != data_start_flash) { xprintf("\nflash: %08x - %08x: %6d\n", (unsigned int)&_flash_start, (unsigned int)&_flash_end, (unsigned int)&_flash_end - (unsigned int)&_flash_start); xprintf("fdata: %08x - %08x: %6d\n", data_start_flash, data_start_flash + data_size, data_size); } xprintf("\nfsize: %dk\n", hal_flash_size()); return 0; } SHELL_CMD(mem, cmd_mem); WEAK unsigned int hal_flash_size(void) { return 0; } static int cmd_hal(int argc, char *argv[]) { char cmd = 'c'; if (argc > 1) cmd = argv[1][0]; switch (cmd) { case 'c': xprintf("CPU clock: %d\n", hal_cpu_clock); break; #if ARCH_STM32 && !BOOT case 'l': xprintf("LS clock: %s\n", clock_ls_name()); break; #endif } return 0; } SHELL_CMD(hal, cmd_hal); #ifndef PRIVATE_SBRK #define _sbrk sbrk #endif void *_sbrk(int count) { unsigned int cur = sbrk_next; XASSERT(count >= 0); if (count > 0) /* align to next 8 byte boundary */ sbrk_next += ALIGN(count, 3); #if 0 xprintf("%08x %d %d\n", cur, count, ALIGN(count, 3)); #endif return (void *)cur; } void hal_init(void) { #if ARCH_STM32 stm32_flash_cache_enable(1); #endif }
25.776471
79
0.659288
08bcb58a96e39b08857baf90eef929d6e777f8a9
2,222
c
C
motomini_dynamics_publisher/src/MotoMINI_Model/pm_math_8d05b7c0.c
ntl-ros-pkg/motoman_path_planning
c9fbe19748a4290182997c2b5baa6a08375745e0
[ "Apache-2.0" ]
null
null
null
motomini_dynamics_publisher/src/MotoMINI_Model/pm_math_8d05b7c0.c
ntl-ros-pkg/motoman_path_planning
c9fbe19748a4290182997c2b5baa6a08375745e0
[ "Apache-2.0" ]
null
null
null
motomini_dynamics_publisher/src/MotoMINI_Model/pm_math_8d05b7c0.c
ntl-ros-pkg/motoman_path_planning
c9fbe19748a4290182997c2b5baa6a08375745e0
[ "Apache-2.0" ]
null
null
null
#include "pm_std.h" #include "math.h" void pm_math_lin_alg_geSolve2x2(const real_T pm_math__lerGssn0Ru_r3kSOzEmI_[4] ,const real_T b[2],real_T x[2]);void pm_math_lin_alg_geSolve2x2(const real_T pm_math__lerGssn0Ru_r3kSOzEmI_[4],const real_T b[2],real_T x[2]){if(fabs( pm_math__lerGssn0Ru_r3kSOzEmI_[0])>=fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[1])&& fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[0])>=fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[2 ])&&fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[0])>=fabs( pm_math__lerGssn0Ru_r3kSOzEmI_[3])){const real_T pm_math_PIqWtbzrbQqv_KS_31HnE2 =pm_math__lerGssn0Ru_r3kSOzEmI_[1]/pm_math__lerGssn0Ru_r3kSOzEmI_[0];x[1]=(b[1 ]-pm_math_PIqWtbzrbQqv_KS_31HnE2*b[0])/(pm_math__lerGssn0Ru_r3kSOzEmI_[3]- pm_math_PIqWtbzrbQqv_KS_31HnE2*pm_math__lerGssn0Ru_r3kSOzEmI_[2]);x[0]=(b[0]- pm_math__lerGssn0Ru_r3kSOzEmI_[2]*x[1])/pm_math__lerGssn0Ru_r3kSOzEmI_[0];} else if(fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[1])>=fabs( pm_math__lerGssn0Ru_r3kSOzEmI_[2])&&fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[1])>= fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[3])){const real_T pm_math_PIqWtbzrbQqv_KS_31HnE2=pm_math__lerGssn0Ru_r3kSOzEmI_[0]/ pm_math__lerGssn0Ru_r3kSOzEmI_[1];x[1]=(b[0]-pm_math_PIqWtbzrbQqv_KS_31HnE2*b[ 1])/(pm_math__lerGssn0Ru_r3kSOzEmI_[2]-pm_math_PIqWtbzrbQqv_KS_31HnE2* pm_math__lerGssn0Ru_r3kSOzEmI_[3]);x[0]=(b[1]-pm_math__lerGssn0Ru_r3kSOzEmI_[3 ]*x[1])/pm_math__lerGssn0Ru_r3kSOzEmI_[1];}else if(fabs( pm_math__lerGssn0Ru_r3kSOzEmI_[2])>=fabs(pm_math__lerGssn0Ru_r3kSOzEmI_[3])){ const real_T pm_math_PIqWtbzrbQqv_KS_31HnE2=pm_math__lerGssn0Ru_r3kSOzEmI_[3]/ pm_math__lerGssn0Ru_r3kSOzEmI_[2];x[0]=(b[1]-pm_math_PIqWtbzrbQqv_KS_31HnE2*b[ 0])/(pm_math__lerGssn0Ru_r3kSOzEmI_[1]-pm_math_PIqWtbzrbQqv_KS_31HnE2* pm_math__lerGssn0Ru_r3kSOzEmI_[0]);x[1]=(b[0]-pm_math__lerGssn0Ru_r3kSOzEmI_[0 ]*x[0])/pm_math__lerGssn0Ru_r3kSOzEmI_[2];}else{const real_T pm_math_PIqWtbzrbQqv_KS_31HnE2=pm_math__lerGssn0Ru_r3kSOzEmI_[2]/ pm_math__lerGssn0Ru_r3kSOzEmI_[3];x[0]=(b[0]-pm_math_PIqWtbzrbQqv_KS_31HnE2*b[ 1])/(pm_math__lerGssn0Ru_r3kSOzEmI_[0]-pm_math_PIqWtbzrbQqv_KS_31HnE2* pm_math__lerGssn0Ru_r3kSOzEmI_[1]);x[1]=(b[1]-pm_math__lerGssn0Ru_r3kSOzEmI_[1 ]*x[0])/pm_math__lerGssn0Ru_r3kSOzEmI_[3];}}
67.333333
80
0.830783
83769fa43c518e5b3ed966d5d12bbcee2102b1ce
64,891
c
C
fiat-c/src/p256_64.c
dderjoel/fiat-crypto
57a9612577d766a0ae83169ea9517bfa7f01ea4e
[ "BSD-1-Clause", "Apache-2.0", "MIT-0", "MIT" ]
491
2015-11-25T23:44:39.000Z
2022-03-29T17:31:21.000Z
fiat-c/src/p256_64.c
dderjoel/fiat-crypto
57a9612577d766a0ae83169ea9517bfa7f01ea4e
[ "BSD-1-Clause", "Apache-2.0", "MIT-0", "MIT" ]
755
2016-02-02T14:03:05.000Z
2022-03-31T16:47:23.000Z
fiat-c/src/p256_64.c
dderjoel/fiat-crypto
57a9612577d766a0ae83169ea9517bfa7f01ea4e
[ "BSD-1-Clause", "Apache-2.0", "MIT-0", "MIT" ]
117
2015-10-25T16:28:15.000Z
2022-02-08T23:01:09.000Z
/* Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --inline-internal --static --use-value-barrier p256 64 '2^256 - 2^224 + 2^192 + 2^96 - 1' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp */ /* curve description: p256 */ /* machine_wordsize = 64 (from "64") */ /* requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp */ /* m = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff (from "2^256 - 2^224 + 2^192 + 2^96 - 1") */ /* */ /* NOTE: In addition to the bounds specified above each function, all */ /* functions synthesized for this Montgomery arithmetic require the */ /* input to be strictly less than the prime modulus (m), and also */ /* require the input to be in the unique saturated representation. */ /* All functions also ensure that these two properties are true of */ /* return values. */ /* */ /* Computed values: */ /* eval z = z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) */ /* bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) */ /* twos_complement_eval z = let x1 := z[0] + (z[1] << 64) + (z[2] << 128) + (z[3] << 192) in */ /* if x1 & (2^256-1) < 2^255 then x1 & (2^256-1) else (x1 & (2^256-1)) - 2^256 */ #include <stdint.h> typedef unsigned char fiat_p256_uint1; typedef signed char fiat_p256_int1; #ifdef __GNUC__ # define FIAT_P256_FIAT_EXTENSION __extension__ # define FIAT_P256_FIAT_INLINE __inline__ #else # define FIAT_P256_FIAT_EXTENSION # define FIAT_P256_FIAT_INLINE #endif FIAT_P256_FIAT_EXTENSION typedef signed __int128 fiat_p256_int128; FIAT_P256_FIAT_EXTENSION typedef unsigned __int128 fiat_p256_uint128; /* The type fiat_p256_montgomery_domain_field_element is a field element in the Montgomery domain. */ /* Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ typedef uint64_t fiat_p256_montgomery_domain_field_element[4]; /* The type fiat_p256_non_montgomery_domain_field_element is a field element NOT in the Montgomery domain. */ /* Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ typedef uint64_t fiat_p256_non_montgomery_domain_field_element[4]; #if (-1 & 3) != 3 #error "This code only works on a two's complement system" #endif #if !defined(FIAT_P256_NO_ASM) && (defined(__GNUC__) || defined(__clang__)) static __inline__ uint64_t fiat_p256_value_barrier_u64(uint64_t a) { __asm__("" : "+r"(a) : /* no inputs */); return a; } #else # define fiat_p256_value_barrier_u64(x) (x) #endif /* * The function fiat_p256_addcarryx_u64 is an addition with carry. * * Postconditions: * out1 = (arg1 + arg2 + arg3) mod 2^64 * out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋ * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [0x0 ~> 0xffffffffffffffff] * arg3: [0x0 ~> 0xffffffffffffffff] * Output Bounds: * out1: [0x0 ~> 0xffffffffffffffff] * out2: [0x0 ~> 0x1] */ static FIAT_P256_FIAT_INLINE void fiat_p256_addcarryx_u64(uint64_t* out1, fiat_p256_uint1* out2, fiat_p256_uint1 arg1, uint64_t arg2, uint64_t arg3) { fiat_p256_uint128 x1; uint64_t x2; fiat_p256_uint1 x3; x1 = ((arg1 + (fiat_p256_uint128)arg2) + arg3); x2 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff)); x3 = (fiat_p256_uint1)(x1 >> 64); *out1 = x2; *out2 = x3; } /* * The function fiat_p256_subborrowx_u64 is a subtraction with borrow. * * Postconditions: * out1 = (-arg1 + arg2 + -arg3) mod 2^64 * out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋ * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [0x0 ~> 0xffffffffffffffff] * arg3: [0x0 ~> 0xffffffffffffffff] * Output Bounds: * out1: [0x0 ~> 0xffffffffffffffff] * out2: [0x0 ~> 0x1] */ static FIAT_P256_FIAT_INLINE void fiat_p256_subborrowx_u64(uint64_t* out1, fiat_p256_uint1* out2, fiat_p256_uint1 arg1, uint64_t arg2, uint64_t arg3) { fiat_p256_int128 x1; fiat_p256_int1 x2; uint64_t x3; x1 = ((arg2 - (fiat_p256_int128)arg1) - arg3); x2 = (fiat_p256_int1)(x1 >> 64); x3 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff)); *out1 = x3; *out2 = (fiat_p256_uint1)(0x0 - x2); } /* * The function fiat_p256_mulx_u64 is a multiplication, returning the full double-width result. * * Postconditions: * out1 = (arg1 * arg2) mod 2^64 * out2 = ⌊arg1 * arg2 / 2^64⌋ * * Input Bounds: * arg1: [0x0 ~> 0xffffffffffffffff] * arg2: [0x0 ~> 0xffffffffffffffff] * Output Bounds: * out1: [0x0 ~> 0xffffffffffffffff] * out2: [0x0 ~> 0xffffffffffffffff] */ static FIAT_P256_FIAT_INLINE void fiat_p256_mulx_u64(uint64_t* out1, uint64_t* out2, uint64_t arg1, uint64_t arg2) { fiat_p256_uint128 x1; uint64_t x2; uint64_t x3; x1 = ((fiat_p256_uint128)arg1 * arg2); x2 = (uint64_t)(x1 & UINT64_C(0xffffffffffffffff)); x3 = (uint64_t)(x1 >> 64); *out1 = x2; *out2 = x3; } /* * The function fiat_p256_cmovznz_u64 is a single-word conditional move. * * Postconditions: * out1 = (if arg1 = 0 then arg2 else arg3) * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [0x0 ~> 0xffffffffffffffff] * arg3: [0x0 ~> 0xffffffffffffffff] * Output Bounds: * out1: [0x0 ~> 0xffffffffffffffff] */ static FIAT_P256_FIAT_INLINE void fiat_p256_cmovznz_u64(uint64_t* out1, fiat_p256_uint1 arg1, uint64_t arg2, uint64_t arg3) { fiat_p256_uint1 x1; uint64_t x2; uint64_t x3; x1 = (!(!arg1)); x2 = ((fiat_p256_int1)(0x0 - x1) & UINT64_C(0xffffffffffffffff)); x3 = ((fiat_p256_value_barrier_u64(x2) & arg3) | (fiat_p256_value_barrier_u64((~x2)) & arg2)); *out1 = x3; } /* * The function fiat_p256_mul multiplies two field elements in the Montgomery domain. * * Preconditions: * 0 ≤ eval arg1 < m * 0 ≤ eval arg2 < m * Postconditions: * eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_mul(fiat_p256_montgomery_domain_field_element out1, const fiat_p256_montgomery_domain_field_element arg1, const fiat_p256_montgomery_domain_field_element arg2) { uint64_t x1; uint64_t x2; uint64_t x3; uint64_t x4; uint64_t x5; uint64_t x6; uint64_t x7; uint64_t x8; uint64_t x9; uint64_t x10; uint64_t x11; uint64_t x12; uint64_t x13; fiat_p256_uint1 x14; uint64_t x15; fiat_p256_uint1 x16; uint64_t x17; fiat_p256_uint1 x18; uint64_t x19; uint64_t x20; uint64_t x21; uint64_t x22; uint64_t x23; uint64_t x24; uint64_t x25; uint64_t x26; fiat_p256_uint1 x27; uint64_t x28; uint64_t x29; fiat_p256_uint1 x30; uint64_t x31; fiat_p256_uint1 x32; uint64_t x33; fiat_p256_uint1 x34; uint64_t x35; fiat_p256_uint1 x36; uint64_t x37; fiat_p256_uint1 x38; uint64_t x39; uint64_t x40; uint64_t x41; uint64_t x42; uint64_t x43; uint64_t x44; uint64_t x45; uint64_t x46; uint64_t x47; fiat_p256_uint1 x48; uint64_t x49; fiat_p256_uint1 x50; uint64_t x51; fiat_p256_uint1 x52; uint64_t x53; uint64_t x54; fiat_p256_uint1 x55; uint64_t x56; fiat_p256_uint1 x57; uint64_t x58; fiat_p256_uint1 x59; uint64_t x60; fiat_p256_uint1 x61; uint64_t x62; fiat_p256_uint1 x63; uint64_t x64; uint64_t x65; uint64_t x66; uint64_t x67; uint64_t x68; uint64_t x69; uint64_t x70; fiat_p256_uint1 x71; uint64_t x72; uint64_t x73; fiat_p256_uint1 x74; uint64_t x75; fiat_p256_uint1 x76; uint64_t x77; fiat_p256_uint1 x78; uint64_t x79; fiat_p256_uint1 x80; uint64_t x81; fiat_p256_uint1 x82; uint64_t x83; uint64_t x84; uint64_t x85; uint64_t x86; uint64_t x87; uint64_t x88; uint64_t x89; uint64_t x90; uint64_t x91; uint64_t x92; fiat_p256_uint1 x93; uint64_t x94; fiat_p256_uint1 x95; uint64_t x96; fiat_p256_uint1 x97; uint64_t x98; uint64_t x99; fiat_p256_uint1 x100; uint64_t x101; fiat_p256_uint1 x102; uint64_t x103; fiat_p256_uint1 x104; uint64_t x105; fiat_p256_uint1 x106; uint64_t x107; fiat_p256_uint1 x108; uint64_t x109; uint64_t x110; uint64_t x111; uint64_t x112; uint64_t x113; uint64_t x114; uint64_t x115; fiat_p256_uint1 x116; uint64_t x117; uint64_t x118; fiat_p256_uint1 x119; uint64_t x120; fiat_p256_uint1 x121; uint64_t x122; fiat_p256_uint1 x123; uint64_t x124; fiat_p256_uint1 x125; uint64_t x126; fiat_p256_uint1 x127; uint64_t x128; uint64_t x129; uint64_t x130; uint64_t x131; uint64_t x132; uint64_t x133; uint64_t x134; uint64_t x135; uint64_t x136; uint64_t x137; fiat_p256_uint1 x138; uint64_t x139; fiat_p256_uint1 x140; uint64_t x141; fiat_p256_uint1 x142; uint64_t x143; uint64_t x144; fiat_p256_uint1 x145; uint64_t x146; fiat_p256_uint1 x147; uint64_t x148; fiat_p256_uint1 x149; uint64_t x150; fiat_p256_uint1 x151; uint64_t x152; fiat_p256_uint1 x153; uint64_t x154; uint64_t x155; uint64_t x156; uint64_t x157; uint64_t x158; uint64_t x159; uint64_t x160; fiat_p256_uint1 x161; uint64_t x162; uint64_t x163; fiat_p256_uint1 x164; uint64_t x165; fiat_p256_uint1 x166; uint64_t x167; fiat_p256_uint1 x168; uint64_t x169; fiat_p256_uint1 x170; uint64_t x171; fiat_p256_uint1 x172; uint64_t x173; uint64_t x174; fiat_p256_uint1 x175; uint64_t x176; fiat_p256_uint1 x177; uint64_t x178; fiat_p256_uint1 x179; uint64_t x180; fiat_p256_uint1 x181; uint64_t x182; fiat_p256_uint1 x183; uint64_t x184; uint64_t x185; uint64_t x186; uint64_t x187; x1 = (arg1[1]); x2 = (arg1[2]); x3 = (arg1[3]); x4 = (arg1[0]); fiat_p256_mulx_u64(&x5, &x6, x4, (arg2[3])); fiat_p256_mulx_u64(&x7, &x8, x4, (arg2[2])); fiat_p256_mulx_u64(&x9, &x10, x4, (arg2[1])); fiat_p256_mulx_u64(&x11, &x12, x4, (arg2[0])); fiat_p256_addcarryx_u64(&x13, &x14, 0x0, x12, x9); fiat_p256_addcarryx_u64(&x15, &x16, x14, x10, x7); fiat_p256_addcarryx_u64(&x17, &x18, x16, x8, x5); x19 = (x18 + x6); fiat_p256_mulx_u64(&x20, &x21, x11, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x22, &x23, x11, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x24, &x25, x11, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x26, &x27, 0x0, x25, x22); x28 = (x27 + x23); fiat_p256_addcarryx_u64(&x29, &x30, 0x0, x11, x24); fiat_p256_addcarryx_u64(&x31, &x32, x30, x13, x26); fiat_p256_addcarryx_u64(&x33, &x34, x32, x15, x28); fiat_p256_addcarryx_u64(&x35, &x36, x34, x17, x20); fiat_p256_addcarryx_u64(&x37, &x38, x36, x19, x21); fiat_p256_mulx_u64(&x39, &x40, x1, (arg2[3])); fiat_p256_mulx_u64(&x41, &x42, x1, (arg2[2])); fiat_p256_mulx_u64(&x43, &x44, x1, (arg2[1])); fiat_p256_mulx_u64(&x45, &x46, x1, (arg2[0])); fiat_p256_addcarryx_u64(&x47, &x48, 0x0, x46, x43); fiat_p256_addcarryx_u64(&x49, &x50, x48, x44, x41); fiat_p256_addcarryx_u64(&x51, &x52, x50, x42, x39); x53 = (x52 + x40); fiat_p256_addcarryx_u64(&x54, &x55, 0x0, x31, x45); fiat_p256_addcarryx_u64(&x56, &x57, x55, x33, x47); fiat_p256_addcarryx_u64(&x58, &x59, x57, x35, x49); fiat_p256_addcarryx_u64(&x60, &x61, x59, x37, x51); fiat_p256_addcarryx_u64(&x62, &x63, x61, x38, x53); fiat_p256_mulx_u64(&x64, &x65, x54, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x66, &x67, x54, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x68, &x69, x54, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x70, &x71, 0x0, x69, x66); x72 = (x71 + x67); fiat_p256_addcarryx_u64(&x73, &x74, 0x0, x54, x68); fiat_p256_addcarryx_u64(&x75, &x76, x74, x56, x70); fiat_p256_addcarryx_u64(&x77, &x78, x76, x58, x72); fiat_p256_addcarryx_u64(&x79, &x80, x78, x60, x64); fiat_p256_addcarryx_u64(&x81, &x82, x80, x62, x65); x83 = ((uint64_t)x82 + x63); fiat_p256_mulx_u64(&x84, &x85, x2, (arg2[3])); fiat_p256_mulx_u64(&x86, &x87, x2, (arg2[2])); fiat_p256_mulx_u64(&x88, &x89, x2, (arg2[1])); fiat_p256_mulx_u64(&x90, &x91, x2, (arg2[0])); fiat_p256_addcarryx_u64(&x92, &x93, 0x0, x91, x88); fiat_p256_addcarryx_u64(&x94, &x95, x93, x89, x86); fiat_p256_addcarryx_u64(&x96, &x97, x95, x87, x84); x98 = (x97 + x85); fiat_p256_addcarryx_u64(&x99, &x100, 0x0, x75, x90); fiat_p256_addcarryx_u64(&x101, &x102, x100, x77, x92); fiat_p256_addcarryx_u64(&x103, &x104, x102, x79, x94); fiat_p256_addcarryx_u64(&x105, &x106, x104, x81, x96); fiat_p256_addcarryx_u64(&x107, &x108, x106, x83, x98); fiat_p256_mulx_u64(&x109, &x110, x99, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x111, &x112, x99, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x113, &x114, x99, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x115, &x116, 0x0, x114, x111); x117 = (x116 + x112); fiat_p256_addcarryx_u64(&x118, &x119, 0x0, x99, x113); fiat_p256_addcarryx_u64(&x120, &x121, x119, x101, x115); fiat_p256_addcarryx_u64(&x122, &x123, x121, x103, x117); fiat_p256_addcarryx_u64(&x124, &x125, x123, x105, x109); fiat_p256_addcarryx_u64(&x126, &x127, x125, x107, x110); x128 = ((uint64_t)x127 + x108); fiat_p256_mulx_u64(&x129, &x130, x3, (arg2[3])); fiat_p256_mulx_u64(&x131, &x132, x3, (arg2[2])); fiat_p256_mulx_u64(&x133, &x134, x3, (arg2[1])); fiat_p256_mulx_u64(&x135, &x136, x3, (arg2[0])); fiat_p256_addcarryx_u64(&x137, &x138, 0x0, x136, x133); fiat_p256_addcarryx_u64(&x139, &x140, x138, x134, x131); fiat_p256_addcarryx_u64(&x141, &x142, x140, x132, x129); x143 = (x142 + x130); fiat_p256_addcarryx_u64(&x144, &x145, 0x0, x120, x135); fiat_p256_addcarryx_u64(&x146, &x147, x145, x122, x137); fiat_p256_addcarryx_u64(&x148, &x149, x147, x124, x139); fiat_p256_addcarryx_u64(&x150, &x151, x149, x126, x141); fiat_p256_addcarryx_u64(&x152, &x153, x151, x128, x143); fiat_p256_mulx_u64(&x154, &x155, x144, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x156, &x157, x144, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x158, &x159, x144, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x160, &x161, 0x0, x159, x156); x162 = (x161 + x157); fiat_p256_addcarryx_u64(&x163, &x164, 0x0, x144, x158); fiat_p256_addcarryx_u64(&x165, &x166, x164, x146, x160); fiat_p256_addcarryx_u64(&x167, &x168, x166, x148, x162); fiat_p256_addcarryx_u64(&x169, &x170, x168, x150, x154); fiat_p256_addcarryx_u64(&x171, &x172, x170, x152, x155); x173 = ((uint64_t)x172 + x153); fiat_p256_subborrowx_u64(&x174, &x175, 0x0, x165, UINT64_C(0xffffffffffffffff)); fiat_p256_subborrowx_u64(&x176, &x177, x175, x167, UINT32_C(0xffffffff)); fiat_p256_subborrowx_u64(&x178, &x179, x177, x169, 0x0); fiat_p256_subborrowx_u64(&x180, &x181, x179, x171, UINT64_C(0xffffffff00000001)); fiat_p256_subborrowx_u64(&x182, &x183, x181, x173, 0x0); fiat_p256_cmovznz_u64(&x184, x183, x174, x165); fiat_p256_cmovznz_u64(&x185, x183, x176, x167); fiat_p256_cmovznz_u64(&x186, x183, x178, x169); fiat_p256_cmovznz_u64(&x187, x183, x180, x171); out1[0] = x184; out1[1] = x185; out1[2] = x186; out1[3] = x187; } /* * The function fiat_p256_square squares a field element in the Montgomery domain. * * Preconditions: * 0 ≤ eval arg1 < m * Postconditions: * eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_square(fiat_p256_montgomery_domain_field_element out1, const fiat_p256_montgomery_domain_field_element arg1) { uint64_t x1; uint64_t x2; uint64_t x3; uint64_t x4; uint64_t x5; uint64_t x6; uint64_t x7; uint64_t x8; uint64_t x9; uint64_t x10; uint64_t x11; uint64_t x12; uint64_t x13; fiat_p256_uint1 x14; uint64_t x15; fiat_p256_uint1 x16; uint64_t x17; fiat_p256_uint1 x18; uint64_t x19; uint64_t x20; uint64_t x21; uint64_t x22; uint64_t x23; uint64_t x24; uint64_t x25; uint64_t x26; fiat_p256_uint1 x27; uint64_t x28; uint64_t x29; fiat_p256_uint1 x30; uint64_t x31; fiat_p256_uint1 x32; uint64_t x33; fiat_p256_uint1 x34; uint64_t x35; fiat_p256_uint1 x36; uint64_t x37; fiat_p256_uint1 x38; uint64_t x39; uint64_t x40; uint64_t x41; uint64_t x42; uint64_t x43; uint64_t x44; uint64_t x45; uint64_t x46; uint64_t x47; fiat_p256_uint1 x48; uint64_t x49; fiat_p256_uint1 x50; uint64_t x51; fiat_p256_uint1 x52; uint64_t x53; uint64_t x54; fiat_p256_uint1 x55; uint64_t x56; fiat_p256_uint1 x57; uint64_t x58; fiat_p256_uint1 x59; uint64_t x60; fiat_p256_uint1 x61; uint64_t x62; fiat_p256_uint1 x63; uint64_t x64; uint64_t x65; uint64_t x66; uint64_t x67; uint64_t x68; uint64_t x69; uint64_t x70; fiat_p256_uint1 x71; uint64_t x72; uint64_t x73; fiat_p256_uint1 x74; uint64_t x75; fiat_p256_uint1 x76; uint64_t x77; fiat_p256_uint1 x78; uint64_t x79; fiat_p256_uint1 x80; uint64_t x81; fiat_p256_uint1 x82; uint64_t x83; uint64_t x84; uint64_t x85; uint64_t x86; uint64_t x87; uint64_t x88; uint64_t x89; uint64_t x90; uint64_t x91; uint64_t x92; fiat_p256_uint1 x93; uint64_t x94; fiat_p256_uint1 x95; uint64_t x96; fiat_p256_uint1 x97; uint64_t x98; uint64_t x99; fiat_p256_uint1 x100; uint64_t x101; fiat_p256_uint1 x102; uint64_t x103; fiat_p256_uint1 x104; uint64_t x105; fiat_p256_uint1 x106; uint64_t x107; fiat_p256_uint1 x108; uint64_t x109; uint64_t x110; uint64_t x111; uint64_t x112; uint64_t x113; uint64_t x114; uint64_t x115; fiat_p256_uint1 x116; uint64_t x117; uint64_t x118; fiat_p256_uint1 x119; uint64_t x120; fiat_p256_uint1 x121; uint64_t x122; fiat_p256_uint1 x123; uint64_t x124; fiat_p256_uint1 x125; uint64_t x126; fiat_p256_uint1 x127; uint64_t x128; uint64_t x129; uint64_t x130; uint64_t x131; uint64_t x132; uint64_t x133; uint64_t x134; uint64_t x135; uint64_t x136; uint64_t x137; fiat_p256_uint1 x138; uint64_t x139; fiat_p256_uint1 x140; uint64_t x141; fiat_p256_uint1 x142; uint64_t x143; uint64_t x144; fiat_p256_uint1 x145; uint64_t x146; fiat_p256_uint1 x147; uint64_t x148; fiat_p256_uint1 x149; uint64_t x150; fiat_p256_uint1 x151; uint64_t x152; fiat_p256_uint1 x153; uint64_t x154; uint64_t x155; uint64_t x156; uint64_t x157; uint64_t x158; uint64_t x159; uint64_t x160; fiat_p256_uint1 x161; uint64_t x162; uint64_t x163; fiat_p256_uint1 x164; uint64_t x165; fiat_p256_uint1 x166; uint64_t x167; fiat_p256_uint1 x168; uint64_t x169; fiat_p256_uint1 x170; uint64_t x171; fiat_p256_uint1 x172; uint64_t x173; uint64_t x174; fiat_p256_uint1 x175; uint64_t x176; fiat_p256_uint1 x177; uint64_t x178; fiat_p256_uint1 x179; uint64_t x180; fiat_p256_uint1 x181; uint64_t x182; fiat_p256_uint1 x183; uint64_t x184; uint64_t x185; uint64_t x186; uint64_t x187; x1 = (arg1[1]); x2 = (arg1[2]); x3 = (arg1[3]); x4 = (arg1[0]); fiat_p256_mulx_u64(&x5, &x6, x4, (arg1[3])); fiat_p256_mulx_u64(&x7, &x8, x4, (arg1[2])); fiat_p256_mulx_u64(&x9, &x10, x4, (arg1[1])); fiat_p256_mulx_u64(&x11, &x12, x4, (arg1[0])); fiat_p256_addcarryx_u64(&x13, &x14, 0x0, x12, x9); fiat_p256_addcarryx_u64(&x15, &x16, x14, x10, x7); fiat_p256_addcarryx_u64(&x17, &x18, x16, x8, x5); x19 = (x18 + x6); fiat_p256_mulx_u64(&x20, &x21, x11, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x22, &x23, x11, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x24, &x25, x11, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x26, &x27, 0x0, x25, x22); x28 = (x27 + x23); fiat_p256_addcarryx_u64(&x29, &x30, 0x0, x11, x24); fiat_p256_addcarryx_u64(&x31, &x32, x30, x13, x26); fiat_p256_addcarryx_u64(&x33, &x34, x32, x15, x28); fiat_p256_addcarryx_u64(&x35, &x36, x34, x17, x20); fiat_p256_addcarryx_u64(&x37, &x38, x36, x19, x21); fiat_p256_mulx_u64(&x39, &x40, x1, (arg1[3])); fiat_p256_mulx_u64(&x41, &x42, x1, (arg1[2])); fiat_p256_mulx_u64(&x43, &x44, x1, (arg1[1])); fiat_p256_mulx_u64(&x45, &x46, x1, (arg1[0])); fiat_p256_addcarryx_u64(&x47, &x48, 0x0, x46, x43); fiat_p256_addcarryx_u64(&x49, &x50, x48, x44, x41); fiat_p256_addcarryx_u64(&x51, &x52, x50, x42, x39); x53 = (x52 + x40); fiat_p256_addcarryx_u64(&x54, &x55, 0x0, x31, x45); fiat_p256_addcarryx_u64(&x56, &x57, x55, x33, x47); fiat_p256_addcarryx_u64(&x58, &x59, x57, x35, x49); fiat_p256_addcarryx_u64(&x60, &x61, x59, x37, x51); fiat_p256_addcarryx_u64(&x62, &x63, x61, x38, x53); fiat_p256_mulx_u64(&x64, &x65, x54, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x66, &x67, x54, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x68, &x69, x54, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x70, &x71, 0x0, x69, x66); x72 = (x71 + x67); fiat_p256_addcarryx_u64(&x73, &x74, 0x0, x54, x68); fiat_p256_addcarryx_u64(&x75, &x76, x74, x56, x70); fiat_p256_addcarryx_u64(&x77, &x78, x76, x58, x72); fiat_p256_addcarryx_u64(&x79, &x80, x78, x60, x64); fiat_p256_addcarryx_u64(&x81, &x82, x80, x62, x65); x83 = ((uint64_t)x82 + x63); fiat_p256_mulx_u64(&x84, &x85, x2, (arg1[3])); fiat_p256_mulx_u64(&x86, &x87, x2, (arg1[2])); fiat_p256_mulx_u64(&x88, &x89, x2, (arg1[1])); fiat_p256_mulx_u64(&x90, &x91, x2, (arg1[0])); fiat_p256_addcarryx_u64(&x92, &x93, 0x0, x91, x88); fiat_p256_addcarryx_u64(&x94, &x95, x93, x89, x86); fiat_p256_addcarryx_u64(&x96, &x97, x95, x87, x84); x98 = (x97 + x85); fiat_p256_addcarryx_u64(&x99, &x100, 0x0, x75, x90); fiat_p256_addcarryx_u64(&x101, &x102, x100, x77, x92); fiat_p256_addcarryx_u64(&x103, &x104, x102, x79, x94); fiat_p256_addcarryx_u64(&x105, &x106, x104, x81, x96); fiat_p256_addcarryx_u64(&x107, &x108, x106, x83, x98); fiat_p256_mulx_u64(&x109, &x110, x99, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x111, &x112, x99, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x113, &x114, x99, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x115, &x116, 0x0, x114, x111); x117 = (x116 + x112); fiat_p256_addcarryx_u64(&x118, &x119, 0x0, x99, x113); fiat_p256_addcarryx_u64(&x120, &x121, x119, x101, x115); fiat_p256_addcarryx_u64(&x122, &x123, x121, x103, x117); fiat_p256_addcarryx_u64(&x124, &x125, x123, x105, x109); fiat_p256_addcarryx_u64(&x126, &x127, x125, x107, x110); x128 = ((uint64_t)x127 + x108); fiat_p256_mulx_u64(&x129, &x130, x3, (arg1[3])); fiat_p256_mulx_u64(&x131, &x132, x3, (arg1[2])); fiat_p256_mulx_u64(&x133, &x134, x3, (arg1[1])); fiat_p256_mulx_u64(&x135, &x136, x3, (arg1[0])); fiat_p256_addcarryx_u64(&x137, &x138, 0x0, x136, x133); fiat_p256_addcarryx_u64(&x139, &x140, x138, x134, x131); fiat_p256_addcarryx_u64(&x141, &x142, x140, x132, x129); x143 = (x142 + x130); fiat_p256_addcarryx_u64(&x144, &x145, 0x0, x120, x135); fiat_p256_addcarryx_u64(&x146, &x147, x145, x122, x137); fiat_p256_addcarryx_u64(&x148, &x149, x147, x124, x139); fiat_p256_addcarryx_u64(&x150, &x151, x149, x126, x141); fiat_p256_addcarryx_u64(&x152, &x153, x151, x128, x143); fiat_p256_mulx_u64(&x154, &x155, x144, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x156, &x157, x144, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x158, &x159, x144, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x160, &x161, 0x0, x159, x156); x162 = (x161 + x157); fiat_p256_addcarryx_u64(&x163, &x164, 0x0, x144, x158); fiat_p256_addcarryx_u64(&x165, &x166, x164, x146, x160); fiat_p256_addcarryx_u64(&x167, &x168, x166, x148, x162); fiat_p256_addcarryx_u64(&x169, &x170, x168, x150, x154); fiat_p256_addcarryx_u64(&x171, &x172, x170, x152, x155); x173 = ((uint64_t)x172 + x153); fiat_p256_subborrowx_u64(&x174, &x175, 0x0, x165, UINT64_C(0xffffffffffffffff)); fiat_p256_subborrowx_u64(&x176, &x177, x175, x167, UINT32_C(0xffffffff)); fiat_p256_subborrowx_u64(&x178, &x179, x177, x169, 0x0); fiat_p256_subborrowx_u64(&x180, &x181, x179, x171, UINT64_C(0xffffffff00000001)); fiat_p256_subborrowx_u64(&x182, &x183, x181, x173, 0x0); fiat_p256_cmovznz_u64(&x184, x183, x174, x165); fiat_p256_cmovznz_u64(&x185, x183, x176, x167); fiat_p256_cmovznz_u64(&x186, x183, x178, x169); fiat_p256_cmovznz_u64(&x187, x183, x180, x171); out1[0] = x184; out1[1] = x185; out1[2] = x186; out1[3] = x187; } /* * The function fiat_p256_add adds two field elements in the Montgomery domain. * * Preconditions: * 0 ≤ eval arg1 < m * 0 ≤ eval arg2 < m * Postconditions: * eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_add(fiat_p256_montgomery_domain_field_element out1, const fiat_p256_montgomery_domain_field_element arg1, const fiat_p256_montgomery_domain_field_element arg2) { uint64_t x1; fiat_p256_uint1 x2; uint64_t x3; fiat_p256_uint1 x4; uint64_t x5; fiat_p256_uint1 x6; uint64_t x7; fiat_p256_uint1 x8; uint64_t x9; fiat_p256_uint1 x10; uint64_t x11; fiat_p256_uint1 x12; uint64_t x13; fiat_p256_uint1 x14; uint64_t x15; fiat_p256_uint1 x16; uint64_t x17; fiat_p256_uint1 x18; uint64_t x19; uint64_t x20; uint64_t x21; uint64_t x22; fiat_p256_addcarryx_u64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); fiat_p256_addcarryx_u64(&x3, &x4, x2, (arg1[1]), (arg2[1])); fiat_p256_addcarryx_u64(&x5, &x6, x4, (arg1[2]), (arg2[2])); fiat_p256_addcarryx_u64(&x7, &x8, x6, (arg1[3]), (arg2[3])); fiat_p256_subborrowx_u64(&x9, &x10, 0x0, x1, UINT64_C(0xffffffffffffffff)); fiat_p256_subborrowx_u64(&x11, &x12, x10, x3, UINT32_C(0xffffffff)); fiat_p256_subborrowx_u64(&x13, &x14, x12, x5, 0x0); fiat_p256_subborrowx_u64(&x15, &x16, x14, x7, UINT64_C(0xffffffff00000001)); fiat_p256_subborrowx_u64(&x17, &x18, x16, x8, 0x0); fiat_p256_cmovznz_u64(&x19, x18, x9, x1); fiat_p256_cmovznz_u64(&x20, x18, x11, x3); fiat_p256_cmovznz_u64(&x21, x18, x13, x5); fiat_p256_cmovznz_u64(&x22, x18, x15, x7); out1[0] = x19; out1[1] = x20; out1[2] = x21; out1[3] = x22; } /* * The function fiat_p256_sub subtracts two field elements in the Montgomery domain. * * Preconditions: * 0 ≤ eval arg1 < m * 0 ≤ eval arg2 < m * Postconditions: * eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_sub(fiat_p256_montgomery_domain_field_element out1, const fiat_p256_montgomery_domain_field_element arg1, const fiat_p256_montgomery_domain_field_element arg2) { uint64_t x1; fiat_p256_uint1 x2; uint64_t x3; fiat_p256_uint1 x4; uint64_t x5; fiat_p256_uint1 x6; uint64_t x7; fiat_p256_uint1 x8; uint64_t x9; uint64_t x10; fiat_p256_uint1 x11; uint64_t x12; fiat_p256_uint1 x13; uint64_t x14; fiat_p256_uint1 x15; uint64_t x16; fiat_p256_uint1 x17; fiat_p256_subborrowx_u64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); fiat_p256_subborrowx_u64(&x3, &x4, x2, (arg1[1]), (arg2[1])); fiat_p256_subborrowx_u64(&x5, &x6, x4, (arg1[2]), (arg2[2])); fiat_p256_subborrowx_u64(&x7, &x8, x6, (arg1[3]), (arg2[3])); fiat_p256_cmovznz_u64(&x9, x8, 0x0, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x10, &x11, 0x0, x1, x9); fiat_p256_addcarryx_u64(&x12, &x13, x11, x3, (x9 & UINT32_C(0xffffffff))); fiat_p256_addcarryx_u64(&x14, &x15, x13, x5, 0x0); fiat_p256_addcarryx_u64(&x16, &x17, x15, x7, (x9 & UINT64_C(0xffffffff00000001))); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /* * The function fiat_p256_opp negates a field element in the Montgomery domain. * * Preconditions: * 0 ≤ eval arg1 < m * Postconditions: * eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_opp(fiat_p256_montgomery_domain_field_element out1, const fiat_p256_montgomery_domain_field_element arg1) { uint64_t x1; fiat_p256_uint1 x2; uint64_t x3; fiat_p256_uint1 x4; uint64_t x5; fiat_p256_uint1 x6; uint64_t x7; fiat_p256_uint1 x8; uint64_t x9; uint64_t x10; fiat_p256_uint1 x11; uint64_t x12; fiat_p256_uint1 x13; uint64_t x14; fiat_p256_uint1 x15; uint64_t x16; fiat_p256_uint1 x17; fiat_p256_subborrowx_u64(&x1, &x2, 0x0, 0x0, (arg1[0])); fiat_p256_subborrowx_u64(&x3, &x4, x2, 0x0, (arg1[1])); fiat_p256_subborrowx_u64(&x5, &x6, x4, 0x0, (arg1[2])); fiat_p256_subborrowx_u64(&x7, &x8, x6, 0x0, (arg1[3])); fiat_p256_cmovznz_u64(&x9, x8, 0x0, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x10, &x11, 0x0, x1, x9); fiat_p256_addcarryx_u64(&x12, &x13, x11, x3, (x9 & UINT32_C(0xffffffff))); fiat_p256_addcarryx_u64(&x14, &x15, x13, x5, 0x0); fiat_p256_addcarryx_u64(&x16, &x17, x15, x7, (x9 & UINT64_C(0xffffffff00000001))); out1[0] = x10; out1[1] = x12; out1[2] = x14; out1[3] = x16; } /* * The function fiat_p256_from_montgomery translates a field element out of the Montgomery domain. * * Preconditions: * 0 ≤ eval arg1 < m * Postconditions: * eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_from_montgomery(fiat_p256_non_montgomery_domain_field_element out1, const fiat_p256_montgomery_domain_field_element arg1) { uint64_t x1; uint64_t x2; uint64_t x3; uint64_t x4; uint64_t x5; uint64_t x6; uint64_t x7; uint64_t x8; fiat_p256_uint1 x9; uint64_t x10; fiat_p256_uint1 x11; uint64_t x12; fiat_p256_uint1 x13; uint64_t x14; fiat_p256_uint1 x15; uint64_t x16; uint64_t x17; uint64_t x18; uint64_t x19; uint64_t x20; uint64_t x21; uint64_t x22; fiat_p256_uint1 x23; uint64_t x24; fiat_p256_uint1 x25; uint64_t x26; fiat_p256_uint1 x27; uint64_t x28; fiat_p256_uint1 x29; uint64_t x30; fiat_p256_uint1 x31; uint64_t x32; fiat_p256_uint1 x33; uint64_t x34; fiat_p256_uint1 x35; uint64_t x36; fiat_p256_uint1 x37; uint64_t x38; uint64_t x39; uint64_t x40; uint64_t x41; uint64_t x42; uint64_t x43; uint64_t x44; fiat_p256_uint1 x45; uint64_t x46; fiat_p256_uint1 x47; uint64_t x48; fiat_p256_uint1 x49; uint64_t x50; fiat_p256_uint1 x51; uint64_t x52; fiat_p256_uint1 x53; uint64_t x54; fiat_p256_uint1 x55; uint64_t x56; fiat_p256_uint1 x57; uint64_t x58; fiat_p256_uint1 x59; uint64_t x60; uint64_t x61; uint64_t x62; uint64_t x63; uint64_t x64; uint64_t x65; uint64_t x66; fiat_p256_uint1 x67; uint64_t x68; fiat_p256_uint1 x69; uint64_t x70; fiat_p256_uint1 x71; uint64_t x72; fiat_p256_uint1 x73; uint64_t x74; fiat_p256_uint1 x75; uint64_t x76; uint64_t x77; fiat_p256_uint1 x78; uint64_t x79; fiat_p256_uint1 x80; uint64_t x81; fiat_p256_uint1 x82; uint64_t x83; fiat_p256_uint1 x84; uint64_t x85; fiat_p256_uint1 x86; uint64_t x87; uint64_t x88; uint64_t x89; uint64_t x90; x1 = (arg1[0]); fiat_p256_mulx_u64(&x2, &x3, x1, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x4, &x5, x1, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x6, &x7, x1, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x8, &x9, 0x0, x7, x4); fiat_p256_addcarryx_u64(&x10, &x11, 0x0, x1, x6); fiat_p256_addcarryx_u64(&x12, &x13, x11, 0x0, x8); fiat_p256_addcarryx_u64(&x14, &x15, 0x0, x12, (arg1[1])); fiat_p256_mulx_u64(&x16, &x17, x14, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x18, &x19, x14, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x20, &x21, x14, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x22, &x23, 0x0, x21, x18); fiat_p256_addcarryx_u64(&x24, &x25, 0x0, x14, x20); fiat_p256_addcarryx_u64(&x26, &x27, x25, (x15 + (x13 + (x9 + x5))), x22); fiat_p256_addcarryx_u64(&x28, &x29, x27, x2, (x23 + x19)); fiat_p256_addcarryx_u64(&x30, &x31, x29, x3, x16); fiat_p256_addcarryx_u64(&x32, &x33, 0x0, x26, (arg1[2])); fiat_p256_addcarryx_u64(&x34, &x35, x33, x28, 0x0); fiat_p256_addcarryx_u64(&x36, &x37, x35, x30, 0x0); fiat_p256_mulx_u64(&x38, &x39, x32, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x40, &x41, x32, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x42, &x43, x32, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x44, &x45, 0x0, x43, x40); fiat_p256_addcarryx_u64(&x46, &x47, 0x0, x32, x42); fiat_p256_addcarryx_u64(&x48, &x49, x47, x34, x44); fiat_p256_addcarryx_u64(&x50, &x51, x49, x36, (x45 + x41)); fiat_p256_addcarryx_u64(&x52, &x53, x51, (x37 + (x31 + x17)), x38); fiat_p256_addcarryx_u64(&x54, &x55, 0x0, x48, (arg1[3])); fiat_p256_addcarryx_u64(&x56, &x57, x55, x50, 0x0); fiat_p256_addcarryx_u64(&x58, &x59, x57, x52, 0x0); fiat_p256_mulx_u64(&x60, &x61, x54, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x62, &x63, x54, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x64, &x65, x54, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x66, &x67, 0x0, x65, x62); fiat_p256_addcarryx_u64(&x68, &x69, 0x0, x54, x64); fiat_p256_addcarryx_u64(&x70, &x71, x69, x56, x66); fiat_p256_addcarryx_u64(&x72, &x73, x71, x58, (x67 + x63)); fiat_p256_addcarryx_u64(&x74, &x75, x73, (x59 + (x53 + x39)), x60); x76 = (x75 + x61); fiat_p256_subborrowx_u64(&x77, &x78, 0x0, x70, UINT64_C(0xffffffffffffffff)); fiat_p256_subborrowx_u64(&x79, &x80, x78, x72, UINT32_C(0xffffffff)); fiat_p256_subborrowx_u64(&x81, &x82, x80, x74, 0x0); fiat_p256_subborrowx_u64(&x83, &x84, x82, x76, UINT64_C(0xffffffff00000001)); fiat_p256_subborrowx_u64(&x85, &x86, x84, 0x0, 0x0); fiat_p256_cmovznz_u64(&x87, x86, x77, x70); fiat_p256_cmovznz_u64(&x88, x86, x79, x72); fiat_p256_cmovznz_u64(&x89, x86, x81, x74); fiat_p256_cmovznz_u64(&x90, x86, x83, x76); out1[0] = x87; out1[1] = x88; out1[2] = x89; out1[3] = x90; } /* * The function fiat_p256_to_montgomery translates a field element into the Montgomery domain. * * Preconditions: * 0 ≤ eval arg1 < m * Postconditions: * eval (from_montgomery out1) mod m = eval arg1 mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_to_montgomery(fiat_p256_montgomery_domain_field_element out1, const fiat_p256_non_montgomery_domain_field_element arg1) { uint64_t x1; uint64_t x2; uint64_t x3; uint64_t x4; uint64_t x5; uint64_t x6; uint64_t x7; uint64_t x8; uint64_t x9; uint64_t x10; uint64_t x11; uint64_t x12; uint64_t x13; fiat_p256_uint1 x14; uint64_t x15; fiat_p256_uint1 x16; uint64_t x17; fiat_p256_uint1 x18; uint64_t x19; uint64_t x20; uint64_t x21; uint64_t x22; uint64_t x23; uint64_t x24; uint64_t x25; fiat_p256_uint1 x26; uint64_t x27; fiat_p256_uint1 x28; uint64_t x29; fiat_p256_uint1 x30; uint64_t x31; fiat_p256_uint1 x32; uint64_t x33; fiat_p256_uint1 x34; uint64_t x35; fiat_p256_uint1 x36; uint64_t x37; uint64_t x38; uint64_t x39; uint64_t x40; uint64_t x41; uint64_t x42; uint64_t x43; uint64_t x44; uint64_t x45; fiat_p256_uint1 x46; uint64_t x47; fiat_p256_uint1 x48; uint64_t x49; fiat_p256_uint1 x50; uint64_t x51; fiat_p256_uint1 x52; uint64_t x53; fiat_p256_uint1 x54; uint64_t x55; fiat_p256_uint1 x56; uint64_t x57; fiat_p256_uint1 x58; uint64_t x59; uint64_t x60; uint64_t x61; uint64_t x62; uint64_t x63; uint64_t x64; uint64_t x65; fiat_p256_uint1 x66; uint64_t x67; fiat_p256_uint1 x68; uint64_t x69; fiat_p256_uint1 x70; uint64_t x71; fiat_p256_uint1 x72; uint64_t x73; fiat_p256_uint1 x74; uint64_t x75; fiat_p256_uint1 x76; uint64_t x77; uint64_t x78; uint64_t x79; uint64_t x80; uint64_t x81; uint64_t x82; uint64_t x83; uint64_t x84; uint64_t x85; fiat_p256_uint1 x86; uint64_t x87; fiat_p256_uint1 x88; uint64_t x89; fiat_p256_uint1 x90; uint64_t x91; fiat_p256_uint1 x92; uint64_t x93; fiat_p256_uint1 x94; uint64_t x95; fiat_p256_uint1 x96; uint64_t x97; fiat_p256_uint1 x98; uint64_t x99; uint64_t x100; uint64_t x101; uint64_t x102; uint64_t x103; uint64_t x104; uint64_t x105; fiat_p256_uint1 x106; uint64_t x107; fiat_p256_uint1 x108; uint64_t x109; fiat_p256_uint1 x110; uint64_t x111; fiat_p256_uint1 x112; uint64_t x113; fiat_p256_uint1 x114; uint64_t x115; fiat_p256_uint1 x116; uint64_t x117; uint64_t x118; uint64_t x119; uint64_t x120; uint64_t x121; uint64_t x122; uint64_t x123; uint64_t x124; uint64_t x125; fiat_p256_uint1 x126; uint64_t x127; fiat_p256_uint1 x128; uint64_t x129; fiat_p256_uint1 x130; uint64_t x131; fiat_p256_uint1 x132; uint64_t x133; fiat_p256_uint1 x134; uint64_t x135; fiat_p256_uint1 x136; uint64_t x137; fiat_p256_uint1 x138; uint64_t x139; uint64_t x140; uint64_t x141; uint64_t x142; uint64_t x143; uint64_t x144; uint64_t x145; fiat_p256_uint1 x146; uint64_t x147; fiat_p256_uint1 x148; uint64_t x149; fiat_p256_uint1 x150; uint64_t x151; fiat_p256_uint1 x152; uint64_t x153; fiat_p256_uint1 x154; uint64_t x155; fiat_p256_uint1 x156; uint64_t x157; fiat_p256_uint1 x158; uint64_t x159; fiat_p256_uint1 x160; uint64_t x161; fiat_p256_uint1 x162; uint64_t x163; fiat_p256_uint1 x164; uint64_t x165; fiat_p256_uint1 x166; uint64_t x167; uint64_t x168; uint64_t x169; uint64_t x170; x1 = (arg1[1]); x2 = (arg1[2]); x3 = (arg1[3]); x4 = (arg1[0]); fiat_p256_mulx_u64(&x5, &x6, x4, UINT64_C(0x4fffffffd)); fiat_p256_mulx_u64(&x7, &x8, x4, UINT64_C(0xfffffffffffffffe)); fiat_p256_mulx_u64(&x9, &x10, x4, UINT64_C(0xfffffffbffffffff)); fiat_p256_mulx_u64(&x11, &x12, x4, 0x3); fiat_p256_addcarryx_u64(&x13, &x14, 0x0, x12, x9); fiat_p256_addcarryx_u64(&x15, &x16, x14, x10, x7); fiat_p256_addcarryx_u64(&x17, &x18, x16, x8, x5); fiat_p256_mulx_u64(&x19, &x20, x11, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x21, &x22, x11, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x23, &x24, x11, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x25, &x26, 0x0, x24, x21); fiat_p256_addcarryx_u64(&x27, &x28, 0x0, x11, x23); fiat_p256_addcarryx_u64(&x29, &x30, x28, x13, x25); fiat_p256_addcarryx_u64(&x31, &x32, x30, x15, (x26 + x22)); fiat_p256_addcarryx_u64(&x33, &x34, x32, x17, x19); fiat_p256_addcarryx_u64(&x35, &x36, x34, (x18 + x6), x20); fiat_p256_mulx_u64(&x37, &x38, x1, UINT64_C(0x4fffffffd)); fiat_p256_mulx_u64(&x39, &x40, x1, UINT64_C(0xfffffffffffffffe)); fiat_p256_mulx_u64(&x41, &x42, x1, UINT64_C(0xfffffffbffffffff)); fiat_p256_mulx_u64(&x43, &x44, x1, 0x3); fiat_p256_addcarryx_u64(&x45, &x46, 0x0, x44, x41); fiat_p256_addcarryx_u64(&x47, &x48, x46, x42, x39); fiat_p256_addcarryx_u64(&x49, &x50, x48, x40, x37); fiat_p256_addcarryx_u64(&x51, &x52, 0x0, x29, x43); fiat_p256_addcarryx_u64(&x53, &x54, x52, x31, x45); fiat_p256_addcarryx_u64(&x55, &x56, x54, x33, x47); fiat_p256_addcarryx_u64(&x57, &x58, x56, x35, x49); fiat_p256_mulx_u64(&x59, &x60, x51, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x61, &x62, x51, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x63, &x64, x51, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x65, &x66, 0x0, x64, x61); fiat_p256_addcarryx_u64(&x67, &x68, 0x0, x51, x63); fiat_p256_addcarryx_u64(&x69, &x70, x68, x53, x65); fiat_p256_addcarryx_u64(&x71, &x72, x70, x55, (x66 + x62)); fiat_p256_addcarryx_u64(&x73, &x74, x72, x57, x59); fiat_p256_addcarryx_u64(&x75, &x76, x74, (((uint64_t)x58 + x36) + (x50 + x38)), x60); fiat_p256_mulx_u64(&x77, &x78, x2, UINT64_C(0x4fffffffd)); fiat_p256_mulx_u64(&x79, &x80, x2, UINT64_C(0xfffffffffffffffe)); fiat_p256_mulx_u64(&x81, &x82, x2, UINT64_C(0xfffffffbffffffff)); fiat_p256_mulx_u64(&x83, &x84, x2, 0x3); fiat_p256_addcarryx_u64(&x85, &x86, 0x0, x84, x81); fiat_p256_addcarryx_u64(&x87, &x88, x86, x82, x79); fiat_p256_addcarryx_u64(&x89, &x90, x88, x80, x77); fiat_p256_addcarryx_u64(&x91, &x92, 0x0, x69, x83); fiat_p256_addcarryx_u64(&x93, &x94, x92, x71, x85); fiat_p256_addcarryx_u64(&x95, &x96, x94, x73, x87); fiat_p256_addcarryx_u64(&x97, &x98, x96, x75, x89); fiat_p256_mulx_u64(&x99, &x100, x91, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x101, &x102, x91, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x103, &x104, x91, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x105, &x106, 0x0, x104, x101); fiat_p256_addcarryx_u64(&x107, &x108, 0x0, x91, x103); fiat_p256_addcarryx_u64(&x109, &x110, x108, x93, x105); fiat_p256_addcarryx_u64(&x111, &x112, x110, x95, (x106 + x102)); fiat_p256_addcarryx_u64(&x113, &x114, x112, x97, x99); fiat_p256_addcarryx_u64(&x115, &x116, x114, (((uint64_t)x98 + x76) + (x90 + x78)), x100); fiat_p256_mulx_u64(&x117, &x118, x3, UINT64_C(0x4fffffffd)); fiat_p256_mulx_u64(&x119, &x120, x3, UINT64_C(0xfffffffffffffffe)); fiat_p256_mulx_u64(&x121, &x122, x3, UINT64_C(0xfffffffbffffffff)); fiat_p256_mulx_u64(&x123, &x124, x3, 0x3); fiat_p256_addcarryx_u64(&x125, &x126, 0x0, x124, x121); fiat_p256_addcarryx_u64(&x127, &x128, x126, x122, x119); fiat_p256_addcarryx_u64(&x129, &x130, x128, x120, x117); fiat_p256_addcarryx_u64(&x131, &x132, 0x0, x109, x123); fiat_p256_addcarryx_u64(&x133, &x134, x132, x111, x125); fiat_p256_addcarryx_u64(&x135, &x136, x134, x113, x127); fiat_p256_addcarryx_u64(&x137, &x138, x136, x115, x129); fiat_p256_mulx_u64(&x139, &x140, x131, UINT64_C(0xffffffff00000001)); fiat_p256_mulx_u64(&x141, &x142, x131, UINT32_C(0xffffffff)); fiat_p256_mulx_u64(&x143, &x144, x131, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x145, &x146, 0x0, x144, x141); fiat_p256_addcarryx_u64(&x147, &x148, 0x0, x131, x143); fiat_p256_addcarryx_u64(&x149, &x150, x148, x133, x145); fiat_p256_addcarryx_u64(&x151, &x152, x150, x135, (x146 + x142)); fiat_p256_addcarryx_u64(&x153, &x154, x152, x137, x139); fiat_p256_addcarryx_u64(&x155, &x156, x154, (((uint64_t)x138 + x116) + (x130 + x118)), x140); fiat_p256_subborrowx_u64(&x157, &x158, 0x0, x149, UINT64_C(0xffffffffffffffff)); fiat_p256_subborrowx_u64(&x159, &x160, x158, x151, UINT32_C(0xffffffff)); fiat_p256_subborrowx_u64(&x161, &x162, x160, x153, 0x0); fiat_p256_subborrowx_u64(&x163, &x164, x162, x155, UINT64_C(0xffffffff00000001)); fiat_p256_subborrowx_u64(&x165, &x166, x164, x156, 0x0); fiat_p256_cmovznz_u64(&x167, x166, x157, x149); fiat_p256_cmovznz_u64(&x168, x166, x159, x151); fiat_p256_cmovznz_u64(&x169, x166, x161, x153); fiat_p256_cmovznz_u64(&x170, x166, x163, x155); out1[0] = x167; out1[1] = x168; out1[2] = x169; out1[3] = x170; } /* * The function fiat_p256_nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. * * Preconditions: * 0 ≤ eval arg1 < m * Postconditions: * out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 * * Input Bounds: * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * Output Bounds: * out1: [0x0 ~> 0xffffffffffffffff] */ static void fiat_p256_nonzero(uint64_t* out1, const uint64_t arg1[4]) { uint64_t x1; x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | (arg1[3])))); *out1 = x1; } /* * The function fiat_p256_selectznz is a multi-limb conditional select. * * Postconditions: * eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) * * Input Bounds: * arg1: [0x0 ~> 0x1] * arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * Output Bounds: * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ static void fiat_p256_selectznz(uint64_t out1[4], fiat_p256_uint1 arg1, const uint64_t arg2[4], const uint64_t arg3[4]) { uint64_t x1; uint64_t x2; uint64_t x3; uint64_t x4; fiat_p256_cmovznz_u64(&x1, arg1, (arg2[0]), (arg3[0])); fiat_p256_cmovznz_u64(&x2, arg1, (arg2[1]), (arg3[1])); fiat_p256_cmovznz_u64(&x3, arg1, (arg2[2]), (arg3[2])); fiat_p256_cmovznz_u64(&x4, arg1, (arg2[3]), (arg3[3])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; } /* * The function fiat_p256_to_bytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. * * Preconditions: * 0 ≤ eval arg1 < m * Postconditions: * out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] * * Input Bounds: * arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * Output Bounds: * out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] */ static void fiat_p256_to_bytes(uint8_t out1[32], const uint64_t arg1[4]) { uint64_t x1; uint64_t x2; uint64_t x3; uint64_t x4; uint8_t x5; uint64_t x6; uint8_t x7; uint64_t x8; uint8_t x9; uint64_t x10; uint8_t x11; uint64_t x12; uint8_t x13; uint64_t x14; uint8_t x15; uint64_t x16; uint8_t x17; uint8_t x18; uint8_t x19; uint64_t x20; uint8_t x21; uint64_t x22; uint8_t x23; uint64_t x24; uint8_t x25; uint64_t x26; uint8_t x27; uint64_t x28; uint8_t x29; uint64_t x30; uint8_t x31; uint8_t x32; uint8_t x33; uint64_t x34; uint8_t x35; uint64_t x36; uint8_t x37; uint64_t x38; uint8_t x39; uint64_t x40; uint8_t x41; uint64_t x42; uint8_t x43; uint64_t x44; uint8_t x45; uint8_t x46; uint8_t x47; uint64_t x48; uint8_t x49; uint64_t x50; uint8_t x51; uint64_t x52; uint8_t x53; uint64_t x54; uint8_t x55; uint64_t x56; uint8_t x57; uint64_t x58; uint8_t x59; uint8_t x60; x1 = (arg1[3]); x2 = (arg1[2]); x3 = (arg1[1]); x4 = (arg1[0]); x5 = (uint8_t)(x4 & UINT8_C(0xff)); x6 = (x4 >> 8); x7 = (uint8_t)(x6 & UINT8_C(0xff)); x8 = (x6 >> 8); x9 = (uint8_t)(x8 & UINT8_C(0xff)); x10 = (x8 >> 8); x11 = (uint8_t)(x10 & UINT8_C(0xff)); x12 = (x10 >> 8); x13 = (uint8_t)(x12 & UINT8_C(0xff)); x14 = (x12 >> 8); x15 = (uint8_t)(x14 & UINT8_C(0xff)); x16 = (x14 >> 8); x17 = (uint8_t)(x16 & UINT8_C(0xff)); x18 = (uint8_t)(x16 >> 8); x19 = (uint8_t)(x3 & UINT8_C(0xff)); x20 = (x3 >> 8); x21 = (uint8_t)(x20 & UINT8_C(0xff)); x22 = (x20 >> 8); x23 = (uint8_t)(x22 & UINT8_C(0xff)); x24 = (x22 >> 8); x25 = (uint8_t)(x24 & UINT8_C(0xff)); x26 = (x24 >> 8); x27 = (uint8_t)(x26 & UINT8_C(0xff)); x28 = (x26 >> 8); x29 = (uint8_t)(x28 & UINT8_C(0xff)); x30 = (x28 >> 8); x31 = (uint8_t)(x30 & UINT8_C(0xff)); x32 = (uint8_t)(x30 >> 8); x33 = (uint8_t)(x2 & UINT8_C(0xff)); x34 = (x2 >> 8); x35 = (uint8_t)(x34 & UINT8_C(0xff)); x36 = (x34 >> 8); x37 = (uint8_t)(x36 & UINT8_C(0xff)); x38 = (x36 >> 8); x39 = (uint8_t)(x38 & UINT8_C(0xff)); x40 = (x38 >> 8); x41 = (uint8_t)(x40 & UINT8_C(0xff)); x42 = (x40 >> 8); x43 = (uint8_t)(x42 & UINT8_C(0xff)); x44 = (x42 >> 8); x45 = (uint8_t)(x44 & UINT8_C(0xff)); x46 = (uint8_t)(x44 >> 8); x47 = (uint8_t)(x1 & UINT8_C(0xff)); x48 = (x1 >> 8); x49 = (uint8_t)(x48 & UINT8_C(0xff)); x50 = (x48 >> 8); x51 = (uint8_t)(x50 & UINT8_C(0xff)); x52 = (x50 >> 8); x53 = (uint8_t)(x52 & UINT8_C(0xff)); x54 = (x52 >> 8); x55 = (uint8_t)(x54 & UINT8_C(0xff)); x56 = (x54 >> 8); x57 = (uint8_t)(x56 & UINT8_C(0xff)); x58 = (x56 >> 8); x59 = (uint8_t)(x58 & UINT8_C(0xff)); x60 = (uint8_t)(x58 >> 8); out1[0] = x5; out1[1] = x7; out1[2] = x9; out1[3] = x11; out1[4] = x13; out1[5] = x15; out1[6] = x17; out1[7] = x18; out1[8] = x19; out1[9] = x21; out1[10] = x23; out1[11] = x25; out1[12] = x27; out1[13] = x29; out1[14] = x31; out1[15] = x32; out1[16] = x33; out1[17] = x35; out1[18] = x37; out1[19] = x39; out1[20] = x41; out1[21] = x43; out1[22] = x45; out1[23] = x46; out1[24] = x47; out1[25] = x49; out1[26] = x51; out1[27] = x53; out1[28] = x55; out1[29] = x57; out1[30] = x59; out1[31] = x60; } /* * The function fiat_p256_from_bytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. * * Preconditions: * 0 ≤ bytes_eval arg1 < m * Postconditions: * eval out1 mod m = bytes_eval arg1 mod m * 0 ≤ eval out1 < m * * Input Bounds: * arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] * Output Bounds: * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ static void fiat_p256_from_bytes(uint64_t out1[4], const uint8_t arg1[32]) { uint64_t x1; uint64_t x2; uint64_t x3; uint64_t x4; uint64_t x5; uint64_t x6; uint64_t x7; uint8_t x8; uint64_t x9; uint64_t x10; uint64_t x11; uint64_t x12; uint64_t x13; uint64_t x14; uint64_t x15; uint8_t x16; uint64_t x17; uint64_t x18; uint64_t x19; uint64_t x20; uint64_t x21; uint64_t x22; uint64_t x23; uint8_t x24; uint64_t x25; uint64_t x26; uint64_t x27; uint64_t x28; uint64_t x29; uint64_t x30; uint64_t x31; uint8_t x32; uint64_t x33; uint64_t x34; uint64_t x35; uint64_t x36; uint64_t x37; uint64_t x38; uint64_t x39; uint64_t x40; uint64_t x41; uint64_t x42; uint64_t x43; uint64_t x44; uint64_t x45; uint64_t x46; uint64_t x47; uint64_t x48; uint64_t x49; uint64_t x50; uint64_t x51; uint64_t x52; uint64_t x53; uint64_t x54; uint64_t x55; uint64_t x56; uint64_t x57; uint64_t x58; uint64_t x59; uint64_t x60; x1 = ((uint64_t)(arg1[31]) << 56); x2 = ((uint64_t)(arg1[30]) << 48); x3 = ((uint64_t)(arg1[29]) << 40); x4 = ((uint64_t)(arg1[28]) << 32); x5 = ((uint64_t)(arg1[27]) << 24); x6 = ((uint64_t)(arg1[26]) << 16); x7 = ((uint64_t)(arg1[25]) << 8); x8 = (arg1[24]); x9 = ((uint64_t)(arg1[23]) << 56); x10 = ((uint64_t)(arg1[22]) << 48); x11 = ((uint64_t)(arg1[21]) << 40); x12 = ((uint64_t)(arg1[20]) << 32); x13 = ((uint64_t)(arg1[19]) << 24); x14 = ((uint64_t)(arg1[18]) << 16); x15 = ((uint64_t)(arg1[17]) << 8); x16 = (arg1[16]); x17 = ((uint64_t)(arg1[15]) << 56); x18 = ((uint64_t)(arg1[14]) << 48); x19 = ((uint64_t)(arg1[13]) << 40); x20 = ((uint64_t)(arg1[12]) << 32); x21 = ((uint64_t)(arg1[11]) << 24); x22 = ((uint64_t)(arg1[10]) << 16); x23 = ((uint64_t)(arg1[9]) << 8); x24 = (arg1[8]); x25 = ((uint64_t)(arg1[7]) << 56); x26 = ((uint64_t)(arg1[6]) << 48); x27 = ((uint64_t)(arg1[5]) << 40); x28 = ((uint64_t)(arg1[4]) << 32); x29 = ((uint64_t)(arg1[3]) << 24); x30 = ((uint64_t)(arg1[2]) << 16); x31 = ((uint64_t)(arg1[1]) << 8); x32 = (arg1[0]); x33 = (x31 + (uint64_t)x32); x34 = (x30 + x33); x35 = (x29 + x34); x36 = (x28 + x35); x37 = (x27 + x36); x38 = (x26 + x37); x39 = (x25 + x38); x40 = (x23 + (uint64_t)x24); x41 = (x22 + x40); x42 = (x21 + x41); x43 = (x20 + x42); x44 = (x19 + x43); x45 = (x18 + x44); x46 = (x17 + x45); x47 = (x15 + (uint64_t)x16); x48 = (x14 + x47); x49 = (x13 + x48); x50 = (x12 + x49); x51 = (x11 + x50); x52 = (x10 + x51); x53 = (x9 + x52); x54 = (x7 + (uint64_t)x8); x55 = (x6 + x54); x56 = (x5 + x55); x57 = (x4 + x56); x58 = (x3 + x57); x59 = (x2 + x58); x60 = (x1 + x59); out1[0] = x39; out1[1] = x46; out1[2] = x53; out1[3] = x60; } /* * The function fiat_p256_set_one returns the field element one in the Montgomery domain. * * Postconditions: * eval (from_montgomery out1) mod m = 1 mod m * 0 ≤ eval out1 < m * */ static void fiat_p256_set_one(fiat_p256_montgomery_domain_field_element out1) { out1[0] = 0x1; out1[1] = UINT64_C(0xffffffff00000000); out1[2] = UINT64_C(0xffffffffffffffff); out1[3] = UINT32_C(0xfffffffe); } /* * The function fiat_p256_msat returns the saturated representation of the prime modulus. * * Postconditions: * twos_complement_eval out1 = m * 0 ≤ eval out1 < m * * Output Bounds: * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ static void fiat_p256_msat(uint64_t out1[5]) { out1[0] = UINT64_C(0xffffffffffffffff); out1[1] = UINT32_C(0xffffffff); out1[2] = 0x0; out1[3] = UINT64_C(0xffffffff00000001); out1[4] = 0x0; } /* * The function fiat_p256_divstep computes a divstep. * * Preconditions: * 0 ≤ eval arg4 < m * 0 ≤ eval arg5 < m * Postconditions: * out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) * twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) * twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) * eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) * eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) * 0 ≤ eval out5 < m * 0 ≤ eval out5 < m * 0 ≤ eval out2 < m * 0 ≤ eval out3 < m * * Input Bounds: * arg1: [0x0 ~> 0xffffffffffffffff] * arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * Output Bounds: * out1: [0x0 ~> 0xffffffffffffffff] * out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ static void fiat_p256_divstep(uint64_t* out1, uint64_t out2[5], uint64_t out3[5], uint64_t out4[4], uint64_t out5[4], uint64_t arg1, const uint64_t arg2[5], const uint64_t arg3[5], const uint64_t arg4[4], const uint64_t arg5[4]) { uint64_t x1; fiat_p256_uint1 x2; fiat_p256_uint1 x3; uint64_t x4; fiat_p256_uint1 x5; uint64_t x6; uint64_t x7; uint64_t x8; uint64_t x9; uint64_t x10; uint64_t x11; uint64_t x12; fiat_p256_uint1 x13; uint64_t x14; fiat_p256_uint1 x15; uint64_t x16; fiat_p256_uint1 x17; uint64_t x18; fiat_p256_uint1 x19; uint64_t x20; fiat_p256_uint1 x21; uint64_t x22; uint64_t x23; uint64_t x24; uint64_t x25; uint64_t x26; uint64_t x27; uint64_t x28; uint64_t x29; uint64_t x30; uint64_t x31; fiat_p256_uint1 x32; uint64_t x33; fiat_p256_uint1 x34; uint64_t x35; fiat_p256_uint1 x36; uint64_t x37; fiat_p256_uint1 x38; uint64_t x39; fiat_p256_uint1 x40; uint64_t x41; fiat_p256_uint1 x42; uint64_t x43; fiat_p256_uint1 x44; uint64_t x45; fiat_p256_uint1 x46; uint64_t x47; fiat_p256_uint1 x48; uint64_t x49; uint64_t x50; uint64_t x51; uint64_t x52; uint64_t x53; fiat_p256_uint1 x54; uint64_t x55; fiat_p256_uint1 x56; uint64_t x57; fiat_p256_uint1 x58; uint64_t x59; fiat_p256_uint1 x60; uint64_t x61; uint64_t x62; fiat_p256_uint1 x63; uint64_t x64; fiat_p256_uint1 x65; uint64_t x66; fiat_p256_uint1 x67; uint64_t x68; fiat_p256_uint1 x69; uint64_t x70; uint64_t x71; uint64_t x72; uint64_t x73; fiat_p256_uint1 x74; uint64_t x75; uint64_t x76; uint64_t x77; uint64_t x78; uint64_t x79; uint64_t x80; fiat_p256_uint1 x81; uint64_t x82; fiat_p256_uint1 x83; uint64_t x84; fiat_p256_uint1 x85; uint64_t x86; fiat_p256_uint1 x87; uint64_t x88; fiat_p256_uint1 x89; uint64_t x90; uint64_t x91; uint64_t x92; uint64_t x93; uint64_t x94; fiat_p256_uint1 x95; uint64_t x96; fiat_p256_uint1 x97; uint64_t x98; fiat_p256_uint1 x99; uint64_t x100; fiat_p256_uint1 x101; uint64_t x102; fiat_p256_uint1 x103; uint64_t x104; fiat_p256_uint1 x105; uint64_t x106; fiat_p256_uint1 x107; uint64_t x108; fiat_p256_uint1 x109; uint64_t x110; fiat_p256_uint1 x111; uint64_t x112; fiat_p256_uint1 x113; uint64_t x114; uint64_t x115; uint64_t x116; uint64_t x117; uint64_t x118; uint64_t x119; uint64_t x120; uint64_t x121; uint64_t x122; uint64_t x123; uint64_t x124; uint64_t x125; uint64_t x126; fiat_p256_addcarryx_u64(&x1, &x2, 0x0, (~arg1), 0x1); x3 = (fiat_p256_uint1)((fiat_p256_uint1)(x1 >> 63) & (fiat_p256_uint1)((arg3[0]) & 0x1)); fiat_p256_addcarryx_u64(&x4, &x5, 0x0, (~arg1), 0x1); fiat_p256_cmovznz_u64(&x6, x3, arg1, x4); fiat_p256_cmovznz_u64(&x7, x3, (arg2[0]), (arg3[0])); fiat_p256_cmovznz_u64(&x8, x3, (arg2[1]), (arg3[1])); fiat_p256_cmovznz_u64(&x9, x3, (arg2[2]), (arg3[2])); fiat_p256_cmovznz_u64(&x10, x3, (arg2[3]), (arg3[3])); fiat_p256_cmovznz_u64(&x11, x3, (arg2[4]), (arg3[4])); fiat_p256_addcarryx_u64(&x12, &x13, 0x0, 0x1, (~(arg2[0]))); fiat_p256_addcarryx_u64(&x14, &x15, x13, 0x0, (~(arg2[1]))); fiat_p256_addcarryx_u64(&x16, &x17, x15, 0x0, (~(arg2[2]))); fiat_p256_addcarryx_u64(&x18, &x19, x17, 0x0, (~(arg2[3]))); fiat_p256_addcarryx_u64(&x20, &x21, x19, 0x0, (~(arg2[4]))); fiat_p256_cmovznz_u64(&x22, x3, (arg3[0]), x12); fiat_p256_cmovznz_u64(&x23, x3, (arg3[1]), x14); fiat_p256_cmovznz_u64(&x24, x3, (arg3[2]), x16); fiat_p256_cmovznz_u64(&x25, x3, (arg3[3]), x18); fiat_p256_cmovznz_u64(&x26, x3, (arg3[4]), x20); fiat_p256_cmovznz_u64(&x27, x3, (arg4[0]), (arg5[0])); fiat_p256_cmovznz_u64(&x28, x3, (arg4[1]), (arg5[1])); fiat_p256_cmovznz_u64(&x29, x3, (arg4[2]), (arg5[2])); fiat_p256_cmovznz_u64(&x30, x3, (arg4[3]), (arg5[3])); fiat_p256_addcarryx_u64(&x31, &x32, 0x0, x27, x27); fiat_p256_addcarryx_u64(&x33, &x34, x32, x28, x28); fiat_p256_addcarryx_u64(&x35, &x36, x34, x29, x29); fiat_p256_addcarryx_u64(&x37, &x38, x36, x30, x30); fiat_p256_subborrowx_u64(&x39, &x40, 0x0, x31, UINT64_C(0xffffffffffffffff)); fiat_p256_subborrowx_u64(&x41, &x42, x40, x33, UINT32_C(0xffffffff)); fiat_p256_subborrowx_u64(&x43, &x44, x42, x35, 0x0); fiat_p256_subborrowx_u64(&x45, &x46, x44, x37, UINT64_C(0xffffffff00000001)); fiat_p256_subborrowx_u64(&x47, &x48, x46, x38, 0x0); x49 = (arg4[3]); x50 = (arg4[2]); x51 = (arg4[1]); x52 = (arg4[0]); fiat_p256_subborrowx_u64(&x53, &x54, 0x0, 0x0, x52); fiat_p256_subborrowx_u64(&x55, &x56, x54, 0x0, x51); fiat_p256_subborrowx_u64(&x57, &x58, x56, 0x0, x50); fiat_p256_subborrowx_u64(&x59, &x60, x58, 0x0, x49); fiat_p256_cmovznz_u64(&x61, x60, 0x0, UINT64_C(0xffffffffffffffff)); fiat_p256_addcarryx_u64(&x62, &x63, 0x0, x53, x61); fiat_p256_addcarryx_u64(&x64, &x65, x63, x55, (x61 & UINT32_C(0xffffffff))); fiat_p256_addcarryx_u64(&x66, &x67, x65, x57, 0x0); fiat_p256_addcarryx_u64(&x68, &x69, x67, x59, (x61 & UINT64_C(0xffffffff00000001))); fiat_p256_cmovznz_u64(&x70, x3, (arg5[0]), x62); fiat_p256_cmovznz_u64(&x71, x3, (arg5[1]), x64); fiat_p256_cmovznz_u64(&x72, x3, (arg5[2]), x66); fiat_p256_cmovznz_u64(&x73, x3, (arg5[3]), x68); x74 = (fiat_p256_uint1)(x22 & 0x1); fiat_p256_cmovznz_u64(&x75, x74, 0x0, x7); fiat_p256_cmovznz_u64(&x76, x74, 0x0, x8); fiat_p256_cmovznz_u64(&x77, x74, 0x0, x9); fiat_p256_cmovznz_u64(&x78, x74, 0x0, x10); fiat_p256_cmovznz_u64(&x79, x74, 0x0, x11); fiat_p256_addcarryx_u64(&x80, &x81, 0x0, x22, x75); fiat_p256_addcarryx_u64(&x82, &x83, x81, x23, x76); fiat_p256_addcarryx_u64(&x84, &x85, x83, x24, x77); fiat_p256_addcarryx_u64(&x86, &x87, x85, x25, x78); fiat_p256_addcarryx_u64(&x88, &x89, x87, x26, x79); fiat_p256_cmovznz_u64(&x90, x74, 0x0, x27); fiat_p256_cmovznz_u64(&x91, x74, 0x0, x28); fiat_p256_cmovznz_u64(&x92, x74, 0x0, x29); fiat_p256_cmovznz_u64(&x93, x74, 0x0, x30); fiat_p256_addcarryx_u64(&x94, &x95, 0x0, x70, x90); fiat_p256_addcarryx_u64(&x96, &x97, x95, x71, x91); fiat_p256_addcarryx_u64(&x98, &x99, x97, x72, x92); fiat_p256_addcarryx_u64(&x100, &x101, x99, x73, x93); fiat_p256_subborrowx_u64(&x102, &x103, 0x0, x94, UINT64_C(0xffffffffffffffff)); fiat_p256_subborrowx_u64(&x104, &x105, x103, x96, UINT32_C(0xffffffff)); fiat_p256_subborrowx_u64(&x106, &x107, x105, x98, 0x0); fiat_p256_subborrowx_u64(&x108, &x109, x107, x100, UINT64_C(0xffffffff00000001)); fiat_p256_subborrowx_u64(&x110, &x111, x109, x101, 0x0); fiat_p256_addcarryx_u64(&x112, &x113, 0x0, x6, 0x1); x114 = ((x80 >> 1) | ((x82 << 63) & UINT64_C(0xffffffffffffffff))); x115 = ((x82 >> 1) | ((x84 << 63) & UINT64_C(0xffffffffffffffff))); x116 = ((x84 >> 1) | ((x86 << 63) & UINT64_C(0xffffffffffffffff))); x117 = ((x86 >> 1) | ((x88 << 63) & UINT64_C(0xffffffffffffffff))); x118 = ((x88 & UINT64_C(0x8000000000000000)) | (x88 >> 1)); fiat_p256_cmovznz_u64(&x119, x48, x39, x31); fiat_p256_cmovznz_u64(&x120, x48, x41, x33); fiat_p256_cmovznz_u64(&x121, x48, x43, x35); fiat_p256_cmovznz_u64(&x122, x48, x45, x37); fiat_p256_cmovznz_u64(&x123, x111, x102, x94); fiat_p256_cmovznz_u64(&x124, x111, x104, x96); fiat_p256_cmovznz_u64(&x125, x111, x106, x98); fiat_p256_cmovznz_u64(&x126, x111, x108, x100); *out1 = x112; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out3[0] = x114; out3[1] = x115; out3[2] = x116; out3[3] = x117; out3[4] = x118; out4[0] = x119; out4[1] = x120; out4[2] = x121; out4[3] = x122; out5[0] = x123; out5[1] = x124; out5[2] = x125; out5[3] = x126; } /* * The function fiat_p256_divstep_precomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). * * Postconditions: * eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋) * 0 ≤ eval out1 < m * * Output Bounds: * out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ static void fiat_p256_divstep_precomp(uint64_t out1[4]) { out1[0] = UINT64_C(0x67ffffffb8000000); out1[1] = UINT64_C(0xc000000038000000); out1[2] = UINT64_C(0xd80000007fffffff); out1[3] = UINT64_C(0x2fffffffffffffff); }
32.251988
532
0.681728
03dab4096a2ea9762e18b59f382d99980a3f9bed
4,730
h
C
cranium/src/function.h
ewail/DiaNN
043090bdb60bcb77b51ebf6c56f8d19b43814eed
[ "CC-BY-4.0" ]
89
2018-03-16T09:16:13.000Z
2022-03-16T03:30:54.000Z
cranium/src/function.h
ewail/DiaNN
043090bdb60bcb77b51ebf6c56f8d19b43814eed
[ "CC-BY-4.0" ]
197
2018-04-18T03:00:16.000Z
2022-03-31T10:35:58.000Z
cranium/src/function.h
ewail/DiaNN
043090bdb60bcb77b51ebf6c56f8d19b43814eed
[ "CC-BY-4.0" ]
35
2019-05-27T01:44:07.000Z
2022-03-30T07:13:59.000Z
#include "std_includes.h" #include "matrix.h" #ifndef FUNCTION_H #define FUNCTION_H typedef void (*Activation)(Matrix*); #define MAX(a,b) (((a)>(b))?(a):(b)) #ifndef RAND_MOD #define RAND_MOD 2147483647 #endif // raw sigmoid function static float sigmoidFunc(float input); // derivatve of sigmoid given output of sigmoid static float sigmoidDeriv(float sigmoidInput); // raw ReLU function static float reluFunc(float input); // derivative of ReLU given output of ReLU static float reluDeriv(float reluInput); // raw tanh function static float tanHFunc(float input); // derivatve of tanh given output of sigmoid static float tanHDeriv(float sigmoidInput); // applies sigmoid function to each entry of $input static void sigmoid(Matrix* input); // applies ReLU function to each entry of input static void relu(Matrix* input); // applues tanh function to each entry of input static void tanH(Matrix* input); // applies softmax function to each row of $input static void softmax(Matrix* input); // applies linear function to each row of $input static void linear(Matrix* input); // derivative of linear function given output of linear static float linearDeriv(float linearInput); // return the string representation of activation function static const char* getFunctionName(Activation func); // return the activation function corresponding to a name static Activation getFunctionByName(const char* name); // return derivative of activation function static float (*activationDerivative(Activation func))(float); /* Begin functions. */ float sigmoidFunc(float input){ return 1 / (1 + expf(-1 * input)); } float sigmoidDeriv(float sigmoidInput){ return sigmoidInput * (1 - sigmoidInput); } float reluFunc(float input){ return MAX(0, input); } float reluDeriv(float reluInput){ return reluInput > 0 ? 1 : 0; } // operates on each row void sigmoid(Matrix* input){ int i, j; for (i = 0; i < input->rows; i++){ for (j = 0; j < input->cols; j++){ setMatrix(input, i, j, sigmoidFunc(getMatrix(input, i, j))); } } } float tanHFunc(float input){ return tanh(input); } float tanHDeriv(float tanhInput){ return 1 - (tanhInput * tanhInput); } // operates on each row void relu(Matrix* input){ int i, j; for (i = 0; i < input->rows; i++){ for (j = 0; j < input->cols; j++){ setMatrix(input, i, j, reluFunc(getMatrix(input, i, j))); } } } // operates on each row void tanH(Matrix* input){ int i, j; for (i = 0; i < input->rows; i++){ for (j = 0; j < input->cols; j++){ setMatrix(input, i, j, tanHFunc(getMatrix(input, i, j))); } } } // operates on each row void softmax(Matrix* input){ int i; for (i = 0; i < input->rows; i++){ float summed = 0; int j; for (j = 0; j < input->cols; j++){ summed += expf(getMatrix(input, i, j)); } for (j = 0; j < input->cols; j++){ setMatrix(input, i, j, expf(getMatrix(input, i, j)) / summed); } } } // operates on each row void linear(Matrix* input){} float linearDeriv(float linearInput){ return 1; } // adapted from wikipedia float box_muller(std::minstd_rand &gen) { const float epsilon = FLT_MIN; const float two_pi = 2.0 * 3.14159265358979323846; float z0; float u1, u2; do { u1 = gen() * (1.0 / (double)RAND_MOD); u2 = gen() * (1.0 / (double)RAND_MOD); } while (u1 <= epsilon); z0 = sqrt(-2.0 * logf(u1)) * cos(two_pi * u2); return z0; } const char* getFunctionName(Activation func){ if (func == sigmoid){ return "sigmoid"; } else if (func == relu){ return "relu"; } else if (func == tanH){ return "tanH"; } else if (func == softmax){ return "softmax"; } else{ return "linear"; } } Activation getFunctionByName(const char* name){ if (strcmp(name, "sigmoid") == 0){ return sigmoid; } else if (strcmp(name, "relu") == 0){ return relu; } else if (strcmp(name, "tanH") == 0){ return tanH; } else if (strcmp(name, "softmax") == 0){ return softmax; } else{ return linear; } } float (*activationDerivative(Activation func))(float){ if (func == sigmoid){ return sigmoidDeriv; } else if (func == relu){ return reluDeriv; } else if (func == tanH){ return tanHDeriv; } else{ return linearDeriv; } } #endif
22.961165
75
0.593023
83c709bbdd6cdf42d0b72871ab18345c65d91619
370
h
C
Connect/Client/Wallet/View/LMSelectTableViewCell.h
connectim/iOS
e93cf080df2333763b00a74bd03c15454d9e5bae
[ "MIT" ]
20
2017-05-12T08:53:47.000Z
2022-03-21T17:00:36.000Z
Connect/Client/Wallet/View/LMSelectTableViewCell.h
connectim/iOS
e93cf080df2333763b00a74bd03c15454d9e5bae
[ "MIT" ]
6
2017-05-11T11:38:22.000Z
2017-12-31T14:00:25.000Z
Connect/Client/Wallet/View/LMSelectTableViewCell.h
connectim/iOS
e93cf080df2333763b00a74bd03c15454d9e5bae
[ "MIT" ]
9
2017-05-09T02:02:47.000Z
2019-09-04T03:37:51.000Z
// // LMSelectTableViewCell.h // Connect // // Created by Edwin on 16/7/19. // Copyright © 2016年 Connect. All rights reserved. // #import <UIKit/UIKit.h> #import "AccountInfo.h" #import "BEMCheckBox.h" @interface LMSelectTableViewCell : UITableViewCell - (void)setAccoutInfo:(AccountInfo *)info; @property(weak, nonatomic) IBOutlet BEMCheckBox *checkBox; @end
18.5
58
0.727027
d8676f3354d2ae76a346166c7ed263ee537a68ef
583
h
C
projects/solar/inc/pin_defs.h
Citrusboa/firmware_xiv
4379cefae900fd67bd14d930da6b8acfce625176
[ "MIT" ]
14
2019-11-12T00:11:29.000Z
2021-12-13T05:32:41.000Z
projects/solar/inc/pin_defs.h
123Logan321/firmware_xiv
14468d55753ad62f8a63a9289511e72131443042
[ "MIT" ]
191
2019-11-12T05:36:58.000Z
2022-03-21T19:54:46.000Z
projects/solar/inc/pin_defs.h
123Logan321/firmware_xiv
14468d55753ad62f8a63a9289511e72131443042
[ "MIT" ]
14
2020-06-06T14:43:14.000Z
2022-03-08T00:48:11.000Z
#pragma once // Pin definitions for solar, kept here to avoid circular dependencies. #define SOLAR_UNUSED_PIN \ { GPIO_PORT_B, 1 } // High on one board, low on the other. #define MPPT_COUNT_DETECTION_PIN \ { GPIO_PORT_A, 7 } #define MUX_SEL_PIN_0 \ { GPIO_PORT_B, 0 } #define MUX_SEL_PIN_1 \ { GPIO_PORT_B, 1 } #define MUX_SEL_PIN_2 \ { GPIO_PORT_B, 2 } #define RELAY_EN_PIN \ { GPIO_PORT_B, 4 } #define OVERTEMP_PIN \ { GPIO_PORT_B, 5 } #define FULL_SPEED_PIN \ { GPIO_PORT_B, 6 } #define FAN_FAIL_PIN \ { GPIO_PORT_B, 7 } #define DISCONNECTED_MUX_OUTPUT 7
19.433333
71
0.711835
96e84ed1cd1c6ad15a5ab218839cdcf5a694cee9
17,229
c
C
apps/legato_quickstart/firmware/src/config/lcdc_rgba8888_mxt_a5d2_wvga_iar/gfx/legato/core/legato_state.c
Microchip-MPLAB-Harmony/gfx_apps_sam_a5d2
649f1fe7aad45f7cdabfc1c726c3850a6adf68d9
[ "0BSD" ]
4
2021-07-23T18:37:34.000Z
2022-01-09T17:31:40.000Z
apps/legato_quickstart/firmware/src/config/lcdc_rgba8888_mxt_a5d2_wvga_iar/gfx/legato/core/legato_state.c
Microchip-MPLAB-Harmony/gfx_apps_sam_a5d2
649f1fe7aad45f7cdabfc1c726c3850a6adf68d9
[ "0BSD" ]
1
2020-12-31T22:40:10.000Z
2020-12-31T22:40:10.000Z
apps/legato_quickstart/firmware/src/config/lcdc_rgba8888_mxt_a5d2_wvga_iar/gfx/legato/core/legato_state.c
Microchip-MPLAB-Harmony/gfx_apps_sam_a5d2
649f1fe7aad45f7cdabfc1c726c3850a6adf68d9
[ "0BSD" ]
2
2020-08-20T09:04:40.000Z
2021-12-07T10:00:18.000Z
// DOM-IGNORE-BEGIN /******************************************************************************* * Copyright (C) 2020 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *******************************************************************************/ // DOM-IGNORE-END #include "gfx/legato/core/legato_state.h" #include "gfx/legato/core/legato_input.h" #include "gfx/legato/image/legato_image.h" #include "gfx/legato/memory/legato_memory.h" #include "gfx/legato/renderer/legato_renderer.h" #include <string.h> int32_t _initialized = LE_FALSE; #define LE_MAX_BUFFER_COUNT 2 static leState _state; leState* leGetState() { return &_state; } #if LE_DYNAMIC_VTABLES == 1 /* vtable generation functions, make sure child classes come after base ones */ typedef void (*vtableFn)(void); void _leString_GenerateVTable(void); void _leDynamicString_GenerateVTable(void); void _leFixedString_GenerateVTable(void); void _leTableString_GenerateVTable(void); void _leWidget_GenerateVTable(void); void _leEditWidget_GenerateVTable(void); void _leArcWidget_GenerateVTable(void); void _leBarGraphWidget_GenerateVTable(void); void _leButtonWidget_GenerateVTable(void); void _leCheckBoxWidget_GenerateVTable(void); void _leCircleWidget_GenerateVTable(void); void _leCircularGaugeWidget_GenerateVTable(void); void _leCircularSliderWidget_GenerateVTable(void); void _leDrawSurfaceWidget_GenerateVTable(void); void _leGradientWidget_GenerateVTable(void); void _leGroupBoxWidget_GenerateVTable(void); void _leImageWidget_GenerateVTable(void); void _leImageRotateWidget_GenerateVTable(void); void _leImageScaleWidget_GenerateVTable(void); void _leImageSequenceWidget_GenerateVTable(void); void _leKeyPadWidget_GenerateVTable(void); void _leLabelWidget_GenerateVTable(void); void _leLineWidget_GenerateVTable(void); void _leLineGraphWidget_GenerateVTable(void); void _leListWidget_GenerateVTable(void); void _leListWheelWidget_GenerateVTable(void); void _lePieChartWidget_GenerateVTable(void); void _leProgressBarWidget_GenerateVTable(void); void _leRadialMenuWidget_GenerateVTable(void); void _leRadioButtonWidget_GenerateVTable(void); void _leRectangleWidget_GenerateVTable(void); void _leScrollBarWidget_GenerateVTable(void); void _leSliderWidget_GenerateVTable(void); void _leTextFieldWidget_GenerateVTable(void); void _leTouchTestWidget_GenerateVTable(void); void _leWindowWidget_GenerateVTable(void); vtableFn vtableFnTable[] = { #if LE_DYNAMIC_VTABLES == 1 _leString_GenerateVTable, _leDynamicString_GenerateVTable, _leFixedString_GenerateVTable, _leTableString_GenerateVTable, #endif _leWidget_GenerateVTable, _leEditWidget_GenerateVTable, #if LE_ARC_WIDGET_ENABLED == 1 _leArcWidget_GenerateVTable, #endif #if LE_BARGRAPH_WIDGET_ENABLED == 1 _leBarGraphWidget_GenerateVTable, #endif #if LE_BUTTON_WIDGET_ENABLED == 1 _leButtonWidget_GenerateVTable, #endif #if LE_CHECKBOX_WIDGET_ENABLED == 1 _leCheckBoxWidget_GenerateVTable, #endif #if LE_CIRCLE_WIDGET_ENABLED == 1 _leCircleWidget_GenerateVTable, #endif #if LE_CIRCULARGAUGE_WIDGET_ENABLED == 1 _leCircularGaugeWidget_GenerateVTable, #endif #if LE_CIRCULARSLIDER_WIDGET_ENABLED == 1 _leCircularSliderWidget_GenerateVTable, #endif #if LE_DRAWSURFACE_WIDGET_ENABLED == 1 _leDrawSurfaceWidget_GenerateVTable, #endif #if LE_GRADIENT_WIDGET_ENABLED == 1 _leGradientWidget_GenerateVTable, #endif #if LE_GROUPBOX_WIDGET_ENABLED == 1 _leGroupBoxWidget_GenerateVTable, #endif #if LE_IMAGE_WIDGET_ENABLED == 1 _leImageWidget_GenerateVTable, #endif #if LE_IMAGEROTATE_WIDGET_ENABLED == 1 _leImageRotateWidget_GenerateVTable, #endif #if LE_IMAGESCALE_WIDGET_ENABLED == 1 _leImageScaleWidget_GenerateVTable, #endif #if LE_IMAGESEQUENCE_WIDGET_ENABLED == 1 _leImageSequenceWidget_GenerateVTable, #endif #if LE_KEYPAD_WIDGET_ENABLED == 1 _leKeyPadWidget_GenerateVTable, #endif #if LE_LABEL_WIDGET_ENABLED == 1 _leLabelWidget_GenerateVTable, #endif #if LE_LINE_WIDGET_ENABLED == 1 _leLineWidget_GenerateVTable, #endif #if LE_LINEGRAPH_WIDGET_ENABLED == 1 _leLineGraphWidget_GenerateVTable, #endif #if LE_LIST_WIDGET_ENABLED == 1 _leListWidget_GenerateVTable, #endif #if LE_LISTWHEEL_WIDGET_ENABLED == 1 _leListWheelWidget_GenerateVTable, #endif #if LE_PIECHART_WIDGET_ENABLED == 1 _lePieChartWidget_GenerateVTable, #endif #if LE_PROGRESSBAR_WIDGET_ENABLED == 1 _leProgressBarWidget_GenerateVTable, #endif #if LE_RADIALMENU_WIDGET_ENABLED == 1 _leRadialMenuWidget_GenerateVTable, #endif #if LE_RADIOBUTTON_WIDGET_ENABLED == 1 _leRadioButtonWidget_GenerateVTable, #endif #if LE_RECTANGLE_WIDGET_ENABLED == 1 _leRectangleWidget_GenerateVTable, #endif #if LE_SCROLLBAR_WIDGET_ENABLED == 1 _leScrollBarWidget_GenerateVTable, #endif #if LE_SLIDER_WIDGET_ENABLED == 1 _leSliderWidget_GenerateVTable, #endif #if LE_TEXTFIELD_WIDGET_ENABLED == 1 _leTextFieldWidget_GenerateVTable, #endif #if LE_TOUCHTEST_WIDGET_ENABLED == 1 _leTouchTestWidget_GenerateVTable, #endif #if LE_WINDOW_WIDGET_ENABLED == 1 _leWindowWidget_GenerateVTable, #endif NULL }; #endif leResult leInitialize(const gfxDisplayDriver* dispDriver, const gfxGraphicsProcessor* gpuDriver) { uint32_t idx; leWidget* root; gfxIOCTLArg_DisplaySize disp; if(_initialized == LE_TRUE) return LE_FAILURE; memset(&_state, 0, sizeof(leState)); #if LE_MEMORY_MANAGER_ENABLE == 1 if(leMemory_Init() == LE_FAILURE) return LE_FAILURE; #endif if(leEvent_Init() == LE_FAILURE || leInput_Init() == LE_FAILURE || leRenderer_Initialize(dispDriver, gpuDriver) == LE_FAILURE) { return LE_FAILURE; } #if LE_DYNAMIC_VTABLES == 1 /* initialize virtual function tables */ idx = 0; while(vtableFnTable[idx] != NULL) { vtableFnTable[idx](); idx += 1; } #endif leImage_InitDecoders(); for(idx = 0; idx < LE_LAYER_COUNT; idx++) { root = &_state.rootWidget[idx]; leWidget_Constructor(root); disp.width = 0; disp.height = 0; dispDriver->ioctl(GFX_IOCTL_SET_ACTIVE_LAYER, &idx); dispDriver->ioctl(GFX_IOCTL_GET_DISPLAY_SIZE, &disp); root->rect.x = 0; root->rect.y = 0; #if LE_RENDER_ORIENTATION == 0 || LE_RENDER_ORIENTATION == 180 root->rect.width = disp.width; root->rect.height = disp.height; #else root->rect.width = disp.height; root->rect.height = disp.width; #endif root->fn->invalidate(root); root->flags |= LE_WIDGET_ISROOT; root->flags |= LE_WIDGET_IGNOREEVENTS; root->flags |= LE_WIDGET_IGNOREPICK; _state.layerStates[idx].colorMode = LE_DEFAULT_COLOR_MODE; } _initialized = LE_TRUE; return LE_SUCCESS; } void leShutdown() { uint32_t idx; leWidget* root; if(_initialized == LE_FALSE) return; for(idx = 0; idx < LE_LAYER_COUNT; idx++) { root = &_state.rootWidget[idx]; root->fn->_destructor(root); } leRenderer_Shutdown(); leInput_Shutdown(); leEvent_Shutdown(); memset(&_state, 0, sizeof(leState)); _initialized = LE_FALSE; } static void updateWidget(leWidget* wgt, uint32_t dt) { uint32_t i; leWidget* child; wgt->fn->update(wgt, dt); for(i = 0; i < wgt->children.size; i++) { child = wgt->children.values[i]; updateWidget(child, dt); } } static void updateWidgets(uint32_t dt) { int32_t i; if(leIsDrawing() == LE_TRUE) return; // iterate over all existing layers for update for(i = 0; i < LE_LAYER_COUNT; i++) { updateWidget(&_state.rootWidget[i], dt); } } leResult leUpdate(uint32_t dt) { #if LE_DRIVER_LAYER_MODE == 1 uint32_t itr; gfxIOCTLArg_LayerRect layerRect; #endif leEvent_ProcessEvents(); #if LE_DRIVER_LAYER_MODE == 1 for(itr = 0; itr < LE_LAYER_COUNT; ++itr) { layerRect.base.id = itr; layerRect.x = 0; layerRect.y = 0; layerRect.width = 0; layerRect.height = 0; leGetRenderState()->dispDriver->ioctl(GFX_IOCTL_GET_LAYER_RECT, &layerRect); _state.layerStates[itr].driverPosition.x = layerRect.x; _state.layerStates[itr].driverPosition.y = layerRect.y; _state.rootWidget[itr].fn->setPosition(&_state.rootWidget[itr], 0, 0); #if LE_RENDER_ORIENTATION == 90 || LE_RENDER_ORIENTATION == 270 _state.rootWidget[itr].fn->setSize(&_state.rootWidget[itr], layerRect.height, layerRect.width); #else _state.rootWidget[itr].fn->setSize(&_state.rootWidget[itr], layerRect.width, layerRect.height); #endif } #endif #if LE_STREAMING_ENABLED == 1 // there is an active stream in progress, service that to completion // before painting anything else if(_state.activeStream != NULL) { if(_state.activeStream->isDone(_state.activeStream) == LE_TRUE) { _state.activeStream = NULL; } else { _state.activeStream->exec(_state.activeStream); return LE_SUCCESS; } } #endif updateWidgets(dt); leRenderer_Paint(); return LE_SUCCESS; } leColorMode leGetLayerColorMode(uint32_t idx) { if(idx >= LE_LAYER_COUNT) return LE_COLOR_MODE_GS_8; return _state.layerStates[idx].colorMode; } leResult leSetLayerColorMode(uint32_t idx, leColorMode mode) { if(idx >= LE_LAYER_COUNT) return LE_FAILURE; _state.layerStates[idx].colorMode = mode; return LE_SUCCESS; } leBool leGetLayerRenderHorizontal(uint32_t idx) { if(idx >= LE_LAYER_COUNT) return LE_FALSE; return _state.layerStates[idx].renderHorizontal; } leResult leSetLayerRenderHorizontal(uint32_t idx, leBool horz) { if(idx >= LE_LAYER_COUNT) return LE_FAILURE; _state.layerStates[idx].renderHorizontal = horz; return LE_SUCCESS; } /*leRect leGetDisplayRect() { return leGetRenderState()->displayRect; }*/ leStringTable* leGetStringTable() { return (leStringTable*)_state.stringTable; } void leSetStringTable(const leStringTable* table) { _state.stringTable = table; leRedrawAll(); } uint32_t leGetStringLanguage() { return _state.languageID; } static void updateWidgetLanguage(leWidget* wgt) { uint32_t i; leWidget* child; wgt->fn->languageChangeEvent(wgt); for(i = 0; i < wgt->children.size; i++) { child = wgt->children.values[i]; updateWidgetLanguage(child); } } void leSetStringLanguage(uint32_t id) { uint32_t i; if(_state.languageID == id) return; _state.languageID = id; // iterate over all existing layers for update for(i = 0; i < LE_LAYER_COUNT; i++) { updateWidgetLanguage(&_state.rootWidget[i]); } } leScheme* leGetDefaultScheme() { return &_state.defaultScheme; } leWidget* leGetFocusWidget() { return _state.focus; } leResult leSetFocusWidget(leWidget* widget) { leEvent evt; if(_state.focus == widget) return LE_SUCCESS; if(_state.focus != NULL) { evt.id = LE_WIDGET_EVENT_FOCUS_LOST; _state.focus->fn->_handleEvent(_state.focus, &evt); } _state.focus = widget; if(_state.focus != NULL) { evt.id = LE_WIDGET_EVENT_FOCUS_GAINED; _state.focus->fn->_handleEvent(_state.focus, &evt); } return LE_SUCCESS; } leEditWidget* leGetEditWidget() { return _state.edit; } leResult leSetEditWidget(leEditWidget* widget) { if(_state.edit == (leEditWidget*)widget) return LE_SUCCESS; if(_state.edit != NULL) { _state.edit->fn->editEnd(_state.edit); } _state.edit = widget; if(_state.edit != NULL && _state.edit->fn->editStart(_state.edit) == LE_FAILURE) { _state.edit = NULL; return LE_FAILURE; } return LE_SUCCESS; } void leRedrawAll() { uint32_t layer; leWidget* root; for(layer = 0; layer < LE_LAYER_COUNT; layer++) { root = &_state.rootWidget[layer]; root->fn->invalidate(root); } } leBool leIsDrawing() { return leGetRenderState()->frameState > LE_FRAME_PREFRAME; } leResult leAddRootWidget(leWidget* wgt, uint32_t layer) { if(wgt == NULL || layer > LE_LAYER_COUNT - 1) return LE_FAILURE; leRenderer_DamageArea(&wgt->rect, layer); return _state.rootWidget[layer].fn->addChild(&_state.rootWidget[layer], wgt); } leResult leRemoveRootWidget(leWidget* wgt, uint32_t layer) { leRect rect; if(wgt == NULL) return LE_FAILURE; rect = wgt->rect; if(_state.rootWidget[layer].fn->removeChild(&_state.rootWidget[layer], wgt) == LE_SUCCESS) { leRenderer_DamageArea(&rect, layer); return LE_SUCCESS; } return LE_FAILURE; } leBool leWidgetIsInScene(const leWidget* wgt) { return leGetWidgetLayer(wgt) >= 0; } int32_t leGetWidgetLayer(const leWidget* wgt) { int32_t layer; leWidget* root; leWidget* wgtRoot; if(wgt == NULL) return LE_FALSE; wgtRoot = wgt->fn->getRootWidget(wgt); if(wgtRoot == NULL) return LE_FALSE; for(layer = 0; layer < LE_LAYER_COUNT; layer++) { root = &_state.rootWidget[layer]; if(root == wgtRoot) return layer; } return -1; } #if LE_STREAMING_ENABLED == 1 leStreamManager* leGetActiveStream() { return _state.activeStream; } leResult leRunActiveStream() { if(_state.activeStream != NULL) { if(_state.activeStream->exec(_state.activeStream) == LE_FAILURE) { leAbortActiveStream(); } else { if(_state.activeStream != NULL && _state.activeStream->isDone(_state.activeStream) == LE_TRUE) { _state.activeStream->cleanup(_state.activeStream); _state.activeStream = NULL; } return LE_SUCCESS; } } return LE_FAILURE; } void leAbortActiveStream() { if(_state.activeStream != NULL) { _state.activeStream->abort(_state.activeStream); if(_state.activeStream != NULL && _state.activeStream->isDone(_state.activeStream) == LE_TRUE) { _state.activeStream->cleanup(_state.activeStream); _state.activeStream = NULL; } } } #endif leResult leEdit_StartEdit() { leEditWidget* edit = leGetEditWidget(); if(edit == NULL) return LE_FAILURE; return edit->fn->editStart(edit); } void leEdit_EndEdit() { leEditWidget* edit = leGetEditWidget(); if(edit == NULL) return; edit->fn->editEnd(edit); } void leEdit_Clear() { leEditWidget* edit = leGetEditWidget(); if(edit == NULL) return; edit->fn->editClear(edit); } void leEdit_Accept() { leEditWidget* edit = leGetEditWidget(); if(edit == NULL) return; edit->fn->editAccept(edit); } void leEdit_Set(leString* str) { leEditWidget* edit = leGetEditWidget(); if(edit == NULL) return; edit->fn->editSet(edit, str); } void leEdit_Append(leString* str) { leEditWidget* edit = leGetEditWidget(); if(edit == NULL) return; edit->fn->editAppend(edit, str); } void leEdit_Backspace() { leEditWidget* edit = leGetEditWidget(); if(edit == NULL) return; edit->fn->editBackspace(edit); }
22.404421
94
0.665738
1e7182b3f3d42d74c3b08ef96387737df70b03dd
844
h
C
trview.app/Menus/MenuDetector.h
sapper-trle/trview
dc9f945355a5976f2a539316a5dbf8323bb75064
[ "MIT" ]
null
null
null
trview.app/Menus/MenuDetector.h
sapper-trle/trview
dc9f945355a5976f2a539316a5dbf8323bb75064
[ "MIT" ]
null
null
null
trview.app/Menus/MenuDetector.h
sapper-trle/trview
dc9f945355a5976f2a539316a5dbf8323bb75064
[ "MIT" ]
null
null
null
#pragma once #include <trview.common/Event.h> #include <trview.common/MessageHandler.h> namespace trview { class MenuDetector final : public MessageHandler { public: /// Create a new MenuDetector. /// @param window The window that the detector is monitoring. explicit MenuDetector(const Window& window); /// Destructor for MenuDetector. virtual ~MenuDetector() = default; /// Handles a window message. /// @param message The message that was received. /// @param wParam The WPARAM for the message. /// @param lParam The LPARAM for the message. virtual void process_message(UINT message, WPARAM wParam, LPARAM lParam) override; /// Event raised when the menu is toggled on or off. Event<bool> on_menu_toggled; private: }; }
29.103448
90
0.652844
f00ddfc005a17a9881461b1145687930cd59ed51
451
h
C
include/HTTPRequest.h
406345/MaratonGameServer
56198afca0b155f4bb643a4a203acdc34afb7324
[ "MIT" ]
null
null
null
include/HTTPRequest.h
406345/MaratonGameServer
56198afca0b155f4bb643a4a203acdc34afb7324
[ "MIT" ]
null
null
null
include/HTTPRequest.h
406345/MaratonGameServer
56198afca0b155f4bb643a4a203acdc34afb7324
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * * * * * * YHGenomics Inc. * Author : yang shubo * Date : 2015-11-15 * Description: * * * * * * * * * * * * * * * */ #ifndef HTTP_REQEUST_H_ #define HTTP_REQEUST_H_ #include <functional> #include "HTTPAction.h" class HTTPRequest : public HTTPAction { public: HTTPRequest( ); virtual Buffer build_http_header( ) override; private: }; #endif // !HTTP_REQEUST_H_
16.107143
50
0.536585
187ddf546e8c17aa2fd0028640d9515fed11f38a
1,494
h
C
libcef/browser/views/textfield_view.h
Exstream-OpenSource/Chromium-Embedded-Framework
74cf22c97ad16b56a37c9362c47a04425615dc28
[ "BSD-3-Clause" ]
3
2018-07-17T16:57:42.000Z
2020-08-11T14:06:02.000Z
libcef/browser/views/textfield_view.h
ghl0323/cef_project
fe68aee82ce9e3c0d41421530899506c54e7ed3b
[ "BSD-3-Clause" ]
null
null
null
libcef/browser/views/textfield_view.h
ghl0323/cef_project
fe68aee82ce9e3c0d41421530899506c54e7ed3b
[ "BSD-3-Clause" ]
3
2018-04-20T17:45:39.000Z
2021-10-20T19:48:00.000Z
// Copyright 2016 The Chromium Embedded Framework Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file. #ifndef CEF_LIBCEF_BROWSER_VIEWS_TEXTFIELD_VIEW_H_ #define CEF_LIBCEF_BROWSER_VIEWS_TEXTFIELD_VIEW_H_ #pragma once #include "include/views/cef_textfield_delegate.h" #include "include/views/cef_textfield.h" #include "libcef/browser/views/view_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/textfield/textfield_controller.h" class CefTextfieldView : public CefViewView<views::Textfield, CefTextfieldDelegate>, public views::TextfieldController { public: typedef CefViewView<views::Textfield, CefTextfieldDelegate> ParentClass; // |cef_delegate| may be nullptr. explicit CefTextfieldView(CefTextfieldDelegate* cef_delegate); void Initialize() override; // Returns the CefTextfield associated with this view. See comments on // CefViewView::GetCefView. CefRefPtr<CefTextfield> GetCefTextfield() const { CefRefPtr<CefTextfield> textfield = GetCefView()->AsTextfield(); DCHECK(textfield); return textfield; } // TextfieldController methods: bool HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) override; void OnAfterUserAction(views::Textfield* sender) override; private: DISALLOW_COPY_AND_ASSIGN(CefTextfieldView); }; #endif // CEF_LIBCEF_BROWSER_VIEWS_TEXTFIELD_VIEW_H_
32.478261
79
0.778447
b70e75d07666e189fef8716dd5a1694e4b84f217
219
h
C
SparrowSDK/Classes/Core/SPRRequestFilter.h
eleme/SparrowSDK-iOS
98e6cefbfbb72ae9762e319b9dde53f5bf29dc52
[ "Apache-2.0" ]
17
2018-10-11T08:53:25.000Z
2019-12-26T01:37:30.000Z
SparrowSDK/Classes/Core/SPRRequestFilter.h
summertian4/SparrowSDK-iOS
c25378410b6d9d5dd0b5b2e744a8e7b73c001263
[ "MIT" ]
null
null
null
SparrowSDK/Classes/Core/SPRRequestFilter.h
summertian4/SparrowSDK-iOS
c25378410b6d9d5dd0b5b2e744a8e7b73c001263
[ "MIT" ]
2
2018-09-29T12:08:24.000Z
2018-11-12T06:54:18.000Z
// // SPRRequestFilter.h // SparrowSDK // // Created by 周凌宇 on 2018/3/13. // #import <Foundation/Foundation.h> @interface SPRRequestFilter : NSObject + (NSURLRequest *)filterRequest:(NSURLRequest *)reqeust; @end
14.6
56
0.707763
764718910e00a347ce16dd2ab70c5cdc7831bef6
868
h
C
Skejool_iOS/Skejool/Classes/Proxy.h
petester42/skejool
757c9cf1a89c8aef889805c2e0f34a351575960f
[ "MIT" ]
null
null
null
Skejool_iOS/Skejool/Classes/Proxy.h
petester42/skejool
757c9cf1a89c8aef889805c2e0f34a351575960f
[ "MIT" ]
null
null
null
Skejool_iOS/Skejool/Classes/Proxy.h
petester42/skejool
757c9cf1a89c8aef889805c2e0f34a351575960f
[ "MIT" ]
null
null
null
// // Proxy.h // Nominator // // Created by Pierre-Marc Airoldi on 11-08-30. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> #import "ASIFormDataRequest.h" #import "JSONKit.h" #import "ProxyRequestHandler.h" @interface Proxy : NSObject { NSRecursiveLock *cancelledLock; } + (id)sharedInstance; +(void)loginWithUsername:(NSString *)userID andPassword:(NSString *)session; +(void)getSequenceForUser:(NSString *)userID withSession:(NSString *)session; +(void)getCoursesForUser:(NSString *)userID withSession:(NSString *)session; +(void)getSchedulesForUser:(NSString *)userID withSession:(NSString *)session; +(void)getGeneratedSchedulesForUser:(NSString *)userID withSession:(NSString *)session; +(void)saveScheduleForUser:(NSString *)userID withSession:(NSString *)session andSchedule:(id)schedule; @end
28.933333
103
0.761521
eb8ece06f6b6ebdce8c8edb01797d6e460e0c536
1,163
h
C
src/modules/memory/dram.h
IronySuzumiya/G-Sim
b6bf4d22da0b0fde190490a2cbb600b21a4ee395
[ "MIT" ]
4
2020-06-17T06:49:01.000Z
2021-08-03T12:43:15.000Z
src/modules/memory/dram.h
IronySuzumiya/G-Sim
b6bf4d22da0b0fde190490a2cbb600b21a4ee395
[ "MIT" ]
10
2019-09-24T15:00:40.000Z
2019-11-13T01:51:14.000Z
src/modules/memory/dram.h
IronySuzumiya/G-Sim
b6bf4d22da0b0fde190490a2cbb600b21a4ee395
[ "MIT" ]
2
2020-09-03T07:06:57.000Z
2020-10-13T01:03:09.000Z
/* * Andrew Smith * * DRAM Memory. Derived from Memory class, Uses DRAMSim2 to model the timing * */ #ifndef _DRAM_H #define _DRAM_H #include <list> #include <tuple> #include <vector> #include "DRAMSim.h" #include "memory.h" namespace SimObj { class DRAM : public Memory { private: std::list<std::tuple<uint64_t, bool*, bool>> _write_queue; std::list<std::tuple<uint64_t, bool*, bool>> _read_queue; DRAMSim::TransactionCompleteCB *write_cb; DRAMSim::TransactionCompleteCB *read_cb; DRAMSim::MultiChannelMemorySystem *_mem; int sequential_write_counter; int sequential_read_counter; int buffer_size; public: DRAM(void); DRAM(uint64_t access_latency, uint64_t write_latency, uint64_t num_simultaneous_requests); ~DRAM(); void tick(void); void write(uint64_t addr, bool* complete, bool sequential=true); void read(uint64_t addr, bool* complete, bool sequential=true); // DRAMSim2 Callbacks: void read_complete(unsigned int id, uint64_t address, uint64_t clock_cycle); void write_complete(unsigned int id, uint64_t address, uint64_t clock_cycle); void print_stats(); }; // class DRAM } // namespace SimObj #endif
22.803922
92
0.742906
8d29535539ee6706266ca108d5ad5b5263cb3c90
1,891
h
C
Branch/Deprecated/ros_code/rospand/src/pandar-ros-vstyle-gps/pandar_driver/src/driver/driver.h
Tsinghua-OpenICV/OpenICV
37bf88122414d0c766491460248f61fa1a9fd78c
[ "MIT" ]
12
2019-12-17T08:17:51.000Z
2021-12-14T03:13:10.000Z
Branch/Deprecated/ros_code/rospand/src/pandar-ros-vstyle-gps/pandar_driver/src/driver/driver.h
Tsinghua-OpenICV/OpenICV
37bf88122414d0c766491460248f61fa1a9fd78c
[ "MIT" ]
null
null
null
Branch/Deprecated/ros_code/rospand/src/pandar-ros-vstyle-gps/pandar_driver/src/driver/driver.h
Tsinghua-OpenICV/OpenICV
37bf88122414d0c766491460248f61fa1a9fd78c
[ "MIT" ]
7
2019-12-17T08:17:54.000Z
2022-02-21T15:53:57.000Z
/* -*- mode: C++ -*- */ /* * Copyright (C) 2012 Austin Robot Technology, Jack O'Quin * Copyright (c) 2017 Hesai Photonics Technology Co., Ltd * * License: Modified BSD Software License Agreement * * $Id$ */ /** \file * * ROS driver interface for the pandar 3D LIDARs */ #ifndef _PANDAR_DRIVER_H_ #define _PANDAR_DRIVER_H_ 1 #include <string> #include <ros/ros.h> #include <diagnostic_updater/diagnostic_updater.h> #include <diagnostic_updater/publisher.h> #include <dynamic_reconfigure/server.h> #include <pandar_driver/input.h> #include <pandar_driver/PandarNodeConfig.h> namespace pandar_driver { class PandarDriver { public: PandarDriver(ros::NodeHandle node, ros::NodeHandle private_nh); ~PandarDriver() {} bool poll(void); private: ///Callback for dynamic reconfigure void callback(pandar_driver::PandarNodeConfig &config, uint32_t level); ///Pointer to dynamic reconfigure service srv_ boost::shared_ptr<dynamic_reconfigure::Server<pandar_driver:: PandarNodeConfig> > srv_; // configuration parameters struct { std::string frame_id; ///< tf frame ID std::string model; ///< device model name int npackets; ///< number of packets to collect double rpm; ///< device rotation rate (RPMs) double time_offset; ///< time in seconds added to each pandar time stamp } config_; boost::shared_ptr<Input> input_; ros::Publisher output_; ros::Publisher gpsoutput_; /** diagnostics updater */ diagnostic_updater::Updater diagnostics_; double diag_min_freq_; double diag_max_freq_; boost::shared_ptr<diagnostic_updater::TopicDiagnostic> diag_topic_; }; } // namespace pandar_driver #endif // _PANDAR_DRIVER_H_
24.881579
90
0.652036
020a28097931f98e441222373ba017394022e007
1,296
h
C
datapath/linux-2.6/compat-2.6/include/linux/mutex.h
salomon42/openvswitch-ovs
7fae5e7bb62af3b8ac74fe20052064eb01feada0
[ "Apache-2.0" ]
9
2015-12-15T00:55:59.000Z
2019-11-22T16:17:58.000Z
datapath/linux-2.6/compat-2.6/include/linux/mutex.h
salomon42/openvswitch-ovs
7fae5e7bb62af3b8ac74fe20052064eb01feada0
[ "Apache-2.0" ]
1
2017-04-17T03:44:27.000Z
2018-04-13T07:48:22.000Z
datapath/linux-2.6/compat-2.6/include/linux/mutex.h
salomon42/openvswitch-ovs
7fae5e7bb62af3b8ac74fe20052064eb01feada0
[ "Apache-2.0" ]
19
2015-02-06T23:24:53.000Z
2021-02-05T05:20:56.000Z
#ifndef __LINUX_MUTEX_WRAPPER_H #define __LINUX_MUTEX_WRAPPER_H #include <linux/version.h> #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16) #include <asm/semaphore.h> struct mutex { struct semaphore sema; }; #define mutex_init(mutex) init_MUTEX(&(mutex)->sema) #define mutex_destroy(mutex) do { } while (0) #define __MUTEX_INITIALIZER(name) \ __SEMAPHORE_INITIALIZER(name,1) #define DEFINE_MUTEX(mutexname) \ struct mutex mutexname = { __MUTEX_INITIALIZER(mutexname.sema) } /* * See kernel/mutex.c for detailed documentation of these APIs. * Also see Documentation/mutex-design.txt. */ static inline void mutex_lock(struct mutex *lock) { down(&lock->sema); } static inline int mutex_lock_interruptible(struct mutex *lock) { return down_interruptible(&lock->sema); } #define mutex_lock_nested(lock, subclass) mutex_lock(lock) #define mutex_lock_interruptible_nested(lock, subclass) mutex_lock_interruptible(lock) /* * NOTE: mutex_trylock() follows the spin_trylock() convention, * not the down_trylock() convention! */ static inline int mutex_trylock(struct mutex *lock) { return !down_trylock(&lock->sema); } static inline void mutex_unlock(struct mutex *lock) { up(&lock->sema); } #else #include_next <linux/mutex.h> #endif /* linux version < 2.6.16 */ #endif
21.6
86
0.752315
77e902b1c3f988d463d50e42d4d2d1b80352d4a1
355
h
C
src/utils.h
Reasoning-Technology/only-one
667c176a4f13940d0d2b94e85405c29e17c8816a
[ "MIT" ]
null
null
null
src/utils.h
Reasoning-Technology/only-one
667c176a4f13940d0d2b94e85405c29e17c8816a
[ "MIT" ]
null
null
null
src/utils.h
Reasoning-Technology/only-one
667c176a4f13940d0d2b94e85405c29e17c8816a
[ "MIT" ]
null
null
null
#ifndef UTILS_H #define UTILS_H #include <iostream> #include <sstream> #include <string> using namespace std; #include "types.h" void printss( stringstream &ss ){ cout << ss.str() << endl; } void printis( istream &is){ if( !is ) RETURN; streampos spot = is.tellg(); cout << is.rdbuf(); is.clear(); is.seekg(spot); is.clear(); } #endif
13.653846
33
0.639437