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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fe92b140f98815035bee924cf1578e48e9011200 | 513 | c | C | software/spu32-system/apps/cmds/shared.c | mfkiwl/spu32 | d1988e6c13a953adc907ce4fbf56d62883359551 | [
"MIT"
] | 51 | 2018-02-23T12:25:43.000Z | 2022-02-13T04:25:16.000Z | software/spu32-system/apps/cmds/shared.c | mfkiwl/spu32 | d1988e6c13a953adc907ce4fbf56d62883359551 | [
"MIT"
] | 1 | 2018-08-01T13:46:09.000Z | 2020-02-19T09:23:46.000Z | software/spu32-system/apps/cmds/shared.c | mfkiwl/spu32 | d1988e6c13a953adc907ce4fbf56d62883359551 | [
"MIT"
] | 8 | 2018-05-01T01:56:06.000Z | 2022-01-25T14:26:03.000Z | #include "shared.h"
#include <libtinyc.h>
void clear_buf(char* buf, int len)
{
for (int i = 0; i < len; ++i) {
buf[i] = 0;
}
}
int arg1_func(int argn, char** argv, int (*fun)(char*))
{
if (argn < 2) {
printf("needs an argument\n\r");
return 1;
}
return (*fun)(argv[1]);
}
int arg2_func(int argn, char** argv, int (*fun)(char*, char*))
{
if (argn < 3) {
printf("needs two arguments\n\r");
return 1;
}
return (*fun)(argv[1], argv[2]);
}
| 16.548387 | 62 | 0.508772 |
5f1d1dc765c30e53d2e65bc4adb5d0f996153d4e | 12,364 | c | C | madrisan-nagios-plugins-linux/nagios-plugins-linux/lib/netinfo-private.c | waja/pkg-nagios-plugins-contrib | fd1480282a016212ac28e4479ff477c72052f6fb | [
"Artistic-1.0-Perl"
] | null | null | null | madrisan-nagios-plugins-linux/nagios-plugins-linux/lib/netinfo-private.c | waja/pkg-nagios-plugins-contrib | fd1480282a016212ac28e4479ff477c72052f6fb | [
"Artistic-1.0-Perl"
] | null | null | null | madrisan-nagios-plugins-linux/nagios-plugins-linux/lib/netinfo-private.c | waja/pkg-nagios-plugins-contrib | fd1480282a016212ac28e4479ff477c72052f6fb | [
"Artistic-1.0-Perl"
] | null | null | null | // SPDX-License-Identifier: GPL-3.0-or-later
/*
* License: GPLv3+
* Copyright (c) 2014,2020 Davide Madrisan <davide.madrisan@gmail.com>
*
* A library for getting some network interfaces.statistics.
*
* 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/>.
*
*/
#include <errno.h>
#include <ifaddrs.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <linux/ethtool.h>
#ifdef HAVE_LINUX_IF_LINK_H
# include <linux/if_link.h>
#endif
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/sockios.h>
#include <linux/wireless.h>
#include "common.h"
#include "logging.h"
#include "messages.h"
#include "netinfo.h"
#include "string-macros.h"
#include "system.h"
#include "xalloc.h"
typedef struct nl_req_s
{
struct nlmsghdr hdr;
struct rtgenmsg gen;
} nl_req_t;
const char *const duplex_table[_DUP_MAX] = {
[DUPLEX_HALF] = "half",
[DUPLEX_FULL] = "full"
};
const struct link_speed
{
long phy_speed;
const char *phy_speed_str;
} phy_speed_to_str[] = {
{ SPEED_10, "10Mbps" },
{ SPEED_100, "100Mbps" },
{ SPEED_1000, "1Gbps" },
{ SPEED_2500, "2.5Gbps" },
{ SPEED_5000, "5Gbps" },
{ SPEED_10000, "10Gbps" },
#if defined (SPEED_14000)
{ SPEED_14000, "14Gbps" },
#endif
#if defined (SPEED_20000)
{ SPEED_20000, "20Gbps" },
#endif
#if defined (SPEED_25000)
{ SPEED_25000, "25Gbps" },
#endif
#if defined (SPEED_40000)
{ SPEED_40000, "40Gbps" },
#endif
#if defined (SPEED_50000)
{ SPEED_50000, "50Gbps" },
#endif
#if defined (SPEED_56000)
{ SPEED_56000, "56Gbps" },
#endif
#if defined (SPEED_100000)
{ SPEED_100000, "100Gbps" },
#endif
{ SPEED_UNKNOWN, "unknown!" }
};
static const size_t link_speed_size =
sizeof (phy_speed_to_str) / sizeof (phy_speed_to_str[0]);
static int
get_ctl_fd (void)
{
int fd;
int s_errno;
if ((fd = socket (PF_INET, SOCK_DGRAM, 0)) >= 0)
return fd;
s_errno = errno;
if ((fd = socket (PF_PACKET, SOCK_DGRAM, 0)) >= 0)
return fd;
if ((fd = socket (PF_INET6, SOCK_DGRAM, 0)) >= 0)
return fd;
errno = s_errno;
return -1;
}
static const char *
map_speed_value_for_key (const struct link_speed * map, long phy_speed)
{
const char* ret = NULL;
for (size_t i = 0 ; i < link_speed_size && ret == NULL; i++)
if (map[i].phy_speed == phy_speed)
ret = map[i].phy_speed_str;
return ret ? ret : "unknown!";
}
/* Determines network interface speed from ETHTOOL_GLINKSETTINGS
* (requires Linux kernel 4.9+).
* In case of failure revert to obsolete ETHTOOL_GSET. */
static int
check_link_speed (const char *ifname, uint32_t *speed, uint8_t *duplex)
{
int fd, ret = -1;
struct ifreq ifr = {};
struct ethtool_cmd ecmd = {
.cmd = ETHTOOL_GSET
};
#ifdef ETHTOOL_GLINKSETTINGS
# define ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32 (SCHAR_MAX)
struct elinkset {
struct ethtool_link_settings req;
uint32_t link_mode_data[3 * ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32];
} elinkset;
#endif
if ((fd = get_ctl_fd ()) < 0)
plugin_error (STATE_UNKNOWN, errno, "socket() failed");
*duplex = DUPLEX_UNKNOWN;
*speed = 0; /* SPEED_UNKNOWN */
STRNCPY_TERMINATED (ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
#ifdef ETHTOOL_GLINKSETTINGS
/* The interaction user/kernel via the new API requires a small
* ETHTOOL_GLINKSETTINGS handshake first to agree on the length
* of the link mode bitmaps. If kernel doesn't agree with user,
* it returns the bitmap length it is expecting from user as a
* negative length (and cmd field is 0). When kernel and user
* agree, kernel returns valid info in all fields (ie. link mode
* length > 0 and cmd is ETHTOOL_GLINKSETTINGS). Based on
* https://github.com/torvalds/linux/commit/3f1ac7a700d039c61d8d8b99f28d605d489a60cf
*/
dbg ("ETHTOOL_GLINKSETTINGS is defined\n");
memset (&elinkset, 0, sizeof (elinkset));
elinkset.req.cmd = ETHTOOL_GLINKSETTINGS;
ifr.ifr_data = (void *) &elinkset;
ret = ioctl (fd, SIOCETHTOOL, &ifr);
/* see above: we expect a strictly negative value from kernel. */
if (ret >= 0 && (elinkset.req.link_mode_masks_nwords < 0))
{
elinkset.req.cmd = ETHTOOL_GLINKSETTINGS;
elinkset.req.link_mode_masks_nwords = -elinkset.req.link_mode_masks_nwords;
ret = ioctl (fd, SIOCETHTOOL, &ifr);
if (ret < 0 || elinkset.req.link_mode_masks_nwords <= 0
|| elinkset.req.cmd != ETHTOOL_GLINKSETTINGS)
ret = -ENOTSUP;
}
#endif
if (ret < 0)
{
dbg ("%s: revert to the obsolete ETHTOOL_GSET...\n", ifname);
ifr.ifr_data = (void *) &ecmd;
if ((ret = ioctl (fd, SIOCETHTOOL, &ifr)) == 0)
{
*duplex = ecmd.duplex;
*speed = ecmd.speed;
}
else
dbg ("%s: no link speed associated to this interface\n", ifname);
}
#ifdef ETHTOOL_GLINKSETTINGS
else
{
*duplex = elinkset.req.duplex;
*speed = elinkset.req.speed;
}
#endif
dbg ("%s: duplex %s (%d), speed is %s (%u)\n"
, ifname
, *duplex == _DUP_UNKNOWN ? "invalid" : duplex_table[*duplex]
, *duplex
, map_speed_value_for_key (phy_speed_to_str, *speed)
, *speed);
/* normalize the unknown speed values */
if (*speed == (uint16_t)(-1) || *speed == (uint32_t)(-1))
{
dbg ("%s: normalizing the unknown speed to zero...\n", ifname);
*speed = 0;
}
close (fd);
return ret;
}
static bool
link_wireless (const char *ifname)
{
bool is_wireless = false;
int sock;
struct iwreq pwrq;
if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
plugin_error (STATE_UNKNOWN, errno, "socket() failed");
memset (&pwrq, 0, sizeof (pwrq));
strncpy (pwrq.ifr_name, ifname, IFNAMSIZ);
if (ioctl (sock, SIOCGIWNAME, &pwrq) != -1)
{
dbg ("%s: wireless interface (%s)\n"
, ifname
, pwrq.u.name);
is_wireless = true;
}
close (sock);
return is_wireless;
}
/* Get the RTNL socket */
static int
get_rtnl_fd ()
{
int fd;
union
{
struct sockaddr addr;
struct sockaddr_nl local; /* local (user space) addr struct */
} u;
fd = socket (AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd < 0)
plugin_error (STATE_UNKNOWN, errno, "failed to create netlink socket");
memset (&u.local, 0, sizeof (u.local));
u.local.nl_family = AF_NETLINK;
u.local.nl_groups = 0;
u.local.nl_pid = getpid ();
if (bind (fd, &u.addr, sizeof (u.addr)) < 0)
{
close (fd);
plugin_error (STATE_UNKNOWN, errno, "failed to bind netlink socket");
}
return fd;
}
/* Prepare and send the RTNL request for dumping the network links
* configuration */
static int
sendmsg_rtnl_links_dump (int fd, struct iovec *iov, struct sockaddr_nl *kernel)
{
nl_req_t req; /* structure that describes the rtnetlink packet itself */
struct msghdr rtnl_msg; /* generic msghdr struct for use with sendmsg */
memset (&rtnl_msg, 0, sizeof (rtnl_msg));
memset (kernel, 0, sizeof (*kernel));
memset (&req, 0, sizeof (req));
kernel->nl_family = AF_NETLINK;
req.hdr.nlmsg_len = NLMSG_LENGTH (sizeof (struct rtgenmsg));
req.hdr.nlmsg_type = RTM_GETLINK;
req.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
req.hdr.nlmsg_seq = 1;
req.hdr.nlmsg_pid = getpid ();
/* no preferred AF, we will get all interfaces */
req.gen.rtgen_family = AF_PACKET;
iov->iov_base = &req;
iov->iov_len = req.hdr.nlmsg_len;
rtnl_msg.msg_iov = iov;
rtnl_msg.msg_iovlen = 1;
rtnl_msg.msg_name = kernel;
rtnl_msg.msg_namelen = sizeof (*kernel);
if (sendmsg (fd, (struct msghdr *) &rtnl_msg, 0) < 0)
return errno;
return 0;
}
static int
parse_rtattr (struct rtattr *tb[], int max, struct rtattr *rta, int len)
{
memset (tb, 0, sizeof (struct rtattr *) * (max + 1));
while (RTA_OK (rta, len))
{
if (rta->rta_type <= max)
tb[rta->rta_type] = rta;
rta = RTA_NEXT (rta,len);
}
return 0;
}
#define IFLIST_REPLY_BUFFER 8192
struct iflist *
get_netinfo_snapshot (unsigned int options, const regex_t *if_regex)
{
bool msg_done = false,
opt_ignore_loopback = (options & NO_LOOPBACK),
opt_ignore_wireless = (options & NO_WIRELESS);
char reply[IFLIST_REPLY_BUFFER];
int fd, ret;
struct iflist *iflhead = NULL, *iflprev = NULL;
/* netlink structures */
struct iovec iov; /* IO vector for sendmsg */
/* the remote (kernel space) side of the communication */
struct sockaddr_nl kernel;
fd = get_rtnl_fd ();
ret = sendmsg_rtnl_links_dump (fd, &iov, &kernel);
if (ret != 0)
plugin_error (STATE_UNKNOWN, ret, "error in sendmsg");
while (!msg_done)
{
/* parse reply */
ssize_t len;
struct nlmsghdr *h;
struct msghdr rtnl_reply;
struct iovec io_reply;
memset (&io_reply, 0, sizeof (io_reply));
memset (&rtnl_reply, 0, sizeof (rtnl_reply));
iov.iov_base = reply;
iov.iov_len = IFLIST_REPLY_BUFFER;
rtnl_reply.msg_iov = &iov;
rtnl_reply.msg_iovlen = 1;
rtnl_reply.msg_name = &kernel;
rtnl_reply.msg_namelen = sizeof (kernel);
/* read as much data as fits in the receive buffer */
if ((len = recvmsg (fd, &rtnl_reply, MSG_DONTWAIT)) < 0)
{
usleep (250000); /* sleep for a while */
continue;
}
char name[IFNAMSIZ];
int attr_len;
struct iflist *ifl;
struct ifinfomsg *ifi;
struct rtattr *tb[IFLA_MAX+1];
struct rtnl_link_stats *stats;
for (h = (struct nlmsghdr *) reply;
NLMSG_OK (h, len); h = NLMSG_NEXT (h, len))
{
switch (h->nlmsg_type)
{
/* this is the special meaning NLMSG_DONE message we asked for
* by using NLM_F_DUMP flag */
case NLMSG_DONE:
msg_done = true;
break;
case RTM_NEWLINK:
ifi = NLMSG_DATA (h);
attr_len = h->nlmsg_len - NLMSG_LENGTH (sizeof (*ifi));
parse_rtattr (tb, IFLA_MAX, IFLA_RTA (ifi), attr_len);
if (NULL == tb[IFLA_IFNAME])
plugin_error (STATE_UNKNOWN, 0,
"BUG: nil ifname returned by parse_rtattr()");
strcpy (name, (char *) RTA_DATA (tb[IFLA_IFNAME]));
bool is_loopback = if_flags_LOOPBACK (ifi->ifi_flags);
bool is_wireless = link_wireless (name);
bool skip_interface =
((is_loopback && opt_ignore_loopback)
|| (is_wireless && opt_ignore_wireless)
|| (regexec (if_regex, name, (size_t) 0, NULL, 0)));
if (skip_interface)
{
dbg ("skipping network interface '%s'...\n", name);
continue;
}
/* create a new list structure 'ifl' and initialize
* all the members, except stats-related ones */
ifl = xmalloc (sizeof (struct iflist));
ifl->ifname = xstrdup (name);
ifl->flags = ifi->ifi_flags;
check_link_speed (name, &(ifl->speed), &(ifl->duplex));
ifl->next = NULL;
ifl->stats = NULL;
if (NULL == iflhead)
iflhead = ifl;
else
iflprev->next = ifl;
iflprev = ifl;
stats = (struct rtnl_link_stats *) RTA_DATA (tb[IFLA_STATS]);
if (stats)
{
/* copy the link statistics into the list structure 'ifl' */
ifl->stats = xmalloc (sizeof (struct ifstats));
ifl->stats->collisions = stats->collisions;
ifl->stats->multicast = stats->multicast;
ifl->stats->tx_packets = stats->tx_packets;
ifl->stats->rx_packets = stats->rx_packets;
ifl->stats->tx_bytes = stats->tx_bytes;
ifl->stats->rx_bytes = stats->rx_bytes;
ifl->stats->tx_errors = stats->tx_errors;
ifl->stats->rx_errors = stats->rx_errors;
ifl->stats->tx_dropped = stats->tx_dropped;
ifl->stats->rx_dropped = stats->rx_dropped;
}
else
dbg ("no network interface stats for '%s'...\n", name);
break;
}
}
}
close (fd);
return iflhead;
}
#undef IFLIST_REPLY_BUFFER
| 27.173626 | 90 | 0.649951 |
24e154f61a068cea4f814f1268ea8c89bd16845f | 1,583 | h | C | BattleTank/Source/BattleTank/TankMovementComponent.h | YuLeven/BattleTank | 6f4fb7cb631e8c335f9b02d4827b942a1c3a922e | [
"MIT"
] | null | null | null | BattleTank/Source/BattleTank/TankMovementComponent.h | YuLeven/BattleTank | 6f4fb7cb631e8c335f9b02d4827b942a1c3a922e | [
"MIT"
] | null | null | null | BattleTank/Source/BattleTank/TankMovementComponent.h | YuLeven/BattleTank | 6f4fb7cb631e8c335f9b02d4827b942a1c3a922e | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/NavMovementComponent.h"
#include "TankMovementComponent.generated.h"
/**
*
*/
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class BATTLETANK_API UTankMovementComponent : public UNavMovementComponent
{
GENERATED_BODY()
public:
UTankMovementComponent();
// Auxiliary method used to set the needed references.
// I'd rather see the constructor used for this kind of stuff but
// apparently this kind of thing is common here thanks to blueprint.
UFUNCTION(BlueprintCallable, Category = Setup)
void Initialize(UTankTrack* LeftTrackToSet, UTankTrack* RightTrackToSet);
// This moves the tank forwards and backwards in a fly-by-wire system
UFUNCTION(BlueprintCallable, Category = Movement)
void IntendMoveForward(float Throw);
// This rotates the tank clockwise in the fly-by-wire system
UFUNCTION(BlueprintCallable, Category = Movement)
void IntendTurnRight(float Throw);
// This rotates the tank anti-clockwise in the fly-by-wire system
UFUNCTION(BlueprintCallable, Category = Movement)
void IntendTurnLeft(float Throw);
private:
UPROPERTY()
class UTankTrack* LeftTrack;
UTankTrack* RightTrack;
// This method is called by the AI when it is standing on a nav mesh bound volume every frame (pathfinding)
// The passed vector is the direction needed to be followed in order to reach the target
virtual void RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed) override;
};
| 32.306122 | 108 | 0.783323 |
0172bd939009a90174378a095e9768804a41cf56 | 523 | h | C | EventAnalyzer/interface/BaseTreeWriter.h | peterthomassen/RutgersIAF | 50fd20b79b8bce30478d49e1ce7c763424e094f1 | [
"MIT"
] | null | null | null | EventAnalyzer/interface/BaseTreeWriter.h | peterthomassen/RutgersIAF | 50fd20b79b8bce30478d49e1ce7c763424e094f1 | [
"MIT"
] | null | null | null | EventAnalyzer/interface/BaseTreeWriter.h | peterthomassen/RutgersIAF | 50fd20b79b8bce30478d49e1ce7c763424e094f1 | [
"MIT"
] | null | null | null | #ifndef BaseTreeWriter_h
#define BaseTreeWriter_h
#include <TROOT.h>
#include <TObject.h>
#include <vector>
#include <map>
class TTree;
class TString;
class SignatureObject;
class TFile;
class BaseHandler;
class BaseTreeWriter : public TObject{
public:
BaseTreeWriter(BaseHandler*,TString);
virtual ~BaseTreeWriter();
TTree* getTree() {return m_tree;}
virtual void finish() = 0;
virtual void fillTree() = 0;
protected:
BaseHandler* m_handler;
TTree* m_tree;
ClassDef(BaseTreeWriter,1);
};
#endif
| 15.382353 | 39 | 0.734226 |
4aeab73be49ed8e3699a570b5847c09702a7da3e | 1,510 | h | C | headers/serial.h | cheetosysst/os | 6baeb134726fca7e32556c1836823e1e9a72bec9 | [
"MIT"
] | 2 | 2022-03-21T09:52:39.000Z | 2022-03-21T11:50:42.000Z | headers/serial.h | cheetosysst/os | 6baeb134726fca7e32556c1836823e1e9a72bec9 | [
"MIT"
] | 2 | 2022-03-21T10:16:08.000Z | 2022-03-25T08:13:55.000Z | headers/serial.h | cheetosysst/os | 6baeb134726fca7e32556c1836823e1e9a72bec9 | [
"MIT"
] | null | null | null | #ifndef SERIAL_LIB
#define SERIAL_LIB
// Serial configuration and init
/**
* @brief Initailize the serial COM1 port.
*
*/
void serial_general_setup();
/**
* @brief Set serial baud rate
*
* @param com COM port number.
* @param divisor Divisor to divide default speed 115200 bits/sec.
*/
void serial_configure_baud_rate(unsigned short com, unsigned short divisor);
/**
* @brief Default serial line configuration. No parity, one stop bit, break control disabled.
*
* @param com Address of the com port.
*/
void serial_configure_line(unsigned short com);
/**
* @brief Default configuration of serial FIFO.
*
* @param com Address of the com port.
*/
void serial_configure_fifo(unsigned short com);
/**
* @brief Check whether serial com's buffer FIFO queue is empty.
*
* @param com Address of the com port.
* @return int
*/
int serial_check_fifo_empty(unsigned int com);
/**
* @brief Prints a single ascii charactor to serial port.
*
* @param com
* @param chr
*/
void serial_putc(unsigned short com, char chr);
/**
* @brief Print a string through to serial com port.
*
* @param com
* @param str
*/
void serial_print(unsigned short com, char str[]);
/**
* @brief Print formated string to serial port.
*
* @param fmt
* @param arg
*/
void serial_printf(unsigned short com, char *fmt, ...);
/**
* @brief Prints a unsigned int.
*
* @param data
* @param base
*/
void serial_print_uint(unsigned short com, unsigned int data, unsigned int base);
#endif | 19.868421 | 93 | 0.690728 |
2b811fde44df94edae50fa9da3de6187693398ce | 9,052 | h | C | src/visualisers/BoxPlotBasicItem.h | dtip/magics | 3247535760ca962f859c203295b508d442aca4ed | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/visualisers/BoxPlotBasicItem.h | dtip/magics | 3247535760ca962f859c203295b508d442aca4ed | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/visualisers/BoxPlotBasicItem.h | dtip/magics | 3247535760ca962f859c203295b508d442aca4ed | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-12-18T17:01:56.000Z | 2019-12-18T17:01:56.000Z | /*
* (C) Copyright 1996-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
/*! \file BoxPlotBasicItem.h
\brief Definition of the Template class BoxPlotBasicItem.
\author Meteorological Visualisation Section, ECMWF
Started: Sep 2006
*/
#ifndef BoxPlotBasicItem_H
#define BoxPlotBasicItem_H
#include "Factory.h"
#include "MagTranslator.h"
#include "Polyline.h"
#include "magics.h"
namespace magics {
class CustomisedPoint;
class PaperPoint;
class NoBoxPlotBox {
public:
NoBoxPlotBox() {}
virtual ~NoBoxPlotBox() {}
void cm(double cm) { cm_ = cm; }
virtual void set(const XmlNode&) { MagLog::dev() << "(const XmlNode&)---> to be checked!...\n"; }
virtual void set(const map<string, string>&) {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
}
virtual bool accept(const string&) { return false; }
virtual NoBoxPlotBox* clone() const {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
return new NoBoxPlotBox();
}
virtual void toxml(ostream&) const { MagLog::dev() << "toxml(ostream& out, int tab)---> to be checked!...\n"; }
virtual void operator()(BasicGraphicsObjectContainer&, const CustomisedPoint&) const {}
protected:
//! Method to print string about this class on to a stream of type ostream (virtual).
virtual void print(ostream&) const {}
double cm_;
private:
//! Copy constructor - No copy allowed
NoBoxPlotBox(const NoBoxPlotBox&);
//! Overloaded << operator to copy - No copy allowed
NoBoxPlotBox& operator=(const NoBoxPlotBox&);
// -- Friends
//! Overloaded << operator to call print().
friend ostream& operator<<(ostream& s, const NoBoxPlotBox& p) {
p.print(s);
return s;
}
};
class NoBoxPlotBoxBorder {
public:
NoBoxPlotBoxBorder() {}
virtual ~NoBoxPlotBoxBorder() {}
void cm(double cm) { cm_ = cm; }
virtual void set(const XmlNode&) { MagLog::dev() << "(const XmlNode&)---> to be checked!...\n"; }
virtual void set(const map<string, string>&) {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
}
virtual bool accept(const string&) { return false; }
virtual NoBoxPlotBoxBorder* clone() const {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
return new NoBoxPlotBoxBorder();
}
virtual void toxml(ostream&) const { MagLog::dev() << "toxml(ostream& out, int tab)---> to be checked!...\n"; }
virtual void operator()(Polyline& poly) const { poly.setStroke(false); }
protected:
//! Method to print string about this class on to a stream of type ostream (virtual).
virtual void print(ostream&) const {}
double cm_;
private:
//! Copy constructor - No copy allowed
NoBoxPlotBoxBorder(const NoBoxPlotBoxBorder&);
//! Overloaded << operator to copy - No copy allowed
NoBoxPlotBoxBorder& operator=(const NoBoxPlotBoxBorder&);
// -- Friends
//! Overloaded << operator to call print().
friend ostream& operator<<(ostream& s, const NoBoxPlotBoxBorder& p) {
p.print(s);
return s;
}
};
template <>
class MagTranslator<string, NoBoxPlotBoxBorder> {
public:
NoBoxPlotBoxBorder* operator()(const string& val) { return SimpleObjectMaker<NoBoxPlotBoxBorder>::create(val); }
NoBoxPlotBoxBorder* magics(const string& param) {
string val;
ParameterManager::get(param, val);
return (*this)(val);
}
};
template <>
class MagTranslator<string, NoBoxPlotBox> {
public:
NoBoxPlotBox* operator()(const string& val) { return SimpleObjectMaker<NoBoxPlotBox>::create(val); }
NoBoxPlotBox* magics(const string& param) {
string val;
ParameterManager::get(param, val);
return (*this)(val);
}
};
class NoBoxPlotMedian {
public:
NoBoxPlotMedian() {}
virtual ~NoBoxPlotMedian() {}
virtual bool accept(const string&) { return false; }
void cm(double cm) { cm_ = cm; }
virtual void set(const XmlNode&) {}
virtual void set(const map<string, string>&) {}
virtual NoBoxPlotMedian* clone() const { return new NoBoxPlotMedian(); }
virtual void toxml(ostream&) const {}
virtual void operator()(BasicGraphicsObjectContainer&, Polyline*) const {}
protected:
//! Method to print string about this class on to a stream of type ostream (virtual).
virtual void print(ostream&) const {}
double cm_;
private:
//! Copy constructor - No copy allowed
NoBoxPlotMedian(const NoBoxPlotMedian&);
//! Overloaded << operator to copy - No copy allowed
NoBoxPlotMedian& operator=(const NoBoxPlotMedian&);
// -- Friends
//! Overloaded << operator to call print().
friend ostream& operator<<(ostream& s, const NoBoxPlotMedian& p) {
p.print(s);
return s;
}
};
template <>
class MagTranslator<string, NoBoxPlotMedian> {
public:
NoBoxPlotMedian* operator()(const string& val) { return SimpleObjectMaker<NoBoxPlotMedian>::create(val); }
NoBoxPlotMedian* magics(const string& param) {
string val;
ParameterManager::get(param, val);
return (*this)(val);
}
};
class NoBoxPlotWhisker {
public:
NoBoxPlotWhisker() {}
virtual ~NoBoxPlotWhisker() {}
virtual bool accept(const string&) { return false; }
void cm(double cm) { cm_ = cm; }
virtual void set(const XmlNode&) { MagLog::dev() << "(const XmlNode&)---> to be checked!...\n"; }
virtual void set(const map<string, string>&) {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
}
virtual NoBoxPlotWhisker* clone() const {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
return new NoBoxPlotWhisker();
}
virtual void toxml(ostream&) const { MagLog::dev() << "toxml(ostream& out, int tab)---> to be checked!...\n"; }
virtual void top(BasicGraphicsObjectContainer&, const CustomisedPoint&) const {}
virtual void bottom(BasicGraphicsObjectContainer&, const CustomisedPoint&) const {}
protected:
//! Method to print string about this class on to a stream of type ostream (virtual).
virtual void print(ostream&) const {}
double cm_;
private:
//! Copy constructor - No copy allowed
NoBoxPlotWhisker(const NoBoxPlotWhisker&);
//! Overloaded << operator to copy - No copy allowed
NoBoxPlotWhisker& operator=(const NoBoxPlotWhisker&);
// -- Friends
//! Overloaded << operator to call print().
friend ostream& operator<<(ostream& s, const NoBoxPlotWhisker& p) {
p.print(s);
return s;
}
};
template <>
class MagTranslator<string, NoBoxPlotWhisker> {
public:
NoBoxPlotWhisker* operator()(const string& val) { return SimpleObjectMaker<NoBoxPlotWhisker>::create(val); }
NoBoxPlotWhisker* magics(const string& param) {
string val;
ParameterManager::get(param, val);
return (*this)(val);
}
};
class NoBoxPlotWhiskerBorder {
public:
NoBoxPlotWhiskerBorder() {}
virtual ~NoBoxPlotWhiskerBorder() {}
virtual bool accept(const string&) { return false; }
virtual void set(const XmlNode&) { MagLog::dev() << "(const XmlNode&)---> to be checked!...\n"; }
virtual void set(const map<string, string>&) {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
}
virtual NoBoxPlotWhiskerBorder* clone() const {
MagLog::dev() << "(const map<string, string&)---> to be checked!...\n";
return new NoBoxPlotWhiskerBorder();
}
virtual void toxml(ostream&) const { MagLog::dev() << "toxml(ostream& out, int tab)---> to be checked!...\n"; }
virtual void operator()(Polyline&) const {}
protected:
//! Method to print string about this class on to a stream of type ostream (virtual).
virtual void print(ostream&) const {}
private:
//! Copy constructor - No copy allowed
NoBoxPlotWhiskerBorder(const NoBoxPlotWhiskerBorder&);
//! Overloaded << operator to copy - No copy allowed
NoBoxPlotWhiskerBorder& operator=(const NoBoxPlotWhiskerBorder&);
// -- Friends
//! Overloaded << operator to call print().
friend ostream& operator<<(ostream& s, const NoBoxPlotWhiskerBorder& p) {
p.print(s);
return s;
}
};
template <>
class MagTranslator<string, NoBoxPlotWhiskerBorder> {
public:
NoBoxPlotWhiskerBorder* operator()(const string& val) {
return SimpleObjectMaker<NoBoxPlotWhiskerBorder>::create(val);
}
NoBoxPlotWhiskerBorder* magics(const string& param) {
string val;
ParameterManager::get(param, val);
return (*this)(val);
}
};
} // end namespace magics
#endif
| 31.106529 | 116 | 0.653999 |
2e21c5aab86d368dfc31b5d421bc8e5e3eb053ef | 14,774 | h | C | Coda/src/utils/Tools/Containers/ContainerEraser.h | Samsung/veles.nlp | 972fde27203cb04d301e34274b57435ed58372c4 | [
"Apache-2.0"
] | 8 | 2016-02-16T10:15:39.000Z | 2020-03-12T21:14:36.000Z | src/utils/Tools/Containers/ContainerEraser.h | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | null | null | null | src/utils/Tools/Containers/ContainerEraser.h | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | 6 | 2016-02-16T10:15:47.000Z | 2020-01-20T20:33:25.000Z | /**
*
* .. invisible:
* _ _ _____ _ _____ _____
*
* | | | | ___| | | ___/ ___|
*
* | | | | |__ | | | |__ \ `--.
*
* | | | | __|| | | __| `--. \
*
* \ \_/ / |___| |___| |___/\__/ /
*
* \___/\____/\_____|____/\____/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License
*
*/
#ifndef CONTAINER_ERASER
#define CONTAINER_ERASER
#include <algorithm>
#include <functional>
#include "TypeTraits.h"
namespace Tools
{
/* DEFINITIONS */
template<class Container>
void Erase(Container* container, std::function<bool(const typename Container::value_type&)> functor);
template<class Container>
void EraseLess(Container* container, const typename Container::value_type& threshold);
template<class Container>
void EraseGreater(Container* container, const typename Container::value_type& threshold);
template<class Container>
void EraseNotLess(Container* container, const typename Container::value_type& threshold);
template<class Container>
void EraseNotGreater(Container* container, const typename Container::value_type& threshold);
template<class Container>
void EraseMapValueLess(Container* container, const typename Container::mapped_type& threshold);
template<class Container>
void EraseMapValueGreater(Container* container, const typename Container::mapped_type& threshold);
template<class Container>
void EraseMapValueNotLess(Container* container, const typename Container::mapped_type& threshold);
template<class Container>
void EraseMapValueNotGreater(Container* container, const typename Container::mapped_type& threshold);
template<class Container0, class Container1>
void EraseDifference(Container0* container0, const Container1& container1);
template<class Container0, class Container1>
void Difference(Container0* container0, const Container1& container1);
template<class Container0, class Container1>
Container0 Difference(const Container0& container0, const Container1& container1);
template<class Container0, class Container1>
void Intersection(Container0* container0, const Container1& container1);
template<class Container0, class Container1>
Container1 Intersection(const Container0& container0, const Container1& container1);
template<class Container>
void Distinct(Container* container);
template<class Container>
Container Distinct(const Container& container);
/* IMPLEMENTATION */
namespace ContainerEraser
{
template<class Container>
void EraseVector(Container* container, std::function<bool(const typename Container::value_type&)> functor)
{
container->erase(std::remove_if(container->begin(), container->end(), functor), container->end());
}
template<class Container>
void EraseMap(Container* container, std::function<bool(const typename Container::value_type&)> functor)
{
for (auto iter = container->begin(); iter != container->end();)
{
if (functor(*iter)) {
container->erase(iter++);
} else {
++iter;
}
}
}
template<int ContainerType>
struct Eraser
{
template<class Container>
static void Erase(Container* container, std::function<bool(const typename Container::value_type&)> functor);
};
template<>
struct Eraser<Tools::UNARY>
{
template<class Container>
static void Erase(Container* container, std::function<bool(const typename Container::value_type&)> functor)
{
EraseVector(container, functor);
}
};
template<>
struct Eraser<Tools::COUPLING>
{
template<class Container>
static void Erase(Container* container, std::function<bool(const typename Container::value_type&)> functor)
{
EraseMap(container, functor);
}
};
}
namespace EraserDifference
{
template<class Container0, class Container1>
void EraseDifferenceVectorVector(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return std::find(container1.begin(), container1.end(), val) != container1.end();
};
Tools::Erase(container0, functor);
}
template<class Container0, class Container1>
void EraseDifferenceVectorMap(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return container1.find(val) != container1.end();
};
Tools::Erase(container0, functor);
}
template<class Container0, class Container1>
void EraseDifferenceMapMap(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return container1.find(val.first) != container1.end();
};
Tools::Erase(container0, functor);
}
template<class Container0, class Container1>
void EraseDifferenceMapVector(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return std::find(container1.begin(), container1.end(), val.first) != container1.end();
};
Tools::Erase(container0, functor);
}
template<int ContainerType0, int ContainerType1>
struct Eraser
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1);
};
template<>
struct Eraser<Tools::UNARY, Tools::UNARY>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseDifferenceVectorVector(container0, container1);
}
};
template<>
struct Eraser<Tools::UNARY, Tools::COUPLING>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseDifferenceVectorMap(container0, container1);
}
};
template<>
struct Eraser<Tools::COUPLING, Tools::UNARY>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseDifferenceMapVector(container0, container1);
}
};
template<>
struct Eraser<Tools::COUPLING, Tools::COUPLING>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseDifferenceMapMap(container0, container1);
}
};
}
namespace EraserIntersection
{
template<class Container0, class Container1>
void EraseInersectionVectorVector(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return std::find(container1.begin(), container1.end(), val) == container1.end();
};
Tools::Erase(container0, functor);
}
template<class Container0, class Container1>
void EraseInersectionVectorMap(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return container1.find(val) == container1.end();
};
Tools::Erase(container0, functor);
}
template<class Container0, class Container1>
void EraseInersectionMapMap(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return container1.find(val.first) == container1.end();
};
Tools::Erase(container0, functor);
}
template<class Container0, class Container1>
void EraseInersectionMapVector(Container0* container0, const Container1& container1)
{
std::function<bool(const typename Container0::value_type&)> functor =
[&](const typename Container0::value_type& val)
{
return std::find(container1.begin(), container1.end(), val.first) == container1.end();
};
Tools::Erase(container0, functor);
}
template<int ContainerType0, int ContainerType1>
struct Eraser
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1);
};
template<>
struct Eraser<Tools::UNARY, Tools::UNARY>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseInersectionVectorVector(container0, container1);
}
};
template<>
struct Eraser<Tools::UNARY, Tools::COUPLING>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseInersectionVectorMap(container0, container1);
}
};
template<>
struct Eraser<Tools::COUPLING, Tools::UNARY>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseInersectionMapVector(container0, container1);
}
};
template<>
struct Eraser<Tools::COUPLING, Tools::COUPLING>
{
template<class Container0, class Container1>
static void Erase(Container0* container0, const Container1& container1)
{
EraseInersectionMapMap(container0, container1);
}
};
}
template<class Container>
void Erase(Container* container, std::function<bool(const typename Container::value_type&)> functor)
{
ContainerEraser::Eraser<Tools::TypeIdentifier<Container>::containerType>::Erase(container, functor);
}
template<class Container>
void EraseLess(Container* container, const typename Container::value_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val < threshold; });
}
template<class Container>
void EraseGreater(Container* container, const typename Container::value_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val > threshold; });
}
template<class Container>
void EraseNotLess(Container* container, const typename Container::value_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val >= threshold; });
}
template<class Container>
void EraseNotGreater(Container* container, const typename Container::value_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val <= threshold; });
}
template<class Container>
void EraseMapValueLess(Container* container, const typename Container::mapped_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val.second < threshold; });
}
template<class Container>
void EraseMapValueGreater(Container* container, const typename Container::mapped_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val.second > threshold; });
}
template<class Container>
void EraseMapValueNotLess(Container* container, const typename Container::mapped_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val.second >= threshold; });
}
template<class Container>
void EraseMapValueNotGreater(Container* container, const typename Container::mapped_type& threshold)
{
Erase<Container>(container, [&](const typename Container::value_type& val) { return val.second <= threshold; });
}
template<class Container0, class Container1>
void Difference(Container0* container0, const Container1& container1)
{
EraserDifference::Eraser<
Tools::TypeIdentifier<Container0>::containerType
, Tools::TypeIdentifier<Container1>::containerType
>::Erase(container0, container1);
}
template<class Container0, class Container1>
void Intersection(Container0* container0, const Container1& container1)
{
EraserIntersection::Eraser<
Tools::TypeIdentifier<Container0>::containerType
, Tools::TypeIdentifier<Container1>::containerType
>::Erase(container0, container1);
}
template<class Container0, class Container1>
Container0 Difference(const Container0& container0, const Container1& container1)
{
Container0 copy0 = container0;
Tools::Difference(©0, container1);
return copy0;
}
template<class Container0, class Container1>
Container1 Intersection(const Container0& container0, const Container1& container1)
{
Container0 copy0 = container0;
Tools::Intersection(©0, container1);
return copy0;
}
template<class Container>
void Distinct(Container* container)
{
typedef typename Container::value_type T;
vector<T> toSort(container->begin(), container->end());
std::sort(toSort.begin(), toSort.end());
vector<T> distinct(toSort.size());
typename vector<T>::iterator end = std::unique_copy(
toSort.begin(), toSort.end(), distinct.begin());
*container = Container(distinct.begin(), end);
}
template<class Container>
Container Distinct(const Container& container)
{
Container distinct = container;
Distinct(&distinct);
return distinct;
}
}
#endif // CONTAINER_ERASER
| 33.051454 | 116 | 0.687898 |
9236f58e3251de75e9945002941725543a4e6fac | 110 | c | C | cil/test/small1/extern1.c | petr-muller/abductor | 4c9199378e847e22660daab5e5843805d4035d0a | [
"Intel",
"Unlicense"
] | 266 | 2015-01-23T16:06:52.000Z | 2022-03-17T19:49:34.000Z | cil/test/small1/extern1.c | petr-muller/abductor | 4c9199378e847e22660daab5e5843805d4035d0a | [
"Intel",
"Unlicense"
] | 93 | 2015-07-31T21:38:04.000Z | 2022-03-24T03:21:34.000Z | cil/test/small1/extern1.c | petr-muller/abductor | 4c9199378e847e22660daab5e5843805d4035d0a | [
"Intel",
"Unlicense"
] | 73 | 2015-01-11T17:06:17.000Z | 2022-02-21T06:20:37.000Z | #include "testharness.h"
// CIL seems to drop this on the floor!!!
extern int main(int argc) {
return 0;
}
| 15.714286 | 41 | 0.672727 |
925c16325cb07b3b4713cb5f2ed2f7db3e214f35 | 434 | h | C | src/controller.h | Xheis/Project | ac809773ad0c8d2c1027c7a55eaf8a8fcd4cd9ff | [
"MIT"
] | null | null | null | src/controller.h | Xheis/Project | ac809773ad0c8d2c1027c7a55eaf8a8fcd4cd9ff | [
"MIT"
] | null | null | null | src/controller.h | Xheis/Project | ac809773ad0c8d2c1027c7a55eaf8a8fcd4cd9ff | [
"MIT"
] | null | null | null | #ifndef CONTROLLER_H
#define CONTROLLER_H
enum {
CTRL_N_INPUT = 3, // number of reference signals and plant states : REF*,v,Theta
CTRL_N_STATE = 1, // number of controller states : 1, just cause
CTRL_N_OUTPUT = 1, // number of controller outputs : V'
};
void ctrl_init(void);
void ctrl_set_state(const float state[CTRL_N_STATE]);
float * ctrl_get_state(void);
float * ctrl_run(const float input[CTRL_N_INPUT]);
#endif | 28.933333 | 85 | 0.730415 |
fac71bed98faf76545a5cc42c711d6e916e50a9f | 2,397 | h | C | SignatureVC/Internal/UIBezierPath+WeightedPoint.h | pp50kg/SignatureVC | b5a431859ac6fa706d6211d4caa25cfa587a6019 | [
"MIT"
] | null | null | null | SignatureVC/Internal/UIBezierPath+WeightedPoint.h | pp50kg/SignatureVC | b5a431859ac6fa706d6211d4caa25cfa587a6019 | [
"MIT"
] | null | null | null | SignatureVC/Internal/UIBezierPath+WeightedPoint.h | pp50kg/SignatureVC | b5a431859ac6fa706d6211d4caa25cfa587a6019 | [
"MIT"
] | null | null | null | //
// UIBezierPath+WeightedPoint.h
// SignatureObjCDemo
//
// Created by 金融研發一部-許祐禎 on 2020/1/15.
// Copyright © 2020 金融研發一部-許祐禎. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
A struct that defines a point that has an associated weight
*/
typedef struct
{
CGPoint point;
CGFloat weight;
} WeightedPoint;
/**
Provides a set of class methods for generating @c UIBezierPaths between weighted points. It provides a dot for a single point, up to a full bezier curve for 4 points.
The bezierPaths generated are actually a shape that needs to be filled. This is how the weight varies gradually between each point rather than using the @c UIBezierPath @c thickness property that sets the thickness of a whole path.
*/
@interface UIBezierPath (WeightedPoint)
/**
Provides a dot with the given point.
@param pointA The co-ordinate for the dot's center.
@return A @c UIBezierPath for the dot.
*/
+ (UIBezierPath *)dotWithWeightedPoint:(WeightedPoint)pointA;
/**
Provides a straight line between the given points.
@param pointA @c WeightedPoint for the start of the line.
@param pointB The @c WeightedPoint for the end of the line.
@return A \c UIBezierPath shape (that should be filled) for the line.
*/
+ (UIBezierPath *)lineWithWeightedPointA:(WeightedPoint)pointA pointB:(WeightedPoint)pointB;
/**
Provides a quad curve between the given points.
@param pointA @c WeightedPoint for the start of the curve.
@param pointB The @c WeightedPoint for the middle of the curve.
@param pointC The @c WeightedPoint for the end of the curve.
@return A @c UIBezierPath shape (that should be filled) for the curve.
*/
+ (UIBezierPath *)quadCurveWithWeightedPointA:(WeightedPoint)pointA pointB:(WeightedPoint)pointB pointC:(WeightedPoint)pointC;
/**
Provides a bezier curve between the given points.
@param pointA The @c WeightedPoint for the start of the curve.
@param pointB The @c WeightedPoint for the first control point of the curve.
@param pointC The @c WeightedPoint for the second control point of the curve.
@param pointD The @c WeightedPoint for the end of the curve.
@return A @c UIBezierPath shape (that should be filled) for the curve.
*/
+ (UIBezierPath *)bezierCurveWithWeightedPointA:(WeightedPoint)pointA pointB:(WeightedPoint)pointB pointC:(WeightedPoint)pointC pointD:(WeightedPoint)pointD;
@end
NS_ASSUME_NONNULL_END
| 35.776119 | 232 | 0.76554 |
7a1c0db7de05f044716c62365f5aaa86868aba68 | 1,343 | h | C | js/cpp/generated/EthereumAddress.h | IFWallet/wallet-core | 4ab8d2fac26530ffde6dbd56a5b4f1e96c111191 | [
"MIT"
] | 7 | 2019-05-29T02:56:59.000Z | 2021-08-31T16:58:29.000Z | js/cpp/generated/EthereumAddress.h | moneto-dev/wallet-core | 0bfd312f868f02fe51cd2672e2397fd98d707db7 | [
"MIT"
] | null | null | null | js/cpp/generated/EthereumAddress.h | moneto-dev/wallet-core | 0bfd312f868f02fe51cd2672e2397fd98d707db7 | [
"MIT"
] | 5 | 2020-03-07T14:54:39.000Z | 2021-09-25T03:27:31.000Z | // Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
//
// This is a GENERATED FILE, changes made here WILL BE LOST.
//
#ifndef NAPI_TW_ETHEREUMADDRESS_H
#define NAPI_TW_ETHEREUMADDRESS_H
#include <TrustWalletCore/TWEthereumAddress.h>
#include <TrustWalletCore/TWPublicKey.h>
#include <TrustWalletCore/TWBase.h>
#include "../TWNapi.h"
using namespace Napi;
External<TWEthereumAddress> Js_wallet_core_napi_EthereumAddress_createWithString(const CallbackInfo& info);
External<TWEthereumAddress> Js_wallet_core_napi_EthereumAddress_createWithKeyHash(const CallbackInfo& info);
External<TWEthereumAddress> Js_wallet_core_napi_EthereumAddress_createWithPublicKey(const CallbackInfo& info);
void Js_wallet_core_napi_EthereumAddress_delete(const CallbackInfo& info);
Boolean Js_wallet_core_napi_EthereumAddress_equals(const CallbackInfo& info);
Boolean Js_wallet_core_napi_EthereumAddress_isValidString(const CallbackInfo& info);
String Js_wallet_core_napi_EthereumAddress_description(const CallbackInfo& info);
Uint8Array Js_wallet_core_napi_EthereumAddress_keyHash(const CallbackInfo& info);
#endif // NAPI_TW_ETHEREUMADDRESS_H | 35.342105 | 110 | 0.8414 |
ffb85f2b0f214e85bd8616b34d81363d32edad8c | 1,395 | h | C | src/vlistue.h | linails/vnote | 97810731db97292f474951c3450aac150acef0bc | [
"MIT"
] | 1 | 2019-02-19T12:01:23.000Z | 2019-02-19T12:01:23.000Z | src/vlistue.h | linails/vnote | 97810731db97292f474951c3450aac150acef0bc | [
"MIT"
] | 1 | 2022-01-22T13:10:44.000Z | 2022-01-22T13:10:44.000Z | src/vlistue.h | linails/vnote | 97810731db97292f474951c3450aac150acef0bc | [
"MIT"
] | 1 | 2021-07-27T14:58:28.000Z | 2021-07-27T14:58:28.000Z | #ifndef VLISTUE_H
#define VLISTUE_H
#include "iuniversalentry.h"
#include <QWidget>
#include <QIcon>
#include <functional>
#include <QSharedPointer>
#include "vsearchconfig.h"
class VListWidgetDoubleRows;
class QListWidgetItem;
class QLabel;
class VUETitleContentPanel;
class VListUE : public IUniversalEntry
{
Q_OBJECT
public:
enum ID
{
// List and search the history.
History = 0
};
explicit VListUE(QObject *p_parent = nullptr);
QString description(int p_id) const Q_DECL_OVERRIDE;
QWidget *widget(int p_id) Q_DECL_OVERRIDE;
void processCommand(int p_id, const QString &p_cmd) Q_DECL_OVERRIDE;
void clear(int p_id) Q_DECL_OVERRIDE;
void selectNextItem(int p_id, bool p_forward) Q_DECL_OVERRIDE;
void activate(int p_id) Q_DECL_OVERRIDE;
void sort(int p_id) Q_DECL_OVERRIDE;
protected:
void init() Q_DECL_OVERRIDE;
private slots:
void activateItem(QListWidgetItem *p_item);
private:
void addResultItem(const QSharedPointer<VSearchResultItem> &p_item);
const QSharedPointer<VSearchResultItem> &itemResultData(const QListWidgetItem *p_item) const;
void listHistory(const QString &p_cmd);
QVector<QSharedPointer<VSearchResultItem> > m_data;
QIcon m_noteIcon;
QIcon m_folderIcon;
VListWidgetDoubleRows *m_listWidget;
VUETitleContentPanel *m_panel;
};
#endif // VLISTUE_H
| 20.514706 | 97 | 0.742652 |
947b7084722a8b7545785a341bd751c6f6c8a296 | 23,315 | h | C | src/dlib/image_transforms/interpolation.h | cpearce/HARM | 1e629099bbaa0203b19fe9007a71d9ab9c938be0 | [
"Apache-2.0"
] | 1 | 2016-10-11T18:37:52.000Z | 2016-10-11T18:37:52.000Z | src/dlib/image_transforms/interpolation.h | wsgan001/HARM | 1e629099bbaa0203b19fe9007a71d9ab9c938be0 | [
"Apache-2.0"
] | 2 | 2017-03-27T22:58:45.000Z | 2017-03-28T04:46:52.000Z | src/dlib/image_transforms/interpolation.h | wsgan001/HARM | 1e629099bbaa0203b19fe9007a71d9ab9c938be0 | [
"Apache-2.0"
] | 4 | 2016-04-19T06:15:01.000Z | 2020-01-02T11:11:57.000Z | // Copyright (C) 2012 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_INTERPOlATION__
#define DLIB_INTERPOlATION__
#include "interpolation_abstract.h"
#include "../pixel.h"
#include "../matrix.h"
#include "assign_image.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class interpolate_nearest_neighbor
{
public:
template <typename image_type>
bool operator() (
const image_type& img,
const dlib::point& p,
typename image_type::type& result
) const
{
if (get_rect(img).contains(p))
{
result = img[p.y()][p.x()];
return true;
}
else
{
return false;
}
}
};
// ----------------------------------------------------------------------------------------
class interpolate_bilinear
{
template <typename T>
struct is_rgb_image
{
const static bool value = pixel_traits<typename T::type>::rgb;
};
public:
template <typename T, typename image_type>
typename disable_if<is_rgb_image<image_type>,bool>::type operator() (
const image_type& img,
const dlib::vector<T,2>& p,
typename image_type::type& result
) const
{
COMPILE_TIME_ASSERT(pixel_traits<typename image_type::type>::has_alpha == false);
const long top = static_cast<long>(std::floor(p.y()));
const long bottom = static_cast<long>(std::ceil (p.y()));
const long left = static_cast<long>(std::floor(p.x()));
const long right = static_cast<long>(std::ceil (p.x()));
// if the interpolation goes outside img
if (!get_rect(img).contains(rectangle(left,top,right,bottom)))
return false;
const double lr_frac = p.x() - std::floor(p.x());
const double tb_frac = p.y() - std::floor(p.y());
double tl = 0, tr = 0, bl = 0, br = 0;
assign_pixel(tl, img[top][left]);
assign_pixel(tr, img[top][right]);
assign_pixel(bl, img[bottom][left]);
assign_pixel(br, img[bottom][right]);
double temp = (1-tb_frac)*((1-lr_frac)*tl + lr_frac*tr) +
tb_frac*((1-lr_frac)*bl + lr_frac*br);
assign_pixel(result, temp);
return true;
}
template <typename T, typename image_type>
typename enable_if<is_rgb_image<image_type>,bool>::type operator() (
const image_type& img,
const dlib::vector<T,2>& p,
typename image_type::type& result
) const
{
COMPILE_TIME_ASSERT(pixel_traits<typename image_type::type>::has_alpha == false);
const long top = static_cast<long>(std::floor(p.y()));
const long bottom = static_cast<long>(std::ceil (p.y()));
const long left = static_cast<long>(std::floor(p.x()));
const long right = static_cast<long>(std::ceil (p.x()));
// if the interpolation goes outside img
if (!get_rect(img).contains(rectangle(left,top,right,bottom)))
return false;
const double lr_frac = p.x() - std::floor(p.x());
const double tb_frac = p.y() - std::floor(p.y());
double tl, tr, bl, br;
tl = img[top][left].red;
tr = img[top][right].red;
bl = img[bottom][left].red;
br = img[bottom][right].red;
const double red = (1-tb_frac)*((1-lr_frac)*tl + lr_frac*tr) +
tb_frac*((1-lr_frac)*bl + lr_frac*br);
tl = img[top][left].green;
tr = img[top][right].green;
bl = img[bottom][left].green;
br = img[bottom][right].green;
const double green = (1-tb_frac)*((1-lr_frac)*tl + lr_frac*tr) +
tb_frac*((1-lr_frac)*bl + lr_frac*br);
tl = img[top][left].blue;
tr = img[top][right].blue;
bl = img[bottom][left].blue;
br = img[bottom][right].blue;
const double blue = (1-tb_frac)*((1-lr_frac)*tl + lr_frac*tr) +
tb_frac*((1-lr_frac)*bl + lr_frac*br);
assign_pixel(result.red, red);
assign_pixel(result.green, green);
assign_pixel(result.blue, blue);
return true;
}
};
// ----------------------------------------------------------------------------------------
class interpolate_quadratic
{
template <typename T>
struct is_rgb_image
{
const static bool value = pixel_traits<typename T::type>::rgb;
};
public:
template <typename T, typename image_type>
typename disable_if<is_rgb_image<image_type>,bool>::type operator() (
const image_type& img,
const dlib::vector<T,2>& p,
typename image_type::type& result
) const
{
COMPILE_TIME_ASSERT(pixel_traits<typename image_type::type>::has_alpha == false);
const point pp(p);
// if the interpolation goes outside img
if (!get_rect(img).contains(grow_rect(pp,1)))
return false;
const long r = pp.y();
const long c = pp.x();
const double temp = interpolate(p-pp,
img[r-1][c-1],
img[r-1][c ],
img[r-1][c+1],
img[r ][c-1],
img[r ][c ],
img[r ][c+1],
img[r+1][c-1],
img[r+1][c ],
img[r+1][c+1]);
assign_pixel(result, temp);
return true;
}
template <typename T, typename image_type>
typename enable_if<is_rgb_image<image_type>,bool>::type operator() (
const image_type& img,
const dlib::vector<T,2>& p,
typename image_type::type& result
) const
{
COMPILE_TIME_ASSERT(pixel_traits<typename image_type::type>::has_alpha == false);
const point pp(p);
// if the interpolation goes outside img
if (!get_rect(img).contains(grow_rect(pp,1)))
return false;
const long r = pp.y();
const long c = pp.x();
const double red = interpolate(p-pp,
img[r-1][c-1].red,
img[r-1][c ].red,
img[r-1][c+1].red,
img[r ][c-1].red,
img[r ][c ].red,
img[r ][c+1].red,
img[r+1][c-1].red,
img[r+1][c ].red,
img[r+1][c+1].red);
const double green = interpolate(p-pp,
img[r-1][c-1].green,
img[r-1][c ].green,
img[r-1][c+1].green,
img[r ][c-1].green,
img[r ][c ].green,
img[r ][c+1].green,
img[r+1][c-1].green,
img[r+1][c ].green,
img[r+1][c+1].green);
const double blue = interpolate(p-pp,
img[r-1][c-1].blue,
img[r-1][c ].blue,
img[r-1][c+1].blue,
img[r ][c-1].blue,
img[r ][c ].blue,
img[r ][c+1].blue,
img[r+1][c-1].blue,
img[r+1][c ].blue,
img[r+1][c+1].blue);
assign_pixel(result.red, red);
assign_pixel(result.green, green);
assign_pixel(result.blue, blue);
return true;
}
private:
/* tl tm tr
ml mm mr
bl bm br
*/
// The above is the pixel layout in our little 3x3 neighborhood. interpolate() will
// fit a quadratic to these 9 pixels and then use that quadratic to find the interpolated
// value at point p.
inline double interpolate(
const dlib::vector<double,2>& p,
double tl, double tm, double tr,
double ml, double mm, double mr,
double bl, double bm, double br
) const
{
matrix<double,6,1> w;
// x
w(0) = (tr + mr + br - tl - ml - bl)*0.16666666666;
// y
w(1) = (bl + bm + br - tl - tm - tr)*0.16666666666;
// x^2
w(2) = (tl + tr + ml + mr + bl + br)*0.16666666666 - (tm + mm + bm)*0.333333333;
// x*y
w(3) = (tl - tr - bl + br)*0.25;
// y^2
w(4) = (tl + tm + tr + bl + bm + br)*0.16666666666 - (ml + mm + mr)*0.333333333;
// 1 (constant term)
w(5) = (tm + ml + mr + bm)*0.222222222 - (tl + tr + bl + br)*0.11111111 + (mm)*0.55555556;
const double x = p.x();
const double y = p.y();
matrix<double,6,1> z;
z = x, y, x*x, x*y, y*y, 1.0;
return dot(w,z);
}
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class black_background
{
public:
template <typename pixel_type>
void operator() ( pixel_type& p) const { assign_pixel(p, 0); }
};
class white_background
{
public:
template <typename pixel_type>
void operator() ( pixel_type& p) const { assign_pixel(p, 255); }
};
class no_background
{
public:
template <typename pixel_type>
void operator() ( pixel_type& ) const { }
};
// ----------------------------------------------------------------------------------------
template <
typename image_type,
typename interpolation_type,
typename point_mapping_type,
typename background_type
>
void transform_image (
const image_type& in_img,
image_type& out_img,
const interpolation_type& interp,
const point_mapping_type& map_point,
const background_type& set_background,
const rectangle& area
)
{
// make sure requires clause is not broken
DLIB_ASSERT( get_rect(out_img).contains(area) == true &&
is_same_object(in_img, out_img) == false ,
"\t void transform_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t get_rect(out_img).contains(area): " << get_rect(out_img).contains(area)
<< "\n\t get_rect(out_img): " << get_rect(out_img)
<< "\n\t area: " << area
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
for (long r = area.top(); r <= area.bottom(); ++r)
{
for (long c = area.left(); c <= area.right(); ++c)
{
if (!interp(in_img, map_point(dlib::vector<double,2>(c,r)), out_img[r][c]))
set_background(out_img[r][c]);
}
}
}
// ----------------------------------------------------------------------------------------
template <
typename image_type,
typename interpolation_type,
typename point_mapping_type,
typename background_type
>
void transform_image (
const image_type& in_img,
image_type& out_img,
const interpolation_type& interp,
const point_mapping_type& map_point,
const background_type& set_background
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void transform_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
transform_image(in_img, out_img, interp, map_point, set_background, get_rect(out_img));
}
// ----------------------------------------------------------------------------------------
template <
typename image_type,
typename interpolation_type,
typename point_mapping_type
>
void transform_image (
const image_type& in_img,
image_type& out_img,
const interpolation_type& interp,
const point_mapping_type& map_point
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void transform_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
transform_image(in_img, out_img, interp, map_point, black_background(), get_rect(out_img));
}
// ----------------------------------------------------------------------------------------
template <
typename image_type,
typename interpolation_type
>
void rotate_image (
const image_type& in_img,
image_type& out_img,
double angle,
const interpolation_type& interp
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void rotate_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
const rectangle rimg = get_rect(in_img);
// figure out bounding box for rotated rectangle
rectangle rect;
rect += rotate_point(center(rimg), rimg.tl_corner(), -angle);
rect += rotate_point(center(rimg), rimg.tr_corner(), -angle);
rect += rotate_point(center(rimg), rimg.bl_corner(), -angle);
rect += rotate_point(center(rimg), rimg.br_corner(), -angle);
out_img.set_size(rect.height(), rect.width());
const matrix<double,2,2> R = rotation_matrix(angle);
transform_image(in_img, out_img, interp,
point_transform_affine(R, -R*dcenter(get_rect(out_img)) + dcenter(rimg)));
}
// ----------------------------------------------------------------------------------------
template <
typename image_type
>
void rotate_image (
const image_type& in_img,
image_type& out_img,
double angle
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void rotate_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
rotate_image(in_img, out_img, angle, interpolate_quadratic());
}
// ----------------------------------------------------------------------------------------
namespace impl
{
class helper_resize_image
{
public:
helper_resize_image(
double x_scale_,
double y_scale_
):
x_scale(x_scale_),
y_scale(y_scale_)
{}
dlib::vector<double,2> operator() (
const dlib::vector<double,2>& p
) const
{
return dlib::vector<double,2>(p.x()*x_scale, p.y()*y_scale);
}
private:
const double x_scale;
const double y_scale;
};
}
template <
typename image_type,
typename interpolation_type
>
void resize_image (
const image_type& in_img,
image_type& out_img,
const interpolation_type& interp
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void resize_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
const double x_scale = (in_img.nc()-1)/(double)std::max<long>((out_img.nc()-1),1);
const double y_scale = (in_img.nr()-1)/(double)std::max<long>((out_img.nr()-1),1);
transform_image(in_img, out_img, interp,
dlib::impl::helper_resize_image(x_scale,y_scale));
}
// ----------------------------------------------------------------------------------------
template <
typename image_type
>
void resize_image (
const image_type& in_img,
image_type& out_img
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void resize_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
resize_image(in_img, out_img, interpolate_quadratic());
}
// ----------------------------------------------------------------------------------------
template <
typename image_type
>
void flip_image_left_right (
const image_type& in_img,
image_type& out_img
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void rotate_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
assign_image(out_img, fliplr(array_to_matrix(in_img)));
}
// ----------------------------------------------------------------------------------------
template <
typename image_type
>
void flip_image_up_down (
const image_type& in_img,
image_type& out_img
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void rotate_image()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
assign_image(out_img, flipud(array_to_matrix(in_img)));
}
// ----------------------------------------------------------------------------------------
namespace impl
{
class helper_pyramid_up
{
public:
helper_pyramid_up(
double x_scale_,
double y_scale_,
const dlib::vector<double,2> offset_
):
x_scale(x_scale_),
y_scale(y_scale_),
offset(offset_)
{}
dlib::vector<double,2> operator() (
const dlib::vector<double,2>& p
) const
{
return dlib::vector<double,2>((p.x()-offset.x())*x_scale,
(p.y()-offset.y())*y_scale);
}
private:
const double x_scale;
const double y_scale;
const dlib::vector<double,2> offset;
};
}
template <
typename image_type,
typename pyramid_type,
typename interpolation_type
>
void pyramid_up (
const image_type& in_img,
image_type& out_img,
const pyramid_type& pyr,
unsigned int levels,
const interpolation_type& interp
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void pyramid_up()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
if (in_img.size() == 0)
{
out_img.clear();
return;
}
if (levels == 0)
{
assign_image(out_img, in_img);
return;
}
rectangle rect = get_rect(in_img);
rectangle uprect = pyr.rect_up(rect,levels);
if (uprect.is_empty())
{
out_img.clear();
return;
}
out_img.set_size(uprect.bottom()+1, uprect.right()+1);
const double x_scale = (rect.width() -1)/(double)std::max<long>(1,(uprect.width() -1));
const double y_scale = (rect.height()-1)/(double)std::max<long>(1,(uprect.height()-1));
transform_image(in_img, out_img, interp,
dlib::impl::helper_pyramid_up(x_scale,y_scale, uprect.tl_corner()));
}
// ----------------------------------------------------------------------------------------
template <
typename image_type,
typename pyramid_type
>
void pyramid_up (
const image_type& in_img,
image_type& out_img,
const pyramid_type& pyr,
unsigned int levels = 1
)
{
// make sure requires clause is not broken
DLIB_ASSERT( is_same_object(in_img, out_img) == false ,
"\t void pyramid_up()"
<< "\n\t Invalid inputs were given to this function."
<< "\n\t is_same_object(in_img, out_img): " << is_same_object(in_img, out_img)
);
pyramid_up(in_img, out_img, pyr, levels, interpolate_quadratic());
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_INTERPOlATION__
| 34.540741 | 103 | 0.454729 |
3d15632302e75e8e2c64ea416f5af553c454e25a | 5,014 | h | C | ulibTests/UMTestHTTP.h | andreasfink/ulib | 04242ae1731fe17c2989d497076576487ee346aa | [
"MIT"
] | 3 | 2016-12-25T12:21:25.000Z | 2020-06-18T11:45:44.000Z | ulibTests/UMTestHTTP.h | andreasfink/ulib | 04242ae1731fe17c2989d497076576487ee346aa | [
"MIT"
] | 2 | 2017-03-01T17:25:34.000Z | 2021-08-18T13:30:07.000Z | ulibTests/UMTestHTTP.h | andreasfink/ulib | 04242ae1731fe17c2989d497076576487ee346aa | [
"MIT"
] | 2 | 2016-11-04T07:40:19.000Z | 2017-04-12T03:50:07.000Z | //
// UMTestHTTP.h
// ulib
//
// Created by Aarno Syvänen on 25.04.12.
// // Copyright © 2017 Andreas Fink (andreas@fink.org). All rights reserved.
//
#import <Foundation/Foundation.h>
#import "UniversalHTTP.h"
#import "UniversalSocket.h"
#ifdef HAVE_OPENSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif
@interface TestCounter : NSObject
{
NSLock *lock;
unsigned long n;
}
@property(readwrite,strong) NSLock *lock;
/* create a new counter object.*/
- (TestCounter *)init;
/* destroy it */
/* return the current value of the counter and increase counter by one */
- (unsigned long)increase;
/* return the current value of the counter and increase counter by value */
- (unsigned long)increaseWith:(unsigned long)value;
/* return the current value of the counter */
-(unsigned long)value;
/* return the current value of the counter and decrease counter by one */
- (unsigned long)decrease;
/* return the current value of the counter and set it to the supplied value */
- (unsigned long)setTo:(unsigned long)value;
@end
@interface TestMutableArray : UMObject
{
NSMutableArray *array;
NSCondition *nonempty;
NSLock *singleOperationLock;
NSLock *permanentLock;
long numProducers;
long numConsumers;
}
@property(readwrite,strong) NSMutableArray *array;
@property(readwrite,strong) NSCondition *nonempty;
@property(readwrite,strong) NSLock *singleOperationLock;
@property(readwrite,strong) NSLock *permanentLock;
@property(readwrite,assign) long numProducers;
@property(readwrite,assign) long numConsumers;
- (TestMutableArray *) init;
- (id) consume;
- (id)consumeUnlocked;
- (void) removeProducer;
- (void)addObject:(id)item;
- (void)addObjectUnlocked:(id)item;
- (NSUInteger)count;
- (id)objectAtIndex:(NSUInteger)index;
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
- (NSString *)description;
@end
@interface UMHTTPCaller : TestMutableArray
{
UMHTTPMethod method;
NSString *subsection;
NSString *section;
NSString *name;
}
@property(readwrite,assign) UMHTTPMethod method;
@property(readwrite,strong) NSString *subsection;
@property(readwrite,strong) NSString *section;
@property(readwrite,strong) NSString *name;
- (UMHTTPCaller *)init;
- (NSString *)subsection;
- (void)addProducer;
- (void) addLogFile:(NSString *)logFile withSection:(NSString *)type withSubsection:(NSString *)ss withName:(NSString *)n;
/*
* Signal to a caller (presumably waiting receiveResultWithCaller) that
* we're entering shutdown phase. This will make receiveResultWithCaller
* no longer block if the queue is empty.
*/
- (void)signalShutdown;
@end
@class UMSocket;
/*
* Pool of open, but unused connections to servers or proxies. Key is
* "servername:port", value is NSMutableArray of UMSocket objects.
*/
@interface UMConnPool : UMObject
{
NSMutableDictionary *connPool;
NSLock *connPoolLock;
}
@property(readwrite,strong) NSMutableDictionary *connPool;
@property(readwrite,strong) NSLock *connPoolLock;
- (UMConnPool *)init;
- (NSString *)keyWithRemoteHost:(NSString *)host withPort:(int) port enableSSL:(BOOL)ssl withCertificate:(NSString *)certfile withLocalHost:(NSString *)our_host;
- (UMSocket *) getSocketWith:(NSString *)host withPort:(int)port withSSL:(BOOL) ssl withCertificate:(NSString *)certkeyfile withLocalHost:(NSString *)ourHost;
- (void)checkSocket:(UMSocket *)sock withKey:(NSString *)data whenRunStatusIs:(BOOL)running andSockError:(BOOL)error andSockEOF:(BOOL)eof;
- (void)putSocket:(UMSocket *)conn withRemoteHost:(NSString *)host withPort:(int)port enableSSL:(int)ssl withCertificate:(NSString *)certfile withLocalHost:(NSString *)our_host;
@end
@interface UMHTTPRequest (UMTestRequest)
- (void)addBasicAuthWithUserName:(NSString *)username andPassword:(NSString *)password;
- (void)requestHeadersCombineWith:(NSMutableArray *)headers;
@end
/*
@interface NSMutableArray (HTTPHeader)
+ (BOOL)nameOf:(NSString *)header is:(NSString *)name;
- (long)removeAllWithName:(NSString *)name;
- (void)getHeaderAtIndex:(long)i withName:(NSString **)name andValue:(NSMutableString **)value;
- (NSString *)findFirstWithName:(NSString *)name;
- (int)readSomeHeadersFrom:(UMSocket *)sock;
- (void)addHeaderWithName:(NSString *)name andValue:(NSString *)value;
- (void)addBasicAuthWithUserName:(NSString *)username andPassword:(NSString *)password;
- (void)proxyAddAuthenticationWithUserName:(NSString *)username andPassword:(NSString *)password;
- (void)getContentType:(NSMutableString **)type andCharset:(NSMutableString **)charset;
@end
*/
@interface NSDictionary (HTTPHeader)
- (NSString *)logDescription;
- (NSMutableArray *) toArray;
@end
@interface TestSocket : UMSocket
{
BOOL useSsl;
// SSL *ssl;
// X509 *peer_certificate;
SSL_CTX *global_ssl_context;
SSL_CTX *global_server_ssl_context;
}
@property(readwrite,assign) BOOL useSsl;
- (TestSocket *)init;
- (void)close;
- (int)SSLSmartShutdown;
- (UMSocketError)initWithSSLWithCertKeyFile:(NSString *)certificate;
@end
| 28.327684 | 177 | 0.750698 |
32494790df655c09fcb29f6e5c53e9715ddc6560 | 513 | h | C | include/Nephilim/Network/SFML_TcpEnvironment.h | GrimshawA/Nephilim | 1e69df544078b55fdaf58a04db963e20094f27a9 | [
"Zlib"
] | 19 | 2015-12-19T11:15:57.000Z | 2022-03-09T11:22:11.000Z | include/Nephilim/Network/SFML_TcpEnvironment.h | DevilWithin/Nephilim | 1e69df544078b55fdaf58a04db963e20094f27a9 | [
"Zlib"
] | 1 | 2017-05-17T09:31:10.000Z | 2017-05-19T17:01:31.000Z | include/Nephilim/Network/SFML_TcpEnvironment.h | GrimshawA/Nephilim | 1e69df544078b55fdaf58a04db963e20094f27a9 | [
"Zlib"
] | 3 | 2015-12-14T17:40:26.000Z | 2021-02-25T00:42:42.000Z | #ifndef NephilimSFML_TcpEnvironment_h__
#define NephilimSFML_TcpEnvironment_h__
#include <Nephilim/Platform.h>
#include <Nephilim/Network/NetworkingEnvironment.h>
#include <Nephilim/Network/TcpSocket.h>
NEPHILIM_NS_BEGIN
/**
\class SFML_TcpEnvironment
\brief This NetworkingEnvironment allows the game to use SFML tcp socket implementation to create connections
*/
class NEPHILIM_API SFML_TcpEnvironment : public NetworkingEnvironment
{
public:
};
NEPHILIM_NS_END
#endif // NephilimSFML_TcpEnvironment_h__
| 23.318182 | 110 | 0.836257 |
5cf8fcde894795f0adfa7930d52da1fbc6b559ed | 768 | h | C | E3_Lighting Box Blur/E3_Lighting/App1.h | giodestone/CMP301-Examples | 408aeafc3a2313866558e9267642baeae24ce51d | [
"MIT"
] | null | null | null | E3_Lighting Box Blur/E3_Lighting/App1.h | giodestone/CMP301-Examples | 408aeafc3a2313866558e9267642baeae24ce51d | [
"MIT"
] | null | null | null | E3_Lighting Box Blur/E3_Lighting/App1.h | giodestone/CMP301-Examples | 408aeafc3a2313866558e9267642baeae24ce51d | [
"MIT"
] | null | null | null | // Application.h
#ifndef _APP1_H
#define _APP1_H
// Includes
#include "DXF.h" // include dxframework
#include "LightShader.h"
#include "LightingDetails.h"
#include "BoxBlurShader.h"
#include <memory>
class App1 : public BaseApplication
{
public:
App1();
~App1();
void init(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight, Input* in, bool VSYNC, bool FULL_SCREEN);
bool frame();
protected:
bool render();
void renderMeshes();
void gui();
private:
LightShader* shader;
PlaneMesh* mesh;
SphereMesh* sphereMesh;
SphereMesh* lightDebugSphere;
Light* light;
std::unique_ptr<RenderTexture> renderTexture;
std::unique_ptr<OrthoMesh> orthoMesh;
std::unique_ptr<BoxBlurShader> boxBlurShader;
LightingDetails lightingDetails;
};
#endif | 18.285714 | 119 | 0.751302 |
cf059b6cb04540ffd56588ffcebe4e080e7f2d3d | 2,393 | h | C | searchlib/src/vespa/searchlib/docstore/compacter.h | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-06-02T13:28:29.000Z | 2020-06-02T13:28:29.000Z | searchlib/src/vespa/searchlib/docstore/compacter.h | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2021-03-31T22:24:20.000Z | 2021-03-31T22:24:20.000Z | searchlib/src/vespa/searchlib/docstore/compacter.h | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-09-03T11:39:52.000Z | 2020-09-03T11:39:52.000Z | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "filechunk.h"
#include "storebybucket.h"
#include <vespa/vespalib/data/memorydatastore.h>
namespace search { class LogDataStore; }
namespace search::docstore {
/**
* A simple write through implementation of the IWriteData interface.
*/
class Compacter : public IWriteData
{
public:
Compacter(LogDataStore & ds) : _ds(ds) { }
void write(LockGuard guard, uint32_t chunkId, uint32_t lid, const void *buffer, size_t sz) override;
void close() override { }
private:
LogDataStore & _ds;
};
/**
* This will split the incoming data into buckets.
* The buckets data will then be written out in bucket order.
* The buckets will be ordered, and the objects inside the buckets will be further ordered.
* All data are kept compressed to minimize memory usage.
**/
class BucketCompacter : public IWriteData, public StoreByBucket::IWrite
{
using CompressionConfig = vespalib::compression::CompressionConfig;
using Executor = vespalib::Executor;
public:
using FileId = FileChunk::FileId;
BucketCompacter(size_t maxSignificantBucketBits, const CompressionConfig & compression, LogDataStore & ds,
Executor & exeutor, const IBucketizer & bucketizer, FileId source, FileId destination);
void write(LockGuard guard, uint32_t chunkId, uint32_t lid, const void *buffer, size_t sz) override ;
void write(BucketId bucketId, uint32_t chunkId, uint32_t lid, const void *buffer, size_t sz) override;
void close() override;
private:
using GenerationHandler = vespalib::GenerationHandler;
FileId getDestinationId(const LockGuard & guard) const;
size_t _unSignificantBucketBits;
FileId _sourceFileId;
FileId _destinationFileId;
LogDataStore & _ds;
const IBucketizer & _bucketizer;
uint64_t _writeCount;
vespalib::duration _maxBucketGuardDuration;
vespalib::steady_time _lastSample;
vespalib::Lock _lock;
vespalib::MemoryDataStore _backingMemory;
std::vector<StoreByBucket> _tmpStore;
GenerationHandler::Guard _lidGuard;
GenerationHandler::Guard _bucketizerGuard;
vespalib::hash_map<uint64_t, uint32_t> _stat;
};
}
| 37.984127 | 118 | 0.707898 |
681e7dd6a48811f3e560f1ef9f0b62f29bd1059f | 31,116 | c | C | qmk_firmware/keyboards/sofle/keymaps/devdev/keymap.c | DanTupi/personal_setup | 911b4951e4d8b78d6ea8ca335229e2e970fda871 | [
"MIT"
] | null | null | null | qmk_firmware/keyboards/sofle/keymaps/devdev/keymap.c | DanTupi/personal_setup | 911b4951e4d8b78d6ea8ca335229e2e970fda871 | [
"MIT"
] | null | null | null | qmk_firmware/keyboards/sofle/keymaps/devdev/keymap.c | DanTupi/personal_setup | 911b4951e4d8b78d6ea8ca335229e2e970fda871 | [
"MIT"
] | null | null | null |
/* Copyright 2021 Dane Evans
*
* 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/>.
*/
// SOFLE RGB
#include <stdio.h>
#include QMK_KEYBOARD_H
#define INDICATOR_BRIGHTNESS 30
#define HSV_OVERRIDE_HELP(h, s, v, Override) h, s , Override
#define HSV_OVERRIDE(hsv, Override) HSV_OVERRIDE_HELP(hsv,Override)
// Light combinations
#define SET_INDICATORS(hsv) \
{0, 1, HSV_OVERRIDE_HELP(hsv, INDICATOR_BRIGHTNESS)}, \
{35+0, 1, hsv}
#define SET_UNDERGLOW(hsv) \
{1, 5, hsv}, \
{35+1, 5,hsv}
#define SET_NUMPAD(hsv) \
{35+15, 5, hsv},\
{35+22, 3, hsv},\
{35+27, 3, hsv}
#define SET_NUMROW(hsv) \
{10, 2, hsv}, \
{20, 2, hsv}, \
{30, 2, hsv}, \
{35+ 10, 2, hsv}, \
{35+ 20, 2, hsv}, \
{35+ 30, 2, hsv}
#define SET_INNER_COL(hsv) \
{33, 4, hsv}, \
{35+ 33, 4, hsv}
#define SET_OUTER_COL(hsv) \
{7, 4, hsv}, \
{35+ 7, 4, hsv}
#define SET_THUMB_CLUSTER(hsv) \
{25, 2, hsv}, \
{35+ 25, 2, hsv}
#define SET_LAYER_ID(hsv) \
{0, 1, HSV_OVERRIDE_HELP(hsv, INDICATOR_BRIGHTNESS)}, \
{35+0, 1, HSV_OVERRIDE_HELP(hsv, INDICATOR_BRIGHTNESS)}, \
{1, 5, hsv}, \
{35+1, 5, hsv}, \
{7, 4, hsv}, \
{35+ 7, 4, hsv}, \
{25, 2, hsv}, \
{35+ 25, 2, hsv}
enum sofle_layers {
_DEFAULTS = 0,
_QWERTY = 0,
_COLEMAK,
_COLEMAKDH,
_LOWER,
_RAISE,
_ADJUST,
_NUMPAD,
_SWITCH
};
enum custom_keycodes {
KC_QWERTY = SAFE_RANGE,
KC_COLEMAK,
KC_COLEMAKDH,
KC_LOWER,
KC_RAISE,
KC_ADJUST,
KC_D_MUTE
};
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
/*
* QWERTY
* ,-----------------------------------------. ,-----------------------------------------.
* | ESC | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 0 | ` |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | TAB | Q | W | E | R | T | | Y | U | I | O | P | Bspc |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* |LShift| A | S | D | F | G |-------. ,-------| H | J | K | L | ; | ' |
* |------+------+------+------+------+------| MUTE | |DISCORD|------+------+------+------+------+------|
* | LCTR | Z | X | C | V | B |-------| |-------| N | M | , | . | / |LShift|
* `-----------------------------------------/ / \ \-----------------------------------------'
* | Bspc | WIN |LOWER | Enter| /Space / \Enter \ |SPACE |RAISE | RCTR | RAlt |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
[_QWERTY] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
KC_ESC, KC_1, KC_2, KC_3, KC_4, KC_5, LT(_SWITCH,KC_6), KC_7, KC_8, KC_9, KC_0, KC_GRV,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
LT(_NUMPAD,KC_TAB),KC_Q,KC_W,KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_BSPC,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
KC_LSFT, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_LCTRL, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_MUTE, KC_D_MUTE,KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_LSFT,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_BSPC, KC_LGUI, KC_LOWER, KC_SPC, KC_ENT , KC_SPC, KC_ENT , KC_RAISE, KC_RCTRL, KC_RALT
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
/*
* COLEMAK
* ,-----------------------------------------. ,-----------------------------------------.
* | ESC | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 0 | ` |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | TAB | Q | W | F | P | G | | J | L | U | Y | ; | Bspc |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* |LShift| A | R | S | T | D |-------. ,-------| H | N | E | I | O | ' |
* |------+------+------+------+------+------| MUTE | |DISCORD|------+------+------+------+------+------|
* | LCTR | Z | X | C | V | B |-------| |-------| K | M | , | . | / |LShift|
* `-----------------------------------------/ / \ \-----------------------------------------'
* | Bspc | WIN |LOWER | Enter| /Space / \Enter \ |SPACE |RAISE | RCTR | RAlt |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
[_COLEMAK] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
KC_TRNS, KC_1, KC_2, KC_3, KC_4, KC_5, LT(_SWITCH,KC_6), KC_7, KC_8, KC_9, KC_0, KC_TRNS,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_Q, KC_W, KC_F, KC_P, KC_G, KC_J, KC_L, KC_U, KC_Y, KC_SCLN, KC_TRNS,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_A, KC_R, KC_S, KC_T, KC_D, KC_H, KC_N, KC_E, KC_I, KC_O, KC_TRNS,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_TRNS, KC_TRNS,KC_K, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_TRNS,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
/*
* COLEMAK-DH
* ,-----------------------------------------. ,-----------------------------------------.
* | ESC | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 0 | ` |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | TAB | Q | W | F | P | B | | J | L | U | Y | ; | Bspc |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* |LShift| A | R | S | T | G |-------. ,-------| M | N | E | I | O | ' |
* |------+------+------+------+------+------| MUTE | |DISCORD|------+------+------+------+------+------|
* | LCTR | Z | X | C | D | V |-------| |-------| K | H | , | . | / |LShift|
* `-----------------------------------------/ / \ \-----------------------------------------'
* | Bspc | WIN |LOWER | Enter| /Space / \Enter \ |SPACE |RAISE | RCTR | RAlt |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
[_COLEMAKDH] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
KC_TRNS, KC_1, KC_2, KC_3, KC_4, KC_5, LT(_SWITCH,KC_6), KC_7, KC_8, KC_9, KC_0, KC_TRNS,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_Q, KC_W, KC_F, KC_P, KC_B, KC_J, KC_L, KC_U, KC_Y, KC_SCLN, KC_TRNS,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_A, KC_R, KC_S, KC_T, KC_G, KC_M, KC_N, KC_E, KC_I, KC_O, KC_TRNS,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_Z, KC_X, KC_C, KC_D, KC_V, KC_TRNS, KC_TRNS,KC_K, KC_H, KC_COMM, KC_DOT, KC_SLSH, KC_TRNS,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
/* LOWER
* ,-----------------------------------------. ,-----------------------------------------.
* | trans| F1 | F2 | F3 | F4 | F5 | | F6 | F7 | F8 | F9 | F10 | F11 |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | ` | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 0 | F12 |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | trans| ! | @ | # | $ | % |-------. ,-------| ^ | & | * | ( | ) | | |
* |------+------+------+------+------+------| MUTE | | |------+------+------+------+------+------|
* | trans| = | - | + | { | } |-------| |-------| [ | ] | ; | : | \ | Shift|
* `-----------------------------------------/ / \ \-----------------------------------------'
* | Bspc | WIN |LOWER | Enter| /Space / \Enter \ |SPACE |RAISE | RCTR | RAlt |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
[_LOWER] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
_______, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_F11,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
KC_GRV, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_BSPC,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
_______, KC_NO, KC_NO, KC_NO, KC_WH_U, KC_PGUP, KC_LEFT, KC_DOWN, KC_UP, KC_RGHT, KC_NO, KC_DEL,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
_______, KC_NO, KC_NO, KC_NO, KC_WH_D, KC_PGDN,_______, _______,KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, _______,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
/* RAISE
* ,----------------------------------------. ,-----------------------------------------.
* | | | | | | | | | | | | | |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | Esc | Ins | Pscr | Menu | | | | | PWrd | Up | NWrd | DLine| Bspc |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | Tab | LAt | LCtl |LShift| | Caps |-------. ,-------| | Left | Down | Rigth| Del | Bspc |
* |------+------+------+------+------+------| MUTE | | |------+------+------+------+------+------|
* |Shift | Undo | Cut | Copy | Paste| |-------| |-------| | LStr | | LEnd | | Shift|
* `-----------------------------------------/ / \ \-----------------------------------------'
* | LGUI | LAlt | LCTR |LOWER | /Enter / \Space \ |RAISE | RCTR | RAlt | RGUI |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
[_RAISE] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
_______, _______ , _______ , _______ , _______ , _______, _______, _______ , _______, _______ , _______ ,_______,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
_______, KC_INS, KC_PSCR, KC_APP, XXXXXXX, XXXXXXX, KC_CIRC, KC_AMPR,KC_ASTR, KC_LPRN, KC_RPRN, KC_BSPC,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
_______, KC_LALT, KC_LCTL, KC_LSFT, XXXXXXX, KC_CAPS, KC_MINS, KC_EQL, KC_LCBR, KC_RCBR, KC_PIPE, KC_GRV,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
_______,KC_UNDO, KC_CUT, KC_COPY, KC_PASTE, XXXXXXX,_______, _______,KC_UNDS, KC_PLUS,KC_LBRC, KC_RBRC, KC_BSLS, KC_TILD,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
/* ADJUST
* ,-----------------------------------------. ,-----------------------------------------.
* | | | | | | | | | | | | | |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | RESET| | | | | | | | | | | | |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* |RGB_TOG|hue^ |sat ^ | bri ^| |COLEMAK|-------. ,-------|desk <| | |desk >| | |
* |------+------+------+------+------+------| MUTE | | |------+------+------+------+------+------|
* | mode | hue dn|sat d|bri dn| |QWERTY|-------| |-------| | PREV | PLAY | NEXT | | |
* `-----------------------------------------/ / \ \-----------------------------------------'
* | LGUI | LAlt | LCTR |LOWER | /Enter / \Space \ |RAISE | RCTR | RAlt | RGUI |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
[_ADJUST] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
EEP_RST, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
RESET, XXXXXXX,XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
RGB_TOG, RGB_HUI,RGB_SAI, RGB_VAI, KC_COLEMAKDH,KC_COLEMAK, C(G(KC_LEFT)),KC_NO,KC_NO,C(G(KC_RGHT)),XXXXXXX, XXXXXXX,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
RGB_MOD, RGB_HUD,RGB_SAD, RGB_VAD, XXXXXXX,KC_QWERTY,XXXXXXX, XXXXXXX, XXXXXXX, KC_MPRV, KC_MPLY, KC_MNXT, XXXXXXX, XXXXXXX,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
_______, _______, _______, _______, _______, _______, _______, _______, _______, _______
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
/* NUMPAD
* ,-----------------------------------------. ,-----------------------------------------.
* | trans| | | | | | | F6 | F7 | F8 | F9 | F10 | F11 |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | ` | | | | | | | | 7 | 8 | 9 | * | F12 |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | trans| | | | | |-------. ,-------| - | 4 | 5 | 6 | | | |
* |------+------+------+------+------+------| MUTE | | |------+------+------+------+------+------|
* | trans| | | | | |-------| |-------| + | 1 | 2 | 3 | \ | Shift|
* `-----------------------------------------/ / \ \-----------------------------------------'
* | Bspc | WIN |LOWER | Enter| /Space / \Enter \ |SPACE | 0 | . | RAlt |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
[_NUMPAD] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
_______, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX,XXXXXXX, XXXXXXX,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, KC_CIRC, KC_P7, KC_P8, KC_P9, KC_ASTR, _______,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, KC_MINS, KC_P4, KC_P5, KC_P6, KC_EQL, KC_PIPE,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX,_______, _______,KC_PLUS, KC_P1, KC_P2, KC_P3, KC_SLSH, _______,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
_______, OSM(MOD_MEH), _______, _______, _______, _______, _______, KC_P0, KC_PDOT, _______
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
/* SWITCH
* ,-----------------------------------------. ,-----------------------------------------.
* | cole | qwer | low |raise | adj |numpd | | | F7 | F8 | F9 | F10 | F11 |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | ` | | | | | | | | 7 | 8 | 9 | * | F12 |
* |------+------+------+------+------+------| |------+------+------+------+------+------|
* | trans| | | | | |-------. ,-------| - | 4 | 5 | 6 | | | |
* |------+------+------+------+------+------| MUTE | | |------+------+------+------+------+------|
* | trans| | | | | |-------| |-------| + | 1 | 2 | 3 | \ | Shift|
* `-----------------------------------------/ / \ \-----------------------------------------'
* | Bspc | WIN |LOWER | Enter| /Space / \Enter \ |SPACE | 0 | . | RAlt |
* | | | | |/ / \ \ | | | | |
* `----------------------------------' '------''---------------------------'
*/
// layer switcher
[_SWITCH] = LAYOUT(
//,------------------------------------------------. ,---------------------------------------------------.
_______, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX,XXXXXXX, XXXXXXX,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
TO(0), TO(1), TO(2), TO(3), TO(4), TO(5), KC_NO, TO(7), KC_NO, KC_NO, KC_NO, RESET,
//|------+-------+--------+--------+--------+------| |--------+-------+--------+--------+--------+---------|
KC_NO, KC_NO, KC_BRIU, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, EEP_RST,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_SYSTEM_SLEEP,KC_NO,KC_BRID,KC_NO,KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO,
//|------+-------+--------+--------+--------+------| === | | === |--------+-------+--------+--------+--------+---------|
KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO
// \--------+--------+--------+---------+-------| |--------+---------+--------+---------+-------/
),
};
#ifdef RGBLIGHT_ENABLE
char layer_state_str[70];
// Now define the array of layers. Later layers take precedence
// QWERTY,
// Light on inner column and underglow
const rgblight_segment_t PROGMEM layer_qwerty_lights[] = RGBLIGHT_LAYER_SEGMENTS(
SET_LAYER_ID(HSV_RED)
);
const rgblight_segment_t PROGMEM layer_colemakdh_lights[] = RGBLIGHT_LAYER_SEGMENTS(
SET_LAYER_ID(HSV_PINK)
);
// _NUM,
// Light on outer column and underglow
const rgblight_segment_t PROGMEM layer_num_lights[] = RGBLIGHT_LAYER_SEGMENTS(
SET_LAYER_ID(HSV_TEAL)
);
// _SYMBOL,
// Light on inner column and underglow
const rgblight_segment_t PROGMEM layer_symbol_lights[] = RGBLIGHT_LAYER_SEGMENTS(
SET_LAYER_ID(HSV_BLUE)
);
// _COMMAND,
// Light on inner column and underglow
const rgblight_segment_t PROGMEM layer_command_lights[] = RGBLIGHT_LAYER_SEGMENTS(
SET_LAYER_ID(HSV_PURPLE)
);
//_NUMPAD
const rgblight_segment_t PROGMEM layer_numpad_lights[] = RGBLIGHT_LAYER_SEGMENTS(
SET_INDICATORS(HSV_ORANGE),
SET_UNDERGLOW(HSV_ORANGE),
SET_NUMPAD(HSV_BLUE),
{7, 4, HSV_ORANGE},
{25, 2, HSV_ORANGE},
{35+6, 4, HSV_ORANGE},
{35+25, 2, HSV_ORANGE}
);
// _SWITCHER // light up top row
const rgblight_segment_t PROGMEM layer_switcher_lights[] = RGBLIGHT_LAYER_SEGMENTS(
SET_LAYER_ID(HSV_GREEN),
SET_NUMROW(HSV_GREEN)
);
const rgblight_segment_t* const PROGMEM my_rgb_layers[] = RGBLIGHT_LAYERS_LIST(
layer_qwerty_lights,
layer_num_lights,// overrides layer 1
layer_symbol_lights,
layer_command_lights,
layer_numpad_lights,
layer_switcher_lights, // Overrides other layers
layer_colemakdh_lights
);
layer_state_t layer_state_set_user(layer_state_t state) {
rgblight_set_layer_state(0, layer_state_cmp(state, _DEFAULTS) && layer_state_cmp(default_layer_state,_QWERTY));
rgblight_set_layer_state(7, layer_state_cmp(state, _DEFAULTS) && layer_state_cmp(default_layer_state,_COLEMAKDH));
rgblight_set_layer_state(1, layer_state_cmp(state, _LOWER));
rgblight_set_layer_state(2, layer_state_cmp(state, _RAISE));
rgblight_set_layer_state(3, layer_state_cmp(state, _ADJUST));
rgblight_set_layer_state(4, layer_state_cmp(state, _NUMPAD));
rgblight_set_layer_state(5, layer_state_cmp(state, _SWITCH));
return state;
}
void keyboard_post_init_user(void) {
// Enable the LED layers
rgblight_layers = my_rgb_layers;
rgblight_mode(10);// haven't found a way to set this in a more useful way
}
#endif
#ifdef OLED_DRIVER_ENABLE
static void render_logo(void) {
static const char PROGMEM qmk_logo[] = {
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94,
0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4,
0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0x00
};
oled_write_P(qmk_logo, false);
}
static void print_status_narrow(void) {
// Print current mode
oled_write_P(PSTR("\n\n"), false);
oled_write_ln_P(PSTR("Dane\nEvans"), false);
oled_write_ln_P(PSTR(""), false);
//snprintf(layer_state_str, sizeof(layer_state_str), "Layer: Undef-%ld", layer_state)
switch (get_highest_layer(default_layer_state)) {
case _QWERTY:
oled_write_ln_P(PSTR("Qwrt"), false);
break;
case _COLEMAK:
oled_write_ln_P(PSTR("Clmk"), false);
break;
case _COLEMAKDH:
oled_write_ln_P(PSTR("CmkDH"), false);
break;
default:
oled_write_ln_P(PSTR("Undef"), false);
}
oled_write_P(PSTR("\n\n"), false);
// Print current layer
oled_write_ln_P(PSTR("LAYER"), false);
switch (get_highest_layer(layer_state)) {
case _COLEMAK:
case _QWERTY:
case _COLEMAKDH:
oled_write_P(PSTR("Base\n"), false);
break;
case _RAISE:
oled_write_P(PSTR("Raise"), false);
break;
case _LOWER:
oled_write_P(PSTR("Lower"), false);
break;
case _ADJUST:
oled_write_P(PSTR("Adj\n"), false);
break;
case _NUMPAD:
oled_write_P(PSTR("Nump\n"), false);
break;
case _SWITCH:
oled_write_P(PSTR("Swit\n"), false);
break;
default:
oled_write_ln_P(PSTR("Undef"), false);
}
}
oled_rotation_t oled_init_user(oled_rotation_t rotation) {
if (is_keyboard_master()) {
return OLED_ROTATION_270;
}
return rotation;
}
void oled_task_user(void) {
if (is_keyboard_master()) {
print_status_narrow();
} else {
render_logo();
}
}
#endif
bool process_record_user(uint16_t keycode, keyrecord_t *record) {
switch (keycode) {
case KC_QWERTY:
if (record->event.pressed) {
set_single_persistent_default_layer(_QWERTY);
}
return false;
case KC_COLEMAK:
if (record->event.pressed) {
set_single_persistent_default_layer(_COLEMAK);
}
return false;
case KC_COLEMAKDH:
if (record->event.pressed) {
set_single_persistent_default_layer(_COLEMAKDH);
}
return false;
case KC_LOWER:
if (record->event.pressed) {
layer_on(_LOWER);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
} else {
layer_off(_LOWER);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
}
return false;
case KC_RAISE:
if (record->event.pressed) {
layer_on(_RAISE);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
} else {
layer_off(_RAISE);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
}
return false;
case KC_ADJUST:
if (record->event.pressed) {
layer_on(_ADJUST);
} else {
layer_off(_ADJUST);
}
return false;
case KC_D_MUTE:
if (record->event.pressed) {
register_mods(mod_config(MOD_MEH));
register_code(KC_UP);
} else {
unregister_mods(mod_config(MOD_MEH));
unregister_code(KC_UP);
}
}
return true;
}
#ifdef ENCODER_ENABLE
bool encoder_update_user(uint8_t index, bool clockwise) {
if (index == 0) {
if (clockwise) {
tap_code(KC_VOLU);
} else {
tap_code(KC_VOLD);
}
} else if (index == 1) {
switch (get_highest_layer(layer_state)) {
case _COLEMAK:
case _QWERTY:
case _COLEMAKDH:
if (clockwise) {
tap_code(KC_PGDOWN);
} else {
tap_code(KC_PGUP);
}
break;
case _RAISE:
case _LOWER:
if (clockwise) {
tap_code(KC_DOWN);
} else {
tap_code(KC_UP);
}
break;
default:
if (clockwise) {
tap_code(KC_WH_D);
} else {
tap_code(KC_WH_U);
}
break;
}
}
return true;
}
#endif
| 54.303665 | 138 | 0.318454 |
a91986ae12ac3eb9769b3c0f7a518d6488d3c85a | 18,836 | c | C | clib-multigpu/stream.c | lsds/Crossbow | d4441b35315f9f7d48293fe81faaf21e1ca48002 | [
"Apache-2.0"
] | 50 | 2019-01-09T14:30:41.000Z | 2022-03-23T11:42:51.000Z | clib-multigpu/stream.c | lsds/Crossbow | d4441b35315f9f7d48293fe81faaf21e1ca48002 | [
"Apache-2.0"
] | 6 | 2019-01-18T07:31:39.000Z | 2021-12-14T21:16:53.000Z | clib-multigpu/stream.c | lsds/Crossbow | d4441b35315f9f7d48293fe81faaf21e1ca48002 | [
"Apache-2.0"
] | 7 | 2019-03-20T14:56:41.000Z | 2022-03-30T06:13:09.000Z | #include "stream.h"
#include "memorymanager.h"
#include "debug.h"
#include "utils.h" /* Defines use of pinned memory */
#include <limits.h>
crossbowStreamP crossbowStreamCreate (int id, crossbowDeviceP dev, int ops, int splits, crossbowVariableSchemaP examples, crossbowVariableSchemaP labels, int branches, crossbowModelSynchronisationMode_t mode, unsigned long long seed) {
int i;
int bytes;
crossbowStreamP p = (crossbowStreamP) crossbowMalloc (sizeof(crossbow_stream_t));
p->id = id;
p->deviceId = dev->id;
p->mode = mode;
/* All calls directed to a particular device */
checkCudaErrors(cudaSetDevice(p->deviceId));
p->branches = branches;
invalidConditionException(p->branches > 0);
p->stream = crossbowMalloc (p->branches * sizeof(cudaStream_t));
for (i = 0; i < p->branches; ++i)
checkCudaErrors(cudaStreamCreateWithFlags(&(p->stream[i]), cudaStreamNonBlocking));
#ifdef INTRA_TASK_MEASUREMENTS
/* Enable timing measurements and create start event */
/*
checkCudaErrors(cudaEventCreateWithFlags(&p->event, cudaEventBlockingSync));
checkCudaErrors(cudaEventCreateWithFlags(&p->start, cudaEventBlockingSync));
*/
checkCudaErrors(cudaEventCreateWithFlags(&p->event, cudaEventDefault));
checkCudaErrors(cudaEventCreateWithFlags(&p->start, cudaEventDefault));
#else
/*
checkCudaErrors(cudaEventCreateWithFlags(&p->event, cudaEventBlockingSync | cudaEventDisableTiming));
*/
checkCudaErrors(cudaEventCreateWithFlags(&p->event, cudaEventDefault | cudaEventDisableTiming));
#endif
#ifdef MAKESPAN_MEASUREMENTS
p->barrier = dev->barrier;
#endif
p->cublasHandle = crossbowMalloc (p->branches * sizeof(cublasHandle_t));
p->cudnnHandle = crossbowMalloc (p->branches * sizeof(cudnnHandle_t));
/* There is one cuRAND generator per stream */
checkCurandStatus(curandCreateGenerator(&(p->curandGenerator), CURAND_RNG_PSEUDO_DEFAULT));
/* Set seed */
checkCurandStatus(curandSetPseudoRandomGeneratorSeed(p->curandGenerator, seed));
for (i = 0; i < p->branches; ++i) {
/* cuBLAS handler */
checkCublasStatus(cublasCreate(&(p->cublasHandle[i])));
/* cuDNN handler */
checkCudnnStatus(cudnnCreate(&(p->cudnnHandle[i])));
/* Set cuBLAS stream. All subsequent cuBLAS function calls ought to be scheduled on stream `p->stream[i]` */
checkCublasStatus(cublasSetStream (p->cublasHandle[i], p->stream[i]));
/* Set cuDNN stream. All subsequent cuDNN function call ought to be scheduled on stream `p->stream[i]` */
checkCudnnStatus(cudnnSetStream (p->cudnnHandle[i], p->stream[i]));
}
p->splits = splits;
/*
* The shape of variable examples already takes into account
* the fact that we may split the batch into smaller tasks.
*
* The size, however reflect the entire batch plus padding.
*/
bytes = examples->bytes + labels->bytes;
#ifdef __INPUT_ISPINNED_
p->input = crossbowDataBufferCreate (bytes, PIN);
#else
p->input = crossbowDataBufferCreate (bytes, REF);
#endif
p->examples = crossbowVariableCreate (crossbowVariableSchemaCopy (examples));
p->labels = crossbowVariableCreate (crossbowVariableSchemaCopy (labels));
/* Set input data buffer pointers */
crossbowVariableSetDataBuffer (p->examples, p->input, 0);
crossbowVariableSetDataBuffer (p->labels, p->input, examples->bytes);
/* Used only with record datasets */
p->dataset = NULL;
p->ops = ops;
p->outputs = (crossbowListP *) crossbowMalloc (p->ops * sizeof (crossbowListP));
for (i = 0; i < p->ops; ++i)
p->outputs[i] = crossbowListCreate ();
p->locals = (crossbowListP *) crossbowMalloc (p->ops * sizeof (crossbowListP));
for (i = 0; i < p->ops; ++i)
p->locals[i] = crossbowListCreate();
p->theModel = NULL;
p->modelSynchronisationHandle = NULL; /* dev->modelSynchronisationHandle; */
p->modelSynchronisationStream = NULL; /* dev->modelSynchronisationStream; */
crossbowStreamClear (p);
return p;
}
crossbowDataBufferP crossbowStreamOperatorGetInput (crossbowStreamP p, crossbowOperatorP op) {
int order;
crossbowOperatorP prev;
crossbowDataBufferP buffer;
/*
* We cannot use `crossbowDataflowMostUpstream(p->dataflow, op)` here because
* it skips the data transformation operator and returns the raw input buffer.
*/
if (op->upstream == NULL) {
return crossbowVariableGetDataBuffer (p->examples, NULL, NULL);
}
else {
/* Input is the output of the previous operator.
* Check that there is only one, and get its id.
*/
invalidConditionException (crossbowArrayListSize(op->upstream) == 1);
prev = crossbowArrayListGet (op->upstream, 0);
/* Check that previous operator has produced at
* least one output. */
invalidConditionException (crossbowListSize(p->outputs [prev->id]) > 0);
if (crossbowListSize(p->outputs [prev->id]) == 1) {
dbg("Return as input the output of %d\n", prev->id);
return crossbowListPeekHead(p->outputs [prev->id]);
}
else {
/* Previous operator has produced more than one outputs.
* Try to find current operator in its downstream nodes.
*/
for (order = 0; order < crossbowArrayListSize(prev->downstream); ++order) {
if (op == crossbowArrayListGet (prev->downstream, order)) {
/* Operator found. Lookup corresponding output */
buffer = (crossbowDataBufferP) crossbowListPeek (p->outputs [prev->id], order);
invalidConditionException (buffer != NULL);
return buffer;
}
}
/* If not found, throw exception */
illegalStateException ();
}
}
}
/**
* Get input of the current operator
*/
crossbowDataBufferP crossbowStreamGetCurrentInput (crossbowStreamP p) {
return crossbowStreamOperatorGetInput (p, p->op);
}
/**
* Get input of the current operator's peer
*/
crossbowDataBufferP crossbowStreamGetPeerInput (crossbowStreamP p) {
nullPointerException(p->op->peer);
return crossbowStreamOperatorGetInput (p, p->op->peer);
}
crossbowDataBufferP crossbowStreamOperatorGetOutput (crossbowStreamP p, crossbowOperatorP op) {
int order;
crossbowDataBufferP buffer;
if (crossbowListSize(p->outputs [op->id]) == 1) {
return crossbowListPeekHead(p->outputs [op->id]);
}
else {
/* Operator `op` has produced more than one outputs. Try to find
* current operator (`p->op`) in `op`'s list of downstream nodes.
*/
for (order = 0; order < crossbowArrayListSize(op->downstream); ++order) {
if (p->op == crossbowArrayListGet (op->downstream, order)) {
/* Operator found. Lookup corresponding output */
buffer = (crossbowDataBufferP) crossbowListPeek (p->outputs [op->id], order);
invalidConditionException (buffer != NULL);
return buffer;
}
}
/* If not found, throw exception */
illegalStateException ();
}
}
crossbowDataBufferP crossbowStreamGetCurrentOutput (crossbowStreamP p) {
crossbowDataBufferP output = NULL;
if (! crossbowOperatorGetOutputBufferFromElsewhere(p->op)) {
output = crossbowKernelGetOutputBuffer (p->op->kernel, p->deviceId, p->id);
}
else {
dbg("Return the output of node %d (%s), position is %d\n", p->op->provider->id, p->op->provider->kernel->name, p->op->position);
output = (crossbowDataBufferP) crossbowListPeek (p->outputs [p->op->provider->id], p->op->position);
/* Increment reference counter */
output->refs++;
}
return output;
}
/**
* Get output of the current operator's peer
*/
crossbowDataBufferP crossbowStreamGetPeerOutput (crossbowStreamP p) {
nullPointerException(p->op->peer);
/* Assert that peer has produced at most one output */
invalidConditionException (crossbowListSize(p->outputs[p->op->peer->id]) >= 1);
return crossbowListPeekHead(p->outputs [p->op->peer->id]);
}
void crossbowStreamComputeInputCheckSum (crossbowStreamP p) {
int i, j;
int s; /* Step size */
int b, n;
float image;
int label;
float imagetotal = 0;
int labeltotal = 0;
if (! crossbowDataflowMostUpstream (p->dataflow, p->op))
err("Fatal error\n");
b = p->examples->schema->shape[0];
n = p->examples->schema->bytes;
if ((n % b) != 0)
err("Fatal error\n");
s = n / b;
/* Assert that the labels' buffer is the same as the one for examples */
if (p->examples->buffer != p->labels->buffer)
err("Fatal error\n");
if (p->examples->buffer != p->input)
err("Fatal error\n");
j = 0;
for (i = 0; i < n; i += s) {
image = crossbowDataBufferComputeCheckSum (p->input, i, s);
label = crossbowDataBufferComputeCheckSumAsInt (p->input, (p->labels->offset + (j * 4)), 4);
/* info("%2d: %+7d %+15.5f\n", j++, label, image); */
imagetotal += image;
labeltotal += label;
}
info("Total: %+7d %+15.5f\n", labeltotal, imagetotal);
}
void crossbowStreamComputeCheckSum (crossbowStreamP p) {
float checksum;
crossbowDataBufferP output;
/* Compute input checksum */
if (crossbowDataflowMostUpstream (p->dataflow, p->op))
{
checksum = crossbowDataBufferComputeCheckSum (p->input, 0, p->examples->schema->bytes);
info("Kernel's %s input checksum is %.5f\n", p->op->kernel->name, checksum);
}
/* Compute output checksum */
if (crossbowListEmpty(p->outputs[p->op->id])) {
info("Kernel's %s output is null\n", p->op->kernel->name);
}
else {
output = crossbowListPeekHead (p->outputs[p->op->id]);
nullPointerException(output);
checksum = crossbowDataBufferComputeCheckSum (output, 0, p->op->kernel->output->schema->bytes);
info("Kernel's %s output (%p) checksum is %.5f\n", p->op->kernel->name, output, checksum);
}
return;
}
#ifdef SHARD_AXPY
static void crossbowStreamShardedSaxpy
(cublasHandle_t handle, int elements, float *alpha, float *x, int incX, float *y, int incY) {
/*
* Assume elements are floats (4 bytes):
* 0.125 MB contain 32768 elements
* 0.25 MB contain 65536 elements
* 0.5 MB contain 131072 elements
* 1.0 MB contains 262144 elements
* 2.0 MB contain 524288 elements
* 4.0 MB contain 1048576 elements
* 8.0 MB contain 2097152 elements
* 16.0 MB contain 4194304 elements
* 32.0 MB contain 8388608 elements
*/
int partition = 83886608;
int remaining;
float *px;
float *py;
int offset;
if (elements <= partition) {
checkCublasStatus(cublasSaxpy (handle, elements, alpha, x, incX, y, incY));
}
else {
dbg("Sharding saxpy into %d calls\n", (((elements - (elements % partition)) / partition) + 1));
remaining = elements;
px = x;
py = y;
while (remaining > 0) {
offset = (remaining > partition) ? partition : remaining;
checkCublasStatus(cublasSaxpy (handle, offset, alpha, px, incX, py, incY));
/* Increment pointers */
px = px + offset;
py = py + offset;
/* Decrement remaining */
remaining -= offset;
}
}
}
#endif
static void crossbowStreamSaxpy (cublasHandle_t handle, int elements, float *alpha, float *x, int incX, float *y, int incY) {
#ifdef SHARD_AXPY
crossbowStreamShardedSaxpy (handle, elements, alpha, x, incX, y, incY);
#else
checkCublasStatus(cublasSaxpy (handle, elements, alpha, x, incX, y, incY));
#endif
}
#ifdef UPDATE_MODEL_INCREMENTALLY
static void crossbowStreamDefaultModelUpdate (crossbowStreamP p, int count) {
int order;
int offset, length;
int elements;
float rate;
crossbowDataBufferP buffer;
float *data;
float *gradient;
float *last;
float *base;
float minusone = -1;
/* Synchronise one or more model replica variables */
for (order = 1; order <= count; ++order) {
buffer = crossbowModelVariable (p->model, p->op->peer->kernel->id, order, &offset, &length);
/* Assumes elements are floats */
elements = length / 4;
data = (float *) ((char *) (buffer->dev) + offset); /* Local replica model pointers */
gradient = (float *) ((char *) (p->model->gradient->dev) + offset);
last = (float *) ((char *) (p->model->last->dev) + offset);
base = (float *) ((char *) (p->theModel->data->dev) + offset); /* Base model pointers */
if (p->model->weightDecay > 0) {
/* Add biased model variable to gradient */
dbg("Compute gradient update with weight decay\n");
crossbowStreamSaxpy (p->handle, elements, &(p->model->weightDecay), data, 1, gradient, 1);
}
if (p->model->momentum > 0) {
rate = crossbowModelGetLearningRateForVariable(p->model, p->task, p->op->peer->id, order);
/* Scale gradient based on learning rate */
checkCublasStatus(cublasSscal(p->handle, elements, &(rate), gradient, 1));
/* Apply momentum to gradient */
crossbowStreamSaxpy (p->handle, elements, &(p->model->momentum), last, 1, gradient, 1);
/* Copy current gradient into last */
checkCudaErrors(cudaMemcpyAsync(last, gradient, length, cudaMemcpyDeviceToDevice, p->stream));
/* Record event that gradient is ready to be used by parameter server */
checkCudaErrors(cudaEventRecord (p->model->client[p->op->peer->id], p->stream));
/* Apply gradient to local model */
crossbowStreamSaxpy (p->handle, elements, &(minusone), gradient, 1, data, 1);
/* Apply gradient to parameter server model (base model) */
checkCudaErrors(cudaStreamWaitEvent(p->modelSynchronisationStream, p->model->client[p->op->peer->id], 0));
crossbowStreamSaxpy (p->modelSynchronisationHandle, elements, &(minusone), gradient, 1, base, 1);
checkCudaErrors(cudaEventRecord(p->model->server[p->op->peer->id], p->modelSynchronisationStream));
} else {
rate = - crossbowModelGetLearningRateForVariable(p->model, p->task, p->op->peer->id, order);
/*
info("offset at %d\n", offset);
info("length is %d (or %d elements)\n", length, elements);
info("data at %p\n", data);
info("gradient at %p\n", gradient);
*/
/* Record event that gradient is ready to be used by parameter server */
checkCudaErrors(cudaEventRecord (p->model->client[p->op->peer->id], p->stream));
/* Apply gradient to local model */
crossbowStreamSaxpy (p->handle, elements, &(rate), gradient, 1, data, 1);
/* Apply gradient to parameter server model (base model) */
checkCudaErrors(cudaStreamWaitEvent(p->modelSynchronisationStream, p->model->client[p->op->peer->id], 0));
crossbowStreamSaxpy (p->modelSynchronisationHandle, elements, &(rate), gradient, 1, base, 1);
checkCudaErrors(cudaEventRecord(p->model->server[p->op->peer->id], p->modelSynchronisationStream));
}
}
return;
}
static void crossbowStreamWorkerModelUpdate (crossbowStreamP p, int count) {
(void) count;
/* Record event that gradient is ready to be used by parameter server */
checkCudaErrors(cudaEventRecord (p->model->client[p->op->peer->id], p->stream));
return;
}
static void crossbowStreamSynchronousEamsgdModelUpdate (crossbowStreamP p, int count) {
int order;
int offset, length;
int elements;
float rate;
crossbowDataBufferP buffer;
float *data;
float *gradient;
float *last;
float minusone = -1;
/* Synchronise one or more model replica variables */
for (order = 1; order <= count; ++order) {
buffer = crossbowModelVariable (p->model, p->op->peer->kernel->id, order, &offset, &length);
/* Assumes elements are floats */
elements = length / 4;
data = (float *) ((char *) (buffer->dev) + offset); /* Local replica model pointers */
gradient = (float *) ((char *) (p->model->gradient->dev) + offset);
last = (float *) ((char *) (p->model->last->dev) + offset);
if (p->model->weightDecay > 0) {
/* Add biased model variable to gradient */
crossbowStreamSaxpy (p->handle, elements, &(p->model->weightDecay), data, 1, gradient, 1);
}
if (p->model->momentum > 0) {
rate = crossbowModelGetLearningRateForVariable(p->model, p->task, p->op->peer->id, order);
/* Scale gradient based on learning rate */
checkCublasStatus(cublasSscal(p->handle, elements, &(rate), gradient, 1));
/* Apply momentum to gradient */
crossbowStreamSaxpy (p->handle, elements, &(p->model->momentum), last, 1, gradient, 1);
/* Copy current gradient into last */
checkCudaErrors(cudaMemcpyAsync(last, gradient, length, cudaMemcpyDeviceToDevice, p->stream));
/* Apply gradient to local model */
crossbowStreamSaxpy (p->handle, elements, &(minusone), gradient, 1, data, 1);
} else {
rate = - crossbowModelGetLearningRateForVariable(p->model, p->task, p->op->peer->id, order);
/* Apply gradient to local model */
crossbowStreamSaxpy (p->handle, elements, &(rate), gradient, 1, data, 1);
}
}
return;
}
static void crossbowStreamEamsgdModelUpdate (crossbowStreamP p, int count) {
(void) p;
(void) count;
err ("Incremental asynchronous elastic averaging SGD is not supported yet");
}
#endif /* UPDATE_MODEL_INCREMENTALLY */
void crossbowStreamUpdateModel (crossbowStreamP p) {
#ifndef UPDATE_MODEL_INCREMENTALLY
/* Do nothing */
(void) p;
#else
int count;
if (p->op->peer == NULL)
return;
/* Are there any model variables updated? */
count = crossbowModelVariableCount (p->model, p->op->peer->kernel->id);
if (count == 0)
return;
switch (s->model->type) {
case DEFAULT:
dbg("Update replica incrementally using default model\n");
crossbowStreamDefaultModelUpdate (p, count);
break;
case WORKER:
dbg("Update replica incrementally using worker model\n");
crossbowStreamWorkerModelUpdate (p, count);
break;
case EAMSGD:
dbg("Update replica incrementally using EAMSGD model\n");
crossbowStreamEamsgdModelUpdate (p, count);
break;
case SYNCHRONOUSEAMSGD:
dbg("Update replica incrementally using synchronous EAMSGD model\n");
crossbowStreamSynchronousEamsgdModelUpdate (p, count);
break;
default:
err("Invalid model update type\n");
}
#endif
return;
}
void crossbowStreamClear (crossbowStreamP p) {
int i;
for (i = 0; i < p->ops; i++) {
if (! crossbowListEmpty(p->outputs[i]))
illegalStateException();
if (! crossbowListEmpty(p->locals [i]))
illegalStateException();
}
p->task = 0;
p->phi = TRAIN;
p->freeP[0] = LONG_MIN;
p->freeP[1] = LONG_MIN;
p->model = NULL;
p->dataflow = NULL;
p->op = NULL;
return;
}
void crossbowStreamFree (crossbowStreamP p) {
int i;
for (i = 0; i < p->branches; ++i) {
checkCudaErrors(cudaStreamDestroy(p->stream[i]));
/* Free stream handlers */
checkCublasStatus(cublasDestroy(p->cublasHandle[i]));
checkCudnnStatus(cudnnDestroy(p->cudnnHandle[i]));
}
crossbowFree (p->stream, (p->branches * sizeof(cudaStream_t)));
crossbowFree (p->cublasHandle, (p->branches * sizeof(cublasHandle_t)));
crossbowFree (p->cudnnHandle, (p->branches * sizeof(cudnnHandle_t)));
checkCurandStatus(curandDestroyGenerator(p->curandGenerator));
checkCudaErrors(cudaEventDestroy(p->event));
crossbowVariableFree (p->examples);
crossbowVariableFree (p->labels);
crossbowDataBufferFree (p->input);
for (i = 0; i < p->ops; i++)
crossbowListFree (p->outputs[i]);
crossbowFree (p->outputs, p->ops * sizeof (crossbowDataBufferP));
for (i = 0; i < p->ops; i++)
crossbowListFree (p->locals[i]);
crossbowFree (p->locals, p->ops * sizeof (crossbowDataBufferP));
crossbowFree (p, sizeof(crossbow_stream_t));
}
| 32.419966 | 235 | 0.695105 |
04b2f36c3b3d461d6c7416d199cf681999bcb9c8 | 260 | c | C | llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/debug/dwarf2/dwarf-die3.c | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/debug/dwarf2/dwarf-die3.c | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/gcc/testsuite/gcc.dg/debug/dwarf2/dwarf-die3.c | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | /* Verify that extern inline function never actually inlined has no abstract DIE. */
/* { dg-do compile } */
/* { dg-options "-O0 -gdwarf-2 -dA" } */
/* { dg-final { scan-assembler-not "DW_AT_inline" } } */
extern inline int t()
{
}
int (*q)()=t;
int t()
{
}
| 21.666667 | 85 | 0.603846 |
aa69a30e124ca360128a1b7ad7c7268d5aa42a01 | 8,486 | c | C | sdk-6.5.20/src/appl/portmod/portmod_reg_access.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/appl/portmod/portmod_reg_access.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/appl/portmod/portmod_reg_access.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.
*
* This file present an example of replacing the registers\memories access functions.
* It assumes using the portmod register DB bcm2801pb_a0
*/
#include <shared/bsl.h>
#include <soc/register.h>
#include <soc/mcm/driver.h>
#include <bcm/error.h>
typedef struct portmod_port_access_info_s {
int block_id;
int inner_index;
} portmod_port_access_info_t;
static portmod_port_access_info_t *port2info[SOC_MAX_NUM_DEVICES] = {0};
#define PORTMOD_NO_DEVICE
#ifdef PORTMOD_NO_DEVICE
STATIC int
portmod_memreg_access(int unit, int cmic_block, uint32 addr, uint32 dwc_read, int is_mem, int is_get, uint32 *data)
{
if(is_get) {
LOG_INFO(BSL_LS_APPL_PORT,
(BSL_META_U(unit,
"Read operation: block[%d] addr[0x%x] dwc_read[%d] is_mem[%d]\n"),
cmic_block, addr, dwc_read, is_mem));
} else {
LOG_INFO(BSL_LS_APPL_PORT,
(BSL_META_U(unit,
"Write operation: block[%d] addr[0x%x] dwc_read[%d] is_mem[%d] data[0x%x]\n"),
cmic_block, addr, dwc_read, is_mem, data[0]));
}
return 0;
}
#else /*PORTMOD_NO_DEVICE*/
STATIC int
portmod_memreg_access(int unit, int cmic_block, uint32 addr, uint32 dwc_read, int is_mem, int is_get, uint32 *data)
{
if(is_get) {
return soc_direct_memreg_get(unit, blk_id, addr, reg_size, 0, data);
} else {
return soc_direct_memreg_set(unit, blk_id, addr, reg_size, 0, data);
}
}
#endif /*PORTMOD_NO_DEVICE*/
STATIC int
portmod_reg_address_get(int unit, soc_reg_t reg, int port, uint32* addr)
{
soc_driver_t* d = &soc_driver_bcm2801pm_a0;
soc_reg_info_t* reg_info = d->reg_info[reg];
(*addr) = reg_info->offset;
if(reg_info->regtype == soc_portreg) {
/* From block type and port user should find the register offset
The example here should be adjust per user architecture */
(*addr) += port2info[unit][port].inner_index;
}
return BCM_E_NONE;
}
STATIC int
portmod_reg_access_handle(int unit, soc_reg_t reg, int port, int index, int is_get, soc_reg_above_64_val_t data)
{
uint32 addr, reg_size;
int rv;
soc_driver_t* d = &soc_driver_bcm2801pm_a0;
soc_reg_info_t* reg_info;
int blk_id, schan_id;
if(reg >= NUM_SOC_REG) {
LOG_ERROR(BSL_LS_SOC_PHYMOD,
(BSL_META_U(unit,
"invalid register")));
return BCM_E_INTERNAL;
}
reg_info = d->reg_info[reg];
if(!reg_info) {
LOG_ERROR(BSL_LS_SOC_PHYMOD,
(BSL_META_U(unit,
"invalid register")));
return BCM_E_INTERNAL;
}
if(!port2info[unit]) {
LOG_ERROR(BSL_LS_SOC_PHYMOD,
(BSL_META_U(unit,
"unit isn't initialized")));
return BCM_E_UNIT;
}
rv = portmod_reg_address_get(unit, reg, port, &addr);
if(rv < 0) {
return rv;
}
/* CMIC functionality - should be replaced by user access*/
if (reg_info->flags & SOC_REG_FLAG_ABOVE_64_BITS) {
reg_size = d->reg_above_64_info[reg]->size;
} else if (reg_info->flags & SOC_REG_FLAG_64_BITS) {
reg_size = 2;
} else {
reg_size = 1;
}
if(port & SOC_REG_ADDR_SCHAN_ID_MASK) {
schan_id = port & (~SOC_REG_ADDR_SCHAN_ID_MASK);
} else if(port & SOC_REG_ADDR_BLOCK_ID_MASK) {
blk_id = port & (~SOC_REG_ADDR_BLOCK_ID_MASK);
schan_id = d->block_info[blk_id].schan;
} else {
schan_id = port2info[unit][port].block_id;
}
return portmod_memreg_access(unit, schan_id, addr, reg_size, 0, is_get, data);
}
STATIC int
portmod_mem_access_handle(int unit, soc_mem_t mem, unsigned int array_index, int copyno, int index, int is_read, void *entry_data)
{
uint32 mem_size, addr, schan_block;
soc_driver_t* d = &soc_driver_bcm2801pm_a0;
soc_mem_info_t* mem_info;
if(mem >= NUM_SOC_REG) {
LOG_ERROR(BSL_LS_SOC_PHYMOD,
(BSL_META_U(unit,
"invalid memory")));
return BCM_E_INTERNAL;
}
mem_info = d->mem_info[mem];
if(!mem_info) {
LOG_ERROR(BSL_LS_SOC_PHYMOD,
(BSL_META_U(unit,
"invalid memory")));
return BCM_E_INTERNAL;
}
if(!port2info[unit]) {
LOG_ERROR(BSL_LS_SOC_PHYMOD,
(BSL_META_U(unit,
"unit isn't initialized")));
return BCM_E_UNIT;
}
addr = mem_info->base + index;
mem_size = (mem_info->bytes + 3) / 4;
schan_block = d->block_info[copyno].schan;
return portmod_memreg_access(unit, schan_block, addr, mem_size, 1, is_read, (uint32*)entry_data);
}
STATIC int
portmod_reg32_get(int unit, soc_reg_t reg, int port, int index, uint32* data)
{
soc_reg_above_64_val_t data_a64;
int rv;
rv = portmod_reg_access_handle(unit, reg, port, index, 1, data_a64);
if(rv<0) {
return rv;
}
data[0] = data_a64[0];
return BCM_E_NONE;
}
STATIC int
portmod_reg64_get(int unit, soc_reg_t reg, int port, int index, uint64* data)
{
soc_reg_above_64_val_t data_a64;
int rv;
rv = portmod_reg_access_handle(unit, reg, port, index, 1, data_a64);
if(rv<0) {
return rv;
}
COMPILER_64_SET(*data, data_a64[1], data_a64[0]);
return BCM_E_NONE;
}
STATIC int
portmod_reg_above64_get(int unit, soc_reg_t reg, int port, int index, soc_reg_above_64_val_t data)
{
return portmod_reg_access_handle(unit, reg, port, index, 1, data);
}
STATIC int
portmod_reg32_set(int unit, soc_reg_t reg, int port, int index, uint32 data)
{
soc_reg_above_64_val_t data_a64;
SOC_REG_ABOVE_64_CLEAR(data_a64);
data_a64[0] = data;
return portmod_reg_access_handle(unit, reg, port, index, 0, data_a64);
}
STATIC int
portmod_reg64_set(int unit, soc_reg_t reg, int port, int index, uint64 data)
{
soc_reg_above_64_val_t data_a64;
SOC_REG_ABOVE_64_CLEAR(data_a64);
data_a64[1] = COMPILER_64_HI(data);
data_a64[0] = COMPILER_64_LO(data);
return portmod_reg_access_handle(unit, reg, port, index, 0, data_a64);
}
STATIC int
portmod_reg_above64_set(int unit, soc_reg_t reg, int port, int index, soc_reg_above_64_val_t data)
{
return portmod_reg_access_handle(unit, reg, port, index, 0, data);
}
STATIC int
portmod_mem_array_read(int unit, soc_mem_t mem, unsigned int array_index, int copyno, int index, void *entry_data)
{
return portmod_mem_access_handle(unit, mem, array_index, copyno, index, 1, entry_data);
}
STATIC int
portmod_mem_array_write(int unit, soc_mem_t mem, unsigned int array_index, int copyno, int index, void *entry_data)
{
return portmod_mem_access_handle(unit, mem, array_index, copyno, index, 0, entry_data);
}
soc_reg_access_t portmod_access = {
portmod_reg32_get,
portmod_reg64_get,
portmod_reg_above64_get,
portmod_reg32_set,
portmod_reg64_set,
portmod_reg_above64_set,
portmod_mem_array_read,
portmod_mem_array_write
};
int
portmod_reg_access_init(int unit)
{
int rv;
soc_driver_t* d = &soc_driver_bcm2801pm_a0;
if(port2info[unit]) {
return BCM_E_EXISTS;
}
/* Required for field operations */
SOC_DRIVER(unit) = d;
port2info[unit] = sal_alloc(sizeof(portmod_port_access_info_t) * SOC_MAX_NUM_PORTS, "portmod reg access");
sal_memset(port2info[unit], 0, sizeof(portmod_port_access_info_t) * SOC_MAX_NUM_PORTS);
if(!port2info[unit]) {
return BCM_E_MEMORY;
}
rv = soc_reg_access_func_register(unit, &portmod_access);
if(rv < 0) {
return rv;
}
return BCM_E_NONE;
}
int
portmod_reg_access_deinit(int unit)
{
if(!port2info[unit]) {
return BCM_E_INIT;
}
sal_free(port2info[unit]);
port2info[unit] = NULL;
return BCM_E_NONE;
}
int
portmod_reg_access_port_bindex_set(int unit, int port, int block_index, int internal_index)
{
if(!port2info[unit]) {
return BCM_E_INIT;
}
port2info[unit][port].inner_index = internal_index;
port2info[unit][port].block_id = block_index;
return BCM_E_NONE;
}
| 26.272446 | 134 | 0.654018 |
b7b323130722ef4fe469a8e8a5b0ea8958486aec | 32,751 | h | C | engine/src/core/dm_math.h | wesExpress/CEngine | 578fd81c5f1388a4d80a5403b86c629b3e1e6140 | [
"MIT"
] | 2 | 2021-11-13T20:48:57.000Z | 2021-12-19T16:51:02.000Z | engine/src/core/dm_math.h | wesExpress/CEngine | 578fd81c5f1388a4d80a5403b86c629b3e1e6140 | [
"MIT"
] | null | null | null | engine/src/core/dm_math.h | wesExpress/CEngine | 578fd81c5f1388a4d80a5403b86c629b3e1e6140 | [
"MIT"
] | 1 | 2022-03-16T23:00:36.000Z | 2022-03-16T23:00:36.000Z | #ifndef __DM_MATH_H__
#define __DM_MATH_H__
#include "dm_defines.h"
#include "dm_assert.h"
#include "dm_math_types.h"
#include "dm_logger.h"
#include <math.h>
#include <stdbool.h>
DM_API float dm_math_angle_xy(float x, float y);
DM_API float dm_sin(float angle);
DM_API float dm_cos(float angle);
DM_API float dm_tan(float angle);
/*
Misc functions
*/
DM_INLINE
float dm_rad_to_deg(float radians)
{
return (float)(radians * (180.0f / DM_MATH_PI));
}
DM_INLINE
float dm_deg_to_rad(float degrees)
{
return (float)(degrees * (DM_MATH_PI / 180.0f));
}
/*
VEC2
*/
DM_INLINE
dm_vec2 dm_vec2_set(float x, float y)
{
return (dm_vec2) { x, y };
}
DM_INLINE
void dm_vec2_set_inpl(float x, float y, dm_vec2* out)
{
*out = dm_vec2_set(x, y);
}
DM_INLINE
dm_vec2 dm_vec2_set_from_vec3(dm_vec3 vec)
{
return (dm_vec2) { vec.x, vec.y };
}
DM_INLINE
void dm_vec2_set_from_vec3_inpl(dm_vec3 vec, dm_vec2* out)
{
*out = dm_vec2_set_from_vec3(vec);
}
DM_INLINE
dm_vec2 dm_vec2_set_from_vec4(dm_vec4 vec)
{
return (dm_vec2) { vec.x, vec.y };
}
DM_INLINE
void dm_vec2_set_from_vec4_inpl(dm_vec4 vec, dm_vec2* out)
{
*out = dm_vec2_set_from_vec4(vec);
}
DM_INLINE
dm_vec2 dm_vec2_add_scalar(dm_vec2 vec, float scalar)
{
return (dm_vec2) { vec.x + scalar, vec.y + scalar };
}
DM_INLINE
void dm_vec2_add_scalar_inpl(dm_vec2 vec, float scalar, dm_vec2* out)
{
*out = dm_vec2_add_scalar(vec, scalar);
}
DM_INLINE
dm_vec2 dm_vec2_sub_scalar(dm_vec2 vec, float scalar)
{
return dm_vec2_add_scalar(vec, -scalar);
}
DM_INLINE
void dm_vec2_sub_scalar_inpl(dm_vec2 vec, float scalar, dm_vec2* out)
{
*out = dm_vec2_sub_scalar(vec, scalar);
}
DM_INLINE
dm_vec2 dm_vec2_scale(dm_vec2 vec, float scale)
{
return (dm_vec2) { vec.x* scale, vec.y* scale };
}
DM_INLINE
void dm_vec2_scale_inpl(float scale, dm_vec2* out)
{
*out = dm_vec2_scale(*out, scale);
}
DM_INLINE
float dm_vec2_dot(dm_vec2 left, dm_vec2 right)
{
return (float)(left.x * right.x + left.y * right.y);
}
DM_INLINE
float dm_vec2_len(dm_vec2 vec)
{
float len = (float)sqrt(dm_vec2_dot(vec, vec));
//if (len == 0) DM_WARN("Vec2 has length 0!");
return len;
}
DM_INLINE
dm_vec2 dm_vec2_add_vec2(dm_vec2 left, dm_vec2 right)
{
return (dm_vec2) { left.x + right.x, left.y + right.y };
}
DM_INLINE
void dm_vec2_add_vec2_inpl(dm_vec2 left, dm_vec2 right, dm_vec2* out)
{
*out = dm_vec2_add_vec2(left, right);
}
DM_INLINE
dm_vec2 dm_vec2_sub_vec2(dm_vec2 left, dm_vec2 right)
{
return (dm_vec2) { left.x - right.x, left.y - right.y };
}
DM_INLINE
void dm_vec2_sub_vec2_inpl(dm_vec2 left, dm_vec2 right, dm_vec2* out)
{
*out = dm_vec2_sub_vec2(left, right);
}
DM_INLINE
dm_vec2 dm_vec2_norm(dm_vec2 vec)
{
float len = dm_vec2_len(vec);
if (len == 0) return (dm_vec2) { 0, 0 };
return dm_vec2_scale(vec, 1.0f / len);
}
DM_INLINE
void dm_vec2_norm_inpl(dm_vec2* out)
{
float len = dm_vec2_len(*out);
if (len != 0) dm_vec2_scale_inpl(1.0f / len, out);
}
DM_INLINE
float dm_vec2_angle(dm_vec2 left, dm_vec2 right)
{
float llen = dm_vec2_len(left);
float rlen = dm_vec2_len(right);
if(llen > 0 && rlen > 0) return (float)acosf(DM_CLAMP(dm_vec2_dot(left, right) / (llen * rlen),-1.0f, 1.0f));
DM_LOG_ERROR("Trying to get an angle between vec2s and at least one has length 0!");
return 0.0f;
}
DM_INLINE
float dm_vec2_angle_degrees(dm_vec2 left, dm_vec2 right)
{
return dm_deg_to_rad(dm_vec2_angle(left, right));
}
/*
VEC3
*/
DM_INLINE
dm_vec3 dm_vec3_set(float x, float y, float z)
{
return (dm_vec3) { x, y, z };
}
DM_INLINE
void dm_vec3_set_inpl(float x, float y, float z, dm_vec3* out)
{
*out = dm_vec3_set(x, y, z);
}
DM_INLINE
dm_vec3 dm_vec3_set_from_vec2(dm_vec2 vec)
{
return (dm_vec3) { vec.x, vec.y, 0.0f };
}
DM_INLINE
void dm_vec3_set_from_vec3_inpl(dm_vec2 vec, dm_vec3* out)
{
*out = dm_vec3_set_from_vec2(vec);
}
DM_INLINE
dm_vec3 dm_vec3_set_from_vec4(dm_vec4 vec)
{
return (dm_vec3) { vec.x, vec.y, vec.z };
}
DM_INLINE
void dm_vec3_set_from_vec4_inpl(dm_vec4 vec, dm_vec3* out)
{
*out = dm_vec3_set_from_vec4(vec);
}
DM_INLINE
dm_vec3 dm_vec3_add_scalar(dm_vec3 vec, float scalar)
{
return (dm_vec3) { vec.x + scalar, vec.y + scalar, vec.z + scalar };
}
DM_INLINE
void dm_vec3_add_scalar_inpl(float scalar, dm_vec3* out)
{
*out = dm_vec3_add_scalar(*out, scalar);
}
DM_INLINE
dm_vec3 dm_vec3_sub_scalar(dm_vec3 vec, float scalar)
{
return dm_vec3_add_scalar(vec, -scalar);
}
DM_INLINE
void dm_vec3_sub_scalar_inpl(float scalar, dm_vec3* out)
{
*out = dm_vec3_sub_scalar(*out, scalar);
}
DM_INLINE
dm_vec3 dm_vec3_scale(dm_vec3 vec, float scale)
{
return (dm_vec3) { vec.x* scale, vec.y* scale, vec.z* scale };
}
DM_INLINE
void dm_vec3_scale_inpl(float scale, dm_vec3* out)
{
*out = dm_vec3_scale(*out, scale);
}
DM_INLINE
float dm_vec3_dot(dm_vec3 left, dm_vec3 right)
{
return (float)(left.x * right.x + left.y * right.y + left.z * right.z);
}
DM_INLINE
dm_vec3 dm_vec3_cross(dm_vec3 left, dm_vec3 right)
{
return (dm_vec3) {
left.y* right.z - right.y * left.z,
-(left.x * right.z - right.x * left.z),
left.x* right.y - right.x * left.y
};
}
DM_INLINE
void dm_vec3_cross_inpl(dm_vec3 left, dm_vec3 right, dm_vec3* out)
{
*out = dm_vec3_cross(left, right);
}
DM_INLINE
float dm_vec3_len(dm_vec3 vec)
{
return (float)sqrt(dm_vec3_dot(vec, vec));
}
DM_INLINE
dm_vec3 dm_vec3_add_vec3(dm_vec3 left, dm_vec3 right)
{
return (dm_vec3) { left.x + right.x, left.y + right.y, left.z + right.z };
}
DM_INLINE
void dm_vec3_add_vec3_inpl(dm_vec3 left, dm_vec3 right, dm_vec3* out)
{
*out = dm_vec3_add_vec3(left, right);
}
DM_INLINE
dm_vec3 dm_vec3_sub_vec3(dm_vec3 left, dm_vec3 right)
{
return (dm_vec3) { left.x - right.x, left.y - right.y, left.z - right.z };
}
DM_INLINE
void dm_vec3_sub_vec3_inpl(dm_vec3 left, dm_vec3 right, dm_vec3* out)
{
*out = dm_vec3_sub_vec3(left, right);
}
DM_INLINE
dm_vec3 dm_vec3_norm(dm_vec3 vec)
{
float len = dm_vec3_len(vec);
if (len == 0)
{
return (dm_vec3) { 0, 0, 0 };
}
return dm_vec3_scale(vec, 1.0f / len);
}
DM_INLINE
void dm_vec3_norm_inpl(dm_vec3* out)
{
float len = dm_vec3_len(*out);
if (len != 0) dm_vec3_scale_inpl(1.0f / len, out);
}
DM_INLINE
float dm_vec3_angle(dm_vec3 left, dm_vec3 right)
{
float llen = dm_vec3_len(left);
float rlen = dm_vec3_len(right);
DM_ASSERT_MSG((llen > 0 && rlen > 0), "Trying to get an angle between vec3s and at least one has length 0!");
return (float)acosf(DM_CLAMP(dm_vec3_dot(left, right) / (llen * rlen),-1.0f, 1.0f));
}
DM_INLINE
float dm_vec3_angle_degrees(dm_vec3 left, dm_vec3 right)
{
return dm_deg_to_rad(dm_vec3_angle(left, right));
}
/*
VEC4
*/
DM_INLINE
dm_vec4 dm_vec4_set(float x, float y, float z, float w)
{
return (dm_vec4) { x, y, z, w };
}
DM_INLINE
void dm_vec4_set_inpl(float x, float y, float z, float w, dm_vec4* out)
{
*out = dm_vec4_set(x, y, z, w);
}
DM_INLINE
dm_vec4 dm_vec4_set_from_float(float f)
{
return dm_vec4_set(f, f, f, 1);
}
DM_INLINE
void dm_vec4_set_from_float_inpl(float f, dm_vec4* out)
{
*out = dm_vec4_set_from_float(f);
}
DM_INLINE
dm_vec4 dm_vec4_set_from_vec2(dm_vec2 vec)
{
return (dm_vec4) { vec.x, vec.y, 0.0f, 0.0f };
}
DM_INLINE
void dm_vec4_set_from_vec2_inpl(dm_vec2 vec, dm_vec4* out)
{
*out = dm_vec4_set_from_vec2(vec);
}
DM_INLINE
dm_vec4 dm_vec4_set_from_vec3(dm_vec3 vec)
{
return (dm_vec4) { vec.x, vec.y, vec.z, 0.0f };
}
DM_INLINE
void dm_vec4_set_from_vec3_inpl(dm_vec3 vec, dm_vec4* out)
{
*out = dm_vec4_set_from_vec3(vec);
}
DM_INLINE
dm_vec4 dm_vec4_add_scalar(dm_vec4 vec, float scalar)
{
return (dm_vec4) { vec.x + scalar, vec.y + scalar, vec.z + scalar, vec.w* scalar };
}
DM_INLINE
void dm_vec4_add_scalar_inpl(float scalar, dm_vec4* out)
{
*out = dm_vec4_add_scalar(*out, scalar);
}
DM_INLINE
dm_vec4 dm_vec4_sub_scalar(dm_vec4 vec, float scalar)
{
return dm_vec4_add_scalar(vec, -scalar);
}
DM_INLINE
void dm_vec4_sub_scalar_inpl(float scalar, dm_vec4* out)
{
*out = dm_vec4_sub_scalar(*out, scalar);
}
DM_INLINE
dm_vec4 dm_vec4_scale(dm_vec4 vec, float scale)
{
return (dm_vec4) { vec.x* scale, vec.y* scale, vec.z* scale, vec.w* scale };
}
DM_INLINE
void dm_vec4_scale_inpl(float scale, dm_vec4* out)
{
*out = dm_vec4_scale(*out, scale);
}
DM_INLINE
float dm_vec4_dot(dm_vec4 left, dm_vec4 right)
{
return (float)(left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
}
DM_INLINE
float dm_vec4_len(dm_vec4 vec)
{
float len = (float)sqrt(dm_vec4_dot(vec, vec));
//if (len == 0) DM_WARN("Vec4 has length 0!");
return len;
}
DM_INLINE
dm_vec4 dm_vec4_add_vec4(dm_vec4 left, dm_vec4 right)
{
return (dm_vec4) { left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w };
}
DM_INLINE
void dm_vec4_add_vec4_inpl(dm_vec4 left, dm_vec4 right, dm_vec4* out)
{
*out = dm_vec4_add_vec4(left, right);
}
DM_INLINE
dm_vec4 dm_vec4_sub_vec4(dm_vec4 left, dm_vec4 right)
{
return (dm_vec4) { left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w };
}
DM_INLINE
void dm_vec4_sub_vec4_inpl(dm_vec4 left, dm_vec4 right, dm_vec4* out)
{
*out = dm_vec4_sub_vec4(left, right);
}
DM_INLINE
dm_vec4 dm_vec4_norm(dm_vec4 vec)
{
float len = dm_vec4_len(vec);
if (len == 0)
{
return (dm_vec4) { 0, 0, 0, 0 };
}
return dm_vec4_scale(vec, 1.0f / len);
}
DM_INLINE
void dm_vec4_norm_inpl(dm_vec4* out)
{
float len = dm_vec4_len(*out);
if (len != 0) dm_vec4_scale_inpl(1.0f / len, out);
}
DM_INLINE
float dm_vec4_angle(dm_vec4 left, dm_vec4 right)
{
float llen = dm_vec4_len(left);
float rlen = dm_vec4_len(right);
DM_ASSERT_MSG((llen > 0 && rlen > 0), "Trying to get an angle between vec3s and at least one has length 0!");
return (float)acosf(DM_CLAMP(dm_vec4_dot(left, right) / (llen * rlen), -1.0f, 1.0f));
}
DM_INLINE
float dm_vec4_angle_degrees(dm_vec4 left, dm_vec4 right)
{
return dm_deg_to_rad(dm_vec4_angle(left, right));
}
/*
QUATERNIONS
*/
DM_INLINE
dm_quat dm_quat_real(float r)
{
return (dm_quat) { 0, 0, 0, r };
}
DM_INLINE
void dm_quat_real_inpl(float r, dm_quat* out)
{
*out = dm_quat_real(r);
}
DM_INLINE
dm_quat dm_quat_pure(dm_vec3 pure)
{
return (dm_quat) { pure.x, pure.y, pure.z, 0 };
}
DM_INLINE
void dm_quat_pure_inpl(dm_vec3 pure, dm_quat* out)
{
*out = dm_quat_pure(pure);
}
DM_INLINE
dm_quat dm_quat_set(float i, float j, float k, float r)
{
return (dm_quat) { i, j, k, r };
}
DM_INLINE
void dm_quat_set_inpl(float r, float i, float j, float k, dm_quat* out)
{
*out = dm_quat_set(i, j, k, r);
}
DM_INLINE
dm_quat dm_quat_set_imaj(float i, float j, float k)
{
return (dm_quat) { i, j, k, 1.0 };
}
DM_INLINE
void dm_quat_set_imaj_inpl(float i, float j, float k, dm_quat* out)
{
*out = dm_quat_set_imaj(i, j, k);
}
DM_INLINE
dm_quat dm_quat_set_from_vec3(dm_vec3 vec)
{
return (dm_quat) { vec.x, vec.y, vec.z };
}
DM_INLINE
void dm_quat_set_from_vec3_inpl(dm_vec3 vec, dm_quat* out)
{
*out = dm_quat_set_from_vec3(vec);
}
DM_INLINE
dm_quat dm_quat_set_from_vec4(dm_vec4 vec)
{
return (dm_quat) { vec.x, vec.y, vec.z, vec.w };
}
DM_INLINE
void dm_quat_set_from_vec4_inpl(dm_vec4 vec, dm_quat* out)
{
*out = dm_quat_set_from_vec4(vec);
}
DM_INLINE
dm_quat dm_quat_add_quat(dm_quat left, dm_quat right)
{
return (dm_quat) { (left.i + right.i), (left.j + right.j), (left.k + right.k), (left.r + right.r) };
}
DM_INLINE
void dm_quat_add_quat_inpl(dm_quat left, dm_quat right, dm_quat* out)
{
*out = dm_quat_add_quat(left, right);
}
DM_INLINE
dm_quat dm_quat_sub_quat(dm_quat left, dm_quat right)
{
return (dm_quat) { (left.i - right.i), (left.j - right.j), (left.k - right.k), (left.r - right.r) };
}
DM_INLINE
void dm_quat_sub_quat_inpl(dm_quat left, dm_quat right, dm_quat* out)
{
*out = dm_quat_sub_quat(left, right);
}
DM_INLINE
dm_vec3 dm_vec3_from_quat(dm_quat quat)
{
return (dm_vec3){ quat.i, quat.j, quat.k };
}
DM_INLINE
dm_quat dm_quat_mul_quat(dm_quat left, dm_quat right)
{
dm_vec3 a = dm_vec3_from_quat(left);
dm_vec3 b = dm_vec3_from_quat(right);
float ab_dot = dm_vec3_dot(a, b);
float real = left.r * right.r - ab_dot;
if (ab_dot) return (dm_quat) { 0, 0, 0, real };
dm_vec3 imaj = dm_vec3_scale(b, left.r);
imaj = dm_vec3_add_vec3(imaj, dm_vec3_scale(a, right.r));
imaj = dm_vec3_add_vec3(imaj, dm_vec3_cross(a, b));
return (dm_quat) { imaj.x, imaj.y, imaj.z, real };
}
DM_INLINE
void dm_quat_mul_quat_inpl(dm_quat left, dm_quat right, dm_quat* out)
{
*out = dm_quat_mul_quat(left, right);
}
DM_INLINE
dm_vec4 dm_vec4_from_quat(dm_quat quat)
{
return (dm_vec4) { quat.i, quat.j, quat.k, quat.r };
}
DM_INLINE
dm_quat dm_quat_scale(dm_quat quat, float scalar)
{
return (dm_quat) { quat.i* scalar, quat.j* scalar, quat.k* scalar, quat.r* scalar };
}
DM_INLINE
void dm_quat_scale_inpl(dm_quat quat, float scalar, dm_quat* out)
{
*out = dm_quat_scale(quat, scalar);
}
DM_INLINE
dm_quat dm_quat_conjugate(dm_quat quat)
{
return (dm_quat) { -quat.i, -quat.j, -quat.k, quat.r };
}
DM_INLINE
float dm_quat_mag(dm_quat quat)
{
return sqrt((quat.i * quat.i) + (quat.j * quat.j) + (quat.k * quat.k) + (quat.r * quat.r));
}
DM_INLINE
dm_quat dm_quat_norm(dm_quat quat)
{
float mag = dm_quat_mag(quat);
if (mag > 0) return dm_quat_scale(quat, 1.0f / mag);
return quat;
}
DM_INLINE
void dm_quat_norm_inpl(dm_quat quat, dm_quat* out)
{
*out = dm_quat_norm(quat);
}
DM_INLINE
dm_quat dm_quat_inverse(dm_quat quat)
{
dm_quat conj = dm_quat_conjugate(quat);
if (dm_quat_mag(conj) == 1) return conj;
float mag = dm_quat_mag(quat);
return dm_quat_scale(conj, mag * mag);
}
DM_INLINE
void dm_quat_inverse_inpl(dm_quat quat, dm_quat* out)
{
*out = dm_quat_inverse(quat);
}
DM_INLINE
float dm_quat_dot(dm_quat left, dm_quat right)
{
return (left.i * right.i) + (left.j * right.j) + (left.k * right.k) + (left.r + right.r);
}
DM_INLINE
float dm_quat_angle(dm_quat left, dm_quat right)
{
float mag = dm_quat_mag(left) * dm_quat_mag(right);
if (mag == 0) return 0;
float angle = dm_quat_dot(left, right) / mag;
return acos(angle);
}
/*
MAT2
*/
DM_INLINE
dm_mat2 dm_mat2_identity()
{
dm_mat2 result = { 0 };
int N = 2;
for (int i = 0; i < N; i++)
{
result.m[i * (N + 1)] = 1;
}
return result;
}
DM_INLINE
void dm_mat2_identity_inpl(dm_mat2* out)
{
*out = dm_mat2_identity();
}
DM_INLINE
dm_mat2 dm_mat2_transpose(dm_mat2 mat)
{
dm_mat2 result = { 0 };
int N = 2;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = mat.m[j * N + i];
}
}
return result;
}
DM_INLINE
void dm_mat2_inpl(dm_mat2 mat, dm_mat2* out)
{
*out = dm_mat2_transpose(mat);
}
DM_INLINE
dm_mat2 dm_mat2_mul_mat2(dm_mat2 left, dm_mat2 right)
{
dm_mat2 result = { 0 };
#if DM_MATH_COL_MAJ
left = dm_mat2_transpose(left);
#else
right = dm_mat2_transpose(right);
#endif
int N = 2;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = dm_vec2_dot(left.rows[i], right.rows[j]);
}
}
#if DM_MATH_COL_MAJ
result = dm_mat2_transpose(result);
#endif
return result;
}
DM_INLINE
void dm_mat2_mul_mat2_inpl(dm_mat2 left, dm_mat2 right, dm_mat2* out)
{
*out = dm_mat2_mul_mat2(left, right);
}
DM_INLINE
dm_vec2 dm_mat2_mul_vec2(dm_mat2 mat, dm_vec2 vec)
{
dm_vec2 result = { 0 };
#if DM_MATH_COL_MAJ
mat = dm_mat2_transpose(mat);
#endif
int N = 2;
for (int i = 0; i < N; i++)
{
result.v[i] = dm_vec2_dot(mat.rows[i], vec);
}
return result;
}
DM_INLINE
void dm_mat2_mul_vec2_inpl(dm_mat2 mat, dm_vec2 vec, dm_vec2* out)
{
*out = dm_mat2_mul_vec2(mat, vec);
}
DM_INLINE
dm_mat2 dm_mat2_mul_scalar(dm_mat2 mat, float scalar)
{
dm_mat2 result = { 0 };
int N = 2;
for (int i = 0; i < N * N; i++)
{
result.m[i] = mat.m[i] * scalar;
}
return result;
}
DM_INLINE
void dm_mat2_mul_scalar_inpl(dm_mat2 mat, float scalar, dm_mat2* out)
{
*out = dm_mat2_mul_scalar(mat, scalar);
}
DM_INLINE
dm_mat2 dm_mat2_add_mat2(dm_mat2 left, dm_mat2 right)
{
dm_mat2 result = { 0 };
int N = 2;
for (int i = 0; i < N * N; i++)
{
result.m[i] = left.m[i] + right.m[i];
}
return result;
}
DM_INLINE
void dm_mat2_add_mat2_inpl(dm_mat2 left, dm_mat2 right, dm_mat2* out)
{
*out = dm_mat2_add_mat2(left, right);
}
DM_INLINE
dm_mat2 dm_mat2_sub_mat2(dm_mat2 left, dm_mat2 right)
{
dm_mat2 result = { 0 };
int N = 2;
for (int i = 0; i < N * N; i++)
{
result.m[i] = left.m[i] - right.m[i];
}
return result;
}
DM_INLINE
void dm_mat2_sub_mat2_inpl(dm_mat2 left, dm_mat2 right, dm_mat2* out)
{
*out = dm_mat2_sub_mat2(left, right);
}
DM_INLINE
dm_mat2 dm_mat2_inverse(dm_mat2 mat)
{
dm_mat2 result = { 0 };
float det = mat.m[0] * mat.m[3] - mat.m[1] * mat.m[2];
if (det == 0)
{
DM_LOG_WARN("Trying to invert non-invertible 2x2 matrix (determinant is zero)! Returning input matrix...");
return mat;
}
det = 1.0f / det;
int N = 2;
for (int i = 0; i < N; i++)
{
result.m[i] = mat.m[N - i];
}
return dm_mat2_mul_scalar(mat, det);
}
DM_INLINE
void dm_mat2_inverse_inpl(dm_mat2 mat, dm_mat2* out)
{
*out = dm_mat2_inverse(mat);
}
DM_INLINE
float dm_mat2_det(dm_mat2 mat)
{
return (float)(mat.m[0] * mat.m[3] - mat.m[1] * mat.m[2]);
}
/*
MAT3
*/
DM_INLINE
dm_mat3 dm_mat3_identity()
{
dm_mat3 result = { 0 };
int N = 3;
for (int i = 0; i < N; i++)
{
result.m[i * (N + 1)] = 1;
}
return result;
}
DM_INLINE
void dm_mat3_identity_inpl(dm_mat3* out)
{
*out = dm_mat3_identity();
}
DM_INLINE
dm_mat3 dm_mat3_transpose(dm_mat3 mat)
{
dm_mat3 result = { 0 };
int N = 3;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = mat.m[j * N + i];
}
}
return result;
}
DM_INLINE
void dm_mat3_transpose_inpl(dm_mat3 mat, dm_mat3* out)
{
*out = dm_mat3_transpose(mat);
}
DM_INLINE
dm_mat3 dm_mat3_mul_mat3(dm_mat3 left, dm_mat3 right)
{
dm_mat3 result = { 0 };
#if DM_MATH_COL_MAJ
left = dm_mat3_transpose(left);
#else
right = dm_mat3_transpose(right);
#endif
int N = 3;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = dm_vec3_dot(left.rows[i], right.rows[j]);
}
}
#if DM_MATH_COL_MAJ
result = dm_mat3_transpose(result);
#endif
return result;
}
DM_INLINE
void dm_mat3_mul_mat3_inpl(dm_mat3 left, dm_mat3 right, dm_mat3* out)
{
*out = dm_mat3_mul_mat3(left, right);
}
DM_INLINE
dm_vec3 dm_mat3_mul_vec3(dm_mat3 mat, dm_vec3 vec)
{
dm_vec3 result = { 0 };
#if DM_MATH_COL_MAJ
mat = dm_mat3_transpose(mat);
#endif
int N = 3;
for (int i = 0; i < N; i++)
{
result.v[i] = dm_vec3_dot(mat.rows[i], vec);
}
return result;
}
DM_INLINE
void dm_mat3_mul_vec3_inpl(dm_mat3 mat, dm_vec3 vec, dm_vec3* out)
{
*out = dm_mat3_mul_vec3(mat, vec);
}
DM_INLINE
dm_mat3 dm_mat3_mul_scalar(dm_mat3 mat, float scalar)
{
dm_mat3 result = { 0 };
int N = 3;
for (int i = 0; i < N * N; i++)
{
result.m[i] = mat.m[i] * scalar;
}
return result;
}
DM_INLINE
void dm_mat3_mul_scalar_inpl(dm_mat3 mat, float scalar, dm_mat3* out)
{
*out = dm_mat3_mul_scalar(mat, scalar);
}
DM_INLINE
dm_mat3 dm_mat3_add_mat3(dm_mat3 left, dm_mat3 right)
{
dm_mat3 result = { 0 };
int N = 3;
for (int i = 0; i < N * N; i++)
{
result.m[i] = left.m[i] + right.m[i];
}
return result;
}
DM_INLINE
void dm_mat3_add_mat3_inpl(dm_mat3 left, dm_mat3 right, dm_mat3* out)
{
*out = dm_mat3_add_mat3(left, right);
}
DM_INLINE
dm_mat3 dm_mat3_sub_mat3(dm_mat3 left, dm_mat3 right)
{
return dm_mat3_add_mat3(left, dm_mat3_mul_scalar(right, -1.0f));
}
DM_INLINE
void dm_mat3_sub_mat3_inpl(dm_mat3 left, dm_mat3 right, dm_mat3* out)
{
*out = dm_mat3_sub_mat3(left, right);
}
DM_INLINE
dm_mat2 dm_mat3_minor(dm_mat3 mat, dm_vec2 cols, dm_vec2 rows)
{
int N = 3;
dm_mat2 minor = { 0 };
for (int i = 0; i < 2; i++)
{
int col = (int)cols.v[i];
for (int j = 0; j < 2; j++)
{
int row = (int)rows.v[j];
minor.m[j * 2 + i] = mat.m[row * N + col];
}
}
return minor;
}
DM_INLINE
float dm_mat3_det(dm_mat3 mat)
{
#if DM_MATH_COL_MAJ
mat = dm_mat3_transpose(mat);
#endif
float det1 = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 1, 2 }, (dm_vec2) { 1, 2 }));
float det2 = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 2 }, (dm_vec2) { 1, 2 }));
float det3 = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 1 }, (dm_vec2) { 1, 2 }));
return mat.m[0] * det1 - mat.m[1] * det2 + mat.m[2] * det3;
}
DM_INLINE
dm_mat3 dm_mat3_cofactors(dm_mat3 mat)
{
dm_mat3 result = { 0 };
#if DM_MATH_COL_MAJ
mat = dm_mat3_transpose(mat);
#endif
result.m[0] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 1, 2 }, (dm_vec2) { 1, 2 }));
result.m[1] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 2 }, (dm_vec2) { 1, 2 }));
result.m[2] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 1 }, (dm_vec2) { 1, 2 }));
result.m[3] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 1, 2 }, (dm_vec2) { 0, 2 }));
result.m[4] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 2 }, (dm_vec2) { 0, 2 }));
result.m[5] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 1 }, (dm_vec2) { 0, 2 }));
result.m[6] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 1, 2 }, (dm_vec2) { 0, 1 }));
result.m[7] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 2 }, (dm_vec2) { 0, 1 }));
result.m[8] = dm_mat2_det(dm_mat3_minor(mat, (dm_vec2) { 0, 1 }, (dm_vec2) { 0, 1 }));
return result;
}
DM_INLINE
dm_mat3 dm_mat3_inverse(dm_mat3 mat)
{
dm_mat3 result = { 0 };
float det = dm_mat3_det(mat);
if (det == 0)
{
DM_LOG_WARN("Trying to invert non-invertible 3x3 matrix! Returning input...");
return mat;
}
det = 1.0f / det;
// cofactors
result = dm_mat3_cofactors(mat);
int N = 3;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = powf(-1.0f, (float)(i + j)) * result.m[i * N + j];
}
}
// adjugate
result = dm_mat3_transpose(result);
return dm_mat3_mul_scalar(result, det);
}
DM_INLINE
dm_mat3 dm_mat3_rotation(float radians, dm_vec3 axis)
{
dm_mat3 result = { 0 };
float C = cosf(radians);
float S = sinf(radians);
float t = 1 - C;
result.m[0] = t * axis.x * axis.x + C;
result.m[1] = t * axis.x * axis.y - S * axis.z;
result.m[2] = t * axis.x * axis.z + S * axis.y;
result.m[3] = t * axis.x * axis.y + S * axis.z;
result.m[4] = t * axis.y * axis.y + C;
result.m[5] = t * axis.y * axis.z - S * axis.x;
result.m[6] = t * axis.x * axis.z - S * axis.y;
result.m[7] = t * axis.y * axis.z + S * axis.x;
result.m[8] = t * axis.z * axis.z + C;
#if DM_MATH_COL_MAJ
result = dm_mat3_transpose(result);
#endif
return result;
}
DM_INLINE
void dm_mat3_rotation_inpl(float radians, dm_vec3 axis, dm_mat3* out)
{
*out = dm_mat3_rotation(radians, axis);
}
DM_INLINE
dm_mat3 dm_mat3_rotation_degrees(float degrees, dm_vec3 axis)
{
return dm_mat3_rotation(dm_deg_to_rad(degrees), axis);
}
DM_INLINE
void dm_mat3_rotation_degrees_inpl(float degrees, dm_vec3 axis, dm_mat3* out)
{
*out = dm_mat3_rotation_degrees(degrees, axis);
}
/*
MAT4
*/
DM_INLINE
dm_mat4 dm_mat4_identity()
{
dm_mat4 result = { 0 };
int N = 4;
for (int i = 0; i < N; i++)
{
result.m[i * (N + 1)] = 1;
}
return result;
}
DM_INLINE
void dm_mat4_identity_inpl(dm_mat4* out)
{
*out = dm_mat4_identity();
}
DM_INLINE
dm_mat4 dm_mat4_transpose(dm_mat4 mat)
{
dm_mat4 result = { 0 };
int N = 4;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = mat.m[j * N + i];
}
}
return result;
}
DM_INLINE
void dm_mat4_transpose_inpl(dm_mat4 mat, dm_mat4* out)
{
*out = dm_mat4_transpose(mat);
}
DM_INLINE
dm_mat4 dm_mat4_mul_mat4(dm_mat4 left, dm_mat4 right)
{
dm_mat4 result = { 0 };
right = dm_mat4_transpose(right);
int N = 4;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = dm_vec4_dot(left.rows[i], right.rows[j]);
}
}
return result;
}
DM_INLINE
void dm_mat4_mul_mat4_inpl(dm_mat4 left, dm_mat4 right, dm_mat4* out)
{
*out = dm_mat4_mul_mat4(left, right);
}
DM_INLINE
dm_vec4 dm_mat4_mul_vec4(dm_mat4 mat, dm_vec4 vec)
{
dm_vec4 result = { 0 };
int N = 4;
for (int i = 0; i < N; i++)
{
result.v[i] = dm_vec4_dot(mat.rows[i], vec);
}
return result;
}
DM_INLINE
void dm_mat4_mul_vec4_inpl(dm_mat4 mat, dm_vec4 vec, dm_vec4* out)
{
*out = dm_mat4_mul_vec4(mat, vec);
}
DM_INLINE
dm_vec4 dm_mat4_mul_vec3(dm_mat4 mat, dm_vec3 vec)
{
dm_vec4 new_vec = dm_vec4_set(vec.x, vec.y, vec.z, 1.0f);
return dm_mat4_mul_vec4(mat, new_vec);
}
DM_INLINE
void dm_mat4_mul_vec3_inpl(dm_mat4 mat, dm_vec3 vec, dm_vec4* out)
{
*out = dm_mat4_mul_vec3(mat, vec);
}
DM_INLINE
dm_mat4 dm_mat4_mul_scalar(dm_mat4 mat, float scalar)
{
dm_mat4 result = { 0 };
int N = 4;
for (int i = 0; i < N * N; i++)
{
result.m[i] = mat.m[i] * scalar;
}
return result;
}
DM_INLINE
void dm_mat4_mul_scalar_inpl(dm_mat4 mat, float scalar, dm_mat4* out)
{
*out = dm_mat4_mul_scalar(mat, scalar);
}
DM_INLINE
dm_mat4 dm_mat4_add_mat4(dm_mat4 left, dm_mat4 right)
{
dm_mat4 result = { 0 };
int N = 4;
for (int i = 0; i < N * N; i++)
{
result.m[i] = left.m[i] + right.m[i];
}
return result;
}
DM_INLINE
void dm_mat4_add_mat4_inpl(dm_mat4 left, dm_mat4 right, dm_mat4* out)
{
*out = dm_mat4_add_mat4(left, right);
}
DM_INLINE
dm_mat4 dm_mat4_sub_mat4(dm_mat4 left, dm_mat4 right)
{
dm_mat4 result = { 0 };
int N = 4;
for (int i = 0; i < N * N; i++)
{
result.m[i] = left.m[i] - right.m[i];
}
return result;
}
DM_INLINE
void dm_mat4_sub_mat4_inpl(dm_mat4 left, dm_mat4 right, dm_mat4* out)
{
*out = dm_mat4_sub_mat4(left, right);
}
DM_INLINE
dm_mat3 dm_mat4_minor(dm_mat4 mat, dm_vec3 cols, dm_vec3 rows)
{
int N = 4;
dm_mat3 minor = { 0 };
for (int i = 0; i < 3; i++)
{
int col = (int)cols.v[i];
for (int j = 0; j < 3; j++)
{
int row = (int)rows.v[j];
minor.m[j * 3 + i] = mat.m[row * N + col];
}
}
return minor;
}
DM_INLINE
float dm_mat4_det(dm_mat4 mat)
{
float det1 = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 1, 2, 3 }, (dm_vec3) { 1, 2, 3 }));
float det2 = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 2, 3 }, (dm_vec3) { 1, 2, 3 }));
float det3 = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 3 }, (dm_vec3) { 1, 2, 3 }));
float det4 = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 2 }, (dm_vec3) { 1, 2, 3 }));
return mat.m[0] * det1 - mat.m[1] * det2 + mat.m[2] * det3 - mat.m[3] * det4;
}
DM_INLINE
dm_mat4 dm_mat4_cofactors(dm_mat4 mat)
{
dm_mat4 result = { 0 };
result.m[0] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 1, 2, 3 }, (dm_vec3) { 1, 2, 3 }));
result.m[1] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 2, 3 }, (dm_vec3) { 1, 2, 3 }));
result.m[2] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 3 }, (dm_vec3) { 1, 2, 3 }));
result.m[3] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 2 }, (dm_vec3) { 1, 2, 3 }));
result.m[4] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 1, 2, 3 }, (dm_vec3) { 0, 2, 3 }));
result.m[5] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 2, 3 }, (dm_vec3) { 0, 2, 3 }));
result.m[6] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 3 }, (dm_vec3) { 0, 2, 3 }));
result.m[7] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 2 }, (dm_vec3) { 0, 2, 3 }));
result.m[8] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 1, 2, 3 }, (dm_vec3) { 0, 1, 3 }));
result.m[9] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 2, 3 }, (dm_vec3) { 0, 1, 3 }));
result.m[10] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 3 }, (dm_vec3) { 0, 1, 3 }));
result.m[11] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 2 }, (dm_vec3) { 0, 1, 3 }));
result.m[12] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 1, 2, 3 }, (dm_vec3) { 0, 1, 2 }));
result.m[13] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 2, 3 }, (dm_vec3) { 0, 1, 2 }));
result.m[14] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 3 }, (dm_vec3) { 0, 1, 2 }));
result.m[15] = dm_mat3_det(dm_mat4_minor(mat, (dm_vec3) { 0, 1, 2 }, (dm_vec3) { 0, 1, 2 }));
return result;
}
DM_INLINE
dm_mat4 dm_mat4_inverse(dm_mat4 mat)
{
dm_mat4 result = { 0 };
float det = dm_mat4_det(mat);
if (det == 0)
{
DM_LOG_WARN("Trying to invert non-invertible 4x4 matrix! Returning input...");
return mat;
}
det = 1.0f / det;
// cofactors
result = dm_mat4_cofactors(mat);
int N = 4;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
result.m[i * N + j] = powf(-1.0f, (float)(i + j)) * result.m[i * N + j];
}
}
// adjugate
result = dm_mat4_transpose(result);
return dm_mat4_mul_scalar(result, det);
}
DM_INLINE
bool dm_mat4_is_equal(dm_mat4 left, dm_mat4 right)
{
int N = 4;
for (int i = 0; i < N * N; i++)
{
if (left.m[i] != right.m[i]) return false;
}
return true;
}
DM_INLINE
dm_mat4 dm_mat4_from_mat3(dm_mat3 mat)
{
dm_mat4 result = { 0 };
for (int i = 0; i < 3; i++)
{
result.rows[i] = dm_vec4_set_from_vec3(mat.rows[i]);
}
return result;
}
/*
MATTRANSFORMS
*/
DM_INLINE
dm_mat4 dm_mat_scale_make(dm_vec3 scale)
{
dm_mat4 result = dm_mat4_identity();
result.m[0] = scale.x;
result.m[5] = scale.y;
result.m[10] = scale.z;
return result;
}
DM_INLINE
dm_mat4 dm_mat_rotation_make(float radians, dm_vec3 axis)
{
if (dm_vec3_len(axis) != 1)
{
axis = dm_vec3_norm(axis);
}
dm_mat4 result = { 0 };
dm_mat3 rotation = dm_mat3_rotation(radians, axis);
result = dm_mat4_from_mat3(rotation);
result.m[15] = 1;
return result;
}
DM_INLINE
dm_mat4 dm_mat_rotation_degrees_make(float degrees, dm_vec3 axis)
{
return dm_mat_rotation_make(dm_deg_to_rad(degrees), axis);
}
DM_INLINE
dm_mat4 dm_mat_translate_make(dm_vec3 translation)
{
dm_mat4 result = dm_mat4_identity();
result.rows[3] = dm_vec4_set(translation.x, translation.y, translation.z, 1.0f);
return result;
}
DM_INLINE
dm_mat4 dm_mat_translate(dm_mat4 mat, dm_vec3 translation)
{
dm_mat4 result = mat;
result.rows[3].x = translation.x;
result.rows[3].y = translation.y;
result.rows[3].z = translation.z;
return result;
}
DM_INLINE
void dm_mat_translate_inpl(dm_mat4 mat, dm_vec3 translation, dm_mat4* out)
{
*out = dm_mat_translate(mat, translation);
}
DM_INLINE
dm_mat4 dm_mat_scale(dm_mat4 mat, dm_vec3 scale)
{
dm_mat4 result = mat;
result.rows[0] = dm_vec4_scale(result.rows[0], scale.x);
result.rows[1] = dm_vec4_scale(result.rows[1], scale.y);
result.rows[2] = dm_vec4_scale(result.rows[2], scale.z);
return result;
}
DM_INLINE
void dm_mat_scale_inpl(dm_mat4 mat, dm_vec3 scale, dm_mat4* out)
{
*out = dm_mat_scale(mat, scale);
}
DM_INLINE
dm_mat4 dm_mat_rotate(dm_mat4 mat, float radians, dm_vec3 axis)
{
dm_mat4 rotation = dm_mat_rotation_make(radians, axis);
return dm_mat4_mul_mat4(mat, rotation);
}
DM_INLINE
void dm_mat_rotate_inpl(dm_mat4 mat, float radians, dm_vec3 axis, dm_mat4* out)
{
*out = dm_mat_rotate(mat, radians, axis);
}
DM_INLINE
dm_mat4 dm_mat_rotate_degrees(dm_mat4 mat, float degrees, dm_vec3 axis)
{
return dm_mat_rotate(mat, dm_deg_to_rad(degrees), axis);
}
DM_INLINE
void dm_mat_rotate_degrees_inpl(dm_mat4 mat, float degrees, dm_vec3 axis, dm_mat4* out)
{
*out = dm_mat_rotate_degrees(mat, degrees, axis);
}
DM_INLINE
dm_mat4 dm_mat_view(dm_vec3 view_origin, dm_vec3 target, dm_vec3 up)
{
//if (dm_vec3_len(up) != 1) up = dm_vec3_norm(up);
dm_vec3 w = dm_vec3_sub_vec3(target, view_origin);
w = dm_vec3_norm(w);
dm_vec3 u = dm_vec3_cross(w, up);
u = dm_vec3_norm(u);
dm_vec3 v = dm_vec3_cross(u, w);
dm_mat4 view = { 0 };
view.rows[0] = (dm_vec4){ u.x, v.x, -w.x, 0 };
view.rows[1] = (dm_vec4){ u.y, v.y, -w.y, 0 };
view.rows[2] = (dm_vec4){ u.z, v.z, -w.z, 0 };
view.rows[3] = (dm_vec4){
-dm_vec3_dot(view_origin, u),
-dm_vec3_dot(view_origin, v),
dm_vec3_dot(view_origin, w),
1
};
return view;
}
DM_INLINE
dm_mat4 dm_mat_perspective(float fov, float aspect_ratio, float n, float f)
{
dm_mat4 projection = { 0 };
float t = 1.0f / tanf(fov * 0.5f);
float fn = 1.0f / (n - f);
projection.m[0] = t / aspect_ratio;
projection.m[5] = t;
projection.m[10] = (f + n) * fn;
projection.m[11] = -1.0f;
projection.m[14] = 2.0f * n * f * fn;
return projection;
}
DM_INLINE
dm_mat4 dm_mat_ortho(float left, float right, float bottom, float top, float n, float f)
{
dm_mat4 ortho = { 0 };
ortho.m[0] = 2.0f / (right - left);
ortho.m[5] = 2.0f / (top - bottom);
ortho.m[10] = -2.0f / (f - n);
ortho.m[12] = -(right + left) / (right - left);
ortho.m[13] = -(top + bottom) / (top - bottom);
ortho.m[14] = -(f + n) / (f - n);
ortho.m[15] = 1.0f;
return ortho;
}
#endif | 19.945798 | 113 | 0.665445 |
a2ceb7bc6af031396ab9c8341b73bd0a78a81600 | 6,684 | c | C | data/builder/builder_level.c | kth-is1200-grupp-47/chip-escape | 3fcf11d556fa8ac2e05dbcc26499977c211593d3 | [
"MIT"
] | null | null | null | data/builder/builder_level.c | kth-is1200-grupp-47/chip-escape | 3fcf11d556fa8ac2e05dbcc26499977c211593d3 | [
"MIT"
] | null | null | null | data/builder/builder_level.c | kth-is1200-grupp-47/chip-escape | 3fcf11d556fa8ac2e05dbcc26499977c211593d3 | [
"MIT"
] | null | null | null | /* Written by Hannes Mann */
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include "game/level.h"
#define STBI_ONLY_PNG
#include "stb/stb_image.h"
/* Temporary output file name */
#define TMP_OUTPUT_FORMAT "%s.data"
/* ld command format for sprintf */
#define LD_FORMAT "$LD -r -b binary -o %s %s"
uint32_t get_image_color_at(uint8_t* image, int x, int y, int iw, int ih) {
/* Outside image */
if(x < 0 || y < 0 || x >= iw || y >= ih) {
return 0;
}
int input_pos = (y * iw + x) * 4;
uint32_t color = image[input_pos + 3] ? 255 : 0 /* A */;
color |= (image[input_pos + 2] << 8) /* B */;
color |= (image[input_pos + 1] << 16) /* G */;
color |= (image[input_pos] << 24) /* R */;
return color;
}
void write_tile(uint8_t* input, uint8_t* output, uint32_t color, int x, int y, int iw, int ih) {
/* Is pixel not transparent? */
if(color & 255) {
/* Match pixel color with tile id */
switch(color) {
/* Ground */
case 0xffffffff: {
*output = TILE_ID_GROUND;
int offset_x = 1;
int offset_y = 0;
bool empty_left = get_image_color_at(input, x - 1, y, iw, ih) != color;
bool empty_right = get_image_color_at(input, x + 1, y, iw, ih) != color;
bool empty_top = get_image_color_at(input, x, y - 1, iw, ih) != color;
bool empty_bottom = get_image_color_at(input, x, y + 1, iw, ih) != color;
/* No ground tile to the left? */
if(empty_left && x > 0) {
offset_x = 0;
}
/* No ground tile to the right? */
if(empty_right && x < iw - 1) {
/* If previous statement is also true */
if(offset_x == 0) {
offset_x = 1;
offset_y = 1;
}
else {
offset_x = 2;
}
}
/* Tile above us? */
if(!empty_top && y > 0) {
offset_y++;
if(!empty_left && !empty_right) {
offset_x = 3; /* draw nothing */
offset_y = 3;
}
if(x == 0 || x == iw - 1) {
offset_x = 3; /* draw nothing */
offset_y = 3;
}
}
/* Tile below us? */
if(empty_bottom && y < ih - 1) {
offset_x = 3;
if(empty_left) {
offset_y = 0;
}
else if(empty_right) {
offset_y = 1;
}
else {
offset_y = 2;
}
}
/* TODO: slope */
*output |= offset_x << 4;
*output |= offset_y << 6;
break;
}
/* Player */
case 0xff0000ff:
*output = TILE_ID_PLAYER;
break;
/* Platforms */
case 0x00ff00ff:
case 0x008000ff:
bool falling = color == 0x008000ff;
/* Platform already read - skip this pixel */
if(get_image_color_at(input, x - 1, y, iw, ih) == color) {
break;
}
/* Find neighbor pixels */
if(get_image_color_at(input, x + 1, y, iw, ih) == color) {
*output = TILE_ID_PLATFORM;
/* Set bits for platform */
if(falling) {
*output |= TILE_PLATFORM_BIT_FALL << 4;
}
/* Is big platform? */
if(get_image_color_at(input, x + 2, y, iw, ih) == color) {
*output |= TILE_PLATFORM_BIT_BIG << 4;
}
else {
*output |= TILE_PLATFORM_BIT_SMALL << 4;
}
}
else {
printf("builder_image: Platform too small at %d %d\n", x, y);
exit(1);
}
break;
/* Hazard */
case 0x0000ffff:
case 0x0080ffff: {
*output = TILE_ID_HAZARD;
int offset_x = color == 0x0080ffff;
int offset_y = 0;
*output |= offset_x << 4;
*output |= offset_y << 6;
break;
}
/* Bits */
case 0x878700ff:
case 0xafaf00ff:
case 0xd7d700ff:
case 0xffff00ff: {
*output = TILE_ID_BITS;
uint8_t bit_count = 1;
if(color == 0xafaf00ff) { bit_count = 2; }
if(color == 0xd7d700ff) { bit_count = 3; }
if(color == 0xffff00ff) { bit_count = 4; }
*output |= bit_count << 4;
break;
}
/* Metal Block */
case 0x808080ff:
*output = TILE_ID_METAL_BLOCK;
break;
case 0xff00ffff:
*output = TILE_ID_FLAG;
/* This is the lower part of the flag */
if(get_image_color_at(input, x, y - 1, iw, ih) == color) {
*output |= 1 << 4;
}
break;
case 0x00ffffff:
*output = TILE_ID_ENEMY_ELECTRICITY;
break;
case 0xaaff00ff:
*output = TILE_ID_ENEMY_SLIME;
break;
default:
printf("builder_image: Unknown tile type 0x%x at %d %d\n", color, x, y);
exit(1);
}
}
}
/* Based on build_image_object */
void build_level_object(const char* input, const char* output) {
int w, h, n;
/* File being loaded */
uint8_t* input_bytes = stbi_load(input, &w, &h, &n, 4);
if(!input_bytes) {
printf("builder_image: stb error %s\n", stbi_failure_reason());
exit(1);
}
if(w < 128 / 8 || h < 32 / 8) {
printf("builder_image: Level is too small! Width: %d, Height: %d\n", w, h);
exit(1);
}
if(w > UINT16_MAX || h > UINT16_MAX) {
printf("builder_image: Level is too big! Width: %d, Height: %d\n", w, h);
exit(1);
}
/* File being written */
int total_bits = sizeof(uint16_t) * 8 * 2 /* w+h */ + sizeof(LevelTile) * 8 * w * h /* x bits per tile */;
int required_bytes = total_bits / 8 + (total_bits % 8 != 0);
uint8_t* output_bytes = malloc(required_bytes);
/* Set all tiles to TILE_ID_NONE by default */
memset(output_bytes, 0, required_bytes);
/* Set first four bytes to size */
uint16_t* output_as_short = (uint16_t*)output_bytes;
output_as_short[0] = w;
output_as_short[1] = h;
int current_byte = 4;
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
int input_pos = (y * w + x) * 4;
/* Assert that we're not reading past the end of the input image */
assert(input_pos + 3 < w * h * 4 /* four bits per pixel */);
/* Assert that we're not writing past the end of the output data */
assert(current_byte < required_bytes);
uint32_t color = get_image_color_at(input_bytes, x, y, w, h);
write_tile(input_bytes, output_bytes + current_byte++, color, x, y, w, h);
}
}
char* tmp_output_name = malloc(strlen(TMP_OUTPUT_FORMAT) + strlen(input) + 1);
sprintf(tmp_output_name, TMP_OUTPUT_FORMAT, input);
/* Create a temporary output file in /tmp to use as argument for ld */
FILE* tmp_output_file = fopen(tmp_output_name, "wb");
fwrite(output_bytes, sizeof(uint8_t), required_bytes, tmp_output_file);
fclose(tmp_output_file);
/* Create the ld command to embed the data in an object file that will be linked to the final binary */
char* command = malloc(strlen(LD_FORMAT) + strlen(tmp_output_name) + strlen(output) + 1);
sprintf(command, LD_FORMAT, output, tmp_output_name);
/* Execute command and delete temporary output file */
system(command);
unlink(tmp_output_name);
free(tmp_output_name);
free(command);
free(output_bytes);
stbi_image_free(input_bytes);
} | 24.755556 | 107 | 0.598893 |
861a1aaf23bcc4d08ac3c8b84013fc977c8608d7 | 675 | c | C | SoftC/10/adj.c | her0m31/Studys | f765310cd826356af04008a055905cade21fda4a | [
"MIT"
] | null | null | null | SoftC/10/adj.c | her0m31/Studys | f765310cd826356af04008a055905cade21fda4a | [
"MIT"
] | null | null | null | SoftC/10/adj.c | her0m31/Studys | f765310cd826356af04008a055905cade21fda4a | [
"MIT"
] | null | null | null | /* adj.c */
#include <gtk/gtk.h>
#include <stdio.h>
#define NODES 9
int main()
{
FILE *fp;
int i, j;
int adj[NODES][NODES];
for(i = 0; i < NODES; i++){
for(j = 0; j < NODES; j ++)
adj[i][j] = 0;
}
fp = fopen("graph1.dat", "r");
if (fp == NULL) {
fprintf(stderr, "Can't open file: graph1.dat\n");
return -1;
}
while( fscanf(fp, "%d %d", &i, &j) != EOF ){
adj[i][j] = 1;
adj[j][i] = 1;
}
printf(" | 0 1 2 3 4 5 6 7 8\n");
printf("----------------------\n");
for(i = 0; i < NODES; i++){
printf("%d |", i);
for(j = 0; j < NODES; j ++)
printf(" %d", adj[i][j]);
printf("\n");
}
return 0;
}
| 16.875 | 53 | 0.425185 |
d822f0661f2bd7b548878853a8a8aa320e0813ce | 17,675 | c | C | Platform/RaspberryPi/RPi3/Drivers/DisplayDxe/DisplayDxe.c | andreiw/lampone-edk2-platforms | 0d5a9b9e01b1fd5084276b60a49980bdfb00cc94 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"BSD-2-Clause-Patent",
"BSD-3-Clause"
] | 5 | 2019-10-17T17:17:36.000Z | 2021-07-06T01:56:51.000Z | Platform/RaspberryPi/RPi3/Drivers/DisplayDxe/DisplayDxe.c | andreiw/lampone-edk2-platforms | 0d5a9b9e01b1fd5084276b60a49980bdfb00cc94 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"BSD-2-Clause-Patent",
"BSD-3-Clause"
] | null | null | null | Platform/RaspberryPi/RPi3/Drivers/DisplayDxe/DisplayDxe.c | andreiw/lampone-edk2-platforms | 0d5a9b9e01b1fd5084276b60a49980bdfb00cc94 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"BSD-2-Clause-Patent",
"BSD-3-Clause"
] | 2 | 2021-06-18T13:41:39.000Z | 2021-09-19T12:09:05.000Z | /** @file
*
* Copyright (c) 2017-2018, Andrei Warkentin <andrey.warkentin@gmail.com>
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*
**/
#include <Base.h>
#include "DisplayDxe.h"
#define POS_TO_FB(posX, posY) ((UINT8*) \
((UINTN)This->Mode->FrameBufferBase + \
(posY) * This->Mode->Info->PixelsPerScanLine * \
PI3_BYTES_PER_PIXEL + \
(posX) * PI3_BYTES_PER_PIXEL))
#define MODE_800_ENABLED BIT0
#define MODE_640_ENABLED BIT1
#define MODE_1024_ENABLED BIT2
#define MODE_720P_ENABLED BIT3
#define MODE_1080P_ENABLED BIT4
#define MODE_NATIVE_ENABLED BIT5
#define JUST_NATIVE_ENABLED MODE_NATIVE_ENABLED
#define ALL_MODES (BIT6 - 1)
STATIC
EFI_STATUS
EFIAPI
DriverSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
STATIC
EFI_STATUS
EFIAPI
DriverStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
STATIC
EFI_STATUS
EFIAPI
DriverStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
);
STATIC
EFI_STATUS
EFIAPI
DisplayQueryMode (
IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
IN UINT32 ModeNumber,
OUT UINTN *SizeOfInfo,
OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
);
STATIC
EFI_STATUS
EFIAPI
DisplaySetMode (
IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
IN UINT32 ModeNumber
);
STATIC
EFI_STATUS
EFIAPI
DisplayBlt (
IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
IN UINTN SourceX,
IN UINTN SourceY,
IN UINTN DestinationX,
IN UINTN DestinationY,
IN UINTN Width,
IN UINTN Height,
IN UINTN Delta OPTIONAL
);
STATIC EFI_DRIVER_BINDING_PROTOCOL mDriverBinding = {
DriverSupported,
DriverStart,
DriverStop,
0xa,
NULL,
NULL
};
typedef struct {
VENDOR_DEVICE_PATH DisplayDevicePath;
EFI_DEVICE_PATH EndDevicePath;
} DISPLAY_DEVICE_PATH;
typedef struct {
UINT32 Width;
UINT32 Height;
} GOP_MODE_DATA;
STATIC UINT32 mBootWidth;
STATIC UINT32 mBootHeight;
STATIC EFI_HANDLE mDevice;
STATIC RASPBERRY_PI_FIRMWARE_PROTOCOL *mFwProtocol;
STATIC EFI_CPU_ARCH_PROTOCOL *mCpu;
STATIC GOP_MODE_DATA mGopModeTemplate[] = {
{ 800, 600 }, /* Legacy */
{ 640, 480 }, /* Legacy */
{ 1024, 768 }, /* Legacy */
{ 1280, 720 }, /* 720p */
{ 1920, 1080 }, /* 1080p */
{ 0, 0 }, /* Physical */
};
STATIC UINTN mLastMode;
STATIC GOP_MODE_DATA mGopModeData[ARRAY_SIZE(mGopModeTemplate)];
STATIC DISPLAY_DEVICE_PATH mDisplayProtoDevicePath =
{
{
{
HARDWARE_DEVICE_PATH,
HW_VENDOR_DP,
{
(UINT8)(sizeof (VENDOR_DEVICE_PATH)),
(UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8),
}
},
EFI_CALLER_ID_GUID,
},
{
END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE,
{
sizeof (EFI_DEVICE_PATH_PROTOCOL),
0
}
}
};
#define PI3_BITS_PER_PIXEL (32)
#define PI3_BYTES_PER_PIXEL (PI3_BITS_PER_PIXEL / 8)
EFI_GRAPHICS_OUTPUT_PROTOCOL gDisplayProto = {
DisplayQueryMode,
DisplaySetMode,
DisplayBlt,
NULL
};
STATIC
EFI_STATUS
EFIAPI
DisplayQueryMode (
IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
IN UINT32 ModeNumber,
OUT UINTN *SizeOfInfo,
OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
)
{
EFI_STATUS Status;
GOP_MODE_DATA *Mode;
if (ModeNumber > mLastMode) {
return EFI_INVALID_PARAMETER;
}
Status = gBS->AllocatePool (
EfiBootServicesData,
sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION),
(VOID**)Info
);
if (EFI_ERROR (Status)) {
return Status;
}
Mode = &mGopModeData[ModeNumber];
*SizeOfInfo = sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
(*Info)->Version = This->Mode->Info->Version;
(*Info)->HorizontalResolution = Mode->Width;
(*Info)->VerticalResolution = Mode->Height;
(*Info)->PixelFormat = This->Mode->Info->PixelFormat;
(*Info)->PixelsPerScanLine = Mode->Width;
return EFI_SUCCESS;
}
STATIC
VOID
ClearScreen (
IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This
)
{
EFI_GRAPHICS_OUTPUT_BLT_PIXEL Fill;
Fill.Red = 0x00;
Fill.Green = 0x00;
Fill.Blue = 0x00;
This->Blt (This, &Fill, EfiBltVideoFill,
0, 0, 0, 0, This->Mode->Info->HorizontalResolution,
This->Mode->Info->VerticalResolution,
This->Mode->Info->HorizontalResolution *
sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL));
}
STATIC
EFI_STATUS
EFIAPI
DisplaySetMode (
IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
IN UINT32 ModeNumber
)
{
UINTN FbSize;
UINTN FbPitch;
EFI_STATUS Status;
EFI_PHYSICAL_ADDRESS FbBase;
GOP_MODE_DATA *Mode = &mGopModeData[ModeNumber];
if (ModeNumber > mLastMode) {
return EFI_UNSUPPORTED;
}
DEBUG ((DEBUG_INFO, "Setting mode %u from %u: %u x %u\n",
ModeNumber, This->Mode->Mode, Mode->Width, Mode->Height));
Status = mFwProtocol->GetFB (Mode->Width, Mode->Height,
PI3_BITS_PER_PIXEL, &FbBase,
&FbSize, &FbPitch);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "Could not set mode %u\n", ModeNumber));
return EFI_DEVICE_ERROR;
}
DEBUG ((DEBUG_INFO, "Mode %u: %u x %u framebuffer is %u bytes at %p\n",
ModeNumber, Mode->Width, Mode->Height, FbSize, FbBase));
if (FbPitch / PI3_BYTES_PER_PIXEL != Mode->Width) {
DEBUG ((DEBUG_ERROR, "Error: Expected width %u, got width %u\n",
Mode->Width, FbPitch / PI3_BYTES_PER_PIXEL));
return EFI_DEVICE_ERROR;
}
/*
* WT, because certain OS loaders access the frame buffer directly
* and we don't want to see corruption due to missing WB cache
* maintenance. Performance with WT is good.
*/
Status = mCpu->SetMemoryAttributes (mCpu, FbBase,
ALIGN_VALUE (FbSize, EFI_PAGE_SIZE),
EFI_MEMORY_WT);
if (Status != EFI_SUCCESS) {
DEBUG ((DEBUG_ERROR, "Couldn't set framebuffer attributes: %r\n", Status));
return Status;
}
This->Mode->Mode = ModeNumber;
This->Mode->Info->Version = 0;
This->Mode->Info->HorizontalResolution = Mode->Width;
This->Mode->Info->VerticalResolution = Mode->Height;
/*
* NOTE: Windows REQUIRES BGR in 32 or 24 bit format.
*/
This->Mode->Info->PixelFormat = PixelBlueGreenRedReserved8BitPerColor;
This->Mode->Info->PixelsPerScanLine = Mode->Width;
This->Mode->SizeOfInfo = sizeof (*This->Mode->Info);
This->Mode->FrameBufferBase = FbBase;
This->Mode->FrameBufferSize = FbSize;
ClearScreen (This);
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
EFIAPI
DisplayBlt (
IN EFI_GRAPHICS_OUTPUT_PROTOCOL *This,
IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, OPTIONAL
IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation,
IN UINTN SourceX,
IN UINTN SourceY,
IN UINTN DestinationX,
IN UINTN DestinationY,
IN UINTN Width,
IN UINTN Height,
IN UINTN Delta OPTIONAL
)
{
UINT8 *VidBuf, *BltBuf, *VidBuf1;
UINTN i;
switch (BltOperation) {
case EfiBltVideoFill:
BltBuf = (UINT8*)BltBuffer;
for (i = 0; i < Height; i++) {
VidBuf = POS_TO_FB (DestinationX, DestinationY + i);
SetMem32 (VidBuf, Width * PI3_BYTES_PER_PIXEL, *(UINT32*)BltBuf);
}
break;
case EfiBltVideoToBltBuffer:
if (Delta == 0) {
Delta = Width * PI3_BYTES_PER_PIXEL;
}
for (i = 0; i < Height; i++) {
VidBuf = POS_TO_FB (SourceX, SourceY + i);
BltBuf = (UINT8*)((UINTN)BltBuffer + (DestinationY + i) * Delta +
DestinationX * PI3_BYTES_PER_PIXEL);
gBS->CopyMem ((VOID*)BltBuf, (VOID*)VidBuf, PI3_BYTES_PER_PIXEL * Width);
}
break;
case EfiBltBufferToVideo:
if (Delta == 0) {
Delta = Width * PI3_BYTES_PER_PIXEL;
}
for (i = 0; i < Height; i++) {
VidBuf = POS_TO_FB (DestinationX, DestinationY + i);
BltBuf = (UINT8*)((UINTN)BltBuffer + (SourceY + i) * Delta +
SourceX * PI3_BYTES_PER_PIXEL);
gBS->CopyMem ((VOID*)VidBuf, (VOID*)BltBuf, Width * PI3_BYTES_PER_PIXEL);
}
break;
case EfiBltVideoToVideo:
for (i = 0; i < Height; i++) {
VidBuf = POS_TO_FB (SourceX, SourceY + i);
VidBuf1 = POS_TO_FB (DestinationX, DestinationY + i);
gBS->CopyMem ((VOID*)VidBuf1, (VOID*)VidBuf, Width * PI3_BYTES_PER_PIXEL);
}
break;
default:
ASSERT_EFI_ERROR (EFI_SUCCESS);
break;
}
return EFI_SUCCESS;
}
/**
Initialize the state information for the Display Dxe
@param ImageHandle of the loaded driver
@param SystemTable Pointer to the System Table
@retval EFI_SUCCESS Protocol registered
@retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
@retval EFI_DEVICE_ERROR Hardware problems
**/
EFI_STATUS
EFIAPI
DisplayDxeInitialize (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
Status = gBS->LocateProtocol (&gRaspberryPiFirmwareProtocolGuid, NULL,
(VOID**)&mFwProtocol);
ASSERT_EFI_ERROR (Status);
if (EFI_ERROR (Status)) {
return Status;
}
Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL,
(VOID**)&mCpu);
ASSERT_EFI_ERROR (Status);
if (EFI_ERROR (Status)) {
return Status;
}
// Query the current display resolution from mailbox
Status = mFwProtocol->GetFBSize (&mBootWidth, &mBootHeight);
if (EFI_ERROR (Status)) {
return Status;
}
DEBUG ((DEBUG_INFO, "Display boot mode is %u x %u\n",
mBootWidth, mBootHeight));
Status = gBS->InstallMultipleProtocolInterfaces (
&mDevice, &gEfiDevicePathProtocolGuid,
&mDisplayProtoDevicePath, &gEfiCallerIdGuid,
NULL, NULL);
ASSERT_EFI_ERROR (Status);
if (EFI_ERROR (Status)) {
return Status;
}
Status = EfiLibInstallDriverBindingComponentName2 (
ImageHandle,
SystemTable,
&mDriverBinding,
ImageHandle,
&gComponentName,
&gComponentName2
);
ASSERT_EFI_ERROR (Status);
if (EFI_ERROR (Status)) {
return Status;
}
return Status;
}
STATIC
EFI_STATUS
EFIAPI
DriverSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
{
VOID *Temp;
if (Controller != mDevice) {
return EFI_UNSUPPORTED;
}
if (gBS->HandleProtocol (Controller, &gEfiGraphicsOutputProtocolGuid,
(VOID**)&Temp) == EFI_SUCCESS) {
return EFI_ALREADY_STARTED;
}
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
EFIAPI
DriverStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
{
UINTN Index;
UINTN TempIndex;
EFI_STATUS Status;
VOID *Dummy;
Status = gBS->OpenProtocol (
Controller,
&gEfiCallerIdGuid,
(VOID**)&Dummy,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_BY_DRIVER
);
if (EFI_ERROR (Status)) {
return Status;
}
gDisplayProto.Mode = AllocateZeroPool (sizeof (EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE));
if (gDisplayProto.Mode == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Done;
}
gDisplayProto.Mode->Info = AllocateZeroPool (sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION));
if (gDisplayProto.Mode->Info == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Done;
}
PcdSet8(PcdDisplayEnableScaledVModes,
PcdGet8(PcdDisplayEnableScaledVModes) & ALL_MODES);
if (PcdGet8(PcdDisplayEnableScaledVModes) == 0) {
PcdSet8(PcdDisplayEnableScaledVModes, JUST_NATIVE_ENABLED);
}
mLastMode = 0;
for (TempIndex = 0, Index = 0;
TempIndex < ARRAY_SIZE(mGopModeTemplate); TempIndex++) {
if ((PcdGet8(PcdDisplayEnableScaledVModes) & (1 << TempIndex)) != 0) {
DEBUG((EFI_D_ERROR, "Mode %u: %u x %u present\n",
TempIndex, mGopModeTemplate[TempIndex].Width,
mGopModeTemplate[TempIndex].Height));
CopyMem(&mGopModeData[Index], &mGopModeTemplate[TempIndex],
sizeof (GOP_MODE_DATA));
mLastMode = Index;
Index++;
}
}
if (PcdGet8(PcdDisplayEnableScaledVModes) == JUST_NATIVE_ENABLED) {
/*
* mBootWidth x mBootHeight may not be sensible,
* so clean it up, since we won't be adding
* any other extra vmodes.
*/
if (mBootWidth < 640 || mBootHeight < 480) {
/*
* At least 640x480. Hardware will downscale as required.
*/
mBootWidth = 640;
mBootHeight = 480;
} else if (mBootWidth == 800 && mBootHeight == 480) {
/*
* The Pi 7" screen is close to 800x600, just pretend it is.
* The hardware will perform the required scaling and it won't
* look that bad.
*/
mBootHeight = 600;
}
}
if ((PcdGet8(PcdDisplayEnableScaledVModes) & MODE_NATIVE_ENABLED) != 0) {
/*
* Adjust actual native res only if enabled native res (so
* last mode is native res).
*/
mGopModeData[mLastMode].Width = mBootWidth;
mGopModeData[mLastMode].Height = mBootHeight;
}
for (Index = 0; Index <= mLastMode; Index++) {
UINTN FbSize;
UINTN FbPitch;
EFI_PHYSICAL_ADDRESS FbBase;
GOP_MODE_DATA *Mode = &mGopModeData[Index];
Status = mFwProtocol->GetFB (Mode->Width, Mode->Height,
PI3_BITS_PER_PIXEL, &FbBase,
&FbSize, &FbPitch);
if (EFI_ERROR (Status)) {
goto Done;
}
//
// There is no way to communicate pitch back to OS. OS and even UEFI
// expect a fully linear frame buffer. So the width should
// be based on the frame buffer's pitch value. In some cases VC
// firmware would allocate ao frame buffer with some padding
// presumably to be 8 byte align.
//
Mode->Width = FbPitch / PI3_BYTES_PER_PIXEL;
DEBUG ((DEBUG_INFO, "Mode %u: %u x %u framebuffer is %u bytes at %p\n",
Index, Mode->Width, Mode->Height, FbSize, FbBase));
ASSERT (FbPitch != 0);
ASSERT (FbBase != 0);
ASSERT (FbSize != 0);
}
// Both set the mode and initialize current mode information.
gDisplayProto.Mode->MaxMode = mLastMode + 1;
DisplaySetMode (&gDisplayProto, 0);
Status = gBS->InstallMultipleProtocolInterfaces (
&Controller, &gEfiGraphicsOutputProtocolGuid,
&gDisplayProto, NULL);
if (EFI_ERROR (Status)) {
goto Done;
}
if (PcdGet32 (PcdDisplayEnableSShot)) {
RegisterScreenshotHandlers ();
} else {
DEBUG ((DEBUG_INFO, "Screenshot capture disabled\n"));
}
Done:
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "Could not start DisplayDxe: %r\n", Status));
if (gDisplayProto.Mode->Info != NULL) {
FreePool (gDisplayProto.Mode->Info);
gDisplayProto.Mode->Info = NULL;
}
if (gDisplayProto.Mode != NULL) {
FreePool (gDisplayProto.Mode);
gDisplayProto.Mode = NULL;
}
gBS->CloseProtocol (
Controller,
&gEfiCallerIdGuid,
This->DriverBindingHandle,
Controller
);
}
return Status;
}
STATIC
EFI_STATUS
EFIAPI
DriverStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
)
{
EFI_STATUS Status;
ClearScreen (&gDisplayProto);
Status = gBS->UninstallMultipleProtocolInterfaces (
Controller, &gEfiGraphicsOutputProtocolGuid,
&gDisplayProto, NULL);
if (EFI_ERROR (Status)) {
return Status;
}
FreePool (gDisplayProto.Mode->Info);
gDisplayProto.Mode->Info = NULL;
FreePool (gDisplayProto.Mode);
gDisplayProto.Mode = NULL;
gBS->CloseProtocol (
Controller,
&gEfiCallerIdGuid,
This->DriverBindingHandle,
Controller
);
return Status;
}
| 27.318393 | 95 | 0.604017 |
96e52ef516a59e370b9f75bb5ba614463d9ac755 | 178 | h | C | ScreenBlurry/ScreenBlurry/AppDelegate.h | MrLuanJX/ScreenBlurry | 14246b295ca973f6c77144d157aaa54f276eb75d | [
"MIT"
] | null | null | null | ScreenBlurry/ScreenBlurry/AppDelegate.h | MrLuanJX/ScreenBlurry | 14246b295ca973f6c77144d157aaa54f276eb75d | [
"MIT"
] | null | null | null | ScreenBlurry/ScreenBlurry/AppDelegate.h | MrLuanJX/ScreenBlurry | 14246b295ca973f6c77144d157aaa54f276eb75d | [
"MIT"
] | null | null | null | //
// AppDelegate.h
// ScreenBlurry
//
// Created by hogo0211 on 2021/11/24.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@end
| 11.866667 | 60 | 0.691011 |
1b131219f4dc273dcf4289cdf36284e6b524ac75 | 312 | h | C | Tools/CommonInclude/src/CommonInclude.h | mupfelofen-de/SNESoIP | f662890a43fac7611946b4479046e649aef7cda7 | [
"MIT"
] | 59 | 2015-01-20T17:25:33.000Z | 2022-03-04T01:34:59.000Z | Tools/CommonInclude/src/CommonInclude.h | mupfelofen-de/SNESoIP | f662890a43fac7611946b4479046e649aef7cda7 | [
"MIT"
] | null | null | null | Tools/CommonInclude/src/CommonInclude.h | mupfelofen-de/SNESoIP | f662890a43fac7611946b4479046e649aef7cda7 | [
"MIT"
] | 7 | 2015-08-06T12:15:30.000Z | 2019-05-13T23:25:58.000Z | /**
* @file CommonInclude.h
* @brief SNESoIP common include
* @ingroup CommonInclude
*/
#pragma once
#include <stdbool.h>
#include <stdint.h>
uint8_t HexToUint8(uint8_t *pu8Hex);
void StrToIP(char* pacIp, uint8_t* pu8Dest);
uint32_t StrToUint32(char* pacStr);
bool IpIsValid(char* pacIn);
| 20.8 | 48 | 0.695513 |
9b16ac8ce0d68b050263e4a1a0d747dce50b004a | 1,908 | h | C | external/iotivity/iotivity_1.2-rel/service/resource-container/examples/HueSampleBundle/include/HueSampleBundleActivator.h | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 1,433 | 2015-04-30T09:26:53.000Z | 2022-03-26T12:44:12.000Z | AllJoyn/Samples/OICAdapter/iotivity-1.0.0/service/resource-container/examples/HueSampleBundle/include/HueSampleBundleActivator.h | buocnhay/samples-1 | ddd614bb5ae595f03811e3dfa15a5d107005d0fc | [
"MIT"
] | 4,673 | 2017-03-29T10:43:43.000Z | 2022-03-31T08:33:44.000Z | AllJoyn/Samples/OICAdapter/iotivity-1.0.0/service/resource-container/examples/HueSampleBundle/include/HueSampleBundleActivator.h | buocnhay/samples-1 | ddd614bb5ae595f03811e3dfa15a5d107005d0fc | [
"MIT"
] | 1,878 | 2015-04-30T04:18:57.000Z | 2022-03-15T16:51:17.000Z | //******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef HUESAMPLEBUNDLEACTIVATOR_H_
#define HUESAMPLEBUNDLEACTIVATOR_H_
#include "ResourceContainerBundleAPI.h"
#include "BundleActivator.h"
#include "BundleResource.h"
#include "HueConnector.h"
using namespace OIC::Service;
namespace OIC
{
namespace Service
{
class HueSampleBundleActivator: public BundleActivator
{
public:
HueSampleBundleActivator();
~HueSampleBundleActivator();
void activateBundle(ResourceContainerBundleAPI *resourceContainer,
std::string bundleId);
void deactivateBundle();
void createResource(resourceInfo resourceInfo);
void destroyResource(BundleResource::Ptr pBundleResource);
std::string m_bundleId;
ResourceContainerBundleAPI *m_pResourceContainer;
std::vector< BundleResource::Ptr > m_vecResources;
private:
HueConnector *m_connector;
};
}
}
#endif /* HUESAMPLEBUNDLEACTIVATOR_H_ */
| 32.896552 | 82 | 0.599057 |
00001e94f79f3be8f6095c147a72bda7d3c17376 | 4,006 | h | C | software/mesa/src/gallium/drivers/swr/swr_resource.h | dhanna11/OpenGPU | ab2f01253bba311e082dfae695b9e70138de75d4 | [
"Apache-2.0"
] | 7 | 2019-09-04T03:44:26.000Z | 2022-01-06T02:54:24.000Z | software/mesa/src/gallium/drivers/swr/swr_resource.h | dhanna11/OpenGPU | ab2f01253bba311e082dfae695b9e70138de75d4 | [
"Apache-2.0"
] | null | null | null | software/mesa/src/gallium/drivers/swr/swr_resource.h | dhanna11/OpenGPU | ab2f01253bba311e082dfae695b9e70138de75d4 | [
"Apache-2.0"
] | 3 | 2021-06-11T23:53:38.000Z | 2021-08-31T03:18:34.000Z | /****************************************************************************
* Copyright (C) 2015 Intel Corporation. All Rights Reserved.
*
* 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 (including the next
* paragraph) 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 SWR_RESOURCE_H
#define SWR_RESOURCE_H
#include "pipe/p_state.h"
#include "api.h"
struct sw_displaytarget;
enum swr_resource_status {
SWR_RESOURCE_UNUSED = 0x0,
SWR_RESOURCE_READ = 0x1,
SWR_RESOURCE_WRITE = 0x2,
};
struct swr_resource {
struct pipe_resource base;
bool has_depth;
bool has_stencil;
UINT alignedWidth;
UINT alignedHeight;
SWR_SURFACE_STATE swr;
SWR_SURFACE_STATE secondary; /* for faking depth/stencil merged formats */
struct sw_displaytarget *display_target;
unsigned row_stride[PIPE_MAX_TEXTURE_LEVELS];
unsigned img_stride[PIPE_MAX_TEXTURE_LEVELS];
unsigned mip_offsets[PIPE_MAX_TEXTURE_LEVELS];
enum swr_resource_status status;
};
static INLINE struct swr_resource *
swr_resource(struct pipe_resource *resource)
{
return (struct swr_resource *)resource;
}
static INLINE boolean
swr_resource_is_texture(const struct pipe_resource *resource)
{
switch (resource->target) {
case PIPE_BUFFER:
return FALSE;
case PIPE_TEXTURE_1D:
case PIPE_TEXTURE_1D_ARRAY:
case PIPE_TEXTURE_2D:
case PIPE_TEXTURE_2D_ARRAY:
case PIPE_TEXTURE_RECT:
case PIPE_TEXTURE_3D:
case PIPE_TEXTURE_CUBE:
case PIPE_TEXTURE_CUBE_ARRAY:
return TRUE;
default:
assert(0);
return FALSE;
}
}
static INLINE uint8_t *
swr_resource_data(struct pipe_resource *resource)
{
struct swr_resource *swr_r = swr_resource(resource);
assert(!swr_resource_is_texture(resource));
return swr_r->swr.pBaseAddress;
}
void swr_store_render_target(struct pipe_context *pipe,
uint32_t attachment,
enum SWR_TILE_STATE post_tile_state);
void swr_store_dirty_resource(struct pipe_context *pipe,
struct pipe_resource *resource,
enum SWR_TILE_STATE post_tile_state);
void swr_update_resource_status(struct pipe_context *,
const struct pipe_draw_info *);
/*
* Functions to indicate a resource's in-use status.
*/
static INLINE enum
swr_resource_status & operator|=(enum swr_resource_status & a,
enum swr_resource_status b) {
return (enum swr_resource_status &)((int&)a |= (int)b);
}
static INLINE void
swr_resource_read(struct pipe_resource *resource)
{
swr_resource(resource)->status |= SWR_RESOURCE_READ;
}
static INLINE void
swr_resource_write(struct pipe_resource *resource)
{
swr_resource(resource)->status |= SWR_RESOURCE_WRITE;
}
static INLINE void
swr_resource_unused(struct pipe_resource *resource)
{
swr_resource(resource)->status = SWR_RESOURCE_UNUSED;
}
#endif
| 29.028986 | 79 | 0.703694 |
000be5cb043b5a2dd55298eaa34fabe5a82888ac | 3,537 | h | C | server/server.h | tort-dla-psa/cli_srv_example | 52bcbe67795556a831acf92cb0d859b4481b2167 | [
"MIT"
] | 1 | 2021-07-13T19:11:51.000Z | 2021-07-13T19:11:51.000Z | server/server.h | tort-dla-psa/cli_srv_example | 52bcbe67795556a831acf92cb0d859b4481b2167 | [
"MIT"
] | null | null | null | server/server.h | tort-dla-psa/cli_srv_example | 52bcbe67795556a831acf92cb0d859b4481b2167 | [
"MIT"
] | null | null | null | #pragma once
#include <QVector>
#include <QTcpSocket>
#include <QTcpServer>
#include <QObject>
#include <QString>
#include "players.h"
#include "id_gen.h"
#include "rooms.h"
#include <iostream>
class Server:public QTcpServer{
Q_OBJECT
quint16 port;
WaitingRoom* wait_room;
QVector<GameRoom*> rooms;
IdGenerator gen;
public:
Server(quint16 port, QObject* parent=nullptr):
QTcpServer(parent),
port(port)
{
wait_room = new WaitingRoom();
connect(wait_room, &WaitingRoom::roomJoinRequested,
this, &Server::onRoomJoinRequested);
connect(wait_room, &WaitingRoom::roomCreateRequested,
this, &Server::onRoomCreateRequested);
connect(this, &QTcpServer::newConnection,
this, &Server::onNewConnection);
}
~Server(){
delete wait_room;
}
public slots:
void onNewConnection(){
//[virtual]QTcpSocket *QTcpServer::nextPendingConnection()
auto client_socket = nextPendingConnection();
auto addr = client_socket->peerAddress().toString();
std::cout<<"new connection:"<<addr.toStdString()<<"\n";
auto plr = new Player(client_socket);
connect(plr, &Player::gotMessage,
wait_room, &WaitingRoom::onPlayerMessage);
wait_room->addPlayer(plr);
}
void run(){
this->listen(QHostAddress::Any, port);
}
void onRoomJoinRequested(Player* plr, std::string id, std::string pass){
auto predicate = [&id](GameRoom* room){
if(room->get_id() == id){
return true;
}else{
return false;
}
};
auto room_it = std::find_if(rooms.begin(), rooms.end(), predicate);
if(room_it == rooms.end()){
}else{
auto room = *room_it;
if(room->get_pass() == pass){
wait_room->removePlayer(plr);
disconnect(plr, &Player::gotMessage,
wait_room, &WaitingRoom::onPlayerMessage);
disconnect(plr, &Player::disconnected,
wait_room, &WaitingRoom::onPlayerDisconnect);
disconnect(plr, &Player::disconnected,
wait_room, &WaitingRoom::onPlayerDisconnect);
connect(plr, &Player::gotMessage,
room, &GameRoom::onPlayerMessage);
room->addPlayer(plr);
}
}
}
void onRoomCreateRequested(Player* plr, std::string pass){
auto id = gen.get_id();
wait_room->removePlayer(plr);
disconnect(plr, &Player::gotMessage,
wait_room, &WaitingRoom::onPlayerMessage);
disconnect(plr, &Player::disconnected,
wait_room, &WaitingRoom::onPlayerDisconnect);
auto adm = new Admin(plr);
delete plr;
auto room = new GameRoom(adm, pass);
room->id = gen.get_id();
std::cout<<"new room, id:"<<room->get_id()
<<" pass:"<<room->get_pass()<<"\n";
connect(adm, &Player::gotMessage,
room, &GameRoom::onPlayerMessage);
connect(adm, &Player::disconnected,
room, &GameRoom::onPlayerDisconnect);
connect(room, &Room::empty,
this, &Server::onRoomEmpty);
rooms.push_back(room);
}
void onRoomEmpty(){
auto room = (GameRoom*)sender();
rooms.removeOne(room);
std::cout<<"room id:"<<room->get_id()<<" is empty now\n";
delete room;
}
signals:
void finished();
}; | 33.367925 | 76 | 0.576477 |
1558c3d22cee60e824938227c595e985417c5b46 | 1,945 | h | C | proj/code/pixmap/fonts/white-size22/0.h | mbcsm/FEUP_LCOM | fe1d84a30a93c36fb28912ea75e990ef213a6809 | [
"MIT"
] | null | null | null | proj/code/pixmap/fonts/white-size22/0.h | mbcsm/FEUP_LCOM | fe1d84a30a93c36fb28912ea75e990ef213a6809 | [
"MIT"
] | null | null | null | proj/code/pixmap/fonts/white-size22/0.h | mbcsm/FEUP_LCOM | fe1d84a30a93c36fb28912ea75e990ef213a6809 | [
"MIT"
] | null | null | null | /* XPM */
static const char * zerow_xpm[] = {
"32 32 49 1",
" c None",
". c #000000",
"+ c #101010",
"@ c #3B3B3B",
"# c #3A3A3A",
"$ c #383838",
"% c #5D5D5D",
"& c #FFFFFF",
"* c #FBFBFB",
"= c #030303",
"- c #7B7B7B",
"; c #E0E0E0",
"> c #CCCCCC",
", c #090909",
"' c #C4C4C4",
") c #FAFAFA",
"! c #353535",
"~ c #C7C7C7",
"{ c #F6F6F6",
"] c #F4F4F4",
"^ c #5E5E5E",
"/ c #2E2E2E",
"( c #4F4F4F",
"_ c #EEEEEE",
": c #1C1C1C",
"< c #494949",
"[ c #EFEFEF",
"} c #292929",
"| c #4C4C4C",
"1 c #222222",
"2 c #484848",
"3 c #FEFEFE",
"4 c #F0F0F0",
"5 c #2F2F2F",
"6 c #040404",
"7 c #0A0A0A",
"8 c #414141",
"9 c #D3D3D3",
"0 c #CDCDCD",
"a c #BCBCBC",
"b c #BDBDBD",
"c c #C6C6C6",
"d c #B0B0B0",
"e c #010101",
"f c #878787",
"g c #282828",
"h c #8F8F8F",
"i c #8C8C8C",
"j c #898989",
" ",
" ",
" ",
" ",
" .......... ",
" .+@#$$$$#@+. ",
" ..%&&****&&%.. ",
" =-;&&&&&&&&;-= ",
" ..>&&&&&&&&&&>.. ",
" ..,'&&*)**)*&&',.. ",
" .!~{&]^/$$/^]&{~!. ",
" .(&&&_:....:_&&&(. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .<&&&[}. .}[&&&<. ",
" .|&&&[1. .1[&&&|. ",
" .23&&45.66.54&&32. ",
" .789&*0abba0*&987. ",
" ..c&&&&&&&&&&c.. ",
" 6d&&&&&&&&&&d6 ",
" e+f&&&&&&&&f+e ",
" ..ghijjjjihg.. ",
" e..........e "};
| 22.882353 | 36 | 0.228278 |
af67e4cf0ed85e8e8e13fe93e0e1e2253f242d41 | 1,245 | h | C | src/CLR/Include/nanoCLR_Application.h | josesimoes/nf-interpreter | 3ec2020143148f40929d597adbd058cd1f6079b8 | [
"MIT"
] | 223 | 2017-02-07T07:57:17.000Z | 2022-03-11T06:03:15.000Z | src/CLR/Include/nanoCLR_Application.h | josesimoes/nf-interpreter | 3ec2020143148f40929d597adbd058cd1f6079b8 | [
"MIT"
] | 1,696 | 2017-01-24T16:08:40.000Z | 2022-03-24T10:26:31.000Z | src/CLR/Include/nanoCLR_Application.h | josesimoes/nf-interpreter | 3ec2020143148f40929d597adbd058cd1f6079b8 | [
"MIT"
] | 208 | 2017-01-23T18:55:43.000Z | 2022-03-16T09:23:20.000Z | //
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#ifndef NANOCLR_APPLICATION_H
#define NANOCLR_APPLICATION_H
#include <stdbool.h>
typedef struct CLR_SETTINGS
{
// this is the maximum number of context switches that execution engine thread scheduler can handle
// higher number: more threads and timers can be handled
unsigned short MaxContextSwitches;
// set this to TRUE if the default behaviour is for the execution engine to wait for a debugger to be connected
// when building is set for RTM this configuration is ignored
bool WaitForDebugger;
// set this to TRUE if a connection from a debugger is to be awaited after the execution engine terminates
// this is required for launching a debug session in Visual Studio
// when building is set for RTM this configuration is ignored
bool EnterDebuggerLoopAfterExit;
#if defined(_WIN32)
CLR_RT_StringVector StartArgs;
#endif
} CLR_SETTINGS;
#ifdef __cplusplus
extern "C"
{
#endif
extern void ClrStartup(CLR_SETTINGS params);
extern void ClrExit();
#ifdef __cplusplus
}
#endif
#endif
| 26.489362 | 115 | 0.755823 |
af9053ed1b2d6f774d2c77e8593888f2577969c2 | 1,504 | h | C | iPhoneClient/NoteDetailsViewController.h | spoymenov/arisgames | aad5f5c6cdb3b1e8ade68da012c6e46ac9a6f77c | [
"MIT"
] | 1 | 2018-12-25T15:19:12.000Z | 2018-12-25T15:19:12.000Z | iPhoneClient/NoteDetailsViewController.h | augustozuniga/arisgames | 1ccf8fcbd9083134972b80e429456dbd6e28aa3d | [
"MIT"
] | null | null | null | iPhoneClient/NoteDetailsViewController.h | augustozuniga/arisgames | 1ccf8fcbd9083134972b80e429456dbd6e28aa3d | [
"MIT"
] | null | null | null | //
// NoteDetailsViewController.h
// ARIS
//
// Created by Brian Thiel on 8/12/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Note.h"
#import "NoteContent.h"
#import "ARISMoviePlayerViewController.h"
@interface NoteDetailsViewController : UIViewController <UIScrollViewDelegate> {
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
id __unsafe_unretained delegate;
int pageNumber;
int numPages;
// UIButton *mediaPlaybackButton;
IBOutlet UILabel *commentLabel;
IBOutlet UILabel *likeLabel;
//ARISMoviePlayerViewController *mMoviePlayer;
Note *note;
IBOutlet UIBarButtonItem *likeButton;
IBOutlet UIBarButtonItem *commentButton;
}
@property(nonatomic) IBOutlet UIBarButtonItem *likeButton;
@property(nonatomic) IBOutlet UIBarButtonItem *commentButton;;
@property(nonatomic, unsafe_unretained) id delegate;
@property(nonatomic) IBOutlet UIScrollView *scrollView;
@property(nonatomic) IBOutlet UIPageControl *pageControl;
@property(nonatomic) IBOutlet UILabel *commentLabel;
@property(nonatomic) IBOutlet UILabel *likeLabel;
@property(nonatomic)Note *note;
- (IBAction)saveButtonTouchAction;
- (IBAction)changePage:(id) sender;
- (void)loadNewPageWithContent:(NoteContent *)content;
- (void)showComments;
-(void)editButtonTouched;
-(IBAction)shareButtonTouch;
-(IBAction)commentButtonTouch;
-(IBAction)likeButtonTouch;
-(void)backButtonTouch;
-(void)addUploadsToNote;
@end
| 28.923077 | 80 | 0.777926 |
15da50ec0698b567b438beefdc78c80020e187fa | 493 | h | C | src/typeset_commands/typeset_command_pair.h | JohnDTill/Forscape | dbbab01f30597af00f87527a8a3d7b468c04b67b | [
"MIT"
] | 10 | 2021-11-13T12:39:06.000Z | 2022-03-19T13:40:05.000Z | src/typeset_commands/typeset_command_pair.h | JohnDTill/Forscape | dbbab01f30597af00f87527a8a3d7b468c04b67b | [
"MIT"
] | 22 | 2021-11-13T12:57:10.000Z | 2022-03-15T21:42:05.000Z | src/typeset_commands/typeset_command_pair.h | JohnDTill/Forscape | dbbab01f30597af00f87527a8a3d7b468c04b67b | [
"MIT"
] | null | null | null | #ifndef TYPESET_COMMAND_PAIR_H
#define TYPESET_COMMAND_PAIR_H
#include <typeset_command.h>
namespace Hope {
namespace Typeset {
class CommandPair : public Command{
public:
CommandPair(Command* a, Command* b);
virtual ~CommandPair();
virtual bool isPairInsertion() const noexcept override;
virtual void undo(Controller& controller) override;
virtual void redo(Controller& controller) override;
Command* a;
Command* b;
};
}
}
#endif // TYPESET_COMMAND_PAIR_H
| 18.259259 | 59 | 0.738337 |
18852a6eadce4abb72be51adc2c7d0e64db74fce | 220 | h | C | binaryutil.h | assyrian7/BlantV2 | ce296f70dcc3764c76054ed94ba187f42525ba5b | [
"Apache-2.0"
] | null | null | null | binaryutil.h | assyrian7/BlantV2 | ce296f70dcc3764c76054ed94ba187f42525ba5b | [
"Apache-2.0"
] | null | null | null | binaryutil.h | assyrian7/BlantV2 | ce296f70dcc3764c76054ed94ba187f42525ba5b | [
"Apache-2.0"
] | null | null | null | #ifndef _BINARYUTIL_H_
#define _BINARYUTIL_H_
#include "math.h"
#include "stdlib.h"
int* numToLowMat(int number, int numNodes);
int* edgeToMat(int *edge, int numNodes);
int matToNum(int *mat, int numNodes);
#endif
| 14.666667 | 43 | 0.740909 |
4948b460e5788286eabf78eb7581d839b7bd59fd | 5,582 | h | C | xi/io/buffer_reader.h | Anomander/xi | 0340675310c41d659762fc3eea48c84ff13b95db | [
"MIT"
] | null | null | null | xi/io/buffer_reader.h | Anomander/xi | 0340675310c41d659762fc3eea48c84ff13b95db | [
"MIT"
] | null | null | null | xi/io/buffer_reader.h | Anomander/xi | 0340675310c41d659762fc3eea48c84ff13b95db | [
"MIT"
] | null | null | null | #pragma once
#include "xi/io/buffer.h"
#include "xi/io/detail/buffer_utils.h"
#include "xi/io/fragment_string.h"
namespace xi {
namespace io {
class buffer::reader {
protected:
mut< buffer > _buffer;
usize _mark = 0;
public:
reader(mut< buffer > b, usize m = 0) : _buffer(b), _mark(m) {
}
template < class T >
bool read_value(T &value) {
if (_mark < _buffer->size() && _buffer->size() - _mark >= sizeof(T)) {
_buffer->read(byte_range_for_object(value), _mark);
return true;
}
return false;
}
template < class T >
opt< T > read_value() {
T value;
if (read_value(value)) {
return some(move(value));
}
return none;
}
template < class T >
opt< T > read_value_and_mark() {
return read_value< T >().map([&](auto &&v) {
_mark += sizeof(T);
return move(v);
});
}
template < class T >
bool read_value_and_mark(T &value) {
auto ret = read_value(value);
if (ret) {
_mark += sizeof(T);
}
return ret;
}
template < class T >
opt< T > read_value_and_skip() {
return read_value< T >().map([&](auto &&v) {
_buffer->skip_bytes(_mark + sizeof(T));
_mark = 0;
return move(v);
});
}
template < class T >
bool read_value_and_skip(T &value) {
auto ret = read_value(value);
if (ret) {
_buffer->skip_bytes(_mark + sizeof(T));
_mark = 0;
}
return ret;
}
template < usize N >
usize skip_any_not_of_and_mark(const char (&pattern)[N]) {
return skip_any_not_of_and_mark(pattern, N - 1);
}
usize skip_any_not_of_and_mark(const char *pattern, usize len) {
if (!len) {
return _mark = _buffer->size();
}
return skip_any_of_and_mark((u8 *)pattern, len, [](bool b) { return b; });
}
template < usize N >
usize skip_any_of_and_mark(const char (&pattern)[N]) {
return skip_any_of_and_mark(pattern, N - 1);
}
usize skip_any_of_and_mark(const char *pattern, usize len) {
if (!len) {
return 0;
}
return skip_any_of_and_mark(
(u8 *)pattern, len, [](bool b) { return !b; });
}
usize total_size() const;
usize unmarked_size() const;
usize marked_size() const;
byte_range next_data_range() const;
usize mark_offset(usize);
void discard_to_mark();
own< buffer > consume_mark_into_buffer();
own< fragment_string > consume_mark_into_string();
template < class Pred >
usize skip_any_of_and_mark(u8 *pattern, usize len, Pred const &);
opt< usize > find_byte(u8 target, usize offset = 0) const;
};
inline buffer::reader make_reader(mut< buffer > b) {
return buffer::reader(b);
}
inline usize buffer::reader::total_size() const {
return _buffer->size();
}
inline usize buffer::reader::unmarked_size() const {
return _buffer->size() - _mark;
}
inline usize buffer::reader::marked_size() const {
return _mark;
}
inline byte_range buffer::reader::next_data_range() const {
if (!unmarked_size()) {
return byte_range::null();
}
auto offset = _mark;
auto end = _buffer->_fragments.end();
auto it = skip_offset(_buffer->_fragments.begin(), end, edit(offset));
while (it != end && it->size() == 0) {
++it;
}
return it == end ? byte_range::null() : it->data_range().subrange(offset);
}
inline usize buffer::reader::mark_offset(usize offset) {
assert(make_signed_t< usize >(_mark + offset) >= 0);
auto cap = min(offset, unmarked_size());
_mark += cap;
return cap;
}
inline void buffer::reader::discard_to_mark() {
XI_SCOPE(success) {
_mark = 0;
};
return _buffer->skip_bytes(_mark);
}
inline own< buffer > buffer::reader::consume_mark_into_buffer() {
XI_SCOPE(success) {
_mark = 0;
};
return _buffer->split(_mark);
}
inline own< fragment_string > buffer::reader::consume_mark_into_string() {
auto buf = _buffer->split(_mark);
_mark = 0;
return make< fragment_string >(move(buf->_fragments), buf->_size);
}
template < class Pred >
usize buffer::reader::skip_any_of_and_mark(u8 *pattern,
usize len,
Pred const &predicate) {
usize ret = 0;
auto end = _buffer->_fragments.end();
auto offset = _mark;
auto it = skip_offset(_buffer->_fragments.begin(), end, edit(offset));
while (end != it) {
auto ch = it->data_range().data() + offset;
auto ch_end = it->data_range().data() + it->size();
while (ch != ch_end) {
if (predicate(::memchr(pattern, *(ch++), len))) {
goto done;
}
++ret;
}
offset = 0;
++it;
}
done:
_mark += ret;
return ret;
}
opt< usize > buffer::reader::find_byte(u8 target, usize offset) const {
if (offset >= _buffer->size()) {
return none;
}
auto end = _buffer->_fragments.end();
auto it = skip_offset(_buffer->_fragments.begin(), end, edit(offset));
void *found = nullptr;
usize size = 0u;
do {
found = ::memchr(it->data() + offset, target, it->size() - offset);
if (found) {
size += ((u8 *)found - it->data()) - offset;
} else {
size += it->size() - offset;
offset = 0;
}
++it;
} while (nullptr == found && end != it);
return found ? some(size) : none;
}
}
}
| 25.372727 | 80 | 0.567897 |
49acfa4510ad3b1b0cdace134f1f646144034390 | 1,198 | h | C | bin/windows/cpp/obj/include/com/haxepunk/tweens/TweenEvent.h | DrSkipper/twogames | 916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b | [
"MIT"
] | null | null | null | bin/windows/cpp/obj/include/com/haxepunk/tweens/TweenEvent.h | DrSkipper/twogames | 916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b | [
"MIT"
] | null | null | null | bin/windows/cpp/obj/include/com/haxepunk/tweens/TweenEvent.h | DrSkipper/twogames | 916e8af6cd45cf85fbca4a6ea8ee12e24dd6689b | [
"MIT"
] | null | null | null | #ifndef INCLUDED_com_haxepunk_tweens_TweenEvent
#define INCLUDED_com_haxepunk_tweens_TweenEvent
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#include <flash/events/Event.h>
HX_DECLARE_CLASS3(com,haxepunk,tweens,TweenEvent)
HX_DECLARE_CLASS2(flash,events,Event)
namespace com{
namespace haxepunk{
namespace tweens{
class HXCPP_CLASS_ATTRIBUTES TweenEvent_obj : public ::flash::events::Event_obj{
public:
typedef ::flash::events::Event_obj super;
typedef TweenEvent_obj OBJ_;
TweenEvent_obj();
Void __construct(::String type,Dynamic bubbles,Dynamic cancelable);
public:
static hx::ObjectPtr< TweenEvent_obj > __new(::String type,Dynamic bubbles,Dynamic cancelable);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
~TweenEvent_obj();
HX_DO_RTTI;
static void __boot();
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
::String __ToString() const { return HX_CSTRING("TweenEvent"); }
static ::String START;
static ::String UPDATE;
static ::String FINISH;
};
} // end namespace com
} // end namespace haxepunk
} // end namespace tweens
#endif /* INCLUDED_com_haxepunk_tweens_TweenEvent */
| 26.043478 | 97 | 0.770451 |
e4187e2aaf084ae1b7ad62a427039950e27b1efa | 2,819 | h | C | src/extern/dcmtk-3.5.4/dcmdata/include/dcmtk/dcmdata/dcvrof.h | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | SmiSDK/include/dcmtk/dcmdata/dcvrof.h | yangguang-ecnu/smisdk | e4fcf939185e87d08633461eff270c4c517c1826 | [
"Apache-2.0"
] | null | null | null | SmiSDK/include/dcmtk/dcmdata/dcvrof.h | yangguang-ecnu/smisdk | e4fcf939185e87d08633461eff270c4c517c1826 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
*
* Copyright (C) 2002-2005, OFFIS
*
* This software and supporting documentation were developed by
*
* Kuratorium OFFIS e.V.
* Healthcare Information and Communication Systems
* Escherweg 2
* D-26121 Oldenburg, Germany
*
* THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND OFFIS MAKES NO WARRANTY
* REGARDING THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY OR
* FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR
* ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND
* PERFORMANCE OF THE SOFTWARE IS WITH THE USER.
*
* Module: dcmdata
*
* Author: Joerg Riesmeier
*
* Purpose: Interface of class DcmOtherFloat
*
* Last Update: $Author: meichel $
* Update Date: $Date: 2005/12/08 16:29:04 $
* Source File: $Source: /share/dicom/cvs-depot/dcmtk/dcmdata/include/dcmtk/dcmdata/dcvrof.h,v $
* CVS/RCS Revision: $Revision: 1.3 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#ifndef DCVROF_H
#define DCVROF_H
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dcvrfl.h"
/** a class representing the DICOM value representation 'Other Float String' (OF)
*/
class DcmOtherFloat
: public DcmFloatingPointSingle
{
public:
/** constructor.
* Create new element from given tag and length.
* @param tag DICOM tag for the new element
* @param len value length for the new element
*/
DcmOtherFloat(const DcmTag &tag,
const Uint32 len = 0);
/** copy constructor
* @param old element to be copied
*/
DcmOtherFloat(const DcmOtherFloat &old);
/** destructor
*/
virtual ~DcmOtherFloat();
/** assignment operator
* @param obj element to be assigned/copied
* @return reference to this object
*/
DcmOtherFloat &operator=(const DcmOtherFloat &obj);
/** clone method
* @return deep copy of this object
*/
virtual DcmObject *clone() const
{
return new DcmOtherFloat(*this);
}
/** get element type identifier
* @return type identifier of this class (EVR_OF)
*/
virtual DcmEVR ident() const;
/** get value multiplicity
* @return always returns 1 (according to the DICOM standard)
*/
virtual unsigned long getVM();
};
#endif // DCVROF_H
/*
* CVS/RCS Log:
* $Log: dcvrof.h,v $
* Revision 1.3 2005/12/08 16:29:04 meichel
* Changed include path schema for all DCMTK header files
*
* Revision 1.2 2004/07/01 12:28:25 meichel
* Introduced virtual clone method for DcmObject and derived classes.
*
* Revision 1.1 2002/12/06 12:06:39 joergr
* Added support for new value representation Other Float String (OF).
*
*
*/
| 25.396396 | 102 | 0.656616 |
17ecdd283093f49d3d666dd55fd2eb830d72b032 | 1,931 | h | C | arduino_chiuhuahua/commandInterface/CommandInterface.h | pboulet/arduino-dog | e88d4f458f2da9ed33599ad304bbbb99c9198e1d | [
"MIT"
] | null | null | null | arduino_chiuhuahua/commandInterface/CommandInterface.h | pboulet/arduino-dog | e88d4f458f2da9ed33599ad304bbbb99c9198e1d | [
"MIT"
] | null | null | null | arduino_chiuhuahua/commandInterface/CommandInterface.h | pboulet/arduino-dog | e88d4f458f2da9ed33599ad304bbbb99c9198e1d | [
"MIT"
] | null | null | null | /*
* CommandInterface.h
* Chico The Robot
*/
/******************************************************************************************************************/
/*! \file CommandInterface.h
*
* \author Patric Boulet & Nick Dubus
*
* \date April 13th, 2016
*
* \brief Sets up a web server that processes
* client response and parses them to their
* associated commands in the context of the robot.
*/
/******************************************************************************************************************/
/******************************************************************************************************************/
#ifndef INCLUDE_WEB_INTERFACE_H_
#define INCLUDE_WEB_INTERFACE_H
// we need to expose this dependency here otherwise our
// API cannot compile some of its type definitions
#include <stdint.h>
/*!
* \enum WebCommand
* \brief All possible commands to be received
* from the web interface.
*/
typedef enum {
FORWARD_CMD,
BACKWARD_CMD,
SPINLEFT_CMD,
SPINRIGHT_CMD,
STOP_CMD,
ATTACHMENT_MODE_CMD,
SCAN_TEMPERATURE_CMD,
SCAN_DISTANCE_CMD,
UNKNOWN_CMD
} WebCommand;
/*--------------------------------------- ENTRY POINTS ---------------------------------------------------------*/
/*!\fn InitWebInterface(void)
* \brief Module initializer.
*
*\details This entry point first enables interrupts in the system,
*\details which is required for the module to function correctly.
*\details It then initializes the wi-fi hot spot and web server sequentially.
*
* @returns none
*/
void InitWebInterface(void);
/*!\fn GetCommand()
* \brief Parses client response and returns the associated
* WebCommand.
*
* @returns WebCommand the WebCommand associated with the client response
* character, if any.
*/
WebCommand GetCommand(void);
/******************************************************************************************************************/
#endif
| 26.094595 | 116 | 0.520974 |
17339ccf623d0f2d8c2f683c15c1a30390ed1351 | 6,753 | h | C | src/other/libosmesa/src/main/shaders.h | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 64 | 2015-03-06T00:30:56.000Z | 2022-03-24T13:26:53.000Z | src/other/libosmesa/src/main/shaders.h | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 8 | 2018-10-31T16:12:07.000Z | 2021-05-15T14:30:49.000Z | src/other/libosmesa/src/main/shaders.h | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 40 | 2015-02-26T15:31:16.000Z | 2022-03-03T23:23:37.000Z | /*
* Mesa 3-D graphics library
* Version: 6.5.3
*
* Copyright (C) 2004-2007 Brian Paul All Rights Reserved.
*
* 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
* BRIAN PAUL 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 SHADERS_H
#define SHADERS_H
#include "glheader.h"
#include "mtypes.h"
extern void GLAPIENTRY
_mesa_DeleteObjectARB(GLhandleARB obj);
extern GLhandleARB GLAPIENTRY
_mesa_GetHandleARB(GLenum pname);
extern void GLAPIENTRY
_mesa_DetachObjectARB (GLhandleARB, GLhandleARB);
extern GLhandleARB GLAPIENTRY
_mesa_CreateShaderObjectARB (GLenum);
extern void GLAPIENTRY
_mesa_ShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *);
extern void GLAPIENTRY
_mesa_CompileShaderARB (GLhandleARB);
extern GLhandleARB GLAPIENTRY
_mesa_CreateProgramObjectARB (void);
extern void GLAPIENTRY
_mesa_AttachObjectARB (GLhandleARB, GLhandleARB);
extern void GLAPIENTRY
_mesa_LinkProgramARB (GLhandleARB);
extern void GLAPIENTRY
_mesa_UseProgramObjectARB (GLhandleARB);
extern void GLAPIENTRY
_mesa_ValidateProgramARB (GLhandleARB);
extern void GLAPIENTRY
_mesa_Uniform1fARB (GLint, GLfloat);
extern void GLAPIENTRY
_mesa_Uniform2fARB (GLint, GLfloat, GLfloat);
extern void GLAPIENTRY
_mesa_Uniform3fARB (GLint, GLfloat, GLfloat, GLfloat);
extern void GLAPIENTRY
_mesa_Uniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
extern void GLAPIENTRY
_mesa_Uniform1iARB (GLint, GLint);
extern void GLAPIENTRY
_mesa_Uniform2iARB (GLint, GLint, GLint);
extern void GLAPIENTRY
_mesa_Uniform3iARB (GLint, GLint, GLint, GLint);
extern void GLAPIENTRY
_mesa_Uniform4iARB (GLint, GLint, GLint, GLint, GLint);
extern void GLAPIENTRY
_mesa_Uniform1fvARB (GLint, GLsizei, const GLfloat *);
extern void GLAPIENTRY
_mesa_Uniform2fvARB (GLint, GLsizei, const GLfloat *);
extern void GLAPIENTRY
_mesa_Uniform3fvARB (GLint, GLsizei, const GLfloat *);
extern void GLAPIENTRY
_mesa_Uniform4fvARB (GLint, GLsizei, const GLfloat *);
extern void GLAPIENTRY
_mesa_Uniform1ivARB (GLint, GLsizei, const GLint *);
extern void GLAPIENTRY
_mesa_Uniform2ivARB (GLint, GLsizei, const GLint *);
extern void GLAPIENTRY
_mesa_Uniform3ivARB (GLint, GLsizei, const GLint *);
extern void GLAPIENTRY
_mesa_Uniform4ivARB (GLint, GLsizei, const GLint *);
extern void GLAPIENTRY
_mesa_UniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
extern void GLAPIENTRY
_mesa_UniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
extern void GLAPIENTRY
_mesa_UniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
extern void GLAPIENTRY
_mesa_GetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *);
extern void GLAPIENTRY
_mesa_GetObjectParameterivARB (GLhandleARB, GLenum, GLint *);
extern void GLAPIENTRY
_mesa_GetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
extern void GLAPIENTRY
_mesa_GetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *);
extern GLint GLAPIENTRY
_mesa_GetUniformLocationARB (GLhandleARB, const GLcharARB *);
extern void GLAPIENTRY
_mesa_GetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
extern void GLAPIENTRY
_mesa_GetUniformfvARB (GLhandleARB, GLint, GLfloat *);
extern void GLAPIENTRY
_mesa_GetUniformivARB (GLhandleARB, GLint, GLint *);
extern void GLAPIENTRY
_mesa_GetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
#if FEATURE_ARB_vertex_shader
extern void GLAPIENTRY
_mesa_BindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *);
extern void GLAPIENTRY
_mesa_GetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
extern GLint GLAPIENTRY
_mesa_GetAttribLocationARB (GLhandleARB, const GLcharARB *);
#endif /* FEATURE_ARB_vertex_shader */
/* 2.0 */
extern void GLAPIENTRY
_mesa_AttachShader(GLuint program, GLuint shader);
extern GLuint GLAPIENTRY
_mesa_CreateShader(GLenum);
extern GLuint GLAPIENTRY
_mesa_CreateProgram(void);
extern void GLAPIENTRY
_mesa_DeleteProgram(GLuint program);
extern void GLAPIENTRY
_mesa_DeleteShader(GLuint shader);
extern void GLAPIENTRY
_mesa_DetachShader(GLuint program, GLuint shader);
extern void GLAPIENTRY
_mesa_GetAttachedShaders(GLuint program, GLsizei maxCount,
GLsizei *count, GLuint *obj);
extern void GLAPIENTRY
_mesa_GetProgramiv(GLuint program, GLenum pname, GLint *params);
extern void GLAPIENTRY
_mesa_GetProgramInfoLog(GLuint program, GLsizei bufSize,
GLsizei *length, GLchar *infoLog);
extern void GLAPIENTRY
_mesa_GetShaderiv(GLuint shader, GLenum pname, GLint *params);
extern void GLAPIENTRY
_mesa_GetShaderInfoLog(GLuint shader, GLsizei bufSize,
GLsizei *length, GLchar *infoLog);
extern GLboolean GLAPIENTRY
_mesa_IsProgram(GLuint program);
extern GLboolean GLAPIENTRY
_mesa_IsShader(GLuint shader);
/* 2.1 */
extern void GLAPIENTRY
_mesa_UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value);
extern void GLAPIENTRY
_mesa_UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value);
extern void GLAPIENTRY
_mesa_UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value);
extern void GLAPIENTRY
_mesa_UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value);
extern void GLAPIENTRY
_mesa_UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value);
extern void GLAPIENTRY
_mesa_UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose,
const GLfloat *value);
#endif /* SHADERS_H */
| 28.493671 | 100 | 0.778469 |
17aa4c8d71bfb5727b4fbc4b5a330873758d3ad0 | 1,976 | c | C | code/heap.c | nyamako/hacktoberfest-2018 | bf7939d4b0cfb57a854a1644dbbae7ddf8af3c4f | [
"MIT"
] | 67 | 2018-09-25T21:37:23.000Z | 2020-11-03T02:03:22.000Z | code/heap.c | nyamako/hacktoberfest-2018 | bf7939d4b0cfb57a854a1644dbbae7ddf8af3c4f | [
"MIT"
] | 245 | 2018-09-18T10:07:28.000Z | 2020-09-30T19:00:11.000Z | code/heap.c | nyamako/hacktoberfest-2018 | bf7939d4b0cfb57a854a1644dbbae7ddf8af3c4f | [
"MIT"
] | 1,192 | 2018-09-18T11:27:55.000Z | 2021-10-17T10:24:37.000Z | /*
Header_Interface:
insert_heap()
delete_heap()
sift_up() // return value valid only if started with already heapified array
*/
#include<stdio.h>
#define N 1000
typedef struct heap_struct
{
int val;
// all other data;
} heapst;
int sift_up(int pos,heapst heaparr[])
{
if (pos == 0) return 0;
int p= (pos-1)/2;
int a=heaparr[p].val;
int b=heaparr[p*2+1].val;
int c=heaparr[p*2+2].val;
if (a>=b && a>=c) return pos;
heapst temp= heaparr[p];
if (a>=b && a<c)
{
heaparr[p]=heaparr[p*2+2];
heaparr[p*2+2]=temp;
return sift_up(p,heaparr);
}
if (a>=c && a<b)
{
heaparr[p]=heaparr[p*2+1];
heaparr[p*2+1]=temp;
return sift_up(p,heaparr);
}
else
{
printf("This part of the header to buildmax hasn't been coded yet\n");
return -pos;
}
}
int insert_heap(int ptr, heapst heaparr[])
{
int v;
scanf("%d",&v);
heaparr[ptr].val=v;
return sift_up(ptr, heaparr);
}
void sift_down(int pos, int ptr,heapst heaparr[])
{
if (pos*2+1 >= ptr) return;
int a=heaparr[pos].val;
int b=heaparr[pos*2+1].val;
if (ptr == pos*2+2)
{
if(a>=b) return;
heapst temp= heaparr[pos];
heaparr[pos]= heaparr[pos*2+1];
heaparr[pos*2+1]=temp;
return;
}
int c=heaparr[pos*2+2].val;
if (a>=b && a>=c) return;
heapst temp= heaparr[pos];
if (b>=c)
{
heaparr[pos]= heaparr[pos*2+1];
heaparr[pos*2+1]=temp;
sift_down(pos*2+1,ptr,heaparr);
}
else
{
heaparr[pos]= heaparr[pos*2+2];
heaparr[pos*2+2]=temp;
sift_down(pos*2+2,ptr,heaparr);
}
}
void delete_heap(int pos,int ptr, heapst heaparr[])
{
heaparr[pos]=heaparr[ptr];
sift_down(pos,ptr,heaparr);
return ;
}
int main()
{
heapst heaparr[N];
int ptr=0,i,j,n;
scanf("%d",&n);
for (j=0;j<n;j++)
{
insert_heap(ptr,heaparr);
ptr++;
for (i=0;i<ptr;i++)
{
printf("%d ",heaparr[i].val);
}
printf("\n");
}
for (j=0;j<n;j++)
{
ptr--;
delete_heap(0,ptr,heaparr);
for (i=0;i<ptr;i++)
{
printf("%d ",heaparr[i].val);
}
printf("\n");
}
return 0;
}
| 16.196721 | 79 | 0.604251 |
cb9d0173efb9ccca805292ed7cb1ed2fb813b77c | 2,070 | h | C | src/gl/utility/gl_clock.h | atsb/ReGLOOME | 2770853677513f204e9282c71d3fd38e4cd6c472 | [
"Unlicense"
] | 79 | 2015-07-07T00:54:33.000Z | 2022-01-31T05:26:12.000Z | src/gl/utility/gl_clock.h | atsb/ReGLOOME | 2770853677513f204e9282c71d3fd38e4cd6c472 | [
"Unlicense"
] | 16 | 2015-07-02T20:10:02.000Z | 2016-04-15T14:58:45.000Z | src/gl/utility/gl_clock.h | atsb/ReGLOOME | 2770853677513f204e9282c71d3fd38e4cd6c472 | [
"Unlicense"
] | 30 | 2015-07-02T08:13:14.000Z | 2021-11-22T08:32:51.000Z | #ifndef __GL_CLOCK_H
#define __GL_CLOCK_H
#include "stats.h"
#include "x86.h"
#include "m_fixed.h"
#ifdef _MSC_VER
extern double gl_SecondsPerCycle;
extern double gl_MillisecPerCycle;
__forceinline long long GetClockCycle ()
{
#if _M_X64
return __rdtsc();
#else
return CPU.bRDTSC ? __rdtsc() : 0;
#endif
}
#elif defined(__GNUG__) && defined(__i386__)
extern double gl_SecondsPerCycle;
extern double gl_MillisecPerCycle;
inline long long GetClockCycle()
{
if (CPU.bRDTSC)
{
long long res;
asm volatile ("rdtsc" : "=A" (res));
return res;
}
else
{
return 0;
}
}
#else
extern double gl_SecondsPerCycle;
extern double gl_MillisecPerCycle;
inline long long GetClockCycle ()
{
return 0;
}
#endif
#if defined (__APPLE__)
typedef cycle_t glcycle_t;
#else // !__APPLE__
class glcycle_t
{
public:
glcycle_t &operator= (const glcycle_t &o)
{
Counter = o.Counter;
return *this;
}
void Reset()
{
Counter = 0;
}
__forceinline void Clock()
{
// Not using QueryPerformanceCounter directly, so we don't need
// to pull in the Windows headers for every single file that
// wants to do some profiling.
long long time = GetClockCycle();
Counter -= time;
}
__forceinline void Unclock()
{
long long time = GetClockCycle();
Counter += time;
}
double Time()
{
return double(Counter) * gl_SecondsPerCycle;
}
double TimeMS()
{
return double(Counter) * gl_MillisecPerCycle;
}
private:
long long Counter;
};
#endif // __APPLE__
extern glcycle_t RenderWall,SetupWall,ClipWall,SplitWall;
extern glcycle_t RenderFlat,SetupFlat;
extern glcycle_t RenderSprite,SetupSprite;
extern glcycle_t All, Finish, PortalAll, Bsp;
extern glcycle_t ProcessAll;
extern glcycle_t RenderAll;
extern glcycle_t Dirty;
extern int iter_dlightf, iter_dlight, draw_dlight, draw_dlightf;
extern int rendered_lines,rendered_flats,rendered_sprites,rendered_decals,render_vertexsplit,render_texsplit;
extern int rendered_portals;
extern int vertexcount, flatvertices, flatprimitives;
void ResetProfilingData();
void CheckBench();
#endif | 16.967213 | 109 | 0.743478 |
48c3c67ce50585a665747703f9667e8b4f7f26b7 | 55,763 | c | C | NetKVM/NDIS5/wxp/ParaNdis5-Impl.c | LinJunming/kvm-guest-drivers-windows | d55b74bc1c0ecb71a960c5747191d4ea2098fa3c | [
"BSD-3-Clause"
] | 982 | 2017-02-15T13:50:13.000Z | 2022-03-31T12:19:54.000Z | NetKVM/NDIS5/wxp/ParaNdis5-Impl.c | LinJunming/kvm-guest-drivers-windows | d55b74bc1c0ecb71a960c5747191d4ea2098fa3c | [
"BSD-3-Clause"
] | 373 | 2017-02-15T13:43:58.000Z | 2022-03-31T12:13:07.000Z | NetKVM/NDIS5/wxp/ParaNdis5-Impl.c | LinJunming/kvm-guest-drivers-windows | d55b74bc1c0ecb71a960c5747191d4ea2098fa3c | [
"BSD-3-Clause"
] | 219 | 2017-02-21T19:09:04.000Z | 2022-03-11T12:53:07.000Z | /*
* This file contains NDIS5.X Implementation of adapter driver procedures.
*
* Copyright (c) 2008-2017 Red Hat, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met :
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and / or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of their contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "ParaNdis5.h"
#ifdef WPP_EVENT_TRACING
#include "ParaNdis5-Impl.tmh"
#endif
/**********************************************************
Per-packet information holder
***********************************************************/
#define SEND_ENTRY_FLAG_READY 0x0001
#define SEND_ENTRY_TSO_USED 0x0002
#define SEND_ENTRY_NO_INDIRECT 0x0004
#define SEND_ENTRY_TCP_CS 0x0008
#define SEND_ENTRY_UDP_CS 0x0010
#define SEND_ENTRY_IP_CS 0x0020
typedef struct _tagSendEntry
{
LIST_ENTRY list;
PNDIS_PACKET packet;
ULONG flags;
ULONG ipTransferUnit;
union
{
ULONG PriorityDataLong;
UCHAR PriorityData[4];
};
} tSendEntry;
/**********************************************************
This defines field in NDIS_PACKET structure to use as holder
of our reference pointer for indicated packets
***********************************************************/
#define IDXTOUSE 0
#define REF_MINIPORT(Packet) ((PVOID *)(Packet->MiniportReservedEx + IDXTOUSE * sizeof(PVOID)))
/**********************************************************
Memory allocation procedure
Parameters:
context(not used)
ULONG ulRequiredSize size of block to allocate
Return value:
PVOID pointer to block or NULL if failed
***********************************************************/
PVOID ParaNdis_AllocateMemory(PARANDIS_ADAPTER *pContext, ULONG ulRequiredSize)
{
PVOID p;
UNREFERENCED_PARAMETER(pContext);
if (NDIS_STATUS_SUCCESS != NdisAllocateMemoryWithTag(&p, ulRequiredSize, PARANDIS_MEMORY_TAG))
p = NULL;
if (!p)
{
DPrintf(0, ("[%s] failed (%d bytes)", __FUNCTION__, ulRequiredSize));
}
return p;
}
/**********************************************************
Implementation of "open adapter configuration" operation
Parameters:
context
Return value:
NDIS_HANDLE Handle to open configuration or NULL, if failed
***********************************************************/
NDIS_HANDLE ParaNdis_OpenNICConfiguration(PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status;
NDIS_HANDLE cfg;
DEBUG_ENTRY(2);
NdisOpenConfiguration(&status, &cfg, pContext->WrapperConfigurationHandle);
if (status != NDIS_STATUS_SUCCESS)
cfg = NULL;
DEBUG_EXIT_STATUS(0, status);
return cfg;
}
void ParaNdis_RestoreDeviceConfigurationAfterReset(
PARANDIS_ADAPTER *pContext)
{
}
/**********************************************************
Indicates connect/disconnect events
Parameters:
context
BOOLEAN bConnected 1/0 connect/disconnect
***********************************************************/
VOID ParaNdis_IndicateConnect(PARANDIS_ADAPTER *pContext, BOOLEAN bConnected, BOOLEAN bForce)
{
// indicate disconnect always
if (bConnected != pContext->bConnected || bForce)
{
pContext->bConnected = bConnected;
DPrintf(0, ("Indicating %sconnect", bConnected ? "" : "dis"));
ParaNdis_DebugHistory(pContext, hopConnectIndication, NULL, bConnected, 0, 0);
NdisMIndicateStatus(
pContext->MiniportHandle,
bConnected ? NDIS_STATUS_MEDIA_CONNECT : NDIS_STATUS_MEDIA_DISCONNECT,
0,
0);
NdisMIndicateStatusComplete(pContext->MiniportHandle);
}
}
VOID ParaNdis_SetPowerState(PARANDIS_ADAPTER *pContext, NDIS_DEVICE_POWER_STATE newState)
{
//NDIS_DEVICE_POWER_STATE prev = pContext->powerState;
pContext->powerState = newState;
}
/**********************************************************
Callback of timer for connect indication, if used
Parameters:
context (on FunctionContext)
all the rest are irrelevant
***********************************************************/
static VOID OnConnectTimer(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext;
ParaNdis_ReportLinkStatus(pContext, FALSE);
}
/**********************************************************
NDIS5 implementation of shared memory allocation
Parameters:
context
tCompletePhysicalAddress *pAddresses
the structure accumulates all our knowledge
about the allocation (size, addresses, cacheability etc)
Return value:
TRUE if the allocation was successful
***********************************************************/
BOOLEAN ParaNdis_InitialAllocatePhysicalMemory(
PARANDIS_ADAPTER *pContext,
tCompletePhysicalAddress *pAddresses)
{
NdisMAllocateSharedMemory(
pContext->MiniportHandle,
pAddresses->size,
(BOOLEAN)pAddresses->IsCached,
&pAddresses->Virtual,
&pAddresses->Physical);
return pAddresses->Virtual != NULL;
}
/**********************************************************
Callback of timer for pending events cleanup after regular DPC processing
Parameters:
context (on FunctionContext)
all the rest are irrelevant
***********************************************************/
static VOID OnDPCPostProcessTimer(
IN PVOID SystemSpecific1,
IN PVOID FunctionContext,
IN PVOID SystemSpecific2,
IN PVOID SystemSpecific3
)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)FunctionContext;
ULONG requiresProcessing;
requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE);
if (requiresProcessing)
{
// we need to request additional DPC
InterlockedOr(&pContext->InterruptStatus, requiresProcessing);
NdisSetTimer(&pContext->DPCPostProcessTimer, 10);
}
}
/**********************************************************
NDIS5 implementation of shared memory freeing
Parameters:
context
tCompletePhysicalAddress *pAddresses
the structure accumulates all our knowledge
about the allocation (size, addresses, cacheability etc)
filled by ParaNdis_InitialAllocatePhysicalMemory
***********************************************************/
VOID ParaNdis_FreePhysicalMemory(
PARANDIS_ADAPTER *pContext,
tCompletePhysicalAddress *pAddresses)
{
NdisMFreeSharedMemory(
pContext->MiniportHandle,
pAddresses->size,
(BOOLEAN)pAddresses->IsCached,
pAddresses->Virtual,
pAddresses->Physical);
}
static void DebugParseOffloadBits()
{
NDIS_TCP_IP_CHECKSUM_PACKET_INFO info;
tChecksumCheckResult res;
ULONG val = 1;
int level = 1;
while (val)
{
info.Value = val;
if (info.Receive.NdisPacketIpChecksumFailed) DPrintf(level, ("W.%X=IPCS failed", val));
if (info.Receive.NdisPacketIpChecksumSucceeded) DPrintf(level, ("W.%X=IPCS OK", val));
if (info.Receive.NdisPacketTcpChecksumFailed) DPrintf(level, ("W.%X=TCPCS failed", val));
if (info.Receive.NdisPacketTcpChecksumSucceeded) DPrintf(level, ("W.%X=TCPCS OK", val));
if (info.Receive.NdisPacketUdpChecksumFailed) DPrintf(level, ("W.%X=UDPCS failed", val));
if (info.Receive.NdisPacketUdpChecksumSucceeded) DPrintf(level, ("W.%X=UDPCS OK", val));
val = val << 1;
}
val = 1;
while (val)
{
res.value = val;
if (res.flags.IpFailed) DPrintf(level, ("C.%X=IPCS failed", val));
if (res.flags.IpOK) DPrintf(level, ("C.%X=IPCS OK", val));
if (res.flags.TcpFailed) DPrintf(level, ("C.%X=TCPCS failed", val));
if (res.flags.TcpOK) DPrintf(level, ("C.%X=TCPCS OK", val));
if (res.flags.UdpFailed) DPrintf(level, ("C.%X=UDPCS failed", val));
if (res.flags.UdpOK) DPrintf(level, ("C.%X=UDPCS OK", val));
val = val << 1;
}
}
/**********************************************************
Procedure for NDIS5 specific initialization:
register interrupt handler
allocate pool of packets to indicate
allocate pool of buffers to indicate
initialize halt event
Parameters:
context
Return value:
SUCCESS or failure code
***********************************************************/
NDIS_STATUS ParaNdis_FinishSpecificInitialization(
PARANDIS_ADAPTER *pContext)
{
NDIS_STATUS status;
UINT nPackets = pContext->NetMaxReceiveBuffers * 2;
DEBUG_ENTRY(2);
NdisInitializeEvent(&pContext->HaltEvent);
InitializeListHead(&pContext->SendQueue);
InitializeListHead(&pContext->TxWaitingList);
NdisInitializeTimer(&pContext->ConnectTimer, OnConnectTimer, pContext);
NdisInitializeTimer(&pContext->DPCPostProcessTimer, OnDPCPostProcessTimer, pContext);
status = NdisMRegisterInterrupt(
&pContext->Interrupt,
pContext->MiniportHandle,
pContext->AdapterResources.Vector,
pContext->AdapterResources.Level,
TRUE,
TRUE,
NdisInterruptLevelSensitive);
if (status == NDIS_STATUS_SUCCESS)
{
NdisAllocatePacketPool(
&status,
&pContext->PacketPool,
nPackets,
PROTOCOL_RESERVED_SIZE_IN_PACKET );
}
if (status == NDIS_STATUS_SUCCESS)
{
NdisAllocateBufferPool(
&status,
&pContext->BuffersPool,
nPackets);
}
#if !DO_MAP_REGISTERS
if (status == NDIS_STATUS_SUCCESS)
{
status = NdisMInitializeScatterGatherDma(
pContext->MiniportHandle,
TRUE,
0x10000);
pContext->bDmaInitialized = status == NDIS_STATUS_SUCCESS;
}
#else
if (status == NDIS_STATUS_SUCCESS)
{
status = NdisMAllocateMapRegisters(
pContext->MiniportHandle,
0,
NDIS_DMA_32BITS,
64,
PAGE_SIZE);
pContext->bDmaInitialized = status == NDIS_STATUS_SUCCESS;
}
#endif
if (status == NDIS_STATUS_SUCCESS)
{
DebugParseOffloadBits();
}
DEBUG_EXIT_STATUS(status ? 0 : 2, status);
return status;
}
/**********************************************************
Procedure of NDIS5-specific cleanup:
deregister interrupt
free buffer and packet pool
Parameters:
context
***********************************************************/
VOID ParaNdis_FinalizeCleanup(PARANDIS_ADAPTER *pContext)
{
if (pContext->Interrupt.InterruptObject)
{
NdisMDeregisterInterrupt(&pContext->Interrupt);
}
if (pContext->BuffersPool)
{
NdisFreeBufferPool(pContext->BuffersPool);
}
if (pContext->PacketPool)
{
NdisFreePacketPool(pContext->PacketPool);
}
#if DO_MAP_REGISTERS
if (pContext->bDmaInitialized)
{
NdisMFreeMapRegisters(pContext->MiniportHandle);
}
#endif
}
static FORCEINLINE ULONG MaxNdisBufferDataSize(PARANDIS_ADAPTER *pContext, pIONetDescriptor pBufferDesc)
{
ULONG size = pBufferDesc->DataInfo.size;
if (pContext->bUseMergedBuffers) size -= pContext->nVirtioHeaderSize;
return size;
}
/**********************************************************
NDIS5-specific procedure for binding RX buffer to
NDIS_PACKET and NDIS_BUFFER
Parameters:
context
pIONetDescriptor pBuffersDesc VirtIO buffer descriptor
Return value:
TRUE, if bound successfully
FALSE, if no buffer or packet can be allocated
***********************************************************/
BOOLEAN ParaNdis_BindBufferToPacket(
PARANDIS_ADAPTER *pContext,
pIONetDescriptor pBufferDesc)
{
NDIS_STATUS status;
PNDIS_BUFFER pBuffer = NULL;
PNDIS_PACKET Packet = NULL;
NdisAllocatePacket(&status, &Packet, pContext->PacketPool);
if (status == NDIS_STATUS_SUCCESS)
{
NdisReinitializePacket(Packet);
NdisAllocateBuffer(
&status,
&pBuffer,
pContext->BuffersPool,
RtlOffsetToPointer(pBufferDesc->DataInfo.Virtual, pContext->bUseMergedBuffers ? pContext->nVirtioHeaderSize : 0),
MaxNdisBufferDataSize(pContext, pBufferDesc));
}
if (status == NDIS_STATUS_SUCCESS)
{
PNDIS_PACKET_OOB_DATA pOOB = NDIS_OOB_DATA_FROM_PACKET(Packet);
NdisZeroMemory(pOOB, sizeof(NDIS_PACKET_OOB_DATA));
NDIS_SET_PACKET_HEADER_SIZE(Packet, ETH_HEADER_SIZE);
NdisChainBufferAtFront(Packet, pBuffer);
pBufferDesc->pHolder = Packet;
}
else
{
if (pBuffer) NdisFreeBuffer(pBuffer);
if (Packet) NdisFreePacket(Packet);
}
return status == NDIS_STATUS_SUCCESS;
}
/**********************************************************
NDIS5-specific procedure for unbinding
previously bound RX buffer from it's NDIS_PACKET and NDIS_BUFFER
Parameters:
context
pIONetDescriptor pBuffersDesc VirtIO buffer descriptor
***********************************************************/
void ParaNdis_UnbindBufferFromPacket(
PARANDIS_ADAPTER *pContext,
pIONetDescriptor pBufferDesc)
{
if (pBufferDesc->pHolder)
{
PNDIS_BUFFER pBuffer = NULL;
PNDIS_PACKET Packet = pBufferDesc->pHolder;
pBufferDesc->pHolder = NULL;
NdisUnchainBufferAtFront(Packet, &pBuffer);
if (pBuffer)
{
NdisAdjustBufferLength(pBuffer, MaxNdisBufferDataSize(pContext, pBufferDesc));
NdisFreeBuffer(pBuffer);
}
NdisFreePacket(Packet);
}
}
/**********************************************************
NDIS5-specific procedure to indicate received packets
Parameters:
context
pIONetDescriptor pBuffersDescriptor - VirtIO buffer descriptor of data buffer
PVOID dataBuffer - data buffer to pass to network stack
PULONG pLength - size of received packet.
BOOLEAN bPrepareOnly - only return NBL for further indication in batch
Return value:
TRUE is packet indicated
FALSE if not (in this case, the descriptor should be freed now)
If priority header is in the packet. it will be removed and *pLength decreased
***********************************************************/
tPacketIndicationType ParaNdis_IndicateReceivedPacket(
PARANDIS_ADAPTER *pContext,
PVOID dataBuffer,
PULONG pLength,
BOOLEAN bPrepareOnly,
pIONetDescriptor pBuffersDesc)
{
BOOLEAN b = FALSE;
PNDIS_BUFFER pBuffer = NULL;
PNDIS_BUFFER pNoBuffer = NULL;
PNDIS_PACKET Packet = pBuffersDesc->pHolder;
ULONG length = *pLength;
if (Packet) NdisUnchainBufferAtFront(Packet, &pBuffer);
if (Packet) NdisUnchainBufferAtFront(Packet, &pNoBuffer);
if (pBuffer)
{
UINT uTotalLength;
NDIS_PACKET_8021Q_INFO qInfo;
qInfo.Value = NULL;
if ((pContext->ulPriorityVlanSetting && length > (ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE)) ||
length > pContext->MaxPacketSize.nMaxFullSizeOS)
{
PUCHAR pPriority = (PUCHAR)dataBuffer + ETH_PRIORITY_HEADER_OFFSET;
if (ETH_HAS_PRIO_HEADER(dataBuffer))
{
if (IsPrioritySupported(pContext))
qInfo.TagHeader.UserPriority = (pPriority[2] & 0xE0) >> 5;
if (IsVlanSupported(pContext))
{
qInfo.TagHeader.VlanId = (((USHORT)(pPriority[2] & 0x0F)) << 8) | pPriority[3];
if (pContext->VlanId && pContext->VlanId != qInfo.TagHeader.VlanId)
{
DPrintf(0, ("[%s] Failing unexpected VlanID %d", __FUNCTION__, qInfo.TagHeader.VlanId));
pContext->extraStatistics.framesFilteredOut++;
pBuffer = NULL;
}
}
RtlMoveMemory(
pPriority,
pPriority + ETH_PRIORITY_HEADER_SIZE,
length - ETH_PRIORITY_HEADER_OFFSET - ETH_PRIORITY_HEADER_SIZE);
length -= ETH_PRIORITY_HEADER_SIZE;
if (length > pContext->MaxPacketSize.nMaxFullSizeOS)
{
DPrintf(0, ("[%s] Can not indicate up packet of %d", __FUNCTION__, length));
pBuffer = NULL;
}
DPrintf(1, ("[%s] Found priority data %p", __FUNCTION__, qInfo.Value));
pContext->extraStatistics.framesRxPriority++;
}
}
if (pBuffer)
{
PVOID headerBuffer = pContext->bUseMergedBuffers ? pBuffersDesc->DataInfo.Virtual:pBuffersDesc->HeaderInfo.Virtual;
virtio_net_hdr_basic *pHeader = (virtio_net_hdr_basic *)headerBuffer;
tChecksumCheckResult csRes;
NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, Ieee8021QInfo) = qInfo.Value;
NDIS_SET_PACKET_STATUS(Packet, STATUS_SUCCESS);
ParaNdis_PadPacketReceived(dataBuffer, &length);
NdisAdjustBufferLength(pBuffer, length);
NdisChainBufferAtFront(Packet, pBuffer);
NdisQueryPacket(Packet, NULL, NULL, NULL, &uTotalLength);
*REF_MINIPORT(Packet) = pBuffersDesc;
csRes = ParaNdis_CheckRxChecksum(pContext, pHeader->flags, dataBuffer, length);
if (csRes.value)
{
NDIS_TCP_IP_CHECKSUM_PACKET_INFO qCSInfo;
qCSInfo.Value = 0;
qCSInfo.Receive.NdisPacketIpChecksumFailed = csRes.flags.IpFailed;
qCSInfo.Receive.NdisPacketIpChecksumSucceeded = csRes.flags.IpOK;
qCSInfo.Receive.NdisPacketTcpChecksumFailed = csRes.flags.TcpFailed;
qCSInfo.Receive.NdisPacketTcpChecksumSucceeded = csRes.flags.TcpOK;
qCSInfo.Receive.NdisPacketUdpChecksumFailed = csRes.flags.UdpFailed;
qCSInfo.Receive.NdisPacketUdpChecksumSucceeded = csRes.flags.UdpOK;
NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpIpChecksumPacketInfo) = (PVOID) (ULONG_PTR) qCSInfo.Value;
DPrintf(1, ("Reporting CS %X->%X", csRes.value, qCSInfo.Value));
}
DPrintf(4, ("[%s] buffer %p(%d b.)", __FUNCTION__, pBuffersDesc, length));
if (!bPrepareOnly)
{
NdisMIndicateReceivePacket(
pContext->MiniportHandle,
&Packet,
1);
}
}
*pLength = length;
}
if (!pBuffer)
{
DPrintf(0, ("[%s] Error: %p(%d b.) with packet %p", __FUNCTION__,
pBuffersDesc, length, Packet));
Packet = NULL;
}
if (pNoBuffer)
{
DPrintf(0, ("[%s] Error: %p(%d b.) with packet %p, buf %p,%p", __FUNCTION__,
pBuffersDesc, length, Packet, pBuffer, pNoBuffer));
}
return Packet;
}
VOID ParaNdis_IndicateReceivedBatch(
PARANDIS_ADAPTER *pContext,
tPacketIndicationType *pBatch,
ULONG nofPackets)
{
NdisMIndicateReceivePacket(
pContext->MiniportHandle,
pBatch,
nofPackets);
}
static FORCEINLINE void GET_NUMBER_OF_SG_ELEMENTS(PNDIS_PACKET Packet, UINT *pNum)
{
PSCATTER_GATHER_LIST pSGList;
pSGList = NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, ScatterGatherListPacketInfo);
if (pSGList)
{
*pNum = pSGList->NumberOfElements;
}
}
/**********************************************************
Complete TX packets to NDIS with status, indicated inside packet
Parameters:
context
PNDIS_PACKET Packet packet to complete
***********************************************************/
static void CompletePacket(PARANDIS_ADAPTER *pContext, PNDIS_PACKET Packet)
{
LONG lRestToReturn;
NDIS_STATUS status = NDIS_GET_PACKET_STATUS(Packet);
lRestToReturn = NdisInterlockedDecrement(&pContext->NetTxPacketsToReturn);
ParaNdis_DebugHistory(pContext, hopSendComplete, Packet, 0, lRestToReturn, status);
NdisMSendComplete(pContext->MiniportHandle, Packet, status);
}
/**********************************************************
Copy data from specified packet to VirtIO buffer, minimum 60 bytes
Parameters:
PNDIS_PACKET Packet packet to copy data from
PVOID dest destination to copy
ULONG maxSize maximal size of destination
Return value:
size = number of bytes copied
if 0, the packet is not transmitted and should be dropped
( should never happen)
request
***********************************************************/
tCopyPacketResult ParaNdis_PacketCopier(
PNDIS_PACKET Packet, PVOID dest, ULONG maxSize, PVOID refValue, BOOLEAN bPreview)
{
PNDIS_BUFFER pBuffer;
ULONG PriorityDataLong = ((tSendEntry *)refValue)->PriorityDataLong;
tCopyPacketResult result;
/* the copier called also for getting Ethernet header
for statistics, when the transfer uses SG table */
UINT uLength = 0;
ULONG nCopied = 0;
ULONG ulToCopy = 0;
if (bPreview) PriorityDataLong = 0;
NdisQueryPacket(Packet,
NULL,
NULL,
&pBuffer,
&ulToCopy);
if (ulToCopy > maxSize) ulToCopy = bPreview ? maxSize : 0;
while (pBuffer && ulToCopy)
{
PVOID VirtualAddress = NULL;
NdisQueryBufferSafe(pBuffer,
&VirtualAddress,
&uLength,
NormalPagePriority);
if (!VirtualAddress)
{
/* the packet copy failed */
nCopied = 0;
break;
}
if(uLength)
{
// Copy the data.
if (uLength > ulToCopy) uLength = ulToCopy;
ulToCopy -= uLength;
if ((PriorityDataLong & 0xFFFF) &&
nCopied < ETH_PRIORITY_HEADER_OFFSET &&
(nCopied + uLength) >= ETH_PRIORITY_HEADER_OFFSET)
{
ULONG ulCopyNow = ETH_PRIORITY_HEADER_OFFSET - nCopied;
NdisMoveMemory(dest, VirtualAddress, ulCopyNow);
dest = (PUCHAR)dest + ulCopyNow;
VirtualAddress = (PUCHAR)VirtualAddress + ulCopyNow;
NdisMoveMemory(dest, &PriorityDataLong, 4);
nCopied += 4;
dest = (PCHAR)dest + 4;
ulCopyNow = uLength - ulCopyNow;
if (ulCopyNow) NdisMoveMemory(dest, VirtualAddress, ulCopyNow);
dest = (PCHAR)dest + ulCopyNow;
nCopied += uLength;
}
else
{
NdisMoveMemory(dest, VirtualAddress, uLength);
nCopied += uLength;
dest = (PUCHAR)dest + uLength;
}
}
NdisGetNextBuffer(pBuffer, &pBuffer);
}
DEBUG_EXIT_STATUS(4, nCopied);
result.size = nCopied;
return result;
}
/**********************************************************
Callback on finished Tx descriptor
***********************************************************/
VOID ParaNdis_OnTransmitBufferReleased(PARANDIS_ADAPTER *pContext, IONetDescriptor *pDesc)
{
tSendEntry *pEntry = (tSendEntry *)pDesc->ReferenceValue;
if (pEntry)
{
DPrintf(2, ("[%s] Entry %p (packet %p, %d buffers) ready!", __FUNCTION__, pEntry, pEntry->packet, pDesc->nofUsedBuffers));
pEntry->flags |= SEND_ENTRY_FLAG_READY;
pDesc->ReferenceValue = NULL;
ParaNdis_DebugHistory(pContext, hopBufferSent, pEntry->packet, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors);
}
else
{
ParaNdis_DebugHistory(pContext, hopBufferSent, NULL, 0, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors);
DPrintf(0, ("[%s] ERROR: Send Entry not set!", __FUNCTION__));
}
}
static FORCEINLINE ULONG CalculateTotalOffloadSize(
ULONG packetSize,
ULONG mss,
ULONG ipheaderOffset,
ULONG maxPossiblePacketSize,
tTcpIpPacketParsingResult packetReview)
{
ULONG ul = 0;
ULONG tcpipHeaders = packetReview.XxpIpHeaderSize;
ULONG allHeaders = tcpipHeaders + ipheaderOffset;
if (tcpipHeaders && (mss + allHeaders) <= maxPossiblePacketSize)
{
ULONG nFragments = (packetSize - allHeaders)/mss;
ULONG last = (packetSize - allHeaders)%mss;
ul = nFragments * (mss + allHeaders) + last + (last ? allHeaders : 0);
}
DPrintf(1, ("[%s]%s %d/%d, headers %d)",
__FUNCTION__, !ul ? "ERROR:" : "", ul, mss, allHeaders));
return ul;
}
/**********************************************************
Maps the HW buffers of the packet into entries of VirtIO queue
Parameters:
miniport context
PNDIS_PACKET Packet packet to copy data from
PVOID ReferenceValue - tSendEntry * of the packet
VirtIOBufferDescriptor buffers = array of buffers to map packet buffers
(it contains number of SG entries >= number of hw elements in the packet)
pIONetDescriptor pDesc - holder of VirtIO header and reserved data buffer
for possible replacement of one or more HW buffers
Returns @pMapperResult: (zeroed before call)
.usBuffersMapped - number of buffers mapped (one of them may be our own)
.ulDataSize - number of bytes to report as transmitted (802.1P tag is not counted)
.usBufferSpaceUsed - number of bytes used in data space of pIONetDescriptor pDesc
***********************************************************/
VOID ParaNdis_PacketMapper(
PARANDIS_ADAPTER *pContext,
PNDIS_PACKET packet,
PVOID ReferenceValue,
struct VirtIOBufferDescriptor *buffers,
pIONetDescriptor pDesc,
tMapperResult *pMapperResult)
{
tSendEntry *pSendEntry = (tSendEntry *)ReferenceValue;
ULONG PriorityDataLong = pSendEntry->PriorityDataLong;
PSCATTER_GATHER_LIST pSGList = NDIS_PER_PACKET_INFO_FROM_PACKET(packet, ScatterGatherListPacketInfo);
SCATTER_GATHER_ELEMENT *pSGElements = pSGList->Elements;
if (pSGList && pSGList->NumberOfElements)
{
UINT i, lengthGet = 0, lengthPut = 0, nCompleteBuffersToSkip = 0, nBytesSkipInFirstBuffer = 0;
if (pSendEntry->flags & (SEND_ENTRY_TSO_USED | SEND_ENTRY_TCP_CS | SEND_ENTRY_UDP_CS | SEND_ENTRY_IP_CS))
lengthGet = pContext->Offload.ipHeaderOffset + MAX_IPV4_HEADER_SIZE + sizeof(TCPHeader);
if (PriorityDataLong && !lengthGet)
lengthGet = ETH_HEADER_SIZE;
if (lengthGet)
{
ULONG len = 0;
for (i = 0; i < pSGList->NumberOfElements; ++i)
{
len += pSGElements[i].Length;
if (len > lengthGet)
{
nBytesSkipInFirstBuffer = pSGList->Elements[i].Length - (len - lengthGet);
break;
}
DPrintf(2, ("[%s] skipping buffer %d of %d", __FUNCTION__, nCompleteBuffersToSkip, pSGElements[i].Length));
nCompleteBuffersToSkip++;
}
// just for case of UDP packet shorter than TCP header
if (lengthGet > len) lengthGet = len;
lengthPut = lengthGet + (PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0);
}
if (lengthPut > pDesc->DataInfo.size)
{
DPrintf(0, ("[%s] ERROR: can not substitute %d bytes, sending as is", __FUNCTION__, lengthPut));
nCompleteBuffersToSkip = 0;
nBytesSkipInFirstBuffer = 0;
lengthGet = lengthPut = 0;
}
if (lengthPut)
{
// we replace 1 or more HW buffers with one buffer preallocated for data
buffers->physAddr = pDesc->DataInfo.Physical;
buffers->length = lengthPut;
pMapperResult->usBufferSpaceUsed = (USHORT)lengthPut;
pMapperResult->ulDataSize += lengthGet;
pMapperResult->usBuffersMapped = (USHORT)(pSGList->NumberOfElements - nCompleteBuffersToSkip + 1);
pSGElements += nCompleteBuffersToSkip;
buffers++;
DPrintf(1, ("[%s](%d bufs) skip %d buffers + %d bytes",
__FUNCTION__, pSGList->NumberOfElements, nCompleteBuffersToSkip, nBytesSkipInFirstBuffer));
}
else
{
pMapperResult->usBuffersMapped = (USHORT)pSGList->NumberOfElements;
}
for (i = nCompleteBuffersToSkip; i < pSGList->NumberOfElements; ++i)
{
if (nBytesSkipInFirstBuffer)
{
buffers->physAddr.QuadPart = pSGElements->Address.QuadPart + nBytesSkipInFirstBuffer;
buffers->length = pSGElements->Length - nBytesSkipInFirstBuffer;
DPrintf(2, ("[%s] using HW buffer %d of %d-%d", __FUNCTION__, i, pSGElements->Length, nBytesSkipInFirstBuffer));
nBytesSkipInFirstBuffer = 0;
}
else
{
buffers->physAddr = pSGElements->Address;
buffers->length = pSGElements->Length;
}
pMapperResult->ulDataSize += buffers->length;
pSGElements++;
buffers++;
}
if (lengthPut)
{
PVOID pBuffer = pDesc->DataInfo.Virtual;
PVOID pIpHeader = RtlOffsetToPointer(pBuffer, pContext->Offload.ipHeaderOffset);
ParaNdis_PacketCopier(packet, pBuffer, lengthGet, ReferenceValue, TRUE);
if (pSendEntry->flags & SEND_ENTRY_TSO_USED)
{
tTcpIpPacketParsingResult packetReview;
ULONG dummyTransferSize = 0;
USHORT saveBuffers = pMapperResult->usBuffersMapped;
ULONG flags = pcrIpChecksum | pcrTcpChecksum | pcrFixIPChecksum | pcrFixPHChecksum;
pMapperResult->usBuffersMapped = 0;
packetReview = ParaNdis_CheckSumVerify(
pIpHeader,
lengthGet - pContext->Offload.ipHeaderOffset,
flags,
__FUNCTION__);
/* uncomment to verify */
/*
packetReview = ParaNdis_CheckSumVerify(
pIpHeader,
lengthGet - pContext->Offload.ipHeaderOffset,
pcrIpChecksum | pcrTcpChecksum,
__FUNCTION__);
*/
if (packetReview.ipCheckSum == ppresCSOK || packetReview.fixedIpCS)
{
dummyTransferSize = CalculateTotalOffloadSize(
pMapperResult->ulDataSize,
pSendEntry->ipTransferUnit,
pContext->Offload.ipHeaderOffset,
pContext->MaxPacketSize.nMaxFullSizeOS,
packetReview);
}
else
{
DPrintf(0, ("[%s] ERROR locating IP header in %d bytes(IP header of %d)", __FUNCTION__,
lengthGet, packetReview.ipHeaderSize));
}
NDIS_PER_PACKET_INFO_FROM_PACKET(packet, TcpLargeSendPacketInfo) = (PVOID)(ULONG_PTR)dummyTransferSize;
if (dummyTransferSize)
{
virtio_net_hdr_basic *pheader = pDesc->HeaderInfo.Virtual;
unsigned short addPriorityLen = PriorityDataLong ? ETH_PRIORITY_HEADER_SIZE : 0;
pheader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
pheader->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
pheader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + pContext->Offload.ipHeaderOffset) + addPriorityLen;
pheader->gso_size = (USHORT)pSendEntry->ipTransferUnit;
pheader->csum_start = (USHORT)pContext->Offload.ipHeaderOffset + (USHORT)packetReview.ipHeaderSize + addPriorityLen;
pheader->csum_offset = TCP_CHECKSUM_OFFSET;
pMapperResult->usBuffersMapped = saveBuffers;
}
}
else if (pSendEntry->flags & SEND_ENTRY_IP_CS)
{
ParaNdis_CheckSumVerify(
pIpHeader,
lengthGet - pContext->Offload.ipHeaderOffset,
pcrIpChecksum | pcrFixIPChecksum,
__FUNCTION__);
}
if (PriorityDataLong && pMapperResult->usBuffersMapped)
{
RtlMoveMemory(
RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET + ETH_PRIORITY_HEADER_SIZE),
RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET),
lengthGet - ETH_PRIORITY_HEADER_OFFSET
);
NdisMoveMemory(
RtlOffsetToPointer(pBuffer, ETH_PRIORITY_HEADER_OFFSET),
&PriorityDataLong,
sizeof(ETH_PRIORITY_HEADER_SIZE));
DPrintf(1, ("[%s] Populated priority value %lX", __FUNCTION__, PriorityDataLong));
}
}
}
}
static void InitializeTransferParameters(tTxOperationParameters *pParams, tSendEntry *pEntry)
{
ULONG flags = (pEntry->flags & SEND_ENTRY_TSO_USED) ? pcrLSO : 0;
if (pEntry->flags & SEND_ENTRY_NO_INDIRECT) flags |= pcrNoIndirect;
NdisQueryPacket(pEntry->packet, &pParams->nofSGFragments, NULL, NULL, &pParams->ulDataSize);
pParams->ReferenceValue = pEntry;
pParams->packet = pEntry->packet;
pParams->offloadMss = (pEntry->flags & SEND_ENTRY_TSO_USED) ? pEntry->ipTransferUnit : 0;
// on NDIS5 it is unknown
pParams->tcpHeaderOffset = 0;
// fills only if SGList present in the packet
GET_NUMBER_OF_SG_ELEMENTS(pEntry->packet, &pParams->nofSGFragments);
if (NDIS_GET_PACKET_PROTOCOL_TYPE(pEntry->packet) == NDIS_PROTOCOL_ID_TCP_IP)
{
flags |= pcrIsIP;
if (pEntry->flags & SEND_ENTRY_TCP_CS)
{
flags |= pcrTcpChecksum;
}
if (pEntry->flags & SEND_ENTRY_UDP_CS)
{
flags |= pcrUdpChecksum;
}
if (pEntry->flags & SEND_ENTRY_IP_CS)
{
flags |= pcrIpChecksum;
}
}
if (pEntry->PriorityDataLong) flags |= pcrPriorityTag;
pParams->flags = flags;
}
BOOLEAN ParaNdis_ProcessTx(
PARANDIS_ADAPTER *pContext,
BOOLEAN IsDpc,
BOOLEAN IsInterrupt)
{
LIST_ENTRY DoneList;
BOOLEAN bDoKick = FALSE;
UINT nBuffersSent = 0, nBytesSent = 0;
BOOLEAN bDataAvailable = FALSE;
tSendEntry *pEntry;
ONPAUSECOMPLETEPROC CallbackToCall = NULL;
InitializeListHead(&DoneList);
UNREFERENCED_PARAMETER(IsDpc);
NdisAcquireSpinLock(&pContext->SendLock);
ParaNdis_DebugHistory(pContext, hopTxProcess, NULL, 1, pContext->nofFreeHardwareBuffers, pContext->nofFreeTxDescriptors);
do
{
if(IsTimeToReleaseTx(pContext))
{
// release some buffers
ParaNdis_VirtIONetReleaseTransmitBuffers(pContext);
}
pEntry = NULL;
if (!IsListEmpty(&pContext->SendQueue))
{
tCopyPacketResult result;
tTxOperationParameters Params;
pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue);
InitializeTransferParameters(&Params, pEntry);
bDataAvailable = TRUE;
result = ParaNdis_DoSubmitPacket(pContext, &Params);
if (result.error == cpeNoBuffer)
{
// can not send now, try next time
InsertHeadList(&pContext->SendQueue, &pEntry->list);
pEntry = NULL;
}
else if (result.error == cpeNoIndirect)
{
InsertHeadList(&pContext->SendQueue, &pEntry->list);
pEntry->flags |= SEND_ENTRY_NO_INDIRECT;
}
else
{
InsertTailList(&pContext->TxWaitingList, &pEntry->list);
ParaNdis_DebugHistory(pContext, hopSubmittedPacket, pEntry->packet, 0, result.error, Params.flags);
if (!result.size)
{
NDIS_STATUS status = NDIS_STATUS_FAILURE;
DPrintf(0, ("[%s] ERROR %d copying packet!", __FUNCTION__, result.error));
if (result.error == cpeTooLarge)
{
status = NDIS_STATUS_BUFFER_OVERFLOW;
pContext->Statistics.ifOutErrors++;
}
NDIS_SET_PACKET_STATUS(pEntry->packet, status);
pEntry->flags |= SEND_ENTRY_FLAG_READY;
// do not worry, go to the next one
}
else
{
nBuffersSent++;
nBytesSent += result.size;
DPrintf(2, ("[%s] Scheduled packet %p, entry %p(%d bytes)!", __FUNCTION__,
pEntry->packet, pEntry, result.size));
}
}
}
} while (pEntry);
if (nBuffersSent)
{
if(IsInterrupt)
{
bDoKick = TRUE;
}
else
{
#ifdef PARANDIS_TEST_TX_KICK_ALWAYS
virtqueue_kick_always(pContext->NetSendQueue);
#else
virtqueue_kick(pContext->NetSendQueue);
#endif
}
DPrintf(2, ("[%s] sent down %d p.(%d b.)", __FUNCTION__, nBuffersSent, nBytesSent));
}
else if (bDataAvailable)
{
DPrintf(2, ("[%s] nothing sent", __FUNCTION__));
}
/* now check the waiting list of packets */
while (!IsListEmpty(&pContext->TxWaitingList))
{
pEntry = (tSendEntry *)RemoveHeadList(&pContext->TxWaitingList);
if (pEntry->flags & SEND_ENTRY_FLAG_READY)
{
InsertTailList(&DoneList, &pEntry->list);
}
else
{
InsertHeadList(&pContext->TxWaitingList, &pEntry->list);
break;
}
}
if (IsListEmpty(&pContext->TxWaitingList) && pContext->SendState == srsPausing && pContext->SendPauseCompletionProc)
{
CallbackToCall = pContext->SendPauseCompletionProc;
pContext->SendPauseCompletionProc = NULL;
pContext->SendState = srsDisabled;
ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0);
}
NdisReleaseSpinLock(&pContext->SendLock);
while (!IsListEmpty(&DoneList))
{
pEntry = (tSendEntry *)RemoveHeadList(&DoneList);
CompletePacket(pContext, pEntry->packet);
NdisFreeMemory(pEntry, 0, 0);
}
if (CallbackToCall) CallbackToCall(pContext);
return bDoKick;
}
/**********************************************************
NDIS releases packets previously indicated by miniport
Free the packet's buffer and the packet back to their pools
Returns VirtIO buffer back to queue of free blocks
Parameters:
context
IN PNDIS_PACKET Packet returned packet
***********************************************************/
VOID ParaNdis5_ReturnPacket(IN NDIS_HANDLE MiniportAdapterContext,IN PNDIS_PACKET Packet)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext;
PNDIS_BUFFER pBuffer = NULL;
UINT nBuffers = 0;
pIONetDescriptor pBufferDescriptor;
pBufferDescriptor = (pIONetDescriptor) *REF_MINIPORT(Packet);
DPrintf(4, ("[%s] buffer %p", __FUNCTION__, pBufferDescriptor));
NdisAcquireSpinLock(&pContext->ReceiveLock);
pContext->ReuseBufferProc(pContext, pBufferDescriptor);
NdisReleaseSpinLock(&pContext->ReceiveLock);
}
static __inline tSendEntry * PrepareSendEntry(PARANDIS_ADAPTER *pContext, PNDIS_PACKET Packet, ULONG len)
{
ULONG mss = (ULONG)(ULONG_PTR)NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpLargeSendPacketInfo);
UINT protocol = NDIS_GET_PACKET_PROTOCOL_TYPE(Packet);
LPCSTR errorFmt = NULL;
LPCSTR offloadName = "NO offload";
tSendEntry *pse = (tSendEntry *)ParaNdis_AllocateMemory(pContext, sizeof(tSendEntry));
if (pse)
{
NDIS_PACKET_8021Q_INFO qInfo;
pse->packet = Packet;
pse->flags = 0;
pse->PriorityDataLong = 0;
pse->ipTransferUnit = len;
//pse->fullTCPCheckSum = 0;
qInfo.Value = pContext->ulPriorityVlanSetting ?
NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, Ieee8021QInfo) : NULL;
if (!qInfo.TagHeader.VlanId) qInfo.TagHeader.VlanId = pContext->VlanId;
if (qInfo.TagHeader.CanonicalFormatId || !IsValidVlanId(pContext, qInfo.TagHeader.VlanId))
{
DPrintf(0, ("[%s] Discarding priority tag %p", __FUNCTION__, qInfo.Value));
errorFmt = "invalid priority tag";
}
else if (qInfo.Value)
{
// ignore priority, if configured
if (!IsPrioritySupported(pContext))
qInfo.TagHeader.UserPriority = 0;
// ignore VlanId, if specified
if (!IsVlanSupported(pContext))
qInfo.TagHeader.VlanId = 0;
SetPriorityData(pse->PriorityData, qInfo.TagHeader.UserPriority, qInfo.TagHeader.VlanId);
DPrintf(1, ("[%s] Populated priority tag %p", __FUNCTION__, qInfo.Value));
}
if (!errorFmt && !mss && len > pContext->MaxPacketSize.nMaxFullSizeOS)
{
DPrintf(0, ("[%s] Request for offload with NO MSS, lso %d, ipheader %d",
__FUNCTION__, pContext->Offload.flags.fTxLso, pContext->Offload.ipHeaderOffset));
if (pContext->Offload.flags.fTxLso && pContext->Offload.ipHeaderOffset)
{
mss = pContext->MaxPacketSize.nMaxFullSizeOS;
}
else
errorFmt = "illegal LSO request";
}
if (errorFmt)
{
// already failed
}
else if (mss > pContext->MaxPacketSize.nMaxFullSizeOS)
errorFmt = "mss is too big";
else if (len > 0xFFFF)
errorFmt = "packet is bigger than we able to send";
else if (mss && pContext->Offload.flags.fTxLso)
{
offloadName = "LSO";
pse->ipTransferUnit = mss;
pse->flags |= SEND_ENTRY_TSO_USED;
// todo: move to common space
// to transmit 'len' with 'mss' we usually need 2 additional buffers
if ((len / mss + 3) > pContext->maxFreeHardwareBuffers)
errorFmt = "packet too big to fragment";
else if (len < pContext->Offload.ipHeaderOffset)
errorFmt = "ip offset is bigger than packet";
else if (protocol != NDIS_PROTOCOL_ID_TCP_IP)
errorFmt = "attempt to offload non-IP packet";
else if (mss < pContext->Offload.ipHeaderOffset)
errorFmt = "mss is too small";
}
else
{
// unexpected CS requests we do not fail - WHQL expects us to send them as is
NDIS_TCP_IP_CHECKSUM_PACKET_INFO csInfo;
csInfo.Value = (ULONG)(ULONG_PTR)NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpIpChecksumPacketInfo);
if (csInfo.Transmit.NdisPacketChecksumV4)
{
if (csInfo.Transmit.NdisPacketTcpChecksum)
{
offloadName = "TCP CS";
if (pContext->Offload.flags.fTxTCPChecksum)
pse->flags |= SEND_ENTRY_TCP_CS;
else
errorFmt = "TCP CS requested but not enabled";
}
if (csInfo.Transmit.NdisPacketUdpChecksum)
{
offloadName = "UDP CS";
if (pContext->Offload.flags.fTxUDPChecksum)
pse->flags |= SEND_ENTRY_UDP_CS;
else
errorFmt = "UDP CS requested but not enabled";
}
if (csInfo.Transmit.NdisPacketIpChecksum)
{
if (pContext->Offload.flags.fTxIPChecksum)
pse->flags |= SEND_ENTRY_IP_CS;
else
errorFmt = "IP CS requested but not enabled";
}
if (errorFmt)
{
DPrintf(0, ("[%s] ERROR: %s (len %d)", __FUNCTION__, errorFmt, len));
errorFmt = NULL;
}
}
}
}
if (errorFmt)
{
DPrintf(0, ("[%s] ERROR: %s (len %d, mss %d)", __FUNCTION__, errorFmt, len, mss));
if (pse) NdisFreeMemory(pse, 0, 0);
pse = NULL;
}
else
{
NDIS_PER_PACKET_INFO_FROM_PACKET(Packet, TcpLargeSendPacketInfo) = (PVOID)(ULONG_PTR)0;
DPrintf(1, ("[%s] Sending packet of %d with %s", __FUNCTION__, len, offloadName));
if (pContext->bDoIPCheckTx)
{
tTcpIpPacketParsingResult res;
VOID *pcopy = ParaNdis_AllocateMemory(pContext, len);
ParaNdis_PacketCopier(pse->packet, pcopy, len, pse, TRUE);
res = ParaNdis_CheckSumVerify(
RtlOffsetToPointer(pcopy, pContext->Offload.ipHeaderOffset),
len,
pcrAnyChecksum/* | pcrFixAnyChecksum*/,
__FUNCTION__);
/*
if (res.xxpStatus == ppresXxpKnown)
{
TCPHeader *ptcp = (TCPHeader *)
RtlOffsetToPointer(pcopy, pContext->Offload.ipHeaderOffset + res.ipHeaderSize);
pse->fullTCPCheckSum = ptcp->tcp_xsum;
}
*/
NdisFreeMemory(pcopy, 0, 0);
}
}
return pse;
}
/**********************************************************
NDIS sends us packets
Queues packets internally and calls the procedure to process the queue
Parameters:
context
IN PPNDIS_PACKET PacketArray Array of packets to send
IN UINT NumberOfPackets number of packets
***********************************************************/
VOID ParaNdis5_SendPackets(IN NDIS_HANDLE MiniportAdapterContext,
IN PPNDIS_PACKET PacketArray,
IN UINT NumberOfPackets)
{
UINT i;
LIST_ENTRY FailedList, DoneList;
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext;
InitializeListHead(&FailedList);
InitializeListHead(&DoneList);
DPrintf(3, ("[%s] %d packets", __FUNCTION__, NumberOfPackets));
ParaNdis_DebugHistory(pContext, hopSend, NULL, 1, NumberOfPackets, 0);
NdisAcquireSpinLock(&pContext->SendLock);
for (i = 0; i < NumberOfPackets; ++i)
{
UINT uPacketLength = 0;
NdisQueryPacketLength(PacketArray[i], &uPacketLength);
NDIS_SET_PACKET_STATUS(PacketArray[i], NDIS_STATUS_SUCCESS);
NdisInterlockedIncrement(&pContext->NetTxPacketsToReturn);
if (!pContext->bSurprizeRemoved && pContext->bConnected && pContext->SendState == srsEnabled && uPacketLength)
{
tSendEntry *pse = PrepareSendEntry(pContext, PacketArray[i], uPacketLength);
if (!pse)
{
NDIS_SET_PACKET_STATUS(PacketArray[i], NDIS_STATUS_FAILURE);
CompletePacket(pContext, PacketArray[i]);
}
else
{
UINT nFragments = 0;
GET_NUMBER_OF_SG_ELEMENTS(PacketArray[i], &nFragments);
ParaNdis_DebugHistory(pContext, hopSendPacketMapped, PacketArray[i], 0, nFragments, 0);
InsertTailList(&pContext->SendQueue, &pse->list);
}
}
else
{
NDIS_STATUS status = NDIS_STATUS_FAILURE;
if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED;
NDIS_SET_PACKET_STATUS(PacketArray[i], status);
CompletePacket(pContext, PacketArray[i]);
DPrintf(1, ("[%s] packet of %d rejected", __FUNCTION__, uPacketLength));
}
}
NdisReleaseSpinLock(&pContext->SendLock);
ParaNdis_ProcessTx(pContext, FALSE, FALSE);
}
/**********************************************************
NDIS procedure, not easy to test
NDIS asks us to cancel packets with specified CancelID
Parameters:
context
PVOID CancelId ID to cancel
***********************************************************/
VOID ParaNdis5_CancelSendPackets(IN NDIS_HANDLE MiniportAdapterContext,IN PVOID CancelId)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext;
LIST_ENTRY DoneList, KeepList;
UINT n = 0;
tSendEntry *pEntry;
DEBUG_ENTRY(0);
InitializeListHead(&DoneList);
InitializeListHead(&KeepList);
NdisAcquireSpinLock(&pContext->SendLock);
while ( !IsListEmpty(&pContext->SendQueue))
{
PNDIS_PACKET Packet;
pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue);
Packet = pEntry->packet;
if (NDIS_GET_PACKET_CANCEL_ID(Packet) == CancelId)
{
InsertTailList(&DoneList, &pEntry->list);
++n;
}
else InsertTailList(&KeepList, &pEntry->list);
}
while ( !IsListEmpty(&KeepList))
{
pEntry = (tSendEntry *)RemoveHeadList(&KeepList);
InsertTailList(&pContext->SendQueue, &pEntry->list);
}
NdisReleaseSpinLock(&pContext->SendLock);
while (!IsListEmpty(&DoneList))
{
pEntry = (tSendEntry *)RemoveHeadList(&DoneList);
NDIS_SET_PACKET_STATUS(pEntry->packet, NDIS_STATUS_REQUEST_ABORTED);
CompletePacket(pContext, pEntry->packet);
NdisFreeMemory(pEntry, 0, 0);
}
DEBUG_EXIT_STATUS(0, n);
}
/**********************************************************
Request to pause or resume data transmit
if stopped, all the packets in internal queue are returned
Parameters:
context
BOOLEAN bStop 1/0 - top or resume
***********************************************************/
NDIS_STATUS ParaNdis5_StopSend(PARANDIS_ADAPTER *pContext, BOOLEAN bStop, ONPAUSECOMPLETEPROC Callback)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
if (bStop)
{
LIST_ENTRY DoneList;
tSendEntry *pEntry;
DEBUG_ENTRY(0);
ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 1, 0, 0);
InitializeListHead(&DoneList);
NdisAcquireSpinLock(&pContext->SendLock);
if (IsListEmpty(&pContext->TxWaitingList))
{
pContext->SendState = srsDisabled;
while (!IsListEmpty(&pContext->SendQueue))
{
pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue);
InsertTailList(&DoneList, &pEntry->list);
}
ParaNdis_DebugHistory(pContext, hopInternalSendPause, NULL, 0, 0, 0);
}
else
{
pContext->SendState = srsPausing;
pContext->SendPauseCompletionProc = Callback;
status = NDIS_STATUS_PENDING;
while (!IsListEmpty(&pContext->SendQueue))
{
pEntry = (tSendEntry *)RemoveHeadList(&pContext->SendQueue);
pEntry->flags |= SEND_ENTRY_FLAG_READY;
InsertTailList(&pContext->TxWaitingList, &pEntry->list);
}
}
NdisReleaseSpinLock(&pContext->SendLock);
while (!IsListEmpty(&DoneList))
{
pEntry = (tSendEntry *)RemoveHeadList(&DoneList);
NDIS_SET_PACKET_STATUS(pEntry->packet, NDIS_STATUS_REQUEST_ABORTED);
CompletePacket(pContext, pEntry->packet);
NdisFreeMemory(pEntry, 0, 0);
}
}
else
{
pContext->SendState = srsEnabled;
ParaNdis_DebugHistory(pContext, hopInternalSendResume, NULL, 0, 0, 0);
}
return status;
}
/**********************************************************
Pause or resume receive operation:
Parameters:
context
BOOLEAN bStop 1/0 - pause or resume
ONPAUSECOMPLETEPROC Callback callback to call, if not completed immediately
Return value:
SUCCESS, if there is no RX packets under NDIS management
PENDING, if we need to wait until NDIS returns us packets
***********************************************************/
NDIS_STATUS ParaNdis5_StopReceive(
PARANDIS_ADAPTER *pContext,
BOOLEAN bStop,
ONPAUSECOMPLETEPROC Callback
)
{
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
if (bStop)
{
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 1, 0, 0);
NdisAcquireSpinLock(&pContext->ReceiveLock);
if (IsListEmpty(&pContext->NetReceiveBuffersWaiting))
{
pContext->ReceiveState = srsDisabled;
ParaNdis_DebugHistory(pContext, hopInternalReceivePause, NULL, 0, 0, 0);
}
else
{
pContext->ReceiveState = srsPausing;
pContext->ReceivePauseCompletionProc = Callback;
status = NDIS_STATUS_PENDING;
}
NdisReleaseSpinLock(&pContext->ReceiveLock);
}
else
{
pContext->ReceiveState = srsEnabled;
ParaNdis_DebugHistory(pContext, hopInternalReceiveResume, NULL, 0, 0, 0);
}
return status;
}
/*************************************************************
Required NDIS procedure, spawns regular (Common) DPC processing
*************************************************************/
VOID ParaNdis5_HandleDPC(IN NDIS_HANDLE MiniportAdapterContext)
{
PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)MiniportAdapterContext;
ULONG requiresProcessing;
BOOLEAN unused;
DEBUG_ENTRY(7);
// we do not need the timer, as DPC will do all the job
// this is not a problem if the timer procedure is already running,
// we need to do our job anyway
NdisCancelTimer(&pContext->DPCPostProcessTimer, &unused);
requiresProcessing = ParaNdis_DPCWorkBody(pContext, PARANDIS_UNLIMITED_PACKETS_TO_INDICATE);
if (requiresProcessing)
{
// we need to request additional DPC
InterlockedOr(&pContext->InterruptStatus, requiresProcessing);
NdisSetTimer(&pContext->DPCPostProcessTimer, 10);
}
}
BOOLEAN ParaNdis_SynchronizeWithInterrupt(
PARANDIS_ADAPTER *pContext,
ULONG messageId,
tSynchronizedProcedure procedure,
PVOID parameter)
{
tSynchronizedContext SyncContext;
SyncContext.pContext = pContext;
SyncContext.Parameter = parameter;
return NdisMSynchronizeWithInterrupt(&pContext->Interrupt, procedure, &SyncContext);
}
| 37.728687 | 140 | 0.596274 |
16421bd16b71d5044e464e854fe138e082187d24 | 2,463 | c | C | tools/tpm2_nvincrement.c | remuswu1019/tpm2-tools | db2c5dfeeab012e36a6a9a641a9642465197b51d | [
"BSD-3-Clause"
] | null | null | null | tools/tpm2_nvincrement.c | remuswu1019/tpm2-tools | db2c5dfeeab012e36a6a9a641a9642465197b51d | [
"BSD-3-Clause"
] | null | null | null | tools/tpm2_nvincrement.c | remuswu1019/tpm2-tools | db2c5dfeeab012e36a6a9a641a9642465197b51d | [
"BSD-3-Clause"
] | null | null | null | /* SPDX-License-Identifier: BSD-3-Clause */
#include <stdlib.h>
#include "tpm2_nv_util.h"
#include "tpm2_tool.h"
typedef struct tpm_nvincrement_ctx tpm_nvincrement_ctx;
struct tpm_nvincrement_ctx {
struct {
const char *ctx_path;
const char *auth_str;
tpm2_loaded_object object;
} auth_hierarchy;
TPM2_HANDLE nv_index;
};
static tpm_nvincrement_ctx ctx;
static bool on_option(char key, char *value) {
bool result;
switch (key) {
case 'x':
result = tpm2_util_string_to_uint32(value, &ctx.nv_index);
if (!result) {
LOG_ERR("Could not convert NV index to number, got: \"%s\"",
value);
return false;
}
if (ctx.nv_index == 0) {
LOG_ERR("NV Index cannot be 0");
return false;
}
/* If the users doesn't specify an authorisation hierarchy use the index
* passed to -x/--index for the authorisation index.
*/
ctx.auth_hierarchy.ctx_path = value;
break;
case 'C':
ctx.auth_hierarchy.ctx_path = value;
break;
case 'P':
ctx.auth_hierarchy.auth_str = value;
break;
}
return true;
}
bool tpm2_tool_onstart(tpm2_options **opts) {
const struct option topts[] = {
{ "index", required_argument, NULL, 'x' },
{ "hierarchy", required_argument, NULL, 'C' },
{ "auth", required_argument, NULL, 'P' },
};
*opts = tpm2_options_new("x:C:P:", ARRAY_LEN(topts), topts,
on_option, NULL, 0);
return *opts != NULL;
}
tool_rc tpm2_tool_onrun(ESYS_CONTEXT *ectx, tpm2_option_flags flags) {
UNUSED(flags);
tool_rc rc = tpm2_util_object_load_auth(ectx, ctx.auth_hierarchy.ctx_path,
ctx.auth_hierarchy.auth_str, &ctx.auth_hierarchy.object, false,
TPM2_HANDLES_FLAGS_NV|TPM2_HIERARCHY_FLAGS_O|TPM2_HIERARCHY_FLAGS_P);
if (rc != tool_rc_success) {
LOG_ERR("Invalid handle authorization");
return rc;
}
rc = tpm2_nv_increment(ectx, &ctx.auth_hierarchy.object, ctx.nv_index);
if (rc != tool_rc_success) {
LOG_ERR("Failed to increment NV counter at index 0x%X", ctx.nv_index);
return rc;
}
return tool_rc_success;
}
tool_rc tpm2_tool_onstop(ESYS_CONTEXT *ectx) {
UNUSED(ectx);
return tpm2_session_close(&ctx.auth_hierarchy.object.session);
}
| 26.771739 | 80 | 0.613886 |
8596164b0570d83e4a3f0d6081fe752788eb1077 | 5,065 | h | C | aws-cpp-sdk-ce/include/aws/ce/model/TerminateRecommendationDetail.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-ce/include/aws/ce/model/TerminateRecommendationDetail.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ce/include/aws/ce/model/TerminateRecommendationDetail.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ce/CostExplorer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace CostExplorer
{
namespace Model
{
/**
* <p>Details on termination recommendation. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ce-2017-10-25/TerminateRecommendationDetail">AWS
* API Reference</a></p>
*/
class AWS_COSTEXPLORER_API TerminateRecommendationDetail
{
public:
TerminateRecommendationDetail();
TerminateRecommendationDetail(Aws::Utils::Json::JsonView jsonValue);
TerminateRecommendationDetail& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline const Aws::String& GetEstimatedMonthlySavings() const{ return m_estimatedMonthlySavings; }
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline bool EstimatedMonthlySavingsHasBeenSet() const { return m_estimatedMonthlySavingsHasBeenSet; }
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline void SetEstimatedMonthlySavings(const Aws::String& value) { m_estimatedMonthlySavingsHasBeenSet = true; m_estimatedMonthlySavings = value; }
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline void SetEstimatedMonthlySavings(Aws::String&& value) { m_estimatedMonthlySavingsHasBeenSet = true; m_estimatedMonthlySavings = std::move(value); }
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline void SetEstimatedMonthlySavings(const char* value) { m_estimatedMonthlySavingsHasBeenSet = true; m_estimatedMonthlySavings.assign(value); }
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline TerminateRecommendationDetail& WithEstimatedMonthlySavings(const Aws::String& value) { SetEstimatedMonthlySavings(value); return *this;}
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline TerminateRecommendationDetail& WithEstimatedMonthlySavings(Aws::String&& value) { SetEstimatedMonthlySavings(std::move(value)); return *this;}
/**
* <p>The estimated savings that result from modification, on a monthly basis.</p>
*/
inline TerminateRecommendationDetail& WithEstimatedMonthlySavings(const char* value) { SetEstimatedMonthlySavings(value); return *this;}
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline const Aws::String& GetCurrencyCode() const{ return m_currencyCode; }
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline bool CurrencyCodeHasBeenSet() const { return m_currencyCodeHasBeenSet; }
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline void SetCurrencyCode(const Aws::String& value) { m_currencyCodeHasBeenSet = true; m_currencyCode = value; }
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline void SetCurrencyCode(Aws::String&& value) { m_currencyCodeHasBeenSet = true; m_currencyCode = std::move(value); }
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline void SetCurrencyCode(const char* value) { m_currencyCodeHasBeenSet = true; m_currencyCode.assign(value); }
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline TerminateRecommendationDetail& WithCurrencyCode(const Aws::String& value) { SetCurrencyCode(value); return *this;}
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline TerminateRecommendationDetail& WithCurrencyCode(Aws::String&& value) { SetCurrencyCode(std::move(value)); return *this;}
/**
* <p>The currency code that Amazon Web Services used to calculate the costs for
* this instance.</p>
*/
inline TerminateRecommendationDetail& WithCurrencyCode(const char* value) { SetCurrencyCode(value); return *this;}
private:
Aws::String m_estimatedMonthlySavings;
bool m_estimatedMonthlySavingsHasBeenSet;
Aws::String m_currencyCode;
bool m_currencyCodeHasBeenSet;
};
} // namespace Model
} // namespace CostExplorer
} // namespace Aws
| 35.921986 | 157 | 0.707009 |
12ffd3c50259cd4a16c5731222a41b3912a3ab2c | 2,700 | h | C | go/src/vendor/github.com/caglar10ur/lxc/src/lxc/confile.h | lionheart1022/koding | 9cf542d1ac2736af25f97f717b14236413463d0e | [
"Apache-2.0"
] | null | null | null | go/src/vendor/github.com/caglar10ur/lxc/src/lxc/confile.h | lionheart1022/koding | 9cf542d1ac2736af25f97f717b14236413463d0e | [
"Apache-2.0"
] | 176 | 2019-12-27T09:01:42.000Z | 2021-08-03T06:19:39.000Z | go/src/vendor/github.com/caglar10ur/lxc/src/lxc/confile.h | lionheart1022/koding | 9cf542d1ac2736af25f97f717b14236413463d0e | [
"Apache-2.0"
] | null | null | null | /*
* lxc: linux Container library
*
* (C) Copyright IBM Corp. 2007, 2008
*
* Authors:
* Daniel Lezcano <daniel.lezcano at free.fr>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __LXC_CONFILE_H
#define __LXC_CONFILE_H
#include <stdio.h>
#include <lxc/attach_options.h>
#include <stdbool.h>
struct lxc_conf;
struct lxc_list;
typedef int (*config_cb)(const char *, const char *, struct lxc_conf *);
struct lxc_config_t {
char *name;
config_cb cb;
};
extern struct lxc_config_t *lxc_getconfig(const char *key);
extern int lxc_list_nicconfigs(struct lxc_conf *c, const char *key, char *retv, int inlen);
extern int lxc_listconfigs(char *retv, int inlen);
extern int lxc_config_read(const char *file, struct lxc_conf *conf, bool from_include);
extern int append_unexp_config_line(const char *line, struct lxc_conf *conf);
extern int lxc_config_define_add(struct lxc_list *defines, char* arg);
extern int lxc_config_define_load(struct lxc_list *defines,
struct lxc_conf *conf);
/* needed for lxc-attach */
extern signed long lxc_config_parse_arch(const char *arch);
extern int lxc_fill_elevated_privileges(char *flaglist, int *flags);
extern int lxc_get_config_item(struct lxc_conf *c, const char *key, char *retv, int inlen);
extern int lxc_clear_config_item(struct lxc_conf *c, const char *key);
extern void write_config(FILE *fout, struct lxc_conf *c);
extern bool do_append_unexp_config_line(struct lxc_conf *conf, const char *key, const char *v);
/* These are used when cloning a container */
extern void clear_unexp_config_line(struct lxc_conf *conf, const char *key, bool rm_subkeys);
extern bool clone_update_unexp_hooks(struct lxc_conf *conf, const char *oldpath,
const char *newpath, const char *oldname, const char *newmame);
bool clone_update_unexp_ovl_paths(struct lxc_conf *conf, const char *oldpath,
const char *newpath, const char *oldname,
const char *newname, const char *ovldir);
extern bool network_new_hwaddrs(struct lxc_conf *conf);
#endif
| 39.130435 | 95 | 0.765926 |
6bce0dcb7cc08d96f9ebb53e70af2da2322d0a11 | 52,158 | c | C | testsuite/EXP_2/test1283.c | ishiura-compiler/CF3 | 0718aa176d0303a4ea8a46bd6c794997cbb8fabb | [
"MIT"
] | 34 | 2017-07-04T14:16:12.000Z | 2021-04-22T21:04:43.000Z | testsuite/EXP_2/test1283.c | ishiura-compiler/CF3 | 0718aa176d0303a4ea8a46bd6c794997cbb8fabb | [
"MIT"
] | 1 | 2017-07-06T03:43:44.000Z | 2017-07-06T03:43:44.000Z | testsuite/EXP_2/test1283.c | ishiura-compiler/CF3 | 0718aa176d0303a4ea8a46bd6c794997cbb8fabb | [
"MIT"
] | 6 | 2017-07-04T16:30:42.000Z | 2019-10-16T05:37:29.000Z |
/*
CF3
Copyright (c) 2015 ishiura-lab.
Released under the MIT license.
https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md
*/
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include"test1.h"
int64_t x1 = INT64_MIN;
volatile int8_t x7 = INT8_MIN;
static volatile int32_t t1 = -110376;
static uint64_t x9 = UINT64_MAX;
volatile int32_t t2 = -451886;
int32_t t4 = -1637379;
volatile uint16_t x39 = 0U;
uint16_t x42 = 4858U;
static volatile int32_t x44 = INT32_MIN;
volatile int32_t x45 = -7;
int32_t t12 = 577;
static uint8_t x58 = 14U;
int64_t x60 = INT64_MIN;
volatile int32_t t14 = -599445;
volatile int32_t t16 = -23558132;
static uint8_t x70 = UINT8_MAX;
static int32_t t17 = -336772;
static int16_t x74 = INT16_MIN;
volatile int16_t x77 = 7;
volatile int16_t x78 = 342;
int32_t t19 = -7206352;
int32_t x81 = 63746;
volatile int32_t x91 = INT32_MAX;
int16_t x92 = INT16_MIN;
static volatile int32_t t22 = 1;
int32_t x108 = -95005;
static volatile int32_t t26 = -2734;
int64_t x109 = 190651858318LL;
int32_t x110 = INT32_MIN;
volatile int32_t t27 = -1258;
uint32_t x113 = UINT32_MAX;
volatile int32_t x115 = -1;
volatile int8_t x119 = INT8_MIN;
volatile int32_t t29 = -5;
int8_t x123 = INT8_MAX;
int32_t x129 = -1;
volatile int32_t x139 = 2;
int32_t t34 = -293467714;
uint16_t x144 = UINT16_MAX;
int32_t t35 = -1228756;
int32_t t37 = -10502;
static volatile int8_t x157 = INT8_MIN;
volatile int32_t t41 = 41858;
volatile uint32_t x176 = UINT32_MAX;
int8_t x178 = 29;
uint16_t x179 = UINT16_MAX;
uint16_t x183 = UINT16_MAX;
volatile int64_t x200 = INT64_MIN;
int8_t x205 = INT8_MAX;
int8_t x209 = 1;
static uint8_t x213 = UINT8_MAX;
volatile int32_t t53 = 5;
volatile int64_t x217 = -18817416952LL;
static int8_t x224 = INT8_MIN;
volatile int32_t t55 = -7826308;
int16_t x227 = INT16_MIN;
uint32_t x230 = UINT32_MAX;
uint8_t x238 = 1U;
int32_t x239 = -1;
int64_t x243 = -3370563625661561LL;
int64_t x244 = -1LL;
static volatile int8_t x250 = INT8_MIN;
int16_t x258 = INT16_MAX;
volatile int64_t x259 = -236817016200LL;
int32_t t64 = -218993;
uint16_t x261 = 3U;
int8_t x273 = -1;
uint64_t x275 = 44915741LLU;
volatile int32_t t68 = 1;
volatile uint32_t x279 = 121178064U;
uint16_t x283 = UINT16_MAX;
volatile int8_t x293 = 0;
static volatile int32_t t74 = -1;
volatile uint64_t x302 = 187686204952353LLU;
volatile int8_t x312 = -1;
volatile int32_t t77 = -119042;
int32_t x318 = -1;
uint64_t x319 = 7101077LLU;
int64_t x320 = INT64_MIN;
uint16_t x322 = UINT16_MAX;
volatile int32_t t81 = 2488;
int32_t x332 = INT32_MAX;
int8_t x333 = 0;
int32_t t83 = -3331;
volatile uint16_t x340 = UINT16_MAX;
int64_t x341 = -19280606102459330LL;
volatile int16_t x342 = -4;
volatile uint32_t x345 = UINT32_MAX;
static uint8_t x349 = UINT8_MAX;
static int16_t x350 = INT16_MIN;
int8_t x351 = -11;
static int32_t x352 = INT32_MIN;
static int64_t x357 = INT64_MIN;
uint8_t x359 = 0U;
int16_t x369 = 8421;
volatile int16_t x378 = -1;
int8_t x380 = INT8_MIN;
uint16_t x381 = UINT16_MAX;
static uint8_t x390 = UINT8_MAX;
volatile int32_t x393 = INT32_MIN;
static int16_t x403 = INT16_MAX;
volatile int32_t t101 = -179400;
volatile int8_t x409 = INT8_MAX;
static volatile int64_t x411 = INT64_MIN;
int8_t x412 = INT8_MIN;
int64_t x417 = INT64_MIN;
int64_t x421 = INT64_MIN;
int32_t x424 = -99331625;
static int32_t t105 = -32234;
static uint32_t x426 = 164U;
int8_t x430 = -26;
uint64_t x433 = UINT64_MAX;
volatile uint8_t x438 = UINT8_MAX;
int8_t x440 = INT8_MIN;
static uint16_t x444 = 17U;
int8_t x447 = -1;
int16_t x453 = -2;
volatile uint8_t x457 = 73U;
int32_t x465 = -1;
volatile int32_t t116 = -1;
static int32_t x474 = INT32_MIN;
int32_t t118 = 185;
uint64_t x484 = 344696602LLU;
volatile int64_t x499 = 3LL;
uint16_t x504 = UINT16_MAX;
int64_t x505 = -28423053492199LL;
int8_t x508 = INT8_MIN;
volatile int32_t t126 = -100155485;
int8_t x511 = -1;
int32_t t127 = -23340;
volatile int8_t x514 = INT8_MIN;
int16_t x520 = INT16_MIN;
int32_t t130 = 370344;
volatile uint32_t x527 = 35506396U;
static int8_t x530 = 3;
int64_t x531 = INT64_MIN;
volatile int64_t x537 = 16073552LL;
int64_t x540 = -1LL;
volatile uint8_t x544 = UINT8_MAX;
int64_t x545 = INT64_MIN;
int64_t x547 = -25513013122134986LL;
int8_t x550 = INT8_MIN;
int16_t x552 = -12284;
uint8_t x555 = UINT8_MAX;
volatile int32_t t138 = -108526;
int16_t x558 = -1;
volatile int32_t x575 = -7021613;
int16_t x576 = INT16_MAX;
int64_t x579 = INT64_MAX;
uint8_t x580 = 2U;
volatile uint64_t x583 = UINT64_MAX;
uint64_t x584 = UINT64_MAX;
static uint64_t x592 = 6694373906LLU;
volatile int32_t t147 = 34;
volatile int8_t x600 = INT8_MIN;
volatile int64_t x603 = -1LL;
static uint16_t x605 = 1966U;
uint32_t x617 = UINT32_MAX;
int16_t x627 = INT16_MIN;
int64_t x628 = -6348841558312LL;
volatile int32_t t158 = 198;
static uint32_t x644 = 213U;
int8_t x646 = 0;
static volatile uint8_t x648 = 1U;
static volatile int64_t x653 = 17842865LL;
int32_t x655 = 984218704;
static int32_t t163 = 63385;
uint32_t x659 = UINT32_MAX;
static volatile int32_t x662 = -31551;
int16_t x668 = INT16_MIN;
static int64_t x669 = -1LL;
volatile int8_t x672 = -1;
int64_t x673 = INT64_MAX;
volatile int32_t x674 = INT32_MIN;
int64_t x675 = INT64_MAX;
int32_t x678 = INT32_MIN;
int64_t x690 = INT64_MIN;
int32_t x691 = -137;
int8_t x698 = -1;
static uint8_t x699 = 101U;
int32_t t174 = 145553;
static volatile int32_t t175 = -52;
volatile uint16_t x708 = UINT16_MAX;
volatile int32_t x709 = INT32_MIN;
int64_t x716 = INT64_MIN;
static int32_t x717 = 813;
uint32_t x719 = 26U;
int32_t x722 = INT32_MIN;
int16_t x723 = 219;
volatile int16_t x729 = INT16_MIN;
static int64_t x732 = INT64_MIN;
volatile int32_t t182 = 26;
uint32_t x735 = 362U;
uint64_t x743 = 17549650773337142LLU;
volatile int32_t t188 = 389768659;
int64_t x760 = 7318889688161589LL;
int32_t x761 = INT32_MIN;
uint64_t x766 = 27LLU;
volatile int32_t t191 = 2096333;
uint32_t x772 = UINT32_MAX;
uint64_t x784 = 22LLU;
int32_t t196 = -9;
int32_t x791 = -1;
void f0(void) {
static int32_t x2 = -2;
int8_t x3 = INT8_MAX;
uint32_t x4 = UINT32_MAX;
int32_t t0 = -747;
t0 = ((x1==(x2!=x3))>x4);
if (t0 != 0) { NG(); } else { ; }
}
void f1(void) {
uint16_t x5 = 11748U;
uint32_t x6 = 31U;
int8_t x8 = 1;
t1 = ((x5==(x6!=x7))>x8);
if (t1 != 0) { NG(); } else { ; }
}
void f2(void) {
volatile int16_t x10 = 13288;
volatile int8_t x11 = INT8_MAX;
int16_t x12 = -1;
t2 = ((x9==(x10!=x11))>x12);
if (t2 != 1) { NG(); } else { ; }
}
void f3(void) {
uint16_t x13 = 15511U;
volatile int64_t x14 = INT64_MIN;
int8_t x15 = INT8_MIN;
volatile int64_t x16 = -1LL;
int32_t t3 = -13468888;
t3 = ((x13==(x14!=x15))>x16);
if (t3 != 1) { NG(); } else { ; }
}
void f4(void) {
int8_t x17 = INT8_MIN;
int64_t x18 = -1LL;
static uint32_t x19 = UINT32_MAX;
int32_t x20 = INT32_MIN;
t4 = ((x17==(x18!=x19))>x20);
if (t4 != 1) { NG(); } else { ; }
}
void f5(void) {
static int64_t x21 = -59072381LL;
volatile uint8_t x22 = UINT8_MAX;
static uint32_t x23 = UINT32_MAX;
volatile int32_t x24 = 0;
static volatile int32_t t5 = 729840;
t5 = ((x21==(x22!=x23))>x24);
if (t5 != 0) { NG(); } else { ; }
}
void f6(void) {
int8_t x25 = -1;
uint32_t x26 = UINT32_MAX;
static int16_t x27 = INT16_MIN;
volatile uint16_t x28 = 0U;
static int32_t t6 = -7112;
t6 = ((x25==(x26!=x27))>x28);
if (t6 != 0) { NG(); } else { ; }
}
void f7(void) {
static uint32_t x29 = 4758555U;
volatile int64_t x30 = -8LL;
uint32_t x31 = UINT32_MAX;
int8_t x32 = INT8_MIN;
static volatile int32_t t7 = 486;
t7 = ((x29==(x30!=x31))>x32);
if (t7 != 1) { NG(); } else { ; }
}
void f8(void) {
volatile uint8_t x33 = 2U;
static int8_t x34 = INT8_MAX;
volatile uint64_t x35 = 38684094931420674LLU;
uint32_t x36 = 2972944U;
int32_t t8 = -115432207;
t8 = ((x33==(x34!=x35))>x36);
if (t8 != 0) { NG(); } else { ; }
}
void f9(void) {
int64_t x37 = -1LL;
volatile int8_t x38 = -1;
int32_t x40 = -1;
static volatile int32_t t9 = 14609;
t9 = ((x37==(x38!=x39))>x40);
if (t9 != 1) { NG(); } else { ; }
}
void f10(void) {
volatile int32_t x41 = -1;
static int32_t x43 = -1;
static volatile int32_t t10 = -200854022;
t10 = ((x41==(x42!=x43))>x44);
if (t10 != 1) { NG(); } else { ; }
}
void f11(void) {
uint8_t x46 = UINT8_MAX;
int64_t x47 = 2989590190935426LL;
int64_t x48 = -1LL;
volatile int32_t t11 = -6992;
t11 = ((x45==(x46!=x47))>x48);
if (t11 != 1) { NG(); } else { ; }
}
void f12(void) {
int8_t x49 = INT8_MAX;
int16_t x50 = INT16_MIN;
int64_t x51 = 1478861934LL;
uint8_t x52 = 0U;
t12 = ((x49==(x50!=x51))>x52);
if (t12 != 0) { NG(); } else { ; }
}
void f13(void) {
int64_t x53 = 1LL;
int16_t x54 = 1;
volatile uint16_t x55 = 23U;
volatile uint16_t x56 = 3U;
int32_t t13 = -11977;
t13 = ((x53==(x54!=x55))>x56);
if (t13 != 0) { NG(); } else { ; }
}
void f14(void) {
uint16_t x57 = 8U;
int8_t x59 = INT8_MAX;
t14 = ((x57==(x58!=x59))>x60);
if (t14 != 1) { NG(); } else { ; }
}
void f15(void) {
int32_t x61 = INT32_MAX;
int64_t x62 = -3025080LL;
uint32_t x63 = UINT32_MAX;
int16_t x64 = INT16_MAX;
static int32_t t15 = 697104;
t15 = ((x61==(x62!=x63))>x64);
if (t15 != 0) { NG(); } else { ; }
}
void f16(void) {
int64_t x65 = -1LL;
int64_t x66 = -1LL;
int32_t x67 = INT32_MIN;
int16_t x68 = 15961;
t16 = ((x65==(x66!=x67))>x68);
if (t16 != 0) { NG(); } else { ; }
}
void f17(void) {
int64_t x69 = INT64_MAX;
int32_t x71 = -1;
int16_t x72 = INT16_MAX;
t17 = ((x69==(x70!=x71))>x72);
if (t17 != 0) { NG(); } else { ; }
}
void f18(void) {
volatile uint16_t x73 = 429U;
int8_t x75 = -51;
int16_t x76 = -1;
volatile int32_t t18 = 6530072;
t18 = ((x73==(x74!=x75))>x76);
if (t18 != 1) { NG(); } else { ; }
}
void f19(void) {
volatile int32_t x79 = INT32_MIN;
int8_t x80 = -2;
t19 = ((x77==(x78!=x79))>x80);
if (t19 != 1) { NG(); } else { ; }
}
void f20(void) {
volatile int64_t x82 = 2770235LL;
volatile int16_t x83 = INT16_MAX;
volatile uint16_t x84 = 233U;
volatile int32_t t20 = -7210;
t20 = ((x81==(x82!=x83))>x84);
if (t20 != 0) { NG(); } else { ; }
}
void f21(void) {
int8_t x85 = -1;
int16_t x86 = 3654;
static int32_t x87 = INT32_MIN;
int64_t x88 = INT64_MIN;
volatile int32_t t21 = 380;
t21 = ((x85==(x86!=x87))>x88);
if (t21 != 1) { NG(); } else { ; }
}
void f22(void) {
volatile int64_t x89 = -19LL;
volatile uint32_t x90 = 26U;
t22 = ((x89==(x90!=x91))>x92);
if (t22 != 1) { NG(); } else { ; }
}
void f23(void) {
static volatile uint16_t x93 = UINT16_MAX;
int8_t x94 = INT8_MIN;
int32_t x95 = -1;
int64_t x96 = -2735519878912620LL;
int32_t t23 = -6000;
t23 = ((x93==(x94!=x95))>x96);
if (t23 != 1) { NG(); } else { ; }
}
void f24(void) {
static volatile int64_t x97 = -28LL;
volatile uint32_t x98 = 409U;
uint64_t x99 = UINT64_MAX;
volatile int32_t x100 = 24;
int32_t t24 = -1527;
t24 = ((x97==(x98!=x99))>x100);
if (t24 != 0) { NG(); } else { ; }
}
void f25(void) {
int8_t x101 = -1;
int8_t x102 = INT8_MAX;
volatile uint64_t x103 = 13696848255388LLU;
int8_t x104 = INT8_MIN;
volatile int32_t t25 = 9951;
t25 = ((x101==(x102!=x103))>x104);
if (t25 != 1) { NG(); } else { ; }
}
void f26(void) {
uint32_t x105 = UINT32_MAX;
int64_t x106 = -1LL;
int16_t x107 = INT16_MIN;
t26 = ((x105==(x106!=x107))>x108);
if (t26 != 1) { NG(); } else { ; }
}
void f27(void) {
int32_t x111 = INT32_MIN;
static int64_t x112 = INT64_MAX;
t27 = ((x109==(x110!=x111))>x112);
if (t27 != 0) { NG(); } else { ; }
}
void f28(void) {
int8_t x114 = -1;
int64_t x116 = INT64_MIN;
volatile int32_t t28 = -37719;
t28 = ((x113==(x114!=x115))>x116);
if (t28 != 1) { NG(); } else { ; }
}
void f29(void) {
int16_t x117 = 0;
int16_t x118 = INT16_MIN;
int64_t x120 = -212779985793974LL;
t29 = ((x117==(x118!=x119))>x120);
if (t29 != 1) { NG(); } else { ; }
}
void f30(void) {
int8_t x121 = -1;
int16_t x122 = INT16_MIN;
volatile int32_t x124 = INT32_MIN;
volatile int32_t t30 = -176663;
t30 = ((x121==(x122!=x123))>x124);
if (t30 != 1) { NG(); } else { ; }
}
void f31(void) {
uint64_t x125 = 45743481LLU;
int64_t x126 = -1LL;
volatile int64_t x127 = INT64_MIN;
volatile uint8_t x128 = 12U;
int32_t t31 = -497;
t31 = ((x125==(x126!=x127))>x128);
if (t31 != 0) { NG(); } else { ; }
}
void f32(void) {
uint32_t x130 = 114364U;
static uint8_t x131 = 4U;
static volatile uint8_t x132 = 0U;
int32_t t32 = 137292;
t32 = ((x129==(x130!=x131))>x132);
if (t32 != 0) { NG(); } else { ; }
}
void f33(void) {
uint64_t x133 = 114859037432LLU;
static volatile uint64_t x134 = UINT64_MAX;
uint8_t x135 = UINT8_MAX;
int64_t x136 = -1LL;
int32_t t33 = 648893579;
t33 = ((x133==(x134!=x135))>x136);
if (t33 != 1) { NG(); } else { ; }
}
void f34(void) {
uint16_t x137 = 47U;
static uint8_t x138 = 86U;
int8_t x140 = 0;
t34 = ((x137==(x138!=x139))>x140);
if (t34 != 0) { NG(); } else { ; }
}
void f35(void) {
int8_t x141 = INT8_MIN;
static int16_t x142 = 1;
volatile int64_t x143 = INT64_MIN;
t35 = ((x141==(x142!=x143))>x144);
if (t35 != 0) { NG(); } else { ; }
}
void f36(void) {
int32_t x145 = INT32_MAX;
int64_t x146 = -1LL;
uint64_t x147 = UINT64_MAX;
uint8_t x148 = 66U;
int32_t t36 = 421;
t36 = ((x145==(x146!=x147))>x148);
if (t36 != 0) { NG(); } else { ; }
}
void f37(void) {
static volatile uint16_t x149 = UINT16_MAX;
uint16_t x150 = 1084U;
int8_t x151 = 2;
static volatile uint16_t x152 = UINT16_MAX;
t37 = ((x149==(x150!=x151))>x152);
if (t37 != 0) { NG(); } else { ; }
}
void f38(void) {
uint64_t x153 = 18LLU;
static uint32_t x154 = 724898672U;
static uint32_t x155 = 453285U;
int64_t x156 = -39LL;
int32_t t38 = 54;
t38 = ((x153==(x154!=x155))>x156);
if (t38 != 1) { NG(); } else { ; }
}
void f39(void) {
volatile uint8_t x158 = 93U;
uint8_t x159 = UINT8_MAX;
volatile int32_t x160 = -344;
volatile int32_t t39 = 16014168;
t39 = ((x157==(x158!=x159))>x160);
if (t39 != 1) { NG(); } else { ; }
}
void f40(void) {
uint64_t x161 = 103010LLU;
uint16_t x162 = 631U;
int16_t x163 = INT16_MAX;
volatile uint32_t x164 = 77118U;
static volatile int32_t t40 = -300356500;
t40 = ((x161==(x162!=x163))>x164);
if (t40 != 0) { NG(); } else { ; }
}
void f41(void) {
int16_t x165 = -1;
volatile int32_t x166 = INT32_MIN;
uint8_t x167 = 5U;
int64_t x168 = -727746609131LL;
t41 = ((x165==(x166!=x167))>x168);
if (t41 != 1) { NG(); } else { ; }
}
void f42(void) {
static int64_t x169 = INT64_MAX;
uint64_t x170 = 6LLU;
volatile int64_t x171 = 734446LL;
uint16_t x172 = 14U;
volatile int32_t t42 = -5355391;
t42 = ((x169==(x170!=x171))>x172);
if (t42 != 0) { NG(); } else { ; }
}
void f43(void) {
volatile int8_t x173 = INT8_MIN;
static int32_t x174 = INT32_MAX;
int64_t x175 = INT64_MIN;
volatile int32_t t43 = 540;
t43 = ((x173==(x174!=x175))>x176);
if (t43 != 0) { NG(); } else { ; }
}
void f44(void) {
int16_t x177 = -7670;
uint32_t x180 = UINT32_MAX;
volatile int32_t t44 = -2;
t44 = ((x177==(x178!=x179))>x180);
if (t44 != 0) { NG(); } else { ; }
}
void f45(void) {
uint64_t x181 = 46965LLU;
int16_t x182 = -1;
int8_t x184 = -28;
volatile int32_t t45 = 387;
t45 = ((x181==(x182!=x183))>x184);
if (t45 != 1) { NG(); } else { ; }
}
void f46(void) {
volatile int16_t x185 = INT16_MIN;
uint32_t x186 = 4739786U;
uint64_t x187 = UINT64_MAX;
int16_t x188 = INT16_MIN;
static int32_t t46 = 154920474;
t46 = ((x185==(x186!=x187))>x188);
if (t46 != 1) { NG(); } else { ; }
}
void f47(void) {
static volatile int8_t x189 = -1;
volatile uint8_t x190 = UINT8_MAX;
int32_t x191 = INT32_MIN;
int32_t x192 = INT32_MIN;
volatile int32_t t47 = -2613233;
t47 = ((x189==(x190!=x191))>x192);
if (t47 != 1) { NG(); } else { ; }
}
void f48(void) {
int64_t x193 = INT64_MIN;
int64_t x194 = INT64_MIN;
int8_t x195 = INT8_MIN;
int32_t x196 = INT32_MAX;
int32_t t48 = 0;
t48 = ((x193==(x194!=x195))>x196);
if (t48 != 0) { NG(); } else { ; }
}
void f49(void) {
static int16_t x197 = INT16_MIN;
static int8_t x198 = INT8_MIN;
volatile int8_t x199 = -1;
int32_t t49 = 13726791;
t49 = ((x197==(x198!=x199))>x200);
if (t49 != 1) { NG(); } else { ; }
}
void f50(void) {
volatile int32_t x201 = INT32_MAX;
uint32_t x202 = UINT32_MAX;
static int8_t x203 = 11;
static volatile int32_t x204 = -1;
volatile int32_t t50 = -807172350;
t50 = ((x201==(x202!=x203))>x204);
if (t50 != 1) { NG(); } else { ; }
}
void f51(void) {
volatile int32_t x206 = -346844;
int64_t x207 = INT64_MIN;
int32_t x208 = INT32_MIN;
volatile int32_t t51 = -25;
t51 = ((x205==(x206!=x207))>x208);
if (t51 != 1) { NG(); } else { ; }
}
void f52(void) {
uint64_t x210 = UINT64_MAX;
static int64_t x211 = INT64_MIN;
volatile int8_t x212 = -1;
int32_t t52 = -2;
t52 = ((x209==(x210!=x211))>x212);
if (t52 != 1) { NG(); } else { ; }
}
void f53(void) {
static uint16_t x214 = 1491U;
static int8_t x215 = INT8_MIN;
int32_t x216 = 2327382;
t53 = ((x213==(x214!=x215))>x216);
if (t53 != 0) { NG(); } else { ; }
}
void f54(void) {
static volatile int16_t x218 = -1739;
int64_t x219 = INT64_MIN;
int16_t x220 = 3291;
volatile int32_t t54 = 458;
t54 = ((x217==(x218!=x219))>x220);
if (t54 != 0) { NG(); } else { ; }
}
void f55(void) {
static int16_t x221 = INT16_MIN;
static int64_t x222 = -899710999453292LL;
volatile uint16_t x223 = 22515U;
t55 = ((x221==(x222!=x223))>x224);
if (t55 != 1) { NG(); } else { ; }
}
void f56(void) {
static int32_t x225 = -269984;
volatile int16_t x226 = -1;
int16_t x228 = INT16_MIN;
int32_t t56 = 716579595;
t56 = ((x225==(x226!=x227))>x228);
if (t56 != 1) { NG(); } else { ; }
}
void f57(void) {
uint16_t x229 = 25U;
int8_t x231 = 0;
int8_t x232 = INT8_MIN;
volatile int32_t t57 = -5322536;
t57 = ((x229==(x230!=x231))>x232);
if (t57 != 1) { NG(); } else { ; }
}
void f58(void) {
volatile int32_t x233 = -1;
static uint8_t x234 = 1U;
int16_t x235 = 3;
static volatile int16_t x236 = 0;
int32_t t58 = 981299219;
t58 = ((x233==(x234!=x235))>x236);
if (t58 != 0) { NG(); } else { ; }
}
void f59(void) {
int16_t x237 = -1661;
uint8_t x240 = UINT8_MAX;
int32_t t59 = -2;
t59 = ((x237==(x238!=x239))>x240);
if (t59 != 0) { NG(); } else { ; }
}
void f60(void) {
int16_t x241 = -1;
int64_t x242 = INT64_MIN;
static volatile int32_t t60 = 44663127;
t60 = ((x241==(x242!=x243))>x244);
if (t60 != 1) { NG(); } else { ; }
}
void f61(void) {
static uint64_t x245 = 0LLU;
int32_t x246 = INT32_MIN;
volatile uint8_t x247 = 3U;
int16_t x248 = INT16_MAX;
volatile int32_t t61 = -325352729;
t61 = ((x245==(x246!=x247))>x248);
if (t61 != 0) { NG(); } else { ; }
}
void f62(void) {
int8_t x249 = INT8_MIN;
static int16_t x251 = -23;
int8_t x252 = -6;
volatile int32_t t62 = 449;
t62 = ((x249==(x250!=x251))>x252);
if (t62 != 1) { NG(); } else { ; }
}
void f63(void) {
uint16_t x253 = 3U;
int64_t x254 = INT64_MIN;
uint32_t x255 = UINT32_MAX;
uint8_t x256 = UINT8_MAX;
static int32_t t63 = -11;
t63 = ((x253==(x254!=x255))>x256);
if (t63 != 0) { NG(); } else { ; }
}
void f64(void) {
uint8_t x257 = UINT8_MAX;
static uint32_t x260 = 2926322U;
t64 = ((x257==(x258!=x259))>x260);
if (t64 != 0) { NG(); } else { ; }
}
void f65(void) {
uint16_t x262 = 23407U;
int8_t x263 = INT8_MAX;
int16_t x264 = 100;
static volatile int32_t t65 = 527185;
t65 = ((x261==(x262!=x263))>x264);
if (t65 != 0) { NG(); } else { ; }
}
void f66(void) {
uint64_t x265 = UINT64_MAX;
volatile int16_t x266 = -533;
uint64_t x267 = 2148LLU;
int16_t x268 = -1;
volatile int32_t t66 = 565574;
t66 = ((x265==(x266!=x267))>x268);
if (t66 != 1) { NG(); } else { ; }
}
void f67(void) {
int8_t x269 = -1;
uint16_t x270 = 1207U;
int64_t x271 = 7166LL;
int16_t x272 = -337;
volatile int32_t t67 = -2;
t67 = ((x269==(x270!=x271))>x272);
if (t67 != 1) { NG(); } else { ; }
}
void f68(void) {
uint32_t x274 = 774190022U;
static volatile uint8_t x276 = 0U;
t68 = ((x273==(x274!=x275))>x276);
if (t68 != 0) { NG(); } else { ; }
}
void f69(void) {
int16_t x277 = -1;
static int64_t x278 = 86512611077LL;
uint16_t x280 = 143U;
static volatile int32_t t69 = -32;
t69 = ((x277==(x278!=x279))>x280);
if (t69 != 0) { NG(); } else { ; }
}
void f70(void) {
volatile int16_t x281 = 236;
int64_t x282 = -725420LL;
int16_t x284 = -165;
int32_t t70 = 79396;
t70 = ((x281==(x282!=x283))>x284);
if (t70 != 1) { NG(); } else { ; }
}
void f71(void) {
volatile uint64_t x285 = 24327627854104776LLU;
int32_t x286 = -68154;
uint32_t x287 = UINT32_MAX;
volatile int64_t x288 = INT64_MIN;
static volatile int32_t t71 = 240;
t71 = ((x285==(x286!=x287))>x288);
if (t71 != 1) { NG(); } else { ; }
}
void f72(void) {
int16_t x289 = -1;
int16_t x290 = -1;
int16_t x291 = -1;
int16_t x292 = -1;
int32_t t72 = -865;
t72 = ((x289==(x290!=x291))>x292);
if (t72 != 1) { NG(); } else { ; }
}
void f73(void) {
int32_t x294 = -1;
volatile uint16_t x295 = 850U;
static int64_t x296 = INT64_MIN;
int32_t t73 = -38;
t73 = ((x293==(x294!=x295))>x296);
if (t73 != 1) { NG(); } else { ; }
}
void f74(void) {
volatile int16_t x297 = -1;
int16_t x298 = INT16_MIN;
int16_t x299 = -1131;
static int8_t x300 = 3;
t74 = ((x297==(x298!=x299))>x300);
if (t74 != 0) { NG(); } else { ; }
}
void f75(void) {
volatile uint16_t x301 = UINT16_MAX;
volatile int8_t x303 = -8;
int64_t x304 = -1093492449621LL;
volatile int32_t t75 = -36956319;
t75 = ((x301==(x302!=x303))>x304);
if (t75 != 1) { NG(); } else { ; }
}
void f76(void) {
int32_t x305 = 1;
static uint32_t x306 = 2650U;
volatile int16_t x307 = -2035;
int64_t x308 = INT64_MAX;
int32_t t76 = 1021;
t76 = ((x305==(x306!=x307))>x308);
if (t76 != 0) { NG(); } else { ; }
}
void f77(void) {
uint8_t x309 = UINT8_MAX;
uint8_t x310 = UINT8_MAX;
uint32_t x311 = 6U;
t77 = ((x309==(x310!=x311))>x312);
if (t77 != 1) { NG(); } else { ; }
}
void f78(void) {
int32_t x313 = -1;
volatile int32_t x314 = -1;
int8_t x315 = 1;
uint32_t x316 = 50881U;
int32_t t78 = -7;
t78 = ((x313==(x314!=x315))>x316);
if (t78 != 0) { NG(); } else { ; }
}
void f79(void) {
int8_t x317 = INT8_MIN;
int32_t t79 = 9;
t79 = ((x317==(x318!=x319))>x320);
if (t79 != 1) { NG(); } else { ; }
}
void f80(void) {
uint16_t x321 = UINT16_MAX;
volatile int64_t x323 = -540651667089345377LL;
int16_t x324 = 377;
volatile int32_t t80 = 11853425;
t80 = ((x321==(x322!=x323))>x324);
if (t80 != 0) { NG(); } else { ; }
}
void f81(void) {
int32_t x325 = 913885;
int32_t x326 = INT32_MAX;
static int8_t x327 = INT8_MIN;
uint8_t x328 = 1U;
t81 = ((x325==(x326!=x327))>x328);
if (t81 != 0) { NG(); } else { ; }
}
void f82(void) {
int32_t x329 = 0;
static int32_t x330 = 158;
volatile uint32_t x331 = 2U;
volatile int32_t t82 = 11142022;
t82 = ((x329==(x330!=x331))>x332);
if (t82 != 0) { NG(); } else { ; }
}
void f83(void) {
int64_t x334 = INT64_MIN;
int64_t x335 = INT64_MAX;
static int32_t x336 = 1915;
t83 = ((x333==(x334!=x335))>x336);
if (t83 != 0) { NG(); } else { ; }
}
void f84(void) {
static uint8_t x337 = 6U;
uint16_t x338 = 121U;
int64_t x339 = INT64_MIN;
static int32_t t84 = -25;
t84 = ((x337==(x338!=x339))>x340);
if (t84 != 0) { NG(); } else { ; }
}
void f85(void) {
volatile int16_t x343 = INT16_MIN;
static int64_t x344 = 6450831LL;
volatile int32_t t85 = -11686;
t85 = ((x341==(x342!=x343))>x344);
if (t85 != 0) { NG(); } else { ; }
}
void f86(void) {
volatile uint16_t x346 = 233U;
int32_t x347 = INT32_MIN;
int32_t x348 = -35;
int32_t t86 = 19;
t86 = ((x345==(x346!=x347))>x348);
if (t86 != 1) { NG(); } else { ; }
}
void f87(void) {
int32_t t87 = 124159824;
t87 = ((x349==(x350!=x351))>x352);
if (t87 != 1) { NG(); } else { ; }
}
void f88(void) {
static int32_t x353 = INT32_MIN;
volatile int16_t x354 = INT16_MIN;
uint32_t x355 = 60405U;
volatile uint64_t x356 = UINT64_MAX;
volatile int32_t t88 = 1467;
t88 = ((x353==(x354!=x355))>x356);
if (t88 != 0) { NG(); } else { ; }
}
void f89(void) {
static volatile int16_t x358 = -1;
int8_t x360 = INT8_MAX;
volatile int32_t t89 = -6403008;
t89 = ((x357==(x358!=x359))>x360);
if (t89 != 0) { NG(); } else { ; }
}
void f90(void) {
uint16_t x361 = 6U;
int64_t x362 = INT64_MAX;
int32_t x363 = INT32_MAX;
int16_t x364 = 1;
volatile int32_t t90 = 3944;
t90 = ((x361==(x362!=x363))>x364);
if (t90 != 0) { NG(); } else { ; }
}
void f91(void) {
int8_t x365 = -3;
uint32_t x366 = 2209U;
uint8_t x367 = UINT8_MAX;
volatile uint16_t x368 = 2881U;
volatile int32_t t91 = -218482481;
t91 = ((x365==(x366!=x367))>x368);
if (t91 != 0) { NG(); } else { ; }
}
void f92(void) {
int64_t x370 = INT64_MIN;
uint16_t x371 = 14U;
int16_t x372 = INT16_MIN;
int32_t t92 = 4309;
t92 = ((x369==(x370!=x371))>x372);
if (t92 != 1) { NG(); } else { ; }
}
void f93(void) {
uint32_t x373 = 77617930U;
volatile int16_t x374 = -1;
int32_t x375 = INT32_MAX;
int64_t x376 = -393572188592LL;
static int32_t t93 = -38805965;
t93 = ((x373==(x374!=x375))>x376);
if (t93 != 1) { NG(); } else { ; }
}
void f94(void) {
volatile uint8_t x377 = UINT8_MAX;
volatile uint16_t x379 = 418U;
static volatile int32_t t94 = 59506;
t94 = ((x377==(x378!=x379))>x380);
if (t94 != 1) { NG(); } else { ; }
}
void f95(void) {
static int8_t x382 = INT8_MAX;
uint8_t x383 = 54U;
uint32_t x384 = 2403U;
int32_t t95 = -45951369;
t95 = ((x381==(x382!=x383))>x384);
if (t95 != 0) { NG(); } else { ; }
}
void f96(void) {
uint8_t x385 = 6U;
static uint16_t x386 = 277U;
static int8_t x387 = -1;
static int64_t x388 = INT64_MIN;
int32_t t96 = -13570969;
t96 = ((x385==(x386!=x387))>x388);
if (t96 != 1) { NG(); } else { ; }
}
void f97(void) {
int8_t x389 = -1;
int16_t x391 = INT16_MAX;
uint64_t x392 = 251LLU;
static volatile int32_t t97 = -883973502;
t97 = ((x389==(x390!=x391))>x392);
if (t97 != 0) { NG(); } else { ; }
}
void f98(void) {
int16_t x394 = -1;
int16_t x395 = -1;
uint8_t x396 = 124U;
volatile int32_t t98 = 0;
t98 = ((x393==(x394!=x395))>x396);
if (t98 != 0) { NG(); } else { ; }
}
void f99(void) {
uint16_t x397 = UINT16_MAX;
int8_t x398 = 0;
int64_t x399 = INT64_MIN;
uint8_t x400 = UINT8_MAX;
volatile int32_t t99 = -194684973;
t99 = ((x397==(x398!=x399))>x400);
if (t99 != 0) { NG(); } else { ; }
}
void f100(void) {
int64_t x401 = -1LL;
int8_t x402 = INT8_MIN;
int16_t x404 = -1;
int32_t t100 = -159743525;
t100 = ((x401==(x402!=x403))>x404);
if (t100 != 1) { NG(); } else { ; }
}
void f101(void) {
uint64_t x405 = 613083LLU;
static int32_t x406 = 6;
int32_t x407 = INT32_MIN;
static uint32_t x408 = 1U;
t101 = ((x405==(x406!=x407))>x408);
if (t101 != 0) { NG(); } else { ; }
}
void f102(void) {
int8_t x410 = INT8_MIN;
volatile int32_t t102 = 4162027;
t102 = ((x409==(x410!=x411))>x412);
if (t102 != 1) { NG(); } else { ; }
}
void f103(void) {
volatile int64_t x413 = INT64_MIN;
int8_t x414 = -1;
static int8_t x415 = INT8_MIN;
int16_t x416 = INT16_MIN;
int32_t t103 = 14955;
t103 = ((x413==(x414!=x415))>x416);
if (t103 != 1) { NG(); } else { ; }
}
void f104(void) {
volatile int16_t x418 = -144;
static int16_t x419 = INT16_MAX;
uint64_t x420 = 873LLU;
volatile int32_t t104 = 15;
t104 = ((x417==(x418!=x419))>x420);
if (t104 != 0) { NG(); } else { ; }
}
void f105(void) {
static uint64_t x422 = UINT64_MAX;
int32_t x423 = -809153;
t105 = ((x421==(x422!=x423))>x424);
if (t105 != 1) { NG(); } else { ; }
}
void f106(void) {
int16_t x425 = -1;
static int8_t x427 = -48;
uint64_t x428 = 16213802644274LLU;
static int32_t t106 = 475794959;
t106 = ((x425==(x426!=x427))>x428);
if (t106 != 0) { NG(); } else { ; }
}
void f107(void) {
int16_t x429 = INT16_MAX;
uint16_t x431 = 582U;
volatile uint16_t x432 = UINT16_MAX;
static int32_t t107 = 619891;
t107 = ((x429==(x430!=x431))>x432);
if (t107 != 0) { NG(); } else { ; }
}
void f108(void) {
volatile int64_t x434 = -98LL;
volatile int32_t x435 = INT32_MIN;
int16_t x436 = -1;
int32_t t108 = -394;
t108 = ((x433==(x434!=x435))>x436);
if (t108 != 1) { NG(); } else { ; }
}
void f109(void) {
uint16_t x437 = 1121U;
volatile uint8_t x439 = UINT8_MAX;
int32_t t109 = -125;
t109 = ((x437==(x438!=x439))>x440);
if (t109 != 1) { NG(); } else { ; }
}
void f110(void) {
static int64_t x441 = INT64_MIN;
int8_t x442 = 5;
volatile int16_t x443 = -1;
int32_t t110 = -990;
t110 = ((x441==(x442!=x443))>x444);
if (t110 != 0) { NG(); } else { ; }
}
void f111(void) {
static volatile int32_t x445 = INT32_MIN;
int64_t x446 = INT64_MAX;
static int8_t x448 = -1;
int32_t t111 = -539128;
t111 = ((x445==(x446!=x447))>x448);
if (t111 != 1) { NG(); } else { ; }
}
void f112(void) {
uint64_t x449 = 4701LLU;
int8_t x450 = INT8_MAX;
int8_t x451 = -1;
volatile uint8_t x452 = UINT8_MAX;
volatile int32_t t112 = 113;
t112 = ((x449==(x450!=x451))>x452);
if (t112 != 0) { NG(); } else { ; }
}
void f113(void) {
uint32_t x454 = 1874686542U;
int8_t x455 = -1;
uint32_t x456 = 32153990U;
volatile int32_t t113 = 19;
t113 = ((x453==(x454!=x455))>x456);
if (t113 != 0) { NG(); } else { ; }
}
void f114(void) {
volatile uint16_t x458 = UINT16_MAX;
static int64_t x459 = INT64_MIN;
int16_t x460 = INT16_MAX;
int32_t t114 = 5;
t114 = ((x457==(x458!=x459))>x460);
if (t114 != 0) { NG(); } else { ; }
}
void f115(void) {
int16_t x461 = INT16_MIN;
int32_t x462 = 23946690;
static int64_t x463 = INT64_MAX;
int32_t x464 = -1;
int32_t t115 = 131479732;
t115 = ((x461==(x462!=x463))>x464);
if (t115 != 1) { NG(); } else { ; }
}
void f116(void) {
uint32_t x466 = UINT32_MAX;
volatile uint16_t x467 = 393U;
int16_t x468 = INT16_MAX;
t116 = ((x465==(x466!=x467))>x468);
if (t116 != 0) { NG(); } else { ; }
}
void f117(void) {
int64_t x469 = INT64_MAX;
int32_t x470 = INT32_MIN;
static int32_t x471 = INT32_MAX;
static int8_t x472 = INT8_MIN;
volatile int32_t t117 = 71;
t117 = ((x469==(x470!=x471))>x472);
if (t117 != 1) { NG(); } else { ; }
}
void f118(void) {
uint32_t x473 = 35944796U;
static volatile int64_t x475 = INT64_MIN;
volatile uint16_t x476 = 1U;
t118 = ((x473==(x474!=x475))>x476);
if (t118 != 0) { NG(); } else { ; }
}
void f119(void) {
static volatile int16_t x477 = 1;
static int16_t x478 = INT16_MAX;
int64_t x479 = INT64_MIN;
int8_t x480 = INT8_MIN;
volatile int32_t t119 = 53841;
t119 = ((x477==(x478!=x479))>x480);
if (t119 != 1) { NG(); } else { ; }
}
void f120(void) {
volatile int8_t x481 = INT8_MIN;
int16_t x482 = 3968;
uint64_t x483 = 1147206649711978724LLU;
volatile int32_t t120 = 935009;
t120 = ((x481==(x482!=x483))>x484);
if (t120 != 0) { NG(); } else { ; }
}
void f121(void) {
static volatile uint32_t x485 = UINT32_MAX;
volatile uint32_t x486 = UINT32_MAX;
int8_t x487 = -1;
int16_t x488 = INT16_MIN;
volatile int32_t t121 = -24;
t121 = ((x485==(x486!=x487))>x488);
if (t121 != 1) { NG(); } else { ; }
}
void f122(void) {
uint16_t x489 = 322U;
static volatile int32_t x490 = -15;
int16_t x491 = INT16_MAX;
int64_t x492 = 3322658213650438916LL;
int32_t t122 = 6214;
t122 = ((x489==(x490!=x491))>x492);
if (t122 != 0) { NG(); } else { ; }
}
void f123(void) {
int8_t x493 = -1;
int64_t x494 = INT64_MIN;
volatile int32_t x495 = INT32_MIN;
static uint32_t x496 = 4U;
volatile int32_t t123 = 870041085;
t123 = ((x493==(x494!=x495))>x496);
if (t123 != 0) { NG(); } else { ; }
}
void f124(void) {
int16_t x497 = -1;
int8_t x498 = -1;
int32_t x500 = INT32_MIN;
volatile int32_t t124 = 1892;
t124 = ((x497==(x498!=x499))>x500);
if (t124 != 1) { NG(); } else { ; }
}
void f125(void) {
uint64_t x501 = 10527158366978924LLU;
int64_t x502 = 2330LL;
int16_t x503 = INT16_MIN;
int32_t t125 = 27;
t125 = ((x501==(x502!=x503))>x504);
if (t125 != 0) { NG(); } else { ; }
}
void f126(void) {
int32_t x506 = 30065;
uint16_t x507 = 1U;
t126 = ((x505==(x506!=x507))>x508);
if (t126 != 1) { NG(); } else { ; }
}
void f127(void) {
int64_t x509 = -1LL;
int16_t x510 = INT16_MAX;
int32_t x512 = -6166;
t127 = ((x509==(x510!=x511))>x512);
if (t127 != 1) { NG(); } else { ; }
}
void f128(void) {
int64_t x513 = INT64_MIN;
static volatile int16_t x515 = INT16_MIN;
int16_t x516 = INT16_MIN;
volatile int32_t t128 = -2327;
t128 = ((x513==(x514!=x515))>x516);
if (t128 != 1) { NG(); } else { ; }
}
void f129(void) {
int64_t x517 = -1LL;
volatile int16_t x518 = INT16_MIN;
static int32_t x519 = -1;
static int32_t t129 = -12;
t129 = ((x517==(x518!=x519))>x520);
if (t129 != 1) { NG(); } else { ; }
}
void f130(void) {
uint16_t x521 = UINT16_MAX;
int16_t x522 = -2327;
uint64_t x523 = UINT64_MAX;
int64_t x524 = INT64_MIN;
t130 = ((x521==(x522!=x523))>x524);
if (t130 != 1) { NG(); } else { ; }
}
void f131(void) {
static int32_t x525 = -1;
int8_t x526 = INT8_MIN;
uint32_t x528 = 942930U;
volatile int32_t t131 = -3189;
t131 = ((x525==(x526!=x527))>x528);
if (t131 != 0) { NG(); } else { ; }
}
void f132(void) {
static int16_t x529 = INT16_MIN;
static uint32_t x532 = 186954910U;
volatile int32_t t132 = 63914758;
t132 = ((x529==(x530!=x531))>x532);
if (t132 != 0) { NG(); } else { ; }
}
void f133(void) {
uint32_t x533 = UINT32_MAX;
uint64_t x534 = UINT64_MAX;
int16_t x535 = INT16_MIN;
static uint16_t x536 = 4U;
static volatile int32_t t133 = 0;
t133 = ((x533==(x534!=x535))>x536);
if (t133 != 0) { NG(); } else { ; }
}
void f134(void) {
volatile int32_t x538 = -1;
int8_t x539 = -9;
volatile int32_t t134 = 43915763;
t134 = ((x537==(x538!=x539))>x540);
if (t134 != 1) { NG(); } else { ; }
}
void f135(void) {
static int16_t x541 = INT16_MIN;
static volatile int32_t x542 = 0;
uint8_t x543 = 62U;
int32_t t135 = 2086758;
t135 = ((x541==(x542!=x543))>x544);
if (t135 != 0) { NG(); } else { ; }
}
void f136(void) {
uint64_t x546 = 663816248LLU;
uint32_t x548 = UINT32_MAX;
volatile int32_t t136 = -124;
t136 = ((x545==(x546!=x547))>x548);
if (t136 != 0) { NG(); } else { ; }
}
void f137(void) {
int64_t x549 = INT64_MIN;
int8_t x551 = 1;
volatile int32_t t137 = -765;
t137 = ((x549==(x550!=x551))>x552);
if (t137 != 1) { NG(); } else { ; }
}
void f138(void) {
int32_t x553 = INT32_MIN;
int64_t x554 = 7715836619699508LL;
int64_t x556 = 1086LL;
t138 = ((x553==(x554!=x555))>x556);
if (t138 != 0) { NG(); } else { ; }
}
void f139(void) {
volatile int32_t x557 = INT32_MIN;
static uint32_t x559 = UINT32_MAX;
int32_t x560 = -3768974;
volatile int32_t t139 = -100;
t139 = ((x557==(x558!=x559))>x560);
if (t139 != 1) { NG(); } else { ; }
}
void f140(void) {
uint16_t x561 = UINT16_MAX;
uint64_t x562 = 147795807LLU;
volatile int32_t x563 = INT32_MIN;
int64_t x564 = -125605506380235LL;
int32_t t140 = 921446215;
t140 = ((x561==(x562!=x563))>x564);
if (t140 != 1) { NG(); } else { ; }
}
void f141(void) {
static volatile uint8_t x565 = 0U;
volatile uint64_t x566 = 58753338254847060LLU;
volatile int64_t x567 = INT64_MIN;
int32_t x568 = 4942;
volatile int32_t t141 = -1137115;
t141 = ((x565==(x566!=x567))>x568);
if (t141 != 0) { NG(); } else { ; }
}
void f142(void) {
volatile uint64_t x569 = UINT64_MAX;
uint16_t x570 = 20242U;
volatile int16_t x571 = INT16_MIN;
uint32_t x572 = 415305801U;
int32_t t142 = 59562;
t142 = ((x569==(x570!=x571))>x572);
if (t142 != 0) { NG(); } else { ; }
}
void f143(void) {
int32_t x573 = INT32_MIN;
int8_t x574 = -1;
int32_t t143 = 489;
t143 = ((x573==(x574!=x575))>x576);
if (t143 != 0) { NG(); } else { ; }
}
void f144(void) {
volatile int64_t x577 = -1LL;
volatile uint16_t x578 = 1248U;
volatile int32_t t144 = -3192;
t144 = ((x577==(x578!=x579))>x580);
if (t144 != 0) { NG(); } else { ; }
}
void f145(void) {
volatile uint64_t x581 = 15822737117617LLU;
uint64_t x582 = 1008884LLU;
volatile int32_t t145 = 24;
t145 = ((x581==(x582!=x583))>x584);
if (t145 != 0) { NG(); } else { ; }
}
void f146(void) {
static int16_t x585 = INT16_MIN;
int16_t x586 = INT16_MAX;
int8_t x587 = 1;
int8_t x588 = 0;
static volatile int32_t t146 = 19;
t146 = ((x585==(x586!=x587))>x588);
if (t146 != 0) { NG(); } else { ; }
}
void f147(void) {
uint16_t x589 = UINT16_MAX;
int32_t x590 = INT32_MIN;
int32_t x591 = -1;
t147 = ((x589==(x590!=x591))>x592);
if (t147 != 0) { NG(); } else { ; }
}
void f148(void) {
int8_t x593 = INT8_MIN;
volatile int64_t x594 = INT64_MIN;
uint8_t x595 = 15U;
uint32_t x596 = 55756522U;
int32_t t148 = 368304;
t148 = ((x593==(x594!=x595))>x596);
if (t148 != 0) { NG(); } else { ; }
}
void f149(void) {
int8_t x597 = 57;
uint16_t x598 = 28U;
volatile uint32_t x599 = 8202U;
int32_t t149 = -1;
t149 = ((x597==(x598!=x599))>x600);
if (t149 != 1) { NG(); } else { ; }
}
void f150(void) {
int64_t x601 = 352927LL;
int16_t x602 = -1;
uint16_t x604 = UINT16_MAX;
int32_t t150 = 636;
t150 = ((x601==(x602!=x603))>x604);
if (t150 != 0) { NG(); } else { ; }
}
void f151(void) {
static uint64_t x606 = 6973671LLU;
volatile int16_t x607 = INT16_MAX;
uint16_t x608 = UINT16_MAX;
volatile int32_t t151 = 1;
t151 = ((x605==(x606!=x607))>x608);
if (t151 != 0) { NG(); } else { ; }
}
void f152(void) {
static volatile uint16_t x609 = 12240U;
static uint32_t x610 = 4636848U;
volatile int8_t x611 = INT8_MIN;
uint64_t x612 = 12200238930LLU;
int32_t t152 = 24921;
t152 = ((x609==(x610!=x611))>x612);
if (t152 != 0) { NG(); } else { ; }
}
void f153(void) {
uint64_t x613 = UINT64_MAX;
int32_t x614 = 105864206;
int32_t x615 = 520529823;
static volatile uint8_t x616 = UINT8_MAX;
volatile int32_t t153 = 2660;
t153 = ((x613==(x614!=x615))>x616);
if (t153 != 0) { NG(); } else { ; }
}
void f154(void) {
static int32_t x618 = -1;
static uint64_t x619 = 90701709LLU;
uint32_t x620 = UINT32_MAX;
static int32_t t154 = 50962447;
t154 = ((x617==(x618!=x619))>x620);
if (t154 != 0) { NG(); } else { ; }
}
void f155(void) {
static uint32_t x621 = UINT32_MAX;
int32_t x622 = -1;
int8_t x623 = -1;
volatile int16_t x624 = 30;
volatile int32_t t155 = -1;
t155 = ((x621==(x622!=x623))>x624);
if (t155 != 0) { NG(); } else { ; }
}
void f156(void) {
volatile uint32_t x625 = 15U;
int16_t x626 = -1267;
int32_t t156 = 371;
t156 = ((x625==(x626!=x627))>x628);
if (t156 != 1) { NG(); } else { ; }
}
void f157(void) {
uint8_t x629 = UINT8_MAX;
int32_t x630 = INT32_MIN;
int8_t x631 = -8;
int64_t x632 = -10026042420995LL;
static volatile int32_t t157 = -2906;
t157 = ((x629==(x630!=x631))>x632);
if (t157 != 1) { NG(); } else { ; }
}
void f158(void) {
static volatile int16_t x633 = INT16_MIN;
uint16_t x634 = 0U;
int16_t x635 = INT16_MIN;
volatile int64_t x636 = -1LL;
t158 = ((x633==(x634!=x635))>x636);
if (t158 != 1) { NG(); } else { ; }
}
void f159(void) {
int64_t x637 = -1LL;
volatile int8_t x638 = INT8_MIN;
volatile uint32_t x639 = UINT32_MAX;
int64_t x640 = -1LL;
static int32_t t159 = -3117;
t159 = ((x637==(x638!=x639))>x640);
if (t159 != 1) { NG(); } else { ; }
}
void f160(void) {
int8_t x641 = INT8_MIN;
int8_t x642 = INT8_MAX;
static int16_t x643 = INT16_MAX;
static volatile int32_t t160 = -70714382;
t160 = ((x641==(x642!=x643))>x644);
if (t160 != 0) { NG(); } else { ; }
}
void f161(void) {
volatile int16_t x645 = INT16_MIN;
static volatile uint32_t x647 = 70053929U;
int32_t t161 = -7625;
t161 = ((x645==(x646!=x647))>x648);
if (t161 != 0) { NG(); } else { ; }
}
void f162(void) {
int64_t x649 = INT64_MAX;
int8_t x650 = INT8_MAX;
int32_t x651 = -1;
static uint16_t x652 = 1U;
static int32_t t162 = 121391298;
t162 = ((x649==(x650!=x651))>x652);
if (t162 != 0) { NG(); } else { ; }
}
void f163(void) {
static int64_t x654 = INT64_MIN;
volatile uint8_t x656 = 22U;
t163 = ((x653==(x654!=x655))>x656);
if (t163 != 0) { NG(); } else { ; }
}
void f164(void) {
static uint16_t x657 = 13342U;
int32_t x658 = INT32_MIN;
static int8_t x660 = -2;
static volatile int32_t t164 = -1752277;
t164 = ((x657==(x658!=x659))>x660);
if (t164 != 1) { NG(); } else { ; }
}
void f165(void) {
int64_t x661 = INT64_MIN;
uint64_t x663 = 55LLU;
uint8_t x664 = UINT8_MAX;
volatile int32_t t165 = -40;
t165 = ((x661==(x662!=x663))>x664);
if (t165 != 0) { NG(); } else { ; }
}
void f166(void) {
uint16_t x665 = 11591U;
static uint64_t x666 = UINT64_MAX;
static uint16_t x667 = 1225U;
int32_t t166 = 6;
t166 = ((x665==(x666!=x667))>x668);
if (t166 != 1) { NG(); } else { ; }
}
void f167(void) {
int16_t x670 = INT16_MAX;
int16_t x671 = INT16_MIN;
volatile int32_t t167 = 285807;
t167 = ((x669==(x670!=x671))>x672);
if (t167 != 1) { NG(); } else { ; }
}
void f168(void) {
static int16_t x676 = INT16_MIN;
volatile int32_t t168 = -13508999;
t168 = ((x673==(x674!=x675))>x676);
if (t168 != 1) { NG(); } else { ; }
}
void f169(void) {
static uint32_t x677 = 1U;
int8_t x679 = INT8_MAX;
static int32_t x680 = -1;
volatile int32_t t169 = 49172716;
t169 = ((x677==(x678!=x679))>x680);
if (t169 != 1) { NG(); } else { ; }
}
void f170(void) {
static uint64_t x681 = UINT64_MAX;
int64_t x682 = INT64_MIN;
int16_t x683 = INT16_MAX;
uint8_t x684 = 0U;
static volatile int32_t t170 = -1764194;
t170 = ((x681==(x682!=x683))>x684);
if (t170 != 0) { NG(); } else { ; }
}
void f171(void) {
uint16_t x685 = 5864U;
volatile uint8_t x686 = 47U;
int32_t x687 = -3905;
static volatile uint8_t x688 = 31U;
static volatile int32_t t171 = -80476;
t171 = ((x685==(x686!=x687))>x688);
if (t171 != 0) { NG(); } else { ; }
}
void f172(void) {
int8_t x689 = -1;
volatile int8_t x692 = -1;
volatile int32_t t172 = 120632;
t172 = ((x689==(x690!=x691))>x692);
if (t172 != 1) { NG(); } else { ; }
}
void f173(void) {
volatile uint16_t x693 = 30970U;
uint32_t x694 = 425322U;
int64_t x695 = -1LL;
int64_t x696 = 7201034709785LL;
volatile int32_t t173 = -61;
t173 = ((x693==(x694!=x695))>x696);
if (t173 != 0) { NG(); } else { ; }
}
void f174(void) {
int32_t x697 = -1;
static uint16_t x700 = 102U;
t174 = ((x697==(x698!=x699))>x700);
if (t174 != 0) { NG(); } else { ; }
}
void f175(void) {
volatile uint16_t x701 = 1U;
volatile uint8_t x702 = 4U;
int64_t x703 = INT64_MAX;
int16_t x704 = -5;
t175 = ((x701==(x702!=x703))>x704);
if (t175 != 1) { NG(); } else { ; }
}
void f176(void) {
uint64_t x705 = 332133LLU;
int8_t x706 = INT8_MIN;
int16_t x707 = INT16_MAX;
volatile int32_t t176 = -1;
t176 = ((x705==(x706!=x707))>x708);
if (t176 != 0) { NG(); } else { ; }
}
void f177(void) {
volatile int32_t x710 = INT32_MIN;
int64_t x711 = -55581419571607LL;
int64_t x712 = -1LL;
static int32_t t177 = -10342;
t177 = ((x709==(x710!=x711))>x712);
if (t177 != 1) { NG(); } else { ; }
}
void f178(void) {
static int8_t x713 = -8;
int8_t x714 = INT8_MIN;
int8_t x715 = INT8_MIN;
static int32_t t178 = -842887;
t178 = ((x713==(x714!=x715))>x716);
if (t178 != 1) { NG(); } else { ; }
}
void f179(void) {
static int16_t x718 = INT16_MIN;
static int16_t x720 = 1;
int32_t t179 = -36;
t179 = ((x717==(x718!=x719))>x720);
if (t179 != 0) { NG(); } else { ; }
}
void f180(void) {
volatile int16_t x721 = 214;
uint8_t x724 = 14U;
int32_t t180 = 2443060;
t180 = ((x721==(x722!=x723))>x724);
if (t180 != 0) { NG(); } else { ; }
}
void f181(void) {
int8_t x725 = INT8_MIN;
static int16_t x726 = INT16_MIN;
volatile uint8_t x727 = 7U;
uint16_t x728 = 1U;
int32_t t181 = 14056;
t181 = ((x725==(x726!=x727))>x728);
if (t181 != 0) { NG(); } else { ; }
}
void f182(void) {
uint8_t x730 = 75U;
uint16_t x731 = 108U;
t182 = ((x729==(x730!=x731))>x732);
if (t182 != 1) { NG(); } else { ; }
}
void f183(void) {
uint32_t x733 = 732401U;
volatile uint32_t x734 = 18U;
static int64_t x736 = 257257514113769505LL;
volatile int32_t t183 = -2998;
t183 = ((x733==(x734!=x735))>x736);
if (t183 != 0) { NG(); } else { ; }
}
void f184(void) {
int64_t x737 = INT64_MIN;
static uint8_t x738 = UINT8_MAX;
static int32_t x739 = -68;
static int32_t x740 = -1;
volatile int32_t t184 = -4516;
t184 = ((x737==(x738!=x739))>x740);
if (t184 != 1) { NG(); } else { ; }
}
void f185(void) {
uint32_t x741 = 253994987U;
int8_t x742 = -1;
int16_t x744 = -1;
int32_t t185 = 184844517;
t185 = ((x741==(x742!=x743))>x744);
if (t185 != 1) { NG(); } else { ; }
}
void f186(void) {
static int8_t x745 = INT8_MIN;
static uint16_t x746 = 5U;
volatile uint16_t x747 = UINT16_MAX;
uint32_t x748 = UINT32_MAX;
int32_t t186 = -16306787;
t186 = ((x745==(x746!=x747))>x748);
if (t186 != 0) { NG(); } else { ; }
}
void f187(void) {
static int8_t x749 = 0;
uint8_t x750 = 0U;
static int64_t x751 = -1LL;
int64_t x752 = INT64_MAX;
static int32_t t187 = 0;
t187 = ((x749==(x750!=x751))>x752);
if (t187 != 0) { NG(); } else { ; }
}
void f188(void) {
int8_t x753 = INT8_MIN;
int16_t x754 = INT16_MAX;
uint32_t x755 = 52U;
int64_t x756 = INT64_MAX;
t188 = ((x753==(x754!=x755))>x756);
if (t188 != 0) { NG(); } else { ; }
}
void f189(void) {
int64_t x757 = -32326321LL;
uint16_t x758 = UINT16_MAX;
int32_t x759 = -1;
int32_t t189 = 0;
t189 = ((x757==(x758!=x759))>x760);
if (t189 != 0) { NG(); } else { ; }
}
void f190(void) {
int32_t x762 = 28401;
int8_t x763 = 1;
int64_t x764 = -20499342352223276LL;
int32_t t190 = -855055172;
t190 = ((x761==(x762!=x763))>x764);
if (t190 != 1) { NG(); } else { ; }
}
void f191(void) {
static uint64_t x765 = UINT64_MAX;
static uint32_t x767 = 8U;
static uint32_t x768 = 0U;
t191 = ((x765==(x766!=x767))>x768);
if (t191 != 0) { NG(); } else { ; }
}
void f192(void) {
static uint64_t x769 = UINT64_MAX;
int64_t x770 = INT64_MAX;
int32_t x771 = INT32_MIN;
volatile int32_t t192 = -1404;
t192 = ((x769==(x770!=x771))>x772);
if (t192 != 0) { NG(); } else { ; }
}
void f193(void) {
volatile int64_t x773 = INT64_MIN;
int64_t x774 = INT64_MAX;
uint16_t x775 = 187U;
volatile int64_t x776 = INT64_MIN;
int32_t t193 = 71404;
t193 = ((x773==(x774!=x775))>x776);
if (t193 != 1) { NG(); } else { ; }
}
void f194(void) {
int8_t x777 = INT8_MIN;
int32_t x778 = 730;
static volatile uint8_t x779 = 1U;
static uint64_t x780 = 206438LLU;
static int32_t t194 = -844903;
t194 = ((x777==(x778!=x779))>x780);
if (t194 != 0) { NG(); } else { ; }
}
void f195(void) {
int32_t x781 = -30804;
volatile int16_t x782 = -1;
uint32_t x783 = 491514526U;
volatile int32_t t195 = 1580;
t195 = ((x781==(x782!=x783))>x784);
if (t195 != 0) { NG(); } else { ; }
}
void f196(void) {
uint64_t x785 = 189706375052603LLU;
uint32_t x786 = UINT32_MAX;
uint8_t x787 = 0U;
static uint32_t x788 = 21065721U;
t196 = ((x785==(x786!=x787))>x788);
if (t196 != 0) { NG(); } else { ; }
}
void f197(void) {
static int8_t x789 = INT8_MIN;
int32_t x790 = 3830876;
int16_t x792 = INT16_MIN;
int32_t t197 = -2685158;
t197 = ((x789==(x790!=x791))>x792);
if (t197 != 1) { NG(); } else { ; }
}
void f198(void) {
static volatile uint8_t x793 = 3U;
int16_t x794 = -1;
static int8_t x795 = INT8_MAX;
volatile int16_t x796 = 25;
static int32_t t198 = 1;
t198 = ((x793==(x794!=x795))>x796);
if (t198 != 0) { NG(); } else { ; }
}
void f199(void) {
uint32_t x797 = 4438473U;
int64_t x798 = INT64_MIN;
uint32_t x799 = 2406U;
int32_t x800 = -1;
int32_t t199 = -8506;
t199 = ((x797==(x798!=x799))>x800);
if (t199 != 1) { NG(); } else { ; }
}
int main(void) {
f0();
f1();
f2();
f3();
f4();
f5();
f6();
f7();
f8();
f9();
f10();
f11();
f12();
f13();
f14();
f15();
f16();
f17();
f18();
f19();
f20();
f21();
f22();
f23();
f24();
f25();
f26();
f27();
f28();
f29();
f30();
f31();
f32();
f33();
f34();
f35();
f36();
f37();
f38();
f39();
f40();
f41();
f42();
f43();
f44();
f45();
f46();
f47();
f48();
f49();
f50();
f51();
f52();
f53();
f54();
f55();
f56();
f57();
f58();
f59();
f60();
f61();
f62();
f63();
f64();
f65();
f66();
f67();
f68();
f69();
f70();
f71();
f72();
f73();
f74();
f75();
f76();
f77();
f78();
f79();
f80();
f81();
f82();
f83();
f84();
f85();
f86();
f87();
f88();
f89();
f90();
f91();
f92();
f93();
f94();
f95();
f96();
f97();
f98();
f99();
f100();
f101();
f102();
f103();
f104();
f105();
f106();
f107();
f108();
f109();
f110();
f111();
f112();
f113();
f114();
f115();
f116();
f117();
f118();
f119();
f120();
f121();
f122();
f123();
f124();
f125();
f126();
f127();
f128();
f129();
f130();
f131();
f132();
f133();
f134();
f135();
f136();
f137();
f138();
f139();
f140();
f141();
f142();
f143();
f144();
f145();
f146();
f147();
f148();
f149();
f150();
f151();
f152();
f153();
f154();
f155();
f156();
f157();
f158();
f159();
f160();
f161();
f162();
f163();
f164();
f165();
f166();
f167();
f168();
f169();
f170();
f171();
f172();
f173();
f174();
f175();
f176();
f177();
f178();
f179();
f180();
f181();
f182();
f183();
f184();
f185();
f186();
f187();
f188();
f189();
f190();
f191();
f192();
f193();
f194();
f195();
f196();
f197();
f198();
f199();
return 0;
}
| 18.469547 | 54 | 0.57692 |
6bb8363a8457ce997e5baf9564074fcb1111fb6a | 184 | h | C | mpers-mx32/timespec_t.h | pixeldustproject-o/android_external_strace | 0be31d963f5c76aa4fbf0a0d220a99fdd66a84ec | [
"BSD-3-Clause"
] | null | null | null | mpers-mx32/timespec_t.h | pixeldustproject-o/android_external_strace | 0be31d963f5c76aa4fbf0a0d220a99fdd66a84ec | [
"BSD-3-Clause"
] | null | null | null | mpers-mx32/timespec_t.h | pixeldustproject-o/android_external_strace | 0be31d963f5c76aa4fbf0a0d220a99fdd66a84ec | [
"BSD-3-Clause"
] | null | null | null | #include <inttypes.h>
typedef uint32_t mpers_ptr_t;
typedef
struct {
int64_t tv_sec;
int64_t tv_nsec;
} ATTRIBUTE_PACKED mx32_timespec_t;
#define MPERS_mx32_timespec_t mx32_timespec_t
| 20.444444 | 45 | 0.842391 |
5942b294da3317b83944561a75e7e13d17474305 | 680 | c | C | debug-hands-on/stack_overflow/main/app_main.c | mahavirj/esp-bootstrap | 3bf1b71d56a82b0fc41ade50575005018e9721aa | [
"Apache-2.0"
] | 8 | 2018-10-15T14:33:51.000Z | 2019-12-31T17:58:54.000Z | debug-hands-on/stack_overflow/main/app_main.c | mahavirj/esp-idf-training | 3bf1b71d56a82b0fc41ade50575005018e9721aa | [
"Apache-2.0"
] | 1 | 2018-11-06T17:54:15.000Z | 2018-11-21T06:00:45.000Z | debug-hands-on/stack_overflow/main/app_main.c | mahavirj/esp-idf-training | 3bf1b71d56a82b0fc41ade50575005018e9721aa | [
"Apache-2.0"
] | 2 | 2018-11-28T06:29:51.000Z | 2020-11-30T17:49:57.000Z | /* Hello World Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <string.h>
void my_task(void *pvParameter)
{
char myarray[512];
memset(myarray, 0, sizeof(myarray));
while (1) {
vTaskDelay(5000);
}
}
void app_main()
{
printf("App main entered!\n");
xTaskCreate(&my_task, "my_task", configMINIMAL_STACK_SIZE, NULL, 5, NULL);
}
| 24.285714 | 79 | 0.692647 |
0dfe05badcb88da25faa8bdbcd8526257f46e901 | 29,435 | c | C | lugre/baselib/openal-soft-1.8.466/OpenAL32/alBuffer.c | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | 1 | 2020-10-18T14:33:05.000Z | 2020-10-18T14:33:05.000Z | lugre/baselib/openal-soft-1.8.466/OpenAL32/alBuffer.c | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | null | null | null | lugre/baselib/openal-soft-1.8.466/OpenAL32/alBuffer.c | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | null | null | null | /**
* OpenAL cross platform audio library
* Copyright (C) 1999-2007 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "alMain.h"
#include "AL/al.h"
#include "AL/alc.h"
#include "alError.h"
#include "alBuffer.h"
#include "alThunk.h"
static void LoadData(ALbuffer *ALBuf, const ALubyte *data, ALsizei size, ALuint freq, ALenum OrigFormat, ALenum NewFormat);
static void ConvertData(ALshort *dst, const ALvoid *src, ALint origBytes, ALsizei len);
static void ConvertDataRear(ALshort *dst, const ALvoid *src, ALint origBytes, ALsizei len);
static void ConvertDataIMA4(ALshort *dst, const ALvoid *src, ALint origChans, ALsizei len);
/*
* AL Buffer Functions
*
* AL Buffers are shared amoung Contexts, so we store the list of generated Buffers
* as a global variable in this module. (A valid context is not required to make
* AL Buffer function calls
*
*/
/*
* Global Variables
*/
static ALbuffer *g_pBuffers = NULL; // Linked List of Buffers
static ALuint g_uiBufferCount = 0; // Buffer Count
static const long g_IMAStep_size[89]={ // IMA ADPCM Stepsize table
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31,
34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143,
157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658,
724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024,
3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,10442,11487,12635,13899,
15289,16818,18500,20350,22358,24633,27086,29794,32767
};
static const long g_IMACodeword_4[16]={ // IMA4 ADPCM Codeword decode table
1, 3, 5, 7, 9, 11, 13, 15,
-1,-3,-5,-7,-9,-11,-13,-15,
};
static const long g_IMAIndex_adjust_4[16]={ // IMA4 ADPCM Step index adjust decode table
-1,-1,-1,-1, 2, 4, 6, 8,
-1,-1,-1,-1, 2, 4, 6, 8
};
/*
* alGenBuffers(ALsizei n, ALuint *puiBuffers)
*
* Generates n AL Buffers, and stores the Buffers Names in the array pointed to by puiBuffers
*/
ALAPI ALvoid ALAPIENTRY alGenBuffers(ALsizei n,ALuint *puiBuffers)
{
ALCcontext *Context;
ALsizei i=0;
Context = alcGetCurrentContext();
SuspendContext(Context);
// Check that we are actually generation some Buffers
if (n > 0)
{
// Check the pointer is valid (and points to enough memory to store Buffer Names)
if (!IsBadWritePtr((void*)puiBuffers, n * sizeof(ALuint)))
{
ALbuffer **list = &g_pBuffers;
while(*list)
list = &(*list)->next;
// Create all the new Buffers
while(i < n)
{
*list = calloc(1, sizeof(ALbuffer));
if(!(*list))
{
alDeleteBuffers(i, puiBuffers);
alSetError(AL_OUT_OF_MEMORY);
break;
}
puiBuffers[i] = (ALuint)ALTHUNK_ADDENTRY(*list);
(*list)->state = UNUSED;
g_uiBufferCount++;
i++;
list = &(*list)->next;
}
}
else
{
// Pointer does not point to enough memory to write Buffer names
alSetError(AL_INVALID_VALUE);
}
}
ProcessContext(Context);
return;
}
/*
* alDeleteBuffers(ALsizei n, ALuint *puiBuffers)
*
* Deletes the n AL Buffers pointed to by puiBuffers
*/
ALAPI ALvoid ALAPIENTRY alDeleteBuffers(ALsizei n, const ALuint *puiBuffers)
{
ALCcontext *Context;
ALbuffer *ALBuf;
ALsizei i;
ALboolean bFailed = AL_FALSE;
Context = alcGetCurrentContext();
SuspendContext(Context);
// Check we are actually Deleting some Buffers
if (n >= 0)
{
// Check that all the buffers are valid and can actually be deleted
for (i = 0; i < n; i++)
{
// Check for valid Buffer ID (can be NULL buffer)
if (alIsBuffer(puiBuffers[i]))
{
// If not the NULL buffer, check that the reference count is 0
ALBuf = ((ALbuffer *)ALTHUNK_LOOKUPENTRY(puiBuffers[i]));
if (ALBuf)
{
if (ALBuf->refcount != 0)
{
// Buffer still in use, cannot be deleted
alSetError(AL_INVALID_OPERATION);
bFailed = AL_TRUE;
}
}
}
else
{
// Invalid Buffer
alSetError(AL_INVALID_NAME);
bFailed = AL_TRUE;
}
}
// If all the Buffers were valid (and have Reference Counts of 0), then we can delete them
if (!bFailed)
{
for (i = 0; i < n; i++)
{
if (puiBuffers[i] && alIsBuffer(puiBuffers[i]))
{
ALbuffer **list = &g_pBuffers;
ALBuf=((ALbuffer *)ALTHUNK_LOOKUPENTRY(puiBuffers[i]));
while(*list && *list != ALBuf)
list = &(*list)->next;
if(*list)
*list = (*list)->next;
// Release the memory used to store audio data
free(ALBuf->data);
// Release buffer structure
ALTHUNK_REMOVEENTRY(puiBuffers[i]);
memset(ALBuf, 0, sizeof(ALbuffer));
g_uiBufferCount--;
free(ALBuf);
}
}
}
}
else
alSetError(AL_INVALID_VALUE);
ProcessContext(Context);
return;
}
/*
* alIsBuffer(ALuint uiBuffer)
*
* Checks if ulBuffer is a valid Buffer Name
*/
ALAPI ALboolean ALAPIENTRY alIsBuffer(ALuint uiBuffer)
{
ALCcontext *Context;
ALboolean result=AL_FALSE;
ALbuffer *ALBuf;
ALbuffer *TgtALBuf;
Context = alcGetCurrentContext();
SuspendContext(Context);
if (uiBuffer)
{
TgtALBuf = (ALbuffer *)ALTHUNK_LOOKUPENTRY(uiBuffer);
// Check through list of generated buffers for uiBuffer
ALBuf = g_pBuffers;
while (ALBuf)
{
if (ALBuf == TgtALBuf)
{
result = AL_TRUE;
break;
}
ALBuf = ALBuf->next;
}
}
else
{
result = AL_TRUE;
}
ProcessContext(Context);
return result;
}
/*
* alBufferData(ALuint buffer,ALenum format,ALvoid *data,ALsizei size,ALsizei freq)
*
* Fill buffer with audio data
*/
ALAPI ALvoid ALAPIENTRY alBufferData(ALuint buffer,ALenum format,const ALvoid *data,ALsizei size,ALsizei freq)
{
ALCcontext *Context;
ALsizei padding = 2;
ALbuffer *ALBuf;
ALvoid *temp;
Context = alcGetCurrentContext();
SuspendContext(Context);
if (alIsBuffer(buffer) && (buffer != 0))
{
ALBuf=((ALbuffer *)ALTHUNK_LOOKUPENTRY(buffer));
if ((ALBuf->refcount==0)&&(data))
{
switch(format)
{
case AL_FORMAT_MONO8:
case AL_FORMAT_MONO16:
case AL_FORMAT_MONO_FLOAT32:
LoadData(ALBuf, data, size, freq, format, AL_FORMAT_MONO16);
break;
case AL_FORMAT_STEREO8:
case AL_FORMAT_STEREO16:
case AL_FORMAT_STEREO_FLOAT32:
LoadData(ALBuf, data, size, freq, format, AL_FORMAT_STEREO16);
break;
case AL_FORMAT_REAR8:
case AL_FORMAT_REAR16:
case AL_FORMAT_REAR32: {
ALuint NewFormat = AL_FORMAT_QUAD16;
ALuint NewChannels = aluChannelsFromFormat(NewFormat);
ALuint OrigBytes = ((format==AL_FORMAT_REAR8) ? 1 :
((format==AL_FORMAT_REAR16) ? 2 :
4));
assert(aluBytesFromFormat(NewFormat) == 2);
if((size%(OrigBytes*2)) != 0)
{
alSetError(AL_INVALID_VALUE);
break;
}
size /= OrigBytes;
size *= 2;
// Samples are converted to 16 bit here
temp = realloc(ALBuf->data, (padding*NewChannels + size) * sizeof(ALshort));
if(temp)
{
ALBuf->data = temp;
ConvertDataRear(ALBuf->data, data, OrigBytes, size);
memset(&(ALBuf->data[size]), 0, padding*NewChannels*sizeof(ALshort));
ALBuf->format = NewFormat;
ALBuf->eOriginalFormat = format;
ALBuf->size = size*sizeof(ALshort);
ALBuf->frequency = freq;
ALBuf->padding = padding;
}
else
alSetError(AL_OUT_OF_MEMORY);
} break;
case AL_FORMAT_QUAD8_LOKI:
case AL_FORMAT_QUAD16_LOKI:
case AL_FORMAT_QUAD8:
case AL_FORMAT_QUAD16:
case AL_FORMAT_QUAD32:
LoadData(ALBuf, data, size, freq, format, AL_FORMAT_QUAD16);
break;
case AL_FORMAT_51CHN8:
case AL_FORMAT_51CHN16:
case AL_FORMAT_51CHN32:
LoadData(ALBuf, data, size, freq, format, AL_FORMAT_51CHN16);
break;
case AL_FORMAT_61CHN8:
case AL_FORMAT_61CHN16:
case AL_FORMAT_61CHN32:
LoadData(ALBuf, data, size, freq, format, AL_FORMAT_61CHN16);
break;
case AL_FORMAT_71CHN8:
case AL_FORMAT_71CHN16:
case AL_FORMAT_71CHN32:
LoadData(ALBuf, data, size, freq, format, AL_FORMAT_71CHN16);
break;
case AL_FORMAT_MONO_IMA4:
case AL_FORMAT_STEREO_IMA4: {
int OrigChans = ((format==AL_FORMAT_MONO_IMA4) ? 1 : 2);
// Here is where things vary:
// nVidia and Apple use 64+1 samples per channel per block => block_size=36*chans bytes
// Most PC sound software uses 2040+1 samples per channel per block -> block_size=1024*chans bytes
if((size%(36*OrigChans)) != 0)
{
alSetError(AL_INVALID_VALUE);
break;
}
size /= 36;
size *= 65;
// Allocate extra padding samples
temp = realloc(ALBuf->data, (padding*OrigChans + size)*sizeof(ALshort));
if(temp)
{
ALBuf->data = temp;
ConvertDataIMA4(ALBuf->data, data, OrigChans, size/65);
memset(&(ALBuf->data[size]), 0, padding*sizeof(ALshort)*OrigChans);
ALBuf->format = ((OrigChans==1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16);
ALBuf->eOriginalFormat = format;
ALBuf->size = size*sizeof(ALshort);
ALBuf->frequency = freq;
ALBuf->padding = padding;
}
else
alSetError(AL_OUT_OF_MEMORY);
} break;
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
// Buffer is in use, or data is a NULL pointer
alSetError(AL_INVALID_VALUE);
}
}
else
{
// Invalid Buffer Name
alSetError(AL_INVALID_NAME);
}
ProcessContext(Context);
}
/*
* alBufferSubDataEXT(ALuint buffer,ALenum format,ALvoid *data,ALsizei offset,ALsizei length)
*
* Fill buffer with audio data
*/
ALvoid ALAPIENTRY alBufferSubDataEXT(ALuint buffer,ALenum format,const ALvoid *data,ALsizei offset,ALsizei length)
{
ALCcontext *Context;
ALbuffer *ALBuf;
Context = alcGetCurrentContext();
SuspendContext(Context);
if(alIsBuffer(buffer) && buffer != 0)
{
ALBuf = (ALbuffer*)ALTHUNK_LOOKUPENTRY(buffer);
if(ALBuf->data == NULL)
{
// buffer does not have any data
alSetError(AL_INVALID_NAME);
}
else if(length < 0 || offset < 0 || (length > 0 && data == NULL))
{
// data is NULL or offset/length is negative
alSetError(AL_INVALID_VALUE);
}
else
{
switch(format)
{
case AL_FORMAT_REAR8:
case AL_FORMAT_REAR16:
case AL_FORMAT_REAR32: {
ALuint OrigBytes = ((format==AL_FORMAT_REAR8) ? 1 :
((format==AL_FORMAT_REAR16) ? 2 :
4));
if(ALBuf->eOriginalFormat != AL_FORMAT_REAR8 &&
ALBuf->eOriginalFormat != AL_FORMAT_REAR16 &&
ALBuf->eOriginalFormat != AL_FORMAT_REAR32)
{
alSetError(AL_INVALID_ENUM);
break;
}
if(ALBuf->size/4/sizeof(ALshort) < (ALuint)offset+length)
{
alSetError(AL_INVALID_VALUE);
break;
}
ConvertDataRear(&ALBuf->data[offset*4], data, OrigBytes, length*2);
} break;
case AL_FORMAT_MONO_IMA4:
case AL_FORMAT_STEREO_IMA4: {
int Channels = aluChannelsFromFormat(ALBuf->format);
if(ALBuf->eOriginalFormat != format)
{
alSetError(AL_INVALID_ENUM);
break;
}
if((offset%65) != 0 || (length%65) != 0 ||
ALBuf->size/Channels/sizeof(ALshort) < (ALuint)offset+length)
{
alSetError(AL_INVALID_VALUE);
break;
}
ConvertDataIMA4(&ALBuf->data[offset*Channels], data, Channels, length/65*Channels);
} break;
default: {
ALuint Channels = aluChannelsFromFormat(format);
ALuint Bytes = aluBytesFromFormat(format);
if(Channels != aluChannelsFromFormat(ALBuf->format))
{
alSetError(AL_INVALID_ENUM);
break;
}
if(ALBuf->size/Channels/sizeof(ALshort) < (ALuint)offset+length)
{
alSetError(AL_INVALID_VALUE);
break;
}
ConvertData(&ALBuf->data[offset*Channels], data, Bytes, length*Channels);
} break;
}
}
}
else
{
// Invalid Buffer Name
alSetError(AL_INVALID_NAME);
}
ProcessContext(Context);
}
ALAPI void ALAPIENTRY alBufferf(ALuint buffer, ALenum eParam, ALfloat flValue)
{
ALCcontext *pContext;
(void)flValue;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alBuffer3f(ALuint buffer, ALenum eParam, ALfloat flValue1, ALfloat flValue2, ALfloat flValue3)
{
ALCcontext *pContext;
(void)flValue1;
(void)flValue2;
(void)flValue3;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alBufferfv(ALuint buffer, ALenum eParam, const ALfloat* flValues)
{
ALCcontext *pContext;
(void)flValues;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alBufferi(ALuint buffer, ALenum eParam, ALint lValue)
{
ALCcontext *pContext;
(void)lValue;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alBuffer3i( ALuint buffer, ALenum eParam, ALint lValue1, ALint lValue2, ALint lValue3)
{
ALCcontext *pContext;
(void)lValue1;
(void)lValue2;
(void)lValue3;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alBufferiv(ALuint buffer, ALenum eParam, const ALint* plValues)
{
ALCcontext *pContext;
(void)plValues;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
ProcessContext(pContext);
}
ALAPI ALvoid ALAPIENTRY alGetBufferf(ALuint buffer, ALenum eParam, ALfloat *pflValue)
{
ALCcontext *pContext;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (pflValue)
{
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
}
else
{
alSetError(AL_INVALID_VALUE);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alGetBuffer3f(ALuint buffer, ALenum eParam, ALfloat* pflValue1, ALfloat* pflValue2, ALfloat* pflValue3)
{
ALCcontext *pContext;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if ((pflValue1) && (pflValue2) && (pflValue3))
{
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
}
else
{
alSetError(AL_INVALID_VALUE);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alGetBufferfv(ALuint buffer, ALenum eParam, ALfloat* pflValues)
{
ALCcontext *pContext;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (pflValues)
{
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
}
else
{
alSetError(AL_INVALID_VALUE);
}
ProcessContext(pContext);
}
ALAPI ALvoid ALAPIENTRY alGetBufferi(ALuint buffer, ALenum eParam, ALint *plValue)
{
ALCcontext *pContext;
ALbuffer *pBuffer;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (plValue)
{
if (alIsBuffer(buffer) && (buffer != 0))
{
pBuffer = ((ALbuffer *)ALTHUNK_LOOKUPENTRY(buffer));
switch (eParam)
{
case AL_FREQUENCY:
*plValue = pBuffer->frequency;
break;
case AL_BITS:
*plValue = aluBytesFromFormat(pBuffer->format) * 8;
break;
case AL_CHANNELS:
*plValue = aluChannelsFromFormat(pBuffer->format);
break;
case AL_SIZE:
*plValue = pBuffer->size;
break;
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
}
else
{
alSetError(AL_INVALID_VALUE);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alGetBuffer3i(ALuint buffer, ALenum eParam, ALint* plValue1, ALint* plValue2, ALint* plValue3)
{
ALCcontext *pContext;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if ((plValue1) && (plValue2) && (plValue3))
{
if (alIsBuffer(buffer) && (buffer != 0))
{
switch(eParam)
{
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
}
else
{
alSetError(AL_INVALID_VALUE);
}
ProcessContext(pContext);
}
ALAPI void ALAPIENTRY alGetBufferiv(ALuint buffer, ALenum eParam, ALint* plValues)
{
ALCcontext *pContext;
pContext = alcGetCurrentContext();
SuspendContext(pContext);
if (plValues)
{
if (alIsBuffer(buffer) && (buffer != 0))
{
switch (eParam)
{
case AL_FREQUENCY:
case AL_BITS:
case AL_CHANNELS:
case AL_SIZE:
alGetBufferi(buffer, eParam, plValues);
break;
default:
alSetError(AL_INVALID_ENUM);
break;
}
}
else
{
alSetError(AL_INVALID_NAME);
}
}
else
{
alSetError(AL_INVALID_VALUE);
}
ProcessContext(pContext);
}
/*
* LoadData
*
* Loads the specified data into the buffer, using the specified formats.
* Currently, the new format must be 16-bit, and must have the same channel
* configuration as the original format. This does NOT handle compressed
* formats (eg. IMA4).
*/
static void LoadData(ALbuffer *ALBuf, const ALubyte *data, ALsizei size, ALuint freq, ALenum OrigFormat, ALenum NewFormat)
{
ALuint NewChannels = aluChannelsFromFormat(NewFormat);
ALuint OrigBytes = aluBytesFromFormat(OrigFormat);
ALuint OrigChannels = aluChannelsFromFormat(OrigFormat);
ALsizei padding = 2;
ALvoid *temp;
assert(aluBytesFromFormat(NewFormat) == 2);
assert(NewChannels == OrigChannels);
if ((size%(OrigBytes*OrigChannels)) != 0)
{
alSetError(AL_INVALID_VALUE);
return;
}
// Samples are converted to 16 bit here
size /= OrigBytes;
temp = realloc(ALBuf->data, (padding*NewChannels + size) * sizeof(ALshort));
if(temp)
{
ALBuf->data = temp;
ConvertData(ALBuf->data, data, OrigBytes, size);
memset(&(ALBuf->data[size]), 0, padding*NewChannels*sizeof(ALshort));
ALBuf->format = NewFormat;
ALBuf->eOriginalFormat = OrigFormat;
ALBuf->size = size*sizeof(ALshort);
ALBuf->frequency = freq;
ALBuf->padding = padding;
}
else
alSetError(AL_OUT_OF_MEMORY);
}
static void ConvertData(ALshort *dst, const ALvoid *src, ALint origBytes, ALsizei len)
{
ALsizei i;
switch(origBytes)
{
case 1:
for(i = 0;i < len;i++)
dst[i] = ((ALshort)((ALubyte*)src)[i] - 128) << 8;
break;
case 2:
memcpy(dst, src, len*sizeof(ALshort));
break;
case 4:
for(i = 0;i < len;i++)
{
ALint smp;
smp = (((ALfloat*)src)[i] * 32767.5f - 0.5f);
smp = min(smp, 32767);
smp = max(smp, -32768);
dst[i] = (ALshort)smp;
}
break;
default:
assert(0);
}
}
static void ConvertDataRear(ALshort *dst, const ALvoid *src, ALint origBytes, ALsizei len)
{
ALsizei i;
switch(origBytes)
{
case 1:
for(i = 0;i < len;i+=4)
{
dst[i+0] = 0;
dst[i+1] = 0;
dst[i+2] = ((ALshort)((ALubyte*)src)[i/2+0] - 128) << 8;
dst[i+3] = ((ALshort)((ALubyte*)src)[i/2+1] - 128) << 8;
}
break;
case 2:
for(i = 0;i < len;i+=4)
{
dst[i+0] = 0;
dst[i+1] = 0;
dst[i+2] = ((ALshort*)src)[i/2+0];
dst[i+3] = ((ALshort*)src)[i/2+1];
}
break;
case 4:
for(i = 0;i < len;i+=4)
{
ALint smp;
dst[i+0] = 0;
dst[i+1] = 0;
smp = (((ALfloat*)src)[i/2+0] * 32767.5f - 0.5);
smp = min(smp, 32767);
smp = max(smp, -32768);
dst[i+2] = (ALshort)smp;
smp = (((ALfloat*)src)[i/2+1] * 32767.5f - 0.5);
smp = min(smp, 32767);
smp = max(smp, -32768);
dst[i+3] = (ALshort)smp;
}
break;
default:
assert(0);
}
}
static void ConvertDataIMA4(ALshort *dst, const ALvoid *src, ALint origChans, ALsizei len)
{
const ALuint *IMAData;
ALint Sample[2],Index[2];
ALuint IMACode[2];
ALsizei i,j,k,c;
assert(origChans <= 2);
IMAData = src;
for(i = 0;i < len/origChans;i++)
{
for(c = 0;c < origChans;c++)
{
Sample[c] = ((ALshort*)IMAData)[0];
Index[c] = ((ALshort*)IMAData)[1];
Index[c] = ((Index[c]<0) ? 0 : Index[c]);
Index[c] = ((Index[c]>88) ? 88 : Index[c]);
dst[i*65*origChans + c] = (ALshort)Sample[c];
IMAData++;
}
for(j = 1;j < 65;j += 8)
{
for(c = 0;c < origChans;c++)
IMACode[c] = *(IMAData++);
for(k = 0;k < 8;k++)
{
for(c = 0;c < origChans;c++)
{
Sample[c] += ((g_IMAStep_size[Index[c]]*g_IMACodeword_4[IMACode[c]&15])/8);
Index[c] += g_IMAIndex_adjust_4[IMACode[c]&15];
if(Sample[c] < -32768) Sample[c] = -32768;
else if(Sample[c] > 32767) Sample[c] = 32767;
if(Index[c]<0) Index[c] = 0;
else if(Index[c]>88) Index[c] = 88;
dst[(i*65+j+k)*origChans + c] = (ALshort)Sample[c];
IMACode[c] >>= 4;
}
}
}
}
}
/*
* ReleaseALBuffers()
*
* INTERNAL FN : Called by DLLMain on exit to destroy any buffers that still exist
*/
ALvoid ReleaseALBuffers(ALvoid)
{
ALbuffer *ALBuffer;
ALbuffer *ALBufferTemp;
#ifdef _DEBUG
if(g_uiBufferCount > 0)
AL_PRINT("exit(): deleting %d Buffer(s)\n", g_uiBufferCount);
#endif
ALBuffer = g_pBuffers;
while(ALBuffer)
{
// Release sample data
free(ALBuffer->data);
// Release Buffer structure
ALBufferTemp = ALBuffer;
ALBuffer = ALBuffer->next;
memset(ALBufferTemp, 0, sizeof(ALbuffer));
free(ALBufferTemp);
}
g_pBuffers = NULL;
g_uiBufferCount = 0;
}
| 26.83227 | 125 | 0.511194 |
8a1accb7890d362a74afc3e8983f64405c5ccb91 | 3,799 | h | C | fake_tchar.h | abrenner/movie-thumbnailer-mtn | d532dba98a46a04bee6a858861ab2f5e8b96a81a | [
"MIT"
] | 35 | 2018-12-07T05:16:26.000Z | 2022-03-19T08:33:55.000Z | fake_tchar.h | abrenner/movie-thumbnailer-mtn | d532dba98a46a04bee6a858861ab2f5e8b96a81a | [
"MIT"
] | 3 | 2018-11-08T20:10:31.000Z | 2019-01-19T17:59:57.000Z | fake_tchar.h | abrenner/movie-thumbnailer-mtn | d532dba98a46a04bee6a858861ab2f5e8b96a81a | [
"MIT"
] | 9 | 2018-12-07T05:16:50.000Z | 2021-12-15T06:49:25.000Z | /*
* fake_tchar.h
*
* Modified from mingw's tchar.h. This file should be used only in systems
* without the real tchar.h. This file maps _t* functions to the normal ones.
*
* This file has no copyright assigned and is placed in the Public Domain.
* This file is a part of the mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER within the package.
*
*/
#ifndef FAKE_TCHAR_H
#define FAKE_TCHAR_H
typedef char TCHAR;
#define _TEOF EOF
#define _TEXT(q) q
#define _T(q) q
/*
* Non-unicode (standard) functions
*/
#define _tprintf printf
#define _ftprintf fprintf
#define _stprintf sprintf
#define _sntprintf snprintf
#define _vtprintf vprintf
#define _vftprintf vfprintf
#define _vstprintf vsprintf
#define _vsntprintf vsnprintf
#define _tscanf scanf
#define _ftscanf fscanf
#define _stscanf sscanf
#define _fgettc fgetc
#define _fgettchar fgetchar
#define _fgetts fgets
#define _fputtc fputc
#define _fputtchar fputchar
#define _fputts fputs
#define _tfdopen fdopen
#define _tfopen fopen
#define _tfreopen freopen
#define _tfsopen fsopen
#define _tgetenv getenv
#define _tputenv putenv
#define _tsearchenv searchenv
#define _tsystem system
#define _tmakepath makepath
#define _tsplitpath splitpath
#define _tfullpath fullpath
#define _gettc getc
#define _getts gets
#define _puttc putc
#define _puttchar putchar
#define _putts puts
#define _ungettc ungetc
#define _tcstod strtod
#define _tcstol strtol
#define _tcstoul strtoul
#define _itot itoa
#define _ltot ltoa
#define _ultot ultoa
#define _ttoi atoi
#define _ttol atol
#define _tcscat strcat
#define _tcschr strchr
#define _tcscmp strcmp
#define _tcscpy strcpy
#define _tcscspn strcspn
#define _tcslen strlen
#define _tcsncat strncat
#define _tcsncmp strncmp
#define _tcsncpy strncpy
#define _tcspbrk strpbrk
#define _tcsrchr strrchr
#define _tcsspn strspn
#define _tcsstr strstr
#define _tcstok strtok
#define _tcsdup strdup
#define _tcsicmp stricmp
#define _tcsnicmp strnicmp
#define _tcsnset strnset
#define _tcsrev strrev
#define _tcsset strset
#define _tcslwr strlwr
#define _tcsupr strupr
#define _tcsxfrm strxfrm
#define _tcscoll strcoll
#define _tcsicoll stricoll
#define _istalpha isalpha
#define _istupper isupper
#define _istlower islower
#define _istdigit isdigit
#define _istxdigit isxdigit
#define _istspace isspace
#define _istpunct ispunct
#define _istalnum isalnum
#define _istprint isprint
#define _istgraph isgraph
#define _istcntrl iscntrl
#define _istascii isascii
#define _totupper toupper
#define _totlower tolower
#define _tasctime asctime
#define _tctime ctime
#define _tstrdate strdate
#define _tstrtime strtime
#define _tutime utime
#define _tcsftime strftime
#define _tchmod chmod
#define _tcreat creat
#define _tfindfirst findfirst
#define _tfindnext findnext
#define _tmktemp mktemp
#define _topen open
#define _taccess access
#define _tremove remove
#define _trename rename
#define _tsopen sopen
#define _tsetlocale setlocale
#define _tunlink unlink
#define _tfinddata_t finddata_t
#define _tchdir chdir
#define _tgetcwd getcwd
#define _tgetdcwd getdcwd
#define _tmkdir mkdir
#define _trmdir rmdir
#define _tstat stat
#define _stat stat // for struct _stat
/* dirent structures and functions */
#define _tdirent dirent
#define _TDIR DIR
#define _topendir opendir
#define _tclosedir closedir
#define _treaddir readdir
#define _trewinddir rewinddir
#define _ttelldir telldir
#define _tseekdir seekdir
#endif /* Not FAKE_TCHAR_H */
| 25.668919 | 77 | 0.740458 |
e1c298ffea7a717e51d5b27569ef893355a9d801 | 3,129 | h | C | ns-3-dev/src/point-to-point/model/ppp-header.h | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 11 | 2015-11-24T11:07:28.000Z | 2021-12-23T04:10:29.000Z | ns-3-dev/src/point-to-point/model/ppp-header.h | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | null | null | null | ns-3-dev/src/point-to-point/model/ppp-header.h | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 6 | 2016-03-01T06:32:21.000Z | 2022-03-24T19:31:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008 University of Washington
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PPP_HEADER_H
#define PPP_HEADER_H
#include "ns3/header.h"
namespace ns3 {
/**
* \ingroup point-to-point
* \brief Packet header for PPP
*
* This class can be used to add a header to PPP packet. Currently we do not
* implement any of the state machine in RFC 1661, we just encapsulate the
* inbound packet send it on. The goal here is not really to implement the
* point-to-point protocol, but to encapsulate our packets in a known protocol
* so packet sniffers can parse them.
*
* if PPP is transmitted over a serial link, it will typically be framed in
* some way derivative of IBM SDLC (HDLC) with all that that entails.
* Thankfully, we don't have to deal with all of that -- we can use our own
* protocol for getting bits across the serial link which we call an ns3
* Packet. What we do have to worry about is being able to capture PPP frames
* which are understandable by Wireshark. All this means is that we need to
* teach the PcapWriter about the appropriate data link type (DLT_PPP = 9),
* and we need to add a PPP header to each packet. Since we are not using
* framed PPP, this just means prepending the sixteen bit PPP protocol number
* to the packet. The ns-3 way to do this is via a class that inherits from
* class Header.
*/
class PppHeader : public Header
{
public:
/**
* \brief Construct a PPP header.
*/
PppHeader ();
/**
* \brief Destroy a PPP header.
*/
virtual ~PppHeader ();
static TypeId GetTypeId (void);
virtual TypeId GetInstanceTypeId (void) const;
virtual void Print (std::ostream &os) const;
virtual void Serialize (Buffer::Iterator start) const;
virtual uint32_t Deserialize (Buffer::Iterator start);
virtual uint32_t GetSerializedSize (void) const;
/**
* \brief Set the protocol type carried by this PPP packet
*
* The type numbers to be used are defined in RFC3818
*
* \param protocol the protocol type being carried
*/
void SetProtocol (uint16_t protocol);
/**
* \brief Get the protocol type carried by this PPP packet
*
* The type numbers to be used are defined in RFC3818
*
* \return the protocol type being carried
*/
uint16_t GetProtocol (void);
private:
/**
* \brief The PPP protocol type of the payload packet
*/
uint16_t m_protocol;
};
} // namespace ns3
#endif /* PPP_HEADER_H */
| 31.606061 | 78 | 0.713327 |
07786d1afebde06538945969daddc15cd194225c | 6,740 | c | C | opt_bst/bst.cpp.pluto.c | piotrbla/transitive-closure-experiments | 0a78c18432f2dc856663278fedf2153b8d47e257 | [
"MIT"
] | null | null | null | opt_bst/bst.cpp.pluto.c | piotrbla/transitive-closure-experiments | 0a78c18432f2dc856663278fedf2153b8d47e257 | [
"MIT"
] | null | null | null | opt_bst/bst.cpp.pluto.c | piotrbla/transitive-closure-experiments | 0a78c18432f2dc856663278fedf2153b8d47e257 | [
"MIT"
] | null | null | null | #include <omp.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define min(x,y) ((x) < (y) ? (x) : (y))
#define max(x,y) ((x) > (y) ? (x) : (y))
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) (((n)<0) ? -((-(n)+(d)-1)/(d)) : (n)/(d))
#define S0(a, i, j, k) c[i][j] = c[i][k] + c[k][j]
#define match(b1, b2) (((b1)+(b2)) == 3 ? 1 : 0)
#define max_score(s1, s2) ((s1 >= s2) ? s1 : s2)
void printMatrix(int**, int, int);
int** allocateMatrix(int);
void deallocateMatrix(int**, int);
void write_results(int , double , char );
void write_results(int , double );
void computeSEQ0(int* p, int n)
{
int** w = allocateMatrix(n + 1);
int i, j, k, m, h, optimal_w;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
w[i][j] = 0;
if (i<n-1)
{
w[i][i+1] = p[i];
}
}
for (i = 0; i < n; i++)
for (j = i+1; j < n; j++)
w[i][j] = 99999;
double start = omp_get_wtime();
int t1, t2, t3, t4, t5, t6;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
if (n >= 3) {
for (t1=0;t1<=floord(44*n-69,475);t1++) {
lbp=max(ceild(19*t1-n+2,19),ceild(19*t1-23,44));
ubp=min(floord(n-1,25),t1);
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(1,19*t1-19*t2);t3<=min(min(n-2,25*t2+23),19*t1-19*t2+18);t3++) {
for (t4=max(25*t2,t3+1);t4<=min(n-1,25*t2+24);t4++) {
for (t6=-t3+t4;t6<=t4;t6++) {
w[(-t3+t4)][(-t3+t4)+t3] = min(w[(-t3+t4)][t6-1] + w[t6+1][(-t3+t4)+t3], w[(-t3+t4)][(-t3+t4)+t3]);;
}
for (t6=-t3+t4;t6<=t4;t6++) {
w[(-t3+t4)][(-t3+t4)+t3] += p[t6];;
}
}
}
}
}
}
double execution_time = omp_get_wtime() - start;
printf("normal: %lf\n", execution_time);
write_results(n, execution_time);
printMatrix(w, n, 0);
deallocateMatrix(w, n + 1);
}
void computeSEQ0Pluto(int* p, int n)
{
int** w = allocateMatrix(n + 1);
int i, j, k, m, h, optimal_w;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
w[i][j] = 0;
if (i<n-1)
{
w[i][i+1] = p[i];
}
}
for (i = 0; i < n; i++)
for (j = i+1; j < n; j++)
w[i][j] = 99999;
double start = omp_get_wtime();
int t1, t2, t3, t4, t5, t6, t7, t8, t9;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
if (n >= 2) {
for (t1=1;t1<=n-1;t1++) {
for (t3=0;t3<=-t1+n-1;t3++) {
for (t5=t3;t5<=t1+t3;t5++) {
optimal_w = w[t3][t5-1] + w[t5+1][t3+t1];;
w[t3][t3+t1] = min(optimal_w, w[t3][t3+t1]);;
}
}
lbp=0;
ubp=floord(-t1+n-1,19);
#pragma omp parallel for private(lbv,ubv,t4,t5,t6,t7,t8,t9)
for (t3=lbp;t3<=ubp;t3++) {
for (t5=ceild(19*t3-24,25);t5<=min(floord(n-1,25),floord(t1+19*t3+18,25));t5++) {
for (t6=max(19*t3,-t1+25*t5);t6<=min(min(19*t3+18,25*t5+24),-t1+n-1);t6++) {
for (t8=max(25*t5,t6);t8<=min(t1+t6,25*t5+24);t8++) {
w[t6][t6+t1] += p[t8];;
}
}
}
}
}
}
double execution_time = omp_get_wtime() - start;
printf("pluto: %lf\n", execution_time);
write_results(n, execution_time);
printMatrix(w, n, 0);
deallocateMatrix(w, n + 1);
}
void computeSEQ1(int* p, int n)
{
int** w = allocateMatrix(n + 1);
int i, j, k, m, h, optimal_w;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
w[i][j] = 0;
if (i<n-1)
{
w[i][i+1] = p[i];
}
}
for (i = 0; i < n; i++)
for (j = i+1; j < n; j++)
w[i][j] = 99999;
double start = omp_get_wtime();
for (j = 1; j < n; j++)
for (i=0; i < n-j; i++){
for (k = i; k <= i+j; k++){
optimal_w = w[i][k-1] + w[k+1][i+j];
if (optimal_w < w[i][i+j]){
w[i][i+j] = optimal_w;
}
}
for (k = i; k <= i+j; w[i][i+j] += p[k++])
;
}
double execution_time = omp_get_wtime() - start;
printf("paralell: %lf\n", execution_time);
write_results(n, execution_time);
printMatrix(w, n, 0);
deallocateMatrix(w, n + 1);
}
void computeSEQ2(int* p, int n)
{
int** w = allocateMatrix(n + 1);
int i, j, k, m, h, optimal_w;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
w[i][j] = 0;
if (i<n-1)
{
w[i][i+1] = p[i];
}
}
for (i = 0; i < n; i++)
for (j = i+1; j < n; j++)
w[i][j] = 99999;
double start = omp_get_wtime();
for (int c0 = floord(-n + 1, 16) + 2; c0 <= floord(n - 3, 16) + 1; c0 += 1) {
#pragma omp parallel for
for (int c1 = -c0 - (n - 16 * c0 + 46) / 32 + 1; c1 <= min(-1, -c0); c1 += 1) {
for (int c4 = -16 * c1 - 15; c4 <= min(min(n - 2, n + 16 * c0 + 16 * c1 - 1), -16 * c1); c4 += 1) {
for (int c5 = max(1, -16 * c0 - 16 * c1); c5 <= min(-16 * c0 - 16 * c1 + 15, n - c4 - 1); c5 += 1) {
for (int c7 = c5; c7 <= c4 + c5; c7 += 1) {
w[c5][c4 + c5] = (((w[c5][c7 - 1] + w[c7 + 1][c4 + c5]) < w[c5][c4 + c5]) ? (w[c5][c7 - 1] + w[c7 + 1][c4 + c5]) : w[c5][c4 + c5]);
}
for (int c7 = c5; c7 <= c4 + c5; c7 += 1) {
w[c5][c4 + c5] += p[c7];
}
}
}
}
if (c0 == 0) {
}
}
double execution_time = omp_get_wtime() - start;
printf("stencil: %lf\n", execution_time);
write_results(n, execution_time);
printMatrix(w, n, 0);
deallocateMatrix(w, n + 1);
}
void printMatrix(int** matrix, int N, int fileno) {
char filename[10];
sprintf(filename, "nontiled%d", fileno);
FILE* f = fopen(filename, "wt");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
{
fprintf(f, "%d ", matrix[i][j]);
//printf("%4d ", matrix[i][j]);
}
fprintf(f, "\n");
// printf("\n");
}
fclose(f);
}
int** allocateMatrix(int N) {
int** t = (int**)malloc(sizeof(int*) * N);
for (int i = 0; i < N; i++) {
t[i] = (int*)malloc(sizeof(int) * N);
}
return t;
}
int* allocateVector(int N) {
int* t = (int*)malloc(sizeof(int) * N);
return t;
}
void deallocateMatrix(int **t, int N) {
for (int i = 0; i < N; i++) {
free(t[i]);
}
free(t);
}
void write_results(int n, double execution_time, char end_char)
{
FILE* f = fopen("results.txt", "at");
fprintf(f, "%d:%lf%c", n, execution_time, end_char);
fclose(f);
}
void write_results(int n, double execution_time)
{
write_results(n, execution_time, ';');
}
int main(void) {//vector
const int ZMAX = 7;
int* seq = allocateVector(ZMAX);
for (int i = 0; i < ZMAX; i++)
seq[i] = i;
int N = ZMAX;
while (N <= ZMAX)
{
computeSEQ0(seq, N);
computeSEQ0Pluto(seq, N);
computeSEQ1(seq, N);
computeSEQ2(seq, N);
N += 10;
}
free(seq);
return 0;
}
| 25.823755 | 143 | 0.474777 |
e0675095d6d431554045a4a41450823358f73305 | 365 | c | C | pycontrol/demo/fibo.c | Velko/8-bit-CPU | 30cab1bd157da01149898607a5c1a15961b56294 | [
"MIT"
] | 7 | 2021-02-22T19:29:35.000Z | 2022-03-27T23:17:04.000Z | pycontrol/demo/fibo.c | Velko/8-bit-CPU | 30cab1bd157da01149898607a5c1a15961b56294 | [
"MIT"
] | 8 | 2021-01-05T19:08:24.000Z | 2021-08-16T20:50:13.000Z | pycontrol/demo/fibo.c | Velko/8-bit-CPU | 30cab1bd157da01149898607a5c1a15961b56294 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdint.h>
/* Reference algorithm for fibo32 */
int main()
{
uint32_t a, b;
a = 0;
b = 1;
printf("%u\n", a);
printf("%u\n", b);
while (1)
{
a += b;
if (a < b) break;
printf("%u\n", a);
b += a;
if (b < a) break;
printf("%u\n", b);
}
return 0;
}
| 11.774194 | 36 | 0.4 |
ef1aea0fbb6aafc001d80cbcaacff29f2d499e6e | 4,092 | c | C | source/foundation/reflect/Method.c | Ken-W-P-Huang/ooc | ffd50877a87bfe622609fd97d3aec837c8eb6dda | [
"Apache-2.0"
] | null | null | null | source/foundation/reflect/Method.c | Ken-W-P-Huang/ooc | ffd50877a87bfe622609fd97d3aec837c8eb6dda | [
"Apache-2.0"
] | null | null | null | source/foundation/reflect/Method.c | Ken-W-P-Huang/ooc | ffd50877a87bfe622609fd97d3aec837c8eb6dda | [
"Apache-2.0"
] | 1 | 2022-03-23T19:14:29.000Z | 2022-03-23T19:14:29.000Z | //
// Created by kenhuang on 2019-10-21.
//
#include "Method.h"
#if (defined(__OVERRIDE__) || defined(__POLYMORPHISM__)) && defined(__REFLECT__)
PRIVATE(Method)
/*属于哪个类*/
const ClassType* clazz;
const String * name;
Function function;
Access* access;
// ClassType** parameterTypes;
ClassType* returnType;
END
/***********************************************************************************************************************
* 私有方法
**********************************************************************************************************************/
static void deinit(Method *self) {
}
/***********************************************************************************************************************
* 公有方法
**********************************************************************************************************************/
Method *Method_init(Method *self,const ClassType *clazz, String *name, Function method) {
if (Object_init((Object*)self)) {
self->p->clazz = clazz;
self->p->function = method;
self->p->name = name;
}
return self;
}
const String * Method_getName(Method *self){
return self->p->name;
}
Function Method_getMethod(Method *self){
return self->p->function;
}
Access* Method_getAccess(Method * self){
return self->p->access;
}
/**
* 不能传递参数
* @param self
* @param object
* @param ...
* @return
*/
//todo 如何将可变参数直接传给function执行。
//https://stackoverflow.com/questions/58441770/how-to-pass-variables-to-a-external-assembly-function
Object* Method_invoke(Method* self,Object* object,...){
long result = self->p->function(object);
Object* o = cast((void*)result,self->p->returnType);
// if (o == NULL) {
// ClassType* clazz = self->p->returnType;
// o = alloc(clazz);
// if(clazz == BoolClass){
// Bool_init(o,(bool)self);
// }else if(clazz == IntegerClass){
// Integer_init(o,(int)self);
// }else if(clazz == ByteClass){
// Byte_init(o,(byte)self);
// }else if(clazz == CharacterClass){
// Character_init(o,(char)self);
// }else if(clazz == DoubleClass){
// Double_init(o,(double)(long)self);
// }else if (clazz == FloatClass){
// Float_init(o,(float)(long)self);
// }else if(clazz == LongClass){
// Long_init(o,(long)self);
// }else if(clazz == PointerClass){
// Pointer_init(o,(void*)self);
// }else if(clazz == ShortClass) {
// Short_init(o, (short) self);
// } else {
//
// o = NULL;
// }
// }
return o;
}
/***********************************************************************************************************************
* 静态方法
**********************************************************************************************************************/
STATIC_INIT(Method)
Class_fillDeclaredFields((ClassType*)MethodClass,
"clazz",PointerClass,AccessClass->READABLE_UNWRITABLE_PRIVATE,
"name",PointerClass,AccessClass->READABLE_UNWRITABLE_PRIVATE,
"function",PointerClass,AccessClass->READABLE_UNWRITABLE_PRIVATE,
"access",CharacterClass,AccessClass->READABLE_UNWRITABLE_PRIVATE,
"returnType",PointerClass,AccessClass->READABLE_UNWRITABLE_PRIVATE,
NULL);
Class_fillDeclaredMethods((ClassType*)MethodClass,
deinit,AccessClass->READABLE_UNWRITABLE_PRIVATE,
Method_init,AccessClass->READABLE_UNWRITABLE_PUBLIC,
Method_getName,AccessClass->READABLE_UNWRITABLE_PUBLIC,
Method_getMethod,AccessClass->READABLE_UNWRITABLE_PUBLIC,
Method_getAccess,AccessClass->READABLE_UNWRITABLE_PUBLIC,
Method_invoke,AccessClass->READABLE_UNWRITABLE_PUBLIC,
NULL);
END
#endif | 39.346154 | 120 | 0.480694 |
d43038978d684eba4f7dafaad928a44d44a48522 | 1,349 | c | C | persistence/es03-files-and-directories/es01-stat.c | meowmeowxw/ostep-exercises | c6dafca9e7fb6040ad00cb39eec813fb4061249d | [
"MIT"
] | 13 | 2021-02-01T13:38:34.000Z | 2021-12-15T22:27:12.000Z | persistence/es03-files-and-directories/es01-stat.c | meowmeowxw/ostep-exercises | c6dafca9e7fb6040ad00cb39eec813fb4061249d | [
"MIT"
] | null | null | null | persistence/es03-files-and-directories/es01-stat.c | meowmeowxw/ostep-exercises | c6dafca9e7fb6040ad00cb39eec813fb4061249d | [
"MIT"
] | 10 | 2020-11-23T22:50:22.000Z | 2022-01-04T11:08:29.000Z | #include "error.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
void print_stat_info(struct stat *info) {
printf("Size: %ld\tBlocks: %ld\tIO Block: %ld\t", info->st_size,
info->st_blocks, info->st_blksize);
switch (info->st_mode & S_IFMT) {
case S_IFBLK:
printf("block device\n");
break;
case S_IFCHR:
printf("character device\n");
break;
case S_IFDIR:
printf("directory\n");
break;
case S_IFIFO:
printf("FIFO/pipe\n");
break;
case S_IFLNK:
printf("symlink\n");
break;
case S_IFREG:
printf("regular file\n");
break;
case S_IFSOCK:
printf("socket\n");
break;
default:
printf("unknown?\n");
break;
}
printf("Device: %ld\tInode: %ld\tLinks:%ld\n", info->st_dev, info->st_ino,
info->st_nlink);
}
int main(int argc, char **argv) {
if (argc == 1) {
fprintf(stderr, "usage: ./es01-stat.exe <file>\n");
exit(1);
}
int i;
struct stat info;
for (i = 1; i < argc; i++) {
if (stat(argv[1], &info) != 0)
print_error();
printf("File: %s\n", argv[1]);
print_stat_info(&info);
}
return 0;
}
| 23.258621 | 78 | 0.533729 |
c30686a65232dd486e16b52c0690359284caed06 | 1,037 | h | C | Src/GUI/EditList/AvailableEditWindows/AdjustRGBWindow/AdjustRGBWindow.h | roseaw/PhoediX | 8c240ff0454531d0fadab34764179f0ea1c48152 | [
"MIT"
] | null | null | null | Src/GUI/EditList/AvailableEditWindows/AdjustRGBWindow/AdjustRGBWindow.h | roseaw/PhoediX | 8c240ff0454531d0fadab34764179f0ea1c48152 | [
"MIT"
] | null | null | null | Src/GUI/EditList/AvailableEditWindows/AdjustRGBWindow/AdjustRGBWindow.h | roseaw/PhoediX | 8c240ff0454531d0fadab34764179f0ea1c48152 | [
"MIT"
] | 1 | 2018-10-20T20:44:12.000Z | 2018-10-20T20:44:12.000Z | // Copyright 2018 Jacob Chesley.
// See LICENSE.TXT in root of project for license information.
#ifndef Adjust_RGB_WINDOW_H
#define Adjust_RGB_WINDOW_H
#include "GUI/EditList/EditWindow/EditWindow.h"
#include "GUI/Controls/DoubleSlider/DoubleSlider.h"
#include "GUI/Colors/Colors.h"
#include "Processing/Processor/Processor.h"
#include "Debugging/MemoryLeakCheck.h"
class AdjustRGBWindow : public EditWindow {
public:
AdjustRGBWindow(wxWindow * parent, wxString editName, Processor * processor);
void SetParamsAndFlags(ProcessorEdit * edit);
ProcessorEdit * GetParamsAndFlags();
bool CheckCopiedParamsAndFlags();
private:
wxWindow * parWindow;
wxBoxSizer * mainSizer;
wxFlexGridSizer * gridSizer;
wxStaticText * editLabel;
wxStaticText * allBrightLabel;
wxStaticText * redBrightLabel;
wxStaticText * greenBrightLabel;
wxStaticText * blueBrightLabel;
DoubleSlider * allBrightSlider;
DoubleSlider * redBrightSlider;
DoubleSlider * greenBrightSlider;
DoubleSlider * blueBrightSlider;
Processor * proc;
};
#endif
| 24.116279 | 78 | 0.793635 |
988bbd775e154c2137920ae7bad1182f54b3f7cb | 2,177 | c | C | 001-050/problem-020.c | exTerEX/project-euler | efdad21f8ebeab240e16a05f850dfc0620b22051 | [
"Unlicense"
] | null | null | null | 001-050/problem-020.c | exTerEX/project-euler | efdad21f8ebeab240e16a05f850dfc0620b22051 | [
"Unlicense"
] | null | null | null | 001-050/problem-020.c | exTerEX/project-euler | efdad21f8ebeab240e16a05f850dfc0620b22051 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
typedef struct big_int {
char data;
struct big_int* next;
struct big_int* prev;
} big_int_t;
big_int_t* add_digit(big_int_t*, char);
void remove_digits(big_int_t*, int);
int main() {
u_int32_t n = 100;
big_int_t* ptr = add_digit(NULL, 1);
const big_int_t* ptr0 = ptr;
u_int64_t sum_digits = 0;
for (u_int32_t index = 1; index <= n; index++) {
int carry = 0;
ptr = (big_int_t*)ptr0;
while (ptr) {
u_int32_t temp = ptr->data * index + carry;
if (temp >= 10) {
carry = div(temp, 10).quot;
temp = div(temp, 10).rem;
}
else {
carry = 0;
}
if (carry > 0 && ptr->next == NULL) {
add_digit(ptr, 0);
}
ptr->data = temp;
if (index == n) {
sum_digits += temp;
}
if (ptr->next) {
ptr = ptr->next;
}
else {
break;
}
}
}
printf("%lu\n", sum_digits);
remove_digits((big_int_t*)ptr0, -1);
return 0;
}
big_int_t* add_digit(big_int_t* digit, char value) {
if (digit == NULL) {
digit = (big_int_t*)malloc(sizeof(big_int_t));
if (!digit) {
perror("Unable to allocate memory!");
return NULL;
}
digit->data = value;
digit->next = NULL;
digit->prev = NULL;
return digit;
}
if (digit->next) {
digit->next->data = value;
return digit->next;
}
digit->next = (big_int_t*)malloc(sizeof(big_int_t));
if (digit->next == NULL) {
perror("Unable to allocate memory!");
return NULL;
}
digit->next->data = value;
digit->next->next = NULL;
digit->next->prev = digit;
return digit->next;
}
void remove_digits(big_int_t* digit, int n) {
if (digit == NULL) {
return;
}
if (digit->next == NULL) {
free(digit);
digit = NULL;
return;
}
if (n > 0) {
return;
}
return;
}
| 19.265487 | 56 | 0.472669 |
816273e6efe0bf5ba81b5eb04f07863c04c75657 | 125,839 | h | C | ttk/core/base/discreteGradient/DiscreteGradient_Template.h | julesvidal/wasserstein-pd-barycenter | 1f62a5e1c40700030357b2bfb9a2f86fe4736861 | [
"BSD-Source-Code"
] | 1 | 2019-09-10T12:36:52.000Z | 2019-09-10T12:36:52.000Z | ttk/core/base/discreteGradient/DiscreteGradient_Template.h | julesvidal/wasserstein-pd-barycenter | 1f62a5e1c40700030357b2bfb9a2f86fe4736861 | [
"BSD-Source-Code"
] | null | null | null | ttk/core/base/discreteGradient/DiscreteGradient_Template.h | julesvidal/wasserstein-pd-barycenter | 1f62a5e1c40700030357b2bfb9a2f86fe4736861 | [
"BSD-Source-Code"
] | 1 | 2021-04-28T12:36:58.000Z | 2021-04-28T12:36:58.000Z | /// \ingroup baseCode
/// \class ttk::DiscreteGradient
/// \author Guillaume Favelier <guillaume.favelier@lip6.fr>
/// \author Julien Tierny <julien.tierny@lip6.fr>
/// \date November 2016.
///
/// \brief TTK %discreteGradient processing package.
///
/// %DiscreteGradient is a TTK processing package that handles discrete gradient
/// (in the sense of Discrete Morse Theory).
///
/// \sa ttk::Triangulation
#ifndef _DISCRETEGRADIENT_TPL_H
#define _DISCRETEGRADIENT_TPL_H
#include<DiscreteGradient.h>
template <typename dataType>
dataType DiscreteGradient::scalarMax(const Cell& cell, const dataType*
const scalars) const{
dataType scalar{};
if(dimensionality_==2){
switch(cell.dim_){
case 0:
scalar=scalars[cell.id_];
break;
case 1:
for(int i=0; i<2; ++i){
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar<vertexScalar)
scalar=vertexScalar;
}
break;
case 2:
for(int i=0; i<3; ++i){
SimplexId vertexId;
inputTriangulation_->getCellVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar<vertexScalar)
scalar=vertexScalar;
}
break;
}
}
else if(dimensionality_==3){
switch(cell.dim_){
case 0:
scalar=scalars[cell.id_];
break;
case 1:
for(int i=0; i<2; ++i){
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar<vertexScalar)
scalar=vertexScalar;
}
break;
case 2:
for(int i=0; i<3; ++i){
SimplexId vertexId;
inputTriangulation_->getTriangleVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar<vertexScalar)
scalar=vertexScalar;
}
break;
case 3:
for(int i=0; i<4; ++i){
SimplexId vertexId;
inputTriangulation_->getCellVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar<vertexScalar)
scalar=vertexScalar;
}
break;
}
}
return scalar;
}
template <typename dataType>
dataType DiscreteGradient::scalarMin(const Cell& cell, const dataType*
const scalars) const{
dataType scalar{};
if(dimensionality_==2){
switch(cell.dim_){
case 0:
scalar=scalars[cell.id_];
break;
case 1:
for(int i=0; i<2; ++i){
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar>vertexScalar)
scalar=vertexScalar;
}
break;
case 2:
for(int i=0; i<3; ++i){
SimplexId vertexId;
inputTriangulation_->getCellVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar>vertexScalar)
scalar=vertexScalar;
}
break;
}
}
else if(dimensionality_==3){
switch(cell.dim_){
case 0:
scalar=scalars[cell.id_];
break;
case 1:
for(int i=0; i<2; ++i){
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar>vertexScalar)
scalar=vertexScalar;
}
break;
case 2:
for(int i=0; i<3; ++i){
SimplexId vertexId;
inputTriangulation_->getTriangleVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar>vertexScalar)
scalar=vertexScalar;
}
break;
case 3:
for(int i=0; i<4; ++i){
SimplexId vertexId;
inputTriangulation_->getCellVertex(cell.id_,i,vertexId);
const dataType vertexScalar=scalars[vertexId];
if(!i or scalar>vertexScalar)
scalar=vertexScalar;
}
break;
}
}
return scalar;
}
template <typename dataType>
dataType DiscreteGradient::getPersistence(const Cell& up, const Cell& down,
const dataType* const scalars) const{
return scalarMax<dataType>(up,scalars)-scalarMin<dataType>(down,scalars);
}
template <typename dataType, typename idType>
int DiscreteGradient::assignGradient(const int alphaDim,
const dataType* const scalars,
const idType* const offsets,
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
std::vector<std::vector<char>>& gradient) const{
#else
std::vector<std::vector<SimplexId>>& gradient) const{
#endif
const int betaDim=alphaDim+1;
const SimplexId alphaNumber=gradient[alphaDim].size();
const auto sosLowerThan=[&scalars,&offsets](const SimplexId a,const SimplexId b){
if(scalars[a] != scalars[b]) return scalars[a]<scalars[b];
else return offsets[a]<offsets[b];
};
if(dimensionality_==2){
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId alpha=0; alpha<alphaNumber; ++alpha){
if (alphaDim == 0) {
SimplexId minEdgeId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minEdgeLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId edgeNumber = inputTriangulation_->getVertexEdgeNumber(alpha);
for (SimplexId k=0; k<edgeNumber; ++k) {
SimplexId edgeId;
inputTriangulation_->getVertexEdge(alpha, k, edgeId);
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(edgeId, 0, vertexId);
if(vertexId == alpha)
inputTriangulation_->getEdgeVertex(edgeId, 1, vertexId);
if(sosLowerThan(vertexId, alpha)){
if(minVertexId==-1){
minEdgeId = edgeId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minEdgeLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minEdgeId = edgeId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minEdgeLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
if (minEdgeId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minEdgeLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<2; ++k){
SimplexId tmp;
inputTriangulation_->getEdgeVertex(minEdgeId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minEdgeId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minEdgeId;
gradient[betaDim][minEdgeId] = alpha;
#endif
}
} else if (alphaDim == 1) {
SimplexId v0;
SimplexId v1;
inputTriangulation_->getEdgeVertex(alpha, 0, v0);
inputTriangulation_->getEdgeVertex(alpha, 1, v1);
SimplexId minStarId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minStarLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId starNumber = inputTriangulation_->getEdgeStarNumber(alpha);
for (SimplexId k = 0; k < starNumber; ++k) {
SimplexId starId;
inputTriangulation_->getEdgeStar(alpha, k, starId);
SimplexId vertexId;
inputTriangulation_->getCellVertex(starId, 0, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getCellVertex(starId, 1, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getCellVertex(starId, 2, vertexId);
if (sosLowerThan(vertexId,v0) and sosLowerThan(vertexId,v1)){
if (minVertexId == -1) {
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
if (minStarId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minStarLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<3; ++k){
SimplexId tmp;
inputTriangulation_->getCellEdge(minStarId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minStarId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minStarId;
gradient[betaDim][minStarId] = alpha;
#endif
}
}
}
}
else if(dimensionality_==3) {
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for (SimplexId alpha = 0; alpha < alphaNumber; ++alpha) {
if (alphaDim == 0) {
SimplexId minEdgeId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minEdgeLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId edgeNumber = inputTriangulation_->getVertexEdgeNumber(alpha);
for (SimplexId k = 0; k < edgeNumber; ++k) {
SimplexId edgeId;
inputTriangulation_->getVertexEdge(alpha, k, edgeId);
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(edgeId, 0, vertexId);
if(vertexId == alpha)
inputTriangulation_->getEdgeVertex(edgeId, 1, vertexId);
if (sosLowerThan(vertexId, alpha)) {
if(minVertexId==-1){
minEdgeId = edgeId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minEdgeLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minEdgeId = edgeId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minEdgeLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
if (minEdgeId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minEdgeLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<2; ++k){
SimplexId tmp;
inputTriangulation_->getEdgeVertex(minEdgeId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minEdgeId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minEdgeId;
gradient[betaDim][minEdgeId] = alpha;
#endif
}
} else if (alphaDim == 1) {
SimplexId v0;
SimplexId v1;
inputTriangulation_->getEdgeVertex(alpha, 0, v0);
inputTriangulation_->getEdgeVertex(alpha, 1, v1);
SimplexId minTriangleId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minTriangleLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId triangleNumber = inputTriangulation_->getEdgeTriangleNumber(alpha);
for (SimplexId k = 0; k < triangleNumber; ++k) {
SimplexId starId;
inputTriangulation_->getEdgeTriangle(alpha, k, starId);
SimplexId vertexId;
inputTriangulation_->getTriangleVertex(starId, 0, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getTriangleVertex(starId, 1, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getTriangleVertex(starId, 2, vertexId);
if (sosLowerThan(vertexId,v0) and
sosLowerThan(vertexId,v1)) {
if (minVertexId == -1) {
minTriangleId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minTriangleLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minTriangleId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minTriangleLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
if (minTriangleId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minTriangleLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<3; ++k){
SimplexId tmp;
inputTriangulation_->getTriangleEdge(minTriangleId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minTriangleId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minTriangleId;
gradient[betaDim][minTriangleId] = alpha;
#endif
}
} else if (alphaDim == 2) {
SimplexId v0;
SimplexId v1;
SimplexId v2;
inputTriangulation_->getTriangleVertex(alpha, 0, v0);
inputTriangulation_->getTriangleVertex(alpha, 1, v1);
inputTriangulation_->getTriangleVertex(alpha, 2, v2);
SimplexId minStarId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minStarLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId starNumber = inputTriangulation_->getTriangleStarNumber(alpha);
for (SimplexId k = 0; k < starNumber; ++k) {
SimplexId starId;
inputTriangulation_->getTriangleStar(alpha, k, starId);
SimplexId vertexId;
inputTriangulation_->getCellVertex(starId, 0, vertexId);
if (vertexId == v0 or vertexId == v1 or vertexId == v2)
inputTriangulation_->getCellVertex(starId, 1, vertexId);
if (vertexId == v0 or vertexId == v1 or vertexId == v2)
inputTriangulation_->getCellVertex(starId, 2, vertexId);
if (vertexId == v0 or vertexId == v1 or vertexId == v2)
inputTriangulation_->getCellVertex(starId, 3, vertexId);
if (sosLowerThan(vertexId,v0) and
sosLowerThan(vertexId,v1) and
sosLowerThan(vertexId,v2)) {
if (minVertexId == -1) {
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
if (minStarId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minStarLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<4; ++k){
SimplexId tmp;
inputTriangulation_->getCellTriangle(minStarId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minStarId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minStarId;
gradient[betaDim][minStarId] = alpha;
#endif
}
}
}
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::assignGradient2(const int alphaDim,
const dataType* const scalars,
const idType* const offsets,
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
std::vector<std::vector<char>>& gradient) const{
#else
std::vector<std::vector<SimplexId>>& gradient) const{
#endif
if(alphaDim>0){
const int betaDim=alphaDim+1;
const SimplexId alphaNumber=gradient[alphaDim].size();
const auto sosLowerThan=[&scalars,&offsets](const SimplexId a, const SimplexId b){
if(scalars[a] != scalars[b]) return scalars[a]<scalars[b];
else return offsets[a]<offsets[b];
};
if(dimensionality_==2){
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId alpha=0; alpha<alphaNumber; ++alpha){
if(!isCellCritical(alphaDim,alpha)) continue;
SimplexId v0;
SimplexId v1;
inputTriangulation_->getEdgeVertex(alpha, 0, v0);
inputTriangulation_->getEdgeVertex(alpha, 1, v1);
SimplexId minStarId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minStarLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId starNumber=inputTriangulation_->getEdgeStarNumber(alpha);
for(SimplexId k=0; k<starNumber; ++k){
SimplexId starId;
inputTriangulation_->getEdgeStar(alpha,k,starId); break;
if(isCellCritical(betaDim,starId)){
SimplexId vertexId;
inputTriangulation_->getCellVertex(starId, 0, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getCellVertex(starId, 1, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getCellVertex(starId, 2, vertexId);
if((sosLowerThan(vertexId,v0) and sosLowerThan(v1, vertexId))
or
(sosLowerThan(vertexId,v1) and sosLowerThan(v0, vertexId))){
if (minVertexId == -1) {
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
}
if (minStarId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minStarLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<3; ++k){
SimplexId tmp;
inputTriangulation_->getCellEdge(minStarId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minStarId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minStarId;
gradient[betaDim][minStarId] = alpha;
#endif
}
}
}
else if(dimensionality_==3){
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId alpha=0; alpha<alphaNumber; ++alpha){
if(!isCellCritical(alphaDim,alpha)) continue;
if(alphaDim==1){
SimplexId v0;
SimplexId v1;
inputTriangulation_->getEdgeVertex(alpha, 0, v0);
inputTriangulation_->getEdgeVertex(alpha, 1, v1);
SimplexId minTriangleId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minTriangleLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId triangleNumber=inputTriangulation_->getEdgeTriangleNumber(alpha);
for(SimplexId k=0; k<triangleNumber; ++k){
SimplexId triangleId;
inputTriangulation_->getEdgeTriangle(alpha,k,triangleId);
if(isCellCritical(betaDim,triangleId)){
SimplexId vertexId;
inputTriangulation_->getTriangleVertex(triangleId, 0, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getTriangleVertex(triangleId, 1, vertexId);
if(vertexId == v0 or vertexId == v1)
inputTriangulation_->getTriangleVertex(triangleId, 2, vertexId);
if((sosLowerThan(vertexId,v0) and sosLowerThan(v1, vertexId))
or
(sosLowerThan(vertexId,v1) and sosLowerThan(v0, vertexId))){
if (minVertexId == -1) {
minTriangleId = triangleId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minTriangleLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minTriangleId = triangleId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minTriangleLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
}
if (minTriangleId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minTriangleLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<3; ++k){
SimplexId tmp;
inputTriangulation_->getTriangleEdge(minTriangleId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minTriangleId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minTriangleId;
gradient[betaDim][minTriangleId] = alpha;
#endif
}
}
else if(alphaDim==2){
SimplexId v0;
SimplexId v1;
SimplexId v2;
inputTriangulation_->getTriangleVertex(alpha, 0, v0);
inputTriangulation_->getTriangleVertex(alpha, 1, v1);
inputTriangulation_->getTriangleVertex(alpha, 2, v2);
SimplexId vb{-1};
if((sosLowerThan(v1, v0) and sosLowerThan(v0, v2))
or
(sosLowerThan(v2, v0) and sosLowerThan(v0, v1)))
vb=v0;
else if((sosLowerThan(v0, v1) and sosLowerThan(v1, v2))
or
(sosLowerThan(v2, v1) and sosLowerThan(v1, v0)))
vb=v1;
else if((sosLowerThan(v1, v2) and sosLowerThan(v2, v0))
or
(sosLowerThan(v0, v2) and sosLowerThan(v2, v1)))
vb=v2;
SimplexId minStarId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minStarLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId starNumber=inputTriangulation_->getTriangleStarNumber(alpha);
for(SimplexId k=0; k<starNumber; ++k){
SimplexId starId;
inputTriangulation_->getTriangleStar(alpha, k, starId);
if(isCellCritical(betaDim, starId)){
SimplexId vertexId;
inputTriangulation_->getCellVertex(starId, 0, vertexId);
if((vertexId == v0) or (vertexId == v1) or (vertexId == v2))
inputTriangulation_->getCellVertex(starId, 1, vertexId);
if((vertexId == v0) or (vertexId == v1) or (vertexId == v2))
inputTriangulation_->getCellVertex(starId, 2, vertexId);
if((vertexId == v0) or (vertexId == v1) or (vertexId == v2))
inputTriangulation_->getCellVertex(starId, 3, vertexId);
if(sosLowerThan(vertexId, vb)){
if (minVertexId == -1) {
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
}
if (minStarId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minStarLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<4; ++k){
SimplexId tmp;
inputTriangulation_->getCellTriangle(minStarId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minStarId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minStarId;
gradient[betaDim][minStarId] = alpha;
#endif
}
}
}
}
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::assignGradient3(const int alphaDim,
const dataType* const scalars,
const idType* const offsets,
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
std::vector<std::vector<char>>& gradient) const{
#else
std::vector<std::vector<SimplexId>>& gradient) const{
#endif
if(alphaDim>0){
const int betaDim=alphaDim+1;
const SimplexId alphaNumber=gradient[alphaDim].size();
const auto sosLowerThan=[&scalars,&offsets](const SimplexId a, const SimplexId b){
if(scalars[a] != scalars[b]) return scalars[a]<scalars[b];
else return offsets[a]<offsets[b];
};
if(dimensionality_==3){
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId alpha=0; alpha<alphaNumber; ++alpha){
if(!isCellCritical(alphaDim,alpha)) continue;
SimplexId v0;
SimplexId v1;
SimplexId v2;
inputTriangulation_->getTriangleVertex(alpha, 0, v0);
inputTriangulation_->getTriangleVertex(alpha, 1, v1);
inputTriangulation_->getTriangleVertex(alpha, 2, v2);
SimplexId vmax=-1;
if(sosLowerThan(v1, v0) and sosLowerThan(v2, v0))
vmax=v0;
else if(sosLowerThan(v0, v1) and sosLowerThan(v2, v1))
vmax=v1;
else if(sosLowerThan(v0, v2) and sosLowerThan(v1, v2))
vmax=v2;
SimplexId minStarId{-1};
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
char minStarLocalId{-1};
#endif
SimplexId minVertexId{-1};
const SimplexId starNumber=inputTriangulation_->getTriangleStarNumber(alpha);
for(SimplexId k=0; k<starNumber; ++k){
SimplexId starId;
inputTriangulation_->getTriangleStar(alpha, k, starId);
if(isCellCritical(betaDim,starId)){
SimplexId vertexId;
inputTriangulation_->getCellVertex(starId, 0, vertexId);
if((vertexId == v0) or (vertexId == v1) or (vertexId == v2))
inputTriangulation_->getCellVertex(starId, 1, vertexId);
if((vertexId == v0) or (vertexId == v1) or (vertexId == v2))
inputTriangulation_->getCellVertex(starId, 2, vertexId);
if((vertexId == v0) or (vertexId == v1) or (vertexId == v2))
inputTriangulation_->getCellVertex(starId, 3, vertexId);
if(sosLowerThan(vertexId,vmax)) {
if (minVertexId == -1) {
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
else if(sosLowerThan(vertexId,minVertexId)){
minStarId = starId;
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
minStarLocalId = k;
#endif
minVertexId = vertexId;
}
}
}
}
if (minStarId != -1) {
#ifdef TTK_ENABLE_DCG_OPTIMIZE_MEMORY
gradient[alphaDim][alpha] = minStarLocalId;
char minAlphaLocalId{-1};
for(SimplexId k=0; k<4; ++k){
SimplexId tmp;
inputTriangulation_->getCellTriangle(minStarId, k, tmp);
if(tmp == alpha){
minAlphaLocalId = k;
break;
}
}
gradient[betaDim][minStarId] = minAlphaLocalId;
#else
gradient[alphaDim][alpha] = minStarId;
gradient[betaDim][minStarId] = alpha;
#endif
}
}
}
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::buildGradient(){
Timer t;
const idType* const offsets=static_cast<idType*>(inputOffsets_);
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const int numberOfDimensions=getNumberOfDimensions();
// init number of cells by dimension
std::vector<SimplexId> numberOfCells(numberOfDimensions);
for(int i=0; i<numberOfDimensions; ++i)
numberOfCells[i]=getNumberOfCells(i);
dmtMax2PL_.clear();
dmt1Saddle2PL_.clear();
dmt2Saddle2PL_.clear();
gradient_.clear();
gradient_.resize(dimensionality_);
for(int i=0; i<dimensionality_; ++i){
// init gradient memory
gradient_[i].resize(numberOfDimensions);
gradient_[i][i].resize(numberOfCells[i], -1);
gradient_[i][i+1].resize(numberOfCells[i+1], -1);
// compute gradient pairs
assignGradient<dataType,idType>(i, scalars, offsets, gradient_[i]);
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Data-set: "
<< numberOfVertices_ << " v., "
<< inputTriangulation_->getNumberOfEdges() << " e.";
if(inputTriangulation_->getDimensionality() == 3){
msg << ", " << inputTriangulation_->getNumberOfTriangles()
<< " t., " << inputTriangulation_->getNumberOfCells()
<< " T." << std::endl;
}
else if(inputTriangulation_->getDimensionality() == 2){
msg << ", " << inputTriangulation_->getNumberOfCells()
<< " t." << std::endl;
}
msg << "[DiscreteGradient] Processed in "
<< t.getElapsedTime() << " s. (" << threadNumber_
<< " thread(s))."
<< std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::buildGradient2(){
Timer t;
const idType* const offsets=static_cast<idType*>(inputOffsets_);
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
for(int i=1; i<dimensionality_; ++i)
assignGradient2<dataType,idType>(i, scalars, offsets, gradient_[i]);
{
std::stringstream msg;
msg << "[DiscreteGradient] Data-set (" << numberOfVertices_
<< " points) post-processed in "
<< t.getElapsedTime() << " s. (" << threadNumber_
<< " thread(s))."
<< std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::buildGradient3(){
Timer t;
const idType* const offsets=static_cast<idType*>(inputOffsets_);
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
for(int i=2; i<dimensionality_; ++i)
assignGradient3<dataType,idType>(i, scalars, offsets, gradient_[i]);
{
std::stringstream msg;
msg << "[DiscreteGradient] Data-set (" << numberOfVertices_
<< " points) post-processed in "
<< t.getElapsedTime() << " s. (" << threadNumber_
<< " thread(s))."
<< std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::setCriticalPoints(const std::vector<Cell>&
criticalPoints) const{
#ifndef TTK_ENABLE_KAMIKAZE
if(!outputCriticalPoints_numberOfPoints_){
std::cerr << "[DiscreteGradient] critical points' pointer to numberOfPoints is null." << std::endl;
return -1;
}
if(!outputCriticalPoints_points_){
std::cerr << "[DiscreteGradient] critical points' pointer to points is null." << std::endl;
return -1;
}
if(!inputScalarField_){
std::cerr << "[DiscreteGradient] critical points' pointer to the input scalar field is null." << std::endl;
return -1;
}
#endif
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const idType* const offsets=static_cast<idType*>(inputOffsets_);
std::vector<dataType>* outputCriticalPoints_points_cellScalars=
static_cast<std::vector<dataType>*>(outputCriticalPoints_points_cellScalars_);
const auto sosGreaterThan=[&scalars,&offsets](const SimplexId a, const SimplexId b){
if(scalars[a] != scalars[b]) return scalars[a]>scalars[b];
else return offsets[a]>offsets[b];
};
(*outputCriticalPoints_numberOfPoints_)=0;
const int numberOfDimensions=getNumberOfDimensions();
std::vector<SimplexId> numberOfCriticalPointsByDimension(numberOfDimensions,0);
// for all critical cells
const SimplexId numberOfCriticalPoints=criticalPoints.size();
for(SimplexId i=0; i<numberOfCriticalPoints; ++i){
const Cell& cell=criticalPoints[i];
const int cellDim=cell.dim_;
const SimplexId cellId=cell.id_;
numberOfCriticalPointsByDimension[cellDim]++;
float incenter[3];
getCellIncenter(cell, incenter);
const dataType scalar=scalarMax<dataType>(cell, scalars);
const char isOnBoundary=isBoundary(cell);
outputCriticalPoints_points_->push_back(incenter[0]);
outputCriticalPoints_points_->push_back(incenter[1]);
outputCriticalPoints_points_->push_back(incenter[2]);
if(outputCriticalPoints_points_cellDimensions_)
outputCriticalPoints_points_cellDimensions_->push_back(cellDim);
if(outputCriticalPoints_points_cellIds_)
outputCriticalPoints_points_cellIds_->push_back(cellId);
if(outputCriticalPoints_points_cellScalars)
outputCriticalPoints_points_cellScalars->push_back(scalar);
if(outputCriticalPoints_points_isOnBoundary_)
outputCriticalPoints_points_isOnBoundary_->push_back(isOnBoundary);
if(outputCriticalPoints_points_PLVertexIdentifiers_){
SimplexId vertexId=-1;
if(dmtMax2PL_.size()){
if(cellDim==0)
vertexId=cellId;
else if(cellDim==dimensionality_)
vertexId=dmtMax2PL_[cellId];
}
if(dmt1Saddle2PL_.size() and cellDim==1){
vertexId=dmt1Saddle2PL_[cellId];
if(vertexId==-1){
SimplexId v0;
SimplexId v1;
inputTriangulation_->getEdgeVertex(cellId, 0, v0);
inputTriangulation_->getEdgeVertex(cellId, 1, v1);
if(sosGreaterThan(v0,v1))
vertexId=v0;
else
vertexId=v1;
}
}
if(dmt2Saddle2PL_.size() and cellDim==2){
vertexId=dmt2Saddle2PL_[cellId];
if(vertexId==-1){
SimplexId v0;
SimplexId v1;
SimplexId v2;
if(dimensionality_==2){
inputTriangulation_->getCellVertex(cellId, 0, v0);
inputTriangulation_->getCellVertex(cellId, 1, v1);
inputTriangulation_->getCellVertex(cellId, 2, v2);
}
else if(dimensionality_==3){
inputTriangulation_->getTriangleVertex(cellId, 0, v0);
inputTriangulation_->getTriangleVertex(cellId, 1, v1);
inputTriangulation_->getTriangleVertex(cellId, 2, v2);
}
if(sosGreaterThan(v0,v1) and sosGreaterThan(v0,v2))
vertexId=v0;
else if(sosGreaterThan(v1,v0) and sosGreaterThan(v1,v2))
vertexId=v1;
else
vertexId=v2;
}
}
outputCriticalPoints_points_PLVertexIdentifiers_->push_back(vertexId);
}
(*outputCriticalPoints_numberOfPoints_)++;
}
{
std::stringstream msg;
for(int i=0; i<numberOfDimensions; ++i)
msg << "[DiscreteGradient] "
<< numberOfCriticalPointsByDimension[i] << " " << i << "-cell(s)."
<< std::endl;
dMsg(std::cout, msg.str(), infoMsg);
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::setCriticalPoints() const{
std::vector<Cell> criticalPoints;
getCriticalPoints(criticalPoints);
setCriticalPoints<dataType,idType>(criticalPoints);
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::setAugmentedCriticalPoints(const std::vector<Cell>& criticalPoints,
std::vector<SimplexId>& maxSeeds,
SimplexId* ascendingManifold,
SimplexId* descendingManifold) const{
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const idType* const offsets=static_cast<idType*>(inputOffsets_);
std::vector<dataType>* outputCriticalPoints_points_cellScalars=
static_cast<std::vector<dataType>*>(outputCriticalPoints_points_cellScalars_);
(*outputCriticalPoints_numberOfPoints_)=0;
const auto sosGreaterThan=[&scalars,&offsets](const SimplexId a, const SimplexId b){
if(scalars[a] != scalars[b]) return scalars[a]>scalars[b];
else return offsets[a]>offsets[b];
};
const int numberOfDimensions=getNumberOfDimensions();
std::vector<SimplexId> numberOfCriticalPointsByDimension(numberOfDimensions,0);
// for all critical cells
const SimplexId numberOfCriticalPoints=criticalPoints.size();
for(SimplexId i=0; i<numberOfCriticalPoints; ++i){
const Cell& cell=criticalPoints[i];
const int cellDim=cell.dim_;
const SimplexId cellId=cell.id_;
numberOfCriticalPointsByDimension[cellDim]++;
float incenter[3];
getCellIncenter(cell, incenter);
const dataType scalar=scalarMax<dataType>(cell, scalars);
const char isOnBoundary=isBoundary(cell);
outputCriticalPoints_points_->push_back(incenter[0]);
outputCriticalPoints_points_->push_back(incenter[1]);
outputCriticalPoints_points_->push_back(incenter[2]);
if(outputCriticalPoints_points_cellDimensions_)
outputCriticalPoints_points_cellDimensions_->push_back(cellDim);
if(outputCriticalPoints_points_cellIds_)
outputCriticalPoints_points_cellIds_->push_back(cellId);
if(outputCriticalPoints_points_cellScalars)
outputCriticalPoints_points_cellScalars->push_back(scalar);
if(outputCriticalPoints_points_isOnBoundary_)
outputCriticalPoints_points_isOnBoundary_->push_back(isOnBoundary);
if(outputCriticalPoints_points_PLVertexIdentifiers_){
SimplexId vertexId=-1;
if(dmtMax2PL_.size()){
if(cellDim==0)
vertexId=cellId;
else if(cellDim==dimensionality_)
vertexId=dmtMax2PL_[cellId];
}
if(dmt1Saddle2PL_.size() and cellDim==1){
vertexId=dmt1Saddle2PL_[cellId];
if(vertexId==-1){
SimplexId v0;
SimplexId v1;
inputTriangulation_->getEdgeVertex(cellId, 0, v0);
inputTriangulation_->getEdgeVertex(cellId, 1, v1);
if(sosGreaterThan(v0,v1))
vertexId=v0;
else
vertexId=v1;
}
}
if(dmt2Saddle2PL_.size() and cellDim==2){
vertexId=dmt2Saddle2PL_[cellId];
if(vertexId==-1){
SimplexId v0;
SimplexId v1;
SimplexId v2;
if(dimensionality_==2){
inputTriangulation_->getCellVertex(cellId, 0, v0);
inputTriangulation_->getCellVertex(cellId, 1, v1);
inputTriangulation_->getCellVertex(cellId, 2, v2);
}
else if(dimensionality_==3){
inputTriangulation_->getTriangleVertex(cellId, 0, v0);
inputTriangulation_->getTriangleVertex(cellId, 1, v1);
inputTriangulation_->getTriangleVertex(cellId, 2, v2);
}
if(sosGreaterThan(v0,v1) and sosGreaterThan(v0,v2))
vertexId=v0;
else if(sosGreaterThan(v1,v0) and sosGreaterThan(v1,v2))
vertexId=v1;
else
vertexId=v2;
}
}
outputCriticalPoints_points_PLVertexIdentifiers_->push_back(vertexId);
}
if(outputCriticalPoints_points_manifoldSize_){
SimplexId manifoldSize=0;
if(cellDim==0){
const SimplexId seedId=descendingManifold[cellId];
manifoldSize=std::count(descendingManifold,
descendingManifold+numberOfVertices_, seedId);
}
else if(cellDim==dimensionality_){
auto ite=std::find(maxSeeds.begin(), maxSeeds.end(), cellId);
if(ite!=maxSeeds.end()){
const SimplexId seedId=std::distance(maxSeeds.begin(), ite);
manifoldSize=std::count(ascendingManifold,
ascendingManifold+numberOfVertices_, seedId);
}
}
outputCriticalPoints_points_manifoldSize_->push_back(manifoldSize);
}
(*outputCriticalPoints_numberOfPoints_)++;
}
{
std::stringstream msg;
for(int i=0; i<numberOfDimensions; ++i)
msg << "[DiscreteGradient] " << numberOfCriticalPointsByDimension[i]
<< " " << i << "-cell(s)." << std::endl;
dMsg(std::cout, msg.str(), infoMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::getRemovableMaxima(const std::vector<std::pair<SimplexId,char>>& criticalPoints,
const bool allowBoundary,
std::vector<char>& isRemovableMaximum,
std::vector<SimplexId>& pl2dmt_maximum){
const SimplexId numberOfCriticalPoints=criticalPoints.size();
const SimplexId numberOfCells=inputTriangulation_->getNumberOfCells();
const int maximumDim=dimensionality_;
// Detect DMT-max cells to remove
isRemovableMaximum.resize(numberOfCells);
dmtMax2PL_.resize(numberOfCells);
std::fill(dmtMax2PL_.begin(), dmtMax2PL_.end(), -1);
// by default : maximum is removable
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId i=0; i<numberOfCells; ++i){
const Cell maximumCandidate(maximumDim, i);
isRemovableMaximum[i]=isMaximum(maximumCandidate);
}
for(SimplexId i=0; i<numberOfCriticalPoints; ++i){
const std::pair<SimplexId,char>& criticalPoint=criticalPoints[i];
const SimplexId criticalPointId=criticalPoint.first;
const char criticalPointType=criticalPoint.second;
if(criticalPointType==static_cast<char>(CriticalType::Local_maximum)){
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(criticalPointId)) continue;
SimplexId numberOfMaxima=0;
SimplexId maximumId=-1;
const SimplexId
starNumber=inputTriangulation_->getVertexStarNumber(criticalPointId);
for(SimplexId j=0; j<starNumber; ++j){
SimplexId starId;
inputTriangulation_->getVertexStar(criticalPointId, j, starId);
if(isMaximum(Cell(maximumDim, starId)) and dmtMax2PL_[starId]==-1){
maximumId=starId;
++numberOfMaxima;
}
}
// a DMT-maximum in the star of only one PL-maximum cannot be removed
// and is automatically associated to it.
if(numberOfMaxima==1){
if(dmtMax2PL_[maximumId]==-1 and pl2dmt_maximum[criticalPointId]==-1){
dmtMax2PL_[maximumId]=criticalPointId;
pl2dmt_maximum[criticalPointId]=maximumId;
isRemovableMaximum[maximumId]=false;
}
}
}
}
return 0;
}
template <typename dataType>
int DiscreteGradient::getRemovableSaddles1(const std::vector<std::pair<SimplexId,char>>& criticalPoints,
const bool allowBoundary,
std::vector<char>& isRemovableSaddle,
std::vector<SimplexId>& pl2dmt_saddle){
const SimplexId numberOfEdges=inputTriangulation_->getNumberOfEdges();
isRemovableSaddle.resize(numberOfEdges);
dmt1Saddle2PL_.resize(numberOfEdges);
std::fill(dmt1Saddle2PL_.begin(), dmt1Saddle2PL_.end(), -1);
// by default : 1-saddle is removable
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId i=0; i<numberOfEdges; ++i){
const Cell saddleCandidate(1, i);
isRemovableSaddle[i]=isSaddle1(saddleCandidate);
}
// is [edgeId] in star of PL-1saddle?
for(auto& criticalPoint : criticalPoints){
const SimplexId criticalPointId=criticalPoint.first;
const char criticalPointType=criticalPoint.second;
if(criticalPointType==static_cast<char>(CriticalType::Saddle1)){
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(criticalPointId)) continue;
SimplexId numberOfSaddles=0;
SimplexId saddleId=-1;
const SimplexId
edgeNumber=inputTriangulation_->getVertexEdgeNumber(criticalPointId);
for(SimplexId i=0; i<edgeNumber; ++i){
SimplexId edgeId;
inputTriangulation_->getVertexEdge(criticalPointId, i, edgeId);
const Cell saddleCandidate(1, edgeId);
if(isSaddle1(saddleCandidate) and dmt1Saddle2PL_[edgeId]==-1){
saddleId=edgeId;
++numberOfSaddles;
}
}
// only one DMT-1saddle in the star so this one is non-removable
if(numberOfSaddles==1){
if(dmt1Saddle2PL_[saddleId]==-1 and pl2dmt_saddle[criticalPointId]==-1){
dmt1Saddle2PL_[saddleId]=criticalPointId;
pl2dmt_saddle[criticalPointId]=saddleId;
isRemovableSaddle[saddleId]=false;
}
}
}
}
return 0;
}
template <typename dataType>
int DiscreteGradient::getRemovableSaddles2(const
std::vector<std::pair<SimplexId,char>>& criticalPoints,
const bool allowBoundary,
std::vector<char>& isRemovableSaddle,
std::vector<SimplexId>& pl2dmt_saddle){
const SimplexId numberOfTriangles=inputTriangulation_->getNumberOfTriangles();
isRemovableSaddle.resize(numberOfTriangles);
dmt2Saddle2PL_.resize(numberOfTriangles);
std::fill(dmt2Saddle2PL_.begin(), dmt2Saddle2PL_.end(), -1);
// by default : 2-saddle is removable
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId i=0; i<numberOfTriangles; ++i){
const Cell saddleCandidate(2, i);
isRemovableSaddle[i]=isSaddle2(saddleCandidate);
}
// is [triangleId] in star of PL-2saddle?
for(auto& criticalPoint : criticalPoints){
const SimplexId criticalPointId=criticalPoint.first;
const char criticalPointType=criticalPoint.second;
if(criticalPointType==static_cast<char>(CriticalType::Saddle2)){
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(criticalPointId)) continue;
SimplexId numberOfSaddles=0;
SimplexId saddleId=-1;
const SimplexId
triangleNumber=inputTriangulation_->getVertexTriangleNumber(criticalPointId);
for(SimplexId i=0; i<triangleNumber; ++i){
SimplexId triangleId;
inputTriangulation_->getVertexTriangle(criticalPointId, i, triangleId);
const Cell saddleCandidate(2, triangleId);
if(isSaddle2(saddleCandidate) and dmt2Saddle2PL_[triangleId]==-1){
saddleId=triangleId;
++numberOfSaddles;
}
}
// only one DMT-2saddle in the star so this one is non-removable
if(numberOfSaddles==1){
if(dmt2Saddle2PL_[saddleId]==-1 and pl2dmt_saddle[criticalPointId]==-1){
dmt2Saddle2PL_[saddleId]=criticalPointId;
pl2dmt_saddle[criticalPointId]=saddleId;
isRemovableSaddle[saddleId]=false;
}
}
}
}
return 0;
}
template <typename dataType>
int DiscreteGradient::orderSaddleMaximumConnections(const
std::vector<VPath>& vpaths,
std::set<std::pair<dataType,SimplexId>,SaddleMaximumVPathComparator<dataType>>&
S){
Timer t;
const SimplexId numberOfVPaths=vpaths.size();
for(SimplexId i=0; i<numberOfVPaths; ++i){
const VPath& vpath=vpaths[i];
if(vpath.isValid_)
S.insert(std::make_pair(vpath.persistence_,i));
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Ordering of the vpaths :\t" <<
t.getElapsedTime() << " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::computeCoefficients(const bool isDense,
std::vector<char>& denseCoefficients,
std::vector<Segment>& segments,
const CriticalPoint& source,
VPath& newVPath,
const std::vector<VPath>& vpaths) const{
if(isDense){
const SimplexId numberOfSegments=segments.size();
// apriori : the following will make only one allocation, the size is fixed
denseCoefficients.resize(numberOfSegments);
std::fill(denseCoefficients.begin(), denseCoefficients.end(), 0);
// 1) initialize accumulator
const SimplexId numberOfNewVPathSegments=newVPath.segments_.size();
for(SimplexId i=0; i<numberOfNewVPathSegments; ++i){
const SimplexId segmentId=newVPath.segments_[i];
const char segmentState=newVPath.states_[i];
denseCoefficients[segmentId]=segmentState;
}
// 2) add source.vpaths.segments to accumulator
const SimplexId numberOfSourceVPaths=source.vpaths_.size();
for(SimplexId i=0; i<numberOfSourceVPaths; ++i){
const SimplexId sourceVPathId=source.vpaths_[i];
const VPath& sourceVPath=vpaths[sourceVPathId];
if(sourceVPath.isValid_){
const SimplexId numberOfSourceVPathSegments=sourceVPath.segments_.size();
for(SimplexId j=0; j<numberOfSourceVPathSegments; ++j){
const SimplexId segmentId=sourceVPath.segments_[j];
const char segmentState=sourceVPath.states_[j];
denseCoefficients[segmentId]+=segmentState;
}
}
}
// 3) update newVPath to the result of accumulation
newVPath.states_.clear();
newVPath.segments_.clear();
for(SimplexId i=0; i<numberOfSegments; ++i){
const SimplexId segmentId=i;
const char segmentState=denseCoefficients[segmentId];
if(segmentState!=0){
newVPath.states_.push_back(segmentState);
newVPath.segments_.push_back(segmentId);
}
}
}
else{
std::vector<std::pair<SimplexId,char>> sparseCoefficients;
// 1) initialize accumulator
const SimplexId numberOfNewVPathSegments=newVPath.segments_.size();
for(SimplexId i=0; i<numberOfNewVPathSegments; ++i){
const SimplexId segmentId=newVPath.segments_[i];
const char segmentState=newVPath.states_[i];
sparseCoefficients.push_back(std::make_pair(segmentId,segmentState));
}
// 2) add source.vpaths.segments to accumulator
const SimplexId numberOfSourceVPaths=source.vpaths_.size();
for(SimplexId i=0; i<numberOfSourceVPaths; ++i){
const SimplexId sourceVPathId=source.vpaths_[i];
const VPath& sourceVPath=vpaths[sourceVPathId];
if(sourceVPath.isValid_){
const SimplexId numberOfSourceVPathSegments=sourceVPath.segments_.size();
for(SimplexId j=0; j<numberOfSourceVPathSegments; ++j){
const SimplexId segmentId=sourceVPath.segments_[j];
const char segmentState=sourceVPath.states_[j];
bool isIn=false;
const SimplexId sparseCoefficientsSize=sparseCoefficients.size();
for(SimplexId k=0; k<sparseCoefficientsSize; ++k){
const SimplexId savedSegmentId=sparseCoefficients[k].first;
const char savedSegmentState=sparseCoefficients[k].second;
if(segmentId==savedSegmentId){
sparseCoefficients[k].second=segmentState+savedSegmentState;
isIn=true;
}
}
if(!isIn)
sparseCoefficients.push_back(std::make_pair(segmentId,segmentState));
}
}
}
// 3) update newVPath to the result of accumulation
newVPath.states_.clear();
newVPath.segments_.clear();
const SimplexId sparseCoefficientsSize=sparseCoefficients.size();
for(SimplexId i=0; i<sparseCoefficientsSize; ++i){
const SimplexId segmentId=sparseCoefficients[i].first;
const char segmentState=sparseCoefficients[i].second;
// apriori : sparseCoefficients store coefficient zero; we must remove
// them
if(segmentState!=0){
newVPath.states_.push_back(segmentState);
newVPath.segments_.push_back(segmentId);
}
}
}
return 0;
}
template <typename dataType>
int DiscreteGradient::reverseSaddleMaximumConnections(const
std::vector<Segment>& segments){
Timer t;
const SimplexId numberOfSegments=segments.size();
for(SimplexId i=0; i<numberOfSegments; ++i){
const Segment& segment=segments[i];
if(segment.isValid_ and segment.orientation_==false)
reverseAscendingPath(segment.cells_);
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Gradient reversal step :\t" <<
t.getElapsedTime() << " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int
DiscreteGradient::initializeSaddleMaximumConnections(std::vector<char>&
isRemovableMaximum,
std::vector<char>& isRemovableSaddle,
const bool allowBruteForce,
std::vector<Segment>& segments,
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints) const{
Timer t;
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const int maximumDim=dimensionality_;
const int saddleDim=maximumDim-1;
// Part 1 : build initial structures
// add the saddles to CriticalPointList and count them
const SimplexId numberOfSaddleCandidates=getNumberOfCells(saddleDim);
for(SimplexId i=0; i<numberOfSaddleCandidates; ++i){
if(allowBruteForce or isRemovableSaddle[i]){
const Cell saddleCandidate(saddleDim, i);
if(isCellCritical(saddleCandidate))
criticalPoints.push_back(CriticalPoint(saddleCandidate));
}
}
const SimplexId numberOfSaddles=criticalPoints.size();
// add the maxima to CriticalPointList and build MaxIndex
const SimplexId numberOfMaximumCandidates=getNumberOfCells(maximumDim);
std::vector<SimplexId> maximumIndex(numberOfMaximumCandidates,-1);
for(SimplexId i=0; i<numberOfMaximumCandidates; ++i){
if(isRemovableMaximum[i]){
const Cell maximumCandidate(maximumDim, i);
const SimplexId index=criticalPoints.size();
maximumIndex[i]=index;
criticalPoints.push_back(CriticalPoint(maximumCandidate));
}
}
const SimplexId numberOfVPaths=2*numberOfSaddles;
vpaths.resize(numberOfVPaths);
segments.resize(numberOfVPaths);
// Part 2 : update the structures
// apriori: by default construction, the vpaths and segments are not valid
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId i=0; i<numberOfSaddles; ++i){
const SimplexId sourceIndex=i;
CriticalPoint& source=criticalPoints[sourceIndex];
const Cell& saddle=source.cell_;
const SimplexId saddleId=saddle.id_;
SimplexId starNumber{};
if(maximumDim==2)
starNumber=inputTriangulation_->getEdgeStarNumber(saddleId);
else if(maximumDim==3)
starNumber=inputTriangulation_->getTriangleStarNumber(saddleId);
std::vector<std::vector<Cell>> paths(starNumber);
for(SimplexId j=0; j<starNumber; ++j){
SimplexId starId;
if(maximumDim==2)
inputTriangulation_->getEdgeStar(saddleId, j, starId);
else if(maximumDim==3)
inputTriangulation_->getTriangleStar(saddleId, j, starId);
const Cell star(maximumDim, starId);
paths[j].push_back(saddle);
getAscendingPath(star, paths[j]);
}
// detect initial double-connection
if(starNumber>1){
bool isDoubleConnected=false;
const Cell& lastCell0=paths[0].back();
for(SimplexId j=1; j<starNumber; ++j){
const Cell& lastCell=paths[j].back();
if(lastCell0.id_==lastCell.id_){
isDoubleConnected=true;
break;
}
}
if(isDoubleConnected)
continue;
}
for(SimplexId j=0; j<starNumber; ++j){
const SimplexId shift=j;
// apriori: there is at least 1 one cell
const Cell& lastCell=paths[j].back();
if(isMaximum(lastCell) and isRemovableMaximum[lastCell.id_]){
const Cell& maximum=lastCell;
const SimplexId destinationIndex=maximumIndex[maximum.id_];
CriticalPoint& destination=criticalPoints[destinationIndex];
// update source and destination
const SimplexId sourceSlot=source.omp_addSlot();
const SimplexId destinationSlot=destination.omp_addSlot();
// update vpath
const SimplexId vpathIndex=2*sourceIndex+shift;
VPath& vpath=vpaths[vpathIndex];
vpath.source_=sourceIndex;
vpath.destination_=destinationIndex;
vpath.sourceSlot_=sourceSlot;
vpath.destinationSlot_=destinationSlot;
vpath.states_.push_back(1);
vpath.segments_.push_back(vpathIndex);
vpath.persistence_=getPersistence<dataType>(maximum, saddle, scalars);
vpath.isValid_=true;
// update segment
Segment& segment=segments[vpathIndex];
segment.orientation_=true;
segment.cells_=std::move(paths[j]);
segment.isValid_=true;
}
}
}
// Part 3 : initialize the last structures
const SimplexId numberOfCriticalPoints=criticalPoints.size();
for(SimplexId i=0; i<numberOfCriticalPoints; ++i){
CriticalPoint& cp=criticalPoints[i];
const SimplexId numberOfSlots=cp.numberOfSlots_;
cp.vpaths_.resize(numberOfSlots);
cp.numberOfSlots_=0;
}
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId i=0; i<numberOfVPaths; ++i){
const VPath& vpath=vpaths[i];
if(vpath.isValid_){
const SimplexId sourceIndex=vpath.source_;
const SimplexId destinationIndex=vpath.destination_;
const SimplexId sourceSlot=vpath.sourceSlot_;
const SimplexId destinationSlot=vpath.destinationSlot_;
CriticalPoint& source=criticalPoints[sourceIndex];
CriticalPoint& destination=criticalPoints[destinationIndex];
source.vpaths_[sourceSlot]=i;
destination.vpaths_[destinationSlot]=i;
}
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Initialization step :\t" << t.getElapsedTime()
<< " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::processSaddleMaximumConnections(const int iterationThreshold,
const std::vector<char>& isPL,
const bool allowBoundary,
const bool allowBruteForce,
std::set<std::pair<dataType,SimplexId>,
SaddleMaximumVPathComparator<dataType>>& S,
std::vector<SimplexId>& pl2dmt_saddle,
std::vector<SimplexId>& pl2dmt_maximum,
std::vector<Segment>& segments,
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints){
Timer t;
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
SimplexId numberOfSaddleCandidates=0;
if(dimensionality_==2)
numberOfSaddleCandidates=inputTriangulation_->getNumberOfEdges();
else if(dimensionality_==3)
numberOfSaddleCandidates=inputTriangulation_->getNumberOfTriangles();
const SimplexId numberOfMaximumCandidates=inputTriangulation_->getNumberOfCells();
const int maximumDim=dimensionality_;
const int saddleDim=maximumDim-1;
std::vector<char> isRemovedSaddle(numberOfSaddleCandidates, false);
std::vector<char> isRemovedMaximum(numberOfMaximumCandidates, false);
int numberOfIterations{};
std::vector<char> denseCoefficients;
while(S.size()){
if(iterationThreshold>=0 and numberOfIterations>=iterationThreshold) break;
auto ptr=S.begin();
const SimplexId vpathId=ptr->second;
S.erase(ptr);
VPath& vpath=vpaths[vpathId];
// filter by saddle condition
int toRemoveSaddle=0;
if(!allowBruteForce and vpath.isValid_){
const SimplexId sourceId=vpath.source_;
const SimplexId dmt_saddleId=criticalPoints[sourceId].cell_.id_;
if(!isRemovedSaddle[dmt_saddleId]){
for(int i=0; i<(saddleDim+1); ++i){
SimplexId vertexId=-1;
if(dimensionality_==2)
inputTriangulation_->getEdgeVertex(dmt_saddleId, i, vertexId);
else if(dimensionality_==3)
inputTriangulation_->getTriangleVertex(dmt_saddleId, i, vertexId);
if(isPL[vertexId]!=static_cast<char>(CriticalType::Saddle1) and dimensionality_==1) continue;
if(isPL[vertexId]!=static_cast<char>(CriticalType::Saddle2) and dimensionality_==2) continue;
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(vertexId)){
toRemoveSaddle=1;
continue;
}
if(pl2dmt_saddle[vertexId]==-1){
const SimplexId pl_saddleId=vertexId;
SimplexId numberOfRemainingSaddles=0;
SimplexId saddleCandidateNumber=0;
if(dimensionality_==2)
saddleCandidateNumber=inputTriangulation_->getVertexEdgeNumber(pl_saddleId);
else if(dimensionality_==3)
saddleCandidateNumber=inputTriangulation_->getVertexTriangleNumber(pl_saddleId);
for(SimplexId j=0; j<saddleCandidateNumber; ++j){
SimplexId saddleCandidateId=-1;
if(dimensionality_==2)
inputTriangulation_->getVertexEdge(pl_saddleId, j,
saddleCandidateId);
else if(dimensionality_==3)
inputTriangulation_->getVertexTriangle(pl_saddleId, j,
saddleCandidateId);
if(saddleCandidateId!=dmt_saddleId and
isCellCritical(Cell(saddleDim,saddleCandidateId)) and
!isRemovedSaddle[saddleCandidateId])
++numberOfRemainingSaddles;
}
if(!numberOfRemainingSaddles){
pl2dmt_saddle[vertexId]=dmt_saddleId;
if(dimensionality_==2)
dmt1Saddle2PL_[dmt_saddleId]=vertexId;
else if(dimensionality_==2)
dmt2Saddle2PL_[dmt_saddleId]=vertexId;
vpath.invalidate();
toRemoveSaddle=-1;
break;
}
}
else if(pl2dmt_saddle[vertexId]==dmt_saddleId){
vpath.invalidate();
toRemoveSaddle=-1;
break;
}
else{
toRemoveSaddle=1;
break;
}
}
if(vpath.isValid_){
toRemoveSaddle=1;
}
}
else{
vpath.invalidate();
toRemoveSaddle=-1;
}
}
// filter by maximum condition
int toRemoveMaximum=0;
if(vpath.isValid_){
const SimplexId destinationId=vpath.destination_;
const SimplexId dmt_maxId=criticalPoints[destinationId].cell_.id_;
if(!isRemovedMaximum[dmt_maxId]){
for(int i=0; i<(maximumDim+1); ++i){
SimplexId vertexId;
inputTriangulation_->getCellVertex(dmt_maxId, i, vertexId);
if(isPL[vertexId]!=static_cast<char>(CriticalType::Local_maximum)) continue;
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(vertexId)){
toRemoveMaximum=1;
continue;
}
if(pl2dmt_maximum[vertexId]==-1){
const SimplexId pl_maxId=vertexId;
SimplexId numberOfRemainingMaxima=0;
const SimplexId
starNumber=inputTriangulation_->getVertexStarNumber(pl_maxId);
for(SimplexId j=0; j<starNumber; ++j){
SimplexId starId;
inputTriangulation_->getVertexStar(pl_maxId, j, starId);
if(starId!=dmt_maxId and isMaximum(Cell(maximumDim,starId)) and
!isRemovedMaximum[starId])
++numberOfRemainingMaxima;
}
if(!numberOfRemainingMaxima){
pl2dmt_maximum[vertexId]=dmt_maxId;
dmtMax2PL_[dmt_maxId]=vertexId;
vpath.invalidate();
toRemoveMaximum=-1;
break;
}
}
else if(pl2dmt_maximum[vertexId]==dmt_maxId){
vpath.invalidate();
toRemoveMaximum=-1;
break;
}
else{
toRemoveMaximum=1;
break;
}
}
if(vpath.isValid_){
toRemoveMaximum=1;
}
}
else{
vpath.invalidate();
toRemoveMaximum=-1;
}
}
// sync removed-state
if(vpath.isValid_){
if((toRemoveSaddle>=0 and toRemoveMaximum>0) or (toRemoveSaddle>0 and
toRemoveMaximum>=0)){
const SimplexId sourceId=vpath.source_;
const SimplexId dmt_saddleId=criticalPoints[sourceId].cell_.id_;
const SimplexId destinationId=vpath.destination_;
const SimplexId dmt_maxId=criticalPoints[destinationId].cell_.id_;
isRemovedSaddle[dmt_saddleId]=true;
isRemovedMaximum[dmt_maxId]=true;
}
}
if(vpath.isValid_){
// all segments of the selected vpath are reversed
const SimplexId numberOfVPathSegments=vpath.segments_.size();
for(SimplexId i=0; i<numberOfVPathSegments; ++i){
const SimplexId segmentId=vpath.segments_[i];
Segment& segment=segments[segmentId];
segment.orientation_=!segment.orientation_;
vpath.states_[i]*=-1;
}
// search new destination for newVPath
SimplexId newDestinationId=-1;
const SimplexId sourceId=vpath.source_;
const SimplexId destinationId=vpath.destination_;
CriticalPoint& source=criticalPoints[sourceId];
CriticalPoint& destination=criticalPoints[destinationId];
const SimplexId numberOfSourceVPaths=source.vpaths_.size();
const SimplexId numberOfDestinationVPaths=destination.vpaths_.size();
for(SimplexId i=0; i<numberOfSourceVPaths; ++i){
const SimplexId sourceVPathId=source.vpaths_[i];
const VPath& sourceVPath=vpaths[sourceVPathId];
if(sourceVPath.isValid_ and sourceVPath.destination_!=destinationId){
newDestinationId=sourceVPath.destination_;
break;
}
}
// no valid destination so continue
const bool hasInvalidDestination=(newDestinationId==-1);
if(hasInvalidDestination)
vpath.invalidate();
// update destination.vpaths
for(SimplexId i=0; i<numberOfDestinationVPaths; ++i){
// newVPath = destination.vpath
const SimplexId newVPathId=destination.vpaths_[i];
VPath& newVPath=vpaths[newVPathId];
if(newVPathId==vpathId) continue;
if(!newVPath.isValid_) continue;
if(hasInvalidDestination){
newVPath.invalidate();
continue;
}
// check for double-connections in newVPath
const SimplexId newSourceId=newVPath.source_;
CriticalPoint& newSource=criticalPoints[newSourceId];
bool isDoubleConnected=false;
const SimplexId numberOfNewSourceVPaths=newSource.vpaths_.size();
for(SimplexId j=0; j<numberOfNewSourceVPaths; ++j){
const SimplexId newSourceVPathId=newSource.vpaths_[j];
VPath& newSourceVPath=vpaths[newSourceVPathId];
if(newSourceVPath.isValid_ and
newSourceVPath.destination_==newDestinationId){
isDoubleConnected=true;
newSourceVPath.invalidate();
break;
}
}
// invalid newVPath
if(isDoubleConnected){
newVPath.invalidate();
continue;
}
// compute final coefficients of newVPath with sparse representation
computeCoefficients<dataType>(false, denseCoefficients, segments,
source, newVPath, vpaths);
// update the destination of newVPath
newVPath.destination_=newDestinationId;
// add newVPath to newDestination connectivity
CriticalPoint& newDestination=criticalPoints[newDestinationId];
newDestination.vpaths_.push_back(newVPathId);
// erase newVPath
S.erase(std::make_pair(newVPath.persistence_,newVPathId));
// update persistence
newVPath.persistence_=getPersistence<dataType>(newDestination.cell_,newSource.
cell_, scalars);
// repush newVPath to confirm update
S.insert(std::make_pair(newVPath.persistence_,newVPathId));
}
// invalid source.vpaths
for(SimplexId i=0; i<numberOfSourceVPaths; ++i){
const SimplexId sourceVPathId=source.vpaths_[i];
VPath& sourceVPath=vpaths[sourceVPathId];
sourceVPath.invalidate();
}
// erase connectivity of source and destination
source.vpaths_.clear();
destination.vpaths_.clear();
}
++numberOfIterations;
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Processing of the vpaths :\t" <<
t.getElapsedTime() << " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::simplifySaddleMaximumConnections(const
std::vector<std::pair<SimplexId,char>>& criticalPoints,
const std::vector<char>& isPL,
const int iterationThreshold,
const bool allowBoundary,
const bool allowBruteForce){
Timer t;
// Part 0 : select the cells to keep or remove (gradient
// is not modified).
std::vector<char> isRemovableMaximum;
std::vector<SimplexId> pl2dmt_maximum(numberOfVertices_, -1);
getRemovableMaxima<dataType>(criticalPoints, allowBoundary,
isRemovableMaximum, pl2dmt_maximum);
std::vector<char> isRemovableSaddle;
std::vector<SimplexId> pl2dmt_saddle(numberOfVertices_, -1);
if(!allowBruteForce){
if(dimensionality_==2)
getRemovableSaddles1<dataType>(criticalPoints, allowBoundary,
isRemovableSaddle, pl2dmt_saddle);
else if(dimensionality_==3)
getRemovableSaddles2<dataType>(criticalPoints, allowBoundary,
isRemovableSaddle, pl2dmt_saddle);
}
// Part 1 : build a virtual but complete MSC structure as
// initialization (gradient is not modified).
std::vector<Segment> segments;
std::vector<VPath> vpaths;
std::vector<CriticalPoint> dmt_criticalPoints;
initializeSaddleMaximumConnections<dataType>(isRemovableMaximum,
isRemovableSaddle,
allowBruteForce,
segments,
vpaths,
dmt_criticalPoints);
// Part 2 : push the vpaths into a set to order them by persistence
// value - lower to higher (gradient is not modified).
SaddleMaximumVPathComparator<dataType> cmp_f;
std::set<std::pair<dataType,SimplexId>, SaddleMaximumVPathComparator<dataType>>
S(cmp_f);
orderSaddleMaximumConnections<dataType>(vpaths, S);
// Part 3 : iteratively process the vpaths, virtually reverse the
// selected vpath and update the structure accordingly (gradient is
// not modified).
processSaddleMaximumConnections<dataType>(iterationThreshold,
isPL,
allowBoundary,
allowBruteForce,
S,
pl2dmt_saddle,
pl2dmt_maximum,
segments,
vpaths,
dmt_criticalPoints);
// Part 4 : from the last version of the virtual MSC: use the
// informations stored in the virtual structure to actually
// reverse the vpaths in the gradient (gradient is modified).
reverseSaddleMaximumConnections<dataType>(segments);
{
std::stringstream msg;
msg << "[DiscreteGradient] Saddle-Maximum pairs simplified in "
<< t.getElapsedTime() << " s, "<< threadNumber_ << " thread(s)." <<
std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::initializeSaddleSaddleConnections1(const
std::vector<char>& isRemovableSaddle1,
const std::vector<char>& isRemovableSaddle2,
const bool allowBruteForce,
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints,
std::vector<SimplexId>& saddle1Index,
std::vector<SimplexId>& saddle2Index) const{
Timer t;
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const int maximumDim=dimensionality_;
const int saddle2Dim=maximumDim-1;
const int saddle1Dim=saddle2Dim-1;
// Part 1 : build initial structures
// add the 2-saddles to CriticalPointList
const SimplexId numberOfSaddle2Candidates=getNumberOfCells(saddle2Dim);
saddle2Index.resize(numberOfSaddle2Candidates, -1);
for(SimplexId i=0; i<numberOfSaddle2Candidates; ++i){
if(allowBruteForce or isRemovableSaddle2[i]){
const Cell saddle2Candidate(saddle2Dim, i);
if(isSaddle2(saddle2Candidate)){
const SimplexId index=criticalPoints.size();
saddle2Index[i]=index;
criticalPoints.push_back(CriticalPoint(saddle2Candidate));
}
}
}
const SimplexId numberOf2Saddles=criticalPoints.size();
// add the 1-saddles to CriticalPointList
const SimplexId numberOfSaddle1Candidates=getNumberOfCells(saddle1Dim);
saddle1Index.resize(numberOfSaddle1Candidates, -1);
for(SimplexId i=0; i<numberOfSaddle1Candidates; ++i){
if(isRemovableSaddle1[i]){
const Cell saddle1Candidate(saddle1Dim, i);
const SimplexId index=criticalPoints.size();
saddle1Index[i]=index;
criticalPoints.push_back(CriticalPoint(saddle1Candidate));
}
}
// Part 2 : update the structures
// apriori: by default construction, the vpaths and segments are not valid
wallId_t descendingWallId=1;
std::vector<wallId_t> isVisited(numberOfSaddle2Candidates, 0);
for(SimplexId i=0; i<numberOf2Saddles; ++i){
const SimplexId destinationIndex=i;
CriticalPoint& destination=criticalPoints[destinationIndex];
const Cell& saddle2=destination.cell_;
std::set<SimplexId> saddles1;
const wallId_t savedDescendingWallId=descendingWallId;
getDescendingWall(descendingWallId, saddle2, isVisited, nullptr, &saddles1);
++descendingWallId;
for(auto& saddle1Id : saddles1){
if(!isRemovableSaddle1[saddle1Id]) continue;
const Cell& saddle1=Cell(1,saddle1Id);
std::vector<Cell> path;
const bool
isMultiConnected=getAscendingPathThroughWall(savedDescendingWallId, saddle1,
saddle2, isVisited, &path);
if(!isMultiConnected){
const SimplexId sourceIndex=saddle1Index[saddle1Id];
CriticalPoint& source=criticalPoints[sourceIndex];
// update source and destination
const SimplexId sourceSlot=source.addSlot();
const SimplexId destinationSlot=destination.addSlot();
// update vpath
const dataType persistence=getPersistence<dataType>(saddle2, saddle1,
scalars);
vpaths.push_back(VPath(true,-1,sourceIndex,destinationIndex,sourceSlot,
destinationSlot,persistence));
}
}
}
// Part 3 : initialize the last structures
const SimplexId numberOfCriticalPoints=criticalPoints.size();
for(SimplexId i=0; i<numberOfCriticalPoints; ++i){
CriticalPoint& cp=criticalPoints[i];
const SimplexId numberOfSlots=cp.numberOfSlots_;
cp.vpaths_.resize(numberOfSlots);
cp.numberOfSlots_=0;
}
const SimplexId numberOfVPaths=vpaths.size();
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId i=0; i<numberOfVPaths; ++i){
const VPath& vpath=vpaths[i];
if(vpath.isValid_){
const SimplexId sourceIndex=vpath.source_;
const SimplexId destinationIndex=vpath.destination_;
const SimplexId sourceSlot=vpath.sourceSlot_;
const SimplexId destinationSlot=vpath.destinationSlot_;
CriticalPoint& source=criticalPoints[sourceIndex];
CriticalPoint& destination=criticalPoints[destinationIndex];
source.vpaths_[sourceSlot]=i;
destination.vpaths_[destinationSlot]=i;
}
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Initialization step :\t" << t.getElapsedTime()
<< " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::orderSaddleSaddleConnections1(const
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints,
std::set<std::tuple<dataType,SimplexId,SimplexId>,
SaddleSaddleVPathComparator<dataType>> &S){
Timer t;
const SimplexId numberOfVPaths=vpaths.size();
for(SimplexId i=0; i<numberOfVPaths; ++i){
const VPath& vpath=vpaths[i];
if(vpath.isValid_){
const SimplexId saddleId=criticalPoints[vpath.destination_].cell_.id_;
S.insert(std::make_tuple(vpath.persistence_,i,saddleId));
}
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Ordering of the vpaths :\t" <<
t.getElapsedTime() << " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::processSaddleSaddleConnections1(const int
iterationThreshold,
const std::vector<char>& isPL,
const bool allowBoundary,
const bool allowBruteForce,
const bool returnSaddleConnectors,
std::set<std::tuple<dataType,SimplexId,SimplexId>,
SaddleSaddleVPathComparator<dataType>>& S,
std::vector<SimplexId>& pl2dmt_saddle1,
std::vector<SimplexId>& pl2dmt_saddle2,
std::vector<char>& isRemovableSaddle1,
std::vector<char>& isRemovableSaddle2,
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints,
std::vector<SimplexId>& saddle1Index,
std::vector<SimplexId>& saddle2Index){
Timer t;
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const SimplexId numberOfEdges=inputTriangulation_->getNumberOfEdges();
const SimplexId numberOfTriangles=inputTriangulation_->getNumberOfTriangles();
const SimplexId optimizedSize=std::max(numberOfEdges, numberOfTriangles);
wallId_t wallId=1;
std::vector<wallId_t> isVisited(optimizedSize, 0);
int numberOfIterations{};
while(!S.empty()){
if(iterationThreshold>=0 and numberOfIterations>=iterationThreshold) break;
auto ptr=S.begin();
const SimplexId vpathId=std::get<1>(*ptr);
S.erase(ptr);
VPath& vpath=vpaths[vpathId];
if(vpath.isValid_){
if(returnSaddleConnectors){
const dataType persistence=vpath.persistence_;
if(persistence>SaddleConnectorsPersistenceThreshold) break;
}
const Cell& minSaddle1=criticalPoints[vpath.source_].cell_;
const Cell& minSaddle2=criticalPoints[vpath.destination_].cell_;
std::set<SimplexId> saddles1;
const wallId_t savedWallId=wallId;
getDescendingWall(wallId, minSaddle2, isVisited, nullptr, &saddles1);
++wallId;
// check if at least one connection exists
auto isFound=saddles1.find(minSaddle1.id_);
if(isFound==saddles1.end()){
++numberOfIterations;
continue;
}
// check if there is multiple connections
std::vector<Cell> path;
const bool isMultiConnected=getAscendingPathThroughWall(savedWallId,
minSaddle1, minSaddle2, isVisited, &path);
if(isMultiConnected){
++numberOfIterations;
continue;
}
// filter by 1-saddle condition
if(vpath.isValid_){
const Cell& dmt_saddle1=criticalPoints[vpath.source_].cell_;
const SimplexId dmt_saddle1Id=dmt_saddle1.id_;
if(isSaddle1(dmt_saddle1)){
for(int i=0; i<2; ++i){
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(dmt_saddle1Id, i, vertexId);
if(isPL[vertexId]!=static_cast<char>(CriticalType::Saddle1)) continue;
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(vertexId)) continue;
if(pl2dmt_saddle1[vertexId]==-1){
const SimplexId pl_saddle1Id=vertexId;
SimplexId numberOfRemainingSaddles1=0;
SimplexId savedId=-1;
const SimplexId
edgeNumber=inputTriangulation_->getVertexEdgeNumber(pl_saddle1Id);
for(SimplexId j=0; j<edgeNumber; ++j){
SimplexId edgeId;
inputTriangulation_->getVertexEdge(pl_saddle1Id, j, edgeId);
if(edgeId!=dmt_saddle1Id and isSaddle1(Cell(1,edgeId)) and
isRemovableSaddle1[edgeId]){
++numberOfRemainingSaddles1;
savedId=edgeId;
}
}
if(numberOfRemainingSaddles1==0){
isRemovableSaddle1[dmt_saddle1Id]=false;
pl2dmt_saddle1[vertexId]=dmt_saddle1Id;
dmt1Saddle2PL_[dmt_saddle1Id]=vertexId;
vpath.invalidate();
break;
}
if(numberOfRemainingSaddles1==1){
isRemovableSaddle1[dmt_saddle1Id]=false;
isRemovableSaddle1[savedId]=false;
pl2dmt_saddle1[vertexId]=savedId;
dmt1Saddle2PL_[savedId]=vertexId;
break;
}
}
else if(pl2dmt_saddle1[vertexId]==dmt_saddle1Id){
vpath.invalidate();
break;
}
}
}
else
vpath.invalidate();
}
// filter by 2-saddle condition
if(!allowBruteForce and vpath.isValid_){
const Cell& dmt_saddle2=criticalPoints[vpath.destination_].cell_;
const SimplexId dmt_saddle2Id=dmt_saddle2.id_;
if(isSaddle2(dmt_saddle2)){
for(int i=0; i<3; ++i){
SimplexId vertexId;
inputTriangulation_->getTriangleVertex(dmt_saddle2Id, i, vertexId);
if(isPL[vertexId]!=static_cast<char>(CriticalType::Saddle2)) continue;
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(vertexId)) continue;
if(pl2dmt_saddle2[vertexId]==-1){
const SimplexId pl_saddle2Id=vertexId;
SimplexId numberOfRemainingSaddles2=0;
SimplexId savedId=-1;
const SimplexId
triangleNumber=inputTriangulation_->getVertexTriangleNumber(pl_saddle2Id);
for(SimplexId j=0; j<triangleNumber; ++j){
SimplexId triangleId;
inputTriangulation_->getVertexTriangle(pl_saddle2Id, j,
triangleId);
if(triangleId!=dmt_saddle2Id and isSaddle2(Cell(2,triangleId))
and isRemovableSaddle2[triangleId]){
++numberOfRemainingSaddles2;
savedId=triangleId;
}
}
if(numberOfRemainingSaddles2==0){
isRemovableSaddle2[dmt_saddle2Id]=false;
pl2dmt_saddle2[vertexId]=dmt_saddle2Id;
dmt2Saddle2PL_[dmt_saddle2Id]=vertexId;
vpath.invalidate();
break;
}
if(numberOfRemainingSaddles2==1){
isRemovableSaddle2[dmt_saddle2Id]=false;
isRemovableSaddle2[savedId]=false;
pl2dmt_saddle2[vertexId]=savedId;
dmt2Saddle2PL_[savedId]=vertexId;
break;
}
}
else if(pl2dmt_saddle2[vertexId]==dmt_saddle2Id){
vpath.invalidate();
break;
}
}
}
else
vpath.invalidate();
}
if(vpath.isValid_)
reverseAscendingPathOnWall(path);
}
if(vpath.isValid_){
// add persistence pair to collection if necessary
if(CollectPersistencePairs and outputPersistencePairs_){
const Cell& minSaddle1=criticalPoints[vpath.source_].cell_;
const Cell& minSaddle2=criticalPoints[vpath.destination_].cell_;
outputPersistencePairs_->push_back(std::make_tuple(minSaddle1, minSaddle2));
}
const SimplexId sourceId=vpath.source_;
const SimplexId destinationId=vpath.destination_;
// invalidate vpaths connected to destination
std::vector<SimplexId> newSourceIds;
CriticalPoint& destination=criticalPoints[destinationId];
for(auto& destinationVPathId : destination.vpaths_){
VPath& destinationVPath=vpaths[destinationVPathId];
if(destinationVPath.isValid_ and destinationVPath.source_!=sourceId){
// save critical point
const SimplexId newSourceId=destinationVPath.source_;
newSourceIds.push_back(newSourceId);
// clear vpath
destinationVPath.invalidate();
}
}
// invalidate vpaths connected to source and save the critical points to
// update
std::vector<SimplexId> newDestinationIds;
CriticalPoint& source=criticalPoints[sourceId];
for(auto& sourceVPathId : source.vpaths_){
VPath& sourceVPath=vpaths[sourceVPathId];
if(sourceVPath.isValid_ and sourceVPath.destination_!=destinationId){
// save critical point
const SimplexId newDestinationId=sourceVPath.destination_;
newDestinationIds.push_back(newDestinationId);
CriticalPoint& newDestination=criticalPoints[newDestinationId];
for(auto& newDestinationVPathId : newDestination.vpaths_){
VPath& newDestinationVPath=vpaths[newDestinationVPathId];
if(newDestinationVPath.isValid_ and
newDestinationVPath.source_!=sourceId){
// clear vpath
newDestinationVPath.invalidate();
}
}
// clear vpath
sourceVPath.invalidate();
}
}
// finally invalidate current vpath and critical points
vpath.invalidate();
source.clear();
destination.clear();
// look at the gradient : reconnect locally the critical points
for(auto& newDestinationId : newDestinationIds){
CriticalPoint& newDestination=criticalPoints[newDestinationId];
const Cell& saddle2=newDestination.cell_;
std::set<SimplexId> saddles1;
const wallId_t savedWallId=wallId;
getDescendingWall(wallId, saddle2, isVisited, nullptr, &saddles1);
++wallId;
for(auto& saddle1Id : saddles1){
const Cell saddle1(1,saddle1Id);
std::vector<Cell> path;
const bool isMultiConnected=getAscendingPathThroughWall(savedWallId,
saddle1, saddle2, isVisited, &path);
if(isMultiConnected)
continue;
SimplexId newSourceId=saddle1Index[saddle1Id];
// connection to a new saddle1 (not present in the graph before)
if(newSourceId==-1){
if(!isRemovableSaddle1[saddle1Id]) continue;
const SimplexId newCriticalPointId=criticalPoints.size();
saddle1Index[saddle1Id]=newCriticalPointId;
criticalPoints.push_back(CriticalPoint(saddle1));
newSourceId=newCriticalPointId;
}
CriticalPoint& newSource=criticalPoints[newSourceId];
// update vpaths
const SimplexId newVPathId=vpaths.size();
const dataType persistence=getPersistence<dataType>(saddle2, saddle1,
scalars);
vpaths.push_back(VPath(true,-1,newSourceId,newDestinationId,-1,-1,persistence));
// update criticalPoints
newDestination.vpaths_.push_back(newVPathId);
newSource.vpaths_.push_back(newVPathId);
// update set
S.insert(std::make_tuple(persistence,newVPathId,newDestination.cell_.id_));
}
}
// look at the gradient : get the links not predicted by the graph
for(auto& newSourceId : newSourceIds){
CriticalPoint& newSource=criticalPoints[newSourceId];
const Cell& saddle1=newSource.cell_;
std::set<SimplexId> saddles2;
const wallId_t savedWallId=wallId;
getAscendingWall(wallId, saddle1, isVisited, nullptr, &saddles2);
++wallId;
for(auto& saddle2Id : saddles2){
const Cell saddle2(2,saddle2Id);
std::vector<Cell> path;
const bool isMultiConnected=getDescendingPathThroughWall(savedWallId,
saddle2, saddle1, isVisited, &path);
if(isMultiConnected)
continue;
const SimplexId newDestinationId=saddle2Index[saddle2Id];
// connection to a new saddle2 (not present in the graph before)
if(newDestinationId==-1)
continue;
CriticalPoint& newDestination=criticalPoints[newDestinationId];
// check existence of the possibly newVPath in the graph
bool alreadyExists=false;
for(auto& newDestinationVPathId : newDestination.vpaths_){
const VPath& newDestinationVPath=vpaths[newDestinationVPathId];
if(newDestinationVPath.isValid_ and
newDestinationVPath.source_==newSourceId){
alreadyExists=true;
break;
}
}
if(alreadyExists)
continue;
// update vpaths
const SimplexId newVPathId=vpaths.size();
const dataType persistence=getPersistence<dataType>(saddle2, saddle1,
scalars);
vpaths.push_back(VPath(true,-1,newSourceId,newDestinationId,-1,-1,persistence));
// update criticalPoints
newDestination.vpaths_.push_back(newVPathId);
newSource.vpaths_.push_back(newVPathId);
// update set
S.insert(std::make_tuple(persistence,newVPathId,newDestination.cell_.id_));
}
}
}
++numberOfIterations;
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Processing of the vpaths :\t" <<
t.getElapsedTime() << " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::simplifySaddleSaddleConnections1(const
std::vector<std::pair<SimplexId,char>>& criticalPoints,
const std::vector<char>& isPL,
const int iterationThreshold,
const bool allowBoundary,
const bool allowBruteForce,
const bool returnSaddleConnectors){
Timer t;
// Part 0 : get removable cells
std::vector<char> isRemovableSaddle1;
std::vector<SimplexId> pl2dmt_saddle1(numberOfVertices_, -1);
getRemovableSaddles1<dataType>(criticalPoints, allowBoundary,
isRemovableSaddle1, pl2dmt_saddle1);
std::vector<char> isRemovableSaddle2;
std::vector<SimplexId> pl2dmt_saddle2(numberOfVertices_, -1);
getRemovableSaddles2<dataType>(criticalPoints, allowBoundary,
isRemovableSaddle2, pl2dmt_saddle2);
// Part 1 : initialization
std::vector<VPath> vpaths;
std::vector<CriticalPoint> dmt_criticalPoints;
std::vector<SimplexId> saddle1Index;
std::vector<SimplexId> saddle2Index;
initializeSaddleSaddleConnections1<dataType>(isRemovableSaddle1,
isRemovableSaddle2,
allowBruteForce,
vpaths,
dmt_criticalPoints,
saddle1Index,
saddle2Index);
// Part 2 : push the vpaths and order by persistence
SaddleSaddleVPathComparator<dataType> cmp_f;
std::set<std::tuple<dataType,SimplexId,SimplexId>, SaddleSaddleVPathComparator<dataType>>
S(cmp_f);
orderSaddleSaddleConnections1<dataType>(vpaths, dmt_criticalPoints, S);
// Part 3 : process the vpaths
processSaddleSaddleConnections1<dataType>(iterationThreshold,
isPL,
allowBoundary,
allowBruteForce,
returnSaddleConnectors,
S,
pl2dmt_saddle1,
pl2dmt_saddle2,
isRemovableSaddle1,
isRemovableSaddle2,
vpaths,
dmt_criticalPoints,
saddle1Index,
saddle2Index);
{
std::stringstream msg;
msg << "[DiscreteGradient] Saddle-Saddle pairs simplified in "
<< t.getElapsedTime() << " s, "<< threadNumber_ << " thread(s)." <<
std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::initializeSaddleSaddleConnections2(const
std::vector<char>& isRemovableSaddle1,
const std::vector<char>& isRemovableSaddle2,
const bool allowBruteForce,
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints,
std::vector<SimplexId>& saddle1Index,
std::vector<SimplexId>& saddle2Index) const{
Timer t;
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const int maximumDim=dimensionality_;
const int saddle2Dim=maximumDim-1;
const int saddle1Dim=saddle2Dim-1;
// Part 1 : build initial structures
// add the 1-saddles to CriticalPointList
const SimplexId numberOfSaddle1Candidates=getNumberOfCells(saddle1Dim);
saddle1Index.resize(numberOfSaddle1Candidates, -1);
for(SimplexId i=0; i<numberOfSaddle1Candidates; ++i){
if(isRemovableSaddle1[i]){
const Cell saddle1Candidate(saddle1Dim, i);
const SimplexId index=criticalPoints.size();
saddle1Index[i]=index;
criticalPoints.push_back(CriticalPoint(saddle1Candidate));
}
}
const SimplexId numberOf1Saddles=criticalPoints.size();
// add the 2-saddles to CriticalPointList
const SimplexId numberOfSaddle2Candidates=getNumberOfCells(saddle2Dim);
saddle2Index.resize(numberOfSaddle2Candidates, -1);
for(SimplexId i=0; i<numberOfSaddle2Candidates; ++i){
if(allowBruteForce or isRemovableSaddle2[i]){
const Cell saddle2Candidate(saddle2Dim, i);
if(isSaddle2(saddle2Candidate)){
const SimplexId index=criticalPoints.size();
saddle2Index[i]=index;
criticalPoints.push_back(CriticalPoint(saddle2Candidate));
}
}
}
// Part 2 : update the structures
// apriori: by default construction, the vpaths and segments are not valid
wallId_t ascendingWallId=1;
std::vector<wallId_t> isVisited(numberOfSaddle1Candidates, 0);
for(SimplexId i=0; i<numberOf1Saddles; ++i){
const SimplexId sourceIndex=i;
CriticalPoint& source=criticalPoints[sourceIndex];
const Cell& saddle1=source.cell_;
std::set<SimplexId> saddles2;
const wallId_t savedAscendingWallId=ascendingWallId;
getAscendingWall(ascendingWallId, saddle1, isVisited, nullptr, &saddles2);
++ascendingWallId;
for(auto& saddle2Id : saddles2){
if(!isRemovableSaddle2[saddle2Id]) continue;
const Cell& saddle2=Cell(2,saddle2Id);
std::vector<Cell> path;
const bool
isMultiConnected=getDescendingPathThroughWall(savedAscendingWallId, saddle2,
saddle1, isVisited, &path);
if(!isMultiConnected){
const SimplexId destinationIndex=saddle2Index[saddle2Id];
CriticalPoint& destination=criticalPoints[destinationIndex];
// update source and destination
const SimplexId sourceSlot=source.addSlot();
const SimplexId destinationSlot=destination.addSlot();
// update vpath
const dataType persistence=getPersistence<dataType>(saddle2, saddle1,
scalars);
vpaths.push_back(VPath(true,-1,sourceIndex,destinationIndex,sourceSlot,
destinationSlot,persistence));
}
}
}
// Part 3 : initialize the last structures
const SimplexId numberOfCriticalPoints=criticalPoints.size();
for(SimplexId i=0; i<numberOfCriticalPoints; ++i){
CriticalPoint& cp=criticalPoints[i];
const SimplexId numberOfSlots=cp.numberOfSlots_;
cp.vpaths_.resize(numberOfSlots);
cp.numberOfSlots_=0;
}
const SimplexId numberOfVPaths=vpaths.size();
#ifdef TTK_ENABLE_OPENMP
# pragma omp parallel for num_threads(threadNumber_)
#endif
for(SimplexId i=0; i<numberOfVPaths; ++i){
const VPath& vpath=vpaths[i];
if(vpath.isValid_){
const SimplexId sourceIndex=vpath.source_;
const SimplexId destinationIndex=vpath.destination_;
const SimplexId sourceSlot=vpath.sourceSlot_;
const SimplexId destinationSlot=vpath.destinationSlot_;
CriticalPoint& source=criticalPoints[sourceIndex];
CriticalPoint& destination=criticalPoints[destinationIndex];
source.vpaths_[sourceSlot]=i;
destination.vpaths_[destinationSlot]=i;
}
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Initialization step :\t" <<
t.getElapsedTime()
<< " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::orderSaddleSaddleConnections2(const
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints,
std::set<std::tuple<dataType,SimplexId,SimplexId>,
SaddleSaddleVPathComparator<dataType>> &S){
Timer t;
const SimplexId numberOfVPaths=vpaths.size();
for(SimplexId i=0; i<numberOfVPaths; ++i){
const VPath& vpath=vpaths[i];
if(vpath.isValid_){
const SimplexId saddleId=criticalPoints[vpath.source_].cell_.id_;
S.insert(std::make_tuple(vpath.persistence_,i,saddleId));
}
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Ordering of the vpaths :\t" <<
t.getElapsedTime() << " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::processSaddleSaddleConnections2(const int
iterationThreshold,
const std::vector<char>& isPL,
const bool allowBoundary,
const bool allowBruteForce,
const bool returnSaddleConnectors,
std::set<std::tuple<dataType,SimplexId,SimplexId>,
SaddleSaddleVPathComparator<dataType>>& S,
std::vector<SimplexId>& pl2dmt_saddle1,
std::vector<SimplexId>& pl2dmt_saddle2,
std::vector<char>& isRemovableSaddle1,
std::vector<char>& isRemovableSaddle2,
std::vector<VPath>& vpaths,
std::vector<CriticalPoint>& criticalPoints,
std::vector<SimplexId>& saddle1Index,
std::vector<SimplexId>& saddle2Index){
Timer t;
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
const SimplexId numberOfEdges=inputTriangulation_->getNumberOfEdges();
const SimplexId numberOfTriangles=inputTriangulation_->getNumberOfTriangles();
const SimplexId optimizedSize=std::max(numberOfEdges, numberOfTriangles);
wallId_t wallId=1;
std::vector<wallId_t> isVisited(optimizedSize, 0);
int numberOfIterations{};
while(!S.empty()){
if(iterationThreshold>=0 and numberOfIterations>=iterationThreshold) break;
auto ptr=S.begin();
const SimplexId vpathId=std::get<1>(*ptr);
S.erase(ptr);
VPath& vpath=vpaths[vpathId];
if(vpath.isValid_){
if(returnSaddleConnectors){
const dataType persistence=vpath.persistence_;
if(persistence>SaddleConnectorsPersistenceThreshold) break;
}
const Cell& minSaddle1=criticalPoints[vpath.source_].cell_;
const Cell& minSaddle2=criticalPoints[vpath.destination_].cell_;
std::set<SimplexId> saddles2;
const wallId_t savedWallId=wallId;
getAscendingWall(wallId, minSaddle1, isVisited, nullptr, &saddles2);
++wallId;
// check if at least one connection exists
auto isFound=saddles2.find(minSaddle2.id_);
if(isFound==saddles2.end()){
++numberOfIterations;
continue;
}
// check if there is multiple connections
std::vector<Cell> path;
const bool isMultiConnected=getDescendingPathThroughWall(savedWallId,
minSaddle2, minSaddle1, isVisited, &path);
if(isMultiConnected){
++numberOfIterations;
continue;
}
// filter by 1-saddle condition
if(vpath.isValid_){
const Cell& dmt_saddle1=criticalPoints[vpath.source_].cell_;
const SimplexId dmt_saddle1Id=dmt_saddle1.id_;
if(isSaddle1(dmt_saddle1)){
for(int i=0; i<2; ++i){
SimplexId vertexId;
inputTriangulation_->getEdgeVertex(dmt_saddle1Id, i, vertexId);
if(isPL[vertexId]!=static_cast<char>(CriticalType::Saddle1)) continue;
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(vertexId)) continue;
if(pl2dmt_saddle1[vertexId]==-1){
const SimplexId pl_saddle1Id=vertexId;
SimplexId numberOfRemainingSaddles1=0;
SimplexId savedId=-1;
const SimplexId
edgeNumber=inputTriangulation_->getVertexEdgeNumber(pl_saddle1Id);
for(SimplexId j=0; j<edgeNumber; ++j){
SimplexId edgeId;
inputTriangulation_->getVertexEdge(pl_saddle1Id, j, edgeId);
if(edgeId!=dmt_saddle1Id and isSaddle1(Cell(1,edgeId)) and
isRemovableSaddle1[edgeId]){
++numberOfRemainingSaddles1;
savedId=edgeId;
}
}
if(numberOfRemainingSaddles1==0){
isRemovableSaddle1[dmt_saddle1Id]=false;
pl2dmt_saddle1[vertexId]=dmt_saddle1Id;
dmt1Saddle2PL_[dmt_saddle1Id]=vertexId;
vpath.invalidate();
break;
}
if(numberOfRemainingSaddles1==1){
isRemovableSaddle1[dmt_saddle1Id]=false;
isRemovableSaddle1[savedId]=false;
pl2dmt_saddle1[vertexId]=savedId;
dmt1Saddle2PL_[savedId]=vertexId;
break;
}
}
else if(pl2dmt_saddle1[vertexId]==dmt_saddle1Id){
vpath.invalidate();
break;
}
}
}
else
vpath.invalidate();
}
// filter by 2-saddle condition
if(!allowBruteForce and vpath.isValid_){
const Cell& dmt_saddle2=criticalPoints[vpath.destination_].cell_;
const SimplexId dmt_saddle2Id=dmt_saddle2.id_;
if(isSaddle2(dmt_saddle2)){
for(int i=0; i<3; ++i){
SimplexId vertexId;
inputTriangulation_->getTriangleVertex(dmt_saddle2Id, i, vertexId);
if(isPL[vertexId]!=static_cast<char>(CriticalType::Saddle2)) continue;
if(!allowBoundary and
inputTriangulation_->isVertexOnBoundary(vertexId)) continue;
if(pl2dmt_saddle2[vertexId]==-1){
const SimplexId pl_saddle2Id=vertexId;
SimplexId numberOfRemainingSaddles2=0;
SimplexId savedId=-1;
const SimplexId
triangleNumber=inputTriangulation_->getVertexTriangleNumber(pl_saddle2Id);
for(SimplexId j=0; j<triangleNumber; ++j){
SimplexId triangleId;
inputTriangulation_->getVertexTriangle(pl_saddle2Id, j,
triangleId);
if(triangleId!=dmt_saddle2Id and isSaddle2(Cell(2,triangleId))
and isRemovableSaddle2[triangleId]){
++numberOfRemainingSaddles2;
savedId=triangleId;
}
}
if(!numberOfRemainingSaddles2){
isRemovableSaddle2[dmt_saddle2Id]=false;
pl2dmt_saddle2[vertexId]=dmt_saddle2Id;
vpath.invalidate();
break;
}
if(numberOfRemainingSaddles2==1){
isRemovableSaddle2[dmt_saddle2Id]=false;
isRemovableSaddle2[savedId]=false;
pl2dmt_saddle2[vertexId]=savedId;
break;
}
}
else if(pl2dmt_saddle2[vertexId]==dmt_saddle2Id){
vpath.invalidate();
break;
}
}
}
else
vpath.invalidate();
}
if(vpath.isValid_)
reverseDescendingPathOnWall(path);
}
if(vpath.isValid_){
// add persistence pair to collection if necessary
if(CollectPersistencePairs and outputPersistencePairs_){
const Cell& minSaddle1=criticalPoints[vpath.source_].cell_;
const Cell& minSaddle2=criticalPoints[vpath.destination_].cell_;
outputPersistencePairs_->push_back(std::make_tuple(minSaddle1, minSaddle2));
}
const SimplexId sourceId=vpath.source_;
const SimplexId destinationId=vpath.destination_;
// invalidate vpaths connected to source
std::vector<SimplexId> newDestinationIds;
CriticalPoint& source=criticalPoints[sourceId];
for(auto& sourceVPathId : source.vpaths_){
VPath& sourceVPath=vpaths[sourceVPathId];
if(sourceVPath.isValid_ and sourceVPath.destination_!=destinationId){
// save critical point
const SimplexId newDestinationId=sourceVPath.destination_;
newDestinationIds.push_back(newDestinationId);
// clear vpath
sourceVPath.invalidate();
}
}
// invalidate vpaths connected to destination and save the critical
// points to update
std::vector<SimplexId> newSourceIds;
CriticalPoint& destination=criticalPoints[destinationId];
for(auto& destinationVPathId : destination.vpaths_){
VPath& destinationVPath=vpaths[destinationVPathId];
if(destinationVPath.isValid_ and destinationVPath.source_!=sourceId){
// save critical point
const SimplexId newSourceId=destinationVPath.source_;
newSourceIds.push_back(newSourceId);
CriticalPoint& newSource=criticalPoints[newSourceId];
for(auto& newSourceVPathId : newSource.vpaths_){
VPath& newSourceVPath=vpaths[newSourceVPathId];
if(newSourceVPath.isValid_ and
newSourceVPath.destination_!=destinationId){
// clear vpath
newSourceVPath.invalidate();
}
}
// clear vpath
destinationVPath.invalidate();
}
}
// finally invalidate current vpath and critical points
vpath.invalidate();
source.clear();
destination.clear();
// look at the gradient : reconnect locally the critical points
for(auto& newSourceId : newSourceIds){
CriticalPoint& newSource=criticalPoints[newSourceId];
const Cell& saddle1=newSource.cell_;
std::set<SimplexId> saddles2;
const wallId_t savedWallId=wallId;
getAscendingWall(wallId, saddle1, isVisited, nullptr, &saddles2);
++wallId;
for(auto& saddle2Id : saddles2){
const Cell saddle2(2,saddle2Id);
const bool isMultiConnected=getDescendingPathThroughWall(savedWallId,
saddle2, saddle1, isVisited, nullptr);
if(isMultiConnected)
continue;
SimplexId newDestinationId=saddle2Index[saddle2Id];
// connection to a new saddle2 (not present in the graph before)
if(newDestinationId==-1){
if(!isRemovableSaddle2[saddle2Id]) continue;
const SimplexId newCriticalPointId=criticalPoints.size();
saddle2Index[saddle2Id]=newCriticalPointId;
criticalPoints.push_back(CriticalPoint(saddle2));
newDestinationId=newCriticalPointId;
}
CriticalPoint& newDestination=criticalPoints[newDestinationId];
// update vpaths
const SimplexId newVPathId=vpaths.size();
const dataType persistence=getPersistence<dataType>(saddle2, saddle1,
scalars);
vpaths.push_back(VPath(true,-1,newSourceId,newDestinationId,-1,-1,persistence));
// update criticalPoints
newDestination.vpaths_.push_back(newVPathId);
newSource.vpaths_.push_back(newVPathId);
// update set
S.insert(std::make_tuple(persistence,newVPathId,newSource.cell_.id_));
}
}
// look at the gradient : get the links not predicted by the graph
for(auto& newDestinationId : newDestinationIds){
CriticalPoint& newDestination=criticalPoints[newDestinationId];
const Cell& saddle2=newDestination.cell_;
std::set<SimplexId> saddles1;
const wallId_t savedWallId=wallId;
getDescendingWall(wallId, saddle2, isVisited, nullptr, &saddles1);
++wallId;
for(auto& saddle1Id : saddles1){
const Cell saddle1(1,saddle1Id);
std::vector<Cell> path;
const bool isMultiConnected=getAscendingPathThroughWall(savedWallId,
saddle1, saddle2, isVisited, &path);
if(isMultiConnected)
continue;
const SimplexId newSourceId=saddle1Index[saddle1Id];
if(newSourceId==-1)
continue;
CriticalPoint& newSource=criticalPoints[newSourceId];
// check existence of the possibly newVPath in the graph
bool alreadyExists=false;
for(auto& newSourceVPathId : newSource.vpaths_){
const VPath& newSourceVPath=vpaths[newSourceVPathId];
if(newSourceVPath.isValid_ and
newSourceVPath.destination_==newDestinationId){
alreadyExists=true;
break;
}
}
if(alreadyExists)
continue;
// update vpaths
const SimplexId newVPathId=vpaths.size();
const dataType persistence=getPersistence<dataType>(saddle2, saddle1,
scalars);
vpaths.push_back(VPath(true,-1,newSourceId,newDestinationId,-1,-1,persistence));
// update criticalPoints
newDestination.vpaths_.push_back(newVPathId);
newSource.vpaths_.push_back(newVPathId);
// update set
S.insert(std::make_tuple(persistence,newVPathId,newSource.cell_.id_));
}
}
}
++numberOfIterations;
}
{
std::stringstream msg;
msg << "[DiscreteGradient] Processing of the vpaths :\t" <<
t.getElapsedTime() << " s." << std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType>
int DiscreteGradient::simplifySaddleSaddleConnections2(const
std::vector<std::pair<SimplexId,char>>& criticalPoints,
const std::vector<char>& isPL,
const int iterationThreshold,
const bool allowBoundary,
const bool allowBruteForce,
const bool returnSaddleConnectors){
Timer t;
// Part 0 : get removable cells
std::vector<char> isRemovableSaddle1;
std::vector<SimplexId> pl2dmt_saddle1(numberOfVertices_, -1);
getRemovableSaddles1<dataType>(criticalPoints, allowBoundary,
isRemovableSaddle1, pl2dmt_saddle1);
std::vector<char> isRemovableSaddle2;
std::vector<SimplexId> pl2dmt_saddle2(numberOfVertices_, -1);
getRemovableSaddles2<dataType>(criticalPoints, allowBoundary,
isRemovableSaddle2, pl2dmt_saddle2);
// Part 1 : initialization
std::vector<VPath> vpaths;
std::vector<CriticalPoint> dmt_criticalPoints;
std::vector<SimplexId> saddle1Index;
std::vector<SimplexId> saddle2Index;
initializeSaddleSaddleConnections2<dataType>(isRemovableSaddle1,
isRemovableSaddle2,
allowBruteForce,
vpaths,
dmt_criticalPoints,
saddle1Index,
saddle2Index);
// Part 2 : push the vpaths and order by persistence
SaddleSaddleVPathComparator<dataType> cmp_f;
std::set<std::tuple<dataType,SimplexId,SimplexId>, SaddleSaddleVPathComparator<dataType>>
S(cmp_f);
orderSaddleSaddleConnections2<dataType>(vpaths, dmt_criticalPoints, S);
// Part 3 : process the vpaths
processSaddleSaddleConnections2<dataType>(iterationThreshold,
isPL,
allowBoundary,
allowBruteForce,
returnSaddleConnectors,
S,
pl2dmt_saddle1,
pl2dmt_saddle2,
isRemovableSaddle1,
isRemovableSaddle2,
vpaths,
dmt_criticalPoints,
saddle1Index,
saddle2Index);
{
std::stringstream msg;
msg << "[DiscreteGradient] Saddle-Saddle pairs simplified in "
<< t.getElapsedTime() << " s, "<< threadNumber_ << " thread(s)." <<
std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::filterSaddleConnectors(const bool allowBoundary){
const bool allowBruteForce=false;
const bool returnSaddleConnectors=true;
// get the node type of a contour tree node (for compatibility with
// ScalarFieldCriticalPoints)
auto getNodeType=[&](const ftm::FTMTree_MT* tree, const ftm::Node* node){
const int upDegree = node->getNumberOfUpSuperArcs();
const int downDegree = node->getNumberOfDownSuperArcs();
const int degree = upDegree + downDegree;
// saddle point
if (degree > 1) {
if (upDegree == 2 and downDegree == 1)
return 2;
else if (upDegree == 1 and downDegree == 2)
return 1;
}
// local extremum
else {
if (upDegree)
return 0;
else
return 3;
}
return -1;
};
std::vector<std::pair<SimplexId,char>> cpset;
idType* const offsets=static_cast<idType*>(inputOffsets_);
const dataType* const scalars=static_cast<dataType*>(inputScalarField_);
ftm::FTMTree contourTree;
contourTree.setDebugLevel(debugLevel_);
contourTree.setupTriangulation(inputTriangulation_, false);
contourTree.setVertexScalars(scalars);
contourTree.setTreeType(ftm::TreeType::Contour);
contourTree.setVertexSoSoffsets(offsets);
contourTree.setThreadNumber(threadNumber_);
contourTree.setSegmentation(false);
contourTree.build<dataType,SimplexId>();
ftm::FTMTree_MT* tree=contourTree.getTree(ftm::TreeType::Contour);
const SimplexId numberOfNodes=tree->getNumberOfNodes();
for (SimplexId nodeId = 0; nodeId < numberOfNodes; ++nodeId) {
const ftm::Node* node = tree->getNode(nodeId);
const SimplexId vertexId = node->getVertexId();
cpset.push_back(std::make_pair(vertexId, getNodeType(tree,node)));
}
std::vector<char> isPL;
getCriticalPointMap(cpset, isPL);
simplifySaddleSaddleConnections1<dataType>(cpset, isPL,
IterationThreshold, allowBoundary, allowBruteForce,
returnSaddleConnectors);
simplifySaddleSaddleConnections2<dataType>(cpset, isPL,
IterationThreshold, allowBoundary, allowBruteForce,
returnSaddleConnectors);
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::reverseGradient(const
std::vector<std::pair<SimplexId,char>>& criticalPoints){
Timer t;
const bool allowBoundary=true;
const bool returnSaddleConnectors=false;
bool allowBruteForce=false;
std::vector<char> isPL;
getCriticalPointMap(criticalPoints, isPL);
dmt1Saddle2PL_.resize(inputTriangulation_->getNumberOfEdges());
std::fill(dmt1Saddle2PL_.begin(), dmt1Saddle2PL_.end(), -1);
if(ReverseSaddleMaximumConnection)
simplifySaddleMaximumConnections<dataType>(criticalPoints, isPL,
IterationThreshold, allowBoundary, allowBruteForce);
if(dimensionality_==3 and ReverseSaddleSaddleConnection){
simplifySaddleSaddleConnections1<dataType>(criticalPoints, isPL,
IterationThreshold, allowBoundary, allowBruteForce,
returnSaddleConnectors);
simplifySaddleSaddleConnections2<dataType>(criticalPoints, isPL,
IterationThreshold, allowBoundary, allowBruteForce,
returnSaddleConnectors);
}
allowBruteForce=true;
if(ReverseSaddleMaximumConnection)
simplifySaddleMaximumConnections<dataType>(criticalPoints, isPL,
IterationThreshold, allowBoundary, allowBruteForce);
if(dimensionality_==3 and ReverseSaddleSaddleConnection){
simplifySaddleSaddleConnections1<dataType>(criticalPoints, isPL,
IterationThreshold, allowBoundary, allowBruteForce,
returnSaddleConnectors);
simplifySaddleSaddleConnections2<dataType>(criticalPoints, isPL,
IterationThreshold, allowBoundary, allowBruteForce,
returnSaddleConnectors);
}
if(dimensionality_==3 and ReverseSaddleMaximumConnection and
ReverseSaddleSaddleConnection and ReturnSaddleConnectors)
filterSaddleConnectors<dataType, idType>(allowBoundary);
{
std::stringstream msg;
msg << "[DiscreteGradient] Gradient reversed in "
<< t.getElapsedTime() << " s. (" << threadNumber_
<< " thread(s))."
<< std::endl;
dMsg(std::cout, msg.str(), timeMsg);
}
return 0;
}
template <typename dataType, typename idType>
int DiscreteGradient::reverseGradient(){
std::vector<std::pair<SimplexId,char>> criticalPoints;
// get the PL critical points
if(ReverseSaddleMaximumConnection or ReverseSaddleSaddleConnection){
const idType* const offsets=static_cast<idType*>(inputOffsets_);
std::vector<SimplexId> sosOffsets(numberOfVertices_);
for(SimplexId i=0; i<numberOfVertices_; ++i)
sosOffsets[i]=offsets[i];
ScalarFieldCriticalPoints<dataType> scp;
scp.setDebugLevel(debugLevel_);
scp.setThreadNumber(threadNumber_);
scp.setDomainDimension(dimensionality_);
scp.setScalarValues(inputScalarField_);
scp.setVertexNumber(numberOfVertices_);
scp.setSosOffsets(&sosOffsets);
scp.setupTriangulation(inputTriangulation_);
scp.setOutput(&criticalPoints);
scp.execute();
}
// print number of critical cells
{
// foreach dimension
const int numberOfDimensions=getNumberOfDimensions();
std::vector<SimplexId> numberOfDMTCriticalPointsByDimension(numberOfDimensions,0);
for(int i=0; i<numberOfDimensions; ++i){
// foreach cell of that dimension
const SimplexId numberOfCells=getNumberOfCells(i);
for(SimplexId j=0; j<numberOfCells; ++j){
const Cell cell(i,j);
if(isCellCritical(cell))
++numberOfDMTCriticalPointsByDimension[i];
}
}
std::vector<SimplexId> numberOfPLInteriorCriticalPoints(numberOfDimensions,0);
for(auto& criticalPoint : criticalPoints){
const SimplexId criticalPointId=criticalPoint.first;
const char criticalPointType=criticalPoint.second;
if(!inputTriangulation_->isVertexOnBoundary(criticalPointId) and
criticalPointType!=static_cast<char>(CriticalType::Regular))
++numberOfPLInteriorCriticalPoints[criticalPointType];
}
{
std::stringstream msg;
for(int i=0; i<numberOfDimensions; ++i){
msg << "[DiscreteGradient] " << numberOfDMTCriticalPointsByDimension[i]
<< " " << i << "-cell(s)";
msg << " and " << numberOfPLInteriorCriticalPoints[i] << " interior PL."
<< std::endl;
}
dMsg(std::cout, msg.str(), infoMsg);
}
}
reverseGradient<dataType,idType>(criticalPoints);
return 0;
}
#endif // DISCRETEGRADIENT_TPL_H
| 35.729415 | 131 | 0.608381 |
8e63dc7b2c766ff83cd7e3932015f89793461ad0 | 16,855 | h | C | src/cppNGS-TEST/SomaticVariantInterpreter_Test.h | BeneKenobi/ngs-bits | cf849deb1c80e87b734d748f37f5878536277386 | [
"MIT"
] | 85 | 2016-04-26T17:24:20.000Z | 2022-03-11T12:33:39.000Z | src/cppNGS-TEST/SomaticVariantInterpreter_Test.h | BeneKenobi/ngs-bits | cf849deb1c80e87b734d748f37f5878536277386 | [
"MIT"
] | 104 | 2016-08-09T22:18:32.000Z | 2022-03-31T12:39:12.000Z | src/cppNGS-TEST/SomaticVariantInterpreter_Test.h | BeneKenobi/ngs-bits | cf849deb1c80e87b734d748f37f5878536277386 | [
"MIT"
] | 28 | 2016-05-10T14:34:20.000Z | 2021-10-14T07:22:39.000Z | #ifndef SOMATICVARIANTINTERPRETER_TEST_H
#define SOMATICVARIANTINTERPRETER_TEST_H
#include "TestFramework.h"
#include "SomaticVariantInterpreter.h"
TEST_CLASS(SomaticVariantInterpreter_Test)
{
Q_OBJECT
private slots:
void SomaticViccDataTest()
{
SomaticViccData input_data;
IS_TRUE(input_data.isValid());
input_data.known_oncogenic_aa = SomaticViccData::State::VICC_TRUE;
input_data.located_in_canerhotspot = SomaticViccData::State::VICC_FALSE;
IS_FALSE(input_data.isValid());
S_EQUAL( input_data.configAsMap()["known_oncogenic_aa"], "TRUE" );
S_EQUAL( input_data.configAsMap()["located_in_canerhotspot"], "FALSE" );
input_data.located_in_canerhotspot = SomaticViccData::State::NOT_APPLICABLE;
IS_TRUE(input_data.isValid());
S_EQUAL( input_data.configAsMap()["located_in_canerhotspot"], "NOT_APPLICABLE" );
input_data.other_aa_known_oncogenic = SomaticViccData::State::VICC_FALSE;
IS_FALSE(input_data.isValid());
S_EQUAL( input_data.configAsMap()["other_aa_known_oncogenic"], "FALSE" );
//evidence counts
input_data = SomaticViccData();
I_EQUAL(input_data.strongEvidenceCount(), 0);
input_data.known_oncogenic_aa = SomaticViccData::State::VICC_TRUE;
input_data.strong_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(input_data.strongEvidenceCount(), 2);
I_EQUAL(input_data.moderateEvidenceCount(), 0);
input_data.absent_from_controls = SomaticViccData::State::VICC_TRUE;
input_data.protein_length_change = SomaticViccData::State::VICC_TRUE;
input_data.weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(input_data.moderateEvidenceCount(), 3);
I_EQUAL(input_data.supportingEvidenceCount(), 0);
input_data.computational_evidence = SomaticViccData::State::VICC_TRUE;
I_EQUAL(input_data.supportingEvidenceCount(), 1);
}
void viccRulesOncogenic()
{
SomaticViccData input_data;
//Very strong evidence and 1x strong evidence
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//Very strong evidence and >=2 moderate
input_data = SomaticViccData();
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.located_in_canerhotspot = SomaticViccData::State::VICC_TRUE;
input_data.absent_from_controls = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//Very strong evidence and >=1 moderate and >=1 supporting
input_data = SomaticViccData();
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.protein_length_change = SomaticViccData::State::VICC_TRUE;
input_data.very_weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//Very strong evidence and and >=2 supporting
input_data = SomaticViccData();
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.computational_evidence = SomaticViccData::State::VICC_TRUE;
input_data.mutation_in_gene_with_etiology = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//>=2 strong evidence
input_data = SomaticViccData();
input_data.strong_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
input_data.known_oncogenic_aa = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//1x strong evidence and >= 3 moderate
input_data = SomaticViccData();
input_data.known_oncogenic_aa = SomaticViccData::State::VICC_TRUE;
input_data.protein_length_change = SomaticViccData::State::VICC_TRUE;
input_data.weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
input_data.located_in_canerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//1x strong and >=2xmoderate and >=2x supporting
input_data = SomaticViccData();
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.absent_from_controls = SomaticViccData::State::VICC_TRUE;
input_data.other_aa_known_oncogenic = SomaticViccData::State::VICC_TRUE;
input_data.very_weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
input_data.mutation_in_gene_with_etiology = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//1x strong and >=1xmoderate and >=3x supporting
input_data = SomaticViccData();
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.protein_length_change = SomaticViccData::State::VICC_TRUE;
input_data.computational_evidence = SomaticViccData::State::VICC_TRUE;
input_data.mutation_in_gene_with_etiology = SomaticViccData::State::VICC_TRUE;
input_data.very_weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
}
void viccRulesLikelyOncogenic()
{
SomaticViccData input_data;
//1x very strong and >=1x moderate
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.other_aa_known_oncogenic = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_ONCOGENIC);
//1x strong and >=1x moderate
input_data = SomaticViccData();
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_ONCOGENIC);
//1x strong and >=2x supporting
input_data = SomaticViccData();
input_data.known_oncogenic_aa = SomaticViccData::State::VICC_TRUE;
input_data.mutation_in_gene_with_etiology = SomaticViccData::State::VICC_TRUE;
input_data.very_weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_ONCOGENIC);
//>=3x moderate
input_data = SomaticViccData();
input_data.other_aa_known_oncogenic = SomaticViccData::State::VICC_TRUE;
input_data.absent_from_controls = SomaticViccData::State::VICC_TRUE;
input_data.weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_ONCOGENIC);
//>=2x moderate and >=2x supporting
input_data = SomaticViccData();
input_data.other_aa_known_oncogenic = SomaticViccData::State::VICC_TRUE;
input_data.absent_from_controls = SomaticViccData::State::VICC_TRUE;
input_data.computational_evidence = SomaticViccData::State::VICC_TRUE;
input_data.mutation_in_gene_with_etiology = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_ONCOGENIC);
//>=1x moderate and >=3x supportung
input_data = SomaticViccData();
input_data.located_in_canerhotspot = SomaticViccData::State::VICC_TRUE;
input_data.computational_evidence = SomaticViccData::State::VICC_TRUE;
input_data.mutation_in_gene_with_etiology = SomaticViccData::State::VICC_TRUE;
input_data.very_weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_ONCOGENIC);
}
void viccRulesBenign()
{
SomaticViccData input_data;
//1x very strong evidence
input_data.very_high_maf = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::BENIGN);
//2x strong evidence
input_data = SomaticViccData();
input_data.benign_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.high_maf = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::BENIGN);
}
void viccRulesLikelyBenign()
{
SomaticViccData input_data;
//1x strong evidence and <=2x supporting evidence
input_data.high_maf = SomaticViccData::State::VICC_TRUE;
input_data.synonymous_mutation = SomaticViccData::State::VICC_TRUE;
input_data.benign_computational_evidence = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_BENIGN);
}
void viccRulesUncertainSignificance()
{
SomaticViccData input_data;
//1xvery strong oncogenic and nothing else = uncertain
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
//1x strong and 1x supporting oncogenic = uncertain
input_data = SomaticViccData();
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.computational_evidence = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
//2x moderate oncogenic = uncertain
input_data = SomaticViccData();
input_data.absent_from_controls = SomaticViccData::State::VICC_TRUE;
input_data.protein_length_change = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
//2x supporting benign = uncertain
input_data = SomaticViccData();
input_data.benign_computational_evidence = SomaticViccData::State::VICC_TRUE;
input_data.synonymous_mutation = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
}
//tests where options for benign and oncogeinc rules apply positively
void viccScore()
{
SomaticViccData input_data;
//oncogenic and not benign/not likely benign
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::ONCOGENIC);
//likely oncogenic and not benign/not likely benign
input_data = SomaticViccData();
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.weak_cancerhotspot = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_ONCOGENIC);
//oncogenic and benign
input_data = SomaticViccData();
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.very_high_maf = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
//oncogenic and likely benign
input_data = SomaticViccData();
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.oncogenic_functional_studies = SomaticViccData::State::VICC_TRUE;
input_data.high_maf = SomaticViccData::State::VICC_TRUE;
input_data.synonymous_mutation = SomaticViccData::State::VICC_TRUE;
input_data.benign_computational_evidence = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
//likely oncogenic and benign
input_data = SomaticViccData();
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.other_aa_known_oncogenic = SomaticViccData::State::VICC_TRUE;
input_data.very_high_maf = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
//likely oncogenic and likely benign
input_data = SomaticViccData();
input_data.null_mutation_in_tsg = SomaticViccData::State::VICC_TRUE;
input_data.other_aa_known_oncogenic = SomaticViccData::State::VICC_TRUE;
input_data.high_maf = SomaticViccData::State::VICC_TRUE;
input_data.synonymous_mutation = SomaticViccData::State::VICC_TRUE;
input_data.benign_computational_evidence = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::UNCERTAIN_SIGNIFICANCE);
//benign and not oncogenic
input_data = SomaticViccData();
input_data.very_high_maf = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::BENIGN);
//likely benign and not oncogneic
input_data = SomaticViccData();
input_data.high_maf = SomaticViccData::State::VICC_TRUE;
input_data.synonymous_mutation = SomaticViccData::State::VICC_TRUE;
input_data.benign_computational_evidence = SomaticViccData::State::VICC_TRUE;
I_EQUAL(SomaticVariantInterpreter::viccScore(input_data), SomaticVariantInterpreter::Result::LIKELY_BENIGN);
}
void predictViccParameters()
{
VariantList vl;
vl.load(TESTDATA("data_in/SomaticVariantInterpreter_predict.GSvar"));
SomaticViccData predicted_params;
//frameshift, but no TSG
predicted_params = SomaticVariantInterpreter::predictViccValue(vl, vl[0]);
I_EQUAL(predicted_params.null_mutation_in_tsg, SomaticViccData::State::VICC_FALSE);
//variant is not strong cancerhotspot
I_EQUAL(predicted_params.strong_cancerhotspot, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.absent_from_controls, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.protein_length_change, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.weak_cancerhotspot, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.computational_evidence, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.very_weak_cancerhotspot, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.very_high_maf, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.benign_functional_studies, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.high_maf, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.synonymous_mutation, SomaticViccData::State::VICC_FALSE);
//TSG and frameshift
predicted_params = SomaticVariantInterpreter::predictViccValue(vl, vl[1]);
I_EQUAL(predicted_params.null_mutation_in_tsg, SomaticViccData::State::VICC_TRUE);
//clinvar class 5 and CMC classification: os1 applies, strong cancerhotspot: os3 applies
predicted_params = SomaticVariantInterpreter::predictViccValue(vl, vl[2]);
I_EQUAL(predicted_params.known_oncogenic_aa, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.strong_cancerhotspot, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.absent_from_controls, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.computational_evidence, SomaticViccData::State::VICC_TRUE);
//clinvar class 5 and no CMC classification: os1 does not apply, strong cancerhotspot: os3 applies
predicted_params = SomaticVariantInterpreter::predictViccValue(vl, vl[3]);
I_EQUAL(predicted_params.known_oncogenic_aa, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.strong_cancerhotspot, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.absent_from_controls, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.weak_cancerhotspot, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.computational_evidence, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.very_high_maf, SomaticViccData::State::VICC_FALSE);
I_EQUAL(predicted_params.high_maf, SomaticViccData::State::VICC_TRUE);
//benign variant
predicted_params = SomaticVariantInterpreter::predictViccValue(vl, vl[4]);
I_EQUAL(predicted_params.very_high_maf, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.benign_functional_studies, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.high_maf, SomaticViccData::State::VICC_TRUE);
I_EQUAL(predicted_params.synonymous_mutation, SomaticViccData::State::VICC_TRUE);
}
};
#endif // SOMATICVARIANTINTERPRETER_TEST_H
| 50.16369 | 119 | 0.817621 |
b83c0128e5cfa420a273dc9b5dc0710e5a5c430f | 1,286 | h | C | logic/mapping/vector2.h | ARDev1161/AmurClient | 5348f05180c15995869d03c07de65513cffaf58e | [
"Apache-2.0"
] | 1 | 2020-12-13T09:49:24.000Z | 2020-12-13T09:49:24.000Z | logic/mapping/vector2.h | ARDev1161/AmurClient | 5348f05180c15995869d03c07de65513cffaf58e | [
"Apache-2.0"
] | null | null | null | logic/mapping/vector2.h | ARDev1161/AmurClient | 5348f05180c15995869d03c07de65513cffaf58e | [
"Apache-2.0"
] | null | null | null | #ifndef VECTOR2_H
#define VECTOR2_H
#include <cmath>
class Vector2
{
int vX;
int vY;
float mod;
public:
Vector2(int _vX, int _vY)
{
vX = _vX;
vX = _vY;
mod = std::sqrt((float)( pow(_vX,2) + pow(_vY, 2) ));
}
int getX()
{
return vX;
}
int getY()
{
return vY;
}
float getMod()
{
return mod;
}
static Vector2 v2sum(Vector2 v1, Vector2 v2)
{
return Vector2(v1.vX + v2.vX, v1.vY + v2.vY);
}
static Vector2 v2sub(Vector2 v1, Vector2 v2)
{
return Vector2(v1.vX - v2.vX, v1.vY - v2.vY);
}
static int v2scalar(Vector2 v1, Vector2 v2)
{
return (v1.vX * v2.vX + v1.vY * v2.vY);
}
static float v2cos(Vector2 v1, Vector2 v2)
{
return ((v2scalar(v1, v2) / (v1.mod * v2.mod)));
}
static Vector2 v2rotation(Vector2 v1, int teta)
{
float _x = v1.vX * cos(teta) - v1.vY * sin(teta);
float _y = v1.vX * sin(teta) + v1.vY * cos(teta);
return Vector2(ceil(_x), ceil(_y));
}
};
#endif // VECTOR2_H
| 20.741935 | 65 | 0.444012 |
52647e0435a7cb06d96bed2f17e94f14310be684 | 1,932 | h | C | lib/hope/concurrency/async_worker.h | glensand/hope | 775286ad6abb5c7ff3e05ba09c5a429a7b9c0c02 | [
"MIT"
] | 10 | 2020-08-15T16:30:30.000Z | 2021-09-02T04:04:27.000Z | lib/hope/concurrency/async_worker.h | glensand/hope | 775286ad6abb5c7ff3e05ba09c5a429a7b9c0c02 | [
"MIT"
] | null | null | null | lib/hope/concurrency/async_worker.h | glensand/hope | 775286ad6abb5c7ff3e05ba09c5a429a7b9c0c02 | [
"MIT"
] | null | null | null | /* Copyright (C) 2020 - 2021 Gleb Bezborodov - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the MIT license.
*
* You should have received a copy of the MIT license with
* this file. If not, please write to: bezborodoff.gleb@gmail.com, or visit : https://github.com/glensand/hope
*/
#pragma once
#include "hope/concurrency/spsc_queue.h"
#include "hope/concurrency/event.h"
#include <functional>
#include <thread>
namespace hope::concurrency {
class async_worker final
{
public:
using job_t = std::function<void()>;
async_worker() noexcept;
/**
* \brief Starts the asynchronous worker, after calling this method you can add new job
* via add_job
*/
void run() noexcept;
/**
* \brief Synchronously wait while all recently added jobs will be completed, and after it shut down
* inner thread
*/
void stop() noexcept;
/**
* \brief Unlike method "Stop" this method does not wait any operation, and stops worker's activity
* as soon as possible, all the remaining jobs will be discarded
*/
void shut_down() noexcept;
/**
* \brief Adds new job to the operation queue, the job may be an empty function, in this case it will be
* just ignored..
* \param task the job to be added
*/
void add_job(job_t&& task) noexcept;
/**
* \brief Waits while all the recently added jobs will be completed
*/
void wait() const noexcept;
private:
void run_impl() noexcept;
std::atomic_flag m_shut_down;
std::atomic_bool m_wait;
std::atomic_bool m_launched;
spsc_queue<job_t> m_job_queue;
std::thread m_thread_impl;
auto_reset_event m_job_added;
auto_reset_event m_jobs_complete;
};
}
| 28.835821 | 112 | 0.623188 |
59a5fd8de6a2121fdf469d0c849719007036c44d | 18,497 | h | C | Plugins/SciberQuestToolKit/CartesianExtent.h | UV-CDAT/ParaView | 095ac28404a85fd86676491b8952884805842223 | [
"Apache-2.0"
] | null | null | null | Plugins/SciberQuestToolKit/CartesianExtent.h | UV-CDAT/ParaView | 095ac28404a85fd86676491b8952884805842223 | [
"Apache-2.0"
] | null | null | null | Plugins/SciberQuestToolKit/CartesianExtent.h | UV-CDAT/ParaView | 095ac28404a85fd86676491b8952884805842223 | [
"Apache-2.0"
] | null | null | null | /*
____ _ __ ____ __ ____
/ __/___(_) / ___ ____/ __ \__ _____ ___ / /_ / _/__ ____
_\ \/ __/ / _ \/ -_) __/ /_/ / // / -_|_-</ __/ _/ // _ \/ __/
/___/\__/_/_.__/\__/_/ \___\_\_,_/\__/___/\__/ /___/_//_/\__(_)
Copyright 2012 SciberQuest Inc.
*/
#ifndef __CartesianExtent_h
#define __CartesianExtent_h
#include <algorithm>
using std::min;
using std::max;
#include <iostream>
using std::ostream;
/// Index space representation of a cartesian volume.
/**
Represnetation of a cartesian volume and common operations
on it. The implementation is intended to be fast and light
so that it may be used in place of int[6] with little or no
performance penalty.
*/
class CartesianExtent
{
public:
CartesianExtent();
CartesianExtent(const int *ext);
CartesianExtent(int ilo, int ihi, int jlo, int jhi, int klo, int khi);
CartesianExtent(const CartesianExtent &other);
CartesianExtent &operator=(const CartesianExtent &other);
/// \Section Accessors \@{
/**
Element access
*/
int &operator[](int i){ return this->Data[i]; }
const int &operator[](int i) const { return this->Data[i]; }
/**
Set the extent.
*/
void Set(const CartesianExtent &ext);
void Set(const int ext[6]);
void Set(int ilo, int ihi, int jlo, int jhi, int klo, int khi);
void Clear();
/**
Direct access to internal data.
*/
void GetData(int data[6]) const;
int *GetData(){ return this->Data; }
const int *GetData() const { return this->Data; }
/**
Get the start/end index relative to an origin.
*/
void GetStartIndex(int first[3]) const;
void GetStartIndex(int first[3], const int origin[3]) const;
void GetEndIndex(int last[3]) const;
/**
Given the dataset origin (point that coresponds to the index 0,0,0
compute the point at the start of this extent.
*/
void GetLowerBound(
const double X0[3],
const double DX[3],
double lowerBound[3]) const;
void GetLowerBound(
const float *X,
const float *Y,
const float *Z,
double lowerBound[3]) const;
/**
Given the dataset origin (point that coresponds to the index 0,0,0)
and the dataset spacing compute the point at the end of this extent.
*/
void GetUpperBound(
const double X0[3],
const double DX[3],
double upperBound[3]) const;
void GetUpperBound(
const float *X,
const float *Y,
const float *Z,
double upperBound[3]) const;
/**
Given the dataset origin (point that coresponds to the index 0,0,0)
and the dataset spacing compute the point at the end of this extent.
WARNING: this produces incorrect result for 2D data
void GetBounds(
const double X0[3],
const double DX[3],
double bounds[6]) const;
void GetBounds(
const float *X,
const float *Y,
const float *Z,
double bounds[6]) const;
*/
/// \@}
/// \Section Queries \@{
/**
Return true if empty.
*/
int Empty() const;
/**
Test for equivalence.
*/
int operator==(const CartesianExtent &other) const;
/**
Return non-zero if this extent conatins the other.
*/
int Contains(const CartesianExtent &other) const;
/**
Get the number in each direction.
*/
template<typename T>
void Size(T nCells[3]) const;
/**
Get the total number.
*/
size_t Size() const;
/// \@}
/// \Section Operators \@{
/// NOTE in most cases operation on an empty object produces
/// incorrect results. If it an issue query Empty().
/**
In place intersection.
*/
void operator&=(const CartesianExtent &other);
/**
Expand the extents by n.
*/
void Grow(int n);
void Grow(int q, int n);
void GrowLow(int q, int n);
void GrowHigh(int q, int n);
/**
Shrink the extent by n.
*/
void Shrink(int n);
void Shrink(int q, int n);
/**
Translate the bounds by n.
*/
void Shift(); // shift by low corner of this
void Shift(const CartesianExtent &ext); // shift by low corner of the given extent
void Shift(int ni, int nj, int nk); // shift by the given amount
void Shift(int q, int n); // shift by the given amount in the given direction
/**
Divide the extent in half in the given direction. The
operation is done in-place the other half of the split
extent is returned. The retunr will be empty if the split
could not be made.
*/
CartesianExtent Split(int dir);
/**
In-place conversion from cell based to node based extent, and vise-versa.
*/
void CellToNode();
void NodeToCell();
/// \@}
/// \Section Ghost Cell Manipulations \@{
enum {
DIM_MODE_INVALID=-1,
DIM_MODE_3D,
DIM_MODE_2D_XY,
DIM_MODE_2D_XZ,
DIM_MODE_2D_YZ
};
/**
Determine if we have 3D or 2D data and which plane we
are in.
*/
static int GetDimensionMode(
const CartesianExtent &problemDomain,
int nGhosts);
static int GetDimensionMode(
const CartesianExtent &problemDomain);
/**
Get the number in each direction.
*/
template<typename T>
static
void Size(const CartesianExtent &ext, T nCells[3]);
/**
Get the total number.
*/
static
size_t Size(const CartesianExtent &ext);
/**
Add or remove ghost cells. If a problem domain is
provided then the result is clipled to be within the
problem domain.
*/
static CartesianExtent Grow(
const CartesianExtent &inputExt,
int nGhosts,
int mode);
static CartesianExtent Grow(
const CartesianExtent &inputExt,
const CartesianExtent &problemDomain,
int nGhosts,
int mode);
static CartesianExtent GrowLow(
const CartesianExtent &ext,
int q,
int n,
int mode);
static CartesianExtent GrowHigh(
const CartesianExtent &ext,
int q,
int n,
int mode);
/**
Remove ghost cells. If a problem domain is
provided the input is pinned at the domain.
*/
static CartesianExtent Shrink(
const CartesianExtent &inputExt,
const CartesianExtent &problemDomain,
int nGhosts,
int mode);
static CartesianExtent Shrink(
const CartesianExtent &inputExt,
int nGhosts,
int mode);
/**
Convert from point extent to cell extent
while respecting the dimensionality of the data.
*/
static CartesianExtent NodeToCell(
const CartesianExtent &inputExt,
int mode);
/**
Convert from cell extent to point extent
while respecting the dimensionality of the data.
*/
static CartesianExtent CellToNode(
const CartesianExtent &inputExt,
int mode);
/**
shift by the given amount while respecting mode
*/
static void Shift(int *ijk, int n, int mode);
static void Shift(int *ijk, int *n, int mode);
/**
Given the dataset origin (point that coresponds to the index 0,0,0
compute the point at the start of this extent.
*/
static void GetLowerBound(
const CartesianExtent &ext,
const double X0[3],
const double DX[3],
double lowerBound[3]);
static void GetLowerBound(
const CartesianExtent &ext,
const float *X,
const float *Y,
const float *Z,
double lowerBound[3]);
/**
Given the dataset origin (point that coresponds to the index 0,0,0)
and the dataset spacing compute the point at the end of this extent.
respecting mode
*/
static void GetBounds(
const CartesianExtent &ext,
const double X0[3],
const double DX[3],
int mode,
double bounds[6]);
static void GetBounds(
const CartesianExtent &ext,
const float *X,
const float *Y,
const float *Z,
int mode,
double bounds[6]);
/// \@}
private:
int Data[6];
};
ostream &operator<<(ostream &os, const CartesianExtent &ext);
//-----------------------------------------------------------------------------
inline
CartesianExtent::CartesianExtent()
{
this->Clear();
}
//-----------------------------------------------------------------------------
inline
CartesianExtent::CartesianExtent(const int ext[6])
{
this->Set(ext);
}
//-----------------------------------------------------------------------------
inline
CartesianExtent::CartesianExtent(
int ilo,
int ihi,
int jlo,
int jhi,
int klo,
int khi)
{
this->Set(ilo,ihi,jlo,jhi,klo,khi);
}
//-----------------------------------------------------------------------------
inline
CartesianExtent::CartesianExtent(const CartesianExtent &other)
{
*this=other;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Set(const CartesianExtent &other)
{
this->Set(other.GetData());
}
//-----------------------------------------------------------------------------
inline
CartesianExtent &CartesianExtent::operator=(const CartesianExtent &other)
{
if (&other==this)
{
return *this;
}
this->Set(other);
return *this;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Set(const int ext[6])
{
Data[0]=ext[0];
Data[1]=ext[1];
Data[2]=ext[2];
Data[3]=ext[3];
Data[4]=ext[4];
Data[5]=ext[5];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Set(int ilo, int ihi, int jlo, int jhi, int klo, int khi)
{
int I[6]={ilo,ihi,jlo,jhi,klo,khi};
this->Set(I);
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Clear()
{
this->Set(1,0,1,0,1,0);
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetData(int data[6]) const
{
data[0]=this->Data[0];
data[1]=this->Data[1];
data[2]=this->Data[2];
data[3]=this->Data[3];
data[4]=this->Data[4];
data[5]=this->Data[5];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetLowerBound(
const double X0[3],
const double DX[3],
double lowerBound[3]) const
{
lowerBound[0]=X0[0]+this->Data[0]*DX[0];
lowerBound[1]=X0[1]+this->Data[2]*DX[1];
lowerBound[2]=X0[2]+this->Data[4]*DX[2];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetLowerBound(
const float *X,
const float *Y,
const float *Z,
double lowerBound[3]) const
{
lowerBound[0]=X[this->Data[0]];
lowerBound[1]=Y[this->Data[2]];
lowerBound[2]=Z[this->Data[4]];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetUpperBound(
const double X0[3],
const double DX[3],
double upperBound[3]) const
{
int nCells[3];
this->Size(nCells);
double extX0[3];
this->GetLowerBound(X0,DX,extX0);
upperBound[0]=extX0[0]+nCells[0]*DX[0];
upperBound[1]=extX0[1]+nCells[1]*DX[1];
upperBound[2]=extX0[2]+nCells[2]*DX[2];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetUpperBound(
const float *X,
const float *Y,
const float *Z,
double upperBound[3]) const
{
upperBound[0]=X[this->Data[1]+1];
upperBound[1]=Y[this->Data[3]+1];
upperBound[2]=Z[this->Data[5]+1];
}
/*
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetBounds(
const double X0[3],
const double DX[3],
double bounds[6]) const
{
int nCells[3];
this->Size(nCells);
double extX0[3];
this->GetLowerBound(X0,DX,extX0);
bounds[0]=extX0[0];
bounds[1]=extX0[0]+nCells[0]*DX[0];
bounds[2]=extX0[1];
bounds[3]=extX0[1]+nCells[1]*DX[1];
bounds[4]=extX0[2];
bounds[5]=extX0[2]+nCells[2]*DX[2];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetBounds(
const float *X,
const float *Y,
const float *Z,
double bounds[6]) const
{
bounds[0]=X[this->Data[0]];
bounds[1]=X[this->Data[1]+1];
bounds[2]=Y[this->Data[2]];
bounds[3]=Y[this->Data[3]+1];
bounds[4]=Z[this->Data[4]];
bounds[5]=Z[this->Data[5]+1];
}
*/
//-----------------------------------------------------------------------------
template<typename T>
void CartesianExtent::Size(T nCells[3]) const
{
CartesianExtent::Size(*this,nCells);
}
//-----------------------------------------------------------------------------
inline
size_t CartesianExtent::Size() const
{
return CartesianExtent::Size(*this);
}
//-----------------------------------------------------------------------------
template<typename T>
void CartesianExtent::Size(const CartesianExtent &ext, T nCells[3])
{
nCells[0]=ext[1]-ext[0]+1;
nCells[1]=ext[3]-ext[2]+1;
nCells[2]=ext[5]-ext[4]+1;
}
//-----------------------------------------------------------------------------
inline
size_t CartesianExtent::Size(const CartesianExtent &ext)
{
return
(ext[1]-ext[0]+1)
*(ext[3]-ext[2]+1)
*(ext[5]-ext[4]+1);
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetStartIndex(int first[3]) const
{
first[0]=this->Data[0];
first[1]=this->Data[2];
first[2]=this->Data[4];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetStartIndex(int first[3], const int origin[3]) const
{
first[0]=this->Data[0]-origin[0];
first[1]=this->Data[2]-origin[1];
first[2]=this->Data[4]-origin[2];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GetEndIndex(int last[3]) const
{
last[0]=this->Data[1];
last[1]=this->Data[3];
last[2]=this->Data[5];
}
//-----------------------------------------------------------------------------
inline
int CartesianExtent::Empty() const
{
if ( this->Data[0]>this->Data[1]
|| this->Data[2]>this->Data[3]
|| this->Data[4]>this->Data[5])
{
return 1;
}
return 0;
}
//-----------------------------------------------------------------------------
inline
int CartesianExtent::operator==(const CartesianExtent &other) const
{
if ( (this->Data[0]==other.Data[0])
&& (this->Data[1]==other.Data[1])
&& (this->Data[2]==other.Data[2])
&& (this->Data[3]==other.Data[3])
&& (this->Data[4]==other.Data[4])
&& (this->Data[5]==other.Data[5]) )
{
return 1;
}
return 0;
}
//-----------------------------------------------------------------------------
inline
int CartesianExtent::Contains(const CartesianExtent &other) const
{
if ( (this->Data[0]<=other.Data[0])
&& (this->Data[1]>=other.Data[1])
&& (this->Data[2]<=other.Data[2])
&& (this->Data[3]>=other.Data[3])
&& (this->Data[4]<=other.Data[4])
&& (this->Data[5]>=other.Data[5]) )
{
return 1;
}
return 0;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::operator&=(const CartesianExtent &other)
{
if (this->Empty())
{
return;
}
if (other.Empty())
{
this->Clear();
return;
}
this->Data[0]=max(this->Data[0],other.Data[0]);
this->Data[1]=min(this->Data[1],other.Data[1]);
this->Data[2]=max(this->Data[2],other.Data[2]);
this->Data[3]=min(this->Data[3],other.Data[3]);
this->Data[4]=max(this->Data[4],other.Data[4]);
this->Data[5]=min(this->Data[5],other.Data[5]);
if (this->Empty())
{
this->Clear();
}
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Grow(int n)
{
this->Data[0]-=n;
this->Data[1]+=n;
this->Data[2]-=n;
this->Data[3]+=n;
this->Data[4]-=n;
this->Data[5]+=n;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Grow(int q, int n)
{
q*=2;
this->Data[q ]-=n;
this->Data[q+1]+=n;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GrowLow(int q, int n)
{
this->Data[2*q]-=n;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::GrowHigh(int q, int n)
{
this->Data[2*q+1]+=n;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Shrink(int n)
{
this->Data[0]+=n;
this->Data[1]-=n;
this->Data[2]+=n;
this->Data[3]-=n;
this->Data[4]+=n;
this->Data[5]-=n;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Shrink(int q, int n)
{
q*=2;
this->Data[q ]+=n;
this->Data[q+1]-=n;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Shift(int ni, int nj, int nk)
{
this->Data[0]+=ni;
this->Data[1]+=ni;
this->Data[2]+=nj;
this->Data[3]+=nj;
this->Data[4]+=nk;
this->Data[5]+=nk;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Shift(int q, int n)
{
q*=2;
this->Data[q ]+=n;
this->Data[q+1]+=n;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Shift(const CartesianExtent &other)
{
for (int q=0; q<3; ++q)
{
int qq=q*2;
int n=-other[qq];
this->Data[qq ]+=n;
this->Data[qq+1]+=n;
}
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::Shift()
{
for (int q=0; q<3; ++q)
{
int qq=q*2;
int n=-this->Data[qq];
this->Data[qq ]+=n;
this->Data[qq+1]+=n;
}
}
//-----------------------------------------------------------------------------
inline
CartesianExtent CartesianExtent::Split(int dir)
{
CartesianExtent half;
int q=2*dir;
int l=this->Data[q+1]-this->Data[q]+1;
int s=l/2;
if (s)
{
s+=this->Data[q];
half=*this;
half.Data[q]=s;
this->Data[q+1]=s-1;
}
return half;
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::CellToNode()
{
++this->Data[1];
++this->Data[3];
++this->Data[5];
}
//-----------------------------------------------------------------------------
inline
void CartesianExtent::NodeToCell()
{
--this->Data[1];
--this->Data[3];
--this->Data[5];
}
#endif
| 23.063591 | 93 | 0.514516 |
74f94145e445471215068a7f232e162449906d17 | 10,443 | h | C | freebsd4/sys/sys/time.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | freebsd4/sys/sys/time.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | freebsd4/sys/sys/time.h | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /*
* Copyright (c) 1982, 1986, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)time.h 8.5 (Berkeley) 5/4/95
* $FreeBSD: src/sys/sys/time.h,v 1.42 1999/12/29 04:24:48 peter Exp $
*/
#ifndef _SYS_TIME_H_
#define _SYS_TIME_H_
#include <sys/types.h>
/*
* Structure returned by gettimeofday(2) system call,
* and used in other calls.
*/
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* and microseconds */
};
#ifndef _TIMESPEC_DECLARED
#define _TIMESPEC_DECLARED
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* and nanoseconds */
};
#endif
#define TIMEVAL_TO_TIMESPEC(tv, ts) \
do { \
(ts)->tv_sec = (tv)->tv_sec; \
(ts)->tv_nsec = (tv)->tv_usec * 1000; \
} while (0)
#define TIMESPEC_TO_TIMEVAL(tv, ts) \
do { \
(tv)->tv_sec = (ts)->tv_sec; \
(tv)->tv_usec = (ts)->tv_nsec / 1000; \
} while (0)
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of dst correction */
};
#define DST_NONE 0 /* not on dst */
#define DST_USA 1 /* USA style dst */
#define DST_AUST 2 /* Australian style dst */
#define DST_WET 3 /* Western European dst */
#define DST_MET 4 /* Middle European dst */
#define DST_EET 5 /* Eastern European dst */
#define DST_CAN 6 /* Canada */
/*
* Structure used to interface to the machine dependent hardware support
* for timekeeping.
*
* A timecounter is a (hard or soft) binary counter which has two properties:
* * it runs at a fixed, known frequency.
* * it must not roll over in less than (1 + delta)/HZ seconds. "delta"
* is expected to be less than 20 msec, but no hard data has been
* collected on this. 16 bit at 5 MHz (31 msec) is known to work.
*
* get_timecount() reads the counter.
*
* counter_mask removes unimplemented bits from the count value.
*
* frequency is the counter frequency in hz.
*
* name is a short mnemonic name for this counter.
*
* cost is a measure of how long time it takes to read the counter.
*
* adjustment [PPM << 16] which means that the smallest unit of correction
* you can apply amounts to 481.5 usec/year.
*
* scale_micro [2^32 * usec/tick].
* scale_nano_i [ns/tick].
* scale_nano_f [(ns/2^32)/tick].
*
* offset_count is the contents of the counter which corresponds to the
* rest of the offset_* values.
*
* offset_sec [s].
* offset_micro [usec].
* offset_nano [ns/2^32] is misnamed, the real unit is .23283064365...
* attoseconds (10E-18) and before you ask: yes, they are in fact
* called attoseconds, it comes from "atten" for 18 in Danish/Swedish.
*
* Each timecounter must supply an array of three timecounters, this is needed
* to guarantee atomicity in the code. Index zero is used to transport
* modifications, for instance done with sysctl, into the timecounter being
* used in a safe way. Such changes may be adopted with a delay of up to 1/HZ,
* index one & two are used alternately for the actual timekeeping.
*
* 'tc_avail' points to the next available (external) timecounter in a
* circular queue. This is only valid for index 0.
*
* `tc_other' points to the next "work" timecounter in a circular queue,
* i.e., for index i > 0 it points to index 1 + (i - 1) % NTIMECOUNTER.
* We also use it to point from index 0 to index 1.
*
* `tc_tweak' points to index 0.
*/
struct timecounter;
typedef unsigned timecounter_get_t __P((struct timecounter *));
typedef void timecounter_pps_t __P((struct timecounter *));
struct timecounter {
/* These fields must be initialized by the driver. */
timecounter_get_t *tc_get_timecount;
timecounter_pps_t *tc_poll_pps;
unsigned tc_counter_mask;
u_int32_t tc_frequency;
char *tc_name;
void *tc_priv;
/* These fields will be managed by the generic code. */
int64_t tc_adjustment;
u_int32_t tc_scale_micro;
u_int32_t tc_scale_nano_i;
u_int32_t tc_scale_nano_f;
unsigned tc_offset_count;
u_int32_t tc_offset_sec;
u_int32_t tc_offset_micro;
u_int64_t tc_offset_nano;
struct timeval tc_microtime;
struct timespec tc_nanotime;
struct timecounter *tc_avail;
struct timecounter *tc_other;
struct timecounter *tc_tweak;
};
#ifdef _KERNEL
/* Operations on timespecs */
#define timespecclear(tvp) ((tvp)->tv_sec = (tvp)->tv_nsec = 0)
#define timespecisset(tvp) ((tvp)->tv_sec || (tvp)->tv_nsec)
#define timespeccmp(tvp, uvp, cmp) \
(((tvp)->tv_sec == (uvp)->tv_sec) ? \
((tvp)->tv_nsec cmp (uvp)->tv_nsec) : \
((tvp)->tv_sec cmp (uvp)->tv_sec))
#define timespecadd(vvp, uvp) \
do { \
(vvp)->tv_sec += (uvp)->tv_sec; \
(vvp)->tv_nsec += (uvp)->tv_nsec; \
if ((vvp)->tv_nsec >= 1000000000) { \
(vvp)->tv_sec++; \
(vvp)->tv_nsec -= 1000000000; \
} \
} while (0)
#define timespecsub(vvp, uvp) \
do { \
(vvp)->tv_sec -= (uvp)->tv_sec; \
(vvp)->tv_nsec -= (uvp)->tv_nsec; \
if ((vvp)->tv_nsec < 0) { \
(vvp)->tv_sec--; \
(vvp)->tv_nsec += 1000000000; \
} \
} while (0)
/* Operations on timevals. */
#define timevalclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0
#define timevalisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec)
#define timevalcmp(tvp, uvp, cmp) \
(((tvp)->tv_sec == (uvp)->tv_sec) ? \
((tvp)->tv_usec cmp (uvp)->tv_usec) : \
((tvp)->tv_sec cmp (uvp)->tv_sec))
/* timevaladd and timevalsub are not inlined */
#endif /* _KERNEL */
#ifndef _KERNEL /* NetBSD/OpenBSD compatable interfaces */
#define timerclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0
#define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec)
#define timercmp(tvp, uvp, cmp) \
(((tvp)->tv_sec == (uvp)->tv_sec) ? \
((tvp)->tv_usec cmp (uvp)->tv_usec) : \
((tvp)->tv_sec cmp (uvp)->tv_sec))
#define timeradd(tvp, uvp, vvp) \
do { \
(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \
(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \
if ((vvp)->tv_usec >= 1000000) { \
(vvp)->tv_sec++; \
(vvp)->tv_usec -= 1000000; \
} \
} while (0)
#define timersub(tvp, uvp, vvp) \
do { \
(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
if ((vvp)->tv_usec < 0) { \
(vvp)->tv_sec--; \
(vvp)->tv_usec += 1000000; \
} \
} while (0)
#endif
/*
* Names of the interval timers, and structure
* defining a timer setting.
*/
#define ITIMER_REAL 0
#define ITIMER_VIRTUAL 1
#define ITIMER_PROF 2
struct itimerval {
struct timeval it_interval; /* timer interval */
struct timeval it_value; /* current value */
};
/*
* Getkerninfo clock information structure
*/
struct clockinfo {
int hz; /* clock frequency */
int tick; /* micro-seconds per hz tick */
int tickadj; /* clock skew rate for adjtime() */
int stathz; /* statistics clock frequency */
int profhz; /* profiling clock frequency */
};
/* CLOCK_REALTIME and TIMER_ABSTIME are supposed to be in time.h */
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 0
#endif
#define CLOCK_VIRTUAL 1
#define CLOCK_PROF 2
#define TIMER_RELTIME 0x0 /* relative timer */
#ifndef TIMER_ABSTIME
#define TIMER_ABSTIME 0x1 /* absolute timer */
#endif
#ifdef _KERNEL
extern struct timecounter *timecounter;
extern time_t time_second;
void getmicrouptime __P((struct timeval *tv));
void getmicrotime __P((struct timeval *tv));
void getnanouptime __P((struct timespec *tv));
void getnanotime __P((struct timespec *tv));
void init_timecounter __P((struct timecounter *tc));
int itimerdecr __P((struct itimerval *itp, int usec));
int itimerfix __P((struct timeval *tv));
void microuptime __P((struct timeval *tv));
void microtime __P((struct timeval *tv));
void nanouptime __P((struct timespec *ts));
void nanotime __P((struct timespec *ts));
void set_timecounter __P((struct timespec *ts));
void timevaladd __P((struct timeval *, struct timeval *));
void timevalsub __P((struct timeval *, struct timeval *));
int tvtohz __P((struct timeval *));
void update_timecounter __P((struct timecounter *tc));
#else /* !_KERNEL */
#include <time.h>
#include <sys/cdefs.h>
__BEGIN_DECLS
int adjtime __P((const struct timeval *, struct timeval *));
int futimes __P((int, const struct timeval *));
int getitimer __P((int, struct itimerval *));
int gettimeofday __P((struct timeval *, struct timezone *));
int lutimes __P((const char *, const struct timeval *));
int setitimer __P((int, const struct itimerval *, struct itimerval *));
int settimeofday __P((const struct timeval *, const struct timezone *));
int utimes __P((const char *, const struct timeval *));
__END_DECLS
#endif /* !_KERNEL */
#endif /* !_SYS_TIME_H_ */
| 34.016287 | 79 | 0.682275 |
46c401a7ef2b50c2464ed3fe8061b2cdad8b8a3c | 3,097 | h | C | demos/demo1/table.h | zhongjingjogy/hash-accelerated | 0152385a4295874bd09dd34813310b442a7e2aaa | [
"MIT"
] | null | null | null | demos/demo1/table.h | zhongjingjogy/hash-accelerated | 0152385a4295874bd09dd34813310b442a7e2aaa | [
"MIT"
] | null | null | null | demos/demo1/table.h | zhongjingjogy/hash-accelerated | 0152385a4295874bd09dd34813310b442a7e2aaa | [
"MIT"
] | null | null | null | #ifndef Table_H
#define Table_H
#include "hashtable.h"
typedef double (*Function)(double *vars);
class Table
{
public:
Table();
Table(int _dimension);
~Table();
void initialize(int _dimension);
void setfunction(Function _function);
void setlimit(double *_lowerlimit, double *_upperlimit, int *_p);
bool query(int *index, double &value);
bool query(double *vars, double &value);
#ifdef DEBUG
void display();
#endif
private:
// storage table
hashTable<double> SPM;
int dimension;
// lower limit of the variables.
double *lowerlimit;
// upper limit of the variables.
double *upperlimit;
// spacing of the grid space.
double *interval;
// number of points of grid space.
int *p;
Function function;
};
Table::Table(){;}
Table::Table(int _dimension) { initialize(_dimension);}
Table::~Table()
{
delete []p;
delete []lowerlimit;
delete []upperlimit;
delete []interval;
}
void Table::initialize(int _dimension)
{
dimension = _dimension;
lowerlimit = new double[dimension];
upperlimit = new double[dimension];
p = new int[dimension];
interval = new double[dimension];
SPM.initialize(dimension);
}
void Table::setfunction(Function _function) {function = _function;}
void Table::setlimit(double *_lowerlimit, double *_upperlimit, int *_p)
{
for(int i=0; i!=dimension; ++i)
{
lowerlimit[i] = _lowerlimit[i];
upperlimit[i] = _upperlimit[i];
p[i] = _p[i];
interval[i] = (upperlimit[i] - lowerlimit[i])/double(p[i]);
}
}
bool Table::query(int *index, double &value)
{
bool flag = SPM.query(index, value);
if(!flag)
{
double tvalue;
double *vars = new double[dimension];
double s = 0.0;
for(int i=0; i<dimension; ++i)
{
vars[i] = lowerlimit[i] + interval[i]*index[i];
s += vars[i];
}
tvalue = function(vars);
value = tvalue;
SPM.insert(index, tvalue);
}
return flag;
}
bool Table::query(double *vars, double &value)
{
int *index = new int[dimension];
for(int i=0; i!=dimension; ++i)
{
// perform the bounary check
if(vars[i] > upperlimit[i]) vars[i] = upperlimit[i];
else if(vars[i] < lowerlimit[i]) vars[i] = lowerlimit[i];
index[i] = int((vars[i] - lowerlimit[i])/interval[i]);
}
double current = 0.0;
query(index, current);
double result = 0.0;
int *tindex = new int[dimension];
// interpolate the a point with the storage record.
for(int i=0; i<dimension; ++i)
{
for(int j=0; j<dimension; ++j) tindex[j] = index[j];
tindex[i] += 1;
double tvalue;
query(tindex, tvalue);
double grad = (tvalue - current)/interval[i];
double dx = vars[i] - index[i]*interval[i] - lowerlimit[i];
result = result - grad*dx;
}
value = result + current;
delete []tindex;
delete []index;
return false;
}
#ifdef DEBUG
void Table::display()
{
SPM.stat();
}
#endif
#endif
| 23.11194 | 71 | 0.595092 |
94094d2275082e2e12766eaccaf10a6cee07f32a | 284 | h | C | Kiosk/model/SVUtil.h | rkirkendall/SureVoting-iOS-kiosk | 38efb1cc746cf8c938ab5cf64f847db237bbb79b | [
"MIT"
] | 1 | 2015-12-17T22:23:53.000Z | 2015-12-17T22:23:53.000Z | Kiosk/model/SVUtil.h | rkirkendall/SureVoting-iOS-demo | 38efb1cc746cf8c938ab5cf64f847db237bbb79b | [
"MIT"
] | null | null | null | Kiosk/model/SVUtil.h | rkirkendall/SureVoting-iOS-demo | 38efb1cc746cf8c938ab5cf64f847db237bbb79b | [
"MIT"
] | null | null | null | //
// SVUtil.h
// Kiosk
//
// Created by Ricky Kirkendall on 12/12/15.
// Copyright © 2015 SureVoting. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface SVUtil : NSObject
+ (UIColor *)buttonGreen;
+ (UIColor *)voteSelectionGreen;
@end
| 17.75 | 53 | 0.693662 |
e387c20ece7aa86215cc4c8755d7dd813b54b8c9 | 258 | h | C | src/foo/FooPrivateHeader.h | seanmarks/cmake_packages | d6d653401137d275f637629717f573e517269035 | [
"MIT"
] | null | null | null | src/foo/FooPrivateHeader.h | seanmarks/cmake_packages | d6d653401137d275f637629717f573e517269035 | [
"MIT"
] | null | null | null | src/foo/FooPrivateHeader.h | seanmarks/cmake_packages | d6d653401137d275f637629717f573e517269035 | [
"MIT"
] | null | null | null |
#pragma once
#ifndef FOO_PRIVATE_HEADER_H
#define FOO_PRIVATE_HEADER_H
#include <string>
class FooHelper
{
public:
FooHelper() {}
std::string help() const {
return "I'm just here to help Foo";
}
private:
};
#endif // ifndef FOO_PRIVATE_HEADER_H
| 12.285714 | 37 | 0.717054 |
5a60d15cdc5fcdd77a16c0574b672adfbf642e71 | 1,062 | h | C | src/Anggur/Math/Matrix.h | noorwachid/anggur | 88379f9205e969e93ffb23073e8d42fe6288803d | [
"MIT"
] | 1 | 2021-06-07T06:29:43.000Z | 2021-06-07T06:29:43.000Z | Source/Anggur/Math/Matrix.h | NoorWachid/Anggur | 73b14abb238f90d964b9764aa259d8483a5dc593 | [
"MIT"
] | null | null | null | Source/Anggur/Math/Matrix.h | NoorWachid/Anggur | 73b14abb238f90d964b9764aa259d8483a5dc593 | [
"MIT"
] | null | null | null | #pragma once
#include <initializer_list>
#include "Math.h"
namespace Anggur {
class Matrix
{
public:
static const Matrix identity;
static const Matrix zero;
Matrix();
Matrix(const std::initializer_list<float>& list);
Matrix(const Vector& translation, float rotation = 0.0f, const Vector& scale = 1.0f);
void Set(const std::initializer_list<float>& list);
const float* ToFloatPtr() const;
float* ToFloatPtr();
float& operator[](size_t index);
float operator[](size_t index) const;
Matrix operator*(const Matrix& right) const;
Matrix operator+(const Matrix& right) const;
Matrix& operator*=(const Matrix& right);
Matrix& operator+=(const Matrix& right);
Matrix& Translate(const Vector& v);
Matrix& Scale(const Vector& v);
Matrix& Rotate(float theta);
static Matrix CreateTranslation(const Vector& v);
static Matrix CreateScale(const Vector& v);
static Matrix CreateRotation(float theta);
static Matrix CreateInverse(const Matrix& m);
private:
float data[9];
};
}
| 23.086957 | 89 | 0.689266 |
f533ecb66dc86443798469bb66272f6ed27eb638 | 302 | c | C | p1-9/p1.c | kbrose/project_euler | f582ef1887f44628997e05d88253adad0822d6b9 | [
"Unlicense"
] | 1 | 2015-10-11T15:53:00.000Z | 2015-10-11T15:53:00.000Z | p1-9/p1.c | kbrose/project_euler | f582ef1887f44628997e05d88253adad0822d6b9 | [
"Unlicense"
] | null | null | null | p1-9/p1.c | kbrose/project_euler | f582ef1887f44628997e05d88253adad0822d6b9 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
int main()
{
int counter = 0;
int is3 = 3;
int i = 0;
for(i = 0; i < 1000; i+=5){
if(is3 == 3){
is3 = 1;
continue;
}
counter += i;
is3++;
}
for(i = 0; i < 1000; i+=3){
counter += i;
}
printf("sum: %d\n", counter);
return 0;
}
| 11.615385 | 31 | 0.427152 |
dc71953adc2029244a6267a3355690d690148a25 | 33,384 | c | C | libexec/got-fetch-pack/got-fetch-pack.c | ThomasAdam/gameoftrees | f7ee51440384d30a815e951ed3084cb1591f29d3 | [
"0BSD"
] | 1 | 2021-02-25T15:42:42.000Z | 2021-02-25T15:42:42.000Z | libexec/got-fetch-pack/got-fetch-pack.c | ThomasAdam/gameoftrees | f7ee51440384d30a815e951ed3084cb1591f29d3 | [
"0BSD"
] | null | null | null | libexec/got-fetch-pack/got-fetch-pack.c | ThomasAdam/gameoftrees | f7ee51440384d30a815e951ed3084cb1591f29d3 | [
"0BSD"
] | null | null | null | /*
* Copyright (c) 2019 Ori Bernstein <ori@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdint.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sha1.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#include <err.h>
#include "got_compat.h"
#include "got_error.h"
#include "got_object.h"
#include "got_path.h"
#include "got_version.h"
#include "got_fetch.h"
#include "got_reference.h"
#include "got_lib_sha1.h"
#include "got_lib_delta.h"
#include "got_lib_object.h"
#include "got_lib_object_parse.h"
#include "got_lib_privsep.h"
#include "got_lib_pack.h"
#ifndef nitems
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
#endif
struct got_object *indexed;
static int chattygot;
static struct got_object_id zhash = {.sha1={0}};
static const struct got_error *
readn(ssize_t *off, int fd, void *buf, size_t n)
{
ssize_t r;
*off = 0;
while (*off != n) {
r = read(fd, buf + *off, n - *off);
if (r == -1)
return got_error_from_errno("read");
if (r == 0)
return NULL;
*off += r;
}
return NULL;
}
static const struct got_error *
flushpkt(int fd)
{
ssize_t w;
if (chattygot > 1)
fprintf(stderr, "%s: writepkt: 0000\n", getprogname());
w = write(fd, "0000", 4);
if (w == -1)
return got_error_from_errno("write");
if (w != 4)
return got_error(GOT_ERR_IO);
return NULL;
}
/*
* Packet header contains a 4-byte hexstring which specifies the length
* of data which follows.
*/
static const struct got_error *
read_pkthdr(int *datalen, int fd)
{
static const struct got_error *err = NULL;
char lenstr[5];
long len;
char *e;
int n, i;
ssize_t r;
*datalen = 0;
err = readn(&r, fd, lenstr, 4);
if (err)
return err;
if (r == 0) {
/* implicit "0000" */
if (chattygot > 1)
fprintf(stderr, "%s: readpkt: 0000\n", getprogname());
return NULL;
}
if (r != 4)
return got_error_msg(GOT_ERR_BAD_PACKET,
"wrong packet header length");
lenstr[4] = '\0';
for (i = 0; i < 4; i++) {
if (!isprint((unsigned char)lenstr[i]))
return got_error_msg(GOT_ERR_BAD_PACKET,
"unprintable character in packet length field");
}
for (i = 0; i < 4; i++) {
if (!isxdigit((unsigned char)lenstr[i])) {
if (chattygot)
fprintf(stderr, "%s: bad length: '%s'\n",
getprogname(), lenstr);
return got_error_msg(GOT_ERR_BAD_PACKET,
"packet length not specified in hex");
}
}
errno = 0;
len = strtol(lenstr, &e, 16);
if (lenstr[0] == '\0' || *e != '\0')
return got_error(GOT_ERR_BAD_PACKET);
if (errno == ERANGE && (len == LONG_MAX || len == LONG_MIN))
return got_error_msg(GOT_ERR_BAD_PACKET, "bad packet length");
if (len > INT_MAX || len < INT_MIN)
return got_error_msg(GOT_ERR_BAD_PACKET, "bad packet length");
n = len;
if (n == 0)
return NULL;
if (n <= 4)
return got_error_msg(GOT_ERR_BAD_PACKET, "packet too short");
n -= 4;
*datalen = n;
return NULL;
}
static const struct got_error *
readpkt(int *outlen, int fd, char *buf, int buflen)
{
const struct got_error *err = NULL;
int datalen, i;
ssize_t n;
err = read_pkthdr(&datalen, fd);
if (err)
return err;
if (datalen > buflen)
return got_error(GOT_ERR_NO_SPACE);
err = readn(&n, fd, buf, datalen);
if (err)
return err;
if (n != datalen)
return got_error_msg(GOT_ERR_BAD_PACKET, "short packet");
if (chattygot > 1) {
fprintf(stderr, "%s: readpkt: %zd:\t", getprogname(), n);
for (i = 0; i < n; i++) {
if (isprint(buf[i]))
fputc(buf[i], stderr);
else
fprintf(stderr, "[0x%.2x]", buf[i]);
}
fputc('\n', stderr);
}
*outlen = n;
return NULL;
}
static const struct got_error *
writepkt(int fd, char *buf, int nbuf)
{
char len[5];
int i;
ssize_t w;
if (snprintf(len, sizeof(len), "%04x", nbuf + 4) >= sizeof(len))
return got_error(GOT_ERR_NO_SPACE);
w = write(fd, len, 4);
if (w == -1)
return got_error_from_errno("write");
if (w != 4)
return got_error(GOT_ERR_IO);
w = write(fd, buf, nbuf);
if (w == -1)
return got_error_from_errno("write");
if (w != nbuf)
return got_error(GOT_ERR_IO);
if (chattygot > 1) {
fprintf(stderr, "%s: writepkt: %s:\t", getprogname(), len);
for (i = 0; i < nbuf; i++) {
if (isprint(buf[i]))
fputc(buf[i], stderr);
else
fprintf(stderr, "[0x%.2x]", buf[i]);
}
fputc('\n', stderr);
}
return NULL;
}
static void
match_remote_ref(struct got_pathlist_head *have_refs,
struct got_object_id *my_id, char *refname)
{
struct got_pathlist_entry *pe;
/* XXX zero-hash signifies we don't have this ref;
* we should use a flag instead */
memset(my_id, 0, sizeof(*my_id));
TAILQ_FOREACH(pe, have_refs, entry) {
struct got_object_id *id = pe->data;
if (strcmp(pe->path, refname) == 0) {
memcpy(my_id, id, sizeof(*my_id));
break;
}
}
}
static int
match_branch(const char *branch, const char *wanted_branch)
{
if (strncmp(branch, "refs/heads/", 11) != 0)
return 0;
if (strncmp(wanted_branch, "refs/heads/", 11) == 0)
wanted_branch += 11;
return (strcmp(branch + 11, wanted_branch) == 0);
}
static int
match_wanted_ref(const char *refname, const char *wanted_ref)
{
if (strncmp(refname, "refs/", 5) != 0)
return 0;
refname += 5;
/*
* Prevent fetching of references that won't make any
* sense outside of the remote repository's context.
*/
if (strncmp(refname, "got/", 4) == 0)
return 0;
if (strncmp(refname, "remotes/", 8) == 0)
return 0;
if (strncmp(wanted_ref, "refs/", 5) == 0)
wanted_ref += 5;
/* Allow prefix match. */
if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
return 1;
/* Allow exact match. */
return (strcmp(refname, wanted_ref) == 0);
}
static const struct got_error *
tokenize_refline(char **tokens, char *line, int len, int maxtokens)
{
const struct got_error *err = NULL;
char *p;
size_t i, n = 0;
for (i = 0; i < maxtokens; i++)
tokens[i] = NULL;
for (i = 0; n < len && i < maxtokens; i++) {
while (isspace(*line)) {
line++;
n++;
}
p = line;
while (*line != '\0' &&
(!isspace(*line) || i == maxtokens - 1)) {
line++;
n++;
}
tokens[i] = strndup(p, line - p);
if (tokens[i] == NULL) {
err = got_error_from_errno("strndup");
goto done;
}
/* Skip \0 field-delimiter at end of token. */
while (line[0] == '\0' && n < len) {
line++;
n++;
}
}
if (i <= 2)
err = got_error(GOT_ERR_NOT_REF);
done:
if (err) {
int j;
for (j = 0; j < i; j++) {
free(tokens[j]);
tokens[j] = NULL;
}
}
return err;
}
static const struct got_error *
parse_refline(char **id_str, char **refname, char **server_capabilities,
char *line, int len)
{
const struct got_error *err = NULL;
char *tokens[3];
err = tokenize_refline(tokens, line, len, nitems(tokens));
if (err)
return err;
if (tokens[0])
*id_str = tokens[0];
if (tokens[1])
*refname = tokens[1];
if (tokens[2]) {
char *p;
*server_capabilities = tokens[2];
p = strrchr(*server_capabilities, '\n');
if (p)
*p = '\0';
}
return NULL;
}
#define GOT_CAPA_AGENT "agent"
#define GOT_CAPA_OFS_DELTA "ofs-delta"
#define GOT_CAPA_SIDE_BAND_64K "side-band-64k"
#define GOT_SIDEBAND_PACKFILE_DATA 1
#define GOT_SIDEBAND_PROGRESS_INFO 2
#define GOT_SIDEBAND_ERROR_INFO 3
struct got_capability {
const char *key;
const char *value;
};
static const struct got_capability got_capabilities[] = {
{ GOT_CAPA_AGENT, "got/" GOT_VERSION_STR },
{ GOT_CAPA_OFS_DELTA, NULL },
{ GOT_CAPA_SIDE_BAND_64K, NULL },
};
static const struct got_error *
match_capability(char **my_capabilities, const char *capa,
const struct got_capability *mycapa)
{
char *equalsign;
char *s;
equalsign = strchr(capa, '=');
if (equalsign) {
if (strncmp(capa, mycapa->key, equalsign - capa) != 0)
return NULL;
} else {
if (strcmp(capa, mycapa->key) != 0)
return NULL;
}
if (asprintf(&s, "%s %s%s%s",
*my_capabilities != NULL ? *my_capabilities : "",
mycapa->key,
mycapa->value != NULL ? "=" : "",
mycapa->value != NULL? mycapa->value : "") == -1)
return got_error_from_errno("asprintf");
free(*my_capabilities);
*my_capabilities = s;
return NULL;
}
static const struct got_error *
add_symref(struct got_pathlist_head *symrefs, char *capa)
{
const struct got_error *err = NULL;
char *colon, *name = NULL, *target = NULL;
/* Need at least "A:B" */
if (strlen(capa) < 3)
return NULL;
colon = strchr(capa, ':');
if (colon == NULL)
return NULL;
*colon = '\0';
name = strdup(capa);
if (name == NULL)
return got_error_from_errno("strdup");
target = strdup(colon + 1);
if (target == NULL) {
err = got_error_from_errno("strdup");
goto done;
}
/* We can't validate the ref itself here. The main process will. */
err = got_pathlist_append(symrefs, name, target);
done:
if (err) {
free(name);
free(target);
}
return err;
}
static const struct got_error *
match_capabilities(char **my_capabilities, struct got_pathlist_head *symrefs,
char *server_capabilities)
{
const struct got_error *err = NULL;
char *capa, *equalsign;
size_t i;
*my_capabilities = NULL;
do {
capa = strsep(&server_capabilities, " ");
if (capa == NULL)
return NULL;
equalsign = strchr(capa, '=');
if (equalsign != NULL &&
strncmp(capa, "symref", equalsign - capa) == 0) {
err = add_symref(symrefs, equalsign + 1);
if (err)
break;
continue;
}
for (i = 0; i < nitems(got_capabilities); i++) {
err = match_capability(my_capabilities,
capa, &got_capabilities[i]);
if (err)
break;
}
} while (capa);
if (*my_capabilities == NULL) {
*my_capabilities = strdup("");
if (*my_capabilities == NULL)
err = got_error_from_errno("strdup");
}
return err;
}
static const struct got_error *
send_fetch_server_progress(struct imsgbuf *ibuf, const char *msg, size_t msglen)
{
if (msglen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
return got_error(GOT_ERR_NO_SPACE);
if (msglen == 0)
return NULL;
if (imsg_compose(ibuf, GOT_IMSG_FETCH_SERVER_PROGRESS, 0, 0, -1,
msg, msglen) == -1)
return got_error_from_errno(
"imsg_compose FETCH_SERVER_PROGRESS");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
send_fetch_download_progress(struct imsgbuf *ibuf, off_t bytes)
{
if (imsg_compose(ibuf, GOT_IMSG_FETCH_DOWNLOAD_PROGRESS, 0, 0, -1,
&bytes, sizeof(bytes)) == -1)
return got_error_from_errno(
"imsg_compose FETCH_DOWNLOAD_PROGRESS");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
send_fetch_done(struct imsgbuf *ibuf, uint8_t *pack_sha1)
{
if (imsg_compose(ibuf, GOT_IMSG_FETCH_DONE, 0, 0, -1,
pack_sha1, SHA1_DIGEST_LENGTH) == -1)
return got_error_from_errno("imsg_compose FETCH");
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
fetch_progress(struct imsgbuf *ibuf, const char *buf, size_t len)
{
size_t i;
if (len == 0)
return NULL;
/*
* Truncate messages which exceed the maximum imsg payload size.
* Server may send up to 64k.
*/
if (len > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
len = MAX_IMSGSIZE - IMSG_HEADER_SIZE;
/* Only allow printable ASCII. */
for (i = 0; i < len; i++) {
if (isprint((unsigned char)buf[i]) ||
isspace((unsigned char)buf[i]))
continue;
return got_error_msg(GOT_ERR_BAD_PACKET,
"non-printable progress message received from server");
}
return send_fetch_server_progress(ibuf, buf, len);
}
static const struct got_error *
fetch_error(const char *buf, size_t len)
{
static char msg[1024];
size_t i;
for (i = 0; i < len && i < sizeof(msg) - 1; i++) {
if (!isprint(buf[i]))
return got_error_msg(GOT_ERR_BAD_PACKET,
"non-printable error message received from server");
msg[i] = buf[i];
}
msg[i] = '\0';
return got_error_msg(GOT_ERR_FETCH_FAILED, msg);
}
static const struct got_error *
send_fetch_symrefs(struct imsgbuf *ibuf, struct got_pathlist_head *symrefs)
{
const struct got_error *err = NULL;
struct ibuf *wbuf;
size_t len, nsymrefs = 0;
struct got_pathlist_entry *pe;
len = sizeof(struct got_imsg_fetch_symrefs);
TAILQ_FOREACH(pe, symrefs, entry) {
const char *target = pe->data;
len += sizeof(struct got_imsg_fetch_symref) +
pe->path_len + strlen(target);
nsymrefs++;
}
if (len >= MAX_IMSGSIZE - IMSG_HEADER_SIZE)
return got_error(GOT_ERR_NO_SPACE);
wbuf = imsg_create(ibuf, GOT_IMSG_FETCH_SYMREFS, 0, 0, len);
if (wbuf == NULL)
return got_error_from_errno("imsg_create FETCH_SYMREFS");
/* Keep in sync with struct got_imsg_fetch_symrefs definition! */
if (imsg_add(wbuf, &nsymrefs, sizeof(nsymrefs)) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
TAILQ_FOREACH(pe, symrefs, entry) {
const char *name = pe->path;
size_t name_len = pe->path_len;
const char *target = pe->data;
size_t target_len = strlen(target);
/* Keep in sync with struct got_imsg_fetch_symref definition! */
if (imsg_add(wbuf, &name_len, sizeof(name_len)) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, &target_len, sizeof(target_len)) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, name, name_len) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, target, target_len) == -1) {
err = got_error_from_errno("imsg_add FETCH_SYMREFS");
ibuf_free(wbuf);
return err;
}
}
wbuf->fd = -1;
imsg_close(ibuf, wbuf);
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
send_fetch_ref(struct imsgbuf *ibuf, struct got_object_id *refid,
const char *refname)
{
const struct got_error *err = NULL;
struct ibuf *wbuf;
size_t len, reflen = strlen(refname);
len = sizeof(struct got_imsg_fetch_ref) + reflen;
if (len >= MAX_IMSGSIZE - IMSG_HEADER_SIZE)
return got_error(GOT_ERR_NO_SPACE);
wbuf = imsg_create(ibuf, GOT_IMSG_FETCH_REF, 0, 0, len);
if (wbuf == NULL)
return got_error_from_errno("imsg_create FETCH_REF");
/* Keep in sync with struct got_imsg_fetch_ref definition! */
if (imsg_add(wbuf, refid->sha1, SHA1_DIGEST_LENGTH) == -1) {
err = got_error_from_errno("imsg_add FETCH_REF");
ibuf_free(wbuf);
return err;
}
if (imsg_add(wbuf, refname, reflen) == -1) {
err = got_error_from_errno("imsg_add FETCH_REF");
ibuf_free(wbuf);
return err;
}
wbuf->fd = -1;
imsg_close(ibuf, wbuf);
return got_privsep_flush_imsg(ibuf);
}
static const struct got_error *
fetch_pack(int fd, int packfd, uint8_t *pack_sha1,
struct got_pathlist_head *have_refs, int fetch_all_branches,
struct got_pathlist_head *wanted_branches,
struct got_pathlist_head *wanted_refs, int list_refs_only,
struct imsgbuf *ibuf)
{
const struct got_error *err = NULL;
char buf[GOT_FETCH_PKTMAX];
char hashstr[SHA1_DIGEST_STRING_LENGTH];
struct got_object_id *have, *want;
int is_firstpkt = 1, nref = 0, refsz = 16;
int i, n, nwant = 0, nhave = 0, acked = 0;
off_t packsz = 0, last_reported_packsz = 0;
char *id_str = NULL, *refname = NULL;
char *server_capabilities = NULL, *my_capabilities = NULL;
const char *default_branch = NULL;
struct got_pathlist_head symrefs;
struct got_pathlist_entry *pe;
int sent_my_capabilites = 0, have_sidebands = 0;
int found_branch = 0;
SHA1_CTX sha1_ctx;
uint8_t sha1_buf[SHA1_DIGEST_LENGTH];
size_t sha1_buf_len = 0;
ssize_t w;
TAILQ_INIT(&symrefs);
SHA1Init(&sha1_ctx);
have = malloc(refsz * sizeof(have[0]));
if (have == NULL)
return got_error_from_errno("malloc");
want = malloc(refsz * sizeof(want[0]));
if (want == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
while (1) {
err = readpkt(&n, fd, buf, sizeof(buf));
if (err)
goto done;
if (n == 0)
break;
if (n >= 4 && strncmp(buf, "ERR ", 4) == 0) {
err = fetch_error(&buf[4], n - 4);
goto done;
}
err = parse_refline(&id_str, &refname, &server_capabilities,
buf, n);
if (err)
goto done;
if (is_firstpkt) {
if (chattygot && server_capabilities[0] != '\0')
fprintf(stderr, "%s: server capabilities: %s\n",
getprogname(), server_capabilities);
err = match_capabilities(&my_capabilities, &symrefs,
server_capabilities);
if (err)
goto done;
if (chattygot)
fprintf(stderr, "%s: my capabilities:%s\n",
getprogname(), my_capabilities);
err = send_fetch_symrefs(ibuf, &symrefs);
if (err)
goto done;
is_firstpkt = 0;
if (!fetch_all_branches) {
TAILQ_FOREACH(pe, &symrefs, entry) {
const char *name = pe->path;
const char *symref_target = pe->data;
if (strcmp(name, GOT_REF_HEAD) != 0)
continue;
default_branch = symref_target;
break;
}
}
continue;
}
if (strstr(refname, "^{}")) {
if (chattygot) {
fprintf(stderr, "%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
if (strncmp(refname, "refs/heads/", 11) == 0) {
if (fetch_all_branches || list_refs_only) {
found_branch = 1;
} else if (!TAILQ_EMPTY(wanted_branches)) {
TAILQ_FOREACH(pe, wanted_branches, entry) {
if (match_branch(refname, pe->path))
break;
}
if (pe == NULL) {
if (chattygot) {
fprintf(stderr,
"%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
found_branch = 1;
} else if (default_branch != NULL) {
if (!match_branch(refname, default_branch)) {
if (chattygot) {
fprintf(stderr,
"%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
found_branch = 1;
}
} else if (strncmp(refname, "refs/tags/", 10) != 0) {
if (!TAILQ_EMPTY(wanted_refs)) {
TAILQ_FOREACH(pe, wanted_refs, entry) {
if (match_wanted_ref(refname, pe->path))
break;
}
if (pe == NULL) {
if (chattygot) {
fprintf(stderr,
"%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
found_branch = 1;
} else if (!list_refs_only) {
if (chattygot) {
fprintf(stderr, "%s: ignoring %s\n",
getprogname(), refname);
}
continue;
}
}
if (refsz == nref + 1) {
refsz *= 2;
have = reallocarray(have, refsz, sizeof(have[0]));
if (have == NULL) {
err = got_error_from_errno("reallocarray");
goto done;
}
want = reallocarray(want, refsz, sizeof(want[0]));
if (want == NULL) {
err = got_error_from_errno("reallocarray");
goto done;
}
}
if (!got_parse_sha1_digest(want[nref].sha1, id_str)) {
err = got_error(GOT_ERR_BAD_OBJ_ID_STR);
goto done;
}
match_remote_ref(have_refs, &have[nref], refname);
err = send_fetch_ref(ibuf, &want[nref], refname);
if (err)
goto done;
if (chattygot)
fprintf(stderr, "%s: %s will be fetched\n",
getprogname(), refname);
if (chattygot > 1) {
char *theirs, *mine;
err = got_object_id_str(&theirs, &want[nref]);
if (err)
goto done;
err = got_object_id_str(&mine, &have[nref]);
if (err) {
free(theirs);
goto done;
}
fprintf(stderr, "%s: remote: %s\n%s: local: %s\n",
getprogname(), theirs, getprogname(), mine);
free(theirs);
free(mine);
}
nref++;
}
if (list_refs_only)
goto done;
/* Abort if we haven't found any branch to fetch. */
if (!found_branch) {
err = got_error(GOT_ERR_FETCH_NO_BRANCH);
goto done;
}
for (i = 0; i < nref; i++) {
if (got_object_id_cmp(&have[i], &want[i]) == 0)
continue;
got_sha1_digest_to_str(want[i].sha1, hashstr, sizeof(hashstr));
n = snprintf(buf, sizeof(buf), "want %s%s\n", hashstr,
sent_my_capabilites ? "" : my_capabilities);
if (n >= sizeof(buf)) {
err = got_error(GOT_ERR_NO_SPACE);
goto done;
}
err = writepkt(fd, buf, n);
if (err)
goto done;
sent_my_capabilites = 1;
nwant++;
}
err = flushpkt(fd);
if (err)
goto done;
if (nwant == 0)
goto done;
for (i = 0; i < nref; i++) {
if (got_object_id_cmp(&have[i], &zhash) == 0)
continue;
got_sha1_digest_to_str(have[i].sha1, hashstr, sizeof(hashstr));
n = snprintf(buf, sizeof(buf), "have %s\n", hashstr);
if (n >= sizeof(buf)) {
err = got_error(GOT_ERR_NO_SPACE);
goto done;
}
err = writepkt(fd, buf, n);
if (err)
goto done;
nhave++;
}
while (nhave > 0 && !acked) {
struct got_object_id common_id;
/* The server should ACK the object IDs we need. */
err = readpkt(&n, fd, buf, sizeof(buf));
if (err)
goto done;
if (n >= 4 && strncmp(buf, "ERR ", 4) == 0) {
err = fetch_error(&buf[4], n - 4);
goto done;
}
if (n >= 4 && strncmp(buf, "NAK\n", 4) == 0) {
/* Server has not located our objects yet. */
continue;
}
if (n < 4 + SHA1_DIGEST_STRING_LENGTH ||
strncmp(buf, "ACK ", 4) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unexpected message from server");
goto done;
}
if (!got_parse_sha1_digest(common_id.sha1, buf + 4)) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"bad object ID in ACK packet from server");
goto done;
}
acked++;
}
n = snprintf(buf, sizeof(buf), "done\n");
err = writepkt(fd, buf, n);
if (err)
goto done;
if (nhave == 0) {
err = readpkt(&n, fd, buf, sizeof(buf));
if (err)
goto done;
if (n != 4 || strncmp(buf, "NAK\n", n) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unexpected message from server");
goto done;
}
}
if (chattygot)
fprintf(stderr, "%s: fetching...\n", getprogname());
if (my_capabilities != NULL &&
strstr(my_capabilities, GOT_CAPA_SIDE_BAND_64K) != NULL)
have_sidebands = 1;
while (1) {
ssize_t r = 0;
int datalen = -1;
if (have_sidebands) {
err = read_pkthdr(&datalen, fd);
if (err)
goto done;
if (datalen <= 0)
break;
/* Read sideband channel ID (one byte). */
r = read(fd, buf, 1);
if (r == -1) {
err = got_error_from_errno("read");
goto done;
}
if (r != 1) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"short packet");
goto done;
}
if (datalen > sizeof(buf) - 5) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"bad packet length");
goto done;
}
datalen--; /* sideband ID has been read */
if (buf[0] == GOT_SIDEBAND_PACKFILE_DATA) {
/* Read packfile data. */
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
} else if (buf[0] == GOT_SIDEBAND_PROGRESS_INFO) {
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
err = fetch_progress(ibuf, buf, r);
if (err)
goto done;
continue;
} else if (buf[0] == GOT_SIDEBAND_ERROR_INFO) {
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
err = fetch_error(buf, r);
goto done;
} else if (buf[0] == 'A') {
err = readn(&r, fd, buf, datalen);
if (err)
goto done;
if (r != datalen) {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"packet too short");
goto done;
}
/*
* Git server responds with ACK after 'done'
* even though multi_ack is disabled?!?
*/
buf[r] = '\0';
if (strncmp(buf, "CK ", 3) == 0)
continue; /* ignore */
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unexpected message from server");
goto done;
} else {
err = got_error_msg(GOT_ERR_BAD_PACKET,
"unknown side-band received from server");
goto done;
}
} else {
/* No sideband channel. Every byte is packfile data. */
err = readn(&r, fd, buf, sizeof buf);
if (err)
goto done;
if (r <= 0)
break;
}
/*
* An expected SHA1 checksum sits at the end of the pack file.
* Since we don't know the file size ahead of time we have to
* keep SHA1_DIGEST_LENGTH bytes buffered and avoid mixing
* those bytes into our SHA1 checksum computation until we
* know for sure that additional pack file data bytes follow.
*
* We can assume r > 0 since otherwise the loop would exit.
*/
if (r < SHA1_DIGEST_LENGTH) {
if (sha1_buf_len < SHA1_DIGEST_LENGTH) {
/*
* If there's enough buffered + read data to
* fill up the buffer then shift a sufficient
* amount of bytes out at the front to make
* room, mixing those bytes into the checksum.
*/
while (sha1_buf_len > 0 &&
sha1_buf_len + r > SHA1_DIGEST_LENGTH) {
SHA1Update(&sha1_ctx, sha1_buf, 1);
memmove(sha1_buf, sha1_buf + 1, 1);
sha1_buf_len--;
}
/* Buffer potential checksum bytes. */
memcpy(sha1_buf + sha1_buf_len, buf, r);
sha1_buf_len += r;
} else {
/*
* Mix in previously buffered bytes which
* are not part of the checksum after all.
*/
SHA1Update(&sha1_ctx, sha1_buf, r);
/* Update potential checksum buffer. */
memmove(sha1_buf, sha1_buf + r,
sha1_buf_len - r);
memcpy(sha1_buf + sha1_buf_len - r, buf, r);
}
} else {
/* Mix in any previously buffered bytes. */
SHA1Update(&sha1_ctx, sha1_buf, sha1_buf_len);
/* Mix in bytes read minus potential checksum bytes. */
SHA1Update(&sha1_ctx, buf, r - SHA1_DIGEST_LENGTH);
/* Buffer potential checksum bytes. */
memcpy(sha1_buf, buf + r - SHA1_DIGEST_LENGTH,
SHA1_DIGEST_LENGTH);
sha1_buf_len = SHA1_DIGEST_LENGTH;
}
/* Write packfile data to temporary pack file. */
w = write(packfd, buf, r);
if (w == -1) {
err = got_error_from_errno("write");
goto done;
}
if (w != r) {
err = got_error(GOT_ERR_IO);
goto done;
}
packsz += w;
/* Don't send too many progress privsep messages. */
if (packsz > last_reported_packsz + 1024) {
err = send_fetch_download_progress(ibuf, packsz);
if (err)
goto done;
last_reported_packsz = packsz;
}
}
err = send_fetch_download_progress(ibuf, packsz);
if (err)
goto done;
SHA1Final(pack_sha1, &sha1_ctx);
if (sha1_buf_len != SHA1_DIGEST_LENGTH ||
memcmp(pack_sha1, sha1_buf, sha1_buf_len) != 0) {
err = got_error_msg(GOT_ERR_BAD_PACKFILE,
"pack file checksum mismatch");
}
done:
TAILQ_FOREACH(pe, &symrefs, entry) {
free((void *)pe->path);
free(pe->data);
}
got_pathlist_free(&symrefs);
free(have);
free(want);
free(id_str);
free(refname);
free(server_capabilities);
return err;
}
int
main(int argc, char **argv)
{
const struct got_error *err = NULL;
int fetchfd, packfd = -1, i;
uint8_t pack_sha1[SHA1_DIGEST_LENGTH];
struct imsgbuf ibuf;
struct imsg imsg;
struct got_pathlist_head have_refs;
struct got_pathlist_head wanted_branches;
struct got_pathlist_head wanted_refs;
struct got_pathlist_entry *pe;
struct got_imsg_fetch_request fetch_req;
struct got_imsg_fetch_have_ref href;
struct got_imsg_fetch_wanted_branch wbranch;
struct got_imsg_fetch_wanted_ref wref;
size_t datalen;
#if 0
static int attached;
while (!attached)
sleep (1);
#endif
TAILQ_INIT(&have_refs);
TAILQ_INIT(&wanted_branches);
TAILQ_INIT(&wanted_refs);
imsg_init(&ibuf, GOT_IMSG_FD_CHILD);
#ifndef PROFILE
/* revoke access to most system calls */
if (pledge("stdio recvfd", NULL) == -1) {
err = got_error_from_errno("pledge");
got_privsep_send_error(&ibuf, err);
return 1;
}
#endif
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_REQUEST) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(fetch_req)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&fetch_req, imsg.data, sizeof(fetch_req));
fetchfd = imsg.fd;
imsg_free(&imsg);
if (fetch_req.verbosity > 0)
chattygot += fetch_req.verbosity;
for (i = 0; i < fetch_req.n_have_refs; i++) {
struct got_object_id *id;
char *refname;
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_HAVE_REF) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(href)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&href, imsg.data, sizeof(href));
if (datalen - sizeof(href) < href.name_len) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
refname = malloc(href.name_len + 1);
if (refname == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
memcpy(refname, imsg.data + sizeof(href), href.name_len);
refname[href.name_len] = '\0';
id = malloc(sizeof(*id));
if (id == NULL) {
free(refname);
err = got_error_from_errno("malloc");
goto done;
}
memcpy(id->sha1, href.id, SHA1_DIGEST_LENGTH);
err = got_pathlist_append(&have_refs, refname, id);
if (err) {
free(refname);
free(id);
goto done;
}
imsg_free(&imsg);
}
for (i = 0; i < fetch_req.n_wanted_branches; i++) {
char *refname;
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_WANTED_BRANCH) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(wbranch)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&wbranch, imsg.data, sizeof(wbranch));
if (datalen - sizeof(wbranch) < wbranch.name_len) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
refname = malloc(wbranch.name_len + 1);
if (refname == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
memcpy(refname, imsg.data + sizeof(wbranch), wbranch.name_len);
refname[wbranch.name_len] = '\0';
err = got_pathlist_append(&wanted_branches, refname, NULL);
if (err) {
free(refname);
goto done;
}
imsg_free(&imsg);
}
for (i = 0; i < fetch_req.n_wanted_refs; i++) {
char *refname;
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_WANTED_REF) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
if (datalen < sizeof(wref)) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
memcpy(&wref, imsg.data, sizeof(wref));
if (datalen - sizeof(wref) < wref.name_len) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
refname = malloc(wref.name_len + 1);
if (refname == NULL) {
err = got_error_from_errno("malloc");
goto done;
}
memcpy(refname, imsg.data + sizeof(wref), wref.name_len);
refname[wref.name_len] = '\0';
err = got_pathlist_append(&wanted_refs, refname, NULL);
if (err) {
free(refname);
goto done;
}
imsg_free(&imsg);
}
if ((err = got_privsep_recv_imsg(&imsg, &ibuf, 0)) != 0) {
if (err->code == GOT_ERR_PRIVSEP_PIPE)
err = NULL;
goto done;
}
if (imsg.hdr.type == GOT_IMSG_STOP)
goto done;
if (imsg.hdr.type != GOT_IMSG_FETCH_OUTFD) {
err = got_error(GOT_ERR_PRIVSEP_MSG);
goto done;
}
if (imsg.hdr.len - IMSG_HEADER_SIZE != 0) {
err = got_error(GOT_ERR_PRIVSEP_LEN);
goto done;
}
packfd = imsg.fd;
err = fetch_pack(fetchfd, packfd, pack_sha1, &have_refs,
fetch_req.fetch_all_branches, &wanted_branches,
&wanted_refs, fetch_req.list_refs_only, &ibuf);
done:
TAILQ_FOREACH(pe, &have_refs, entry) {
free((char *)pe->path);
free(pe->data);
}
got_pathlist_free(&have_refs);
TAILQ_FOREACH(pe, &wanted_branches, entry)
free((char *)pe->path);
got_pathlist_free(&wanted_branches);
if (fetchfd != -1 && close(fetchfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (packfd != -1 && close(packfd) == -1 && err == NULL)
err = got_error_from_errno("close");
if (err != NULL)
got_privsep_send_error(&ibuf, err);
else
err = send_fetch_done(&ibuf, pack_sha1);
if (err != NULL) {
fprintf(stderr, "%s: %s\n", getprogname(), err->msg);
got_privsep_send_error(&ibuf, err);
}
exit(0);
}
| 24.565121 | 80 | 0.646837 |
09b8df9a7d092d4df9025f2722191ad4c35d0758 | 170 | h | C | src/tftp.h | commandblockguy/nanotube | aa911f1a64e8ca11e017a1aa3be95dd0629c7d89 | [
"MIT"
] | 8 | 2019-11-26T17:29:26.000Z | 2021-10-09T21:58:06.000Z | src/tftp.h | commandblockguy/nanotube | aa911f1a64e8ca11e017a1aa3be95dd0629c7d89 | [
"MIT"
] | null | null | null | src/tftp.h | commandblockguy/nanotube | aa911f1a64e8ca11e017a1aa3be95dd0629c7d89 | [
"MIT"
] | 2 | 2020-03-08T09:53:52.000Z | 2020-07-20T21:07:37.000Z | #ifndef NANOTUBE_TFTP_H
#define NANOTUBE_TFTP_H
#include "lwIP/include/lwip/apps/tftp_server.h"
extern const struct tftp_context tftpContext;
#endif //NANOTUBE_TFTP_H
| 18.888889 | 47 | 0.823529 |
f4a38ff62b571507937893cf489c56c390170dc1 | 1,384 | h | C | SharedLib/BaseUI/include/zooming/pixitem.h | telecommai/linux | b44ba344c17a7e044dfd4363d260877411cace09 | [
"BSD-3-Clause"
] | 1 | 2019-04-19T08:06:44.000Z | 2019-04-19T08:06:44.000Z | SharedLib/BaseUI/include/zooming/pixitem.h | telecommai/linux | b44ba344c17a7e044dfd4363d260877411cace09 | [
"BSD-3-Clause"
] | null | null | null | SharedLib/BaseUI/include/zooming/pixitem.h | telecommai/linux | b44ba344c17a7e044dfd4363d260877411cace09 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PIXITEM_H
#define PIXITEM_H
#include <QGraphicsItem>
#include <QPixmap>
#include <QPainter>
#include <QRectF>
#include <QMouseEvent>
#include <QPointF>
#include <QDragEnterEvent>
#include <QGraphicsSceneWheelEvent>
#include <QMovie>
#include <QTimer>
enum Enum_ZoomState{
NO_STATE,
RESET,
ZOOM_IN,
ZOOM_OUT
};
enum Enum_ZoomTimes{
ZOOM_IN_TIMES = 5,
ZOOM_OUT_TIMES = -5,
};
class PixItem : public QGraphicsItem //继承自图元类,实现自定义的图元,,,qt预置的有直线,椭圆,文本图元,矩形图元等
{
public:
PixItem(QPixmap *pixmap); //构造函数初始化了变量pix
PixItem(QMovie *pMovie);
QRectF boundingRect() const; //实现自己的boundingRect 图元边界方法,完成以图元坐标系为基础增加两个像素点的冗余的工作
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); //重画图形函数
void wheelEvent(QGraphicsSceneWheelEvent *event);
void setZoomState(const int &zoomState);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void SpWheelevent(int iScale, int iX, int iY);
int getScaleValue() const;
void setScaleValue(const int &, int imove);
void paintgif();
QPixmap GetPix(){ return pix; }
private:
qreal m_scaleValue; //缩放值
QPixmap pix; //作为图元显示的图片
int m_zoomState;
bool m_isMove;
QPointF m_startPos;
bool m_bIsGif;
QMovie* m_Movie;
QTimer *pTimer;
};
#endif // PIXITEM_H
| 21.292308 | 97 | 0.758671 |
3ce041dc2d38f3839ee863e22272346d772c25e5 | 2,828 | h | C | modules/platforms/cpp/binary/include/ignite/binary/binary_enum_entry.h | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | 218 | 2015-01-04T13:20:55.000Z | 2022-03-28T05:28:55.000Z | modules/platforms/cpp/binary/include/ignite/binary/binary_enum_entry.h | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | 175 | 2015-02-04T23:16:56.000Z | 2022-03-28T18:34:24.000Z | modules/platforms/cpp/binary/include/ignite/binary/binary_enum_entry.h | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | 93 | 2015-01-06T20:54:23.000Z | 2022-03-31T08:09:00.000Z | /*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Declares ignite::binary::BinaryEnumEntry class.
*/
#ifndef _IGNITE_BINARY_BINARY_ENUM_ENTRY
#define _IGNITE_BINARY_BINARY_ENUM_ENTRY
#include <stdint.h>
#include <ignite/common/common.h>
namespace ignite
{
namespace binary
{
/**
* Binary enum entry.
*
* Represents a single entry of enum in a binary form.
*/
class IGNITE_IMPORT_EXPORT BinaryEnumEntry
{
public:
/**
* Default constructor.
*/
BinaryEnumEntry() :
typeId(0),
ordinal(0)
{
// No-op.
}
/**
* Constructor.
*
* @param typeId Type ID of the enum.
* @param ordinal Ordinal of the enum value.
*/
BinaryEnumEntry(int32_t typeId, int32_t ordinal) :
typeId(typeId),
ordinal(ordinal)
{
// No-op.
}
/**
* Get type ID.
* Type ID can never equal zero. If the Type ID equals zero, the instance is not valid, and could only be
* acquired by manual construction or by reading NULL value.
*
* @return Type ID.
*/
int32_t GetTypeId() const
{
return typeId;
}
/**
* Get ordinal of the enum value.
*
* @return Ordinal.
*/
int32_t GetOrdinal() const
{
return ordinal;
}
/**
* Check whether value was acquired by reading a NULL value.
*
* @return @c true if acquired by reading a NULL value.
*/
bool IsNull() const
{
return typeId == 0;
}
private:
/** Type ID. */
int32_t typeId;
/** Ordinal value. */
int32_t ordinal;
};
}
}
#endif //_IGNITE_BINARY_BINARY_ENUM_ENTRY
| 26.429907 | 117 | 0.517327 |
f0ba1ba4a7770d4c7eaafed842a8a5cd0c00159f | 2,640 | h | C | Sample Code/DJIVideoParser/threadsafequeue.h | busplastic/team7-KLHackathon | 19883b5012aae10aa5ffc7164e3281f27d703902 | [
"MIT"
] | 148 | 2018-10-31T13:53:39.000Z | 2022-03-22T06:55:09.000Z | Sample Code/DJIVideoParser/threadsafequeue.h | busplastic/team7-KLHackathon | 19883b5012aae10aa5ffc7164e3281f27d703902 | [
"MIT"
] | 72 | 2018-10-31T07:58:20.000Z | 2022-03-08T07:07:31.000Z | Sample Code/DJIVideoParser/threadsafequeue.h | busplastic/team7-KLHackathon | 19883b5012aae10aa5ffc7164e3281f27d703902 | [
"MIT"
] | 128 | 2018-11-01T11:44:25.000Z | 2022-03-20T18:13:31.000Z | #pragma once
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
namespace dji
{
namespace videoparser
{
template<typename T>
class threadsafe_queue
{
private:
mutable std::mutex m_mut;
std::queue<T> m_data_queue;
std::condition_variable m_data_cond;
public:
threadsafe_queue() {}
threadsafe_queue(threadsafe_queue const& other)
{
std::lock_guard<std::mutex> lk(other.m_mut);
m_data_queue = other.m_data_queue;
}
void push(const T &new_value)
{
{
std::lock_guard<std::mutex> lk(m_mut);
m_data_queue.push(new_value);
}
m_data_cond.notify_one();
}
void push(T && new_value)
{
{
std::lock_guard<std::mutex> lk(m_mut);
m_data_queue.push(std::forward<T>(new_value));
}
m_data_cond.notify_one();
}
void wait_and_pop(T& value)
{
std::unique_lock<std::mutex> lk(m_mut);
m_data_cond.wait(lk, [this] {return !m_data_queue.empty(); });
value = std::move(m_data_queue.front());
m_data_queue.pop();
}
template <class _Predicate> bool wait_for_item(_Predicate _Pred)
{
std::unique_lock<std::mutex> lk(m_mut);
m_data_cond.wait(lk, [this, _Pred] {return (!m_data_queue.empty() && _Pred()); });
return !m_data_queue.empty();
}
std::shared_ptr<T> wait_and_pop()
{
std::unique_lock<std::mutex> lk(m_mut);
m_data_cond.wait(lk, [this] {return !m_data_queue.empty(); });
std::shared_ptr<T> res = std::make_shared<T>(std::move(m_data_queue.front()));
m_data_queue.pop();
return res;
}
bool try_pop(T& value)
{
std::lock_guard<std::mutex> lk(m_mut);
if (m_data_queue.empty())
return false;
value = std::move(m_data_queue.front());
m_data_queue.pop();
return true;
}
std::shared_ptr<T> front()
{
std::lock_guard<std::mutex> lk(m_mut);
if (m_data_queue.empty())
return nullptr;
std::shared_ptr<T> res = std::make_shared<T>(m_data_queue.front());
return res;
}
std::shared_ptr<T> try_pop()
{
std::lock_guard<std::mutex> lk(m_mut);
if (m_data_queue.empty())
return nullptr;
std::shared_ptr<T> res = std::make_shared<T>(std::move(m_data_queue.front()));
m_data_queue.pop();
return res;
}
bool empty() const
{
std::lock_guard<std::mutex> lk(m_mut);
return m_data_queue.empty();
}
size_t size() const
{
std::lock_guard<std::mutex> lk(m_mut);
return m_data_queue.size();
}
void clear()
{
std::lock_guard<std::mutex> lk(m_mut);
std::queue<T> tmp;
std::swap(m_data_queue, tmp);
}
};
}
}
| 21.463415 | 86 | 0.626894 |
f0be878c12f7ccee7916475367e8426b94f476b1 | 2,853 | h | C | PrivateFrameworks/CalendarUI/CalUIDayMiniMonthDayCell.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/CalendarUI/CalUIDayMiniMonthDayCell.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/CalendarUI/CalUIDayMiniMonthDayCell.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSTextFieldCell.h"
@class NSAttributedString, NSColor, NSDate;
@interface CalUIDayMiniMonthDayCell : NSTextFieldCell
{
NSDate *_date;
struct CGRect _frame;
BOOL _isHovered;
BOOL _isActive;
id _axParent;
BOOL _isInPreviousMonth;
BOOL _isInNextMonth;
BOOL _weekNumbersEnabled;
BOOL _alwaysDrawsBackground;
BOOL _backgroundHasRoundedCorners;
BOOL _backgroundIsCircle;
BOOL _backgroundSizeIsStatic;
long long _weekRow;
NSAttributedString *_weekNumberString;
NSColor *_dayBackgroundColor;
double _backgroundCircleRadius;
double _backgroundXOffset;
double _backgroundYOffset;
struct CGSize _backgroundSize;
}
+ (id)_todayInsetBorderGradient;
+ (id)_todayBorderGradient;
+ (id)_todayGradient;
+ (id)_localizedStringForNumber:(id)arg1;
@property struct CGSize backgroundSize; // @synthesize backgroundSize=_backgroundSize;
@property BOOL backgroundSizeIsStatic; // @synthesize backgroundSizeIsStatic=_backgroundSizeIsStatic;
@property double backgroundYOffset; // @synthesize backgroundYOffset=_backgroundYOffset;
@property double backgroundXOffset; // @synthesize backgroundXOffset=_backgroundXOffset;
@property double backgroundCircleRadius; // @synthesize backgroundCircleRadius=_backgroundCircleRadius;
@property BOOL backgroundIsCircle; // @synthesize backgroundIsCircle=_backgroundIsCircle;
@property BOOL backgroundHasRoundedCorners; // @synthesize backgroundHasRoundedCorners=_backgroundHasRoundedCorners;
@property BOOL alwaysDrawsBackground; // @synthesize alwaysDrawsBackground=_alwaysDrawsBackground;
@property(retain) NSColor *dayBackgroundColor; // @synthesize dayBackgroundColor=_dayBackgroundColor;
@property(retain) NSAttributedString *weekNumberString; // @synthesize weekNumberString=_weekNumberString;
@property long long weekRow; // @synthesize weekRow=_weekRow;
@property BOOL weekNumbersEnabled; // @synthesize weekNumbersEnabled=_weekNumbersEnabled;
@property BOOL isInNextMonth; // @synthesize isInNextMonth=_isInNextMonth;
@property BOOL isInPreviousMonth; // @synthesize isInPreviousMonth=_isInPreviousMonth;
@property(retain) id axParent; // @synthesize axParent=_axParent;
@property BOOL isActive; // @synthesize isActive=_isActive;
@property BOOL isHovered; // @synthesize isHovered=_isHovered;
@property(retain) NSDate *date; // @synthesize date=_date;
@property struct CGRect frame; // @synthesize frame=_frame;
- (void).cxx_destruct;
- (void)drawInteriorWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (void)drawWithFrame:(struct CGRect)arg1 inView:(id)arg2;
- (id)initTextCellWithDate:(id)arg1 calendar:(id)arg2 isActive:(BOOL)arg3 font:(id)arg4 textColor:(id)arg5 alignment:(long long)arg6;
@end
| 44.578125 | 133 | 0.797757 |
ad7af89658a1876ccc9369e22cf92c05dc8540d3 | 1,495 | c | C | Test/hash_table_delete.c | Graham--M/libobjc2 | b32ee7787d8a624e96952bbd8f34259c19e34427 | [
"MIT"
] | 381 | 2015-01-20T04:11:53.000Z | 2022-03-31T21:26:50.000Z | Test/hash_table_delete.c | Graham--M/libobjc2 | b32ee7787d8a624e96952bbd8f34259c19e34427 | [
"MIT"
] | 176 | 2015-01-28T02:38:10.000Z | 2022-03-03T07:52:19.000Z | Test/hash_table_delete.c | Graham--M/libobjc2 | b32ee7787d8a624e96952bbd8f34259c19e34427 | [
"MIT"
] | 106 | 2015-01-15T09:43:44.000Z | 2022-02-17T22:28:40.000Z | #include <stdbool.h>
#include <stdint.h>
struct test_struct {
uintptr_t key;
};
struct test_struct null_placeholder = {0};
static int test_compare(const void *key, const struct test_struct test) {
return (uintptr_t)key == test.key;
}
// force hash collisions
static uint32_t test_key_hash(const void *ptr) {
return ((uint32_t)(uintptr_t)ptr)>>2;
}
static uint32_t test_value_hash(const struct test_struct test) {
return test.key>>2;
}
static int test_is_null(const struct test_struct test) {
return test.key == 0;
}
#define MAP_TABLE_NAME test
#define MAP_TABLE_COMPARE_FUNCTION test_compare
#define MAP_TABLE_VALUE_TYPE struct test_struct
#define MAP_TABLE_VALUE_NULL test_is_null
#define MAP_TABLE_HASH_KEY test_key_hash
#define MAP_TABLE_HASH_VALUE test_value_hash
#define MAP_TABLE_VALUE_PLACEHOLDER null_placeholder
#define MAP_TABLE_ACCESS_BY_REFERENCE 1
#define MAP_TABLE_SINGLE_THREAD 1
#define MAP_TABLE_NO_LOCK 1
#include "../hash_table.h"
int main(int argc, char *argv[])
{
test_table *testTable;
test_initialize(&testTable, 128);
struct test_struct one, two, three;
one.key = 1;
two.key = 2;
three.key = 3;
test_insert(testTable, one);
test_insert(testTable, two);
test_insert(testTable, three);
test_remove(testTable, (void*)2);
test_remove(testTable, (void*)1);
struct test_struct *pthree = test_table_get(testTable, (void*)3);
if (!pthree) {
fprintf(stderr, "failed to find value (key=3) inserted into hash table\n");
return 1;
}
return 0;
}
| 23 | 77 | 0.765217 |
09392718ac841a12b40aefd15b6b055263051ffa | 9,550 | c | C | usr/src/cmd/cmd-inet/usr.sbin/snoop/snoop_pppoe.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/cmd-inet/usr.sbin/snoop/snoop_pppoe.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/cmd-inet/usr.sbin/snoop/snoop_pppoe.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2001 by Sun Microsystems, Inc.
* All rights reserved.
*/
#pragma ident "%Z%%M% %I% %E% SMI"
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sysmacros.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/pppoe.h>
#include "snoop.h"
/*
* These two macros extract the version and type fields respectively from
* the first byte of the PPPoE header.
*/
#define POE_VERS(x) (((x) >> 4) & 0x0f)
#define POE_TYPE(x) ((x) & 0x0f)
typedef void interpret_func_t(uint8_t *, uint16_t);
typedef struct taginfo {
char *tag_name;
uint16_t tag_type;
interpret_func_t *interpret_tagvalue;
} taginfo_t;
static char *pppoe_codetoname(int, boolean_t);
static taginfo_t *pppoe_gettaginfo(uint16_t);
static void print_hexdata(char *, uint8_t *, uint16_t);
static void print_utf8string(char *, char *, uint16_t);
static char *print_linetag(char *);
static interpret_func_t interpret_tags;
static interpret_func_t interpret_hexdata;
static interpret_func_t interpret_service;
static interpret_func_t interpret_access;
static interpret_func_t interpret_cookie;
static interpret_func_t interpret_vendor;
static interpret_func_t interpret_relay;
static interpret_func_t interpret_error;
static interpret_func_t interpret_hurl;
static interpret_func_t interpret_motm;
static interpret_func_t interpret_rteadd;
static taginfo_t taginfo_array[] = {
{ "End-Of-List", POETT_END, interpret_hexdata },
{ "Service-Name", POETT_SERVICE, interpret_service },
{ "AC-Name", POETT_ACCESS, interpret_access },
{ "Host-Uniq", POETT_UNIQ, interpret_hexdata },
{ "AC-Cookie", POETT_COOKIE, interpret_cookie },
{ "Vendor-Specific", POETT_VENDOR, interpret_vendor },
{ "Relay-Session-Id", POETT_RELAY, interpret_relay },
{ "Service-Name-Error", POETT_NAMERR, interpret_error },
{ "AC-System-Error", POETT_SYSERR, interpret_error },
{ "Generic-Error", POETT_GENERR, interpret_error },
{ "Multicast-Capable", POETT_MULTI, interpret_hexdata },
{ "Host-URL", POETT_HURL, interpret_hurl },
{ "Message-Of-The-Minute", POETT_MOTM, interpret_motm },
{ "IP-Route-Add", POETT_RTEADD, interpret_rteadd },
{ "Unknown TAG", 0, NULL }
};
int
interpret_pppoe(int flags, poep_t *poep, int len)
{
uint8_t code = poep->poep_code;
uint8_t *payload;
if (len < sizeof (poep_t))
return (len);
payload = (uint8_t *)poep + sizeof (poep_t);
if (flags & F_SUM) {
(void) sprintf(get_sum_line(), "PPPoE %s",
pppoe_codetoname(code, B_FALSE));
} else { /* flags & F_DTAIL */
show_header("PPPoE: ", "PPP Over Ethernet", len);
show_space();
(void) sprintf(get_line(0, 0),
"Version = %d", POE_VERS(poep->poep_version_type));
(void) sprintf(get_line(0, 0),
"Type = %d", POE_TYPE(poep->poep_version_type));
(void) sprintf(get_line(0, 0),
"Code = %d (%s)", code, pppoe_codetoname(code, B_TRUE));
(void) sprintf(get_line(0, 0),
"Session Id = %d", ntohs(poep->poep_session_id));
(void) sprintf(get_line(0, 0),
"Length = %d bytes", ntohs(poep->poep_length));
show_space();
len -= sizeof (poep_t);
len = MIN(len, ntohs(poep->poep_length));
if (poep->poep_code != 0 && poep->poep_length > 0) {
interpret_tags(payload, len);
}
}
if (poep->poep_code == 0) {
return (interpret_ppp(flags, payload, len));
}
return (len);
}
/*
* interpret_tags() prints PPPoE Discovery Stage TAGs in detail.
*/
static void
interpret_tags(uint8_t *payload, uint16_t length)
{
uint8_t *tagptr = payload;
uint16_t tag_length;
uint16_t tag_type;
uint8_t *tag_value;
taginfo_t *tinfo;
while (length >= POET_HDRLEN) {
tag_type = POET_GET_TYPE(tagptr);
tag_length = POET_GET_LENG(tagptr);
tinfo = pppoe_gettaginfo(tag_type);
show_header("PPPoE: ", tinfo->tag_name,
tag_length + POET_HDRLEN);
(void) sprintf(get_line(0, 0),
"Tag Type = %d", tag_type);
(void) sprintf(get_line(0, 0),
"Tag Length = %d bytes", tag_length);
length -= POET_HDRLEN;
if (tag_length > length) {
(void) sprintf(get_line(0, 0),
"Warning: Truncated Packet");
show_space();
break;
}
/*
* unknown tags or tags which should always have 0 length
* are not interpreted any further.
*/
tag_value = POET_DATA(tagptr);
if (tag_length != 0 && tinfo->interpret_tagvalue != NULL)
tinfo->interpret_tagvalue(tag_value, tag_length);
show_space();
length -= tag_length;
tagptr = POET_NEXT(tagptr);
}
}
static char *
pppoe_codetoname(int code, boolean_t verbose)
{
char *name;
switch (code) {
case POECODE_DATA:
name = "Session";
break;
case POECODE_PADO:
if (verbose)
name = "Active Discovery Offer";
else
name = "PADO";
break;
case POECODE_PADI:
if (verbose)
name = "Active Discovery Initiation";
else
name = "PADI";
break;
case POECODE_PADR:
if (verbose)
name = "Active Discovery Request";
else
name = "PADR";
break;
case POECODE_PADS:
if (verbose)
name = "Active Discovery Session-Confirmation";
else
name = "PADS";
break;
case POECODE_PADT:
if (verbose)
name = "Active Discovery Terminate";
else
name = "PADT";
break;
case POECODE_PADM:
if (verbose)
name = "Active Discovery Message";
else
name = "PADM";
break;
case POECODE_PADN:
if (verbose)
name = "Active Discovery Network";
else
name = "PADN";
break;
default:
name = "Unknown Code";
}
return (name);
}
static taginfo_t *
pppoe_gettaginfo(uint16_t type)
{
taginfo_t *taginfo_ptr = &taginfo_array[0];
int i = 0;
while (taginfo_ptr->tag_type != type &&
taginfo_ptr->interpret_tagvalue != NULL) {
taginfo_ptr = &taginfo_array[++i];
}
return (taginfo_ptr);
}
static void
interpret_hexdata(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("Data = ");
print_hexdata(endofline, tag_value, tag_length);
}
static void
interpret_service(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("Service Name = ");
print_utf8string(endofline, (char *)tag_value, tag_length);
}
static void
interpret_access(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("AC Name = ");
print_utf8string(endofline, (char *)tag_value, tag_length);
}
static void
interpret_cookie(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("Cookie = ");
print_hexdata(endofline, tag_value, tag_length);
}
static void
interpret_vendor(uint8_t *tag_value, uint16_t tag_length)
{
uint8_t *vendor_data;
uint32_t vendorid;
char *endofline;
vendorid = ntohl(*(uint32_t *)tag_value);
(void) sprintf(get_line(0, 0),
"Vendor ID = %d", vendorid);
if (tag_length > 4) {
vendor_data = tag_value + 4;
endofline = print_linetag("Vendor Data = ");
print_hexdata(endofline, vendor_data, tag_length - 4);
}
}
static void
interpret_relay(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("ID = ");
print_hexdata(endofline, tag_value, tag_length);
}
static void
interpret_error(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("Error = ");
print_utf8string(endofline, (char *)tag_value, tag_length);
}
static void
interpret_hurl(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("URL = ");
print_utf8string(endofline, (char *)tag_value, tag_length);
}
static void
interpret_motm(uint8_t *tag_value, uint16_t tag_length)
{
char *endofline;
endofline = print_linetag("Message = ");
print_utf8string(endofline, (char *)tag_value, tag_length);
}
static void
interpret_rteadd(uint8_t *tag_value, uint16_t tag_length)
{
char dest[INET_ADDRSTRLEN];
char mask[INET_ADDRSTRLEN];
char gateway[INET_ADDRSTRLEN];
uint32_t metric;
if (tag_length == 16) {
(void) inet_ntop(AF_INET, tag_value, dest,
INET_ADDRSTRLEN);
(void) inet_ntop(AF_INET, &tag_value[4], mask,
INET_ADDRSTRLEN);
(void) inet_ntop(AF_INET, &tag_value[8], gateway,
INET_ADDRSTRLEN);
metric = ntohl(*(uint32_t *)&tag_value[12]);
sprintf(get_line(0, 0),
"Destination\tNetmask\tGateway\tMetric");
sprintf(get_line(0, 0),
"%s\t%s\t%s\t%d", dest, mask, gateway, metric);
}
}
static void
print_hexdata(char *line, uint8_t *data, uint16_t length)
{
uint16_t index = 0;
line += sprintf(line, "0x");
while (index < length) {
line += sprintf(line, "%02x", data[index++]);
}
}
static void
print_utf8string(char *firstline, char *string, uint16_t length)
{
(void) sprintf(firstline, "%.*s", length, string);
}
static char *
print_linetag(char *string)
{
char *line = get_line(0, 0);
return (line + sprintf(line, string));
}
| 23.875 | 73 | 0.705131 |
1faee23787465113415a6239b4e6c62a144635ff | 244 | h | C | WeiXinTableViewController.h | HDZTony/weixin | a7a80b761514a23b02906a1aea4fdedc5227e4e8 | [
"Apache-2.0"
] | null | null | null | WeiXinTableViewController.h | HDZTony/weixin | a7a80b761514a23b02906a1aea4fdedc5227e4e8 | [
"Apache-2.0"
] | null | null | null | WeiXinTableViewController.h | HDZTony/weixin | a7a80b761514a23b02906a1aea4fdedc5227e4e8 | [
"Apache-2.0"
] | null | null | null | //
// WeiXinTableViewController.h
// 微信例子
//
// Created by 何东洲 on 15/11/19.
// Copyright © 2015年 何东洲. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MJRefresh.h"
@interface WeiXinTableViewController : UITableViewController
@end
| 17.428571 | 60 | 0.717213 |
4eae0e95a56f6d991845e1e629dbc91f3454d358 | 3,589 | c | C | test/array/src/main.c | mpevnev/miscellany | 593c10e2188f3ae96c1e37a7883242d2044f0338 | [
"BSL-1.0"
] | 3 | 2018-06-21T07:06:41.000Z | 2019-06-02T20:38:22.000Z | test/array/src/main.c | mpevnev/miscellany | 593c10e2188f3ae96c1e37a7883242d2044f0338 | [
"BSL-1.0"
] | null | null | null | test/array/src/main.c | mpevnev/miscellany | 593c10e2188f3ae96c1e37a7883242d2044f0338 | [
"BSL-1.0"
] | null | null | null |
#include <check.h>
#include <stdlib.h>
#include "array.h"
#include "main.h"
START_TEST(test_creation)
{
struct array *arr = arr_create(4, sizeof(int));
int i1 = 0;
int i2 = 10;
int i3 = 2;
int i4 = 3;
ck_assert_msg(arr_append(arr, &i1), "Failed to append 0 to the array");
ck_assert_msg(arr_append(arr, &i2), "Failed to append 10 to the array");
ck_assert_msg(arr_append(arr, &i3), "Failed to append 2 to the array");
ck_assert_msg(arr_append(arr, &i4), "Failed to append 3 to the array");
arr_destroy(arr);
}
END_TEST;
START_TEST(test_ex_destruction)
{
struct array *arr = arr_create(4, sizeof(int *));
int *i1 = mk_int(1);
int *i2 = mk_int(2);
int *i3 = mk_int(3);
int *i4 = mk_int(4);
ck_assert_msg(arr_append(arr, &i1), "Failed to append first value to the array");
ck_assert_msg(arr_append(arr, &i2), "Failed to append first value to the array");
ck_assert_msg(arr_append(arr, &i3), "Failed to append first value to the array");
ck_assert_msg(arr_append(arr, &i4), "Failed to append first value to the array");
arr_destroy_ex(arr, &free_int);
}
END_TEST;
START_TEST(test_appending)
{
int a[2] = {1, 2};
int b[2] = {3, 4};
struct array *arr_a = arr_from_data(2, sizeof(int), a);
struct array *arr_b = arr_from_data(2, sizeof(int), b);
ck_assert_msg(arr_a != NULL, "Failed to create the first array");
ck_assert_msg(arr_b != NULL, "Failed to create the second array");
int i = 5;
int append_one = arr_append(arr_b, &i);
ck_assert_msg(append_one, "Failed to append 5 to the second array");
int must_be[5] = {1, 2, 3, 4, 5};
int append_arr = arr_append_a(arr_a, arr_b);
ck_assert_msg(append_arr, "Failed to append arrays");
ck_assert_msg(int_arr_eq(arr_a, must_be), "After appending, the array "
"is not {1, 2, 3, 4, 5}");
arr_destroy(arr_a);
arr_destroy(arr_b);
}
END_TEST;
START_TEST(test_prepending)
{
int a[2] = {1, 2};
int b[2] = {3, 4};
struct array *arr_a = arr_from_data(2, sizeof(int), a);
struct array *arr_b = arr_from_data(2, sizeof(int), b);
ck_assert_msg(arr_a != NULL, "Failed to create the first array");
ck_assert_msg(arr_b != NULL, "Failed to create the second array");
int i = 5;
int prepend_one = arr_prepend(arr_b, &i);
ck_assert_msg(prepend_one, "Failed to prepend 5 to the second array");
int must_be[5] = {5, 3, 4, 1, 2};
int append_arr = arr_prepend_a(arr_a, arr_b);
ck_assert_msg(append_arr, "Failed to prepend arrays");
ck_assert_msg(int_arr_eq(arr_a, must_be), "After prepending, the array "
"is not {5, 3, 4, 1, 2}");
arr_destroy(arr_a);
arr_destroy(arr_b);
}
END_TEST;
Suite *
array_suite(void)
{
Suite *res = suite_create("Array");
/* Core tests. */
TCase *core_tests = tcase_create("Core");
tcase_add_test(core_tests, test_creation);
tcase_add_test(core_tests, test_ex_destruction);
tcase_add_test(core_tests, test_appending);
tcase_add_test(core_tests, test_prepending);
suite_add_tcase(res, core_tests);
return res;
}
int
main(int argc, char **argv)
{
int failed = 0;
Suite *suite = array_suite();
SRunner *runner = srunner_create(suite);
srunner_run_all(runner, CK_NORMAL);
failed = srunner_ntests_failed(runner);
srunner_free(runner);
return (failed == 0) ? 0 : 1;
}
/* ---------- helper functions ---------- */
#include <stdio.h>
void
free_int(void *ptr)
{
int **i = ptr;
free(*i);
}
int *
mk_int(int i)
{
int *res = malloc(sizeof(int));
*res = i;
return res;
}
int
int_arr_eq(struct array *array, int *ints)
{
for (size_t i = 0; i < arr_size(array); i++) {
int *val = arr_ix(array, i);
if (*val != ints[i]) return 0;
}
return 1;
}
| 23.00641 | 82 | 0.68292 |
5e43bad81cc25baae4075272de531c2b01886376 | 1,069 | h | C | tf2_src/utils/scenemanager/statuswindow.h | d3fc0n6/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | tf2_src/utils/scenemanager/statuswindow.h | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | null | null | null | tf2_src/utils/scenemanager/statuswindow.h | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef STATUSWINDOW_H
#define STATUSWINDOW_H
#ifdef _WIN32
#pragma once
#endif
class mxScrollbar;
#define IDC_STATUS_SCROLL 1000
class CStatusWindow : public mxWindow
{
public:
CStatusWindow (mxWindow *parent, int x, int y, int w, int h, const char *label = 0 );
~CStatusWindow();
void StatusPrint( int r, int g, int b, bool overwrite, const char *text );
virtual void redraw();
virtual bool PaintBackground( void );
virtual int handleEvent( mxEvent *event );
// virtual void Think( float dt );
private:
void PositionSliders( int sboffset );
enum
{
MAX_TEXT_LINES = 1024,
TEXT_LINE_MASK = MAX_TEXT_LINES - 1,
};
struct TextLine
{
char m_szText[ 512 ];
int r, g, b;
float curtime;
};
TextLine m_rgTextLines[ MAX_TEXT_LINES ];
int m_nCurrentLine;
mxScrollbar *m_pScrollbar;
};
extern CStatusWindow *g_pStatusWindow;
#endif // STATUSWINDOW_H
| 18.431034 | 86 | 0.641721 |
e2fc82dacbd4d82b9ce9327499614a85c1ebccfd | 1,192 | h | C | bes2600w/sdk_liteos/bsp/platform/drivers/usb/usb_host/inc/usb_tester.h | dawmlight/device_bestechnic | 63ade68296297f19742d8d5f98353c4376e516cb | [
"Apache-2.0"
] | null | null | null | bes2600w/sdk_liteos/bsp/platform/drivers/usb/usb_host/inc/usb_tester.h | dawmlight/device_bestechnic | 63ade68296297f19742d8d5f98353c4376e516cb | [
"Apache-2.0"
] | null | null | null | bes2600w/sdk_liteos/bsp/platform/drivers/usb/usb_host/inc/usb_tester.h | dawmlight/device_bestechnic | 63ade68296297f19742d8d5f98353c4376e516cb | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 bestechnic (Shanghai) Technologies CO., LIMITED.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef USB_TESTER_H
#define USB_TESTER_H
#include "FATFileSystem.h"
#include <stdint.h>
class USBFileSystem : public FATFileSystem
{
public:
USBFileSystem();
void SetDevice(int device);
int GetDevice(void);
virtual int disk_initialize();
virtual int disk_write(const uint8_t * buffer, uint64_t sector, uint8_t count);
virtual int disk_read(uint8_t * buffer, uint64_t sector, uint8_t count);
virtual uint64_t disk_sectors();
protected:
int _device;
u32 _blockSize;
u32 _blockCount;
};
#endif
| 24.326531 | 83 | 0.720638 |
61bd6a8ece5012629bd55abc414415cd91dd919f | 949 | h | C | ios/source/courses/skutarenko/iOSDevCourse-Objective-C/HW/iOSDev2901_SettingsHW/iOSDev2901_SettingsHW/OTSettingsTableViewController.h | oltv00/knowledge | 25d9507d529c494e0d6d9c1d7f643d3249624b65 | [
"MIT"
] | null | null | null | ios/source/courses/skutarenko/iOSDevCourse-Objective-C/HW/iOSDev2901_SettingsHW/iOSDev2901_SettingsHW/OTSettingsTableViewController.h | oltv00/knowledge | 25d9507d529c494e0d6d9c1d7f643d3249624b65 | [
"MIT"
] | null | null | null | ios/source/courses/skutarenko/iOSDevCourse-Objective-C/HW/iOSDev2901_SettingsHW/iOSDev2901_SettingsHW/OTSettingsTableViewController.h | oltv00/knowledge | 25d9507d529c494e0d6d9c1d7f643d3249624b65 | [
"MIT"
] | null | null | null | //
// OTSettingsTableViewController.h
// iOSDev2901_SettingsHW
//
// Created by Oleg Tverdokhleb on 24.04.16.
// Copyright © 2016 Oleg Tverdokhleb. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface OTSettingsTableViewController : UITableViewController <UITextFieldDelegate>
@property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *textFields;
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *lastnameField;
@property (weak, nonatomic) IBOutlet UITextField *loginField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UITextField *ageField;
@property (weak, nonatomic) IBOutlet UITextField *telNumberField;
@property (weak, nonatomic) IBOutlet UITextField *emailField;
- (IBAction)actionFieldsEditingChanged:(UITextField *)sender;
- (IBAction)actionEmailFieldDidEndEditing:(UITextField *)sender;
@end
| 35.148148 | 86 | 0.797682 |
6687a84edb2ad362c7343f76151cd1cc8a140179 | 10,794 | h | C | src/lib/support/CmdLineParser.h | sriharikrishna/OpenADFortTk | bd6f1144eab397f6ef6ef420d7e5fd235fea39f6 | [
"BSD-3-Clause"
] | null | null | null | src/lib/support/CmdLineParser.h | sriharikrishna/OpenADFortTk | bd6f1144eab397f6ef6ef420d7e5fd235fea39f6 | [
"BSD-3-Clause"
] | null | null | null | src/lib/support/CmdLineParser.h | sriharikrishna/OpenADFortTk | bd6f1144eab397f6ef6ef420d7e5fd235fea39f6 | [
"BSD-3-Clause"
] | null | null | null | // ##########################################################
// # This file is part of OpenADFortTk. #
// # The full COPYRIGHT notice can be found in the top #
// # level directory of the OpenADFortTk source tree. #
// # For more information visit #
// # http://www.mcs.anl.gov/openad #
// ##########################################################
#ifndef CmdLineParser_H
#define CmdLineParser_H
#include <iostream>
#include <map>
#include <vector>
#include <string>
//*************************** User Include Files ****************************
#include <inttypes.h> /* commonly available, unlike <stdint.h> */
//*************************** Forward Declarations ***************************
//****************************************************************************
//****************************************************************************
// CmdLineParser
//****************************************************************************
// CmdLineParser: Parses arguments on the command line, argc and argv.
// Provides easy access to both optional arguments (with short or long
// specifiers) and regular arguments. Provides functionality similar
// to getopt() and GNU's getopt_long(), but in an easier to use -- and
// in the case of getopt_long(), more portable -- package. In
// addition, the package provides configurable handling of duplicate
// options/arguments and routines to convert string arguments into
// numerical types.
//
// A user creates a NULL-terminated array of option descriptors
// (OptArgDesc) indicating switch names and arguments, if any. He
// then instantiates a CmdLineParser and parses argc/argv. Errors are
// delivered with the exception Exception. The parser object provides
// access to all optional and regular arguments using the interface
// routines belows.
//
// More details:
// The command line generally has the form (but note qualifications below):
// <command> [arguments]
//
// [arguments] ::= [optional_arg] | [regular_arg]
//
// [optional_arg] ::= -f [arg] | -f[arg]
// | --foo [arg] | --foo=arg
//
// An element of argv that starts with '-' or '--' (and is not exactly
// '--') signifies an option. The option switch is the text without
// the initial dashes. As the above shows, we support a variety of
// option styles.
//
// Features:
// - The '--' token forces the end of optional argument scanning and
// iterprets everything following as a list of regular arguments.
// This is useful for non-option arguments that begin with dashes.
// - Unlike getopt() we do not support the deprecated use of the single
// '-'; this is an error.
// - Long argument switches may be abbreviated if the abbreviation
// is unique.
// - Configurable handling of duplicate options and arguments.
//
// Limitations:
// - Unlike getopt(), we do not currently support short switch grouping,
// e.g. using -abc instead of -a -b -c. [FIXME: we can assume that
// only options without arguments are allowed to be grouped.]
//
// Warnings:
// - Switches that take optional arguments can be confusing. For
// example, assume a command 'foo' takes a filename and on option,
// --debug, which itself takes an optional debug level. The
// following commands pose no difficulties:
// foo myfile
// foo --debug=3 myfile
// foo --debug 3 myfile
// foo myfile --debug
// However, in the following
// foo --debug myfile
// 'myfile' is erroneously assumed to be the optional argument to
// --debug. While the '--' token solves this, it remains awkward.
//
class CmdLineParser {
public:
// ---------------------------------------------------------
// Structure used to describe command line options
// ---------------------------------------------------------
// Describes if an option switch takes an argument
enum OptKind {
ARG_NULL = 0,
ARG_NONE, // switch does not take argument
ARG_REQ, // switch must take an argument
ARG_OPT // switch takes an (optional!) argument
};
// Describes how to handle duplicate options and option arguments
enum DupOptKind {
DUPOPT_NULL = 0,
DUPOPT_ERR, // throw an exception for duplicate option or argument
DUPOPT_CLOB, // clobber any previous argument
DUPOPT_CAT // concat all available arguments using 'dupArgSep'
};
struct OptArgDesc {
bool operator==(const OptArgDesc& x) const {
return (swShort == x.swShort && swLong == x.swLong
&& kind == x.kind && dupKind == x.dupKind
&& dupArgSep == x.dupArgSep);
}
bool operator!=(const OptArgDesc& x) const { return !(*this == x); }
// Data
char swShort; // 0 if n/a
const char* swLong; // NULL if n/a
OptKind kind;
DupOptKind dupKind;
const char* dupArgSep; // separator for 'DUPARG_CONCAT'
};
// The NULL terminator (two versions). The use of the first version
// is preferable, but some older compilers won't support it.
static OptArgDesc OptArgDesc_NULL;
# define CmdLineParser_OptArgDesc_NULL_MACRO \
{ 0, NULL, CmdLineParser::ARG_NULL, CmdLineParser::DUPOPT_NULL, NULL }
// ---------------------------------------------------------
// Exception thrown when errors are encountered
// ---------------------------------------------------------
class Exception {
public:
Exception(const char* m) : msg(m) { }
Exception(std::string m) : msg(m) { }
virtual ~Exception () { }
virtual const std::string& GetMessage() const { return msg; }
virtual void Report(std::ostream& os) const {
os << "CmdLineParser::Exception: " << msg << std::endl;
}
virtual void Report() const { Report(std::cerr); }
protected:
std::string msg;
};
class ParseError : public Exception {
public:
ParseError(const char* m) : Exception(m) { }
ParseError(std::string m) : Exception(m) { }
virtual ~ParseError () { }
};
class InternalError : public Exception {
public:
InternalError(const char* m) : Exception(m) { }
InternalError(std::string m) : Exception(m) { }
virtual ~InternalError () { }
private:
void Ctor() {
msg = "CmdLineParser internal error (Don't abuse me!): " + msg;
}
};
// ---------------------------------------------------------
public:
// ---------------------------------------------------------
// Constructor/Destructor
// ---------------------------------------------------------
CmdLineParser();
CmdLineParser(const OptArgDesc* optArgDescs,
int argc, const char* const argv[]);
~CmdLineParser();
// -------------------------------------------------------
// Parsing
// -------------------------------------------------------
// Parse: Given a NULL terminated array of OptArgDesc describing
// command line arguments, parses the argv/argc into switches,
// optional and required arguments.
void
Parse(const OptArgDesc* optArgDescs,
int argc, const char* const argv[]);
// -------------------------------------------------------
// Parsed Data: Command
// -------------------------------------------------------
// GetCmd: The command (will be valid even after a parse error)
const std::string& GetCmd() const;
// -------------------------------------------------------
// Parsed Data: Optional arguments
// -------------------------------------------------------
// IsOpt: (IsOption) Given a short or long switch, returns whether
// the switch has been seen.
bool IsOpt(const char swShort) const;
bool IsOpt(const char* swLong) const;
bool IsOpt(const std::string& sw) const;
// IsOptArg: (IsOptionArgument) Given a short or long switch,
// returns whether an argument is associated with it. Designed for
// switches that optionally take arguments.
bool IsOptArg(const char swShort) const;
bool IsOptArg(const char* swLong) const;
bool IsOptArg(const std::string& sw) const;
// GetOptArg: (GetOptionArgument) Given a short or long switch, get
// the argument associated with it. Assumes user has verified that
// an argument *exists*.
const std::string& GetOptArg(const char swShort) const;
const std::string& GetOptArg(const char* swLong) const;
const std::string& GetOptArg(const std::string& sw) const;
// -------------------------------------------------------
// Parsed Data: Arguments
// -------------------------------------------------------
unsigned int GetNumArgs() const;
const std::string& GetArg(unsigned int i) const;
// -------------------------------------------------------
// Convert strings into other formats
// -------------------------------------------------------
// The input should be non-empty
static long ToLong(const std::string& str);
static uint64_t ToUInt64(const std::string& str);
static double ToDbl(const std::string& str);
// -------------------------------------------------------
// Misc
// -------------------------------------------------------
void Dump(std::ostream& os = std::cerr) const;
void DDump() const;
private:
// Should not be used
CmdLineParser(const CmdLineParser& p) { }
CmdLineParser& operator=(const CmdLineParser& x) { return *this; }
typedef std::map<std::string, std::string*> SwitchToArgMap;
typedef std::vector<std::string> ArgVec;
// Switch descriptor (Because of limited use, we allow this to be
// returned as an object)
class SwDesc {
public:
SwDesc() : isLong(false) { }
SwDesc(const char* sw_, bool isLong_, const char* arg_)
: sw(sw_), isLong(isLong_), arg(arg_) { }
SwDesc(const std::string& sw_, bool isLong_, const std::string& arg_)
: sw(sw_), isLong(isLong_), arg(arg_) { }
~SwDesc() { }
// use default copy constructor if necessary
std::string sw; // switch text without dashes
bool isLong; // long style
std::string arg; // any argument
};
private:
void Ctor();
void Reset();
void CheckForErrors(const OptArgDesc* optArgDescs);
const OptArgDesc*
CreateSortedCopy(const OptArgDesc* optArgDescs);
// Parsing helpers
SwDesc
MakeSwitchDesc(const char* str);
const OptArgDesc*
FindOptDesc(const OptArgDesc* optArgDescs, const SwDesc& swdesc,
bool errOnMultipleMatches = true);
void
AddOption(const OptArgDesc& odesc, const SwDesc& swdesc);
void
AddOption(const OptArgDesc& odesc,
const std::string& sw, const std::string& arg);
private:
std::string command; // comand name
SwitchToArgMap switchToArgMap; // optional arguments
ArgVec arguments; // regular arguments
};
#endif
| 35.506579 | 78 | 0.567352 |
450cd346577638906e1d1ca55f01e324ef5862c3 | 2,572 | h | C | nimbus_source/004_wifi/maradns-1.3.07.09/tcp/getzone_de.h | isabella232/wireless-media-drive | ab09fbd1194c8148131cf0a37425419253a137b0 | [
"Apache-2.0"
] | 10 | 2015-02-28T21:05:37.000Z | 2021-09-16T04:57:27.000Z | nimbus_source/004_wifi/maradns-1.3.07.09/tcp/getzone_de.h | SanDisk-Open-Source/wireless-media-drive | ab09fbd1194c8148131cf0a37425419253a137b0 | [
"Apache-2.0"
] | 1 | 2021-02-24T05:16:58.000Z | 2021-02-24T05:16:58.000Z | nimbus_source/004_wifi/maradns-1.3.07.09/tcp/getzone_de.h | isabella232/wireless-media-drive | ab09fbd1194c8148131cf0a37425419253a137b0 | [
"Apache-2.0"
] | 5 | 2018-11-19T16:42:53.000Z | 2021-12-07T12:39:23.000Z | #define L_FATAL_COMMENT "# Fataler Fehler: "
#define L_TIMEOUT "Verbindungs Time out"
#define L_USAGE "Benutzung: getzone zone_name zone_server_IP"
#define L_USAGE_FETCH "Benutzung: fetchzone zone_name zone_server_IP"
#define L_VALID_IP "Bitte benutzen Sie eine gueltige IP fuer den Zonen Server"
#define L_NO_SOCK "Kann keinen TCP Socket erstellen"
#define L_NO_CONNECT "Kann keine Verbindung zum Zone Server herstellen"
#define L_NO_SEND "Kann kein send string Objekt erstellen"
#define L_NO_HEADER "Kann keinen DNS Header erstellen"
#define L_NO_ZSTRING "Kann kein zone string Objekt erstellen"
#define L_QSTR2JS_ERROR "qstr2js"
#define L_APPEND_Z "Kann Zonen String an Zonen Objekt anhaengen"
#define L_APPEND_D "Kann keine Punkt an das Ende des zone string Objekt ergaenzen"
#define L_INVALID_NAME "Ungueltige Form eines Zonen Namen"
#define L_APPEND_ZS "Kann zone string nicht an send string anhaengen"
#define L_ADD_QT "Kann Query Type zum Senden nicht ergaenzen"
#define L_ADD_QC "Kann Query Klasse zum Senden nicht ergaenzen"
#define L_SEND_2BYTE "Konnte keinen 2 byte Laengen Header zum Zonen Server senden"
#define L_SEND_QUERY "Konnte keine Anfrage zum Zonen Server senden"
#define L_C_RRNAME "Kontte keine rr.name erzeugen"
#define L_MNAME "Konnte keinen soa.mname erzeugen"
#define L_RNAME "Konnte keinen soa.rname erzeugen"
#define L_NOT_MANLY "Antworten des Server ist nicht lang genug um den Header zu behalten"
#define L_NO_GET "Kann keine Speicher zum Empfang fuer eine String bereitstellen"
#define L_NO_EXPAND "Kann keine Speicher zum Expandieren eines String bereitstellen"
#define L_SERVER "Kann kein Packet vom Server erhalten"
#define L_DECOMPRESS "Fataler Fehler beim durchfuehren der Dekomprimierung"
#define L_RHEADER "Konnte den Header vom Server nicht lesen"
#define L_FORMAT "Format Fehler"
#define L_SERVER_FAIL "Server Fehler"
#define L_NAME "Namens Fehler"
#define L_NOTIMPL "Nicht implementiert"
#define L_REFUSE "Abgelehtn"
#define L_RCODE "Rcode > 5"
#define L_DLABEL "Ungueltiges dlabel in der Anfrage"
#define L_READ_RR_H "Fataler Fehler beim Ausfuehren von read_rr_h"
#define L_GET_S "Konnte nicht get string durchfuehren"
#define L_GET_COPY "Fataler Fehler beim Kopieren vom Namen zum get"
#define L_BALIWICK "# Unterdrueckter out-of-bailiwick Eintrag folgt"
#define L_HASH "# "
#define L_CGET "Konnte keine get string durchfuehren"
#define L_RDDATA "Problem beim Empfang von rddata"
#define L_TRANS "Problem beim Uebersetzen des A record Namen"
#define LF "\n"
#define L_HNAME "Hname problem"
#define L_ZERO "Kein 0-length Name!"
| 54.723404 | 89 | 0.810264 |
8478fe7470ca1c1f4b5daaefc6036059f1a9f1e6 | 636 | h | C | crypto.h | svetoslavenchev/openssl-aes-256-cbc-cmac | 235ff511c9422a362f7b08e0ae8b2316089ff61a | [
"OpenSSL"
] | null | null | null | crypto.h | svetoslavenchev/openssl-aes-256-cbc-cmac | 235ff511c9422a362f7b08e0ae8b2316089ff61a | [
"OpenSSL"
] | null | null | null | crypto.h | svetoslavenchev/openssl-aes-256-cbc-cmac | 235ff511c9422a362f7b08e0ae8b2316089ff61a | [
"OpenSSL"
] | null | null | null | #ifndef HEADER_CRYPTO_H
#define HEADER_CRYPTO_H
#include <stddef.h> // size_t
#include "opensslconf.h"
void *CRYPTO_malloc(size_t num, const char *file, int line);
void *CRYPTO_zalloc(size_t num, const char *file, int line);
void CRYPTO_free(void *ptr, const char *file, int line);
void OPENSSL_cleanse(void *ptr, size_t len);
# define OPENSSL_malloc(num) \
CRYPTO_malloc(num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_zalloc(num) \
CRYPTO_zalloc(num, OPENSSL_FILE, OPENSSL_LINE)
# define OPENSSL_free(addr) \
CRYPTO_free(addr, OPENSSL_FILE, OPENSSL_LINE)
#endif /* HEADER_CRYPTO_H */
| 27.652174 | 60 | 0.718553 |
d59b00e055abf6f4424abdc6e5658b4426b668fb | 22,793 | c | C | src/t_net_sck.c | tobbik/lua-t | 3a82323660ec0ecba4736a77164abb1551a7d999 | [
"MIT"
] | 6 | 2017-05-12T18:39:01.000Z | 2017-12-21T09:59:29.000Z | src/t_net_sck.c | tobbik/lua-t | 3a82323660ec0ecba4736a77164abb1551a7d999 | [
"MIT"
] | 2 | 2018-07-19T22:17:46.000Z | 2018-07-19T22:40:23.000Z | src/t_net_sck.c | tobbik/lua-t | 3a82323660ec0ecba4736a77164abb1551a7d999 | [
"MIT"
] | 2 | 2016-05-11T04:42:22.000Z | 2017-01-13T14:51:12.000Z | /* vim: ts=3 sw=3 sts=3 tw=80 sta noet list
*/
/**
* \file t_net_sck.c
* \brief OOP wrapper around network sockets.
* TCP/UDP/RAW, read write connect listen bind etc
* \author tkieslich
* \copyright See Copyright notice at the end of t.h
*/
#include "t_net_l.h"
#include "t_buf.h"
#include <stdlib.h> // bsearch()
#include <errno.h> // errno
#include <string.h> // strcmp
#ifdef DEBUG
#include "t_dbg.h"
#endif
/**--------------------------------------------------------------------------
* Get a string representation of address for error messages.
* \param L Lua State.
* \param adr t_net_adr Address struct.
* \return *char string of address.
* --------------------------------------------------------------------------*/
static const char
*t_net_sck_getAddrString( lua_State *L, struct sockaddr_storage *adr )
{
char dst[ INET6_ADDRSTRLEN ];
SOCK_ADDR_INET_NTOP( adr, dst );
lua_pushfstring( L, "%s:%d", dst,
ntohs( SOCK_ADDR_SS_PORT( adr ) ) );
return lua_tostring( L, -1 );
}
/**--------------------------------------------------------------------------
* Create a socket and push to LuaStack.
* \param L Lua state.
* \lparam protocol string: 'tcp', 'udp' ... -- use lower cased for platform
* independence
* \lparam family string: 'ip4', 'AF_INET6', 'raw' ...
* \lparam type string: 'stream', 'datagram' ...
* \usage Net.Socket( ) -> create TCP IPv4 Socket
* Net.Socket( 'TCP' ) -> create TCP IPv4 Socket
* Net.Socket( 'TCP', 'ip4' ) -> create TCP IPv4 Socket
* Net.Socket( 'UDP', 'ip4' ) -> create UDP IPv4 Socket
* Net.Socket( 'UDP', 'ip6' ) -> create UDP IPv6 Socket
* \return struct t_net_sck pointer to the socket struct.
* --------------------------------------------------------------------------*/
static int
lt_net_sck_New( lua_State *L )
{
struct t_net_sck *sck;
sck = t_net_sck_create_ud( L );
if (-1 == p_net_sck_createHandle( sck,
(AF_UNIX == luaL_checkinteger( L, 2 )) ? 0 : lua_tointeger( L, 2 ),
luaL_checkinteger( L, 3 ),
luaL_checkinteger( L, 1 ) )
)
t_push_error( L, 0, 0, "Can't create socket" );
return 1;
}
/**--------------------------------------------------------------------------
* Create a socket and push to LuaStack.
* \param L Lua state.
* \param family int AF_INET, AF_INET6, ...
* \param protocol int IPPROTO_UDP, IPPROTO_TCP, ...
* \param type int SOCK_STREAM, SOCK_DGRAM, ...
* \param create bool, should socket be created or just wrapping userdata.
* \return struct t_net_sck* pointer to the socket struct.
* --------------------------------------------------------------------------*/
struct t_net_sck
*t_net_sck_create_ud( lua_State *L )
{
struct t_net_sck *sck = (struct t_net_sck *) lua_newuserdata( L, sizeof( struct t_net_sck ) );
sck->fd = 0;
luaL_getmetatable( L, T_NET_SCK_TYPE );
lua_setmetatable( L, -2 );
return sck;
}
/** -------------------------------------------------------------------------
* Close a socket.
* \param L Lua state.
* \lparam ud t_net_sck userdata instance.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_close( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
//printf("CLOSING SOCK: %d\n", sck->fd);
if (-1 == p_net_sck_close( sck ))
return t_push_error( L, 0, 1, "Can't close socket" );
else
return 0;
}
/** -------------------------------------------------------------------------
* Shutdown a socket.
* \param L Lua state.
* \lparam sck Net.Socket userdata instance.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_shutDown( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
if (-1 == p_net_sck_shutDown( sck, luaL_checkinteger( L, 2 ) ))
return t_push_error( L, 0, 1, "Can't shutdown socket" );
else
return 0;
}
/** -------------------------------------------------------------------------
* Listen on a socket or create a listening socket.
* \param L Lua state.
* \lparam sck Net.Sck userdata instance( socket ).
* \lparam adr Net.Address userdata instance( ipaddr ).
* \lparam int port to listen on.
* \lparam int Backlog connections.
* \lreturn sck t.Net.Socket userdata(struct).
* \lreturn adr t.Net.Address userdata(struct).
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_listener( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
int bl = luaL_optinteger( L, 2, SOMAXCONN );
if (-1 == p_net_sck_listen( sck, bl ))
return t_push_error( L, 0, 1, "Can't listen on socket" );
else
return 1;
}
/** -------------------------------------------------------------------------
* Bind a socket to an address.
* \param L Lua state.
* \lparam ud t_net_sck userdata instance.
* \lparam ud t_net_adr userdata instance.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_binder( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
struct sockaddr_storage *adr = t_net_adr_check_ud( L, 2, 1 );
if (-1 == p_net_sck_bind( sck, adr ))
return t_push_error( L, 0, 0, "Can't bind socket to %s", t_net_sck_getAddrString( L, adr ) );
else
{
lua_pushboolean( L, 1 );
return 1;
}
}
/** -------------------------------------------------------------------------
* Connect an existing socket to an address.
* \param L Lua state.
* \lparam ud t_net_sck userdata instance.
* \lparam adr userdata;t_net_adr userdata instance.
* OR
* \lparam family string;
* \lparam ipstr string; string representing IP.
* \lparam port integer; port number.
* \lreturn adr userdata; t_net_adr userdata instance (optional).
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_connecter( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
struct sockaddr_storage *adr = t_net_adr_check_ud( L, 2, 1 );
if (-1 == p_net_sck_connect( sck, adr ))
return t_push_error( L, 0, 0, "Can't connect socket to %s", t_net_sck_getAddrString( L, adr ) );
else
{
lua_pushboolean( L, 1==1 );
return 1;
}
}
/** -------------------------------------------------------------------------
* Accept a (TCP) socket connection.
* \param L Lua state.
* \lparam srv T.Net.Socket userdata instance( server socket ).
* \lreturn cli T.Net.Socket userdata instance( new client socket ).
* \lreturn adr T.Net.Address userdata instance( new client sockaddr ).
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_accept( lua_State *L )
{
struct t_net_sck *srv = t_net_sck_check_ud( L, 1, 1 ); // listening socket
struct t_net_sck *cli = t_net_sck_create_ud( L ); // accepted socket
struct sockaddr_storage *adr = t_net_adr_create_ud( L ); // peer address
if (-1 == p_net_sck_accept( srv, cli, adr ))
return t_push_error( L, 0, 0, "Can't accept on socket bound on %s", t_net_sck_getAddrString( L, adr ) );
else
return 2;
}
/** -------------------------------------------------------------------------
* Send data to a socket.
*
* A Buffer, Buffer.Segment or Lua string is mandatory as second parameter. If
* the third parameter is a Net.Address it will be passed to sendto and used
* for an unconnected socket to determine where it goes to. A fourth parameter,
* or if Net.Address is omitted a third, is an integer and determines the number
* of bytes to send. The following permutations are possible:
* cnt,err = s:send( buf/seg/str )
* cnt,err = s:send( buf/seg/str, adr )
* cnt,err = s:send( buf/seg/str, max )
* cnt,err = s:send( buf/seg/str, adr, max )
* \usage int cnt = sck:send( Buffer/Segment/string buf[, Net.Address adr, int size ] )
* \param L Lua state.
* \lparam sck Net.Socket userdata instance. -> mandatory
* \lparam msg Buffer/Segment/string instance. -> mandatory
* \lparam adr Net.Address userdata instance. -> optional
* \lparam max size of msg t be send in bytes. -> optional
* \lreturn sent number of bytes sent.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_send( lua_State *L )
{
size_t len; // length of message to send
ssize_t snt; // actually sent bytes
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
char *msg = t_buf_checklstring( L, 2, &len, NULL );
struct sockaddr_storage *adr = t_net_adr_check_ud( L, 3, 0 );
size_t max = (lua_gettop( L ) == ((NULL==adr) ?3 :4))
? (size_t) luaL_checkinteger( L, (NULL==adr) ?3 :4 )
: len;
snt = p_net_sck_send( sck, adr, msg, (max<len) ? max : len );
if (snt > -1)
{
lua_pushinteger( L, snt );
return 1;
}
else
return ((NULL == adr)
? t_push_error( L, 0, 1, "Can't send message" )
: t_push_error( L, 0, 1, "Can't send Message to %s", t_net_sck_getAddrString( L, adr ) )
);
}
/** -------------------------------------------------------------------------
* Recieve some data from a socket.
* If the first parameter is a Net.Address it will be passed to recvfrom() and
* be filled with the peers ip Address. If the first or second parameter is a
* Buffer or a Buffer.Segement received data will be written into it.
* Otherwise a Lua string with the data will be returned as first return value.
* If a Buffer or Buffer.Segement is passed the receiving of data is
* automatically capped to the buffers/segements defined length. It is not
* possible to pass an offset to Buffer, instead use a temporary Buffer.Segement
* to compose a bigger Buffer from multiple recv() operations. The following
* permutations are possible:
* str ,int = sck:recv( )
* str ,int = sck:recv( adr )
* str ,int = sck:recv( max )
* bool,int = sck:recv( buf/seg )
* str ,int = sck:recv( adr, max )
* bool,int = sck:recv( adr, buf/seg )
* bool,int = sck:recv( buf/seg, max )
* bool,int = sck:recv( adr, buf/seg, max )
* \usage string msg, int cnt = sck:recv( [Net.Address adr, int size ] )
* \usage bool rcvd, int cnt = sck:recv( [Net.Address adr,] Buffer/Segment buf[, int size ] )
* \param L Lua state.
* \lparam sck Net.Socket userdata instance. -> mandatory
* \lparam adr Net.Address userdata instance. -> optional
* \lparam buf Buffer/Segment userdata instance. -> optional
* \lparam int size of msg t be received in bytes. -> optional
* \lreturn msg Lua string of received message or boolean true if written to Buffer.
* Is nil or false if nothing was received.
* \lreturn rcvd number of bytes recieved. 0 if nothing was received.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_recv( lua_State *L )
{
size_t len = 0; // length of sink buffer
size_t max; // desired or determined size to recv
int cw = 0; // test buffer to be writeable (can write)
ssize_t rcvd = 0; // actually rcvd bytes
luaL_Buffer lB;
char *msg; // char pointer to recv into
size_t args = lua_gettop( L );
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
struct sockaddr_storage *adr = t_net_adr_check_ud( L, 2, 0 );
if (t_buf_isstring( L, (NULL==adr) ?2 :3, &cw ) && cw) // is writable -> buffer
{
msg = t_buf_checklstring( L, (NULL==adr) ?2 :3, &len, &cw );
max = (args == ((NULL==adr) ?3 :4)) ? (size_t) luaL_checkinteger( L, (NULL==adr) ?3 :4 ) : len;
luaL_argcheck( L, max<=len, (NULL==adr) ?2 :3, "max must be smaller than sink" );
rcvd = p_net_sck_recv( sck, adr, msg, max );
if (rcvd > -1 ) // 0 for nothing received
lua_pushboolean( L, rcvd > 0 );
}
else
{
max = (args == ((NULL==adr) ?2 :3)) ? luaL_checkinteger( L, (NULL==adr) ?2 :3 ) : BUFSIZ-1;
luaL_argcheck( L, max<BUFSIZ, (NULL==adr) ? 2:3, "max must be smaller than BUFSIZ" );
msg = luaL_buffinitsize( L, &lB, max );
rcvd = p_net_sck_recv( sck, adr, msg, max );
if (rcvd < 1) // 0 for nothing received, -1 for errno being set
{
luaL_pushresultsize( &lB, 0 );
lua_pop( L, 1 );
if (0 == rcvd) // 0 for nothing received
lua_pushnil( L );
}
else
luaL_pushresultsize( &lB, rcvd );
}
if (-1 == rcvd)
return ((NULL == adr)
? t_push_error( L, 0, 1, "Can't receive message" )
: t_push_error( L, 0, 1, "Can't receive Message from %s", t_net_sck_getAddrString( L, adr ) )
);
lua_pushinteger( L, (lua_Integer) rcvd );
return 2;
}
/** -------------------------------------------------------------------------
* Recieve t.Net.Address from a (TCP) socket.
* \param L Lua state.
* \lparam sck t.Net.Socket userdata instance.
* \lparam adr t.Net.Address userdata instance.
* \lreturn ud t.Net.Address userdata instance.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck_getsockname( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
struct sockaddr_storage *adr = t_net_adr_check_ud( L, 2, 0 );
if (NULL == adr)
adr = t_net_adr_create_ud( L );
if (-1 == p_net_sck_getsockname( sck, adr ))
return t_push_error( L, 0, 1, "Couldn't get peer address" );
else
return 1;
}
/** -------------------------------------------------------------------------
* Systemcall select() for ready sockets.
* \param L Lua state.
* \lparam table Net socket table All sockets to read from.
* \lparam table Net socket table All sockets to write to.
* \lreturn table Net.Socket table of sockets ready to read from.
* \lreturn table Net.Socket table of sockets ready to write to.
* \return int # of values pushed onto the stack.
* TODO: Allow for a Time Out to be handed to it
*-------------------------------------------------------------------------*/
static int
lt_net_sck_Select( lua_State *L )
{
fd_set rfds, wfds;
struct t_net_sck *sck;
int rdyScks, i;
int rMax = p_net_sck_mkFdSet( L, 1, &rfds );
int wMax = p_net_sck_mkFdSet( L, 2, &wfds );
rdyScks = select(
(wMax > rMax) ? wMax+1 : rMax+1,
(-1 != rMax) ? &rfds : NULL,
(-1 != wMax) ? &wfds : NULL,
(fd_set *) 0,
NULL
);
lua_createtable( L, 0, 0 ); // create read result table
lua_createtable( L, 0, 0 ); // create write result table
for (i=1; i<3; i++)
{
lua_pushnil( L );
while (lua_next( L, i ))
{
sck = t_net_sck_check_ud( L, -1, 1 ); //S: rdi wri rdr wrr key sck
if (FD_ISSET( sck->fd, (1==i) ? &rfds : &wfds ))
{
if (lua_isinteger( L, -2 )) // append numeric idx
lua_rawseti( L, i+2, lua_rawlen( L, i+2 )+1 );
else
{
lua_pushvalue( L, -2 ); // reuse key for hash idx
lua_insert( L, -2 ); //S: rdi wri rdr wrr key key sck
lua_rawset( L, i+2 );
}
if (0 == --rdyScks)
{
lua_pop( L, 1 );
break;
}
}
else
lua_pop( L, 1 );
}
}
return 2;
}
/**--------------------------------------------------------------------------
* Prints out the socket.
* \param L Lua state.
* \lparam sck Net.Socket userdata instance.
* \lreturn string formatted string representing socket.
* \return int # of values pushed onto the stack.
* --------------------------------------------------------------------------*/
int
lt_net_sck__tostring( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
lua_pushfstring( L, T_NET_SCK_TYPE"{%d}: %p"
, sck->fd
, sck );
return 1;
}
static int t_net_sck_optCompare( const void *needle, const void *haystack )
{
const char *const key = needle;
const struct t_net_sck_option *const value = haystack;
return strcmp( key, value->name );
}
/** -------------------------------------------------------------------------
* __index; retrieve socket option values and other attributes
* \param L Lua state.
* \lparam ud T.Net.Socket userdata instance.
* \lparam string socket option name or function name.
* \lreturn value Lua value; socket option/attribute value or instance method
* function.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck__index( lua_State *L )
{
struct t_net_sck *sck = t_net_sck_check_ud( L, 1, 1 );
struct t_net_sck_option *opt = bsearch(
luaL_checkstring( L, 2 )
, t_net_sck_options
, T_NET_SCK_OPTS_MAX
, sizeof( struct t_net_sck_option )
, t_net_sck_optCompare
);
if (NULL == opt) //S: sck key val
{
// in case no socket option was requested, relay functions from the
// metatable if available (send,recv,accept,bind etc.). Can be nil.
lua_getmetatable( L, 1 );
lua_pushvalue( L, 2 );
lua_gettable( L, -2 );
return 1;
}
else
return p_net_sck_getSocketOption( L, sck, opt );
}
/** -------------------------------------------------------------------------
* __index; set socket option values and other attributes
* \param L Lua state.
* \lparam ud T.Net.Socket userdata instance.
* \lparam string socket option name or function name.
* \lparam value Lua value; socket option/attribute value.
* \return int # of values pushed onto the stack.
*-------------------------------------------------------------------------*/
static int
lt_net_sck__newindex( lua_State *L )
{
struct t_net_sck_option *opt = bsearch(
luaL_checkstring( L, 2 )
, t_net_sck_options
, T_NET_SCK_OPTS_MAX
, sizeof( struct t_net_sck_option )
, t_net_sck_optCompare
);
if (NULL == opt) //S: sck key val
return luaL_error( L, "Can't set unknown socket option: `%s`", lua_tostring( L, 2 ) );
else
{
if (opt->set)
return p_net_sck_setSocketOption( L, t_net_sck_check_ud( L, 1, 1 ), opt );
else
return luaL_error( L, "Socket option: `%s` is read-only", lua_tostring( L, 2 ) );
}
}
/**--------------------------------------------------------------------------
* Class metamethods library definition
* --------------------------------------------------------------------------*/
static const struct luaL_Reg t_net_sck_fm [] = {
{ NULL , NULL }
};
/**--------------------------------------------------------------------------
* Class functions library definition
* --------------------------------------------------------------------------*/
static const luaL_Reg t_net_sck_cf [] =
{
{ "select" , lt_net_sck_Select }
, { "new" , lt_net_sck_New }
, { NULL , NULL }
};
/**--------------------------------------------------------------------------
* Objects metamethods library definition
* --------------------------------------------------------------------------*/
static const luaL_Reg t_net_sck_m [] =
{
// metamethods
{ "__tostring" , lt_net_sck__tostring }
, { "__index" , lt_net_sck__index }
, { "__newindex" , lt_net_sck__newindex }
, { "__gc" , lt_net_sck_close }
// object methods
, { "listener" , lt_net_sck_listener }
, { "binder" , lt_net_sck_binder }
, { "connecter" , lt_net_sck_connecter }
, { "accept" , lt_net_sck_accept }
, { "close" , lt_net_sck_close }
, { "shutdowner" , lt_net_sck_shutDown }
, { "send" , lt_net_sck_send }
, { "recv" , lt_net_sck_recv }
, { "getsockname" , lt_net_sck_getsockname }
, { NULL , NULL }
};
/**--------------------------------------------------------------------------
* Pushes the Socket library onto the stack
* - creates Metatable with functions
* - creates metatable with methods
* \param L Lua state.
* \lreturn table the library
* \return int # of values pushed onto the stack.
* --------------------------------------------------------------------------*/
int
luaopen_t_net_sck( lua_State *L )
{
// just make metatable known to be able to register and check userdata
luaL_newmetatable( L, T_NET_SCK_TYPE ); // stack: functions meta
luaL_setfuncs( L, t_net_sck_m, 0 );
lua_pop( L, 1 );
p_net_sck_open( ); // native initialization
// Push the class onto the stack
// this is avalable as Socket.<member>
luaL_newlib( L, t_net_sck_cf );
lua_pushinteger( L, SHUT_RD ); // No more receptions.
lua_setfield( L, -2, "SHUT_RD" );
lua_pushstring( L, "SHUT_RD" );
lua_rawseti( L, -2, SHUT_RD );
lua_pushinteger( L, SHUT_WR ); // No more transmissions.
lua_setfield( L, -2, "SHUT_WR" );
lua_pushstring( L, "SHUT_WR" );
lua_rawseti( L, -2, SHUT_WR );
lua_pushinteger( L, SHUT_RDWR ); // No more receptions or transmissions.
lua_setfield( L, -2, "SHUT_RDWR" );
lua_pushstring( L, "SHUT_RDWR" );
lua_rawseti( L, -2, SHUT_RDWR );
// Load available Shutdown modes
luaopen_t_net_sck_typ( L );
lua_setfield( L, -2, T_NET_SCK_TYP_IDNT );
// Load available protocols
luaopen_t_net_sck_ptc( L );
lua_setfield( L, -2, T_NET_SCK_PTC_IDNT );
// set the methods as metatable
// this is only avalable a <instance>.<member>
luaL_newlib( L, t_net_sck_fm );
lua_setmetatable( L, -2 );
return 1;
}
| 37.243464 | 106 | 0.529241 |
5771ecfcbe7562a19079c204bad93fa1af117642 | 1,065 | h | C | lib/dht/DhtUtils.h | gjerecze/daqdb | ebab10f3ef2a64d541043b7378a951af294d44cb | [
"Apache-2.0"
] | 22 | 2019-02-08T17:23:12.000Z | 2021-10-12T06:35:37.000Z | lib/dht/DhtUtils.h | gjerecze/daqdb | ebab10f3ef2a64d541043b7378a951af294d44cb | [
"Apache-2.0"
] | 8 | 2019-02-11T06:30:47.000Z | 2020-04-22T09:49:44.000Z | lib/dht/DhtUtils.h | gjerecze/daqdb | ebab10f3ef2a64d541043b7378a951af294d44cb | [
"Apache-2.0"
] | 10 | 2019-02-11T10:26:52.000Z | 2019-09-16T20:49:25.000Z | /**
* Copyright (c) 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <asio/io_service.hpp>
namespace DaqDB
{
namespace utils
{
/*!
* Returns free network port
* @param io_service boost io service
* @param backbonePort prefered port, if not used then function should
* @param reuseAddr allow to reuse an address that is already in use
* return it as a result
*/
unsigned short getFreePort(asio::io_service &io_service,
const unsigned short backbonePort,
bool reuseAddr = false);
}
}
| 27.307692 | 75 | 0.733333 |
706f2d73f66935a2127e1195b5c38356ed811ca7 | 1,089 | h | C | Filters/OBBtoGrid/vtkOBBtoGrid.h | ObjectivitySRC/PVGPlugins | 5e24150262af751159d719cc810620d1770f2872 | [
"BSD-2-Clause"
] | 4 | 2016-01-21T21:45:43.000Z | 2021-07-31T19:24:09.000Z | Filters/OBBtoGrid/vtkOBBtoGrid.h | ObjectivitySRC/PVGPlugins | 5e24150262af751159d719cc810620d1770f2872 | [
"BSD-2-Clause"
] | null | null | null | Filters/OBBtoGrid/vtkOBBtoGrid.h | ObjectivitySRC/PVGPlugins | 5e24150262af751159d719cc810620d1770f2872 | [
"BSD-2-Clause"
] | 6 | 2015-08-31T06:21:03.000Z | 2021-07-31T19:24:10.000Z | /*create a structured grid inside an oriented bounding box*/
#ifndef _vtkOBBtoGrid_h
#define _vtkOBBtoGrid_h
#include "vtkStructuredGridAlgorithm.h"
/*
// Mirarco Mining Innovation
//
// Filter: Mine24DtoMap3D
// Class: vtkMine24DtoMap3D
// Author: Nehme Bilal
// Date: July 2009
// contact: nehmebilal@gmail.com
This filter allow creating a grid from an oriented box.
If you just have a set of points, use the FitDataSet filter to create an oriented bounding box
from the set of points.
*/
class VTK_EXPORT vtkOBBtoGrid : public vtkStructuredGridAlgorithm
{
public:
static vtkOBBtoGrid *New();
vtkTypeRevisionMacro(vtkOBBtoGrid,vtkStructuredGridAlgorithm);
vtkSetVector3Macro(GridSize, int);
vtkGetVector3Macro(GridSize, int);
protected:
vtkOBBtoGrid();
~vtkOBBtoGrid();
virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
virtual int FillInputPortInformation(int port, vtkInformation *info);
private:
int GridSize[3];
vtkOBBtoGrid(const vtkOBBtoGrid&);
void operator = (const vtkOBBtoGrid&);
};
#endif
| 23.170213 | 94 | 0.764004 |
7de1260525dd12417ef1495a3a74e1f84f7bfc0e | 378 | h | C | src/engine/audio/private/snd_dev_mac_audioqueue.h | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | src/engine/audio/private/snd_dev_mac_audioqueue.h | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | null | null | null | src/engine/audio/private/snd_dev_mac_audioqueue.h | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=====================================================================================//
#ifndef SND_DEV_MAC_AUDIOQUEUE_H
#define SND_DEV_MAC_AUDIOQUEUE_H
#pragma once
class IAudioDevice;
IAudioDevice *Audio_CreateMacAudioQueueDevice( void );
#endif // SND_DEV_MAC_AUDIOQUEUE_H
| 25.2 | 89 | 0.560847 |
e0f3974a79d13bbd82c06220a2a5d9f4bb023f85 | 7,184 | h | C | open-vm-tools/lib/include/hgfsServer.h | tmeralli-tehtris/open-vm-tools-security-research | 9f759add2ddb2c48a0588beb41295568301cad6a | [
"X11"
] | null | null | null | open-vm-tools/lib/include/hgfsServer.h | tmeralli-tehtris/open-vm-tools-security-research | 9f759add2ddb2c48a0588beb41295568301cad6a | [
"X11"
] | null | null | null | open-vm-tools/lib/include/hgfsServer.h | tmeralli-tehtris/open-vm-tools-security-research | 9f759add2ddb2c48a0588beb41295568301cad6a | [
"X11"
] | null | null | null | /*********************************************************
* Copyright (C) 1998 VMware, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*********************************************************/
#ifndef _HGFS_SERVER_H_
#define _HGFS_SERVER_H_
#include "hgfs.h" /* for HGFS_PACKET_MAX */
#include "dbllnklst.h"
/*
* Function used for sending updates of server state to the manager.
* Passed by the caller at session connect time.
*/
typedef void
HgfsServerStateLoggerFunc(void *data, // IN
uint64 cookie); // IN
typedef struct HgfsServerStateLogger {
HgfsServerStateLoggerFunc *logger; // logger callback
void *loggerData; // logger callback private data
} HgfsServerStateLogger;
typedef struct HgfsVmxIov {
void *va; /* Virtual addr */
uint64 pa; /* Physical address passed by the guest */
uint32 len; /* length of data; should be <= PAGE_SIZE for VMCI; arbitrary for backdoor */
void *context; /* Mapping context */
} HgfsVmxIov;
typedef enum {
BUF_READABLE, /* Establish readable mappings */
BUF_WRITEABLE, /* Establish writeable mappings */
BUF_READWRITEABLE, /* Establish read-writeable mappings */
} MappingType;
typedef uint64 HgfsStateFlags;
#define HGFS_STATE_CLIENT_REQUEST (1 << 0)
#define HGFS_STATE_ASYNC_REQUEST (1 << 1)
typedef struct HgfsPacket {
uint64 id;
HgfsStateFlags state;
/* For metapacket we always establish writeable mappings */
void *metaPacket;
size_t metaPacketSize;
uint32 metaPacketMappedIov;
size_t metaPacketDataSize;
Bool metaPacketIsAllocated;
MappingType metaMappingType;
void *dataPacket;
size_t dataPacketSize;
uint32 dataPacketMappedIov;
size_t dataPacketDataSize;
uint32 dataPacketIovIndex;
Bool dataPacketIsAllocated;
/* What type of mapping was established - readable/ writeable ? */
MappingType dataMappingType;
void *replyPacket;
size_t replyPacketSize;
size_t replyPacketDataSize;
Bool replyPacketIsAllocated;
/* Iov for the packet private to the channel. */
HgfsVmxIov channelIov[2];
uint32 iovCount;
HgfsVmxIov iov[1];
} HgfsPacket;
/*
* Function used for sending replies to the client for a session.
* Passed by the caller at session connect time.
*/
/*
* Send flags.
*
* Contains a bitwise OR of a combination of the following flags:
* HGFS_SEND_CAN_DELAY - directs the channel to try and optimize
* otherwise it will send the data immediately.
* HGFS_SEND_NO_COMPLETE - directs the channel to not call the
* send complete callback. Caller does not call completion notification
* callback, for example to free buffers.
*/
typedef uint32 HgfsSendFlags;
#define HGFS_SEND_CAN_DELAY (1 << 0)
#define HGFS_SEND_NO_COMPLETE (1 << 1)
// Channel capability flags
typedef uint32 HgfsChannelFlags;
#define HGFS_CHANNEL_SHARED_MEM (1 << 0)
#define HGFS_CHANNEL_ASYNC (1 << 1)
typedef struct HgfsServerChannelData {
HgfsChannelFlags flags;
uint32 maxPacketSize;
}HgfsServerChannelData;
/* Default maximum number of open nodes. */
#define HGFS_MAX_CACHED_FILENODES 30
typedef uint32 HgfsConfigFlags;
#define HGFS_CONFIG_USE_HOST_TIME (1 << 0)
#define HGFS_CONFIG_NOTIFY_ENABLED (1 << 1)
#define HGFS_CONFIG_VOL_INFO_MIN (1 << 2)
#define HGFS_CONFIG_OPLOCK_ENABLED (1 << 3)
#define HGFS_CONFIG_SHARE_ALL_HOST_DRIVES_ENABLED (1 << 4)
typedef struct HgfsServerConfig {
HgfsConfigFlags flags;
uint32 maxCachedOpenNodes;
}HgfsServerConfig;
typedef Bool (*HgfsChannelSendFunc)(void *opaqueSession,
HgfsPacket *packet,
HgfsSendFlags flags);
typedef void * (*HgfsChannelMapVirtAddrFunc)(uint64 pa, uint32 size, void **context);
typedef void (*HgfsChannelUnmapVirtAddrFunc)(void **context);
typedef struct HgfsServerChannelCallbacks {
HgfsChannelMapVirtAddrFunc getReadVa;
HgfsChannelMapVirtAddrFunc getWriteVa;
HgfsChannelUnmapVirtAddrFunc putVa;
HgfsChannelSendFunc send;
}HgfsServerChannelCallbacks;
typedef struct HgfsServerSessionCallbacks {
Bool (*connect)(void *, HgfsServerChannelCallbacks *, HgfsServerChannelData *,void **);
void (*disconnect)(void *);
void (*close)(void *);
void (*receive)(HgfsPacket *packet, void *);
void (*invalidateObjects)(void *, DblLnkLst_Links *);
uint32 (*invalidateInactiveSessions)(void *);
void (*sendComplete)(HgfsPacket *, void *);
} HgfsServerSessionCallbacks;
Bool HgfsServer_InitState(HgfsServerSessionCallbacks **,
HgfsServerConfig *,
HgfsServerStateLogger *);
void HgfsServer_ExitState(void);
uint32 HgfsServer_GetHandleCounter(void);
void HgfsServer_SetHandleCounter(uint32 newHandleCounter);
/*
* Function pointers used for getting names in HgfsServerGetDents
*
* Functions of this type are expected to return a NUL terminated
* string and the length of that string.
*/
typedef Bool
HgfsGetNameFunc(void *data, // IN
char const **name, // OUT
size_t *len, // OUT
Bool *done); // OUT
/*
* Associated setup and cleanup function types, which should be called
* before and after (respectively) HgfsGetNameFunc.
*/
typedef void *
HgfsInitFunc(void);
typedef Bool
HgfsCleanupFunc(void *); // IN
/*
* Function used for invalidating nodes and searches that fall outside of a
* share when the list of shares changes.
*/
typedef void
HgfsInvalidateObjectsFunc(DblLnkLst_Links *shares); // IN
/*
* Function used to notify HGFS server that a shared folder has been created or updated.
* It allows HGFS server to maintain up-to-date list of shared folders and its
* properties.
*/
typedef uint32 HgfsSharedFolderHandle;
#define HGFS_INVALID_FOLDER_HANDLE ((HgfsSharedFolderHandle)~((HgfsSharedFolderHandle)0))
typedef HgfsSharedFolderHandle
HgfsRegisterSharedFolderFunc(const char *shareName,
const char *sharePath,
Bool addFolder);
HgfsSharedFolderHandle HgfsServer_RegisterSharedFolder(const char *shareName,
const char *sharePath,
Bool addFolder);
void HgfsServer_Quiesce(Bool freeze);
#endif // _HGFS_SERVER_H_
| 33.259259 | 100 | 0.686386 |
7d417688268b5335016294969914e390d9ea1eda | 5,301 | h | C | s32v234_sdk/libs/isp/h264dec/kernel/linux/include/h264dcd_linux.h | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/isp/h264dec/kernel/linux/include/h264dcd_linux.h | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/isp/h264dec/kernel/linux/include/h264dcd_linux.h | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | 2 | 2021-01-21T02:06:16.000Z | 2021-01-28T10:47:37.000Z | /*
* Copyright (c) 2014-2016 Freescale Semiconductor
* Copyright (c) 2017-2018 NXP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* o Neither the name of NXP nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef H264DCDLLDCMD_H
#define H264DCDLLDCMD_H
/**
* @file h264dcd_linux.h
* brief Linux declarations for H264 Decoder driver
*/
#define LLDCMD_APP_TYPE 'c'
/************************************************
H264DCD LLDCMD function codes
*************************************************/
/************ Set Input Data ***************/
#define H264DCD_LLDCMD_INPUTSTREAM_CFG 1U
/************* Get FIFO Status **************/
#define H264DCD_LLDCMD_FIFO_STATUS_GET 2U
/*********** Get Data From FIFO ************/
#define H264DCD_LLDCMD_PCK_STATUS_GET 3U
/******** Set FIFO Watermark Level ***********/
#define H264DCD_LLDCMD_FIFO_WATERMARK_SET 4U
/************** Clear FIFO *************/
#define H264DCD_LLDCMD_FIFO_CLEAR 5U
/********** Set H264 Timeout **********/
#define H264DCD_LLDCMD_TIMEOUT_SET 6U
/********** Enable The TimeOut Check ***********/
#define H264DCD_LLDCMD_TIMEOUT_ENABLE 7U
/**************** Sw Reset ****************/
#define H264DCD_LLDCMD_SW_RESET 8U
/****** Set The Ouput Stream Configuration ******/
#define H264DCD_LLDCMD_OUTSTREAM_CFG 9U
/******** Set Sampling Mode **********/
#define H264DCD_LLDCMD_OUTSAMPLEMODE_SET 10U
/******* Set Output Image Colour Params ******/
#define H264DCD_LLDCMD_OUTCOLOURDATA_SET 11U
/********* Set The Data Flow Mode ***********/
#define H264DCD_LLDCMD_DATAFLOWMODE_SET 12U
/********* Get The Data Flow Mode ***********/
#define H264DCD_LLDCMD_DATAFLOWMODE_GET 13U
/******* Set The Bankstride Length ********/
#define H264DCD_LLDCMD_BANKSTRIDE_SET 14U
/******** Get The Bankstride Length *********/
#define H264DCD_LLDCMD_BANKSTRIDE_GET 15U
/*********** Channel Stop *************/
#define H264DCD_LLDCMD_DCD_CH_STOP 16U
/********* Set The Codded Image Size **********/
#define H264DCD_LLDCMD_DCD_INFRAMESIZE_SET 17U
/********* Set Memory Type & Filter ********/
#define H264DCD_LLDCMD_DCD_CFG_SET 18U
/********* Get Memory Type & Filter *********/
#define H264DCD_LLDCMD_DCD_CFG_GET 19U
/********* Set Threshold Levels ************/
#define H264DCD_LLDCMD_DCD_THRLEVELS_SET 20U
/********* Get Threshold Levels *************/
#define H264DCD_LLDCMD_DCD_THRLEVELS_GET 21U
/******** Set Reference Memory Address ********/
#define H264DCD_LLDCMD_DCD_REFMEMORY_SET 22U
/******** Get Reference Memory Address ********/
#define H264DCD_LLDCMD_DCD_REFMEMORY_GET 23U
/********** Get The Channel Status *********/
#define H264DCD_LLDCMD_CH_STATUS_GET 24U
/********* Get Decoded Image Paramters *********/
#define H264DCD_LLDCMD_PICDCD_PARAM_GET 25U
/******** Get Decoded Image Status ********/
#define H264DCD_LLDCMD_PICDCD_STATUS_GET 26U
/******** Get Decoded Image Gen Params *********/
#define H264DCD_LLDCMD_PICDCD_GENPARAMS_GET 27U
/******* Enable/Disable Interrupts ********/
#define H264DCD_LLDCMD_IRQ_CONTROL 28U
/********* Get The Enabled Interrupts *********/
#define H264DCD_LLDCMD_IRQ_GET 29U
/********* Get The TimeOut Intr Status ********/
#define H264DCD_LLDCMD_IRQ_TIMEOUT_GET 30U
/********* Get The Error Intr Status ********/
#define H264DCD_LLDCMD_IRQ_ERROR_GET 31U
/********* Get The Interrupts Flags **********/
#define H264DCD_LLDCMD_IRQ_STREAMSTATUS_GET 32U
#endif /* H264DCDLLDCMD_H */
| 37.06993 | 85 | 0.61196 |
00a26646a1b27ba48d44fa01bef6bb12a149fb10 | 854 | h | C | src/Core/MCVFreight.h | ykst/MobileCV | 57b969f708a2c742f446eb4a5b0a1d99ae945f7a | [
"MIT"
] | 1 | 2015-05-05T09:43:53.000Z | 2015-05-05T09:43:53.000Z | src/Core/MCVFreight.h | ykst/MobileCV | 57b969f708a2c742f446eb4a5b0a1d99ae945f7a | [
"MIT"
] | null | null | null | src/Core/MCVFreight.h | ykst/MobileCV | 57b969f708a2c742f446eb4a5b0a1d99ae945f7a | [
"MIT"
] | 2 | 2015-05-05T09:43:55.000Z | 2021-07-10T05:24:10.000Z | // Copyright (c) 2014 Yohsuke Yukishita
// This software is released under the MIT License: http://opensource.org/licenses/mit-license.php
#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>
@interface MCVFreight : NSObject
@end
@protocol MCVAttitudeFreightProtocol <NSObject>
@property (nonatomic, readonly) double roll;
@property (nonatomic, readonly) double pitch;
@property (nonatomic, readonly) double yaw;
@end
@protocol MCVVec3ArrayFreightProtocol <NSObject>
@property (nonatomic, readwrite) size_t effective_elems;
@property (nonatomic, readonly) size_t total_elems;
@property (nonatomic, readonly) GLKVector3 *buf;
@end
@protocol MCVVec4ArrayFreightProtocol <NSObject>
@property (nonatomic, readwrite) size_t effective_elems;
@property (nonatomic, readonly) size_t total_elems;
@property (nonatomic, readonly) GLKVector4 *buf;
@end
| 29.448276 | 98 | 0.793911 |
138a362c8f2b6e09b552ac876b7b4a49017656b1 | 3,548 | c | C | xdk-asf-3.51.0/common/services/clock/example2/clock_example2_xmega.c | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | xdk-asf-3.51.0/common/services/clock/example2/clock_example2_xmega.c | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | xdk-asf-3.51.0/common/services/clock/example2/clock_example2_xmega.c | j3270/SAMD_Experiments | 5c242aff44fc8d7092322d7baf2dda450a78a9b7 | [
"MIT"
] | null | null | null | /**
* \file
*
* \brief Clock system example 2
*
* Copyright (c) 2014-2018 Microchip Technology Inc. and its subsidiaries.
*
* \asf_license_start
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip
* software and any derivatives exclusively with Microchip products.
* It is your responsibility to comply with third party license terms applicable
* to your use of third party software (including open source software) that
* may accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES,
* WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE,
* INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE
* LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL
* LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE
* SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE
* POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT
* ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY
* RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*
* \asf_license_stop
*
*/
/**
* \mainpage
*
* \section intro Introduction
* This example shows how to initialize the clock system and output the
* CPU clock on a dedicated pin.
*
* \section files Main files:
* - clock_example2_xmega.c: clock system example application
* - conf_board.h: board initialization configuration
* - conf_clock.h: system clock configuration
* - conf_example2.h: chip- or board-specific example configuration
*
* \section deviceinfo Device Info
* All AVR XMEGA devices can be used.
*
* \section exampledescription Description of the example
* Pin 7 (\ref IOPORT_PIN) on a configurable port (\ref CLKOUT_PORT) is used for
* output of the CPU clock signal.
*
* The main system clock source and prescalers are defined in conf_clock.h.
* The port to output the clock signal on is defined in conf_example2.h.
*
* Refer to the \ref clk_group API documentation for further information on the
* clock configuration, and the \ref port_driver_group API documentation for
* further information on the pin configuration.
*
* \section compinfo Compilation Info
* This software was written for the GNU GCC and IAR for AVR.
* Other compilers may or may not work.
*
* \section contactinfo Contact Information
* For further information, visit
* <A href="http://www.microchip.com/">Microchip</A>.\n
*/
//! \name Example configuration
//@{
/**
* \def CLKOUT_PORT
* \brief Port to output clock signal on
*
* This is the configuration for the clock output port, and must be defined as
* one of the \c PORTCFG_CLKOUT_t settings of the device header file.
*
* \note It is only possible to select the port, not the pin: the clock signal
* will be output on pin 7 of the configured port.
*/
/**
* \def IOPORT_PIN
* \brief Pin to set as output for clock signal
*
* This must be defined as IOPORT pin 7 of the port setting in CLKOUT_PORT.
*/
/*
* Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a>
*/
//@}
#include <compiler.h>
#include <sysclk.h>
#include <ioport.h>
#include <conf_example2.h>
int main(void)
{
sysclk_init();
board_init();
ioport_configure_pin(IOPORT_PIN, IOPORT_DIR_OUTPUT);
PORTCFG.CLKEVOUT = CLKOUT_PORT;
while (1) {
/* Do nothing */
}
}
| 32.254545 | 92 | 0.737035 |
39790815892a32c31873fd793d00911e180ab62d | 4,666 | h | C | src/color.h | s-light/PaperCutLightBox_fw | 39d3c3fa54fd4b0a1a205b6e9612046703eec5e7 | [
"MIT"
] | null | null | null | src/color.h | s-light/PaperCutLightBox_fw | 39d3c3fa54fd4b0a1a205b6e9612046703eec5e7 | [
"MIT"
] | null | null | null | src/color.h | s-light/PaperCutLightBox_fw | 39d3c3fa54fd4b0a1a205b6e9612046703eec5e7 | [
"MIT"
] | null | null | null | /******************************************************************************
minimal float version of FastLED / FancyLED pixel types and HSV2RGB
Enjoy the colors :-)
heavily based on work from:
- https://github.com/FastLED/FastLED/
- https://github.com/adafruit/Adafruit_CircuitPython_FancyLED
written by stefan krueger (s-light),
github@s-light.eu, http://s-light.eu, https://github.com/s-light/
******************************************************************************/
/******************************************************************************
The MIT License (MIT)
Copyright (c) 2019 Stefan Krüger
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 color_H_
#define color_H_
// include Core Arduino functionality
#include <Arduino.h>
// enable float support
// https://github.com/arduino/ArduinoCore-samd/issues/217
asm(".global _printf_float");
struct CHSV {
// based on / copied partly from:
// https://github.com/FastLED/FastLED/blob/master/pixeltypes.h
union {
float hue;
float h;
};
union {
float saturation;
float sat;
float s;
};
union {
float value;
float val;
float v;
};
// default values are UNITIALIZED
inline CHSV() __attribute__((always_inline)) {}
// allow construction from H, S, V
inline CHSV( float ih, float is, float iv) __attribute__((always_inline))
: h(ih), s(is), v(iv) {}
CHSV operator + (const CHSV& obj) {
CHSV temp;
temp.hue = hue + obj.hue;
temp.sat = sat + obj.sat;
temp.val = val + obj.val;
return temp;
}
CHSV operator += (const CHSV& obj) {
// return this + obj;
CHSV temp;
temp.hue = hue + obj.hue;
temp.sat = sat + obj.sat;
temp.val = val + obj.val;
return temp;
}
CHSV operator * (const CHSV& obj) {
CHSV temp;
// temp.hue = hue * obj.hue;
// temp.sat = sat * obj.sat;
// temp.val = val * obj.val;
temp.hue = (hue + obj.hue) / 2;
temp.sat = (sat + obj.sat) / 2;
temp.val = (val + obj.val) / 2;
return temp;
}
CHSV operator *= (const CHSV& obj) {
CHSV temp;
// temp.hue = hue * obj.hue;
// temp.sat = sat * obj.sat;
// temp.val = val * obj.val;
temp.hue = (hue + obj.hue) / 2;
temp.sat = (sat + obj.sat) / 2;
temp.val = (val + obj.val) / 2;
return temp;
}
static void print(Print &out, CHSV &color);
void print(Print &out);
};
struct CRGB {
// based on / copied partly from:
// https://github.com/FastLED/FastLED/blob/master/pixeltypes.h
union {
float r;
float red;
};
union {
float g;
float green;
};
union {
float b;
float blue;
};
// default values are UNINITIALIZED
inline CRGB() __attribute__((always_inline)) {}
// allow construction from R, G, B
inline CRGB(float ir, float ig, float ib) __attribute__((always_inline))
: r(ir), g(ig), b(ib) {}
};
CRGB hsv2rgb(CHSV hsv);
// TODO(s-light): port hsv2rgb_rainbow
// https://github.com/FastLED/FastLED/blob/master/hsv2rgb.cpp#L278
// TODO(s-light): port gamma_adjust from
// https://github.com/adafruit/Adafruit_CircuitPython_FancyLED/blob/master/adafruit_fancyled/adafruit_fancyled.py#L331
// or
// https://github.com/FastLED/FastLED/blob/master/colorutils.h#L1679
// https://github.com/FastLED/FastLED/blob/master/colorutils.cpp#L1140-L1151
#endif // color_H_
| 29.910256 | 118 | 0.594514 |
c932e06407c88822541dce2a8c12e0533850bb9d | 14,461 | c | C | ref_code/cjdns/switch/EncodingScheme.c | krattai/noo-ebs | 00f67fd8f25b7c1eadf7348245670cb0ac911184 | [
"BSD-2-Clause"
] | 2 | 2015-04-07T14:37:24.000Z | 2015-11-06T00:31:01.000Z | ref_code/cjdns/switch/EncodingScheme.c | krattai/noo-ebs | 00f67fd8f25b7c1eadf7348245670cb0ac911184 | [
"BSD-2-Clause"
] | null | null | null | ref_code/cjdns/switch/EncodingScheme.c | krattai/noo-ebs | 00f67fd8f25b7c1eadf7348245670cb0ac911184 | [
"BSD-2-Clause"
] | null | null | null | /* vim: set expandtab ts=4 sw=4: */
/*
* You may redistribute this program 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/>.
*/
#include "benc/String.h"
#include "benc/Dict.h"
#include "memory/Allocator.h"
#include "switch/EncodingScheme.h"
#include "util/Bits.h"
#include "util/Hex.h"
int EncodingScheme_getFormNum(struct EncodingScheme* scheme, uint64_t routeLabel)
{
if (scheme->count == 1) {
return 0;
}
for (int i = 0; i < scheme->count; i++) {
struct EncodingScheme_Form* form = &scheme->forms[i];
Assert_true(form->prefixLen > 0 && form->prefixLen < 32);
Assert_true(form->bitCount > 0 && form->bitCount < 32);
if (0 == ((form->prefix ^ (uint32_t)routeLabel) << (32 - form->prefixLen))) {
return i;
}
}
return EncodingScheme_getFormNum_INVALID;
}
uint64_t EncodingScheme_convertLabel(struct EncodingScheme* scheme,
uint64_t routeLabel,
int convertTo)
{
int formNum = EncodingScheme_getFormNum(scheme, routeLabel);
if (formNum == EncodingScheme_getFormNum_INVALID) {
return EncodingScheme_convertLabel_INVALID;
}
struct EncodingScheme_Form* currentForm = &scheme->forms[formNum];
if (scheme->count == 1
|| (routeLabel & Bits_maxBits64(currentForm->prefixLen + currentForm->bitCount)) == 1)
{
// fixed width encoding or it's a self label, this is easy
switch (convertTo) {
case 0:
case EncodingScheme_convertLabel_convertTo_CANNONICAL: return routeLabel;
default: return EncodingScheme_convertLabel_INVALID;
}
}
routeLabel >>= currentForm->prefixLen;
uint64_t director = routeLabel & Bits_maxBits64(currentForm->bitCount);
routeLabel >>= currentForm->bitCount;
// ACKTUNG: Magic afoot!
// Conversions are necessary for two reasons.
// #1 ensure 0001 always references interface 1, the self interface.
// #2 reuse interface the binary encoding for interface 1 in other EncodingForms
// because interface 1 cannot be expressed as anything other than 0001
if ((currentForm->prefix & Bits_maxBits64(currentForm->prefixLen)) == 1) {
// Swap 0 and 1 if the prefix is 1, this makes 0001 alias to 1
// because 0 can never show up in the wild, we reuse it for 1.
Assert_true(director != 0);
if (director == 1) { director--; }
} else if (director) {
// Reuse the number 1 for 2 and 2 for 3 etc. to gain an extra slot in all other encodings.
director++;
}
if (convertTo == EncodingScheme_convertLabel_convertTo_CANNONICAL) {
// Take into account the fact that if the destination form does not have a 1 prefix,
// an extra number will be available.
int minBitsA = Bits_log2x64(director) + 1;
int minBitsB = Bits_log2x64(director-1) + 1;
for (int i = 0; i < scheme->count; i++) {
struct EncodingScheme_Form* form = &scheme->forms[i];
int minBits = ((form->prefix & Bits_maxBits64(form->prefixLen)) == 1)
? minBitsA : minBitsB;
if (form->bitCount >= minBits) {
convertTo = i;
break;
}
}
}
if (convertTo < 0 || convertTo >= scheme->count) {
// convertTo value is insane
return EncodingScheme_convertLabel_INVALID;
}
struct EncodingScheme_Form* nextForm = &scheme->forms[convertTo];
if ((nextForm->prefix & Bits_maxBits64(nextForm->prefixLen)) == 1) {
// Swap 1 and 0 back if necessary.
if (director == 0) { director++; }
} else if (director) {
// Or move the numbers down by one.
director--;
}
if ((Bits_log2x64(director) + 1) > nextForm->bitCount) {
// won't fit in requested form
return EncodingScheme_convertLabel_INVALID;
}
if (Bits_log2x64(routeLabel) + EncodingScheme_formSize(nextForm) > 59) {
return EncodingScheme_convertLabel_INVALID;
}
routeLabel <<= nextForm->bitCount;
routeLabel |= director;
routeLabel <<= nextForm->prefixLen;
routeLabel |= nextForm->prefix;
if ((routeLabel & Bits_maxBits64(nextForm->prefixLen + nextForm->bitCount)) == 1) {
// looks like a self-route
return EncodingScheme_convertLabel_INVALID;
}
return routeLabel;
}
/**
* Decode a form from it's binary representation.
* Can only use a maximum of 41 bits.
*
* @param out the output which will be populated with the encoding form data.
* @param data the binary data in host order.
* @return the number of bits of data which were consumed by the decoding.
* If the content is definitely not an encoding form, 0 is returned.
*/
static inline int decodeForm(struct EncodingScheme_Form* out, uint64_t d)
{
out->prefixLen = d & Bits_maxBits64(5);
d >>= 5;
int bitCount = d & Bits_maxBits64(5);
if (bitCount < 1) {
return 0;
}
out->bitCount = bitCount;
d >>= 5;
out->prefix = d & Bits_maxBits64(out->prefixLen);
return 5 + 5 + out->prefixLen;
}
static inline int encodeForm(struct EncodingScheme_Form* in, uint64_t* data, int bits)
{
*data |= ((uint64_t)in->prefixLen & Bits_maxBits64(5)) << bits;
bits += 5;
*data |= ((uint64_t)in->bitCount & Bits_maxBits64(5)) << bits;
bits += 5;
*data |= ((uint64_t)in->prefix & Bits_maxBits64(in->prefixLen)) << bits;
return 5 + 5 + in->prefixLen;
}
bool EncodingScheme_isSane(struct EncodingScheme* scheme)
{
// Check for obviously insane encoding.
if (scheme->count == 0) {
// No encoding schemes
return false;
}
if (scheme->count > 31) {
// impossible, each form must have a different bitCount and bitCount
// can only be expressed in 5 bits limiting it to 31 bits max and a form
// using zero bits is not allowed so there are only 31 max possibilities.
return false;
}
if (scheme->count == 1) {
// Fixed width encoding, prefix is not allowed and bitcount must be non-zero
if (scheme->forms[0].prefixLen != 0 || scheme->forms[0].prefix != 0) {
// prefixLen must be 0
return false;
}
if (scheme->forms[0].bitCount == 0 || scheme->forms[0].bitCount > 31) {
// bitcount must be non-zero and can't overflow the number
return false;
}
return true;
}
// Variable width encoding.
for (int i = 0; i < scheme->count; i++) {
struct EncodingScheme_Form* form = &scheme->forms[i];
if (form->prefixLen == 0 || form->prefixLen > 31) {
// Prefix must exist in order to distinguish between forms
return false;
}
if (form->bitCount == 0 || form->bitCount > 31) {
// Bitcount must be non-zero
return false;
}
if (EncodingScheme_formSize(form) > 59) {
// cannot be represented in the usable space in a label
return false;
}
if (i > 0 && form->bitCount <= scheme->forms[i-1].bitCount) {
// Forms must be in ascending order.
return false;
}
for (int j = 0; j < scheme->count; j++) {
// Forms must be distinguishable by their prefixes.
if (j != i
&& (scheme->forms[j].prefix & Bits_maxBits64(form->prefixLen)) == form->prefix)
{
return false;
}
}
}
return true;
}
List* EncodingScheme_asList(struct EncodingScheme* list, struct Allocator* alloc)
{
Assert_ifParanoid(EncodingScheme_isSane(list));
String* prefixLen = String_new("prefixLen", alloc);
String* bitCount = String_new("bitCount", alloc);
String* prefix = String_new("prefix", alloc);
List* scheme = List_new(alloc);
for (int i = 0; i < (int)list->count; i++) {
Dict* form = Dict_new(alloc);
Dict_putInt(form, prefixLen, list->forms[i].prefixLen, alloc);
Dict_putInt(form, bitCount, list->forms[i].bitCount, alloc);
String* pfx = String_newBinary(NULL, 8, alloc);
uint32_t prefix_be = Endian_hostToBigEndian32(list->forms[i].prefix);
Hex_encode(pfx->bytes, 8, (uint8_t*)&prefix_be, 4);
Dict_putString(form, prefix, pfx, alloc);
List_addDict(scheme, form, alloc);
}
return scheme;
}
struct EncodingScheme* EncodingScheme_fromList(List* scheme, struct Allocator* alloc)
{
struct EncodingScheme* list = Allocator_malloc(alloc, sizeof(struct EncodingScheme));
list->count = List_size(scheme);
list->forms = Allocator_malloc(alloc, sizeof(struct EncodingScheme_Form) * list->count);
for (int i = 0; i < (int)list->count; i++) {
Dict* form = List_getDict(scheme, i);
uint64_t* prefixLen = Dict_getInt(form, String_CONST("prefixLen"));
uint64_t* bitCount = Dict_getInt(form, String_CONST("bitCount"));
String* prefixStr = Dict_getString(form, String_CONST("prefix"));
if (!prefixLen || !bitCount || !prefixStr || prefixStr->len != 8) {
return NULL;
}
uint32_t prefix_be;
if (Hex_decode((uint8_t*)&prefix_be, 4, prefixStr->bytes, 8) != 4) {
return NULL;
}
list->forms[i].prefixLen = *prefixLen;
list->forms[i].bitCount = *bitCount;
list->forms[i].prefix = Endian_bigEndianToHost32(prefix_be);
}
if (!EncodingScheme_isSane(list)) {
return NULL;
}
return list;
}
String* EncodingScheme_serialize(struct EncodingScheme* list,
struct Allocator* alloc)
{
Assert_ifParanoid(EncodingScheme_isSane(list));
// Create the string as the largest that is possible for the list size.
String* out = String_newBinary(NULL, list->count * 6, alloc);
int bits = 0;
int outIndex = 0;
uint64_t block = 0;
for (int listIndex = 0; listIndex < (int)list->count; listIndex++) {
bits += encodeForm(&list->forms[listIndex], &block, bits);
while (bits > 8) {
Assert_true(outIndex < (int)out->len);
out->bytes[outIndex++] = (uint8_t) (block & 0xff);
bits -= 8;
block >>= 8;
}
}
if (bits > 0) {
out->bytes[outIndex++] = (uint8_t) (block & 0xff);
}
out->len = outIndex;
return out;
}
struct EncodingScheme* EncodingScheme_deserialize(String* data,
struct Allocator* alloc)
{
struct EncodingScheme_Form* forms = NULL;
int outCount = 0;
uint64_t block = 0;
int bits = 0;
int dataIndex = 0;
for (;;) {
// load data into the block from the incoming data source
while (bits < 56 && dataIndex < (int)data->len) {
block |= (((uint64_t)data->bytes[dataIndex++] & 0xff) << bits);
bits += 8;
}
struct EncodingScheme_Form next;
int ret = decodeForm(&next, block);
bits -= ret;
if (!ret || bits < 0) {
if (block || dataIndex < (int)data->len || bits < 0) {
// Invalid encoding
return NULL;
}
break;
}
block >>= ret;
Assert_true((next.prefix >> next.prefixLen) == 0);
outCount += 1;
forms = Allocator_realloc(alloc, forms, outCount * sizeof(struct EncodingScheme_Form));
Bits_memcpyConst(&forms[outCount-1], &next, sizeof(struct EncodingScheme_Form));
}
struct EncodingScheme* out = Allocator_clone(alloc, (&(struct EncodingScheme) {
.forms = forms,
.count = outCount
}));
return EncodingScheme_isSane(out) ? out : NULL;
}
struct EncodingScheme* EncodingScheme_defineFixedWidthScheme(int bitCount, struct Allocator* alloc)
{
struct NumberCompress_FixedWidthScheme
{
struct EncodingScheme scheme;
struct EncodingScheme_Form form;
};
struct NumberCompress_FixedWidthScheme* out =
Allocator_malloc(alloc, sizeof(struct NumberCompress_FixedWidthScheme));
struct NumberCompress_FixedWidthScheme scheme = {
.scheme = { .count = 1, .forms = &out->form },
.form = { .bitCount = bitCount, .prefixLen = 0, .prefix = 0, },
};
Bits_memcpyConst(out, &scheme, sizeof(struct NumberCompress_FixedWidthScheme));
Assert_true(EncodingScheme_isSane(&out->scheme));
return &out->scheme;
}
struct EncodingScheme* EncodingScheme_defineDynWidthScheme(struct EncodingScheme_Form* forms,
int formCount,
struct Allocator* alloc)
{
struct EncodingScheme_Form* formsCopy =
Allocator_malloc(alloc, sizeof(struct EncodingScheme_Form) * formCount);
Bits_memcpy(formsCopy, forms, sizeof(struct EncodingScheme_Form) * formCount);
struct EncodingScheme* scheme = Allocator_clone(alloc, (&(struct EncodingScheme) {
.count = formCount,
.forms = formsCopy
}));
Assert_ifParanoid(EncodingScheme_isSane(scheme));
return scheme;
}
int EncodingScheme_compare(struct EncodingScheme* a, struct EncodingScheme* b)
{
if (a->count == b->count) {
return Bits_memcmp(a->forms, b->forms, sizeof(struct EncodingScheme_Form) * a->count);
}
return a->count > b->count ? 1 : -1;
}
/**
* Return true if the route is to the switch's router interface.
*/
int EncodingScheme_isSelfRoute(struct EncodingScheme* scheme, uint64_t routeLabel)
{
int formNum = EncodingScheme_getFormNum(scheme, routeLabel);
if (formNum == EncodingScheme_getFormNum_INVALID) {
return 0;
}
struct EncodingScheme_Form* currentForm = &scheme->forms[formNum];
return (routeLabel & Bits_maxBits64(currentForm->prefixLen + currentForm->bitCount)) == 1;
}
| 35.270732 | 99 | 0.618491 |
3ad70f0fe4d43d99589146f29f506fafae8c7f70 | 396 | h | C | LuaGame/src/core/utils/point/Point2f.h | Urnark/LuaWrapper | 641520c554a4f64ccb237f3f559ddc8d9c42f3ee | [
"MIT"
] | null | null | null | LuaGame/src/core/utils/point/Point2f.h | Urnark/LuaWrapper | 641520c554a4f64ccb237f3f559ddc8d9c42f3ee | [
"MIT"
] | 1 | 2019-02-28T10:18:50.000Z | 2019-02-28T10:19:45.000Z | LuaGame/src/core/utils/point/Point2f.h | Urnark/LuaWrapper | 641520c554a4f64ccb237f3f559ddc8d9c42f3ee | [
"MIT"
] | null | null | null | #pragma once
#include <SFML\Graphics.hpp>
#include <Wrapper\FunctionWrapper\LuaFunctionsWrapper.h>
class Point2f : public lw::ReturnToLua<float, float>
{
public:
float x, y;
Point2f() { x = 0.0f; y = 0.0F; }
Point2f(float x, float y) { this->x = x; this->y = y; };
sf::Vector2f getPos() const { return sf::Vector2f(x, y); };
void SetReturnVariables() {
LW_SetReturnValues(x, y);
}
}; | 20.842105 | 60 | 0.661616 |
be603a79a2734c91442f817955de9061f5ec1db5 | 2,702 | h | C | Sandbox/Eudora/TocFrame.h | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 10 | 2018-05-23T10:43:48.000Z | 2021-12-02T17:59:48.000Z | Windows/Sandbox/Eudora/TocFrame.h | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 1 | 2019-03-19T03:56:36.000Z | 2021-05-26T18:36:03.000Z | Windows/Sandbox/Eudora/TocFrame.h | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 11 | 2018-05-23T10:43:53.000Z | 2021-12-27T15:42:58.000Z | #if !defined(AFX_TOCFRAME_H__CE6A8E92_1B2D_11D1_91DB_00805FD2B1FA__INCLUDED_)
#define AFX_TOCFRAME_H__CE6A8E92_1B2D_11D1_91DB_00805FD2B1FA__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// TocFrame.h : header file
//
#include "mdidrag.h"
#include "MsgSplitter.h"
class CSummary;
/////////////////////////////////////////////////////////////////////////////
// CTocFrame frame
class CTocFrame : public CMDIChildTarget
{
INT m_iMajorVersion;
INT m_iMinorVersion;
CSummary* m_pPreviewSummary;
DWORD m_dwStartPreviewTime;
int m_nTocListHeight;
// for the automarkasread hack
bool m_bSchmookieState;
DECLARE_DYNCREATE(CTocFrame)
protected:
CTocFrame(); // protected constructor used by dynamic creation
// Operations
public:
INT GetSplitterPos();
CSummary* GetPreviewSummary() { return m_pPreviewSummary; }
// Overrides
virtual BOOL OnCreateClient( LPCREATESTRUCT lpcs, CCreateContext* pContext);
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTocFrame)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
//}}AFX_VIRTUAL
INT GetMajorVersion() const { return m_iMajorVersion; }
INT GetMinorVersion() const { return m_iMinorVersion; }
void ShowHideSplitter();
// Implementation
protected:
virtual ~CTocFrame();
void DoPreviewDisplay();
bool ShouldPreview();
CMsgSplitterWnd m_wndSplitter;
// Generated message map functions
//{{AFX_MSG(CTocFrame)
afx_msg void OnChildActivate();
afx_msg long OnPreviewMessage( WPARAM wParam, LPARAM lParam );
afx_msg long OnPurgeSummaryCache( WPARAM wParam, LPARAM lParam );
afx_msg long OnInitPreview( WPARAM wParam, LPARAM lParam );
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnCmdDelete();
afx_msg void OnUpdateCmdDelete(CCmdUI* pCmdUI);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint ptScreen);
afx_msg void OnClose();
afx_msg void OnToggleHeader();
afx_msg void OnEditFindFindMsg();
afx_msg void OnUpdateCmdUndelete (CCmdUI* pCmdUI);
afx_msg void OnUpdateCmdImapExpunge (CCmdUI* pCmdUI);
afx_msg void OnCmdUnDelete();
afx_msg void OnCmdImapExpunge();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
CSummary* GetPreviewableSummaryFromDoc();
BOOL m_bIsPreviewPaneEmpty;
CSummary* m_pPreviousPreviewableSummaryFromDoc;
BOOL m_bDoAutoMarkAsRead;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TOCFRAME_H__CE6A8E92_1B2D_11D1_91DB_00805FD2B1FA__INCLUDED_)
| 27.02 | 103 | 0.741673 |
67b1a78ef836d15efaabe48592c05951a92e8cbf | 358 | h | C | src/hfs/hfs_btree.h | ahknight/hfsinspect | 02e0853b68e13cdb3dff5b82056bc17ae96275c9 | [
"MIT"
] | 31 | 2015-02-14T18:26:06.000Z | 2021-09-15T16:51:01.000Z | src/hfs/hfs_btree.h | NSGod/hfsinspect | 02e0853b68e13cdb3dff5b82056bc17ae96275c9 | [
"MIT"
] | 6 | 2015-02-12T00:20:51.000Z | 2020-05-06T11:43:21.000Z | src/hfs/hfs_btree.h | NSGod/hfsinspect | 02e0853b68e13cdb3dff5b82056bc17ae96275c9 | [
"MIT"
] | 3 | 2015-12-30T18:27:48.000Z | 2018-09-16T09:29:45.000Z | //
// hfs_btree.h
// hfsinspect
//
// Created by Adam Knight on 6/4/13.
// Copyright (c) 2013 Adam Knight. All rights reserved.
//
#ifndef hfsinspect_hfs_btree_h
#define hfsinspect_hfs_btree_h
#include "hfs/types.h"
#include "hfs/btree/btree.h"
int hfs_get_btree(BTreePtr* btree, const HFSPlus* hfs, hfs_cnid_t cnid) __attribute__((nonnull));
#endif
| 19.888889 | 97 | 0.731844 |
a7f9eb20c92eb22fdf241a7a80b2bf5951e1f765 | 1,792 | h | C | Firmware/Version_1_0/ADE9000.h | voelkerb/smartmeter | 60c4105f615b3759c66acd30e62a35b4a44b7d3f | [
"CC-BY-4.0"
] | 1 | 2021-03-12T23:09:09.000Z | 2021-03-12T23:09:09.000Z | Firmware/Version_1_0/ADE9000.h | voelkerb/smartmeter | 60c4105f615b3759c66acd30e62a35b4a44b7d3f | [
"CC-BY-4.0"
] | null | null | null | Firmware/Version_1_0/ADE9000.h | voelkerb/smartmeter | 60c4105f615b3759c66acd30e62a35b4a44b7d3f | [
"CC-BY-4.0"
] | null | null | null | /*
* Copyright: Gregor Richter
* Author: Gregor Richter
* Remarks: all rights reserved, this Copyright must be included
*/
#ifndef ADE9000_H_
#define ADE9000_H_
#define ADE9000_DEFAULT_SPI VSPI
#include <SPI.h>
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
class ADE9000 {
private:
SPIClass *_spi;
int8_t _spi_num;
int8_t _ss;
bool _burst_en;
public:
// Constructor build a new SPI object
ADE9000(uint8_t spi_bus = VSPI); // FIXME
~ADE9000(void);
// config Interrupt, reset ADE9000 and conig it with defaults
void setup(void);
// reset the ADE9000
void reset(void);
// open SPI (you can reconfig the SPI signals)
void begin(int8_t sck = -1, int8_t miso = -1, int8_t mosi = -1, int8_t ss = -1);
// setup ISR, used the IRAM_ATTR Macro for initialization!!!
// Exampe: void IRAM_ATTR ISR_FUNC_NAME(void) { ... }
// [ ... ]
// call: setupInterrupt( ISR_FUNC_NAME );
void setupInterrupt(void (*)(void));
void clearInterrupt(void);
// close SPI
void end(void);
void dataBitShift(uint8_t *data, uint16_t size);
uint16_t read_16(uint16_t addr);
uint32_t read_32(uint16_t addr);
void write_16(uint16_t addr, uint16_t data);
void write_32(uint16_t addr, uint32_t data);
void burst_read_en(bool enable);
void burst_read(uint16_t addr, uint32_t *data, uint16_t size);
// Unfortunately the "RX-Buffer-Full-interrupt" of the ESP-SPI does not work
// as expected, therefore the SPI bus must be accessed close to the hardware:
// write Data on SPI out
void burst_write_SPI(uint8_t *tx_data, uint8_t bytes);
// read RX Buffer. Returns "False" if the SPI is still busy.
bool burst_read_SPI_Buffer(uint8_t *rx_data, uint8_t bytes);
};
#endif // ADE9000_H_
| 21.853659 | 82 | 0.694754 |
57f772bd4624fa928c77f74e6341bb3452edea34 | 965 | h | C | FirmwareSource/libraries/MF_Modules/MFAnalog.h | rofl-er/MobiFlight-Connector | 1f0fd45fe1c29fe48a2cb60683d9446e1bc7dcc2 | [
"Unlicense"
] | null | null | null | FirmwareSource/libraries/MF_Modules/MFAnalog.h | rofl-er/MobiFlight-Connector | 1f0fd45fe1c29fe48a2cb60683d9446e1bc7dcc2 | [
"Unlicense"
] | null | null | null | FirmwareSource/libraries/MF_Modules/MFAnalog.h | rofl-er/MobiFlight-Connector | 1f0fd45fe1c29fe48a2cb60683d9446e1bc7dcc2 | [
"Unlicense"
] | null | null | null | // MFSegments.h
//
/// \mainpage MF MFAnalog module for MobiFlight Framework
/// \par Revision History
/// \version 1.0 Initial release
/// \author Manfred Berry (manfred@nystedberry.info) DO NOT CONTACT THE AUTHOR DIRECTLY: USE THE LISTS
// Copyright (C) 2021 Manfred Berry
#ifndef MFAnalog_h
#define MFAnalog_h
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
extern "C"
{
// callback functions
typedef void (*analogEvent) (int, uint8_t, const char *);
};
/////////////////////////////////////////////////////////////////////
/// \class MFAnalog MFAnalog.h <MFAnalog.h>
class MFAnalog
{
public:
MFAnalog(uint8_t pin = 1, analogEvent callback = NULL, const char * name = "Analog Input", uint8_t sensitivity = 2);
void update();
const char * _name;
uint8_t _pin;
private:
int _lastValue;
uint32_t _last;
analogEvent _handler;
uint8_t _sensitivity;
};
#endif | 23.536585 | 120 | 0.620725 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.