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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24c05a31c39cbce3b007a6019d9d500e22bd79b5 | 10,237 | c | C | src/plugins/custom/regmark/metaphone.c | wiedi/rspamd | 9c9527faa922fff90f04a7c22788a282b4b02fa1 | [
"BSD-2-Clause"
] | null | null | null | src/plugins/custom/regmark/metaphone.c | wiedi/rspamd | 9c9527faa922fff90f04a7c22788a282b4b02fa1 | [
"BSD-2-Clause"
] | null | null | null | src/plugins/custom/regmark/metaphone.c | wiedi/rspamd | 9c9527faa922fff90f04a7c22788a282b4b02fa1 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2009-2012, Vsevolod Stakhov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR ''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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This is implementation of metaphone algorithm that was originally written by
* Michael G Schwern <schwern@pobox.com> as perl XS module
*/
/*
* I suppose I could have been using a character pointer instead of
* accesssing the array directly...
*/
#include "config.h"
#include "metaphone.h"
/*
* Look at the next letter in the word
*/
#define Next_Letter (g_ascii_toupper (word[w_idx+1]))
/*
* Look at the current letter in the word
*/
#define Curr_Letter (g_ascii_toupper(word[w_idx]))
/*
* Go N letters back.
*/
#define Look_Back_Letter(n) (w_idx >= n ? g_ascii_toupper(word[w_idx-n]) : '\0')
/*
* Previous letter. I dunno, should this return null on failure?
*/
#define Prev_Letter (Look_Back_Letter(1))
/*
* Look two letters down. It makes sure you don't walk off the string.
*/
#define After_Next_Letter (Next_Letter != '\0' ? g_ascii_toupper(word[w_idx+2]) \
: '\0')
#define Look_Ahead_Letter(n) (g_ascii_toupper(Lookahead(word+w_idx, n)))
#define SH 'X'
#define TH '0'
/*-- Character encoding array & accessing macros --*/
/* Stolen directly out of the book... */
char _codes[26] = {
1,16,4,16,9,2,4,16,9,2,0,2,2,2,1,4,0,2,4,4,1,0,0,0,8,0
/* a b c d e f g h i j k l m n o p q r s t u v w x y z */
};
/*
* Allows us to safely look ahead an arbitrary # of letters
*/
/*
* I probably could have just used strlen...
*/
static char
Lookahead (char *word, int how_far)
{
char letter_ahead = '\0'; /* null by default */
int idx;
for (idx = 0; word[idx] != '\0' && idx < how_far; idx++);
/*
* Edge forward in the string...
*/
letter_ahead = word[idx]; /* idx will be either == to how_far or at
* the end of the string */
return letter_ahead;
}
/*
* phonize one letter
*/
#define Phonize(c) {p[p_idx++] = c;}
/*
* Slap a null character on the end of the phoned word
*/
#define End_Phoned_Word {p[p_idx] = '\0';}
/*
* How long is the phoned word?
*/
#define Phone_Len (p_idx)
/*
* Note is a letter is a 'break' in the word
*/
#define Isbreak(c) (!g_ascii_isalpha(c))
gboolean
metaphone (char *word, int max_phonemes, char **phoned_word)
{
int w_idx = 0; /* point in the phonization we're at. */
int p_idx = 0; /* end of the phoned phrase */
char *p;
/*-- Parameter checks --*/
/*
* Assume largest possible if we're given no limit
*/
if (max_phonemes == 0) {
max_phonemes = strlen (word) * 2 + 1;
}
if (max_phonemes == 0) {
return FALSE;
}
/*-- Allocate memory for our phoned_phrase --*/
*phoned_word = g_malloc (max_phonemes * sizeof (char));
p = *phoned_word;
/*-- The first phoneme has to be processed specially. --*/
/*
* Find our first letter
*/
for (; ! g_ascii_isalpha (Curr_Letter); w_idx++) {
/*
* On the off chance we were given nothing but crap...
*/
if (Curr_Letter == '\0') {
End_Phoned_Word
return TRUE; /* For testing */
}
}
switch (Curr_Letter) {
/*
* AE becomes E
*/
case 'A':
if (Next_Letter == 'E') {
Phonize ('E');
w_idx += 2;
}
/*
* Remember, preserve vowels at the beginning
*/
else {
Phonize ('A');
w_idx++;
}
break;
/*
* [GKP]N becomes N
*/
case 'G':
case 'K':
case 'P':
if (Next_Letter == 'N') {
Phonize ('N');
w_idx += 2;
}
break;
/*
* WH becomes H, WR becomes R W if followed by a vowel
*/
case 'W':
if (Next_Letter == 'H' || Next_Letter == 'R') {
Phonize (Next_Letter);
w_idx += 2;
} else if (isvowel (Next_Letter)) {
Phonize ('W');
w_idx += 2;
}
/*
* else ignore
*/
break;
/*
* X becomes S
*/
case 'X':
Phonize ('S');
w_idx++;
break;
/*
* Vowels are kept
*/
/*
* We did A already case 'A': case 'a':
*/
case 'E':
case 'I':
case 'O':
case 'U':
Phonize (Curr_Letter);
w_idx++;
break;
}
/*
* On to the metaphoning
*/
for (; Curr_Letter != '\0' && (max_phonemes == 0 || Phone_Len < max_phonemes); w_idx++) {
/*
* How many letters to skip because an eariler encoding handled
* multiple letters
*/
unsigned short int skip_letter = 0;
/*
* THOUGHT: It would be nice if, rather than having things like...
* well, SCI. For SCI you encode the S, then have to remember to
* skip the C. So the phonome SCI invades both S and C. It would
* be better, IMHO, to skip the C from the S part of the encoding.
* Hell, I'm trying it.
*/
/*
* Ignore non-alphas
*/
if (! g_ascii_isalpha (Curr_Letter))
continue;
/*
* Drop duplicates, except CC
*/
if (Curr_Letter == Prev_Letter && Curr_Letter != 'C')
continue;
switch (Curr_Letter) {
/*
* B -> B unless in MB
*/
case 'B':
if (Prev_Letter != 'M')
Phonize ('B');
break;
/*
* 'sh' if -CIA- or -CH, but not SCH, except SCHW. (SCHW is
* handled in S) S if -CI-, -CE- or -CY- dropped if -SCI-,
* SCE-, -SCY- (handed in S) else K
*/
case 'C':
if (MAKESOFT (Next_Letter)) { /* C[IEY] */
if (After_Next_Letter == 'A' && Next_Letter == 'I') { /* CIA
*/
Phonize (SH);
}
/*
* SC[IEY]
*/
else if (Prev_Letter == 'S') {
/*
* Dropped
*/
} else {
Phonize ('S');
}
} else if (Next_Letter == 'H') {
#ifndef USE_TRADITIONAL_METAPHONE
if (After_Next_Letter == 'R' || Prev_Letter == 'S') { /* Christ,
* School
*/
Phonize ('K');
} else {
Phonize (SH);
}
#else
Phonize (SH);
#endif
skip_letter++;
} else {
Phonize ('K');
}
break;
/*
* J if in -DGE-, -DGI- or -DGY- else T
*/
case 'D':
if (Next_Letter == 'G' && MAKESOFT (After_Next_Letter)) {
Phonize ('J');
skip_letter++;
} else {
Phonize ('T');
}
break;
/*
* F if in -GH and not B--GH, D--GH, -H--GH, -H---GH else
* dropped if -GNED, -GN, else dropped if -DGE-, -DGI- or
* -DGY- (handled in D) else J if in -GE-, -GI, -GY and not GG
* else K
*/
case 'G':
if (Next_Letter == 'H') {
if (!(NOGHTOF (Look_Back_Letter (3)) ||
Look_Back_Letter (4) == 'H')) {
Phonize ('F');
skip_letter++;
} else {
/*
* silent
*/
}
} else if (Next_Letter == 'N') {
if (Isbreak (After_Next_Letter) ||
(After_Next_Letter == 'E' &&
Look_Ahead_Letter (3) == 'D')) {
/*
* dropped
*/
} else {
Phonize ('K');
}
} else if (MAKESOFT (Next_Letter) && Prev_Letter != 'G') {
Phonize ('J');
} else {
Phonize ('K');
}
break;
/*
* H if before a vowel and not after C,G,P,S,T
*/
case 'H':
if (isvowel (Next_Letter) && !AFFECTH (Prev_Letter)) {
Phonize ('H');
}
break;
/*
* dropped if after C else K
*/
case 'K':
if (Prev_Letter != 'C') {
Phonize ('K');
}
break;
/*
* F if before H else P
*/
case 'P':
if (Next_Letter == 'H') {
Phonize ('F');
} else {
Phonize ('P');
}
break;
/*
* K
*/
case 'Q':
Phonize ('K');
break;
/*
* 'sh' in -SH-, -SIO- or -SIA- or -SCHW- else S
*/
case 'S':
if (Next_Letter == 'I' &&
(After_Next_Letter == 'O' || After_Next_Letter == 'A')) {
Phonize (SH);
} else if (Next_Letter == 'H') {
Phonize (SH);
skip_letter++;
}
#ifndef USE_TRADITIONAL_METAPHONE
else if (Next_Letter == 'C' &&
Look_Ahead_Letter (2) == 'H' &&
Look_Ahead_Letter (3) == 'W') {
Phonize (SH);
skip_letter += 2;
}
#endif
else {
Phonize ('S');
}
break;
/*
* 'sh' in -TIA- or -TIO- else 'th' before H else T
*/
case 'T':
if (Next_Letter == 'I' &&
(After_Next_Letter == 'O' || After_Next_Letter == 'A')) {
Phonize (SH);
} else if (Next_Letter == 'H') {
Phonize (TH);
skip_letter++;
} else {
Phonize ('T');
}
break;
/*
* F
*/
case 'V':
Phonize ('F');
break;
/*
* W before a vowel, else dropped
*/
case 'W':
if (isvowel (Next_Letter)) {
Phonize ('W');
}
break;
/*
* KS
*/
case 'X':
Phonize ('K');
Phonize ('S');
break;
/*
* Y if followed by a vowel
*/
case 'Y':
if (isvowel (Next_Letter)) {
Phonize ('Y');
}
break;
/*
* S
*/
case 'Z':
Phonize ('S');
break;
/*
* No transformation
*/
case 'F':
case 'J':
case 'L':
case 'M':
case 'N':
case 'R':
Phonize (Curr_Letter);
break;
} /* END SWITCH */
w_idx += skip_letter;
} /* END FOR */
End_Phoned_Word;
return TRUE;
}
| 22.206074 | 93 | 0.545472 |
f21eb930c2078530684bb476835cf5ad2046abd2 | 9,612 | h | C | modules/apps/include/v4r/apps/compute_recognition_rate.h | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 17 | 2015-11-16T14:21:10.000Z | 2020-11-09T02:57:33.000Z | modules/apps/include/v4r/apps/compute_recognition_rate.h | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 35 | 2015-07-27T15:04:43.000Z | 2019-08-22T10:52:35.000Z | modules/apps/include/v4r/apps/compute_recognition_rate.h | ToMadoRe/v4r | 7cb817e05cb9d99cb2f68db009c27d7144d07f09 | [
"MIT"
] | 18 | 2015-08-06T09:26:27.000Z | 2020-09-03T01:31:00.000Z | #pragma once
#include <v4r/core/macros.h>
#include <v4r/common/pcl_visualization_utils.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <iostream>
#include <sstream>
#include <fstream>
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
#undef BOOST_NO_CXX11_SCOPED_ENUMS
namespace bf = boost::filesystem;
namespace v4r
{
namespace apps
{
struct Hypothesis
{
Eigen::Matrix4f pose;
float occlusion;
};
class V4R_EXPORTS RecognitionEvaluator
{
private:
typedef pcl::PointXYZRGB PointT;
struct Model
{
pcl::PointCloud<PointT>::Ptr cloud;
Eigen::Vector4f centroid;
bool is_rotation_invariant_ = false; // in-plane (x/y)
bool is_rotational_symmetric_ = false;
};
float rotation_error_threshold_deg;
float translation_error_threshold_m;
float occlusion_threshold;
std::vector<std::string> coordinate_system_ids_;
std::string out_dir;
std::string gt_dir;
std::string or_dir;
std::string models_dir;
std::string test_dir;
bool visualize_;
bool visualize_errors_only_;
bool save_images_to_disk_;
bool highlight_errors_;
bool use_generated_hypotheses_;
pcl::visualization::PCLVisualizer::Ptr vis_;
int vp1_, vp2_, vp3_;
std::map<std::string, Model> models;
PCLVisualizationParams::Ptr vis_params_;
void loadModels();
std::vector<std::string> rotational_symmetric_objects_; ///< name of objects which are rotational symmetric with respect to xy plane
std::vector<std::string> rotational_invariant_objects_; ///< name of objects which are rotational invariant with respect to xy plane
public:
RecognitionEvaluator()
:
rotation_error_threshold_deg(30.f),
translation_error_threshold_m(0.05f),
occlusion_threshold(0.95f),
out_dir("/tmp/recognition_rates/"),
visualize_(false),
visualize_errors_only_(false),
save_images_to_disk_(false),
highlight_errors_ (false),
use_generated_hypotheses_(false)
{
rotational_invariant_objects_ = {
"toilet_paper", "red_mug_white_spots", "muller_milch_shoko", "muller_milch_banana", "coffee_container",
"object_11", "object_19", "object_29", "object_32",
"object_18", "object_22", "object_23", "object_25", "object_27", "object_28" //last row are debatable objects - not completely invariant but very hard to distinguish
};
rotational_symmetric_objects_ = {
"jasmine_green_tea", "fruchtmolke", "asus_box",
"object_10", "object_26", "object_35",
"object_01", "object_02", "object_03", "object_09", "object_08", "object_30", "object_31", "object_33" //last row are debatable objects - not 100% symmetric but very hard to distinguish
};
vis_params_.reset(new PCLVisualizationParams());
vis_params_->bg_color_ = Eigen::Vector3i(255,255,255);
vis_params_->coordinate_axis_scale_ = 0.04f;
}
/**
* @brief init set directories and stuff from (boost) console arguments
* @param params parameters (boost program options)
* @param unused parameters
*/
std::vector<std::string>
init(const std::vector<std::string> ¶ms);
// ======= DECLARATIONS ===================
/**
* @brief computeError compute translation error for a given pose
* @param[in] pose_a
* @param[in] pose_b
* @param[in] centroid of object model in model coordinate system
* @param[out] trans_error translation error
* @param[out] rot_error rotation error
* @param[in] true if model is invariant for rotation around z
* @param[in] true if model is symmetric for rotation around z (180deg periodic)
* @return boolean indicitating if error is outside given threshold
*/
bool computeError(const Eigen::Matrix4f &pose_a, const Eigen::Matrix4f &pose_b, const Eigen::Vector4f ¢roid_model,
float &trans_error, float &rot_error, bool is_rotation_invariant , bool is_rotational_symmetric );
/**
* @brief checkMatchvector check a certain match configuration
* @param[in] rec2gt matches indicated by first index corresponding
* to model id and second index to ground-truth id
* @param[in] rec_hyps recognition hypotheses
* @param[in] gt_hyps ground-truth hypotheses
* @param[in] centroid of object model in model coordinate system
* @param[out] translation_errors
* @param[out] rotational_errors
* @param[out] tp true positives
* @param[out] fp flase positives
* @param[out] fn false negatives
* @param[in] true if model is invariant for rotation around z
* @param[in] true if model is symmetric for rotation around z (180deg periodic)
*/
void checkMatchvector(const std::vector< std::pair<int, int> > &rec2gt,
const std::vector<Hypothesis> &rec_hyps,
const std::vector<Hypothesis> >_hyps,
const Eigen::Vector4f &model_centroid,
std::vector<float> &translation_error,
std::vector<float> &rotational_error,
size_t &tp, size_t &fp, size_t &fn,
bool is_rotation_invariant , bool is_rotational_symmetric );
/**
* @brief selectBestMatch computes the best matches for a set of hypotheses. This
* tackles the problem when multiple object instances are present in the scene and
* the question is which ground-truth object belongs to which recognized object. By
* permuating through all possible solutions, it finds the match which gives the
* best f-score taking into account to be neglected hypotheses due to occlusion.
* @param rec_hyps recognized hypotheses
* @param gt_hyps ground-truth hypotheses
* @param centroid of object model in model coordinate system
* @param tp true positives for best match
* @param fp false positives for best match
* @param fn false negatives for best match
* @param translation_errors accumulated translation error for best match
* @param rotational_errors accumulated rotational error for best match
* @param[in] true if model is invariant for rotation around z
* @param[in] true if model is symmetric for rotation around z (180deg periodic)
* @return best match for the given hypotheses. First index corresponds to element in
* given recognition hypothesis, second index to ground-truth hypothesis
*/
std::vector<std::pair<int, int> > selectBestMatch(const std::vector<Hypothesis> &rec_hyps,
const std::vector<Hypothesis> >_hyps,
const Eigen::Vector4f &model_centroid,
size_t &tp, size_t &fp, size_t &fn,
std::vector<float> &translation_errors,
std::vector<float> &rotational_errors,
bool is_rotation_invariant , bool is_rotational_symmetric );
std::map<std::string, std::vector<Hypothesis> >
readHypothesesFromFile( const std::string &filename );
/**
* @brief setRotationalInvariantObjects
* @param rot_invariant_objects name of objects which are rotational invariant with respect to xy plane
*/
void
setRotationalInvariantObjects(const std::vector<std::string> &rot_invariant_objects)
{
rotational_invariant_objects_ = rot_invariant_objects;
}
/**
* @brief setRotationalSymmetricObjects
* @param rotational_symmetric_objects name of objects which are rotational symmetric with respect to xy plane
*/
void
setRotationalSymmetricObjects(const std::vector<std::string> &rotational_symmetric_objects)
{
rotational_symmetric_objects_ = rotational_symmetric_objects;
}
void compute_recognition_rate (size_t &total_tp, size_t &total_fp, size_t &total_fn);
float compute_recognition_rate_over_occlusion (); ///< basically checks for each ground-truth object if there exists a corresponding recognized object
void checkIndividualHypotheses(); ///< check for each recognized object if there is a corresponding ground-truth object<w
std::string getModels_dir() const;
void setModels_dir(const std::string &value);
std::string getTest_dir() const;
void setTest_dir(const std::string &value);
std::string getOr_dir() const;
void setOr_dir(const std::string &value);
std::string getGt_dir() const;
void setGt_dir(const std::string &value);
bool getUse_generated_hypotheses() const;
void setUse_generated_hypotheses(bool value = true);
bool getVisualize() const;
void setVisualize(bool value);
std::string getOut_dir() const;
void setOut_dir(const std::string &value);
/**
* @brief visualize results for an input cloud with ground-truth and recognized object models
* @param input_cloud cloud of the input scene
* @param gt_path file path to the ground-truth annotation file
* @param recognition_results_path file path to the results stored in the format of the annotation file
*/
void
visualizeResults(const typename pcl::PointCloud<PointT>::Ptr &input_cloud, const bf::path & gt_path, const bf::path &recognition_results_path);
Eigen::MatrixXi compute_confusion_matrix();
};
}
}
| 40.728814 | 197 | 0.672597 |
f289c44165963f4f6c5abfa39a178fc9c160e43c | 1,099 | h | C | Overshare Kit/OSKActivity_SystemAccounts.h | blackpixel/overshare-kit | 63f6566b3fb265dbed3639be70535e47cff84647 | [
"MIT"
] | 342 | 2015-01-02T22:13:41.000Z | 2022-02-06T10:10:21.000Z | Overshare Kit/OSKActivity_SystemAccounts.h | blackpixel/overshare-kit | 63f6566b3fb265dbed3639be70535e47cff84647 | [
"MIT"
] | 8 | 2015-03-03T09:19:18.000Z | 2021-07-19T21:10:49.000Z | Overshare Kit/OSKActivity_SystemAccounts.h | blackpixel/overshare-kit | 63f6566b3fb265dbed3639be70535e47cff84647 | [
"MIT"
] | 48 | 2015-01-12T11:41:03.000Z | 2021-05-27T07:02:54.000Z | //
// OSKActivity_SystemAccounts.h
// Overshare
//
//
// Copyright (c) 2013 Overshare Kit. All rights reserved.
//
@import Accounts;
typedef void(^OSKSystemAccountAccessRequestCompletionHandler)(BOOL successful, NSError *error);
///-----------------------------------------------
/// @name System Accounts
///-----------------------------------------------
/**
A protocol for `OSKActivity` subclasses that use iOS system accounts for authentication.
*/
@protocol OSKActivity_SystemAccounts <NSObject>
/**
The active system account.
*/
@property (strong, nonatomic) ACAccount *activeSystemAccount;
/**
@return Returns the iOS account type identifier corresponding to the activity.
*/
+ (NSString *)systemAccountTypeIdentifier;
@optional
/**
@return Returns an `NSDictionary` of read access request options, or nil. Used only by `OSKFacebookActivity`.
*/
+ (NSDictionary *)readAccessRequestOptions;
/**
@return Returns an `NSDictionary` of write access request options, or nil. Used only by `OSKFacebookActivity`.
*/
+ (NSDictionary *)writeAccessRequestOptions;
@end
| 20.735849 | 111 | 0.676069 |
9a0630867d68836616d35aba102224e16a6ae1d6 | 1,816 | c | C | src/init.c | gto76/tanks | fc51232983cf635c29c52a5530615aa6de07dc45 | [
"MIT"
] | 5 | 2017-04-24T17:59:05.000Z | 2022-02-14T20:34:12.000Z | src/init.c | gto76/tanks | fc51232983cf635c29c52a5530615aa6de07dc45 | [
"MIT"
] | null | null | null | src/init.c | gto76/tanks | fc51232983cf635c29c52a5530615aa6de07dc45 | [
"MIT"
] | 3 | 2019-02-19T12:24:28.000Z | 2020-12-04T13:46:03.000Z | #include <allegro.h>
#include <stdio.h>
#include "struc.h"
#include "konst.h"
#include "funct.h"
#include "var.h"
void tankca();
void kugle();
void kraterji();
void narisi();
void zvok();
void
init()
{
install_keyboard();
install_timer();
if (set_gfx_mode(GFX_AUTODETECT, SIRINA, VISINA, 0, 0) < 0) {
printf("%s\n", allegro_error);
exit(1);
}
//zvok();
clear(screen);
end_game=0;
tankca();
kugle();
kraterji();
narisi(); //narise ozemlje in tankca
}
void
tankca()
{
tnk1.x=SIRINA/6;
tnk1.dx=SIRINA/6; //leva stran
tnk1.y=B-1;
tnk1.dy=B-1; //eno piko nad tlemi
tnk1.fi=tnk1.dfi=1; //cev
tnk1.fire=tnk1.moc=0;
tnk1.t=-1;
tnk2.x=SIRINA/6*5;//desna stran
tnk2.dx=SIRINA/6*5;
tnk2.y=B-1;
tnk2.dy=B-1;
tnk2.fi=tnk2.dfi=2;
tnk2.fire=tnk1.moc=0;
tnk2.t=-1;
}
void
kugle()
{
int i;
for(i=0;i<=9;i++)
kgl[i].t=-1;
}
void
kraterji()
{
int i;
kratr[0]=SREDINA;
for(i=1;i<=499;i++)
kratr[i]=-1;
}
void
narisi()
{
//ozemlje
line(screen,0,B,SIRINA,B,15);
krater();
//okvir za merilca
rect(screen,10,VISINA-10,110,VISINA-20,15);
rect(screen,SIRINA-10,VISINA-10,SIRINA-110,VISINA-20,15);
//tankca
tank_draw(&tnk1);
tank_draw(&tnk2);
}
void
zvok()
{
if (install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL) != 0) {
allegro_message("Error initialising sound system\n%s\n",
allegro_error);
exit(1);
}
blast = load_sample("./res/blast.wav");
cev = load_sample("./res/cev.wav");
fire = load_sample("./res/fire.wav");
load = load_sample("./res/load.wav");
move = load_sample("./res/move.wav");
themes = load_sample("./res/themes.wav");
hit = load_sample("./res/hit.wav");
battle = load_sample("./res/battle.wav");
}
| 16.070796 | 63 | 0.587555 |
a46b31265205f16f2bcfe434c1fdafc302050b39 | 730 | c | C | Programming/ConsoleApplication31/ConsoleApplication31/test5.c | BedrockDev/Sunrin2016 | 549fb617e957c3453c4c8a38a7017a1baaff6617 | [
"Unlicense"
] | 4 | 2016-05-19T00:42:03.000Z | 2016-09-30T04:26:46.000Z | Programming/ConsoleApplication31/ConsoleApplication31/test5.c | BedrockDev/Sunrin2016 | 549fb617e957c3453c4c8a38a7017a1baaff6617 | [
"Unlicense"
] | null | null | null | Programming/ConsoleApplication31/ConsoleApplication31/test5.c | BedrockDev/Sunrin2016 | 549fb617e957c3453c4c8a38a7017a1baaff6617 | [
"Unlicense"
] | 2 | 2016-10-31T19:16:59.000Z | 2016-12-10T12:05:45.000Z | #include <stdio.h>
struct Score {
int no;
char name[20];
int ko;
int en;
int ma;
int tot;
};
void main() {
FILE *score;
char str[216];
char ch;
struct Score list[10];
int i = 0;
int n;
score = fopen("score.dat", "r");
if (score == NULL) {
printf("Error occured while reading the file\n");
}
while (fscanf(score, "%d %s %d %d %d",
&list[i].no, &list[i].name, &list[i].ko, &list[i].en, &list[i].ma) != EOF) {
list[i].tot = list[i].ko + list[i].en + list[i].ma;
i++;
}
printf("No Name Ko En Ma Tot\n\n");
for (n = 0; n < i; n++) {
fprintf(stdout, "%d %s %d %d %d %d",
list[n].no, list[n].name, list[n].ko, list[n].en, list[n].ma, list[n].tot);
printf("\n");
}
printf("\n\n");
fclose(score);
} | 19.210526 | 78 | 0.546575 |
a49b875f0b3e6c384c7756271b307756bbe25b0d | 602 | c | C | src/signal_handlers.c | duckinator/cadel | a725a85b315174a142e5a8d068ef0d7ccb94c258 | [
"MIT"
] | null | null | null | src/signal_handlers.c | duckinator/cadel | a725a85b315174a142e5a8d068ef0d7ccb94c258 | [
"MIT"
] | null | null | null | src/signal_handlers.c | duckinator/cadel | a725a85b315174a142e5a8d068ef0d7ccb94c258 | [
"MIT"
] | null | null | null | #include "cadel.h"
#include <signal.h>
#include <stdbool.h>
#include <stdlib.h>
static volatile bool _cadel_running = true;
void cadel_stop()
{
_cadel_running = false;
}
bool cadel_running()
{
return _cadel_running;
}
void cadel_interrupt_handler(int signal_number)
{
cadel_stop();
}
bool cadel_register_signal_handlers()
{
struct sigaction new_sigaction;
new_sigaction.sa_handler = cadel_interrupt_handler;
if (atexit(&cadel_stop) != 0) {
return false;
}
if (sigaction(SIGINT, &new_sigaction, NULL) != 0) {
return false;
}
return true;
}
| 16.27027 | 55 | 0.679402 |
f2ca347a150c795e8d2cd5b7ee2d6c4253694dd4 | 728 | h | C | base/stdafx.h | jonathanpotts/Spectral | e9355c44e95fa5cacc311930233ca549a261b8ca | [
"MIT"
] | 10 | 2018-07-04T17:40:22.000Z | 2021-02-02T12:37:35.000Z | base/stdafx.h | jonathanpotts/Spectral | e9355c44e95fa5cacc311930233ca549a261b8ca | [
"MIT"
] | 7 | 2018-08-03T08:04:08.000Z | 2020-05-11T02:34:13.000Z | base/stdafx.h | jonathanpotts/Spectral | e9355c44e95fa5cacc311930233ca549a261b8ca | [
"MIT"
] | 4 | 2018-09-16T00:32:29.000Z | 2021-09-11T16:58:15.000Z | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
// TODO: reference additional headers your program requires here
#include <climits>
#include <iostream>
#include <tchar.h>
#include <assert.h>
#include <wtypes.h>
#include <vector>
#include <map>
#include <cmath>
#include "Spectral.h"
#include "LogitechLEDLib.h"
#include "CUESDK.h"
#include "RzChromaSDKDefines.h"
#include "RzChromaSDKTypes.h"
#include "RzErrors.h"
#include "RzChromaImpl.h" | 25.103448 | 89 | 0.745879 |
44f33561862bf8d40c50e30f08a5586114e65905 | 371 | h | C | PrivateFrameworks/CallKit/CXCallDirectoryManagerMaintenanceHostProtocol-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/CallKit/CXCallDirectoryManagerMaintenanceHostProtocol-Protocol.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/CallKit/CXCallDirectoryManagerMaintenanceHostProtocol-Protocol.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 "NSObject.h"
@protocol CXCallDirectoryManagerMaintenanceHostProtocol <NSObject>
- (oneway void)compactStoreWithReply:(void (^)(NSError *))arg1;
- (oneway void)synchronizeExtensionsWithReply:(void (^)(NSError *))arg1;
@end
| 26.5 | 83 | 0.714286 |
2b21ca9f4965a98daf2808d4d6b4b10329fb67b6 | 3,801 | h | C | framework/common/error.h | TomasRejhons/siren | 9ef3ace7174cbdb48b9e45a2db104f3f5c4b9825 | [
"MIT"
] | null | null | null | framework/common/error.h | TomasRejhons/siren | 9ef3ace7174cbdb48b9e45a2db104f3f5c4b9825 | [
"MIT"
] | null | null | null | framework/common/error.h | TomasRejhons/siren | 9ef3ace7174cbdb48b9e45a2db104f3f5c4b9825 | [
"MIT"
] | 1 | 2021-05-26T12:06:12.000Z | 2021-05-26T12:06:12.000Z | /*
* MIT License
*
* Copyright (c) 2021 silicon-village
*
* 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.
*/
#pragma once
#include <cassert>
#include <stdexcept>
#include <string>
#include "common/strings.h"
#include "logging.h"
#include "vk_common.h"
#if defined(__clang__)
// CLANG ENABLE/DISABLE WARNING DEFINITION
#define VKBP_DISABLE_WARNINGS() \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wtautological-compare\"")
#define VKBP_ENABLE_WARNINGS() \
_Pragma("clang diagnostic pop")
#elif defined(__GNUC__) || defined(__GNUG__)
// GCC ENABLE/DISABLE WARNING DEFINITION
#define VKBP_DISABLE_WARNINGS() \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wtautological-compare\"")
#define VKBP_ENABLE_WARNINGS() \
_Pragma("GCC diagnostic pop")
#elif defined(_MSC_VER)
// MSVC ENABLE/DISABLE WARNING DEFINITION
#define VKBP_DISABLE_WARNINGS() \
__pragma(warning(push, 0))
#define VKBP_ENABLE_WARNINGS() \
__pragma(warning(pop))
#endif
namespace siren {
/**
* @brief Vulkan exception structure
*/
class VulkanException : public std::runtime_error {
public:
/**
* @brief Vulkan exception constructor
*/
VulkanException(VkResult result, const std::string &msg = "Vulkan error");
/**
* @brief Returns the Vulkan error code as string
* @return String message of exception
*/
const char *what() const
noexcept override;
VkResult result;
private:
std::string error_message;
};
} // namespace siren
/// @brief Helper macro to test the result of Vulkan calls which can return an error.
#define VK_CHECK(x) \
do { \
VkResult err = x; \
if (err) { \
LOGE("Detected Vulkan error: {}", siren::to_string(err)); \
abort(); \
} \
} while (0)
#define ASSERT_VK_HANDLE(handle) \
do { \
if ((handle) == VK_NULL_HANDLE) { \
LOGE("Handle is NULL"); \
abort(); \
} \
} while (0)
#if !defined(NDEBUG) || defined(DEBUG) || defined(_DEBUG)
#define VKB_DEBUG
#endif
| 34.243243 | 85 | 0.60563 |
2b45e3a4787eed497e622654229b0a96d11d2f03 | 248 | h | C | common/fileio.h | nohajc/resman | ce52d5a0950db247f25fd0ba1dc1097b3887ea60 | [
"MIT"
] | 43 | 2018-10-16T20:56:14.000Z | 2022-03-28T03:47:41.000Z | common/fileio.h | nohajc/resman | ce52d5a0950db247f25fd0ba1dc1097b3887ea60 | [
"MIT"
] | null | null | null | common/fileio.h | nohajc/resman | ce52d5a0950db247f25fd0ba1dc1097b3887ea60 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/Error.h>
llvm::Expected<std::vector<char>> readFileIntoMemory(const std::string& ifname, const std::vector<llvm::StringRef>& searchPath = {}); | 31 | 133 | 0.741935 |
d1b880662d5e80b90af54411b5106d9ecebbe7d5 | 1,187 | h | C | src/pepper.h | jrl-umi3218/mc_pepper | 137202c430c80a8d6f5219a8605acf9e4476e41e | [
"BSD-2-Clause"
] | null | null | null | src/pepper.h | jrl-umi3218/mc_pepper | 137202c430c80a8d6f5219a8605acf9e4476e41e | [
"BSD-2-Clause"
] | null | null | null | src/pepper.h | jrl-umi3218/mc_pepper | 137202c430c80a8d6f5219a8605acf9e4476e41e | [
"BSD-2-Clause"
] | 1 | 2022-03-28T12:53:31.000Z | 2022-03-28T12:53:31.000Z | #pragma once
#include <mc_robots/api.h>
#include <mc_rbdyn/RobotModuleMacros.h>
#include <mc_rbdyn/Robots.h>
#include <mc_rtc/logging.h>
namespace mc_robots
{
struct MC_ROBOTS_DLLAPI PepperRobotModule : public mc_rbdyn::RobotModule
{
public:
PepperRobotModule(bool fixed, bool hands, bool extraHardware);
protected:
void readUrdf(const std::string & robotName, bool fixed, const std::vector<std::string> & filteredLinks);
std::map<std::string, std::vector<double>> halfSittingPose(const rbd::MultiBody & mb) const;
std::map<std::string, std::pair<std::string, std::string>> stdCollisionsFiles(const rbd::MultiBody & mb) const;
std::map<std::string, std::pair<std::string, std::string>> getConvexHull(
const std::map<std::string, std::pair<std::string, std::string>> & files) const;
// Ensure that mc_pepper::(tasks/constraints) libraries are loaded by mc_rtc when mc_pepper is loaded
void forceLibraryLink(const mc_rbdyn::Robots & robots);
public:
std::vector<std::string> virtualLinks;
std::map<std::string, std::vector<double>> halfSitting;
std::vector<std::string> excludedLinks;
std::vector<std::string> gripperJoints;
};
} // namespace mc_robots
| 33.914286 | 113 | 0.73968 |
94c7d95ed996998689aa32e4f242714d6bdce70b | 3,324 | c | C | ccx_prool/SPOOLES.2.2/SemiImplMtx/src/IO.c | alleindrach/calculix-desktop | 2cb2c434b536eb668ff88bdf82538d22f4f0f711 | [
"MIT"
] | null | null | null | ccx_prool/SPOOLES.2.2/SemiImplMtx/src/IO.c | alleindrach/calculix-desktop | 2cb2c434b536eb668ff88bdf82538d22f4f0f711 | [
"MIT"
] | 4 | 2017-09-21T17:03:55.000Z | 2018-01-25T16:08:31.000Z | ccx_prool/SPOOLES.2.2/SemiImplMtx/src/IO.c | alleindrach/calculix-desktop | 2cb2c434b536eb668ff88bdf82538d22f4f0f711 | [
"MIT"
] | 1 | 2019-08-29T18:41:28.000Z | 2019-08-29T18:41:28.000Z | /* IO.c */
#include "../SemiImplMtx.h"
/*--------------------------------------------------------------------*/
/*
-------------------------------------------
purpose -- to write a SemiImplMtx to a file
in a human readable format
return values ---
1 -- normal return
-1 -- mtx is NULL
-2 -- type is invalid
-3 -- symmetry flag is invalid
-4 -- fp is NULL
created -- 98oct16, cca
-------------------------------------------
*/
int
SemiImplMtx_writeForHumanEye (
SemiImplMtx *mtx,
FILE *fp
) {
/*
---------------
check the input
---------------
*/
if ( mtx == NULL ) {
fprintf(stderr, "\n error in SemiImplMtx_writeForHumanEye()"
"\n mtx is NULL\n") ;
return(-1) ;
}
switch ( mtx->type ) {
case SPOOLES_REAL :
case SPOOLES_COMPLEX :
break ;
default :
fprintf(stderr, "\n error in SemiImplMtx_writeForHumanEye()"
"\n invalid type %d\n", mtx->type) ;
return(-2) ;
break ;
}
switch ( mtx->symmetryflag ) {
case SPOOLES_SYMMETRIC :
case SPOOLES_HERMITIAN :
case SPOOLES_NONSYMMETRIC :
break ;
default :
fprintf(stderr, "\n error in SemiImplMtx_writeForHumanEye()"
"\n invalid symmetry flag %d\n", mtx->symmetryflag) ;
return(-3) ;
break ;
}
if ( fp == NULL ) {
fprintf(stderr, "\n error in SemiImplMtx_writeForHumanEye()"
"\n fp is NULL\n") ;
return(-4) ;
}
fprintf(fp, "\n\n Semi-Implicit Matrix") ;
fprintf(fp,
"\n %d equations, %d in the domain, %d in the schur complement",
mtx->neqns, mtx->ndomeqns, mtx->nschureqns) ;
switch ( mtx->type ) {
case SPOOLES_REAL :
fprintf(fp, "\n real entries") ;
break ;
case SPOOLES_COMPLEX :
fprintf(fp, "\n complex entries") ;
break ;
}
switch ( mtx->symmetryflag ) {
case SPOOLES_SYMMETRIC :
fprintf(fp, ", symmetric matrix") ;
break ;
case SPOOLES_HERMITIAN :
fprintf(fp, ", Hermitian matrix") ;
break ;
case SPOOLES_NONSYMMETRIC :
fprintf(fp, ", nonsymmetric matrix") ;
break ;
}
if ( mtx->domColsIV != NULL ) {
fprintf(fp, "\n\n domain columns") ;
IV_writeForHumanEye(mtx->domColsIV, fp) ;
}
if ( mtx->symmetryflag == SPOOLES_NONSYMMETRIC ) {
if ( mtx->domRowsIV != NULL ) {
fprintf(fp, "\n\n domain rows") ;
IV_writeForHumanEye(mtx->domRowsIV, fp) ;
}
}
if ( mtx->schurColsIV != NULL ) {
fprintf(fp, "\n\n schur complement columns") ;
IV_writeForHumanEye(mtx->schurColsIV, fp) ;
}
if ( mtx->symmetryflag == SPOOLES_NONSYMMETRIC ) {
if ( mtx->schurRowsIV != NULL ) {
fprintf(fp, "\n\n schur complement rows") ;
IV_writeForHumanEye(mtx->schurRowsIV, fp) ;
}
}
if ( mtx->domainMtx != NULL ) {
fprintf(fp, "\n\n domain FrontMtx object") ;
FrontMtx_writeForHumanEye(mtx->domainMtx, fp) ;
}
if ( mtx->schurMtx != NULL ) {
fprintf(fp, "\n\n schur complement FrontMtx object") ;
FrontMtx_writeForHumanEye(mtx->schurMtx, fp) ;
}
if ( mtx->A12 != NULL ) {
fprintf(fp, "\n\n original (1,2) matrix") ;
InpMtx_writeForHumanEye(mtx->A12, fp) ;
}
if ( mtx->symmetryflag == SPOOLES_NONSYMMETRIC ) {
if ( mtx->A21 != NULL ) {
fprintf(fp, "\n\n original (2,1) matrix") ;
InpMtx_writeForHumanEye(mtx->A21, fp) ;
}
}
return(1) ; }
/*--------------------------------------------------------------------*/
| 26.173228 | 72 | 0.566185 |
b111602f8db680f221b1a3353b71c0554ac7a174 | 1,959 | h | C | resources/texture.h | oceancx/DmitrysEngine | 67856be79b6970168e57acd67db913a625a3797a | [
"MIT"
] | null | null | null | resources/texture.h | oceancx/DmitrysEngine | 67856be79b6970168e57acd67db913a625a3797a | [
"MIT"
] | null | null | null | resources/texture.h | oceancx/DmitrysEngine | 67856be79b6970168e57acd67db913a625a3797a | [
"MIT"
] | 1 | 2020-03-10T13:47:12.000Z | 2020-03-10T13:47:12.000Z | /* Copyright (c) 2017-2019 Dmitry Stepanov a.k.a mr.DIMAS
*
* 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. */
/**
* @brief Possible texture types
*/
typedef enum de_texture_type_e {
DE_TEXTURE_TYPE_2D,
DE_TEXTURE_TYPE_VOLUME,
DE_TEXTURE_TYPE_CUBE
} de_texture_type_t;
/**
* @brief Common texture. Can be 2D, volume or cube
*/
struct de_texture_t {
unsigned int id; /**< OpenGL texture id */
int width; /**< Width of texture */
int height; /**< Height of texture */
int depth; /**< Depth of volume texture */
char* pixels; /**< Texture pixels */
int byte_per_pixel; /**< Count of bytes per pixel */
de_texture_type_t type; /**< Type of texture */
bool need_upload; /**< Indicates that texture needs to be uploaded to GPU */
};
de_resource_dispatch_table_t* de_texture_get_dispatch_table(void);
/**
* @brief Allocates pixels for rectangle image.
*/
void de_texture_alloc_pixels(de_texture_t* tex, int w, int h, size_t byte_per_pixel); | 39.18 | 85 | 0.752425 |
b145d9aa8c1957da95fdba6604f900d00aca2da6 | 24,195 | h | C | include/chibi/features.h | spurious/chibi-scheme-mirror | 49168ab073f64a95c834b5f584a9aaea3469594d | [
"BSD-3-Clause"
] | null | null | null | include/chibi/features.h | spurious/chibi-scheme-mirror | 49168ab073f64a95c834b5f584a9aaea3469594d | [
"BSD-3-Clause"
] | null | null | null | include/chibi/features.h | spurious/chibi-scheme-mirror | 49168ab073f64a95c834b5f584a9aaea3469594d | [
"BSD-3-Clause"
] | null | null | null | /* features.h -- general feature configuration */
/* Copyright (c) 2009-2012 Alex Shinn. All rights reserved. */
/* BSD-style license: http://synthcode.com/license.txt */
/* uncomment this to disable most features */
/* Most features are enabled by default, but setting this */
/* option will disable any not explicitly enabled. */
/* #define SEXP_USE_NO_FEATURES 1 */
/* uncomment this to disable interpreter-based threads */
/* #define SEXP_USE_GREEN_THREADS 0 */
/* uncomment this to enable the experimental native x86 backend */
/* #define SEXP_USE_NATIVE_X86 1 */
/* uncomment this to disable the module system */
/* Currently this just loads the meta.scm from main and */
/* sets up an (import (module name)) macro. */
/* #define SEXP_USE_MODULES 0 */
/* uncomment this to disable dynamic loading */
/* If enabled, you can LOAD .so files with a */
/* sexp_init_library(ctx, env) function provided. */
/* #define SEXP_USE_DL 0 */
/* uncomment this to statically compile all C libs */
/* If set, this will statically include the clibs.c file */
/* into the standard environment, so that you can have */
/* access to a predefined set of C libraries without */
/* needing dynamic loading. The clibs.c file is generated */
/* automatically by searching the lib directory for */
/* modules with include-shared, but can be hand-tailored */
/* to your needs. */
/* #define SEXP_USE_STATIC_LIBS 1 */
/* uncomment this to disable detailed source info for debugging */
/* By default Chibi will associate source info with every */
/* bytecode offset. By disabling this only lambda-level source */
/* info will be recorded (the line of the opening paren for the */
/* lambda). */
/* #define SEXP_USE_FULL_SOURCE_INFO 0 */
/* uncomment this to disable a simplifying optimization pass */
/* This performs some simple optimizations such as dead-code */
/* elimination, constant-folding, and directly propagating */
/* non-mutated let values bound to constants or non-mutated */
/* references. More than performance, this is aimed at reducing the */
/* size of the compiled code, especially as the result of macro */
/* expansions, so it's a good idea to leave it enabled. */
/* #define SEXP_USE_SIMPLIFY 0 */
/* uncomment this to disable dynamic type definitions */
/* This enables register-simple-type and related */
/* opcodes for defining types, needed by the default */
/* implementation of (srfi 9). */
/* #define SEXP_USE_TYPE_DEFS 0 */
/* uncomment this to use the Boehm conservative GC */
/* Conservative GCs make it easier to write extensions, */
/* since you don't have to keep track of intermediate */
/* variables, but can leak memory. Boehm is also a */
/* very large library to link in. You may want to */
/* enable this when debugging your own extensions, or */
/* if you suspect a bug in the native GC. */
/* #define SEXP_USE_BOEHM 1 */
/* uncomment this to disable weak references */
/* #define SEXP_USE_WEAK_REFERENCES 0 */
/* uncomment this to just malloc manually instead of any GC */
/* Mostly for debugging purposes, this is the no GC option. */
/* You can use just the read/write API and */
/* explicitly free sexps, though. */
/* #define SEXP_USE_MALLOC 1 */
/* uncomment this to allocate heaps with mmap instead of malloc */
/* #define SEXP_USE_MMAP_GC 1 */
/* uncomment this to add conservative checks to the native GC */
/* Please mail the author if enabling this makes a bug */
/* go away and you're not working on your own C extension. */
/* #define SEXP_USE_CONSERVATIVE_GC 1 */
/* uncomment this to add additional native checks to only mark objects in the heap */
/* #define SEXP_USE_SAFE_GC_MARK 1 */
/* uncomment this to track what C source line each object is allocated from */
/* #define SEXP_USE_TRACK_ALLOC_SOURCE 1 */
/* uncomment this to take a short backtrace of where each object is */
/* allocated from */
/* #define SEXP_USE_TRACK_ALLOC_BACKTRACE 1 */
/* uncomment this to add additional native gc checks to verify a magic header */
/* #define SEXP_USE_HEADER_MAGIC 1 */
/* uncomment this to add very verbose debugging stats to the native GC */
/* #define SEXP_USE_DEBUG_GC 1 */
/* uncomment this to enable "safe" field accessors for primitive types */
/* The sexp union type fields are abstracted away with macros of the */
/* form sexp_<type>_<field>(<obj>), however these are just convenience */
/* macros equivalent to directly accessing the union field, and will */
/* return incorrect results (or segfault) if <obj> isn't of the correct */
/* <type>. Thus you're required to check the types manually before */
/* accessing them. However, to detect errors earlier you can enable */
/* SEXP_USE_SAFE_ACCESSORS, and on invalid accesses chibi will print */
/* a friendly error message and immediately segfault itself so you */
/* can see where the invalid access was made. */
/* Note this is only intended for debugging, and mostly for user code. */
/* If you want to build chibi itself with this option, compilation */
/* may be very slow and using CFLAGS=-O0 is recommended. */
/* #define SEXP_USE_SAFE_ACCESSORS 1 */
/* uncomment to install a default signal handler in main() for segfaults */
/* This will print a helpful backtrace. */
/* #define SEXP_USE_PRINT_BACKTRACE_ON_SEGFAULT 1 */
/* uncomment this to make the heap common to all contexts */
/* By default separate contexts can have separate heaps, */
/* and are thus thread-safe and independant. */
/* #define SEXP_USE_GLOBAL_HEAP 1 */
/* uncomment this to make the symbol table common to all contexts */
/* Will still be restricted to all contexts sharing the same */
/* heap, of course. */
/* #define SEXP_USE_GLOBAL_SYMBOLS 1 */
/* uncomment this to disable foreign function bindings with > 6 args */
/* #define SEXP_USE_EXTENDED_FCALL 0 */
/* uncomment this if you don't need flonum support */
/* This is only for EVAL - you'll still be able to read */
/* and write flonums directly through the sexp API. */
/* #define SEXP_USE_FLONUMS 0 */
/* uncomment this to disable reading/writing IEEE infinities */
/* By default you can read/write +inf.0, -inf.0 and +nan.0 */
/* #define SEXP_USE_INFINITIES 0 */
/* uncomment this if you want immediate flonums */
/* This is experimental, enable at your own risk. */
/* #define SEXP_USE_IMMEDIATE_FLONUMS 1 */
/* uncomment this if you don't want bignum support */
/* Bignums are implemented with a small, custom library */
/* in opt/bignum.c. */
/* #define SEXP_USE_BIGNUMS 0 */
/* uncomment this if you don't want exact ratio support */
/* Ratios are part of the bignum library and imply bignums. */
/* #define SEXP_USE_RATIOS 0 */
/* uncomment this if you don't want imaginary number support */
/* #define SEXP_USE_COMPLEX 0 */
/* uncomment this if you don't want 1## style approximate digits */
/* #define SEXP_USE_PLACEHOLDER_DIGITS 0 */
/* uncomment this if you don't need extended math operations */
/* This includes the trigonometric and expt functions. */
/* Automatically disabled if you've disabled flonums. */
/* #define SEXP_USE_MATH 0 */
/* uncomment this to disable warning about references to undefined variables */
/* This is something of a hack, but can be quite useful. */
/* It's very fast and doesn't involve any separate analysis */
/* passes. */
/* #define SEXP_USE_WARN_UNDEFS 0 */
/* uncomment this to disable huffman-coded immediate symbols */
/* By default (this may change) small symbols are represented */
/* as immediates using a simple huffman encoding. This keeps */
/* the symbol table small, and minimizes hashing when doing a */
/* lot of reading. */
/* #define SEXP_USE_HUFF_SYMS 0 */
/* uncomment this to just use a single list for hash tables */
/* You can trade off some space in exchange for longer read */
/* times by disabling hashing and just putting all */
/* non-immediate symbols in a single list. */
/* #define SEXP_USE_HASH_SYMS 0 */
/* uncomment this to disable extended char names as defined in R7RS */
/* #define SEXP_USE_EXTENDED_CHAR_NAMES 0 */
/* uncomment this to disable UTF-8 string support */
/* The default settings store strings in memory as UTF-8, */
/* and assumes strings passed to/from the C FFI are UTF-8. */
/* #define SEXP_USE_UTF8_STRINGS 0 */
/* uncomment this to disable the string-set! opcode */
/* By default (non-literal) strings are mutable. */
/* Making them immutable allows for packed UTF-8 strings. */
/* #define SEXP_USE_MUTABLE_STRINGS 0 */
/* uncomment this to base string ports on C streams */
/* This historic option enables string and custom ports backed */
/* by FILE* objects using memstreams and funopen/fopencookie. */
/* #define SEXP_USE_STRING_STREAMS 1 */
/* uncomment this to disable automatic closing of ports */
/* If enabled, the underlying FILE* for file ports will be */
/* automatically closed when they're garbage collected. Doesn't */
/* apply to stdin/stdout/stderr. */
/* #define SEXP_USE_AUTOCLOSE_PORTS 0 */
/* uncomment this to use a 2010/01/01 epoch */
/* By default chibi uses the normal 1970 unix epoch in accordance */
/* with R7RS, but this can represent more times as fixnums. */
/* #define SEXP_USE_2010_EPOCH 1 */
/* uncomment this to disable stack overflow checks */
/* By default stacks are fairly small, so it's good to leave */
/* this enabled. */
/* #define SEXP_USE_CHECK_STACK 0 */
/* uncomment this to disable growing the stack on overflow */
/* If enabled, chibi attempts to grow the stack on overflow, */
/* up to SEXP_MAX_STACK_SIZE, otherwise a failed stack check */
/* will just raise an error immediately. */
/* #define SEXP_USE_GROW_STACK 0 */
/* #define SEXP_USE_DEBUG_VM 0 */
/* Experts only. */
/* For *very* verbose output on every VM operation. */
/* uncomment this to make the VM adhere to alignment rules */
/* This is required on some platforms, e.g. ARM */
/* #define SEXP_USE_ALIGNED_BYTECODE */
/************************************************************************/
/* These settings are configurable but only recommended for */
/* experienced users, and only apply when using the native GC. */
/************************************************************************/
/* the initial heap size in bytes */
#ifndef SEXP_INITIAL_HEAP_SIZE
#define SEXP_INITIAL_HEAP_SIZE (2*1024*1024)
#endif
/* the maximum heap size in bytes - if 0 there is no limit */
#ifndef SEXP_MAXIMUM_HEAP_SIZE
#define SEXP_MAXIMUM_HEAP_SIZE 0
#endif
#ifndef SEXP_MINIMUM_HEAP_SIZE
#define SEXP_MINIMUM_HEAP_SIZE 8*1024
#endif
/* if after GC more than this percentage of memory is still in use, */
/* and we've not exceeded the maximum size, grow the heap */
#ifndef SEXP_GROW_HEAP_RATIO
#define SEXP_GROW_HEAP_RATIO 0.75
#endif
/* the default number of opcodes to run each thread for */
#ifndef SEXP_DEFAULT_QUANTUM
#define SEXP_DEFAULT_QUANTUM 500
#endif
#ifndef SEXP_MAX_ANALYZE_DEPTH
#define SEXP_MAX_ANALYZE_DEPTH 8192
#endif
/************************************************************************/
/* DEFAULTS - DO NOT MODIFY ANYTHING BELOW THIS LINE */
/************************************************************************/
#ifndef SEXP_64_BIT
#if defined(__amd64) || defined(__x86_64) || defined(_WIN64) || defined(_Wp64) || defined(__LP64__) || defined(__PPC64__)
#define SEXP_64_BIT 1
#else
#define SEXP_64_BIT 0
#endif
#endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
#define SEXP_BSD 1
#else
#define SEXP_BSD 0
#if ! defined(_GNU_SOURCE) && ! defined(_WIN32) && ! defined(PLAN9)
#define _GNU_SOURCE
#endif
#endif
#ifndef SEXP_USE_NO_FEATURES
#define SEXP_USE_NO_FEATURES 0
#endif
#ifndef SEXP_USE_PEDANTIC
#define SEXP_USE_PEDANTIC 0
#endif
#ifndef SEXP_USE_GREEN_THREADS
#define SEXP_USE_GREEN_THREADS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_DEBUG_THREADS
#define SEXP_USE_DEBUG_THREADS 0
#endif
#ifndef SEXP_USE_AUTO_FORCE
#define SEXP_USE_AUTO_FORCE 0
#endif
#ifndef SEXP_USE_NATIVE_X86
#define SEXP_USE_NATIVE_X86 0
#endif
#ifndef SEXP_USE_MODULES
#define SEXP_USE_MODULES ! SEXP_USE_NO_FEATURES
#endif
#ifndef sexp_default_user_module_path
#define sexp_default_user_module_path "./lib:."
#endif
#ifndef SEXP_USE_TYPE_DEFS
#define SEXP_USE_TYPE_DEFS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_MAXIMUM_TYPES
#define SEXP_MAXIMUM_TYPES ((sexp_tag_t)-1)
#endif
#ifndef SEXP_USE_DL
#if defined(PLAN9) || defined(_WIN32)
#define SEXP_USE_DL 0
#else
#define SEXP_USE_DL ! SEXP_USE_NO_FEATURES
#endif
#endif
#ifndef SEXP_USE_STATIC_LIBS
#define SEXP_USE_STATIC_LIBS 0
#endif
/* don't include clibs.c - include separately or link */
#ifndef SEXP_USE_STATIC_LIBS_NO_INCLUDE
#define SEXP_USE_STATIC_LIBS_NO_INCLUDE defined(PLAN9)
#endif
#ifndef SEXP_USE_FULL_SOURCE_INFO
#define SEXP_USE_FULL_SOURCE_INFO ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_SIMPLIFY
#define SEXP_USE_SIMPLIFY ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_BOEHM
#define SEXP_USE_BOEHM 0
#endif
#ifndef SEXP_USE_WEAK_REFERENCES
#define SEXP_USE_WEAK_REFERENCES ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_MALLOC
#define SEXP_USE_MALLOC 0
#endif
#ifndef SEXP_USE_LIMITED_MALLOC
#define SEXP_USE_LIMITED_MALLOC 0
#endif
#ifndef SEXP_USE_MMAP_GC
#define SEXP_USE_MMAP_GC 0
#endif
#ifndef SEXP_USE_DEBUG_GC
#define SEXP_USE_DEBUG_GC 0
#endif
#ifndef SEXP_USE_SAFE_GC_MARK
#define SEXP_USE_SAFE_GC_MARK SEXP_USE_DEBUG_GC > 1
#endif
#ifndef SEXP_USE_CONSERVATIVE_GC
#define SEXP_USE_CONSERVATIVE_GC 0
#endif
#ifndef SEXP_USE_TRACK_ALLOC_SOURCE
#define SEXP_USE_TRACK_ALLOC_SOURCE SEXP_USE_DEBUG_GC > 2
#endif
#ifndef SEXP_USE_TRACK_ALLOC_BACKTRACE
#define SEXP_USE_TRACK_ALLOC_BACKTRACE SEXP_USE_TRACK_ALLOC_SOURCE
#endif
#ifndef SEXP_BACKTRACE_SIZE
#define SEXP_BACKTRACE_SIZE 3
#endif
#ifndef SEXP_USE_HEADER_MAGIC
#define SEXP_USE_HEADER_MAGIC 0
#endif
#ifndef SEXP_GC_PAD
#define SEXP_GC_PAD 0
#endif
#ifndef SEXP_USE_SAFE_ACCESSORS
#define SEXP_USE_SAFE_ACCESSORS 0
#endif
#ifndef SEXP_USE_SAFE_VECTOR_ACCESSORS
#define SEXP_USE_SAFE_VECTOR_ACCESSORS 0
#endif
#ifndef SEXP_USE_GLOBAL_HEAP
#if SEXP_USE_BOEHM || SEXP_USE_MALLOC
#define SEXP_USE_GLOBAL_HEAP 1
#else
#define SEXP_USE_GLOBAL_HEAP 0
#endif
#endif
#ifndef SEXP_USE_GLOBAL_SYMBOLS
#if SEXP_USE_BOEHM || SEXP_USE_MALLOC
#define SEXP_USE_GLOBAL_SYMBOLS 1
#else
#define SEXP_USE_GLOBAL_SYMBOLS 0
#endif
#endif
#ifndef SEXP_USE_STRICT_TOPLEVEL_BINDINGS
#define SEXP_USE_STRICT_TOPLEVEL_BINDINGS 0
#endif
#if SEXP_USE_STRICT_TOPLEVEL_BINDINGS
#define SEXP_USE_RENAME_BINDINGS 1
#else
#ifndef SEXP_USE_RENAME_BINDINGS
#define SEXP_USE_RENAME_BINDINGS 1
#endif
#endif
#ifndef SEXP_USE_SPLICING_LET_SYNTAX
#define SEXP_USE_SPLICING_LET_SYNTAX 0
#endif
#ifndef SEXP_USE_FLAT_SYNTACTIC_CLOSURES
#define SEXP_USE_FLAT_SYNTACTIC_CLOSURES 0
#endif
#ifndef SEXP_USE_UNWRAPPED_TOPLEVEL_BINDINGS
#define SEXP_USE_UNWRAPPED_TOPLEVEL_BINDINGS 0
#endif
#ifndef SEXP_USE_EXTENDED_FCALL
#define SEXP_USE_EXTENDED_FCALL (!SEXP_USE_NO_FEATURES)
#endif
#ifndef SEXP_USE_FLONUMS
#define SEXP_USE_FLONUMS (!SEXP_USE_NO_FEATURES)
#endif
#ifndef SEXP_USE_BIGNUMS
#define SEXP_USE_BIGNUMS (!SEXP_USE_NO_FEATURES)
#endif
#ifndef SEXP_USE_RATIOS
#define SEXP_USE_RATIOS SEXP_USE_FLONUMS
#endif
#ifndef SEXP_USE_COMPLEX
#define SEXP_USE_COMPLEX SEXP_USE_FLONUMS
#endif
#if (SEXP_USE_RATIOS || SEXP_USE_COMPLEX)
#undef SEXP_USE_BIGNUMS
#define SEXP_USE_BIGNUMS 1
#undef SEXP_USE_FLONUMS
#define SEXP_USE_FLONUMS 1
#endif
#ifndef SEXP_USE_INFINITIES
#if defined(PLAN9) || ! SEXP_USE_FLONUMS
#define SEXP_USE_INFINITIES 0
#else
#define SEXP_USE_INFINITIES ! SEXP_USE_NO_FEATURES
#endif
#endif
#ifndef SEXP_USE_IMMEDIATE_FLONUMS
#define SEXP_USE_IMMEDIATE_FLONUMS 0
#endif
#ifndef SEXP_USE_IEEE_EQV
#define SEXP_USE_IEEE_EQV SEXP_USE_FLONUMS
#endif
#ifndef SEXP_USE_PLACEHOLDER_DIGITS
#define SEXP_USE_PLACEHOLDER_DIGITS 0
#endif
#ifndef SEXP_PLACEHOLDER_DIGIT
#define SEXP_PLACEHOLDER_DIGIT '#'
#endif
#ifndef SEXP_USE_MATH
#define SEXP_USE_MATH SEXP_USE_FLONUMS && ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_ESCAPE_NEWLINE
#define SEXP_USE_ESCAPE_NEWLINE ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_ESCAPE_REQUIRES_TRAILING_SEMI_COLON
#define SEXP_USE_ESCAPE_REQUIRES_TRAILING_SEMI_COLON SEXP_USE_PEDANTIC
#endif
#ifndef SEXP_USE_OBJECT_BRACE_LITERALS
#define SEXP_USE_OBJECT_BRACE_LITERALS (SEXP_USE_TYPE_DEFS && !SEXP_USE_NO_FEATURES)
#endif
/* Dangerous without shared object detection. */
#ifndef SEXP_USE_TYPE_PRINTERS
#define SEXP_USE_TYPE_PRINTERS 0
#endif
#ifndef SEXP_USE_BYTEVECTOR_LITERALS
#define SEXP_USE_BYTEVECTOR_LITERALS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_SELF_PARAMETER
#define SEXP_USE_SELF_PARAMETER 1
#endif
#ifndef SEXP_USE_WARN_UNDEFS
#define SEXP_USE_WARN_UNDEFS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_HUFF_SYMS
#define SEXP_USE_HUFF_SYMS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_HASH_SYMS
#define SEXP_USE_HASH_SYMS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_FOLD_CASE_SYMS
#define SEXP_USE_FOLD_CASE_SYMS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_DEFAULT_FOLD_CASE_SYMS
#define SEXP_DEFAULT_FOLD_CASE_SYMS 0
#endif
/* experimental optimization to use jumps instead of the TAIL-CALL opcode */
#ifndef SEXP_USE_TAIL_JUMPS
/* #define SEXP_USE_TAIL_JUMPS ! SEXP_USE_NO_FEATURES */
#define SEXP_USE_TAIL_JUMPS 0
#endif
#ifndef SEXP_USE_RESERVE_OPCODE
#define SEXP_USE_RESERVE_OPCODE SEXP_USE_TAIL_JUMPS
#endif
/* experimental optimization to avoid boxing locals which aren't set! */
#ifndef SEXP_USE_UNBOXED_LOCALS
/* #define SEXP_USE_UNBOXED_LOCALS ! SEXP_USE_NO_FEATURES */
#define SEXP_USE_UNBOXED_LOCALS 0
#endif
#ifndef SEXP_USE_DEBUG_VM
#define SEXP_USE_DEBUG_VM 0
#endif
#ifndef SEXP_USE_PROFILE_VM
#define SEXP_USE_PROFILE_VM 0
#endif
#ifndef SEXP_USE_EXTENDED_CHAR_NAMES
#define SEXP_USE_EXTENDED_CHAR_NAMES ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_UTF8_STRINGS
#define SEXP_USE_UTF8_STRINGS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_MUTABLE_STRINGS
#define SEXP_USE_MUTABLE_STRINGS 1
#endif
#if (SEXP_USE_UTF8_STRINGS && SEXP_USE_MUTABLE_STRINGS)
#define SEXP_USE_PACKED_STRINGS 0
#endif
#ifndef SEXP_USE_PACKED_STRINGS
#define SEXP_USE_PACKED_STRINGS 1
#endif
#ifndef SEXP_USE_STRING_STREAMS
#define SEXP_USE_STRING_STREAMS 0
#endif
#ifndef SEXP_USE_AUTOCLOSE_PORTS
#define SEXP_USE_AUTOCLOSE_PORTS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_GC_FILE_DESCRIPTORS
#define SEXP_USE_GC_FILE_DESCRIPTORS (SEXP_USE_AUTOCLOSE_PORTS &&!SEXP_USE_BOEHM && !defined(PLAN9))
#endif
#ifndef SEXP_USE_BIDIRECTIONAL_PORTS
#define SEXP_USE_BIDIRECTIONAL_PORTS 0
#endif
#ifndef SEXP_PORT_BUFFER_SIZE
#define SEXP_PORT_BUFFER_SIZE 4096
#endif
#ifndef SEXP_USE_NTP_GETTIME
#define SEXP_USE_NTP_GETTIME 0
#endif
#ifndef SEXP_USE_2010_EPOCH
#define SEXP_USE_2010_EPOCH 0
#endif
#ifndef SEXP_EPOCH_OFFSET
#if SEXP_USE_2010_EPOCH
#define SEXP_EPOCH_OFFSET 1262271600
#else
#define SEXP_EPOCH_OFFSET 0
#endif
#endif
#ifndef SEXP_USE_CHECK_STACK
#define SEXP_USE_CHECK_STACK ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_GROW_STACK
#define SEXP_USE_GROW_STACK SEXP_USE_CHECK_STACK && ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_LONG_PROCEDURE_ARGS
#define SEXP_USE_LONG_PROCEDURE_ARGS ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_INIT_BCODE_SIZE
#define SEXP_INIT_BCODE_SIZE 128
#endif
#ifndef SEXP_INIT_STACK_SIZE
#if SEXP_USE_CHECK_STACK
#define SEXP_INIT_STACK_SIZE 1024
#else
#define SEXP_INIT_STACK_SIZE 8192
#endif
#endif
#ifndef SEXP_MAX_STACK_SIZE
#define SEXP_MAX_STACK_SIZE SEXP_INIT_STACK_SIZE*1000
#endif
#ifndef SEXP_DEFAULT_EQUAL_DEPTH
#define SEXP_DEFAULT_EQUAL_DEPTH 10000
#endif
#ifndef SEXP_DEFAULT_EQUAL_BOUND
#define SEXP_DEFAULT_EQUAL_BOUND 100000000
#endif
#ifndef SEXP_USE_IMAGE_LOADING
#define SEXP_USE_IMAGE_LOADING SEXP_USE_DL && !SEXP_USE_GLOBAL_HEAP && !SEXP_USE_BOEHM && !SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_UNSAFE_PUSH
#define SEXP_USE_UNSAFE_PUSH 0
#endif
#ifndef SEXP_USE_MAIN_HELP
#define SEXP_USE_MAIN_HELP ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_MAIN_ERROR_ADVISE
#define SEXP_USE_MAIN_ERROR_ADVISE ! SEXP_USE_NO_FEATURES
#endif
#ifndef SEXP_USE_SEND_FILE
#define SEXP_USE_SEND_FILE 0
/* #define SEXP_USE_SEND_FILE (__linux || SEXP_BSD) */
#endif
#if SEXP_USE_NATIVE_X86
#undef SEXP_USE_BOEHM
#define SEXP_USE_BOEHM 1
#undef SEXP_USE_FLONUMS
#define SEXP_USE_FLONUMS 0
#undef SEXP_USE_BIGNUMS
#define SEXP_USE_BIGNUMS 0
#undef SEXP_USE_RATIOS
#define SEXP_USE_RATIOS 0
#undef SEXP_USE_COMPLEX
#define SEXP_USE_COMPLEX 0
#undef SEXP_USE_UTF8_STRINGS
#define SEXP_USE_UTF8_STRINGS 0
#undef SEXP_USE_SIMPLIFY
#define SEXP_USE_SIMPLIFY 0
#endif
#ifndef SEXP_USE_ALIGNED_BYTECODE
#if defined(__arm__)
#define SEXP_USE_ALIGNED_BYTECODE 1
#else
#define SEXP_USE_ALIGNED_BYTECODE 0
#endif
#endif
#ifdef PLAN9
#define strcasecmp cistrcmp
#define strncasecmp cistrncmp
#define strcasestr cistrstr
#define round(x) floor((x)+0.5)
#define trunc(x) floor((x)+0.5*(((x)<0)?1:0))
#define isinf(x) (isInf(x,1) || isInf(x,-1))
#define isnan(x) isNaN(x)
#elif defined(_WIN32)
#define snprintf(buf, len, fmt, val) sprintf(buf, fmt, val)
#define strcasecmp lstrcmpi
#define strncasecmp(s1, s2, n) lstrcmpi(s1, s2)
#define round(x) floor((x)+0.5)
#define trunc(x) floor((x)+0.5*(((x)<0)?1:0))
#define isnan(x) (x!=x)
#define isinf(x) (x > DBL_MAX || x < -DBL_MAX)
#endif
#ifdef _WIN32
#define sexp_pos_infinity (DBL_MAX*DBL_MAX)
#define sexp_neg_infinity -sexp_pos_infinity
#define sexp_nan log(-2)
#elif PLAN9
#define sexp_pos_infinity Inf(1)
#define sexp_neg_infinity Inf(-1)
#define sexp_nan NaN()
#else
#define sexp_pos_infinity (1.0/0.0)
#define sexp_neg_infinity -sexp_pos_infinity
#define sexp_nan (0.0/0.0)
#endif
#ifdef __MINGW32__
#ifdef BUILDING_DLL
#define SEXP_API __declspec(dllexport)
#else
#define SEXP_API __declspec(dllimport)
#endif
#else
#define SEXP_API extern
#endif
/************************************************************************/
/* Feature signature. Used for image files and dynamically loaded */
/* libraries to verify they are compatible with the compiled options . */
/************************************************************************/
typedef char sexp_abi_identifier_t[8];
#if SEXP_USE_BOEHM
#define SEXP_ABI_GC "b"
#elif (SEXP_USE_HEADER_MAGIC && SEXP_USE_TRACK_ALLOC_SOURCE)
#define SEXP_ABI_GC "d"
#elif SEXP_USE_HEADER_MAGIC
#define SEXP_ABI_GC "m"
#elif SEXP_USE_TRACK_ALLOC_SOURCE
#define SEXP_ABI_GC "s"
#else
#define SEXP_ABI_GC "c"
#endif
#if SEXP_USE_NATIVE_X86
#define SEXP_ABI_BACKEND "x"
#else
#define SEXP_ABI_BACKEND "v"
#endif
#if (SEXP_USE_RESERVE_OPCODE && SEXP_USE_AUTO_FORCE)
#define SEXP_ABI_INSTRUCTIONS "*"
#elif SEXP_USE_RESERVE_OPCODE
#define SEXP_ABI_INSTRUCTIONS "r"
#elif SEXP_USE_AUTO_FORCE
#define SEXP_ABI_INSTRUCTIONS "f"
#else
#define SEXP_ABI_INSTRUCTIONS "-"
#endif
#if SEXP_USE_GREEN_THREADS
#define SEXP_ABI_THREADS "g"
#else
#define SEXP_ABI_THREADS "-"
#endif
#if SEXP_USE_MODULES
#define SEXP_ABI_MODULES "m"
#else
#define SEXP_ABI_MODULES "-"
#endif
#if (SEXP_USE_COMPLEX && SEXP_USE_RATIOS)
#define SEXP_ABI_NUMBERS "*"
#elif SEXP_USE_COMPLEX
#define SEXP_ABI_NUMBERS "c"
#elif SEXP_USE_RATIOS
#define SEXP_ABI_NUMBERS "r"
#elif SEXP_USE_BIGNUMS
#define SEXP_ABI_NUMBERS "b"
#elif SEXP_USE_INFINITIES
#define SEXP_ABI_NUMBERS "i"
#elif SEXP_USE_FLONUMS
#define SEXP_ABI_NUMBERS "f"
#else
#define SEXP_ABI_NUMBERS "-"
#endif
#if SEXP_USE_UTF8_STRINGS
#define SEXP_ABI_STRINGS "u"
#elif SEXP_USE_PACKED_STRINGS
#define SEXP_ABI_STRINGS "p"
#else
#define SEXP_ABI_STRINGS "-"
#endif
#if SEXP_USE_HUFF_SYMS
#define SEXP_ABI_SYMS "h"
#else
#define SEXP_ABI_SYMS "-"
#endif
#define SEXP_ABI_IDENTIFIER \
(SEXP_ABI_GC SEXP_ABI_BACKEND SEXP_ABI_INSTRUCTIONS SEXP_ABI_THREADS \
SEXP_ABI_MODULES SEXP_ABI_NUMBERS SEXP_ABI_STRINGS SEXP_ABI_SYMS)
#define sexp_version_compatible(ctx, subver, genver) (strcmp((subver), (genver)) == 0)
#define sexp_abi_compatible(ctx, subabi, genabi) (strncmp((subabi), (genabi), sizeof(sexp_abi_identifier_t)) == 0)
| 28.976048 | 121 | 0.762885 |
2cfbb314d49d32eade82a5c82da8f9c7950335ac | 866 | h | C | System/Library/PrivateFrameworks/TSUtility.framework/TSUAggregateEnumerator.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/TSUtility.framework/TSUAggregateEnumerator.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/TSUtility.framework/TSUAggregateEnumerator.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:17:07 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/TSUtility.framework/TSUtility
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <CoreFoundation/NSEnumerator.h>
@class NSMutableArray;
@interface TSUAggregateEnumerator : NSEnumerator {
NSMutableArray* _objects;
}
+(id)aggregateEnumeratorWithObjects:(id)arg1 ;
-(id)init;
-(void)dealloc;
-(void)addObject:(id)arg1 ;
-(id)nextObject;
-(id)initWithObjects:(id)arg1 ;
-(id)initWithFirstObject:(id)arg1 argumentList:(char*)arg2 ;
@end
| 32.074074 | 130 | 0.642032 |
2c8697a2d84e44262a857db8990fb48839f42a77 | 2,654 | h | C | opal-3.16.2/plugins/video/common/platform.h | wwl33695/myopal | d302113c8ad8156b3392ce514cde491cf42d51af | [
"MIT"
] | null | null | null | opal-3.16.2/plugins/video/common/platform.h | wwl33695/myopal | d302113c8ad8156b3392ce514cde491cf42d51af | [
"MIT"
] | null | null | null | opal-3.16.2/plugins/video/common/platform.h | wwl33695/myopal | d302113c8ad8156b3392ce514cde491cf42d51af | [
"MIT"
] | null | null | null | /*
* Common platform code for OPAL
*
* The original files, and this version of the original code, are released under the same
* MPL 1.0 license. Substantial portions of the original code were contributed
* by Salyens and March Networks and their right to be identified as copyright holders
* of the original code portions and any parts now included in this new copy is asserted through
* their inclusion in the copyright notices below.
*
* Copyright (C) 2011 Vox Lucida Pty. Ltd.
* Copyright (C) 2006 Post Increment
* Copyright (C) 2005 Salyens
* Copyright (C) 2001 March Networks Corporation
* Copyright (C) 1999-2000 Equivalence Pty. Ltd.
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Open H323 Library.
*
* The Initial Developer of the Original Code is Equivalence Pty. Ltd.
*
* Contributor(s): Guilhem Tardy (gtardy@salyens.com)
* Craig Southeren (craigs@postincrement.com)
* Matthias Schneider (ma30002000@yahoo.de)
* Robert Jongbloed (robertj@voxlucida.com.au)
*/
#ifndef __PLATFORM_H__
#define __PLATFORM_H__ 1
#define __STDC_CONSTANT_MACROS 1
#if defined (_MSC_VER)
#define _CRT_NONSTDC_NO_DEPRECATE 1
#define _CRT_SECURE_NO_WARNINGS 1
#include "stdint.h"
#include <windows.h>
#undef min
#undef max
#undef IS_ERROR
#include <malloc.h>
#include <stdio.h>
#if _MSC_VER < 1800
#define round(d) ((int)((double)(d)+0.5))
#endif
#define strdup(s) _strdup(s)
#define STRCMPI _strcmpi
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#pragma warning(disable:4101 4244 4996)
#pragma pack(16)
#pragma include_alias(<inttypes.h>, <stdint.h>)
#elif defined(_WIN32)
#include <windows.h>
#include "stdint.h"
#else
#include "plugin_config.h"
#include <stdio.h>
#if defined HAVE_STDINT_H
#include <stdint.h>
#elif defined HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#include <semaphore.h>
#include <dlfcn.h>
#define STRCMPI strcasecmp
typedef uint8_t BYTE;
#endif
#ifdef _WIN32
# define DIR_SEPARATOR "\\"
# define DIR_TOKENISER ";"
#else
# define DIR_SEPARATOR "/"
# define DIR_TOKENISER ":"
#endif
#endif // __PLATFORM_H__
| 27.081633 | 97 | 0.714017 |
82ce9e3e5a726cd1b00109bcb9f71c76090fb54c | 5,613 | c | C | sites/workstation/gcc/p4est/test/test_face_transform3.c | jmark/p4wrap | 6d237ab8fbe03c8ca985778ac1f65678ecbcccb3 | [
"MIT"
] | 2 | 2018-06-02T12:26:35.000Z | 2018-06-27T14:29:52.000Z | sites/workstation/gcc/p4est/test/test_face_transform3.c | jmark/p4wrap | 6d237ab8fbe03c8ca985778ac1f65678ecbcccb3 | [
"MIT"
] | null | null | null | sites/workstation/gcc/p4est/test/test_face_transform3.c | jmark/p4wrap | 6d237ab8fbe03c8ca985778ac1f65678ecbcccb3 | [
"MIT"
] | null | null | null | /*
This file is part of p4est.
p4est is a C library to manage a collection (a forest) of multiple
connected adaptive quadtrees or octrees in parallel.
Copyright (C) 2010 The University of Texas System
Additional copyright (C) 2011 individual authors
Written by Carsten Burstedde, Lucas C. Wilcox, and Tobin Isaac
p4est 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.
p4est 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 p4est; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* Purpose of this program is to verify the face transformation codes
* that are computed in a fast but cryptic way in p8est_find_face_transform.
*/
#include <p8est.h>
#include <p4est_to_p8est.h>
int
main (int argc, char **argv)
{
int my_face, target_face, orientation;
int face_ref, face_perm;
int low[2], high[2], swap;
int i, reverse;
int ft[9], gt[9];
int *my_axis = &ft[0];
int *target_axis = &ft[3];
int *edge_reverse = &ft[6];
sc_init (sc_MPI_COMM_NULL, 1, 1, NULL, SC_LP_DEFAULT);
p4est_init (NULL, SC_LP_DEFAULT);
for (my_face = 0; my_face < 2 * P4EST_DIM; ++my_face) {
for (target_face = 0; target_face < 2 * P4EST_DIM; ++target_face) {
for (orientation = 0; orientation < 4; ++orientation) {
/* find if my edges 0 and 2 are parallel to the x, y, or z-axis */
my_axis[0] = p8est_face_edges[my_face][0] / 4;
my_axis[1] = p8est_face_edges[my_face][2] / 4;
target_axis[0] = target_axis[1] = -1;
edge_reverse[0] = edge_reverse[1] = 0;
/* find matching target vertices */
face_ref = p8est_face_permutation_refs[my_face][target_face];
face_perm = p8est_face_permutation_sets[face_ref][orientation];
low[0] = low[1] =
p8est_face_corners[target_face][p8est_face_permutations[face_perm]
[0]];
high[0] =
p8est_face_corners[target_face][p8est_face_permutations[face_perm]
[1]];
high[1] =
p8est_face_corners[target_face][p8est_face_permutations[face_perm]
[2]];
if (low[0] > high[0]) {
swap = low[0];
low[0] = high[0];
high[0] = swap;
edge_reverse[0] = 1;
}
if (low[1] > high[1]) {
swap = low[1];
low[1] = high[1];
high[1] = swap;
edge_reverse[1] = 1;
}
/* find matching target edges */
for (i = 0; i < 12; ++i) {
if (low[0] == p8est_edge_corners[i][0] &&
high[0] == p8est_edge_corners[i][1]) {
P4EST_ASSERT (target_axis[0] == -1);
target_axis[0] = i / 4;
#ifndef P4EST_ENABLE_DEBUG
if (target_axis[1] >= 0)
break;
#endif
}
else if (low[1] == p8est_edge_corners[i][0] &&
high[1] == p8est_edge_corners[i][1]) {
P4EST_ASSERT (target_axis[1] == -1);
target_axis[1] = i / 4;
#ifndef P4EST_ENABLE_DEBUG
if (target_axis[0] >= 0)
break;
#endif
}
}
/* find what axis is normal to the faces */
my_axis[2] = my_face / 2;
target_axis[2] = target_face / 2;
edge_reverse[2] = 2 * (my_face % 2) + target_face % 2;
#ifdef P4EST_ENABLE_DEBUG
for (i = 0; i < 3; ++i) {
P4EST_ASSERT (0 <= my_axis[i] && my_axis[i] < 3);
P4EST_ASSERT (0 <= target_axis[i] && target_axis[i] < 3);
}
P4EST_ASSERT (my_axis[0] != my_axis[1] &&
my_axis[0] != my_axis[2] && my_axis[1] != my_axis[2]);
P4EST_ASSERT (target_axis[0] != target_axis[1] &&
target_axis[0] != target_axis[2] &&
target_axis[1] != target_axis[2]);
#endif
/* output the results */
P4EST_LDEBUGF
("Results for %d %d %d are %d %d %d %d %d %d %d %d %d\n",
my_face, target_face, orientation, ft[0], ft[1], ft[2],
ft[3], ft[4], ft[5], ft[6], ft[7], ft[8]);
/* compute the transformation code in a faster way and compare */
gt[0] = my_face < 2 ? 1 : 0;
gt[1] = my_face < 4 ? 2 : 1;
gt[2] = my_face / 2;
reverse =
p8est_face_permutation_refs[0][my_face] ^
p8est_face_permutation_refs[0][target_face] ^
(orientation == 0 || orientation == 3);
gt[3 + reverse] = target_face < 2 ? 1 : 0;
gt[3 + !reverse] = target_face < 4 ? 2 : 1;
gt[5] = target_face / 2;
reverse = p8est_face_permutation_refs[my_face][target_face] == 1;
gt[6 + reverse] = orientation % 2;
gt[6 + !reverse] = orientation / 2;
gt[8] = 2 * (my_face % 2) + target_face % 2;
/* ensure that both computations yield the same result */
SC_CHECK_ABORT (!memcmp (ft, gt, 9 * sizeof (int)), "Mismatch");
}
}
}
sc_finalize ();
return 0;
}
| 36.448052 | 76 | 0.55799 |
5ced0b67e759506e228b76fcd40ef666d668d5c8 | 624 | h | C | Nextion.h | bert386/esp32-pellet-hmi | 17e389632defb51dbc42cb2eef968fdc74a39477 | [
"Apache-2.0"
] | 1 | 2021-03-03T05:35:43.000Z | 2021-03-03T05:35:43.000Z | Nextion.h | bert386/esp32-pellet-hmi | 17e389632defb51dbc42cb2eef968fdc74a39477 | [
"Apache-2.0"
] | null | null | null | Nextion.h | bert386/esp32-pellet-hmi | 17e389632defb51dbc42cb2eef968fdc74a39477 | [
"Apache-2.0"
] | null | null | null |
#ifndef __NEXTION_H__
#define __NEXTION_H__
#include "Arduino.h"
#include "NexConfig.h"
#include "NexTouch.h"
#include "NexHardware.h"
#include "NexButton.h"
#include "NexCrop.h"
#include "NexGauge.h"
#include "NexHotspot.h"
#include "NexPage.h"
#include "NexPicture.h"
#include "NexProgressBar.h"
#include "NexSlider.h"
#include "NexText.h"
#include "NexWaveform.h"
#include "NexTimer.h"
#include "NexNumber.h"
#include "NexDualStateButton.h"
#include "NexVariable.h"
#include "NexCheckbox.h"
#include "NexRadio.h"
#include "NexScrolltext.h"
#include "NexGpio.h"
#include "NexRtc.h"
#endif /* #ifndef __NEXTION_H__ */
| 19.5 | 34 | 0.74359 |
ca6b1c07632928dacf4939a84b94ba745c7c1547 | 1,437 | c | C | sources/main.c | nicolasvienot/wolf-3d | 309311db408d32b2fd5cd6dd7aaf36d3ce762f9e | [
"MIT"
] | 5 | 2019-04-28T00:10:55.000Z | 2019-10-08T19:36:15.000Z | sources/main.c | nicolasvienot/wolf3d | 309311db408d32b2fd5cd6dd7aaf36d3ce762f9e | [
"MIT"
] | null | null | null | sources/main.c | nicolasvienot/wolf3d | 309311db408d32b2fd5cd6dd7aaf36d3ce762f9e | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nvienot <nvienot@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/17 16:04:11 by nvienot #+# #+# */
/* Updated: 2019/05/22 18:12:11 by nvienot ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
int main(int argc, char **argv)
{
t_win win;
win.secu = 0;
if (argc != 2)
clear_n_exit(&win, 1);
if (!(win.map = get_map(argv[1], &win)))
clear_n_exit(&win, 2);
win.secu = 1;
if (!(check_map(&win)))
clear_n_exit(&win, 3);
put_map(win.map);
if (init(&win) == 1)
clear_n_exit(&win, 4);
if (Mix_PlayMusic(win.theme, -1) == -1)
clear_n_exit(&win, 5);
loop_intro(&win);
if (SDL_SetRelativeMouseMode(SDL_TRUE) < 0)
clear_n_exit(&win, 7);
loop_play(win);
clear_n_exit(&win, 0);
return (EXIT_SUCCESS);
}
| 36.846154 | 80 | 0.30341 |
43a89052f6ebc4478573e55d13b1965c0445c257 | 5,108 | c | C | vendors/nxp/LPC54608/drivers/fsl_utick.c | nateglims/amazon-freertos | 5cc32eb29d935f124101a3584c6d29aa1f5d687d | [
"MIT"
] | 10 | 2019-09-10T11:20:19.000Z | 2021-08-10T02:14:57.000Z | vendors/nxp/LPC54608/drivers/fsl_utick.c | nateglims/amazon-freertos | 5cc32eb29d935f124101a3584c6d29aa1f5d687d | [
"MIT"
] | 19 | 2018-12-07T03:41:15.000Z | 2020-02-05T14:42:04.000Z | vendors/nxp/LPC54608/drivers/fsl_utick.c | nateglims/amazon-freertos | 5cc32eb29d935f124101a3584c6d29aa1f5d687d | [
"MIT"
] | 13 | 2019-12-31T21:22:09.000Z | 2022-03-07T15:55:27.000Z | /*
* Copyright (c) 2016, Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 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 Freescale Semiconductor, Inc. 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.
*/
#include "fsl_utick.h"
#include "fsl_power.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/* Typedef for interrupt handler. */
typedef void (*utick_isr_t)(UTICK_Type *base, utick_callback_t cb);
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* @brief Gets the instance from the base address
*
* @param base UTICK peripheral base address
*
* @return The UTICK instance
*/
static uint32_t UTICK_GetInstance(UTICK_Type *base);
/*******************************************************************************
* Variables
******************************************************************************/
/* Array of UTICK handle. */
static utick_callback_t s_utickHandle[FSL_FEATURE_SOC_UTICK_COUNT];
/* Array of UTICK peripheral base address. */
static UTICK_Type *const s_utickBases[] = UTICK_BASE_PTRS;
/* Array of UTICK IRQ number. */
static const IRQn_Type s_utickIRQ[] = UTICK_IRQS;
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
/* Array of UTICK clock name. */
static const clock_ip_name_t s_utickClock[] = UTICK_CLOCKS;
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
/* UTICK ISR for transactional APIs. */
static utick_isr_t s_utickIsr;
/*******************************************************************************
* Code
******************************************************************************/
static uint32_t UTICK_GetInstance(UTICK_Type *base)
{
uint32_t instance;
/* Find the instance index from base address mappings. */
for (instance = 0; instance < FSL_FEATURE_SOC_UTICK_COUNT; instance++)
{
if (s_utickBases[instance] == base)
{
break;
}
}
assert(instance < FSL_FEATURE_SOC_UTICK_COUNT);
return instance;
}
void UTICK_SetTick(UTICK_Type *base, utick_mode_t mode, uint32_t count, utick_callback_t cb)
{
uint32_t instance;
/* Get instance from peripheral base address. */
instance = UTICK_GetInstance(base);
/* Save the handle in global variables to support the double weak mechanism. */
s_utickHandle[instance] = cb;
EnableDeepSleepIRQ(s_utickIRQ[instance]);
base->CTRL = count | UTICK_CTRL_REPEAT(mode);
}
void UTICK_Init(UTICK_Type *base)
{
/* Enable utick clock */
CLOCK_EnableClock(s_utickClock[UTICK_GetInstance(base)]);
/* Power up Watchdog oscillator*/
POWER_DisablePD(kPDRUNCFG_PD_WDT_OSC);
s_utickIsr = UTICK_HandleIRQ;
}
void UTICK_Deinit(UTICK_Type *base)
{
/* Turn off utick */
base->CTRL = 0;
/* Disable utick clock */
CLOCK_DisableClock(s_utickClock[UTICK_GetInstance(base)]);
}
uint32_t UTICK_GetStatusFlags(UTICK_Type *base)
{
return (base->STAT);
}
void UTICK_ClearStatusFlags(UTICK_Type *base)
{
base->STAT = UTICK_STAT_INTR_MASK;
}
void UTICK_HandleIRQ(UTICK_Type *base, utick_callback_t cb)
{
UTICK_ClearStatusFlags(base);
if (cb)
{
cb();
}
}
#if defined(UTICK0)
void UTICK0_DriverIRQHandler(void)
{
s_utickIsr(UTICK0, s_utickHandle[0]);
}
#endif
#if defined(UTICK1)
void UTICK1_DriverIRQHandler(void)
{
s_utickIsr(UTICK1, s_utickHandle[1]);
}
#endif
#if defined(UTICK2)
void UTICK2_DriverIRQHandler(void)
{
s_utickIsr(UTICK2, s_utickHandle[2]);
}
#endif
| 32.74359 | 92 | 0.645458 |
a282be70a251d6c2c88972ee085b42ad9cf885ab | 959 | h | C | libs/ReWireSDK_2.6.4_135/ReWireSDK/ReWireAPI.h | alxarsenault/axLib-1 | aff63abebff118059d5daca80f06cc8464192c6d | [
"MIT"
] | 1 | 2019-10-15T05:09:34.000Z | 2019-10-15T05:09:34.000Z | libs/ReWireSDK_2.6.4_135/ReWireSDK/ReWireAPI.h | EQ4/axLib | aff63abebff118059d5daca80f06cc8464192c6d | [
"MIT"
] | null | null | null | libs/ReWireSDK_2.6.4_135/ReWireSDK/ReWireAPI.h | EQ4/axLib | aff63abebff118059d5daca80f06cc8464192c6d | [
"MIT"
] | 1 | 2021-12-18T06:30:51.000Z | 2021-12-18T06:30:51.000Z | #ifndef REWIREAPI_H_
#define REWIREAPI_H_
/*
ReWire by Propellerhead, (C) Copyright Propellerhead Software AB.
ReWire and Propellerhead are trademarks of Propellerhead Software
AB. email: rewire@propellerheads.se
*/
/* Structures/types and constants for basic (non-portable) services.
This is internal to ReWire - not for mixer or device writer. */
#include "ReWire.h"
#ifdef __cplusplus
namespace ReWire {
extern "C" {
#endif /* __cplusplus */
#if WINDOWS && !_WIN64
#define REWIRECALL _cdecl
#else
#define REWIRECALL
#endif /* WINDOWS && !_WIN64 */
typedef ReWire_int32_t (REWIRECALL *REWIREPROC)();
/* Internal stuff */
extern ReWireError ReWireLoadReWireSharedLibrary(void);
extern REWIREPROC ReWireFindReWireSharedLibraryFunction(const ReWire_char_t functionName[]);
extern ReWireError ReWireUnloadReWireSharedLibrary(void);
#ifdef __cplusplus
} /* extern "C" */
} /* namespace ReWire */
#endif /* __cplusplus */
#endif /* REWIREAPI_H_ */
| 23.975 | 92 | 0.762252 |
2e6bab0e48187854ade69fc3dec26042b55653ea | 1,556 | h | C | pink/include/pika_cmd_time_histogram.h | rockeet/pink | 98870f811e9cfecaaad9fa44ebf99ab2933b18f1 | [
"BSD-3-Clause"
] | 1 | 2021-12-31T09:58:40.000Z | 2021-12-31T09:58:40.000Z | pink/include/pika_cmd_time_histogram.h | rockeet/pink | 98870f811e9cfecaaad9fa44ebf99ab2933b18f1 | [
"BSD-3-Clause"
] | null | null | null | pink/include/pika_cmd_time_histogram.h | rockeet/pink | 98870f811e9cfecaaad9fa44ebf99ab2933b18f1 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021-present, Topling, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#pragma once
#include <unordered_map>
#include <string>
#include "terark/fstring.hpp"
#include "monitoring/histogram.h"
namespace time_histogram {
using terark::fstring;
enum CmdProcessStep {
Parse,
Schedule,
Process,
Response,
All,
StepMax,
};
struct CmdProcessTime {
size_t cmd_idx;
uint64_t start_time;
uint64_t end_time;
};
struct CmdTimeInfo {
uint64_t read_start_time;
uint64_t parse_end_time;
uint64_t schedule_end_time;
uint64_t response_end_time;
std::vector<CmdProcessTime> cmd_process_times;
};
class PikaCmdRunTimeHistogram {
public:
PikaCmdRunTimeHistogram(const PikaCmdRunTimeHistogram&) = delete;
PikaCmdRunTimeHistogram& operator=(const PikaCmdRunTimeHistogram&) = delete;
PikaCmdRunTimeHistogram();
~PikaCmdRunTimeHistogram();
void AddTimeMetric(CmdTimeInfo& info);
std::string GetTimeMetric();
//size_t (*m_get_idx)(fstring) = nullptr;
fstring (*m_get_name)(size_t) = nullptr;
static constexpr size_t HistogramNum = 151;
private:
void AddTimeMetric(size_t cmd_idx, uint64_t value, CmdProcessStep step);
rocksdb::HistogramStat* HistogramTable[HistogramNum][StepMax];
const terark::fstring step_str[StepMax] = {"parse","schedule","process","response","all"};
};
} // end time_histogram
| 27.298246 | 92 | 0.762853 |
c82e6243c07e36ec4617c27775fb8ae859885507 | 534 | h | C | usr/libexec/identityservicesd/IDSEndpointResolverComponent.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | usr/libexec/identityservicesd/IDSEndpointResolverComponent.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | usr/libexec/identityservicesd/IDSEndpointResolverComponent.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import "IDSPipelineComponent.h"
@class IDSPeerIDManager;
@interface IDSEndpointResolverComponent : IDSPipelineComponent
{
IDSPeerIDManager *_peerIDManager; // 8 = 0x8
}
- (void).cxx_destruct; // IMP=0x00000001000a7654
- (id)runIndividuallyWithInput:(id)arg1; // IMP=0x00000001000a70dc
- (id)initWithQueryCache:(id)arg1; // IMP=0x00000001000a6fec
@end
| 24.272727 | 120 | 0.7397 |
aea8e46ee665a78f761743c5af73a565adcecfc8 | 507 | h | C | servers.h | slist/cbapi-qt-demo | b44e31824a5b9973aa0ccff39c15ff7805902b8b | [
"MIT"
] | 3 | 2020-09-14T19:39:53.000Z | 2021-01-19T11:58:27.000Z | servers.h | slist/cbapi-qt-demo | b44e31824a5b9973aa0ccff39c15ff7805902b8b | [
"MIT"
] | null | null | null | servers.h | slist/cbapi-qt-demo | b44e31824a5b9973aa0ccff39c15ff7805902b8b | [
"MIT"
] | null | null | null | // Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: MIT
#ifndef SERVERS_H
#define SERVERS_H
#include <QWidget>
#include <QVBoxLayout>
namespace Ui {
class Servers;
}
class Servers : public QWidget
{
Q_OBJECT
public:
explicit Servers(QWidget *parent = nullptr);
~Servers();
private slots:
void on_pushButton_cancel_clicked();
private:
Ui::Servers *ui;
QVBoxLayout * layout1;
QVBoxLayout * layout2;
QVBoxLayout * layout3;
void load();
};
#endif // SERVERS_H
| 14.911765 | 48 | 0.690335 |
aee744401df0f73a72987250d2740e2656f339ac | 2,819 | h | C | STM32F1/system/libmaple/usart_private.h | saloid/Arduino_STM32 | ab952e126725e638438dd81cf29c62a274915497 | [
"Unlicense"
] | null | null | null | STM32F1/system/libmaple/usart_private.h | saloid/Arduino_STM32 | ab952e126725e638438dd81cf29c62a274915497 | [
"Unlicense"
] | null | null | null | STM32F1/system/libmaple/usart_private.h | saloid/Arduino_STM32 | ab952e126725e638438dd81cf29c62a274915497 | [
"Unlicense"
] | null | null | null | /******************************************************************************
* The MIT License
*
* Copyright (c) 2012 LeafLabs, LLC.
* Copyright (c) 2010 Perry Hung.
*
* 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.
*****************************************************************************/
/**
* @file libmaple/usart_private.h
* @author Marti Bolivar <mbolivar@leaflabs.com>
* @brief Private USART header.
*/
#ifndef _LIBMAPLE_USART_PRIVATE_H_
#define _LIBMAPLE_USART_PRIVATE_H_
#include <libmaple/ring_buffer.h>
#include <libmaple/usart.h>
inline void usart_irq(ring_buffer *rb, ring_buffer *wb, usart_reg_map *regs) {
/* Handling RXNEIE and TXEIE interrupts.
* RXNE signifies availability of a byte in DR.
*
* See table 198 (sec 27.4, p809) in STM document RM0008 rev 15.
* We enable RXNEIE. */
if ((regs->CR1 & USART_CR1_RXNEIE) && (regs->SR & USART_SR_RXNE)) {
if( regs->SR & USART_SR_FE || regs->SR & USART_SR_PE ) {
// framing error or parity error
regs->DR; //read and throw away the data, this clears FE and PE as well
} else {
#ifdef USART_SAFE_INSERT
/* If the buffer is full and the user defines USART_SAFE_INSERT,
* ignore new bytes. */
rb_safe_insert(rb, (uint8)regs->DR);
#else
/* By default, push bytes around in the ring buffer. */
rb_push_insert(rb, (uint8)regs->DR);
#endif
}
}
/* TXE signifies readiness to send a byte to DR. */
if ((regs->CR1 & USART_CR1_TXEIE) && (regs->SR & USART_SR_TXE)) {
if (!rb_is_empty(wb))
regs->DR=rb_remove(wb);
else
regs->CR1 &= ~((uint32)USART_CR1_TXEIE); // disable TXEIE
}
}
uint32 _usart_clock_freq(usart_dev *dev);
#endif
| 38.616438 | 82 | 0.64491 |
08f7af99d02c9aa667b9b712c6fcc7afc651e528 | 459 | c | C | program_design/week1/money.c | KevOrr/Classes | e2ebea5e09f742e9120345ba4b08528256a5cfce | [
"PostgreSQL"
] | 1 | 2017-07-10T05:09:27.000Z | 2017-07-10T05:09:27.000Z | program_design/week1/money.c | KevOrr/Classes | e2ebea5e09f742e9120345ba4b08528256a5cfce | [
"PostgreSQL"
] | 3 | 2016-03-24T02:48:19.000Z | 2017-04-11T06:26:27.000Z | program_design/week1/money.c | KevOrr/Classes | e2ebea5e09f742e9120345ba4b08528256a5cfce | [
"PostgreSQL"
] | null | null | null | // Kevin Orr
// Prof. Jing Wang MW 12:30-1:45
#include <stdio.h>
int main(void) {
int pennies, nickles, dimes, quarters;
printf("Pennies: ");
scanf("%d", &pennies);
printf("Nickles: ");
scanf("%d", &nickles);
printf("Dimes: ");
scanf("%d", &dimes);
printf("Quarters: ");
scanf("%d", &quarters);
int total = pennies + 5*nickles + 10*dimes + 25*quarters;
printf("Total: $%.2f\n", total / 100.0);
return 0;
}
| 19.956522 | 61 | 0.555556 |
835653d830f2d7ea84236a01fd2a51b41d858ec1 | 591 | h | C | tools/krad_effects/pass.h | diederickh/krad_radio | 2477d2e5ad5d68a0c122ce34082977b3bdfe55d7 | [
"0BSD"
] | null | null | null | tools/krad_effects/pass.h | diederickh/krad_radio | 2477d2e5ad5d68a0c122ce34082977b3bdfe55d7 | [
"0BSD"
] | null | null | null | tools/krad_effects/pass.h | diederickh/krad_radio | 2477d2e5ad5d68a0c122ce34082977b3bdfe55d7 | [
"0BSD"
] | null | null | null | #include <malloc.h>
#include <math.h>
//#include "util/db.h"
//#include "util/rms.h"
#include "util/biquad.h"
#include "util/iir.h"
#define BANDWIDTH 1.5f
typedef struct {
int pos;
float rate;
biquad *high_filter;
biquad *low_filter;
float samp;
float high_freq;
float low_freq;
//int low;
//int high;
//iir
int stages;
iirf_t* high_iirf;
iir_stage_t* high_gt;
iirf_t* low_iirf;
iir_stage_t* low_gt;
} pass_t;
pass_t *pass_create(pass_t *pass);
void pass_run(pass_t *pass, float *input, float *output, int sample_count);
void pass_destroy(pass_t *pass);
| 15.153846 | 75 | 0.692047 |
83a40b8d9f4b4b54e1b8e76524e68a9e94a6eaae | 28,541 | h | C | SeetaNet/src/include_inner/SeetaNetProto.h | chlzaoyaowan/SeetaFace2 | 7ce6714c766ffb1f5f5fc073e38fa5d4981d7a52 | [
"BSD-2-Clause"
] | 2,063 | 2019-08-19T01:16:50.000Z | 2022-03-30T03:45:19.000Z | SeetaNet/src/include_inner/SeetaNetProto.h | chlzaoyaowan/SeetaFace2 | 7ce6714c766ffb1f5f5fc073e38fa5d4981d7a52 | [
"BSD-2-Clause"
] | 102 | 2019-08-19T01:55:19.000Z | 2021-12-22T03:33:39.000Z | SeetaNet/src/include_inner/SeetaNetProto.h | chlzaoyaowan/SeetaFace2 | 7ce6714c766ffb1f5f5fc073e38fa5d4981d7a52 | [
"BSD-2-Clause"
] | 636 | 2019-08-19T01:21:43.000Z | 2022-03-06T13:57:53.000Z | #ifndef _SEETANET_PROTO_H_
#define _SEETANET_PROTO_H_
#include <string>
#include <vector>
#include <cstdint>
#include <memory>
using std::vector;
using std::string;
namespace seeta
{
class SeetaNet_BaseMsg {
public:
SeetaNet_BaseMsg();
virtual ~SeetaNet_BaseMsg();
virtual int read( const char *buf, int len ) = 0;
virtual int write( char *buf, int len ) = 0;
int read_tag( const char *buf, int len );
int write_tag( char *buf, int len );
public:
uint32_t tag;
};
class SeetaNet_BlobShape : public SeetaNet_BaseMsg {
public:
SeetaNet_BlobShape();
~SeetaNet_BlobShape();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
vector<uint32_t> dim; //0x00000001
};
class SeetaNet_BlobProto : public SeetaNet_BaseMsg {
public:
SeetaNet_BlobProto();
~SeetaNet_BlobProto();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
SeetaNet_BlobShape shape; //0x00000001
vector<float> data; //0x00000002
};
class SeetaNet_PreluParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_PreluParameter();
~SeetaNet_PreluParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
SeetaNet_BlobProto param; //0x00000001
};
class SeetaNet_CropParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_CropParameter();
~SeetaNet_CropParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_axis( int32_t value ) {
axis = value;
tag |= 0x00000001;
}
bool has_axis() const {
return ( ( tag & 0x00000001 ) > 0 );
}
public:
int32_t axis; //0x00000001
vector<uint32_t> offset; //0x00000002
};
class SeetaNet_ConvolutionParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_ConvolutionParameter();
~SeetaNet_ConvolutionParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_dilation_height( uint32_t value ) {
dilation_height = value;
tag |= 0x00000004;
}
bool has_dilation_height() const {
return ( ( tag & 0x00000004 ) > 0 );
}
void set_dilation_width( uint32_t value ) {
dilation_width = value;
tag |= 0x00000008;
}
bool has_dilation_width() const {
return ( ( tag & 0x00000008 ) > 0 );
}
void set_num_output( uint32_t value ) {
num_output = value;
tag |= 0x00000010;
}
bool has_num_output() const {
return ( ( tag & 0x00000010 ) > 0 );
}
void set_pad_height( uint32_t value ) {
pad_height = value;
tag |= 0x00000020;
}
bool has_pad_height() const {
return ( ( tag & 0x00000020 ) > 0 );
}
void set_pad_width( uint32_t value ) {
pad_width = value;
tag |= 0x00000040;
}
bool has_pad_width() const {
return ( ( tag & 0x00000040 ) > 0 );
}
void set_kernel_height( uint32_t value ) {
kernel_height = value;
tag |= 0x00000080;
}
bool has_kernel_height() const {
return ( ( tag & 0x00000080 ) > 0 );
}
void set_kernel_width( uint32_t value ) {
kernel_width = value;
tag |= 0x00000100;
}
bool has_kernel_width() const {
return ( ( tag & 0x00000100 ) > 0 );
}
void set_stride_height( uint32_t value ) {
stride_height = value;
tag |= 0x00000200;
}
bool has_stride_height() const {
return ( ( tag & 0x00000200 ) > 0 );
}
void set_stride_width( uint32_t value ) {
stride_width = value;
tag |= 0x00000400;
}
bool has_stride_width() const {
return ( ( tag & 0x00000400 ) > 0 );
}
void set_group( uint32_t value ) {
group = value;
tag |= 0x00000800;
}
bool has_group() const {
return ( ( tag & 0x00000800 ) > 0 );
}
void set_axis( uint32_t value ) {
axis = value;
tag |= 0x00001000;
}
bool has_axis() const {
return ( ( tag & 0x00001000 ) > 0 );
}
void set_force_nd_im2col( bool value ) {
force_nd_im2col = value;
tag |= 0x00002000;
}
bool has_force_nd_im2col() const {
return ( ( tag & 0x00002000 ) > 0 );
}
void set_tf_padding( const std::string &value ) {
tf_padding = value;
tag |= 0x00004000;
}
bool has_tf_padding() const {
return ( ( tag & 0x00004000 ) > 0 );
}
public:
SeetaNet_BlobProto bias_param; //0x00000001
SeetaNet_BlobProto kernel_param; //0x00000002
uint32_t dilation_height; //0x00000004
uint32_t dilation_width; //0x00000008
uint32_t num_output; //0x00000010
uint32_t pad_height; //0x00000020
uint32_t pad_width; //0x00000040
uint32_t kernel_height; //0x00000080
uint32_t kernel_width; //0x00000100
uint32_t stride_height; //0x00000200
uint32_t stride_width; //0x00000400
uint32_t group; //0x00000800
int32_t axis; //0x00001000
bool force_nd_im2col; //0x00002000
// for tf padding setting, supporting VALID and SAME option
string tf_padding; //0x00004000
};
class SeetaNet_BatchNormliseParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_BatchNormliseParameter();
~SeetaNet_BatchNormliseParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
SeetaNet_BlobProto mean_param; //0x00000001
SeetaNet_BlobProto covariance_param; //0x00000002
};
class SeetaNet_ScaleParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_ScaleParameter();
~SeetaNet_ScaleParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
SeetaNet_BlobProto scale_param; //0x00000001
SeetaNet_BlobProto bias_param; //0x00000002
};
class SeetaNet_ConcatParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_ConcatParameter();
~SeetaNet_ConcatParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_concat_dim( uint32_t value ) {
concat_dim = value;
tag |= 0x00000001;
}
bool has_concat_dim() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_axis( int32_t value ) {
axis = value;
tag |= 0x00000002;
}
bool has_axis() const {
return ( ( tag & 0x00000002 ) > 0 );
}
public:
uint32_t concat_dim; //0x00000001
int32_t axis; //0x00000002
};
class SeetaNet_EltwiseParameter : public SeetaNet_BaseMsg {
public:
enum EltwiseOp
{
PROD = 0,
SUM = 1,
MAX = 2
};
SeetaNet_EltwiseParameter();
~SeetaNet_EltwiseParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_operation( EltwiseOp value ) {
operation = value;
tag |= 0x00000001;
}
bool has_operation() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_stable_prod_grad( bool value ) {
stable_prod_grad = value;
tag |= 0x00000004;
}
bool has_stable_prod_grad() const {
return ( ( tag & 0x00000004 ) > 0 ) ;
}
public:
EltwiseOp operation; //0x00000001
vector<float> coeff; //0x00000002
bool stable_prod_grad; //0x00000004
};
class SeetaNet_ExpParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_ExpParameter();
~SeetaNet_ExpParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_base( float value ) {
base = value;
tag |= 0x00000001;
}
bool has_base() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_scale( float value ) {
scale = value;
tag |= 0x00000002;
}
bool has_scale() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_shift( float value ) {
shift = value;
tag |= 0x00000004;
}
bool has_shift() const {
return ( ( tag & 0x00000004 ) > 0 );
}
public:
float base; //0x00000001
float scale; //0x00000002
float shift; //0x00000004
};
class SeetaNet_MemoryDataParameterProcess: public SeetaNet_BaseMsg {
public:
SeetaNet_MemoryDataParameterProcess();
~SeetaNet_MemoryDataParameterProcess();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_batch_size( uint32_t value ) {
batch_size = value;
tag |= 0x00000001;
}
bool has_batch_size() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_channels( uint32_t value ) {
channels = value;
tag |= 0x00000002;
}
bool has_channels() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_height( uint32_t value ) {
height = value;
tag |= 0x00000004;
}
bool has_height() const {
return ( ( tag & 0x00000004 ) > 0 );
}
void set_width( uint32_t value ) {
width = value;
tag |= 0x00000008;
}
bool has_width() const {
return ( ( tag & 0x00000008 ) > 0 );
}
void set_new_height( uint32_t value ) {
new_height = value;
tag |= 0x00000010;
}
bool has_new_height() const {
return ( ( tag & 0x00000010 ) > 0 );
}
void set_new_width( uint32_t value ) {
new_width = value;
tag |= 0x00000020;
}
bool has_new_width() const {
return ( ( tag & 0x00000020 ) > 0 );
}
void set_scale( float value ) {
scale = value;
tag |= 0x00000040;
}
bool has_scale() const {
return ( ( tag & 0x00000040 ) > 0 );
}
void set_crop_size_height( uint32_t value ) {
crop_size_height = value;
tag |= 0x00000200;
}
bool has_crop_size_height() const {
return ( ( tag & 0x00000200 ) > 0 );
}
void set_crop_size_width( uint32_t value ) {
crop_size_width = value;
tag |= 0x00000400;
}
bool has_crop_size_width() const {
return ( ( tag & 0x00000400 ) > 0 );
}
void set_prewhiten( bool value ) {
prewhiten = value;
tag |= 0x00001000;
}
bool has_prewhiten() const {
return ( ( tag & 0x00001000 ) > 0 );
}
public:
uint32_t batch_size; //0x00000001
uint32_t channels; //0x00000002
uint32_t height; //0x00000004
uint32_t width; //0x00000008
uint32_t new_height; //0x00000010
uint32_t new_width; //0x00000020
float scale; //0x00000040
SeetaNet_BlobProto mean_file; //0x00000080
vector<float> mean_value; //0x00000100
uint32_t crop_size_height; //0x00000200
uint32_t crop_size_width; //0x00000400
// for channels swap supprt push [2, 1, 0] means convert BGR2RGB
vector<uint32_t> channel_swaps; //0x00000800
// for prewhiten action after above actions
bool prewhiten; //0x00001000
};
class SeetaNet_TransformationParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_TransformationParameter();
~SeetaNet_TransformationParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_scale( float value ) {
scale = value;
tag |= 0x00000001;
}
bool has_scale() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_mirror( bool value ) {
mirror = value;
tag |= 0x00000002;
}
bool has_mirror() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_crop_height( uint32_t value ) {
crop_height = value;
tag |= 0x00000004;
}
bool has_crop_height() const {
return ( ( tag & 0x00000004 ) > 0 );
}
void set_crop_width( uint32_t value ) {
crop_width = value;
tag |= 0x00000008;
}
bool has_crop_width() const {
return ( ( tag & 0x00000008 ) > 0 );
}
void set_mean_file( const string &value ) {
mean_file = value;
tag |= 0x00000010;
}
bool has_mean_file() const {
return ( ( tag & 0x00000010 ) > 0 );
}
void set_mean_value( float value ) {
mean_value = value;
tag |= 0x00000020;
}
bool has_mean_value() const {
return ( ( tag & 0x00000020 ) > 0 );
}
void set_force_color( bool value ) {
force_color = value;
tag |= 0x00000040;
}
bool has_force_color() const {
return ( ( tag & 0x00000040 ) > 0 );
}
void set_force_gray( bool value ) {
force_gray = value;
tag |= 0x00000080;
}
bool has_force_gray() const {
return ( ( tag & 0x00000080 ) > 0 );
}
public:
float scale; //0x00000001
bool mirror; //0x00000002
uint32_t crop_height; //0x00000004
uint32_t crop_width; //0x00000008
string mean_file; //0x00000010
float mean_value; //0x00000020
bool force_color; //0x00000040
bool force_gray; //0x00000080
};
class SeetaNet_InnerProductParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_InnerProductParameter();
~SeetaNet_InnerProductParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_num_output( uint32_t value ) {
num_output = value;
tag |= 0x00000001;
}
bool has_num_output() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_axis( int32_t value ) {
axis = value;
tag |= 0x00000002;
}
bool has_axis() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_transpose( bool value ) {
transpose = value;
tag |= 0x00000004;
}
bool has_transpose() const {
return ( ( tag & 0x00000004 ) > 0 );
}
public:
uint32_t num_output; //0x00000001
int32_t axis; //0x00000002
bool transpose; //0x00000004
SeetaNet_BlobProto bias_param; //0x00000008
SeetaNet_BlobProto Inner_param; //0x00000010
};
class SeetaNet_LRNParameter: public SeetaNet_BaseMsg {
public:
enum NormRegion
{
ACROSS_CHANNELS = 0,
WITHIN_CHANNEL = 1
};
SeetaNet_LRNParameter();
~SeetaNet_LRNParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_local_size( uint32_t value ) {
local_size = value;
tag |= 0x00000001;
}
bool has_local_size() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_alpha( float value ) {
alpha = value;
tag |= 0x00000002;
}
bool has_alpha() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_beta( float value ) {
beta = value;
tag |= 0x00000004;
}
bool has_beta() const {
return ( ( tag & 0x00000004 ) > 0 );
}
void set_norm_region( NormRegion value ) {
norm_region = value;
tag |= 0x00000008;
}
bool has_norm_region() const {
return ( ( tag & 0x00000008 ) > 0 );
}
void set_k( float value ) {
k = value;
tag |= 0x00000010;
}
bool has_k() const {
return ( ( tag & 0x00000010 ) > 0 );
}
public:
uint32_t local_size; //0x00000001
float alpha; //0x00000002
float beta; //0x00000004
NormRegion norm_region; //0x00000008
float k; //0x00000010
};
class SeetaNet_PoolingParameter: public SeetaNet_BaseMsg {
public:
enum PoolMethod
{
MAX = 0,
AVE = 1,
STOCHASTIC = 2
};
SeetaNet_PoolingParameter();
~SeetaNet_PoolingParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_pool( PoolMethod value ) {
pool = value;
tag |= 0x00000001;
}
bool has_pool() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_pad_height( uint32_t value ) {
pad_height = value;
tag |= 0x00000002;
}
bool has_pad_height() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_pad_width( uint32_t value ) {
pad_width = value;
tag |= 0x00000004;
}
bool has_pad_width() const {
return ( ( tag & 0x00000004 ) > 0 );
}
void set_kernel_height( uint32_t value ) {
kernel_height = value;
tag |= 0x00000008;
}
bool has_kernel_height() const {
return ( ( tag & 0x00000008 ) > 0 );
}
void set_kernel_width( uint32_t value ) {
kernel_width = value;
tag |= 0x00000010;
}
bool has_kernel_width() const {
return ( ( tag & 0x00000010 ) > 0 );
}
void set_stride_height( uint32_t value ) {
stride_height = value;
tag |= 0x00000020;
}
bool has_stride_height() const {
return ( ( tag & 0x00000020 ) > 0 );
}
void set_stride_width( uint32_t value ) {
stride_width = value;
tag |= 0x00000040;
}
bool has_stride_width() const {
return ( ( tag & 0x00000040 ) > 0 );
}
void set_global_pooling( bool value ) {
global_pooling = value;
tag |= 0x00000080;
}
bool has_global_pooling() const {
return ( ( tag & 0x00000080 ) > 0 );
}
void set_valid( bool value ) {
valid = value;
tag |= 0x00000100;
}
bool has_valid() const {
return ( ( tag & 0x00000100 ) > 0 );
}
void set_tf_padding( const std::string &value ) {
tf_padding = value;
tag |= 0x00000200;
}
bool has_tf_padding() const {
return ( ( tag & 0x00000200 ) > 0 );
}
public:
PoolMethod pool; //0x00000001
uint32_t pad_height; //0x00000002
uint32_t pad_width; //0x00000004
uint32_t kernel_height; //0x00000008
uint32_t kernel_width; //0x00000010
uint32_t stride_height; //0x00000020
uint32_t stride_width; //0x00000040
bool global_pooling; //0x00000080
bool valid; //0x00000100
string tf_padding; //0x00000200
};
class SeetaNet_PowerParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_PowerParameter();
~SeetaNet_PowerParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_power( float value ) {
power = value;
tag |= 0x00000001;
}
bool has_power() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_scale( float value ) {
scale = value;
tag |= 0x00000002;
}
bool has_scale() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_shift( float value ) {
shift = value;
tag |= 0x00000004;
}
bool has_shift() const {
return ( ( tag & 0x00000004 ) > 0 );
}
public:
float power; //0x00000001
float scale; //0x00000002
float shift; //0x00000004
};
class SeetaNet_ReLUParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_ReLUParameter();
~SeetaNet_ReLUParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_negative_slope( float value ) {
negative_slope = value;
tag |= 0x00000001;
}
bool has_negative_slope() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_max( float value ) {
max = value;
tag |= 0x00000002;
}
bool has_max() const {
return ( ( tag & 0x00000002 ) > 0 );
}
public:
float negative_slope; //0x00000001
float max; //0x00000002
};
class SeetaNet_SoftmaxParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_SoftmaxParameter();
~SeetaNet_SoftmaxParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_axis( int32_t value ) {
axis = value;
tag |= 0x00000001;
}
bool has_axis() const {
return ( ( tag & 0x00000001 ) > 0 );
}
public:
int32_t axis; //0x00000001
};
class SeetaNet_SliceParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_SliceParameter();
~SeetaNet_SliceParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_axis( int32_t value ) {
axis = value;
tag |= 0x00000001;
}
bool has_axis() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_slice_dim( uint32_t value ) {
slice_dim = value;
tag |= 0x00000004;
}
bool has_slice_dim() const {
return ( ( tag & 0x00000004 ) > 0 );
}
public:
int32_t axis; //0x00000001
vector<uint32_t> slice_point; //0x00000002
uint32_t slice_dim; //0x00000004
};
class SeetaNet_SigmoidParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_SigmoidParameter();
~SeetaNet_SigmoidParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
};
class SeetaNet_SplitParameter: public SeetaNet_BaseMsg {
public:
SeetaNet_SplitParameter();
~SeetaNet_SplitParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
};
class SeetaNet_SpaceToBatchNDLayer: public SeetaNet_BaseMsg {
public:
SeetaNet_SpaceToBatchNDLayer();
~SeetaNet_SpaceToBatchNDLayer();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
// size should be 2, like [2, 2]
vector<int32_t> block_shape; //0x00000001
// size should be 2x2, like [1, 1, 2, 2]
vector<int32_t> paddings; //0x00000002
};
class SeetaNet_BatchToSpaceNDLayer: public SeetaNet_BaseMsg {
public:
SeetaNet_BatchToSpaceNDLayer();
~SeetaNet_BatchToSpaceNDLayer();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
// size should be 2, like [2, 2]
vector<int32_t> block_shape; //0x00000001
// size should be 2x2, like [1, 1, 2, 2]
vector<int32_t> crops; //0x00000002
};
class SeetaNet_ReshapeLayer: public SeetaNet_BaseMsg {
public:
SeetaNet_ReshapeLayer();
~SeetaNet_ReshapeLayer();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
vector<int32_t> shape; //0x00000001
// for tf, NCHW -> NHWC
vector<int32_t> permute; //0x00000002
};
class SeetaNet_RealMulLayer: public SeetaNet_BaseMsg {
public:
SeetaNet_RealMulLayer();
~SeetaNet_RealMulLayer();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
SeetaNet_BlobProto y; //0x00000001
};
class SeetaNet_ShapeIndexPatchLayer: public SeetaNet_BaseMsg {
public:
SeetaNet_ShapeIndexPatchLayer();
~SeetaNet_ShapeIndexPatchLayer();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
public:
//{h,w}
vector<int32_t> origin_patch; //0x00000001
//{h,w}
vector<int32_t> origin; //0x00000002
};
class SeetaNet_LayerParameter : public SeetaNet_BaseMsg {
public:
SeetaNet_LayerParameter();
~SeetaNet_LayerParameter();
virtual int read( const char *buf, int len );
virtual int write( char *buf, int len );
void set_name( const string &value ) {
name = value;
tag |= 0x00000001;
}
bool has_name() const {
return ( ( tag & 0x00000001 ) > 0 );
}
void set_type( uint32_t value ) {
type = value;
tag |= 0x00000002;
}
bool has_type() const {
return ( ( tag & 0x00000002 ) > 0 );
}
void set_layer_index( uint32_t value ) {
layer_index = value;
tag |= 0x00000004;
}
bool has_layer_index() const {
return ( ( tag & 0x00000004 ) > 0 );
}
public:
string name; //0x00000001
uint32_t type; //0x00000002
uint32_t layer_index; //0x00000004
vector<string> bottom; //0x00000008
vector<string> top; //0x00000010
vector<uint32_t> top_index; //0x00000020
vector<uint32_t> bottom_index; //0x00000040
std::shared_ptr<SeetaNet_BaseMsg> msg; //0x00000080
};
}
#endif
| 29.393409 | 72 | 0.516906 |
d3bbde7f06ecba87ad3972640052163108738b21 | 1,412 | c | C | PosixCompilation/UefiMock/Library/MemoryAllocationLib.c | harperse/CloverBootloader | 8d1baad2a62c66aae776cfd45d832399632c299e | [
"BSD-2-Clause"
] | null | null | null | PosixCompilation/UefiMock/Library/MemoryAllocationLib.c | harperse/CloverBootloader | 8d1baad2a62c66aae776cfd45d832399632c299e | [
"BSD-2-Clause"
] | null | null | null | PosixCompilation/UefiMock/Library/MemoryAllocationLib.c | harperse/CloverBootloader | 8d1baad2a62c66aae776cfd45d832399632c299e | [
"BSD-2-Clause"
] | null | null | null | //
// MemoryAllocationLib.c
// cpp_tests UTF16 signed char
//
// Created by Jief on 30/01/2021.
// Copyright © 2021 Jief_Machak. All rights reserved.
//
#include <Library/MemoryAllocationLib.h>
void* AllocatePool(UINTN AllocationSize)
{
return (void*)malloc((size_t)AllocationSize);
}
void* AllocateZeroPool(UINTN AllocationSize)
{
void* p = (void*)malloc((size_t)AllocationSize);
memset(p, 0, (size_t)AllocationSize);
return p;
}
void* AllocateCopyPool (UINTN AllocationSize, CONST VOID *Buffer)
{
void* p = malloc(AllocationSize);
memcpy(p, Buffer, AllocationSize);
return p;
}
void* ReallocatePool(UINTN OldSize, UINTN NewSize, void* OldBuffer)
{
(void)OldSize;
if ( !OldBuffer ) return AllocatePool(NewSize);
return (void*)realloc(OldBuffer, (size_t)NewSize);
}
void FreePool(IN JCONST VOID *Buffer)
{
free((void*)Buffer);
}
//#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
VOID *
EFIAPI
AllocateAlignedPages (
IN UINTN Pages,
IN UINTN Alignment
)
{
panic("not yet");
}
VOID
EFIAPI
FreeAlignedPages (
IN VOID *Buffer,
IN UINTN Pages
)
{
panic("not yet");
}
VOID *
EFIAPI
AllocatePages (
IN UINTN Pages
)
{
panic("not yet");
}
VOID
EFIAPI
FreePages (
IN VOID *Buffer,
IN UINTN Pages
)
{
panic("not yet");
}
| 16.611765 | 70 | 0.648017 |
039054750db09c349379679f3203d00e1fe564ed | 39,999 | c | C | src/mustache.c | mity/mustache4c | 1d6b25ac1ef93cf3cf032684d4689b2a7789e41f | [
"MIT"
] | 15 | 2017-09-07T02:39:39.000Z | 2021-05-02T13:59:10.000Z | src/mustache.c | mity/mustache4c | 1d6b25ac1ef93cf3cf032684d4689b2a7789e41f | [
"MIT"
] | null | null | null | src/mustache.c | mity/mustache4c | 1d6b25ac1ef93cf3cf032684d4689b2a7789e41f | [
"MIT"
] | 1 | 2020-05-10T11:36:53.000Z | 2020-05-10T11:36:53.000Z | /*
* Mustache4C
* (http://github.com/mity/mustache4c)
*
* Copyright (c) 2017 Martin Mitas
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "mustache.h"
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> /* for off_t */
#ifdef _MSC_VER
/* MSVC does not understand "inline" when building as pure C (not C++).
* However it understands "__inline" */
#ifndef __cplusplus
#define inline __inline
#endif
#endif
#define MUSTACHE_DEFAULTOPENER "{{"
#define MUSTACHE_DEFAULTCLOSER "}}"
#define MUSTACHE_MAXOPENERLENGTH 32
#define MUSTACHE_MAXCLOSERLENGTH 32
/**********************
*** Growing Buffer ***
**********************/
typedef struct MUSTACHE_BUFFER {
uint8_t* data;
size_t n;
size_t alloc;
} MUSTACHE_BUFFER;
static inline void
mustache_buffer_free(MUSTACHE_BUFFER* buf)
{
free(buf->data);
}
static int
mustache_buffer_insert(MUSTACHE_BUFFER* buf, off_t off, const void* data, size_t n)
{
if(buf->n + n > buf->alloc) {
size_t new_alloc = (buf->n + n) * 2;
uint8_t* new_data;
new_data = (uint8_t*) realloc(buf->data, new_alloc);
if(new_data == NULL)
return -1;
buf->data = new_data;
buf->alloc = new_alloc;
}
if(off < buf->n)
memmove(buf->data + off + n, buf->data + off, buf->n - off);
memcpy(buf->data + off, data, n);
buf->n += n;
return 0;
}
static inline int
mustache_buffer_append(MUSTACHE_BUFFER* buf, const void* data, size_t n)
{
return mustache_buffer_insert(buf, (off_t) buf->n, data, n);
}
static int
mustache_buffer_insert_num(MUSTACHE_BUFFER* buf, off_t off, uint64_t num)
{
uint8_t tmp[16];
size_t n = 0;
tmp[15 - n++] = num & 0x7f;
while(1) {
num = num >> 7;
if(num == 0)
break;
tmp[15 - n++] = 0x80 | (num & 0x7f);
}
return mustache_buffer_insert(buf, off, tmp+16-n, n);
}
static inline int
mustache_buffer_append_num(MUSTACHE_BUFFER* buf, uint64_t num)
{
return mustache_buffer_insert_num(buf, buf->n, num);
}
static uint64_t
mustache_decode_num(const uint8_t* data, off_t off, off_t* p_off)
{
uint64_t num = 0;
while(data[off] >= 0x80) {
num |= (data[off++] & 0x7f);
num = num << 7;
}
num |= data[off++];
*p_off = off;
return num;
}
/****************************
*** Stack Implementation ***
****************************/
typedef MUSTACHE_BUFFER MUSTACHE_STACK;
static inline void
mustache_stack_free(MUSTACHE_STACK* stack)
{
mustache_buffer_free(stack);
}
static inline int
mustache_stack_is_empty(MUSTACHE_STACK* stack)
{
return (stack->n == 0);
}
static inline int
mustache_stack_push(MUSTACHE_STACK* stack, uintptr_t item)
{
return mustache_buffer_append(stack, &item, sizeof(uintptr_t));
}
static inline uintptr_t
mustache_stack_peek(MUSTACHE_STACK* stack)
{
return *((uintptr_t*)(stack->data + (stack->n - sizeof(uintptr_t))));
}
static inline uintptr_t
mustache_stack_pop(MUSTACHE_STACK* stack)
{
uintptr_t item = mustache_stack_peek(stack);
stack->n -= sizeof(uintptr_t);
return item;
}
/***************************
*** Parsing & Compiling ***
***************************/
#define MUSTACHE_ISANYOF2(ch, ch1, ch2) ((ch) == (ch1) || (ch) == (ch2))
#define MUSTACHE_ISANYOF4(ch, ch1, ch2, ch3, ch4) ((ch) == (ch1) || (ch) == (ch2) || (ch) == (ch3) || (ch) == (ch4))
#define MUSTACHE_ISWHITESPACE(ch) MUSTACHE_ISANYOF4((ch), ' ', '\t', '\v', '\f')
#define MUSTACHE_ISNEWLINE(ch) MUSTACHE_ISANYOF2((ch), '\r', '\n')
/* Keep in sync with MUSTACHE_ERR_xxx constants. */
static const char* mustache_err_messages[] = {
"Success.",
"Tag opener has no closer.",
"Tag closer has no opener.",
"Tag closer is incompatible with its opener.",
"Tag has no name.",
"Tag name is invalid.",
"Section-opening tag has no closer.",
"Section-closing tag has no opener.",
"Name of section-closing tag does not match corresponding section-opening tag.",
"The section-opening is located here.",
"Invalid specification of delimiters."
};
/* For the given template, we construct list of MUSTACHE_TAGINFO structures.
* Along the way, we also check for any parsing errors and report them
* to the app.
*/
typedef enum MUSTACHE_TAGTYPE {
MUSTACHE_TAGTYPE_NONE = 0,
MUSTACHE_TAGTYPE_DELIM, /* {{=@ @=}} */
MUSTACHE_TAGTYPE_COMMENT, /* {{! comment }} */
MUSTACHE_TAGTYPE_VAR, /* {{ var }} */
MUSTACHE_TAGTYPE_VERBATIMVAR, /* {{{ var }}} */
MUSTACHE_TAGTYPE_VERBATIMVAR2, /* {{& var }} */
MUSTACHE_TAGTYPE_OPENSECTION, /* {{# section }} */
MUSTACHE_TAGTYPE_OPENSECTIONINV, /* {{^ section }} */
MUSTACHE_TAGTYPE_CLOSESECTION, /* {{/ section }} */
MUSTACHE_TAGTYPE_CLOSESECTIONINV,
MUSTACHE_TAGTYPE_PARTIAL, /* {{> partial }} */
MUSTACHE_TAGTYPE_INDENT /* for internal purposes. */
} MUSTACHE_TAGTYPE;
typedef struct MUSTACHE_TAGINFO {
MUSTACHE_TAGTYPE type;
off_t line;
off_t col;
off_t beg;
off_t end;
off_t name_beg;
off_t name_end;
} MUSTACHE_TAGINFO;
static void
mustache_parse_error(int err_code, const char* msg,
unsigned line, unsigned column, void* parser_data)
{
/* noop */
}
static int
mustache_is_std_closer(const char* closer, size_t closer_len)
{
off_t off;
for(off = 0; off < closer_len; off++) {
if(closer[off] != '}')
return 0;
}
return 1;
}
static int
mustache_validate_tagname(const char* tagname, size_t size)
{
off_t off;
if(size == 1 && tagname[0] == '.')
return 0;
/* Verify there is no whitespace and that '.' is used only as a delimiter
* of non-empty tokens. */
if(tagname[0] == '.' || tagname[size-1] == '.')
return -1;
for(off = 0; off < size; off++) {
if(MUSTACHE_ISWHITESPACE(tagname[off]))
return -1;
if(tagname[off] == '.' && off+1 < size && tagname[off+1] == '.')
return -1;
}
return 0;
}
static int
mustache_validate_sections(const char* templ_data, MUSTACHE_BUFFER* tags_buffer,
const MUSTACHE_PARSER* parser, void* parser_data)
{
MUSTACHE_TAGINFO* tags = (MUSTACHE_TAGINFO*) tags_buffer->data;
unsigned n_tags = tags_buffer->n / sizeof(MUSTACHE_TAGINFO);
unsigned i;
MUSTACHE_STACK section_stack = { 0 };
MUSTACHE_TAGINFO* opener;
int n_errors = 0;
int ret = -1;
for(i = 0; i < n_tags; i++) {
switch(tags[i].type) {
case MUSTACHE_TAGTYPE_OPENSECTION:
case MUSTACHE_TAGTYPE_OPENSECTIONINV:
if(mustache_stack_push(§ion_stack, (uintptr_t) &tags[i]) != 0)
goto err;
break;
case MUSTACHE_TAGTYPE_CLOSESECTION:
case MUSTACHE_TAGTYPE_CLOSESECTIONINV:
if(mustache_stack_is_empty(§ion_stack)) {
parser->parse_error(MUSTACHE_ERR_DANGLINGSECTIONCLOSER,
mustache_err_messages[MUSTACHE_ERR_DANGLINGSECTIONCLOSER],
(unsigned)tags[i].line, (unsigned)tags[i].col,
parser_data);
n_errors++;
} else {
opener = (MUSTACHE_TAGINFO*) mustache_stack_pop(§ion_stack);
if(opener->name_end - opener->name_beg != tags[i].name_end - tags[i].name_beg ||
strncmp(templ_data + opener->name_beg,
templ_data + tags[i].name_beg,
opener->name_end - opener->name_beg) != 0)
{
parser->parse_error(MUSTACHE_ERR_SECTIONNAMEMISMATCH,
mustache_err_messages[MUSTACHE_ERR_SECTIONNAMEMISMATCH],
(unsigned)tags[i].line, (unsigned)tags[i].col,
parser_data);
parser->parse_error(MUSTACHE_ERR_SECTIONOPENERHERE,
mustache_err_messages[MUSTACHE_ERR_SECTIONOPENERHERE],
(unsigned)opener->line, (unsigned)opener->col,
parser_data);
n_errors++;
}
if(opener->type == MUSTACHE_TAGTYPE_OPENSECTIONINV)
tags[i].type = MUSTACHE_TAGTYPE_CLOSESECTIONINV;
}
break;
default:
break;
}
}
if(!mustache_stack_is_empty(§ion_stack)) {
while(!mustache_stack_is_empty(§ion_stack)) {
opener = (MUSTACHE_TAGINFO*) mustache_stack_pop(§ion_stack);
parser->parse_error(MUSTACHE_ERR_DANGLINGSECTIONOPENER,
mustache_err_messages[MUSTACHE_ERR_DANGLINGSECTIONOPENER],
(unsigned)opener->line, (unsigned)opener->col,
parser_data);
n_errors++;
}
}
if(n_errors == 0)
ret = 0;
err:
mustache_stack_free(§ion_stack);
return ret;
}
static int
mustache_parse_delimiters(const char* delim_spec, size_t size,
char* opener, size_t* p_opener_len,
char* closer, size_t* p_closer_len)
{
off_t opener_beg, opener_end;
off_t closer_beg, closer_end;
opener_beg = 0;
opener_end = opener_beg;
while(opener_end < size) {
if(MUSTACHE_ISWHITESPACE(delim_spec[opener_end]))
break;
if(delim_spec[opener_end] == '=')
return -1;
opener_end++;
}
if(opener_end <= opener_beg || opener_end - opener_beg > MUSTACHE_MAXOPENERLENGTH)
return -1;
closer_beg = opener_end;
while(closer_beg < size) {
if(!MUSTACHE_ISWHITESPACE(delim_spec[closer_beg]))
break;
closer_beg++;
}
if(closer_beg <= opener_end)
return -1;
closer_end = closer_beg;
while(closer_end < size) {
if(MUSTACHE_ISWHITESPACE(delim_spec[closer_end]))
return -1;
closer_end++;
}
if(closer_end <= closer_beg || closer_end - closer_beg > MUSTACHE_MAXCLOSERLENGTH)
return -1;
if(closer_end != size)
return -1;
memcpy(opener, delim_spec + opener_beg, opener_end - opener_beg);
*p_opener_len = opener_end - opener_beg;
memcpy(closer, delim_spec + closer_beg, closer_end - closer_beg);
*p_closer_len = closer_end - closer_beg;
return 0;
}
static int
mustache_parse(const char* templ_data, size_t templ_size,
const MUSTACHE_PARSER* parser, void* parser_data,
MUSTACHE_TAGINFO** p_tags, unsigned* p_n_tags)
{
int n_errors = 0;
char opener[MUSTACHE_MAXOPENERLENGTH] = MUSTACHE_DEFAULTOPENER;
char closer[MUSTACHE_MAXCLOSERLENGTH] = MUSTACHE_DEFAULTCLOSER;
size_t opener_len;
size_t closer_len;
off_t off = 0;
off_t line = 1;
off_t col = 1;
MUSTACHE_TAGINFO current_tag;
MUSTACHE_BUFFER tags = { 0 };
/* If this template will ever be used as a partial, it may inherit an
* extra indentation from parent template, so we mark every line beginning
* with the dummy tag for further processing in mustache_compile(). */
if(off < templ_size) {
current_tag.type = MUSTACHE_TAGTYPE_INDENT;
current_tag.beg = off;
current_tag.end = off;
if(mustache_buffer_append(&tags, ¤t_tag, sizeof(MUSTACHE_TAGINFO)) != 0)
goto err;
}
current_tag.type = MUSTACHE_TAGTYPE_NONE;
opener_len = strlen(MUSTACHE_DEFAULTOPENER);
closer_len = strlen(MUSTACHE_DEFAULTCLOSER);
while(off < templ_size) {
int is_opener, is_closer;
is_opener = (off + opener_len <= templ_size && memcmp(templ_data+off, opener, opener_len) == 0);
is_closer = (off + closer_len <= templ_size && memcmp(templ_data+off, closer, closer_len) == 0);
if(is_opener && is_closer) {
/* Opener and closer may be defined to be the same string.
* Consider for example "{{=@ @=}}".
* Determine the real meaning from current parser state:
*/
if(current_tag.type == MUSTACHE_TAGTYPE_NONE)
is_closer = 0;
else
is_opener = 0;
}
if(is_opener) {
/* Handle tag opener "{{" */
if(current_tag.type != MUSTACHE_TAGTYPE_NONE && current_tag.type != MUSTACHE_TAGTYPE_COMMENT) {
/* Opener after some previous opener??? */
parser->parse_error(MUSTACHE_ERR_DANGLINGTAGOPENER,
mustache_err_messages[MUSTACHE_ERR_DANGLINGTAGOPENER],
(unsigned)current_tag.line, (unsigned)current_tag.col,
parser_data);
n_errors++;
current_tag.type = MUSTACHE_TAGTYPE_NONE;
}
current_tag.line = line;
current_tag.col = col;
current_tag.beg = off;
off += opener_len;
if(off < templ_size) {
switch(templ_data[off]) {
case '=': current_tag.type = MUSTACHE_TAGTYPE_DELIM; off++; break;
case '!': current_tag.type = MUSTACHE_TAGTYPE_COMMENT; off++; break;
case '{': current_tag.type = MUSTACHE_TAGTYPE_VERBATIMVAR; off++; break;
case '&': current_tag.type = MUSTACHE_TAGTYPE_VERBATIMVAR2; off++; break;
case '#': current_tag.type = MUSTACHE_TAGTYPE_OPENSECTION; off++; break;
case '^': current_tag.type = MUSTACHE_TAGTYPE_OPENSECTIONINV; off++; break;
case '/': current_tag.type = MUSTACHE_TAGTYPE_CLOSESECTION; off++; break;
case '>': current_tag.type = MUSTACHE_TAGTYPE_PARTIAL; off++; break;
default: current_tag.type = MUSTACHE_TAGTYPE_VAR; break;
}
}
while(off < templ_size && MUSTACHE_ISWHITESPACE(templ_data[off]))
off++;
current_tag.name_beg = off;
col += current_tag.name_beg - current_tag.beg;
} else if(is_closer && current_tag.type == MUSTACHE_TAGTYPE_NONE) {
/* Invalid closer. */
parser->parse_error(MUSTACHE_ERR_DANGLINGTAGCLOSER,
mustache_err_messages[MUSTACHE_ERR_DANGLINGTAGCLOSER],
(unsigned) line, (unsigned) col, parser_data);
n_errors++;
off++;
col++;
} else if(is_closer) {
/* Handle tag closer "}}" */
current_tag.name_end = off;
off += closer_len;
col += closer_len;
if(current_tag.type == MUSTACHE_TAGTYPE_VERBATIMVAR) {
/* Eat the extra '}'. Note it may be after the found
* closer (if closer is "}}" or before it for a custom
* closer. */
if(current_tag.name_end > current_tag.name_beg &&
templ_data[current_tag.name_end-1] == '}') {
current_tag.name_end--;
} else if(mustache_is_std_closer(closer, closer_len) &&
off < templ_size && templ_data[off] == '}') {
off++;
col++;
} else {
parser->parse_error(MUSTACHE_ERR_INCOMPATIBLETAGCLOSER,
mustache_err_messages[MUSTACHE_ERR_INCOMPATIBLETAGCLOSER],
(unsigned) line, (unsigned) col, parser_data);
n_errors++;
}
} else if(current_tag.type == MUSTACHE_TAGTYPE_DELIM) {
/* Maybe we are not really the closer. Maybe the directive
* does not change the closer so we are the "new closer" in
* something like "{{=<something> }}=}}". */
if(templ_data[current_tag.name_end - 1] != '=' &&
off + closer_len < templ_size &&
templ_data[off] == '=' &&
memcmp(templ_data + off + 1, closer, closer_len) == 0)
{
current_tag.name_end += closer_len + 1;
off += closer_len + 1;
col += closer_len + 1;
}
if(templ_data[current_tag.name_end - 1] != '=') {
parser->parse_error(MUSTACHE_ERR_INCOMPATIBLETAGCLOSER,
mustache_err_messages[MUSTACHE_ERR_INCOMPATIBLETAGCLOSER],
(unsigned) line, (unsigned) col, parser_data);
n_errors++;
} else if(current_tag.name_end > current_tag.name_beg) {
current_tag.name_end--; /* Consume the closer's '=' */
}
}
current_tag.end = off;
/* If the tag is standalone, expand it to consume also any
* preceding whitespace and also one new-line (before or after). */
if(current_tag.type != MUSTACHE_TAGTYPE_VAR &&
current_tag.type != MUSTACHE_TAGTYPE_VERBATIMVAR &&
current_tag.type != MUSTACHE_TAGTYPE_VERBATIMVAR2 &&
(current_tag.end >= templ_size || MUSTACHE_ISNEWLINE(templ_data[current_tag.end])))
{
off_t tmp_off = current_tag.beg;
while(tmp_off > 0 && MUSTACHE_ISWHITESPACE(templ_data[tmp_off-1]))
tmp_off--;
if(tmp_off == 0 || MUSTACHE_ISNEWLINE(templ_data[tmp_off-1])) {
current_tag.beg = tmp_off;
if(current_tag.end < templ_size && templ_data[current_tag.end] == '\r')
current_tag.end++;
if(current_tag.end < templ_size && templ_data[current_tag.end] == '\n')
current_tag.end++;
}
}
while(current_tag.name_end > current_tag.name_beg &&
MUSTACHE_ISWHITESPACE(templ_data[current_tag.name_end-1]))
current_tag.name_end--;
if(current_tag.type != MUSTACHE_TAGTYPE_COMMENT) {
if(current_tag.name_end <= current_tag.name_beg) {
parser->parse_error(MUSTACHE_ERR_NOTAGNAME,
mustache_err_messages[MUSTACHE_ERR_NOTAGNAME],
(unsigned)current_tag.line, (unsigned)current_tag.col,
parser_data);
n_errors++;
}
}
if(current_tag.type == MUSTACHE_TAGTYPE_DELIM) {
if(mustache_parse_delimiters(templ_data + current_tag.name_beg,
current_tag.name_end - current_tag.name_beg,
opener, &opener_len, closer, &closer_len) != 0)
{
parser->parse_error(MUSTACHE_ERR_INVALIDDELIMITERS,
mustache_err_messages[MUSTACHE_ERR_INVALIDDELIMITERS],
(unsigned)current_tag.line, (unsigned)current_tag.col,
parser_data);
n_errors++;
}
/* From now on, ignore this tag. */
current_tag.type = MUSTACHE_TAGTYPE_COMMENT;
}
if(current_tag.type != MUSTACHE_TAGTYPE_COMMENT) {
if(mustache_validate_tagname(templ_data + current_tag.name_beg,
current_tag.name_end - current_tag.name_beg) != 0) {
parser->parse_error(MUSTACHE_ERR_INVALIDTAGNAME,
mustache_err_messages[MUSTACHE_ERR_INVALIDTAGNAME],
(unsigned)current_tag.line, (unsigned)current_tag.col,
parser_data);
n_errors++;
}
}
/* Remember the tag info. */
if(mustache_buffer_append(&tags, ¤t_tag, sizeof(MUSTACHE_TAGINFO)) != 0)
goto err;
current_tag.type = MUSTACHE_TAGTYPE_NONE;
} else if(MUSTACHE_ISNEWLINE(templ_data[off])) {
/* Handle end of line. */
if(current_tag.type != MUSTACHE_TAGTYPE_NONE && current_tag.type != MUSTACHE_TAGTYPE_COMMENT) {
parser->parse_error(MUSTACHE_ERR_DANGLINGTAGOPENER,
mustache_err_messages[MUSTACHE_ERR_DANGLINGTAGOPENER],
(unsigned)current_tag.line, (unsigned)current_tag.col,
parser_data);
n_errors++;
current_tag.type = MUSTACHE_TAGTYPE_NONE;
}
/* New line may be formed by digraph "\r\n". */
if(templ_data[off] == '\r')
off++;
if(off < templ_size && templ_data[off] == '\n')
off++;
if(current_tag.type == MUSTACHE_TAGTYPE_NONE && off < templ_size) {
current_tag.type = MUSTACHE_TAGTYPE_INDENT;
current_tag.beg = off;
current_tag.end = off;
if(mustache_buffer_append(&tags, ¤t_tag, sizeof(MUSTACHE_TAGINFO)) != 0)
goto err;
current_tag.type = MUSTACHE_TAGTYPE_NONE;
}
line++;
col = 1;
} else {
/* Handle any other character. */
off++;
col++;
}
}
if(mustache_validate_sections(templ_data, &tags, parser, parser_data) != 0)
goto err;
/* Add an extra dummy tag marking end of the template. */
current_tag.type = MUSTACHE_TAGTYPE_NONE;
current_tag.beg = templ_size;
current_tag.end = templ_size;
if(mustache_buffer_append(&tags, ¤t_tag, sizeof(MUSTACHE_TAGINFO)) != 0)
goto err;
/* Success? */
if(n_errors == 0) {
*p_tags = (MUSTACHE_TAGINFO*) tags.data;
*p_n_tags = tags.n / sizeof(MUSTACHE_TAGINFO);
return 0;
}
/* Error path. */
err:
mustache_buffer_free(&tags);
*p_tags = NULL;
*p_n_tags = 0;
return -1;
}
/* The compiled template is a sequence of following instruction types.
* The instructions have two types of arguments:
* -- NUM: a number encoded with mustache_buffer_[append|insert]_num().
* -- STR: a string (always preceded with a NUM denoting its length).
*/
/* Instruction denoting end of template.
*/
#define MUSTACHE_OP_EXIT 0
/* Instruction for outputting a literal text.
*
* Arg #1: Length of the literal string (NUM).
* Arg #2: The literal string (STR).
*/
#define MUSTACHE_OP_LITERAL 1
/* Instruction to resolve a tag name.
*
* Arg #1: (Relative) setjmp value (NUM).
* Arg #2: Count of names (NUM).
* Arg #3: Length of the 1st tag name (NUM).
* Arg #4: The tag name (STR).
* etc. (more names follow, up to the count in arg #2)
*
* Registers: reg_node is set to the resolved node, or NULL.
* reg_jmpaddr is set to address where some next instruction may
* want to jump on some condition.
*/
#define MUSTACHE_OP_RESOLVE_setjmp 2
/* Instruction to resolve a tag name.
*
* Arg #1: Count of names (NUM).
* Arg #2: Length of the tag name (NUM).
* Arg #3: The tag name (STR).
* etc. (more names follow, up to the count in arg #1)
*
* Registers: reg_node is set to the resolved node, or NULL.
*/
#define MUSTACHE_OP_RESOLVE 3
/* Instructions to output a node.
*
* Registers: If it is not NULL, reg_node determines the node to output.
* Otherwise, it is noop.
*/
#define MUSTACHE_OP_OUTVERBATIM 4
#define MUSTACHE_OP_OUTESCAPED 5
/* Instruction to enter a node in register reg_node, i.e. to change a lookup
* context for resolve instructions.
*
* Registers: If it is not NULL, reg_node is pushed to the stack.
* Otherwise, program counter is changed to address in reg_jmpaddr.
*/
#define MUSTACHE_OP_ENTER 6
/* Instruction to leave a node. The top node in the lookup context stack is
* popped out.
*
* Arg #1: (Relative) setjmp value (NUM) for jumping back for next loop iteration.
*/
#define MUSTACHE_OP_LEAVE 7
/* Instruction to open inverted section.
* Note there is no MUSTACHE_OP_LEAVEINV instruction as it is noop.
*
* Registers: If reg_node is NULL, continues normally.
* Otherwise, program counter is changed to address in reg_jmpaddr.
*/
#define MUSTACHE_OP_ENTERINV 8
/* Instruction to enter a partial.
*
* Arg #1: Length of the partial name (NUM).
* Arg #2: The partial name (STR).
* Arg #3: Length of the indentation string (NUM).
* Arg #4: Indentation, i.e. string composed of whitespace characters (STR).
*/
#define MUSTACHE_OP_PARTIAL 9
/* Instruction to insert extra indentation (inherited from parent templates).
*/
#define MUSTACHE_OP_INDENT 10
static int
mustache_compile_tagname(MUSTACHE_BUFFER* insns, const char* name, size_t size)
{
unsigned n_tokens = 1;
unsigned i;
off_t tok_beg, tok_end;
if(size == 1 && name[0] == '.') {
/* Implicit iterator. */
n_tokens = 0;
} else {
for(i = 0; i < size; i++) {
if(name[i] == '.')
n_tokens++;
}
}
if(mustache_buffer_append_num(insns, n_tokens) != 0)
return -1;
tok_beg = 0;
for(i = 0; i < n_tokens; i++) {
tok_end = tok_beg;
while(tok_end < size && name[tok_end] != '.')
tok_end++;
if(mustache_buffer_append_num(insns, tok_end - tok_beg) != 0)
return -1;
if(mustache_buffer_append(insns, name + tok_beg, tok_end - tok_beg) != 0)
return -1;
tok_beg = tok_end + 1;
}
return 0;
}
MUSTACHE_TEMPLATE*
mustache_compile(const char* templ_data, size_t templ_size,
const MUSTACHE_PARSER* parser, void* parser_data,
unsigned flags)
{
static const MUSTACHE_PARSER default_parser = { mustache_parse_error };
MUSTACHE_TAGINFO* tags = NULL;
unsigned n_tags;
off_t off;
off_t jmp_pos;
MUSTACHE_TAGINFO* tag;
MUSTACHE_BUFFER insns = { 0 };
MUSTACHE_STACK jmp_pos_stack = { 0 };
int done = 0;
int success = 0;
size_t indent_len;
if(parser == NULL)
parser = &default_parser;
/* Collect all tags from the template. */
if(mustache_parse(templ_data, templ_size, parser, parser_data, &tags, &n_tags) != 0)
goto err;
/* Build the template */
#define APPEND(data, n) \
do { \
if(mustache_buffer_append(&insns, (data), (n)) != 0) \
goto err; \
} while(0)
#define APPEND_NUM(num) \
do { \
if(mustache_buffer_append_num(&insns, (uint64_t)(num)) != 0) \
goto err; \
} while(0)
#define APPEND_TAGNAME(tag) \
do { \
if(mustache_compile_tagname(&insns, templ_data + (tag)->name_beg, \
(tag)->name_end - (tag)->name_beg) != 0) \
goto err; \
} while(0)
#define INSERT_NUM(pos, num) \
do { \
if(mustache_buffer_insert_num(&insns, (pos), (uint64_t)(num)) != 0) \
goto err; \
} while(0)
#define PUSH_JMP_POS() \
do { \
if(mustache_stack_push(&jmp_pos_stack, insns.n) != 0) \
goto err; \
} while(0)
#define POP_JMP_POS() ((off_t) mustache_stack_pop(&jmp_pos_stack))
off = 0;
tag = &tags[0];
while(1) {
if(off < tag->beg) {
/* Handle literal text before the next tag. */
APPEND_NUM(MUSTACHE_OP_LITERAL);
APPEND_NUM(tag->beg - off);
APPEND(templ_data + off, tag->beg - off);
off = tag->beg;
}
switch(tag->type) {
case MUSTACHE_TAGTYPE_VAR:
case MUSTACHE_TAGTYPE_VERBATIMVAR:
case MUSTACHE_TAGTYPE_VERBATIMVAR2:
APPEND_NUM(MUSTACHE_OP_RESOLVE);
APPEND_TAGNAME(tag);
APPEND_NUM((tag->type == MUSTACHE_TAGTYPE_VAR) ?
MUSTACHE_OP_OUTESCAPED : MUSTACHE_OP_OUTVERBATIM);
break;
case MUSTACHE_TAGTYPE_OPENSECTION:
APPEND_NUM(MUSTACHE_OP_RESOLVE_setjmp);
PUSH_JMP_POS();
APPEND_TAGNAME(tag);
APPEND_NUM(MUSTACHE_OP_ENTER);
PUSH_JMP_POS();
break;
case MUSTACHE_TAGTYPE_CLOSESECTION:
APPEND_NUM(MUSTACHE_OP_LEAVE);
APPEND_NUM(insns.n - POP_JMP_POS());
jmp_pos = POP_JMP_POS();
INSERT_NUM(jmp_pos, insns.n - jmp_pos);
break;
case MUSTACHE_TAGTYPE_OPENSECTIONINV:
APPEND_NUM(MUSTACHE_OP_RESOLVE_setjmp);
PUSH_JMP_POS();
APPEND_TAGNAME(tag);
APPEND_NUM(MUSTACHE_OP_ENTERINV);
break;
case MUSTACHE_TAGTYPE_CLOSESECTIONINV:
jmp_pos = POP_JMP_POS();
INSERT_NUM(jmp_pos, insns.n - jmp_pos);
break;
case MUSTACHE_TAGTYPE_PARTIAL:
APPEND_NUM(MUSTACHE_OP_PARTIAL);
APPEND_NUM(tag->name_end - tag->name_beg);
APPEND(templ_data + tag->name_beg, tag->name_end - tag->name_beg);
indent_len = 0;
while(MUSTACHE_ISWHITESPACE(templ_data[tag->beg + indent_len]))
indent_len++;
APPEND_NUM(indent_len);
APPEND(templ_data + tag->beg, indent_len);
break;
case MUSTACHE_TAGTYPE_INDENT:
APPEND_NUM(MUSTACHE_OP_INDENT);
break;
case MUSTACHE_TAGTYPE_NONE:
APPEND_NUM(MUSTACHE_OP_EXIT);
done = 1;
break;
default:
break;
}
if(done)
break;
off = tag->end;
tag++;
}
success = 1;
err:
free(tags);
mustache_buffer_free(&jmp_pos_stack);
if(success) {
return (MUSTACHE_TEMPLATE*) insns.data;
} else {
mustache_buffer_free(&insns);
return NULL;
}
}
void
mustache_release(MUSTACHE_TEMPLATE* t)
{
if(t == NULL)
return;
free(t);
}
/**********************************
*** Applying Compiled Template ***
**********************************/
int
mustache_process(const MUSTACHE_TEMPLATE* t,
const MUSTACHE_RENDERER* renderer, void* renderer_data,
const MUSTACHE_DATAPROVIDER* provider, void* provider_data)
{
const uint8_t* insns = (const uint8_t*) t;
off_t reg_pc = 0; /* Program counter register. */
off_t reg_jmpaddr; /* Jump target address register. */
void* reg_node = NULL; /* Working node register. */
int done = 0;
MUSTACHE_STACK node_stack = { 0 };
MUSTACHE_STACK index_stack = { 0 };
MUSTACHE_STACK partial_stack = { 0 };
MUSTACHE_BUFFER indent_buffer = { 0 };
int ret = -1;
#define PUSH_NODE() \
do { \
if(mustache_stack_push(&node_stack, (uintptr_t) reg_node) != 0) \
goto err; \
} while(0)
#define POP_NODE() ((void*) mustache_stack_pop(&node_stack))
#define PEEK_NODE() ((void*) mustache_stack_peek(&node_stack))
#define PUSH_INDEX(index) \
do { \
if(mustache_stack_push(&index_stack, (uintptr_t) (index)) != 0) \
goto err; \
} while(0)
#define POP_INDEX() ((unsigned) mustache_stack_pop(&index_stack))
reg_node = provider->get_root(provider_data);
PUSH_NODE();
while(!done) {
unsigned opcode = (unsigned) mustache_decode_num(insns, reg_pc, ®_pc);
switch(opcode) {
case MUSTACHE_OP_LITERAL:
{
size_t n = (size_t) mustache_decode_num(insns, reg_pc, ®_pc);
if(renderer->out_verbatim((const char*)(insns + reg_pc), n, renderer_data) != 0)
goto err;
reg_pc += n;
break;
}
case MUSTACHE_OP_RESOLVE_setjmp:
{
size_t jmp_len = (size_t) mustache_decode_num(insns, reg_pc, ®_pc);
reg_jmpaddr = reg_pc + jmp_len;
/* Pass through */
}
case MUSTACHE_OP_RESOLVE:
{
unsigned n_names = (unsigned) mustache_decode_num(insns, reg_pc, ®_pc);
unsigned i;
if(n_names == 0) {
/* Implicit iterator. */
reg_node = PEEK_NODE();
break;
}
for(i = 0; i < n_names; i++) {
size_t name_len = (size_t) mustache_decode_num(insns, reg_pc, ®_pc);
const char* name = (const char*)(insns + reg_pc);
reg_pc += name_len;
if(i == 0) {
void** nodes = (void**) node_stack.data;
size_t n_nodes = node_stack.n / sizeof(void*);
while(n_nodes-- > 0) {
reg_node = provider->get_child_by_name(nodes[n_nodes],
name, name_len, provider_data);
if(reg_node != NULL)
break;
}
} else if(reg_node != NULL) {
reg_node = provider->get_child_by_name(reg_node,
name, name_len, provider_data);
}
}
break;
}
case MUSTACHE_OP_OUTVERBATIM:
case MUSTACHE_OP_OUTESCAPED:
if(reg_node != NULL) {
int (*out)(const char*, size_t, void*);
out = (opcode == MUSTACHE_OP_OUTVERBATIM) ?
renderer->out_verbatim : renderer->out_escaped;
if(provider->dump(reg_node, out, renderer_data, provider_data) != 0)
goto err;
}
break;
case MUSTACHE_OP_ENTER:
if(reg_node != NULL) {
PUSH_NODE();
reg_node = provider->get_child_by_index(reg_node, 0, provider_data);
if(reg_node != NULL) {
PUSH_NODE();
PUSH_INDEX(0);
} else {
(void) POP_NODE();
}
}
if(reg_node == NULL)
reg_pc = reg_jmpaddr;
break;
case MUSTACHE_OP_LEAVE:
{
off_t jmp_base = reg_pc;
size_t jmp_len = (size_t) mustache_decode_num(insns, reg_pc, ®_pc);
unsigned index = POP_INDEX();
(void) POP_NODE();
reg_node = provider->get_child_by_index(PEEK_NODE(), ++index, provider_data);
if(reg_node != NULL) {
PUSH_NODE();
PUSH_INDEX(index);
reg_pc = jmp_base - jmp_len;
} else {
(void) POP_NODE();
}
break;
}
case MUSTACHE_OP_ENTERINV:
if(reg_node == NULL || provider->get_child_by_index(reg_node,
0, provider_data) == NULL) {
/* Resolve failed: Noop, continue normally. */
} else {
reg_pc = reg_jmpaddr;
}
break;
case MUSTACHE_OP_PARTIAL:
{
size_t name_len;
const char* name;
size_t indent_len;
const char* indent;
MUSTACHE_TEMPLATE* partial;
name_len = mustache_decode_num(insns, reg_pc, ®_pc);
name = (const char*) (insns + reg_pc);
reg_pc += name_len;
indent_len = mustache_decode_num(insns, reg_pc, ®_pc);
indent = (const char*) (insns + reg_pc);
reg_pc += indent_len;
partial = provider->get_partial(name, name_len, provider_data);
if(partial != NULL) {
if(mustache_stack_push(&partial_stack, (uintptr_t) insns) != 0)
goto err;
if(mustache_stack_push(&partial_stack, (uintptr_t) reg_pc) != 0)
goto err;
if(mustache_stack_push(&partial_stack, (uintptr_t) indent_len) != 0)
goto err;
if(mustache_buffer_append(&indent_buffer, indent, indent_len) != 0)
goto err;
reg_pc = 0;
insns = (uint8_t*) partial;
}
break;
}
case MUSTACHE_OP_INDENT:
if(renderer->out_verbatim((const char*)(indent_buffer.data),
indent_buffer.n, renderer_data) != 0)
goto err;
break;
case MUSTACHE_OP_EXIT:
if(mustache_stack_is_empty(&partial_stack)) {
done = 1;
} else {
size_t indent_len = (size_t) mustache_stack_pop(&partial_stack);
reg_pc = (off_t) mustache_stack_pop(&partial_stack);
insns = (uint8_t*) mustache_stack_pop(&partial_stack);
indent_buffer.n -= indent_len;
}
break;
}
}
/* Success. */
ret = 0;
err:
mustache_stack_free(&node_stack);
mustache_stack_free(&index_stack);
mustache_stack_free(&partial_stack);
mustache_buffer_free(&indent_buffer);
return ret;
}
| 34.452196 | 117 | 0.543989 |
23c2358bed21d9ae39e5855e7d633e1ce48c71ed | 2,188 | c | C | src/libbu/tests/vls_incr.c | earl-ducaine/brlcad-mirror | 402bd3542a10618d1f749b264cadf9b0bd723546 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 1 | 2019-10-23T16:17:49.000Z | 2019-10-23T16:17:49.000Z | src/libbu/tests/vls_incr.c | pombredanne/sf.net-brlcad | fb56f37c201b51241e8f3aa7b979436856f43b8c | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/libbu/tests/vls_incr.c | pombredanne/sf.net-brlcad | fb56f37c201b51241e8f3aa7b979436856f43b8c | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* V L S _ I N C R . C
* BRL-CAD
*
* Copyright (c) 2015-2019 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This 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 file; see the file named COPYING for more
* information.
*/
#include "common.h"
#include <limits.h>
#include <stdlib.h> /* for strtol */
#include <ctype.h>
#include <errno.h> /* for errno */
#include "bu.h"
#include "bn.h"
#include "string.h"
int
main(int argc, char *argv[])
{
int ret = 1;
int i = 0;
struct bu_vls name = BU_VLS_INIT_ZERO;
long inc_count = 0;
char *endptr;
const char *rs = NULL;
const char *rs_complex = "([-_:]*[0-9]+[-_:]*)[^0-9]*$";
const char *formatting = NULL;
/* Sanity check */
if (argc < 6)
bu_exit(1, "Usage: %s {name} {num} {formatting} {incr_count} {expected}\n", argv[0]);
if (BU_STR_EQUAL(argv[2], "1")) {
rs = rs_complex;
}
if (!rs && !BU_STR_EQUAL(argv[2], "0") && !BU_STR_EQUAL(argv[2], "NULL")) {
rs = argv[2];
}
if (!BU_STR_EQUAL(argv[3], "NULL")) {
formatting = argv[3];
}
errno = 0;
inc_count = strtol(argv[4], &endptr, 10);
if (errno == ERANGE || inc_count <= 0) {
bu_exit(1, "invalid increment count: %s\n", argv[4]);
}
bu_vls_sprintf(&name, "%s", argv[1]);
while (i < inc_count) {
(void)bu_vls_incr(&name, rs, formatting, NULL, NULL);
i++;
}
if (BU_STR_EQUAL(bu_vls_addr(&name), argv[5])) ret = 0;
bu_log("output: %s\n", bu_vls_addr(&name));
return ret;
}
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
| 25.149425 | 86 | 0.622943 |
140f6b178abbcb31b7e0a72156e8627314642372 | 407 | h | C | include/SpringBoard/SBDismissForEmptySwitcherSwitcherModifierAction.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 3 | 2020-06-20T02:53:25.000Z | 2020-11-07T08:39:13.000Z | include/SpringBoard/SBDismissForEmptySwitcherSwitcherModifierAction.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | null | null | null | include/SpringBoard/SBDismissForEmptySwitcherSwitcherModifierAction.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 1 | 2020-07-26T02:16:06.000Z | 2020-07-26T02:16:06.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 22 2020 01:47:48).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <SpringBoard/SBGroupSwitcherModifierAction.h>
@interface SBDismissForEmptySwitcherSwitcherModifierAction : SBGroupSwitcherModifierAction
{
}
- (long long)type;
- (id)initWithDismissalDelay:(double)arg1 validator:(id /* CDUnknownBlockType */)arg2;
@end
| 22.611111 | 90 | 0.749386 |
bb1b195ca0cb1700ca7783d775b8ab93b3cc0a4c | 416 | h | C | CGXHotBrandViewOC/Slider/CGXHotBrandSliderFlowLayout.h | 974794055/CGXHotBrandView-OC | e987285dc897db377961301bb34d0ab6a916dfb5 | [
"MIT"
] | 2 | 2021-02-23T05:07:41.000Z | 2021-09-24T01:49:11.000Z | CGXHotBrandViewOC/Slider/CGXHotBrandSliderFlowLayout.h | 974794055/CGXHotBrandView-OC | e987285dc897db377961301bb34d0ab6a916dfb5 | [
"MIT"
] | null | null | null | CGXHotBrandViewOC/Slider/CGXHotBrandSliderFlowLayout.h | 974794055/CGXHotBrandView-OC | e987285dc897db377961301bb34d0ab6a916dfb5 | [
"MIT"
] | null | null | null | //
// CGXHotBrandSliderFlowLayout.h
// CGXHotBrandView-OC
//
// Created by CGX on 2020/12/12.
// Copyright © 2020 CGX. All rights reserved.
//
#import "CGXHotBrandBaseFlowLayout.h"
NS_ASSUME_NONNULL_BEGIN
@interface CGXHotBrandSliderFlowLayout : CGXHotBrandBaseFlowLayout
@property (nonatomic,assign) NSInteger visibleItemsCount;
@property (nonatomic,assign) CGFloat minScale;
@end
NS_ASSUME_NONNULL_END
| 18.086957 | 66 | 0.786058 |
bb20ef5cce5df99a7be34b913aeec8cf20937884 | 1,850 | h | C | firmware/libs/i2c_slave/include/i2c_slave_lib.h | vives-projectweek-2022/Lannooleaf | f4990c128124e9e42c6c3f1072c05b8e57a03a3a | [
"Apache-2.0"
] | null | null | null | firmware/libs/i2c_slave/include/i2c_slave_lib.h | vives-projectweek-2022/Lannooleaf | f4990c128124e9e42c6c3f1072c05b8e57a03a3a | [
"Apache-2.0"
] | 5 | 2022-03-29T09:37:03.000Z | 2022-03-31T06:27:10.000Z | firmware/libs/i2c_slave/include/i2c_slave_lib.h | vives-projectweek-2022/Lannooleaf | f4990c128124e9e42c6c3f1072c05b8e57a03a3a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Valentin Milea <valentin.milea@gmail.com>
*
* SPDX-License-Identifier: MIT
*/
#ifndef _I2C_SLAVE_H_
#define _I2C_SLAVE_H_
#include <hardware/i2c.h>
#ifdef __cplusplus
extern "C" {
#endif
/** \file i2c_slave.h
*
* \brief I2C slave setup.
*/
/**
* \brief I2C slave event types.
*/
typedef enum i2c_slave_event_t
{
I2C_SLAVE_RECEIVE, /**< Data from master is available for reading. Slave must read from Rx FIFO. */
I2C_SLAVE_REQUEST, /**< Master is requesting data. Slave must write into Tx FIFO. */
I2C_SLAVE_FINISH, /**< Master has sent a Stop or Restart signal. Slave may prepare for the next transfer. */
I2C_GEN_CALL
} i2c_slave_event_t;
/**
* \brief I2C slave event handler
*
* The event handler will run from the I2C ISR, so it should return quickly (under 25 us at 400 kb/s).
* Avoid blocking inside the handler and split large data transfers across multiple calls for best results.
* When sending data to master, up to `i2c_get_write_available()` bytes can be written without blocking.
* When receiving data from master, up to `i2c_get_read_available()` bytes can be read without blocking.
*
* \param i2c Slave I2C instance.
* \param event Event type.
*/
typedef void (*i2c_slave_handler_t)(i2c_inst_t *i2c, i2c_slave_event_t event);
/**
* \brief Configure I2C instance for slave mode.
*
* \param i2c I2C instance.
* \param address 7-bit slave address.
* \param handler Called on events from I2C master. It will run from the I2C ISR, on the CPU core
* where the slave was initialized.
*/
void i2c_slave_init(i2c_inst_t *i2c, uint8_t address, i2c_slave_handler_t handler);
/**
* \brief Restore I2C instance to master mode.
*
* \param i2c I2C instance.
*/
void i2c_slave_deinit(i2c_inst_t *i2c);
#ifdef __cplusplus
}
#endif
#endif // _I2C_SLAVE_H_
| 27.61194 | 112 | 0.718919 |
49ccfecb30d06299a92466a2d6fd9a6a63d69a96 | 1,810 | h | C | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/transition/CSceneHelper.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/transition/CSceneHelper.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/transition/CSceneHelper.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#ifndef __ELASTOS_DROID_TRANSITION_CSCENEHELPER_H__
#define __ELASTOS_DROID_TRANSITION_CSCENEHELPER_H__
#include "_Elastos_Droid_Transition_CSceneHelper.h"
#include <elastos/core/Singleton.h>
using Elastos::Droid::View::IView;
using Elastos::Droid::View::IViewGroup;
using Elastos::Droid::Content::IContext;
using Elastos::Core::Singleton;
namespace Elastos {
namespace Droid {
namespace Transition {
CarClass (CSceneHelper)
, public Singleton
, public ISceneHelper
{
public:
CAR_SINGLETON_DECL()
CAR_INTERFACE_DECL()
CARAPI GetSceneForLayout(
/* [in] */ IViewGroup* sceneRoot,
/* [in] */ Int32 layoutId,
/* [in] */ IContext* context,
/* [out] */ IScene** result);
CARAPI SetCurrentScene(
/* [in] */ IView* vw,
/* [in] */ IScene* scene);
CARAPI GetCurrentScene(
/* [in] */ IView* view,
/* [out] */ IScene** result);
};
} // namespace Transition
} // namespace Droid
} // namespace Elastos
#endif //__ELASTOS_DROID_TRANSITION_CSCENEHELPER_H__ | 29.672131 | 75 | 0.643646 |
17d6be522a067a645d8de57a486b9b818dcbcdff | 1,519 | h | C | orte/mca/ras/gridengine/ras_gridengine.h | abouteiller/ulfm-legacy | 720dfbd7d522b67b8ff0b3e1321676a1870c7fc8 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2015-12-16T08:16:23.000Z | 2015-12-16T08:16:23.000Z | orte/mca/ras/gridengine/ras_gridengine.h | abouteiller/ulfm-legacy | 720dfbd7d522b67b8ff0b3e1321676a1870c7fc8 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orte/mca/ras/gridengine/ras_gridengine.h | abouteiller/ulfm-legacy | 720dfbd7d522b67b8ff0b3e1321676a1870c7fc8 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-10-16T09:18:38.000Z | 2019-10-16T09:18:38.000Z | /*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2006 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
/**
* @file
* Resource allocation for Grid Engine
*/
#ifndef ORTE_RAS_GRIDENGINE_H
#define ORTE_RAS_GRIDENGINE_H
#include "orte_config.h"
#include "orte/mca/ras/ras.h"
#include "orte/mca/ras/base/base.h"
BEGIN_C_DECLS
/**
* RAS Component
*/
struct orte_ras_gridengine_component_t {
orte_ras_base_component_t super;
int debug;
int verbose;
int priority;
int show_jobid;
};
typedef struct orte_ras_gridengine_component_t orte_ras_gridengine_component_t;
ORTE_DECLSPEC extern orte_ras_gridengine_component_t mca_ras_gridengine_component;
ORTE_DECLSPEC extern orte_ras_base_module_t orte_ras_gridengine_module;
END_C_DECLS
#endif
| 28.660377 | 82 | 0.679394 |
8d4e3c609bd0217d44876974750dc1f921f27767 | 1,867 | h | C | include/mysql-8.0/my_icp.h | realnickel/mysql-connector-odbc | cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189 | [
"Artistic-1.0-Perl"
] | null | null | null | include/mysql-8.0/my_icp.h | realnickel/mysql-connector-odbc | cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189 | [
"Artistic-1.0-Perl"
] | null | null | null | include/mysql-8.0/my_icp.h | realnickel/mysql-connector-odbc | cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189 | [
"Artistic-1.0-Perl"
] | null | null | null | /* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#ifndef _my_icp_h
#define _my_icp_h
/**
@file include/my_icp.h
*/
/**
Values returned by index_cond_func_xxx functions.
*/
typedef enum icp_result {
/** Index tuple doesn't satisfy the pushed index condition (the engine
should discard the tuple and go to the next one) */
ICP_NO_MATCH,
/** Index tuple satisfies the pushed index condition (the engine should
fetch and return the record) */
ICP_MATCH,
/** Index tuple is out of the range that we're scanning, e.g. if we're
scanning "t.key BETWEEN 10 AND 20" and got a "t.key=21" tuple (the engine
should stop scanning and return HA_ERR_END_OF_FILE right away). */
ICP_OUT_OF_RANGE
} ICP_RESULT;
#endif /* _my_icp_h */
| 36.607843 | 79 | 0.74933 |
e4a68c738f2d706020913930ec3c6f4f92bd5dd5 | 1,147 | c | C | Daily_Projects/d07v00/ex00/ft_strdup.c | jnawrock42/42_the_final_backup | 221623a2a329533bf38f141d806255e9a762531a | [
"MIT"
] | null | null | null | Daily_Projects/d07v00/ex00/ft_strdup.c | jnawrock42/42_the_final_backup | 221623a2a329533bf38f141d806255e9a762531a | [
"MIT"
] | null | null | null | Daily_Projects/d07v00/ex00/ft_strdup.c | jnawrock42/42_the_final_backup | 221623a2a329533bf38f141d806255e9a762531a | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strdup.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jnawrock <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/31 00:03:46 by jnawrock #+# #+# */
/* Updated: 2019/10/31 00:03:49 by jnawrock ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
char *ft_strdup(char *src)
{
int i;
char *res;
i = 0;
while (src[i] != '\0')
i++;
res = (char *)malloc(sizeof(*src) * (i + 1));
i = 0;
while (src[i] != '\0')
{
res[i] = src[i];
i++;
}
res[i] = '\0';
return (res);
}
| 34.757576 | 80 | 0.183958 |
48d887bb51fcc684811ac473067164ebc45102ce | 5,394 | h | C | src/tune.h | bmerry/clogs | b5e751e83478634e5c066b8dbfc83e1f23a743e1 | [
"MIT"
] | 10 | 2018-05-07T20:53:24.000Z | 2021-09-12T13:04:51.000Z | src/tune.h | bmerry/clogs | b5e751e83478634e5c066b8dbfc83e1f23a743e1 | [
"MIT"
] | 1 | 2018-05-09T19:05:28.000Z | 2018-05-09T20:39:47.000Z | src/tune.h | bmerry/clogs | b5e751e83478634e5c066b8dbfc83e1f23a743e1 | [
"MIT"
] | 1 | 2019-11-08T05:33:14.000Z | 2019-11-08T05:33:14.000Z | /* Copyright (c) 2012-2014 University of Cape Town
* Copyright (c) 2014, 2018 Bruce Merry
*
* 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.
*/
/**
* @file
*
* Utilities for autotuning
*/
#ifndef TUNE_H
#define TUNE_H
#include <clogs/visibility_push.h>
#include <string>
#include <vector>
#include <ostream>
#include <boost/any.hpp>
#include <functional>
#include <clogs/visibility_pop.h>
#include <clogs/tune.h>
#include "cache_types.h"
namespace cl
{
class Context;
class Device;
} // namespace cl
namespace clogs
{
namespace detail
{
/**
* Create a key with fields uniquely describing @a device.
*/
CLOGS_LOCAL DeviceKey deviceKey(const cl::Device &device);
class CLOGS_LOCAL TunePolicy
{
private:
bool enabled;
TuneVerbosity verbosity;
std::ostream *out;
public:
/**
* Constructor. The default state is that tuning is permitted, verbosity level
* is normal, and output is sent to @c std::cout.
*/
TunePolicy();
/// Allow or deny on-the-fly tuning
void setEnabled(bool enabled) { this->enabled = enabled; }
/// Set how verbose output is
void setVerbosity(TuneVerbosity verbosity) { this->verbosity = verbosity; }
/**
* Set the output stream. A pointer is held, so the stream must exist until the
* policy is destroyed.
*/
void setOutput(std::ostream &out) { this->out = &out; }
/// Returns whether tuning is permitted
bool isEnabled() const { return enabled; }
/**
* Checks that tuning is permitted, throwing an exception if not.
*
* @throw clogs::CacheError if tuning is not enabled
*/
void assertEnabled() const;
/**
* @name Methods called by the tuning algorithms to report progress
* @{
*/
/// Called at the beginning of tuning one algorithm instance
void logStartAlgorithm(const std::string &description, const cl::Device &device) const;
/// Called at the end of tuning one algorithm instance
void logEndAlgorithm() const;
/// Called at the beginning of a related set of tuning tests
void logStartGroup() const;
/// Called at the end of a related set of tuning tests
void logEndGroup() const;
/// Called at the start of a single tuning test
void logStartTest() const;
/**
* Called at the end of a single tuning test.
* @param success Whether the test succeeded i.e. did not throw an exception
* @param rate Rate at which operations occurred (arbitrary scale)
*/
void logEndTest(bool success, double rate) const;
/**
* @}
*/
};
/**
* Perform low-level tuning. The callback function is called for each set of parameters,
* and returns two values, A and B. The selected parameter set is computed as follows:
*
* -# The largest value of A, Amax is computed.
* -# The first parameter set with B >= Amax is returned.
*
* To simply pick the
* best, return B = A. However, if earlier parameter sets are in some
* way intrinsicly better, then setting e.g. B = 1.05 * A will yield a
* parameter set that has A ~= Amax but possibly much earlier. It is required
* that A <= B.
*
* @a problemSizes contains values to pass to the callback. A separate phase is
* run for each value in sequence. In the first phase, all parameter sets are
* used. In each subsequent phase, only those whose A value was at least
* ratio*Amax are retained. This allows for very slow parameter sets to be
* quickly eliminated on small problem sizes (which can also avoid hardware
* timeouts), before refining the selection on more representative problem sizes.
*
* It is legal for the callback function to throw @c cl::Error or @ref
* InternalError. In either case, the parameter set will be dropped from
* consideration.
*
* Each call will be made with a fresh context. It is advisable for the
* callback function to execute a warmup pass to obtain reliable results.
*/
boost::any tuneOne(
const TunePolicy &policy,
const cl::Device &device,
const std::vector<boost::any> ¶meterSets,
const std::vector<std::size_t> &problemSizes,
std::function<
std::pair<double, double>(
const cl::Context &,
const cl::Device &,
std::size_t,
const boost::any &)> callback,
double ratio = 0.5);
} // namespace detail
} // namespace clogs
#endif /* TUNE_H */
| 32.890244 | 91 | 0.695773 |
127a9750005bd285acbd09c73c7258c4b52e3a3e | 3,893 | c | C | E2Manager/3rdparty/asn1codec/e2ap_engine/TraceActivation.c | cachengo/ric-plt-e2mgr | e3de46b8ef25583731f1c998d9d396d82ffcc860 | [
"Apache-2.0",
"CC-BY-4.0"
] | 2 | 2020-07-02T02:01:29.000Z | 2021-12-07T14:38:51.000Z | E2Manager/3rdparty/asn1codec/e2ap_engine/TraceActivation.c | cachengo/ric-plt-e2mgr | e3de46b8ef25583731f1c998d9d396d82ffcc860 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | E2Manager/3rdparty/asn1codec/e2ap_engine/TraceActivation.c | cachengo/ric-plt-e2mgr | e3de46b8ef25583731f1c998d9d396d82ffcc860 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2021-03-01T18:55:38.000Z | 2021-03-01T18:55:38.000Z | /*
* Copyright 2019 AT&T Intellectual Property
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This source code is part of the near-RT RIC (RAN Intelligent Controller)
* platform project (RICP).
*/
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "X2AP-IEs"
* found in "../../asnFiles/X2AP-IEs.asn"
* `asn1c -fcompound-names -fincludes-quoted -fno-include-deps -findirect-choice -gen-PER -no-gen-OER -D.`
*/
#include "TraceActivation.h"
#include "ProtocolExtensionContainer.h"
asn_TYPE_member_t asn_MBR_TraceActivation_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct TraceActivation, eUTRANTraceID),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_EUTRANTraceID,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"eUTRANTraceID"
},
{ ATF_NOFLAGS, 0, offsetof(struct TraceActivation, interfacesToTrace),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_InterfacesToTrace,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"interfacesToTrace"
},
{ ATF_NOFLAGS, 0, offsetof(struct TraceActivation, traceDepth),
(ASN_TAG_CLASS_CONTEXT | (2 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_TraceDepth,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"traceDepth"
},
{ ATF_NOFLAGS, 0, offsetof(struct TraceActivation, traceCollectionEntityIPAddress),
(ASN_TAG_CLASS_CONTEXT | (3 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_TraceCollectionEntityIPAddress,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"traceCollectionEntityIPAddress"
},
{ ATF_POINTER, 1, offsetof(struct TraceActivation, iE_Extensions),
(ASN_TAG_CLASS_CONTEXT | (4 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_ProtocolExtensionContainer_170P207,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"iE-Extensions"
},
};
static const int asn_MAP_TraceActivation_oms_1[] = { 4 };
static const ber_tlv_tag_t asn_DEF_TraceActivation_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_TraceActivation_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* eUTRANTraceID */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* interfacesToTrace */
{ (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* traceDepth */
{ (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 }, /* traceCollectionEntityIPAddress */
{ (ASN_TAG_CLASS_CONTEXT | (4 << 2)), 4, 0, 0 } /* iE-Extensions */
};
asn_SEQUENCE_specifics_t asn_SPC_TraceActivation_specs_1 = {
sizeof(struct TraceActivation),
offsetof(struct TraceActivation, _asn_ctx),
asn_MAP_TraceActivation_tag2el_1,
5, /* Count of tags in the map */
asn_MAP_TraceActivation_oms_1, /* Optional members */
1, 0, /* Root/Additions */
5, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_TraceActivation = {
"TraceActivation",
"TraceActivation",
&asn_OP_SEQUENCE,
asn_DEF_TraceActivation_tags_1,
sizeof(asn_DEF_TraceActivation_tags_1)
/sizeof(asn_DEF_TraceActivation_tags_1[0]), /* 1 */
asn_DEF_TraceActivation_tags_1, /* Same as above */
sizeof(asn_DEF_TraceActivation_tags_1)
/sizeof(asn_DEF_TraceActivation_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_TraceActivation_1,
5, /* Elements count */
&asn_SPC_TraceActivation_specs_1 /* Additional specs */
};
| 33.273504 | 107 | 0.697919 |
16396c4eb4a3d43676cd51084109f551c3fea955 | 478 | h | C | iOS/PlayAppStore/WorkFlow/SafeCategory/NSNumber/NSNumber+Safe.h | playappstore/PlayAppStore | b25f602d50f41fee428587eb0e8fc61562b91b67 | [
"MIT"
] | 24 | 2017-03-08T12:46:26.000Z | 2020-09-07T15:48:36.000Z | iOS/PlayAppStore/WorkFlow/SafeCategory/NSNumber/NSNumber+Safe.h | playappstore/PlayAppStore | b25f602d50f41fee428587eb0e8fc61562b91b67 | [
"MIT"
] | 2 | 2017-04-05T09:29:19.000Z | 2018-11-03T12:42:45.000Z | iOS/PlayAppStore/WorkFlow/SafeCategory/NSNumber/NSNumber+Safe.h | playappstore/PlayAppStore | b25f602d50f41fee428587eb0e8fc61562b91b67 | [
"MIT"
] | 11 | 2017-02-17T09:31:39.000Z | 2021-02-20T06:21:44.000Z | //
// NSNumber+Safe.h
// PlayAppStore
//
// Created by Winn on 2017/2/19.
// Copyright © 2017年 Winn. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSNumber (Safe)
/**
对象的safe判断 如果为NSNumber直接返回 double值时进行转换 NSNull时断言
@param obj 传入对象
@return NSNumber
*/
+ (NSNumber *)safeNumberFromObject:(id)obj;
/**
对象的safe判断 如果为NSNumber直接返回 double值时进行转换
@param obj 传入对象
@return NSNumber
*/
+ (NSNumber *)safeDoubleNumberFromObject:(id)obj;
@end
| 14.9375 | 49 | 0.707113 |
3f0d8cc124ea609cf72eda700b9d572e1fa09df5 | 1,480 | h | C | include/SPStackedNav/SPSideTabBar.h | axellundback/SPStackedNav | 5fbad66ef33b57ac8bc866fe90a489d7efcf870b | [
"Apache-2.0"
] | 138 | 2015-01-10T22:26:46.000Z | 2021-11-18T20:18:37.000Z | include/SPStackedNav/SPSideTabBar.h | sdarlington/SPStackedNav | 9d5398a6484b794f1646a8cb4c3aeb4322d4d094 | [
"Apache-2.0"
] | 11 | 2018-03-19T21:02:15.000Z | 2018-03-28T12:34:45.000Z | include/SPStackedNav/SPSideTabBar.h | nevyn/SPStackedNav | c5bbf6168cea94ae9dd745a3effe6168ac197cad | [
"Apache-2.0"
] | 21 | 2015-08-25T17:39:48.000Z | 2022-03-19T10:37:34.000Z | // Copyright 2014 Spotify
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <UIKit/UIKit.h>
@protocol SPSideTabBarDelegate;
@interface SPSideTabBar : UIView
- (id)initWithFrame:(CGRect)r;
@property(nonatomic,assign) id<SPSideTabBarDelegate> delegate; // weak reference. default is nil
@property(nonatomic,copy) NSArray *items; // get/set visible UITabBarItems. default is nil. changes not animated. shown in order
@property(nonatomic,retain) UITabBarItem *selectedItem;
@property(nonatomic,copy) NSArray *additionalItems; // shown starting from the bottom, not associated with a view controller
- (void)select:(BOOL)selected additionalItem:(UITabBarItem*)item;
- (CGRect)rectForItem:(UITabBarItem*)item;
@end
@protocol SPSideTabBarDelegate<NSObject>
@optional
- (void)tabBar:(SPSideTabBar *)tabBar didSelectItem:(UITabBarItem *)item; // called when a new view is selected by the user (but not programatically)
@end
| 44.848485 | 149 | 0.747973 |
8b8e714c3204a6d1abb968919bf88f930881851f | 910 | h | C | System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI.GameCenterDataUpdatePresenter.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 5 | 2021-04-29T04:31:43.000Z | 2021-08-19T18:59:58.000Z | System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI.GameCenterDataUpdatePresenter.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI.GameCenterDataUpdatePresenter.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 1 | 2022-03-19T11:16:23.000Z | 2022-03-19T11:16:23.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 28, 2021 at 9:08:01 PM Mountain Standard Time
* Operating System: Version 14.5 (Build 18L204)
* Image Source: /System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <libobjc.A.dylib/GKDaemonProxyDataUpdateDelegate.h>
@interface GameCenterUI.GameCenterDataUpdatePresenter : NSObject <GKDaemonProxyDataUpdateDelegate> {
onGameCenterDataUpdate;
}
-(id)init;
-(void)dealloc;
-(void)friendRequestSelected:(id)arg1 ;
-(void)setBadgeCount:(long long)arg1 forType:(unsigned long long)arg2 ;
-(void)refreshContentsForDataType:(unsigned)arg1 userInfo:(id)arg2 ;
@end
| 39.565217 | 130 | 0.669231 |
e9694e1ecc0fa1e004e6e1054e2f204ae3ead838 | 768 | h | C | ZYPlayer/ZYPlayerView/ZYPlayerScrollViewManager.h | YanIsMe/ZYPlayer | 104857189ee3a25f025cee6e291e721e56e4ffe5 | [
"MIT"
] | 3 | 2019-04-08T15:38:28.000Z | 2021-06-15T01:25:32.000Z | ZYPlayer/ZYPlayerView/ZYPlayerScrollViewManager.h | YanIsMe/ZYPlayer | 104857189ee3a25f025cee6e291e721e56e4ffe5 | [
"MIT"
] | null | null | null | ZYPlayer/ZYPlayerView/ZYPlayerScrollViewManager.h | YanIsMe/ZYPlayer | 104857189ee3a25f025cee6e291e721e56e4ffe5 | [
"MIT"
] | null | null | null | //
// HFPlayerScrollViewManager.h
// Leaflet
//
// Created by ZhaoYan on 2018/12/18.
// Copyright © 2018 Starunion. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface ZYPlayerScrollViewManager : NSObject
@property (nonatomic, weak) UIScrollView *scrollView;
@property (nonatomic, copy) NSIndexPath *playingIndexPath;
@property (nonatomic, assign) NSInteger containerViewTag;
@property (nonatomic, assign) BOOL fullScreen;
@property (nonatomic, copy) void(^cellDisappearingInScrollView)(NSIndexPath *indexPath);
@property (nonatomic, copy) void(^scrollViewWillReload)(NSIndexPath *indexPath);
@property (nonatomic, copy) void(^scrollViewDidReload)(NSIndexPath *indexPath);
- (UIView *)getContainerViewFromCell;
@end
| 28.444444 | 88 | 0.77474 |
eb31a3df89419efb491a6fbf7549e52435e4ba5f | 8,424 | h | C | modules/transforms/lib/PiiHoughTransform.h | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | 14 | 2015-01-19T22:14:18.000Z | 2020-04-13T23:27:20.000Z | modules/transforms/lib/PiiHoughTransform.h | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | null | null | null | modules/transforms/lib/PiiHoughTransform.h | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | 14 | 2015-01-16T05:43:15.000Z | 2019-01-29T07:57:11.000Z | /* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#ifndef _PIIHOUGHTRANSFORM_H
#define _PIIHOUGHTRANSFORM_H
#include "PiiTransformsGlobal.h"
#include <PiiMatrix.h>
#include <PiiMathDefs.h>
#include <PiiFunctional.h>
#include <PiiSharedD.h>
/**
* Linear Hough transform. The linear Hough transform is used in
* detecting lines in images. Lines are paramerized by their slope and
* distance to the origin, resulting in a two-dimensional
* transformation domain. In the transformation domain, columns
* represent slopes and rows distances to the origin. The origin of
* the domain is at the center of the image. The quantization of the
* transformation domain is user-specifiable.
*
* The number of rows in the result will always be odd. The row at the
* middle always represents lines that intersect the origin (i.e.
* distance zero). If `distanceResolution` is 1.0 (the default),
* moving up or down from the middle row increases distance to the
* origin by one pixel. The first column represents lines with a zero
* slope. If `angleResolution` is 1.0 (the default), the next column
* represents lines with a 1 degree slope and so on. Zero angle points
* downwards, and the angle grows clockwise. This peculiar choice was
* made to make it easy to calculate the resulting lines in image
* coordinates (x is columns and y is rows, positive y axis
* downwards).
*
* Formally, the detected lines are parametrized with the following
* equation:
*
* \[
* d = x\cos \theta + y\sin \theta
* \]
*
* where \(\theta\) stands for the angle, and d is the "distance"
* from origin (d can be negative). If you pick a value from the
* transform domain, its row and column coordinates tell the values
* of d and \(\theta\), respectively. Once these are known, it
* is straightforward to solve x with respect to y or vice versa.
*
* Note that the transform adds the value of a transformed pixel to
* the transformation domain (a.k.a. the accumulator). If the input
* image is binary, each pixel will have an equal effect. Higher
* values can be used in giving higher significance to certain
* pixels.
*
* @param angleResolution the number of degrees each column
* represents. The default value is 1.0 which produces 180 columns
* in the result matrix.
*
* @param distanceResolution the distance (in pixels) each row
* represents.
*
* @param angleStart the start angle of the transformation domain.
* The default value is zero, which places zero angle to the
* leftmost column. This value can be negative.
*
* @param angleEnd the end angle of the transformation domain. This
* value with `angleStart` can be used to limit the line search to
* a certain range of angles. Note that the last angle will not be
* present in the transformation. That is, if `angleEnd` is 180
* (the default) and `angleResolution` is 1, the last angle will be
* 179.
*
* @param distanceStart the smallest (signed) distance to the origin
* considered in the transformation. If the distance is smaller than
* the minimum possible distance, the theoretical minimum will be
* used.
*
* @param distanceEnd the largest (signed) distance to the origin
* considered in the transformation. If the distance is larger than
* the maximum possible distance, the theoretical maximum will be
* used.
*
*
* ~~~(c++)
* PiiMatrix<int> img; // fill somehow...
* // Make the Hough transform. The result will be a PiiMatrix<int>,
* // and each pixel with a value higher than or equal to three will
* // be transformed. The angles will be quantized to 90 discrete
* // levels (2 degrees each)
*
* double distanceResolution = 1.0;
* double angleResolution = 2.0;
* PiiMatrix<int> result =
* PiiHoughTransform(distanceResolution,
* angleResolution).transform(img,
* std::bind2nd(std::greater<int>(), 3));
* ~~~
*/
class PII_TRANSFORMS_EXPORT PiiHoughTransform
{
public:
PiiHoughTransform();
PiiHoughTransform(double angleResolution,
double distanceResolution,
int startAngle = 0,
int endAngle = 180,
int startDistance = Pii::Numeric<int>::minValue(),
int endDistance = Pii::Numeric<int>::maxValue());
PiiHoughTransform(const PiiHoughTransform& other);
~PiiHoughTransform();
PiiHoughTransform& operator= (const PiiHoughTransform& other);
void setAngleResolution(double angleResolution);
double angleResolution() const;
void setDistanceResolution(double distanceResolution);
double distanceResolution() const;
void setStartAngle(int startAngle);
int startAngle() const;
void setEndAngle(int endAngle);
int endAngle() const;
void setStartDistance(int startDistance);
int startDistance() const;
void setEndDistance(int endDistance);
int endDistance() const;
/**
* Returns the distance from the center of the input image, given
* the index of a *row* in the transformation result.
*/
double distance(int row) const;
/**
* Returns the angle (degrees) corresponding to the given *column*
* in the transformation result.
*/
double angle(int column) const;
/**
* Returns the points at which the line represented by the given
* point in the accumulator hits the input image's borders.
*
* @param d the distance of the line to the transform's origin
*
* @param theta the angle of the line, in degrees.
*
* @return a 1-by-4 matrix storing the start and end points of a
* line segment (x1, y1, x2, y2). The returned value is suitable for
* use with PiiImageAnnotator's `property` input.
*
* ~~~(c++)
* // Transform an image
* PiiHoughTransform hough;
* PiiMatrix<int> matTransformed(hough.transform(img));
* // Find 10 highest peaks in the transformation domain
* PiiHeap<PiiMatrixValue<int> > maxima = Pii::findMaxima(matTransformed, 10);
* PiiMatrix<int> matPoints(0,4);
* for (int i=0; i<maxima.size(); ++i)
* matPoints.insertRow(hough.lineEnds(maxima[i].row, maxima[i].column));
* ~~~
*
* @see Pii::findMaxima()
*/
PiiMatrix<int> lineEnds(int row, int column) const;
/**
* @param img the input image. The image will be scanned, and each
* pixel that makes `rule` evaluate `true` will be added to
* the parameter space. Typically, the input image is binary.
*
* @param rule the is unary function which is used to determine if a
* pixel may be part of a line. The function takes the pixel value
* as a parameter and returns a `bool`.
*
* @return the accumulator array. The size of the returned matrix
* depends on angle and distance limits and their resolution.
*/
template <class T, class Matrix, class UnaryOp>
PiiMatrix<T> transform(const Matrix& img, UnaryOp rule);
template <class T, class Matrix>
PiiMatrix<T> transform(const Matrix& img)
{
return transform<T>(img, Pii::Identity<typename Matrix::value_type>());
}
protected:
/// @internal
class Data : public PiiSharedD<Data>
{
public:
Data();
Data(double angleResolution,
double distanceResolution,
int startAngle,
int endAngle,
int startDistance,
int endDistance);
Data(const Data& other);
~Data();
double dAngleResolution;
double dDistanceResolution;
int iStartAngle;
int iEndAngle;
int iStartDistance;
int iEndDistance;
int iRows, iColumns;
double dMaxDistance;
double *pSinTable, *pCosTable;
int iPreviousAngles, iPreviousStartAngle;
double dPreviousAngleResolution;
} *d;
PII_SHARED_D_FUNC;
private:
void setSize(int rows, int columns);
void initSinCosTables(int angles);
const double* sinTable() const;
const double* cosTable() const;
};
#include "PiiHoughTransform-templates.h"
#endif //_PIIHOUGHTRANSFORM_H
| 34.809917 | 88 | 0.705247 |
b1736f2a0a8c996ad52b1504024f739b3e9409ce | 3,348 | h | C | klib/include/klib/kterminal.h | po4y/solunar2 | b5412565ecfb4bb0113d391df229ae1fa48a6092 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 15 | 2020-06-28T22:51:01.000Z | 2022-01-28T10:12:32.000Z | klib/include/klib/kterminal.h | po4y/solunar2 | b5412565ecfb4bb0113d391df229ae1fa48a6092 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 4 | 2020-06-30T20:39:24.000Z | 2021-11-03T16:21:59.000Z | klib/include/klib/kterminal.h | kevinboone/qcd | 0e32b67da70fbed4180f0b28a26737acf4287e00 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 4 | 2020-06-28T22:54:44.000Z | 2021-09-23T14:50:15.000Z | /*============================================================================
klib
kterminal.h
Definition of the KTerminal class
Copyright (c)1990-2020 Kevin Boone. Distributed under the terms of the
GNU Public Licence, v3.0
==========================================================================*/
#pragma once
#include <klib/defs.h>
#include <klib/types.h>
#include <klib/kstring.h>
// Key codes for cursor movement, etc
#define VK_BACK 8
#define VK_TAB 9
#define VK_ENTER 10
// Note that Linux console/terminal usually sends DEL when
// backspace is pressed
#define VK_DEL 127
#define VK_DOWN 1000
#define VK_UP 1001
#define VK_LEFT 1002
#define VK_RIGHT 1003
#define VK_PGUP 1004
#define VK_PGDN 1005
#define VK_HOME 1006
#define VK_END 10067
//Terminal attributes
#define KTATTR_REVERSE 0x0001
#define KTATTR_ITALIC 0x0002
#define KTATTR_BOLD 0x0004
#define KTATTR_RESET 0x8000
#define KTATTR_OFF 0
#define KTATTR_ON 1
struct _KTerminal;
typedef void (*KTerminalDestroyFn) (struct _KTerminal *self);
typedef BOOL (*KTerminalInitFn) (struct _KTerminal *self, KString **error);
typedef BOOL (*KTerminalGetSizeFn) (const struct _KTerminal *self, int *rows,
int *cols, KString **error);
typedef void (*KTerminalSetRawModeFn) (struct _KTerminal *self, BOOL raw);
typedef int (*KTerminalReadKeyFn) (const struct _KTerminal *self);
typedef void (*KTerminalClearFn) (struct _KTerminal *self);
typedef void (*KTerminalSetCursorFn) (const struct _KTerminal *self,
int row, int col);
typedef void (*KTerminalWriteAtFn) (const struct _KTerminal *self, int row,
int col, const KString *text, BOOL truncate);
typedef void (*KTerminalSetAttrFn) (const struct _KTerminal *self, int attrs, BOOL on);
typedef void (*KTerminalEraseLineFn) (struct _KTerminal *self, int line);
typedef struct _KTerminal
{
KTerminalInitFn init;
KTerminalInitFn deinit;
KTerminalDestroyFn destroy;
KTerminalGetSizeFn get_size;
KTerminalSetRawModeFn set_raw_mode;
KTerminalReadKeyFn read_key;
KTerminalClearFn clear;
KTerminalWriteAtFn write_at;
KTerminalSetCursorFn set_cursor;
KTerminalSetAttrFn set_attr;
KTerminalEraseLineFn erase_line;
} KTerminal;
BEGIN_DECLS
extern void kterminal_destroy (KTerminal *self);
extern BOOL kterminal_deinit (KTerminal *self, KString **error);
extern void kterminal_clear (KTerminal *self);
extern BOOL kterminal_get_size (const KTerminal *self, int *rows,
int *cols, KString **error);
// Line is zero-based
extern void kterminal_erase_line (KTerminal *self, int line);
extern BOOL kterminal_init (KTerminal *self, KString **error);
extern int kterminal_read_key (const KTerminal *self);
extern void kterminal_set_attributes (const KTerminal *self, int attrs, BOOL on);
extern void kterminal_set_cursor (const KTerminal *self, int row,
int col);
extern void kterminal_set_raw_mode (KTerminal *self, BOOL raw);
extern void kterminal_write_at (const KTerminal *self, int row,
int col, const KString *text, BOOL truncate);
extern void kterminal_write_at_utf8 (const KTerminal *self, int row,
int col, const UTF8 *text, BOOL truncate);
END_DECLS
| 31 | 87 | 0.69086 |
169927ec4b2ec1a8039499b82668ef1a0e715719 | 31,451 | c | C | ODIN_II/SRC/activity_estimation.c | joseppinilla/VTR7_Analytical | 530138b5c9b85f324b7dfb42387d6ef3279e772e | [
"Unlicense"
] | 31 | 2016-02-15T02:57:28.000Z | 2021-06-02T10:40:25.000Z | ODIN_II/SRC/activity_estimation.c | joseppinilla/VTR7_Analytical | 530138b5c9b85f324b7dfb42387d6ef3279e772e | [
"Unlicense"
] | null | null | null | ODIN_II/SRC/activity_estimation.c | joseppinilla/VTR7_Analytical | 530138b5c9b85f324b7dfb42387d6ef3279e772e | [
"Unlicense"
] | 6 | 2017-02-08T21:51:51.000Z | 2021-06-02T10:40:40.000Z | /*
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#include "globals.h"
#include "errors.h"
#include "netlist_utils.h"
#include "odin_util.h"
#include "ast_util.h"
#include "util.h"
#include "activity_estimation.h"
#include "netlist_check.h"
#define DEFAULT_STATIC_PROBABILITY .5
#define DEFAULT_TRANSITION_DENSITY .5
#define ACT_NUM_ITER 3
#define activation_t struct activation_t_t
activation_t
{
double *static_probability;
double *transition_probability;
double *transition_density;
};
void initialize_probabilities(char *input_file, netlist_t *netlist);
void calc_transition_density(netlist_t *netlist);
void calc_probabilities_and_init_act_data(netlist_t *netlist);
short *boolean_difference(nnode_t *node, int variable_spot);
double calc_density(nnode_t *node, int variable_spot, short *boolean_difference);
void output_activation_file_ace_and_function_file(char *output_filename, int lut_size, netlist_t *LUT_netlist, netlist_t *CLUSTER_netlist);
void cleanup_activation(netlist_t *netlist);
/*---------------------------------------------------------------------------------------------
* (function: activity_estimation)
*-------------------------------------------------------------------------------------------*/
void activity_estimation(char *input_filename, char *output_filename, int lut_size, netlist_t *LUT_netlist, netlist_t *CLUSTER_netlist)
{
/* levelize the graph. Note, can't levelize the ClUSTER_netlist since there are loops */
levelize_and_check_for_combinational_loop_and_liveness(FALSE, LUT_netlist);
/* initializes the data structures and the PI */
initialize_probabilities(input_filename, LUT_netlist);
/* Calculate the probabilities for each of the nodes in the LUT_netlist */
calc_probabilities_and_init_act_data(LUT_netlist);
/* calculate the transition density for each node */
calc_transition_density(LUT_netlist);
/* Output file with the transition densities */
output_activation_file_ace_and_function_file(output_filename, lut_size, LUT_netlist, CLUSTER_netlist);
/* cleanup the data structures so we can use node_data in another algorithm */
cleanup_activation(LUT_netlist);
/* Path is where we are */
// graphVizOutputNetlist(configuration.debug_output_path, "blif", 1, blif_gnd_node, blif_vcc_node, blif_input_nodes, num_blif_input_nodes);
}
/*---------------------------------------------------------------------------------------------
* (function: calc_transition_density)
*-------------------------------------------------------------------------------------------*/
void calc_transition_density(netlist_t *netlist)
{
int i, j, m;
activation_t *act_data;
/* progress from the primary inputs (in the forward level 0) to each stage */
for (i = 0; i < netlist->num_forward_levels; i++)
{
for (j = 0; j < netlist->num_at_forward_level[i]; j++)
{
/* initialize the activation data */
nnode_t *current_node = netlist->forward_levels[i][j];
act_data = (activation_t*)current_node->node_data;
/* All other levels we pass through the probabilities and calculate Transition prbability for the DEnsity calculation */
if (current_node->type == BLIF_FUNCTION)
{
/* only one output */
act_data->transition_density = (double*)malloc(sizeof(double)); // only one output
if (current_node->num_input_pins == 1)
{
/* If this is a Constant, NOT or a BUFFER then the transition density is easy to calculate */
nnode_t *input_node = current_node->input_pins[0]->net->driver_pin->node;
int input_node_pin = current_node->input_pins[0]->net->driver_pin->pin_node_idx;
activation_t *input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
if ((current_node->associated_function[0] == 0) && (current_node->associated_function[1] == 0))
/* CONSTANT 0 */
act_data->transition_density[0] = 0;
if ((current_node->associated_function[0] == 0) && (current_node->associated_function[1] == 1))
/* BUFFER */
act_data->transition_density[0] = input_data->transition_density[input_node_pin];
if ((current_node->associated_function[0] == 1) && (current_node->associated_function[1] == 0))
/* NOT */
act_data->transition_density[0] = input_data->transition_density[input_node_pin];
if ((current_node->associated_function[0] == 1) && (current_node->associated_function[1] == 1))
/* CONSTANT 1 */
act_data->transition_density[0] = 0;
}
else
{
double density_val = 0.0;
/* calculate the transition densities sumof(D(y)*P(boolean_diff, y) */
for (m = 0; m < current_node->num_input_pins; m++)
{
short *boolean_difference_function;
/* calculate hte boolean difference */
boolean_difference_function = boolean_difference(current_node, m);
/* now calculate the denisty of this input ... sum of */
density_val = density_val + calc_density(current_node, m, boolean_difference_function);
/* free the array */
free(boolean_difference_function);
}
act_data->transition_density[0] = density_val;
}
}
else if (current_node->type == FF_NODE)
{
nnode_t *input_node = current_node->input_pins[0]->net->driver_pin->node;
int input_node_pin = current_node->input_pins[0]->net->driver_pin->pin_node_idx;
activation_t *input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
/* just store since allocated in the initialization */
act_data->transition_density = (double*)malloc(sizeof(double));
act_data->transition_density[0] = 2 * (input_data->static_probability[input_node_pin] * (1-input_data->static_probability[input_node_pin]));
}
else if (current_node->type == OUTPUT_NODE)
{
nnode_t *input_node = current_node->input_pins[0]->net->driver_pin->node;
int input_node_pin = current_node->input_pins[0]->net->driver_pin->pin_node_idx;
activation_t *input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
/* allocate and stre through */
act_data->transition_density = (double*)malloc(sizeof(double));
act_data->transition_density[0] = input_data->static_probability[input_node_pin];
}
else if ((current_node->type == INPUT_NODE) || (current_node->type == VCC_NODE) || (current_node->type == GND_NODE))
{
oassert(current_node->unique_node_data_id == ACTIVATION);
}
else
{
oassert(FALSE);
}
}
}
}
/*---------------------------------------------------------------------------------------------
* (function: initialize_probabilities)
*-------------------------------------------------------------------------------------------*/
void initialize_probabilities(char *input_file, netlist_t *netlist)
{
int i, j;
activation_t *act_data;
for (i = 0; i < netlist->num_forward_levels; i++)
{
for (j = 0; j < netlist->num_at_forward_level[i]; j++)
{
/* initialize the activation data */
nnode_t *current_node = netlist->forward_levels[i][j];
oassert(current_node->unique_node_data_id == RESET);
current_node->unique_node_data_id = ACTIVATION;
act_data = (activation_t*)malloc(sizeof(activation_t));
current_node->node_data = (void*)act_data;
if (current_node->type == INPUT_NODE)
{
oassert(i == 0);
/* IF - PI and FFs, then we set their probability */
if (input_file != NULL)
{
/* READ input probabilities */
oassert(FALSE);
/* READ in the input file */
/* exit since all read */
i = netlist->num_forward_levels;
}
else
{
/* initialize all the initial probabilities */
act_data->static_probability = (double*)malloc(sizeof(double));
act_data->transition_probability = (double*)malloc(sizeof(double));
act_data->transition_density = (double*)malloc(sizeof(double));
act_data->static_probability[0] = DEFAULT_STATIC_PROBABILITY;
act_data->transition_probability[0] = -1;
act_data->transition_density[0] = DEFAULT_TRANSITION_DENSITY;
}
}
else if (current_node->type == GND_NODE)
{
/* initialize all the initial probabilities */
act_data->static_probability = (double*)malloc(sizeof(double));
act_data->transition_probability = (double*)malloc(sizeof(double));
act_data->transition_density = (double*)malloc(sizeof(double));
act_data->static_probability[0] = 0.0;
act_data->transition_probability[0] = -1;
act_data->transition_density[0] = 0;
}
else if (current_node->type == VCC_NODE)
{
/* initialize all the initial probabilities */
act_data->static_probability = (double*)malloc(sizeof(double));
act_data->transition_probability = (double*)malloc(sizeof(double));
act_data->transition_density = (double*)malloc(sizeof(double));
act_data->static_probability[0] = 1.0;
act_data->transition_probability[0] = -1;
act_data->transition_density[0] = 0;
}
else if (current_node->type == FF_NODE)
{
/* initialize all the initial probabilities */
act_data->static_probability = (double*)malloc(sizeof(double));
act_data->transition_probability = (double*)malloc(sizeof(double));
act_data->transition_density = (double*)malloc(sizeof(double));
act_data->static_probability[0] = DEFAULT_STATIC_PROBABILITY;
act_data->transition_probability[0] = -1;
act_data->transition_density[0] = -1;
}
}
}
}
/*---------------------------------------------------------------------------------------------
* (function: calc_probabilities_and_init_act_data)
* Calculates the static probability for each output pin P(y)
* Calculates the transition probabiliy for each output pin Pt(y) = 2*P(y)*(1-P(y))
*-------------------------------------------------------------------------------------------*/
void calc_probabilities_and_init_act_data(netlist_t *netlist)
{
int i, j, k, l, rep;
activation_t *act_data;
for (rep = 0; rep < ACT_NUM_ITER; rep++)
{
/* progress from the primary inputs (in the forward level 0) to each stage */
for (i = 0; i < netlist->num_forward_levels; i++)
{
for (j = 0; j < netlist->num_at_forward_level[i]; j++)
{
/* initialize the activation data */
nnode_t *current_node = netlist->forward_levels[i][j];
act_data = (activation_t*)current_node->node_data;
/* All other levels we pass through the probabilities and calculate Transition prbability for the DEnsity calculation */
if (current_node->type == BLIF_FUNCTION)
{
double totalProb = 0;
int function_size = pow2(current_node->num_input_pins);
if (rep == 0)
{
/* only one output */
act_data->static_probability = (double*)malloc(sizeof(double));
}
for (k = 0; k < function_size; k++)
{
long long int place = 1;
double probVal = 1;
if (current_node->associated_function[k] == 1)
{
/* IF - this function value is on then calculate the probability */
for (l = 0; l < current_node->num_input_pins; l++)
{
nnode_t *input_node = current_node->input_pins[l]->net->driver_pin->node;
int input_node_pin = current_node->input_pins[l]->net->driver_pin->pin_node_idx;
activation_t *input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
if ((k & place) > 0) // if this bit is high
{
probVal = probVal * input_data->static_probability[input_node_pin];
}
else
{
probVal = probVal * (1-input_data->static_probability[input_node_pin]);
}
/* move the bit collumn */
place = place << 1;
}
totalProb += probVal;
}
}
/* store the total probability */
act_data->static_probability[0] = totalProb;
}
else if (current_node->type == FF_NODE)
{
if (rep != 0)
{
/* ONLY do calculations after first repetition */
nnode_t *input_node = current_node->input_pins[0]->net->driver_pin->node;
int input_node_pin = current_node->input_pins[0]->net->driver_pin->pin_node_idx;
activation_t *input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
act_data->static_probability[0] = input_data->static_probability[input_node_pin];
}
}
else if (current_node->type == OUTPUT_NODE)
{
nnode_t *input_node = current_node->input_pins[0]->net->driver_pin->node;
int input_node_pin = current_node->input_pins[0]->net->driver_pin->pin_node_idx;
activation_t *input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
if (rep == 0)
{
/* only one output */
act_data->static_probability = (double*)malloc(sizeof(double));
}
act_data->static_probability[0] = input_data->static_probability[input_node_pin];
}
else if ((current_node->type == INPUT_NODE) || (current_node->type == VCC_NODE) || (current_node->type == GND_NODE))
{
oassert(current_node->unique_node_data_id == ACTIVATION);
continue; // skip transition probability calculation
}
else
{
oassert(FALSE);
}
if (rep == 0)
{
/* calculate transition probability */
act_data->transition_probability = (double*)malloc(sizeof(double)*current_node->num_output_pins);
}
for (k = 0; k < current_node->num_output_pins; k++)
{
act_data->transition_probability[k] = 2 * (act_data->static_probability[k] * (1-act_data->static_probability[k]));
}
}
}
}
}
/*---------------------------------------------------------------------------------------------
* (function: boolean_difference)
*-------------------------------------------------------------------------------------------*/
short *boolean_difference(nnode_t *node, int variable_spot)
{
int i, l;
short *return_function;
int function_size;
long long skip_size = 1 << variable_spot;
int index;
oassert(node->num_input_pins < sizeof (long long int)*8);
oassert(node->associated_function != NULL);
oassert(node->num_input_pins > 1);
/* calculate the size of the boolean difference */
function_size = pow2(node->num_input_pins-1);
return_function = (short*)calloc(sizeof(short), function_size);
for (i = 0; i < function_size; i++)
{
long long int place = 1;
long long int index_plus = 1;
index = 0;
/* IF - this function value is on then calculate the probability */
for (l = 0; l < node->num_input_pins-1; l++)
{
/* move the bit collumn */
if (l == variable_spot)
{
index_plus = index_plus << 1;
}
if ((i & place) > 0) // if this bit is high
{
index += index_plus;
}
place = place << 1;
index_plus = index_plus << 1;
}
/* do the boolean xor of this element */
return_function[i] = node->associated_function[index] ^ node->associated_function[index+skip_size];
}
return return_function;
}
/*---------------------------------------------------------------------------------------------
* (function: calc_density)
*-------------------------------------------------------------------------------------------*/
double calc_density(nnode_t *node, int variable_spot, short *boolean_difference)
{
int i, l;
int function_size;
double totalProb = 0;
double input_density = 0;
oassert(node->num_input_pins < sizeof (long long int)*8);
if ((node->input_pins[variable_spot] != NULL) && (node->input_pins[variable_spot]->net->driver_pin != NULL) && (node->input_pins[variable_spot]->net->driver_pin->node != NULL))
{
nnode_t *input_node = node->input_pins[variable_spot]->net->driver_pin->node;
int input_node_pin = node->input_pins[variable_spot]->net->driver_pin->pin_node_idx;
activation_t *input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
input_density = input_data->transition_density[input_node_pin];
}
else
{
oassert(FALSE);
}
/* calculate the size of the boolean difference */
function_size = pow2(node->num_input_pins-1);
for (i = 0; i < function_size; i++)
{
long long int place = 1;
double probVal = 1;
int index = -1;
if (boolean_difference[i] == 1)
{
/* IF - this function value is on then calculate the probability */
for (l = 0; l < node->num_input_pins-1; l++)
{
nnode_t *input_node;
activation_t *input_data;
int input_node_pin;
/* move the bit collumn */
if (l == variable_spot)
{
/* skip this one */
index += 2;
}
else
{
index ++;
}
input_node = node->input_pins[index]->net->driver_pin->node;
input_node_pin = node->input_pins[index]->net->driver_pin->pin_node_idx;
input_data = (activation_t*)input_node->node_data;
oassert(input_node->unique_node_data_id == ACTIVATION);
if ((i & place) > 0) // if this bit is high
{
probVal = probVal * input_data->static_probability[input_node_pin];
}
else
{
probVal = probVal * (1-input_data->static_probability[input_node_pin]);
}
place = place << 1;
}
totalProb += probVal;
}
}
oassert(totalProb <= 1.1);
if (totalProb > 1)
totalProb = 1; // for rounding errors
// oassert(totalProb * input_density < 1);
return totalProb * input_density;
}
/*---------------------------------------------------------------------------------------------
* (function: output_activation_file_ace_and_function_file)
* Creates the 2 files (+1 .ace file) for the power estimation.
* Traverses the blif_netlist, net_netlist to print out tranisition densities
* and static probabilities. Also, pushes out functions based on the clustered
* netlist.
*-------------------------------------------------------------------------------------------*/
void output_activation_file_ace_and_function_file(char *output_filename, int lut_size, netlist_t *LUT_netlist, netlist_t *CLUSTER_netlist)
{
char *ace_file_name = (char*)malloc(sizeof(char)*(strlen(output_filename)+4+1));
char *ac2_file_name = (char*)malloc(sizeof(char)*(strlen(output_filename)+4+1));
char *function_file_name = (char*)malloc(sizeof(char)*(strlen(output_filename)+4+1));
int i, j, k, l;
FILE *ace_out;
FILE *ac2_out;
FILE *function_out;
long sc_spot;
nnode_t *lut_node;
activation_t *act_data;
sprintf(ace_file_name, "%s.ace", output_filename);
sprintf(ac2_file_name, "%s.ac2", output_filename);
sprintf(function_file_name, "%s.fun", output_filename);
ace_out = fopen(ace_file_name, "w");
if (ace_out == NULL)
{
error_message(ACTIVATION_ERROR, -1, -1, "Could not open output file %s\n", ace_file_name);
}
ac2_out = fopen(ac2_file_name, "w");
if (ac2_out == NULL)
{
error_message(ACTIVATION_ERROR, -1, -1, "Could not open output file %s\n", ac2_file_name);
}
function_out = fopen(function_file_name, "w");
if (function_out == NULL)
{
error_message(ACTIVATION_ERROR, -1, -1, "Could not open output file %s\n", function_file_name);
}
/* Go through the LUT netlist and print out the ace files */
for (i = 0; i < LUT_netlist->num_forward_levels; i++)
{
for (j = 0; j < LUT_netlist->num_at_forward_level[i]; j++)
{
/* initialize the activation data */
nnode_t *current_node = LUT_netlist->forward_levels[i][j];
activation_t *act_data = (activation_t*)current_node->node_data;
if (current_node->type != OUTPUT_NODE)
{
for (k = 0; k < current_node->num_output_pins; k++)
{
if (current_node->output_pins[0]->net->num_fanout_pins != 0)
{
/* IF this node fans out */
fprintf(ace_out, "%s %f %f\n", current_node->name, act_data->static_probability[k], act_data->transition_density[k]);
}
}
}
else
{
fprintf(ace_out, "out:%s %f %f\n", current_node->name, act_data->static_probability[0], act_data->transition_density[0]);
}
}
}
fclose(ace_out);
/* now create the ac2 file and function file */
/* first we spit out the clocks */
for (i = 0; i < CLUSTER_netlist->num_clocks; i++)
{
nnode_t *cluster_node = CLUSTER_netlist->clocks[i];
fprintf (ac2_out, "global_net_probability %s 0.5\n", cluster_node->name);
fprintf (ac2_out, "global_net_density %s 2.0\n", cluster_node->name);
}
/* next we make the intercluster probabilities for inputs */
for (i = 0; i < CLUSTER_netlist->num_top_input_nodes; i++)
{
nnode_t *cluster_node = CLUSTER_netlist->top_input_nodes[i];
if (cluster_node->type == CLOCK_NODE)
{
continue;
}
/* find the equivalent blif point */
if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, cluster_node->name)) == -1)
{
warning_message(ACTIVATION_ERROR, -1, -1, "Could not find %s INPUT in LUT netlist ...\n", cluster_node->name);
continue;
}
lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];
act_data = (activation_t*)lut_node->node_data;
oassert(lut_node->num_output_pins == 1); /* assumption now, but will change with heterognenous blocks */
fprintf (ac2_out, "intercluster_net_probability %s %f\n", cluster_node->name, act_data->static_probability[0]);
fprintf (ac2_out, "intercluster_net_density %s %f\n", cluster_node->name, act_data->transition_density[0]);
}
/* next we make the intercluster probabilities for inputs */
for (i = 0; i < CLUSTER_netlist->num_top_output_nodes; i++)
{
nnode_t *cluster_node = CLUSTER_netlist->top_output_nodes[i];
/* find the equivalent blif point */
if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, cluster_node->name)) == -1)
{
warning_message(ACTIVATION_ERROR, -1, -1, "Could not find %s OUTPUT in LUT netlist ...\n", cluster_node->name);
continue;
}
lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];
act_data = (activation_t*)lut_node->node_data;
oassert(lut_node->num_output_pins == 0); /* assumption now, but will change with heterognenous blocks */
fprintf (ac2_out, "intercluster_net_probability %s %f\n", (cluster_node->name+4), act_data->static_probability[0]); /* +4 to skip "out:" that isn't needed in output */
fprintf (ac2_out, "intercluster_net_density %s %f\n", (cluster_node->name+4), act_data->transition_density[0]);
}
/* next we make the intercluster probabilities */
for (i = 0; i < CLUSTER_netlist->num_internal_nodes; i++)
{
nnode_t *cluster_node = CLUSTER_netlist->internal_nodes[i];
netlist_t* internal_subblocks = cluster_node->internal_netlist;
if (internal_subblocks == NULL)
{
/* INPUT/OUTPUT pins and globals (clocks) have no subblocks */
continue;
}
/* now we process the internal structure of the node, which represents the subblocks. This is stored in an internall netlist. */
for (k = 0; k < internal_subblocks->num_internal_nodes; k++)
{
nnode_t *current_subblock = internal_subblocks->internal_nodes[k];
char *output_search_name = (char*)malloc(sizeof(char)*(strlen(current_subblock->name)+1+4));
sprintf(output_search_name, "out:%s", current_subblock->name);
if ((sc_spot = sc_lookup_string(internal_subblocks->nodes_sc, output_search_name)) != -1)
{
/* IF - this is an output of the cluster then we need inter cluster info */
/* now find this node */
/* find the equivalent blif point */
if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, current_subblock->name)) == -1)
{
error_message(ACTIVATION_ERROR, -1, -1, "Could not find %s in LUT netlist ...\n", current_subblock->name);
}
lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];
act_data = (activation_t*)lut_node->node_data;
/* Finally, put in th output switching values */
fprintf (ac2_out, "intercluster_net_probability %s %f\n", current_subblock->name, act_data->static_probability[0]);
fprintf (ac2_out, "intercluster_net_density %s %f\n", current_subblock->name, act_data->transition_density[0]);
}
free(output_search_name);
}
}
/* next we process the subblocks */
for (i = 0; i < CLUSTER_netlist->num_internal_nodes; i++)
{
nnode_t *cluster_node = CLUSTER_netlist->internal_nodes[i];
netlist_t* internal_subblocks = cluster_node->internal_netlist;
if (internal_subblocks == NULL)
{
/* INPUT/OUTPUT pins and globals (clocks) have no subblocks */
oassert(FALSE);
continue;
}
/* now we process the internal structure of the node, which represents the subblocks. This is stored in an internall netlist. */
for (k = 0; k < internal_subblocks->num_internal_nodes; k++)
{
nnode_t *current_subblock = internal_subblocks->internal_nodes[k];
char probability_string[4096];
char density_string[4096];
int input_active_count = 0;
short is_clock = FALSE;
int input_index = 0;
sprintf(probability_string, "subblock_probability %s", current_subblock->name);
sprintf(density_string, "subblock_density %s", current_subblock->name);
/* first get all the input values */
for (l = 0; l < lut_size+1; l++)
{
if (current_subblock->input_pins[input_index] != NULL)
{
nnode_t *input_node = current_subblock->input_pins[input_index]->net->driver_pin->node;
/* find the equivalent blif point */
if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, input_node->name)) == -1)
{
error_message(ACTIVATION_ERROR, -1, -1, "Could not find %s in LUT netlist ...\n", input_node->name);
}
lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];
act_data = (activation_t*)lut_node->node_data;
if (lut_node->type == CLOCK_NODE)
{
/* IF - the clock spot */
if (l == lut_size)
{
/* only print it out if this is the last spot */
sprintf(probability_string, "%s %f", probability_string, act_data->static_probability[0]);
sprintf(density_string, "%s %f", density_string, act_data->transition_density[0]);
is_clock = TRUE;
}
else
{
sprintf(probability_string, "%s 0.0", probability_string);
sprintf(density_string, "%s 0.0", density_string);
}
}
else
{
sprintf(probability_string, "%s %f", probability_string, act_data->static_probability[0]);
sprintf(density_string, "%s %f", density_string, act_data->transition_density[0]);
input_index++;
}
input_active_count ++;
}
else
{
/* No connection to this input */
sprintf(probability_string, "%s 0.0", probability_string);
sprintf(density_string, "%s 0.0", density_string);
}
}
if (is_clock == FALSE)
{
/* IF - there is no clock meaning this is just a LUT, output the probabilities */
sprintf(probability_string, "%s 0.0", probability_string);
sprintf(density_string, "%s 0.0", density_string);
}
/* now find this node */
/* find the equivalent blif point */
if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, current_subblock->name)) == -1)
{
error_message(ACTIVATION_ERROR, -1, -1, "Could not find %s in LUT netlist ...\n", current_subblock->name);
}
lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];
act_data = (activation_t*)lut_node->node_data;
/* find the values of the switching between LUT and FF */
if ((lut_node->type == FF_NODE) && (input_active_count > 0))
{
/* LUT + FF */
/* IF - this is a FF node and has more than 1 input, then it's a LUT-FF */
activation_t *input_node_to_ff_act_data = (activation_t *)lut_node->input_pins[0]->net->driver_pin->node->node_data;
sprintf(probability_string, "%s %f", probability_string, input_node_to_ff_act_data->static_probability[0]);
sprintf(density_string, "%s %f", density_string, input_node_to_ff_act_data->transition_density[0]);
/* print out the function of this node based on it's inputs function */
oassert (lut_node->input_pins[0]->net->driver_pin->node->associated_function != NULL)
fprintf(function_out, "subblock_function %s ", lut_node->name);
for (l = 0; l < pow2(lut_size); l++)
{
fprintf(function_out, "%d", lut_node->input_pins[0]->net->driver_pin->node->associated_function[l]);
}
fprintf(function_out, "\n");
}
else if (lut_node->type == FF_NODE)
{
/* FF */
/* ELSE - this is a FF_NODE only */
sprintf(probability_string, "%s 0.0", probability_string);
sprintf(density_string, "%s 0.0", density_string);
/* output function is just a buffer since this is just a FF */
fprintf(function_out, "subblock_function %s ", lut_node->name);
for (l = 0; l < pow2(lut_size); l++)
{
if (l % 2 == 0)
{
fprintf(function_out, "0");
}
else
{
fprintf(function_out, "1");
}
}
fprintf(function_out, "\n");
}
else
{
/* LUT */
/* print out the function of this node based on it's just a LUT */
oassert (lut_node->associated_function != NULL)
fprintf(function_out, "subblock_function %s ", lut_node->name);
for (l = 0; l < pow2(lut_size); l++)
{
fprintf(function_out, "%d", lut_node->associated_function[l]);
}
fprintf(function_out, "\n");
}
/* Finally, put in th output switching values */
sprintf(probability_string, "%s %f", probability_string, act_data->static_probability[0]);
sprintf(density_string, "%s %f", density_string, act_data->transition_density[0]);
/* output the values created for the subblock */
fprintf(ac2_out, "%s\n", probability_string);
fprintf(ac2_out, "%s\n", density_string);
}
}
fclose(function_out);
fclose(ac2_out);
}
/*---------------------------------------------------------------------------------------------
* (function: cleanup_activation)
*-------------------------------------------------------------------------------------------*/
void cleanup_activation(netlist_t *netlist)
{
int i, j;
for (i = 0; i < netlist->num_forward_levels; i++)
{
for (j = 0; j < netlist->num_at_forward_level[i]; j++)
{
/* initialize the activation data */
nnode_t *current_node = netlist->forward_levels[i][j];
activation_t *act_data = (activation_t*)current_node->node_data;
oassert(act_data != NULL);
if (act_data->static_probability != NULL)
free(act_data->static_probability);
if (act_data->transition_density != NULL)
free(act_data->transition_density);
if (act_data->transition_probability != NULL)
free(act_data->transition_probability);
free(act_data);
current_node->unique_node_data_id = RESET;
}
}
}
| 35.86203 | 177 | 0.65521 |
55da6e9f54f3dbc8616886b610f0feda56160831 | 2,078 | h | C | MAX/library/include/Activity/CurrentActivityRequests.h | isabella232/max-toolkit | 6fc0b416efa064094ffc98daf6ee8755c3ec73fe | [
"Apache-2.0"
] | 4 | 2021-09-10T18:35:11.000Z | 2022-01-07T11:33:10.000Z | MAX/library/include/Activity/CurrentActivityRequests.h | alexa/max-toolkit | 6fc0b416efa064094ffc98daf6ee8755c3ec73fe | [
"Apache-2.0"
] | 1 | 2022-02-08T19:22:12.000Z | 2022-02-08T20:42:28.000Z | MAX/library/include/Activity/CurrentActivityRequests.h | isabella232/max-toolkit | 6fc0b416efa064094ffc98daf6ee8755c3ec73fe | [
"Apache-2.0"
] | 3 | 2021-09-20T22:11:32.000Z | 2022-02-08T17:26:53.000Z | /*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 MULTI_AGENT_EXPERIENCE_LIBRARY_INCLUDE_ACTIVITY_CURRENTACTIVITYREQUESTS_H_
#define MULTI_AGENT_EXPERIENCE_LIBRARY_INCLUDE_ACTIVITY_CURRENTACTIVITYREQUESTS_H_
#include <memory>
#include <mutex>
#include <unordered_map>
#include "Activity.h"
#include "ActivityID.h"
#include "ActivityRequestID.h"
#include "ActivityLifecycle.h"
#include "ActivityRequestLifecycle.h"
namespace multiAgentExperience {
namespace library {
namespace activity {
class CurrentActivityRequests {
public:
virtual ~CurrentActivityRequests();
virtual void add(std::shared_ptr<ActivityRequestLifecycle> activityRequest);
virtual std::shared_ptr<ActivityLifecycle> grant(const ActivityRequestID activityRequestId);
virtual bool wait(const ActivityRequestID activityRequestId);
virtual void deny(const ActivityRequestID activityRequestId);
virtual const ActivityID remove(const ActivityRequestID activityRequestId);
virtual const ActivityID finish(const ActivityRequestID activityRequestId);
private:
enum class RemovalReason { DENIED, REMOVED, ABANDONED };
const ActivityID finish(const ActivityRequestID activityRequestId, const RemovalReason state);
std::mutex m_activeRequestsMutex;
std::unordered_map<ActivityRequestID, std::shared_ptr<ActivityRequestLifecycle>> m_activityRequests;
};
} // namespace activity
} // namespace library
} // namespace multiAgentExperience
#endif // MULTI_AGENT_EXPERIENCE_LIBRARY_INCLUDE_ACTIVITY_CURRENTACTIVITYREQUESTS_H_
| 32.984127 | 104 | 0.793551 |
5920b50ff13012ca1c0ad30843232b0d38084278 | 1,530 | h | C | include/hurricane/task/SpoutExecutor.h | JianboTang/hurricane | 65c62829669efcdd17b4675a15f97ffce0d321a6 | [
"Apache-2.0"
] | 242 | 2016-07-12T11:27:27.000Z | 2022-03-14T09:16:05.000Z | include/hurricane/task/SpoutExecutor.h | JianboTang/hurricane | 65c62829669efcdd17b4675a15f97ffce0d321a6 | [
"Apache-2.0"
] | 14 | 2016-12-13T04:35:00.000Z | 2022-01-16T02:48:43.000Z | include/hurricane/task/SpoutExecutor.h | JianboTang/hurricane | 65c62829669efcdd17b4675a15f97ffce0d321a6 | [
"Apache-2.0"
] | 115 | 2016-07-20T03:49:20.000Z | 2022-02-14T09:07:36.000Z | /**
* 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.
*/
#pragma once
#include "hurricane/task/Executor.h"
#include <thread>
#include <memory>
namespace hurricane {
namespace spout {
class ISpout;
}
namespace task {
class SpoutExecutor : public Executor {
public:
SpoutExecutor();
~SpoutExecutor() {}
void Start();
void SetSpout(spout::ISpout* spout)
{
_spout.reset(spout);
}
std::shared_ptr<spout::ISpout> GetSpout() {
return _spout;
}
int32_t GetFlowParam() const
{
return _flowParam;
}
void SetFlowParam(int32_t flowParam)
{
_flowParam = flowParam;
}
private:
void MainLoop();
std::thread _thread;
std::shared_ptr<spout::ISpout> _spout;
int32_t _flowParam;
};
}
}
| 22.5 | 75 | 0.694118 |
33e5d05260bc36ef198f7d34f6efb45c8358fcac | 183 | c | C | C/1044.c | mayconrebordao/uri-codes | 1081c25ecaf0142f38c7ba287bd01490a1d34474 | [
"MIT"
] | null | null | null | C/1044.c | mayconrebordao/uri-codes | 1081c25ecaf0142f38c7ba287bd01490a1d34474 | [
"MIT"
] | null | null | null | C/1044.c | mayconrebordao/uri-codes | 1081c25ecaf0142f38c7ba287bd01490a1d34474 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main(){
int a,b;
scanf("%d %d",&a,&b);
if ((b%a)==0 ||(a%b)==0){
printf("Sao Multiplos\n");
}
else{
printf("Nao sao Multiplos\n");
}
return 0;
}
| 12.2 | 32 | 0.513661 |
b4f121d6d0e1097e59153e20401b4c244f8ba32e | 23,747 | c | C | src/snmp-mib/ip/ip-traffic-stats.c | verrio/osnmpd | a7c7830cfbbb77fc20d18021531e250267da67e3 | [
"MIT"
] | 11 | 2017-05-20T22:34:34.000Z | 2022-02-15T00:30:49.000Z | src/snmp-mib/ip/ip-traffic-stats.c | verrio/osnmpd | a7c7830cfbbb77fc20d18021531e250267da67e3 | [
"MIT"
] | 1 | 2019-12-10T01:40:18.000Z | 2019-12-10T01:40:18.000Z | src/snmp-mib/ip/ip-traffic-stats.c | verrio/osnmpd | a7c7830cfbbb77fc20d18021531e250267da67e3 | [
"MIT"
] | 5 | 2017-05-20T22:40:25.000Z | 2021-03-18T19:00:54.000Z | /*
* This file is part of the osnmpd project (https://github.com/verrio/osnmpd).
* Copyright (C) 2016 Olivier Verriest
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <sys/utsname.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdio.h>
#include <stddef.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "snmp-agent/agent-cache.h"
#include "snmp-agent/mib-tree.h"
#include "snmp-core/utils.h"
#include "snmp-core/snmp-types.h"
#include "snmp-mib/single-level-module.h"
#include "snmp-mib/ip/if-cache.h"
#include "snmp-mib/ip/ip-cache.h"
#include "snmp-mib/ip/ip-address-cache.h"
#include "snmp-mib/ip/ip-module.h"
#include "snmp-mib/ip/ip-traffic-stats.h"
enum IPTrafficStatsMIB {
IP_SYSTEM_STATS_TABLE = 1,
IP_IF_STATS_TABLE_LAST_CHANGE = 2,
IP_IF_STATS_TABLE = 3
};
enum IPSystemStatsTableColumns {
IP_SYSTEM_STATS_IP_VERSION = 1,
IP_SYSTEM_STATS_UNUSED = 2,
IP_SYSTEM_STATS_IN_RECEIVES = 3,
IP_SYSTEM_STATS_HC_IN_RECEIVES = 4,
IP_SYSTEM_STATS_IN_OCTETS = 5,
IP_SYSTEM_STATS_HC_IN_OCTETS = 6,
IP_SYSTEM_STATS_IN_HDR_ERRORS = 7,
IP_SYSTEM_STATS_IN_NO_ROUTES = 8,
IP_SYSTEM_STATS_IN_ADDR_ERRORS = 9,
IP_SYSTEM_STATS_IN_UNKNOWN_PROTOS = 10,
IP_SYSTEM_STATS_IN_TRUNCATED_PKTS = 11,
IP_SYSTEM_STATS_IN_FORW_DATAGRAMS = 12,
IP_SYSTEM_STATS_HC_IN_FORW_DATAGRAMS = 13,
IP_SYSTEM_STATS_REASM_REQDS = 14,
IP_SYSTEM_STATS_REASM_OKS = 15,
IP_SYSTEM_STATS_REASM_FAILS = 16,
IP_SYSTEM_STATS_IN_DISCARDS = 17,
IP_SYSTEM_STATS_IN_DELIVERS = 18,
IP_SYSTEM_STATS_HC_IN_DELIVERS = 19,
IP_SYSTEM_STATS_OUT_REQUESTS = 20,
IP_SYSTEM_STATS_HC_OUT_REQUESTS = 21,
IP_SYSTEM_STATS_OUT_NO_ROUTES = 22,
IP_SYSTEM_STATS_OUT_FORW_DATAGRAMS = 23,
IP_SYSTEM_STATS_HC_OUT_FORW_DATAGRAMS = 24,
IP_SYSTEM_STATS_OUT_DISCARDS = 25,
IP_SYSTEM_STATS_OUT_FRAG_REQDS = 26,
IP_SYSTEM_STATS_OUT_FRAG_OKS = 27,
IP_SYSTEM_STATS_OUT_FRAG_FAILS = 28,
IP_SYSTEM_STATS_OUT_FRAG_CREATES = 29,
IP_SYSTEM_STATS_OUT_TRANSMITS = 30,
IP_SYSTEM_STATS_HC_OUT_TRANSMITS = 31,
IP_SYSTEM_STATS_OUT_OCTETS = 32,
IP_SYSTEM_STATS_HC_OUT_OCTETS = 33,
IP_SYSTEM_STATS_IN_MCAST_PKTS = 34,
IP_SYSTEM_STATS_HC_IN_MCAST_PKTS = 35,
IP_SYSTEM_STATS_IN_MCAST_OCTETS = 36,
IP_SYSTEM_STATS_HC_IN_MCAST_OCTETS = 37,
IP_SYSTEM_STATS_OUT_MCAST_PKTS = 38,
IP_SYSTEM_STATS_HC_OUT_MCAST_PKTS = 39,
IP_SYSTEM_STATS_OUT_MCAST_OCTETS = 40,
IP_SYSTEM_STATS_HC_OUT_MCAST_OCTETS = 41,
IP_SYSTEM_STATS_IN_BCAST_PKTS = 42,
IP_SYSTEM_STATS_HC_IN_BCAST_PKTS = 43,
IP_SYSTEM_STATS_OUT_BCAST_PKTS = 44,
IP_SYSTEM_STATS_HC_OUT_BCAST_PKTS = 45,
IP_SYSTEM_STATS_DISCONTINUITY_TIME = 46,
IP_SYSTEM_STATS_REFRESH_RATE = 47
};
enum IPIFStatusTableColumns {
IP_IF_STATS_IP_VERSION = 1,
IP_IF_STATS_IF_INDEX = 2,
IP_IF_STATS_IN_RECEIVES = 3,
IP_IF_STATS_HC_IN_RECEIVES = 4,
IP_IF_STATS_IN_OCTETS = 5,
IP_IF_STATS_HC_IN_OCTETS = 6,
IP_IF_STATS_IN_HDR_ERRORS = 7,
IP_IF_STATS_IN_NO_ROUTES = 8,
IP_IF_STATS_IN_ADDR_ERRORS = 9,
IP_IF_STATS_IN_UNKNOWN_PROTOS = 10,
IP_IF_STATS_IN_TRUNCATED_PKTS = 11,
IP_IF_STATS_IN_FORW_DATAGRAMS = 12,
IP_IF_STATS_HC_IN_FORW_DATAGRAMS = 13,
IP_IF_STATS_REASM_REQDS = 14,
IP_IF_STATS_REASM_OKS = 15,
IP_IF_STATS_REASM_FAILS = 16,
IP_IF_STATS_IN_DISCARDS = 17,
IP_IF_STATS_IN_DELIVERS = 18,
IP_IF_STATS_HC_IN_DELIVERS = 19,
IP_IF_STATS_OUT_REQUESTS = 20,
IP_IF_STATS_HC_OUT_REQUESTS = 21,
IP_IF_STATS_UNUSED = 22,
IP_IF_STATS_OUT_FORW_DATAGRAMS = 23,
IP_IF_STATS_HC_OUT_FORW_DATAGRAMS = 24,
IP_IF_STATS_OUT_DISCARDS = 25,
IP_IF_STATS_OUT_FRAG_REQDS = 26,
IP_IF_STATS_OUT_FRAG_OKS = 27,
IP_IF_STATS_OUT_FRAG_FAILS = 28,
IP_IF_STATS_OUT_FRAG_CREATES = 29,
IP_IF_STATS_OUT_TRANSMITS = 30,
IP_IF_STATS_HC_OUT_TRANSMITS = 31,
IP_IF_STATS_OUT_OCTETS = 32,
IP_IF_STATS_HC_OUT_OCTETS = 33,
IP_IF_STATS_IN_MCAST_PKTS = 34,
IP_IF_STATS_HC_IN_MCAST_PKTS = 35,
IP_IF_STATS_IN_MCAST_OCTETS = 36,
IP_IF_STATS_HC_IN_MCAST_OCTETS = 37,
IP_IF_STATS_OUT_MCAST_PKTS = 38,
IP_IF_STATS_HC_OUT_MCAST_PKTS = 39,
IP_IF_STATS_OUT_MCAST_OCTETS = 40,
IP_IF_STATS_HC_OUT_MCAST_OCTETS = 41,
IP_IF_STATS_IN_BCAST_PKTS = 42,
IP_IF_STATS_HC_IN_BCAST_PKTS = 43,
IP_IF_STATS_OUT_BCAST_PKTS = 44,
IP_IF_STATS_HC_OUT_BCAST_PKTS = 45,
IP_IF_STATS_DISCONTINUITY_TIME = 46,
IP_IF_STATS_REFRESH_RATE = 47
};
static enum IpAddressFamily get_ip_version(SubOID *row, size_t row_len, int next_row)
{
if (!next_row) {
if (row_len == 1 && (row[0] == ADDRESS_IP4 || row[0] == ADDRESS_IP6)) {
return row[0];
}
} else if (row_len < 1 || row[0] < ADDRESS_IP4) {
return ADDRESS_IP4;
} else if (row[0] < ADDRESS_IP6) {
return ADDRESS_IP6;
}
return ADDRESS_UNKNOWN;
}
static IfaceEntry *get_iface_entry(SubOID *row, size_t row_len, int next_row)
{
int iface;
if (next_row) {
if (row_len < 1 || row[0] < ADDRESS_IP6) {
iface = 0;
} else if (row[0] == ADDRESS_IP6) {
iface = row_len > 1 ? row[1] : 0;
} else {
return NULL;
}
} else if (row_len != 2 || row[0] != ADDRESS_IP6) {
return NULL;
} else {
iface = row[1];
}
for (IfaceEntry *entry = get_iface_list(); entry != NULL; entry = entry->next) {
if (iface < entry->id) {
return next_row ? entry : NULL;
} else if (!next_row && iface == entry->id) {
return entry;
}
}
return NULL;
}
static SnmpErrorStatus get_ip_system_stats_table(int column, SubOID *row, size_t row_len,
SnmpVariableBinding *binding, int next_row)
{
IpStatistics *statistics = get_ip_statistics();
if (statistics == NULL) {
return GENERAL_ERROR;
}
enum IpAddressFamily version = get_ip_version(row, row_len, next_row);
IpGeneralStatistics *ip_stats = NULL;
if (version == ADDRESS_IP4) {
ip_stats = &statistics->ip4;
} else if (version == ADDRESS_IP6) {
ip_stats = &statistics->ip6;
}
CHECK_INSTANCE_FOUND(next_row, ip_stats);
switch (column) {
case IP_SYSTEM_STATS_IP_VERSION: {
SET_INTEGER_BIND(binding, version);
break;
}
case IP_SYSTEM_STATS_UNUSED: {
binding->type = SMI_TYPE_NULL;
break;
}
case IP_SYSTEM_STATS_IN_RECEIVES: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_receives));
break;
}
case IP_SYSTEM_STATS_HC_IN_RECEIVES: {
SET_UNSIGNED64_BIND(binding, ip_stats->in_receives);
break;
}
case IP_SYSTEM_STATS_IN_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_octets));
break;
}
case IP_SYSTEM_STATS_HC_IN_OCTETS: {
SET_UNSIGNED64_BIND(binding, ip_stats->in_octets);
break;
}
case IP_SYSTEM_STATS_IN_HDR_ERRORS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_hdr_errors));
break;
}
case IP_SYSTEM_STATS_IN_NO_ROUTES: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_no_routes));
break;
}
case IP_SYSTEM_STATS_IN_ADDR_ERRORS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_addr_errors));
break;
}
case IP_SYSTEM_STATS_IN_UNKNOWN_PROTOS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_unknown_protos));
break;
}
case IP_SYSTEM_STATS_IN_TRUNCATED_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_truncated_pkts));
break;
}
case IP_SYSTEM_STATS_IN_FORW_DATAGRAMS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_forw_datagrams));
break;
}
case IP_SYSTEM_STATS_HC_IN_FORW_DATAGRAMS: {
SET_UNSIGNED64_BIND(binding, ip_stats->in_forw_datagrams);
break;
}
case IP_SYSTEM_STATS_REASM_REQDS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->reasm_reqds));
break;
}
case IP_SYSTEM_STATS_REASM_OKS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->reasm_oks));
break;
}
case IP_SYSTEM_STATS_REASM_FAILS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->reasm_fails));
break;
}
case IP_SYSTEM_STATS_IN_DISCARDS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_discards));
break;
}
case IP_SYSTEM_STATS_IN_DELIVERS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_delivers));
break;
}
case IP_SYSTEM_STATS_HC_IN_DELIVERS: {
SET_UNSIGNED64_BIND(binding, ip_stats->in_delivers);
break;
}
case IP_SYSTEM_STATS_OUT_REQUESTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_requests));
break;
}
case IP_SYSTEM_STATS_HC_OUT_REQUESTS: {
SET_UNSIGNED64_BIND(binding, ip_stats->out_requests);
break;
}
case IP_SYSTEM_STATS_OUT_NO_ROUTES: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_no_routes));
break;
}
case IP_SYSTEM_STATS_OUT_FORW_DATAGRAMS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_forw_datagrams));
break;
}
case IP_SYSTEM_STATS_HC_OUT_FORW_DATAGRAMS: {
SET_UNSIGNED64_BIND(binding, ip_stats->out_forw_datagrams);
break;
}
case IP_SYSTEM_STATS_OUT_DISCARDS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_discards));
break;
}
case IP_SYSTEM_STATS_OUT_FRAG_REQDS: {
SET_UNSIGNED_BIND(binding,
LOWER_HALF(ip_stats->out_frag_oks + ip_stats->out_frag_fails));
break;
}
case IP_SYSTEM_STATS_OUT_FRAG_OKS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_frag_oks));
break;
}
case IP_SYSTEM_STATS_OUT_FRAG_FAILS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_frag_fails));
break;
}
case IP_SYSTEM_STATS_OUT_FRAG_CREATES: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_frag_creates));
break;
}
case IP_SYSTEM_STATS_OUT_TRANSMITS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_transmit));
break;
}
case IP_SYSTEM_STATS_HC_OUT_TRANSMITS: {
SET_UNSIGNED64_BIND(binding, ip_stats->out_transmit);
break;
}
case IP_SYSTEM_STATS_OUT_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_octets));
break;
}
case IP_SYSTEM_STATS_HC_OUT_OCTETS: {
SET_UNSIGNED64_BIND(binding, ip_stats->out_octets);
break;
}
case IP_SYSTEM_STATS_IN_MCAST_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_mcast_pkts));
break;
}
case IP_SYSTEM_STATS_HC_IN_MCAST_PKTS: {
SET_UNSIGNED64_BIND(binding, ip_stats->in_mcast_pkts);
break;
}
case IP_SYSTEM_STATS_IN_MCAST_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_mcast_octets));
break;
}
case IP_SYSTEM_STATS_HC_IN_MCAST_OCTETS: {
SET_UNSIGNED64_BIND(binding, ip_stats->in_mcast_octets);
break;
}
case IP_SYSTEM_STATS_OUT_MCAST_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_mcast_pkts));
break;
}
case IP_SYSTEM_STATS_HC_OUT_MCAST_PKTS: {
SET_UNSIGNED64_BIND(binding, ip_stats->out_mcast_pkts);
break;
}
case IP_SYSTEM_STATS_OUT_MCAST_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_mcast_octets));
break;
}
case IP_SYSTEM_STATS_HC_OUT_MCAST_OCTETS: {
SET_UNSIGNED64_BIND(binding, ip_stats->out_mcast_octets);
break;
}
case IP_SYSTEM_STATS_IN_BCAST_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->in_bcast_pkts));
break;
}
case IP_SYSTEM_STATS_HC_IN_BCAST_PKTS: {
SET_UNSIGNED64_BIND(binding, ip_stats->in_bcast_pkts);
break;
}
case IP_SYSTEM_STATS_OUT_BCAST_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(ip_stats->out_bcast_pkts));
break;
}
case IP_SYSTEM_STATS_HC_OUT_BCAST_PKTS: {
SET_UNSIGNED64_BIND(binding, ip_stats->out_bcast_pkts);
break;
}
case IP_SYSTEM_STATS_DISCONTINUITY_TIME: {
SET_TIME_TICKS_BIND(binding, 0);
break;
}
case IP_SYSTEM_STATS_REFRESH_RATE: {
SET_GAUGE_BIND(binding, IP_CACHE_UPDATE_INTERVAL * 1000);
break;
}
}
INSTANCE_FOUND_INT_ROW(next_row, SNMP_OID_IP_TRAFFIC_STATS,
IP_SYSTEM_STATS_TABLE, column, version)
}
static SnmpErrorStatus get_if_stats_table(int column, SubOID *row, size_t row_len,
SnmpVariableBinding *binding, int next_row)
{
IfaceEntry *iface = get_iface_entry(row, row_len, next_row);
CHECK_INSTANCE_FOUND(next_row, iface);
switch (column) {
case IP_IF_STATS_IP_VERSION: {
SET_INTEGER_BIND(binding, ADDRESS_IP6);
break;
}
case IP_IF_STATS_IF_INDEX: {
SET_INTEGER_BIND(binding, iface->id);
break;
}
case IP_IF_STATS_IN_RECEIVES: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_receives));
break;
}
case IP_IF_STATS_HC_IN_RECEIVES: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.in_receives);
break;
}
case IP_IF_STATS_IN_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_octets));
break;
}
case IP_IF_STATS_HC_IN_OCTETS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.in_octets);
break;
}
case IP_IF_STATS_IN_HDR_ERRORS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_hdr_errors));
break;
}
case IP_IF_STATS_IN_NO_ROUTES: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_no_routes));
break;
}
case IP_IF_STATS_IN_ADDR_ERRORS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_addr_errors));
break;
}
case IP_IF_STATS_IN_UNKNOWN_PROTOS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_unknown_protos));
break;
}
case IP_IF_STATS_IN_TRUNCATED_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_truncated_pkts));
break;
}
case IP_IF_STATS_IN_FORW_DATAGRAMS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_forw_datgrams));
break;
}
case IP_IF_STATS_HC_IN_FORW_DATAGRAMS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.in_forw_datgrams);
break;
}
case IP_IF_STATS_REASM_REQDS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.reasm_reqds));
break;
}
case IP_IF_STATS_REASM_OKS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.reasm_ok));
break;
}
case IP_IF_STATS_REASM_FAILS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.reasm_fails));
break;
}
case IP_IF_STATS_IN_DISCARDS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_discards));
break;
}
case IP_IF_STATS_IN_DELIVERS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.in_delivers));
break;
}
case IP_IF_STATS_HC_IN_DELIVERS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.in_delivers);
break;
}
case IP_IF_STATS_OUT_REQUESTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_requests));
break;
}
case IP_IF_STATS_HC_OUT_REQUESTS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.out_requests);
break;
}
case IP_IF_STATS_UNUSED: {
binding->type = SMI_TYPE_NULL;
break;
}
case IP_IF_STATS_OUT_FORW_DATAGRAMS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_forw_datagrams));
break;
}
case IP_IF_STATS_HC_OUT_FORW_DATAGRAMS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.out_forw_datagrams);
break;
}
case IP_IF_STATS_OUT_DISCARDS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_discards));
break;
}
case IP_IF_STATS_OUT_FRAG_REQDS: {
SET_UNSIGNED_BIND(binding,
LOWER_HALF(iface->ip6_stats.out_frag_oks + iface->ip6_stats.out_frag_fails));
break;
}
case IP_IF_STATS_OUT_FRAG_OKS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_frag_oks));
break;
}
case IP_IF_STATS_OUT_FRAG_FAILS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_frag_fails));
break;
}
case IP_IF_STATS_OUT_FRAG_CREATES: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_frag_creates));
break;
}
case IP_IF_STATS_OUT_TRANSMITS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_transmits));
break;
}
case IP_IF_STATS_HC_OUT_TRANSMITS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.out_transmits);
break;
}
case IP_IF_STATS_OUT_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_octets));
break;
}
case IP_IF_STATS_HC_OUT_OCTETS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.out_octets);
break;
}
case IP_IF_STATS_IN_MCAST_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_mcast_pkts));
break;
}
case IP_IF_STATS_HC_IN_MCAST_PKTS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.out_mcast_pkts);
break;
}
case IP_IF_STATS_IN_MCAST_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_mcast_pkts));
break;
}
case IP_IF_STATS_HC_IN_MCAST_OCTETS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.in_mcast_octets);
break;
}
case IP_IF_STATS_OUT_MCAST_PKTS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_mcast_pkts));
break;
}
case IP_IF_STATS_HC_OUT_MCAST_PKTS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.out_mcast_pkts);
break;
}
case IP_IF_STATS_OUT_MCAST_OCTETS: {
SET_UNSIGNED_BIND(binding, LOWER_HALF(iface->ip6_stats.out_mcast_octets));
break;
}
case IP_IF_STATS_HC_OUT_MCAST_OCTETS: {
SET_UNSIGNED64_BIND(binding, iface->ip6_stats.out_mcast_octets);
break;
}
case IP_IF_STATS_IN_BCAST_PKTS:
case IP_IF_STATS_OUT_BCAST_PKTS: {
SET_UNSIGNED_BIND(binding, 0);
break;
}
case IP_IF_STATS_HC_IN_BCAST_PKTS:
case IP_IF_STATS_HC_OUT_BCAST_PKTS: {
SET_UNSIGNED64_BIND(binding, 0);
break;
}
case IP_IF_STATS_DISCONTINUITY_TIME: {
SET_TIME_TICKS_BIND(binding, 0);
break;
}
case IP_IF_STATS_REFRESH_RATE: {
SET_GAUGE_BIND(binding, IP_CACHE_UPDATE_INTERVAL * 1000);
break;
}
}
INSTANCE_FOUND_INT_ROW2(next_row, SNMP_OID_IP_TRAFFIC_STATS,
IP_IF_STATS_TABLE, column, ADDRESS_IP6, iface->id)
}
DEF_METHOD(get_scalar, SnmpErrorStatus, SingleLevelMibModule,
SingleLevelMibModule, int id, SnmpVariableBinding *binding)
{
SET_TIME_TICKS_BIND(binding, 0);
return NO_ERROR;
}
DEF_METHOD(set_scalar, SnmpErrorStatus, SingleLevelMibModule,
SingleLevelMibModule, int id, SnmpVariableBinding *binding, int dry_run)
{
return NOT_WRITABLE;
}
DEF_METHOD(get_tabular, SnmpErrorStatus, SingleLevelMibModule,
SingleLevelMibModule, int id, int column, SubOID *row, size_t row_len,
SnmpVariableBinding *binding, int next_row)
{
switch (id) {
case IP_SYSTEM_STATS_TABLE: {
return get_ip_system_stats_table(column, row, row_len, binding, next_row);
}
case IP_IF_STATS_TABLE: {
return get_if_stats_table(column, row, row_len, binding, next_row);
}
default: {
return GENERAL_ERROR;
}
}
}
DEF_METHOD(set_tabular, SnmpErrorStatus, SingleLevelMibModule,
SingleLevelMibModule, int id, int column, SubOID *index, size_t index_len,
SnmpVariableBinding *binding, int dry_run)
{
return NO_CREATION;
}
DEF_METHOD(finish_module, void, MibModule, SingleLevelMibModule)
{
finish_single_level_module(this);
}
MibModule *init_ip_traffic_stats_module(void)
{
SingleLevelMibModule *module = malloc(sizeof(SingleLevelMibModule));
if (module == NULL) {
return NULL;
} else if (init_single_level_module(module, IP_SYSTEM_STATS_TABLE,
IP_IF_STATS_TABLE - IP_SYSTEM_STATS_TABLE + 1,
IP_SYSTEM_STATS_REFRESH_RATE, LEAF_SCALAR, IP_IF_STATS_REFRESH_RATE)) {
free(module);
return NULL;
}
SET_PREFIX(module, SNMP_OID_IP_TRAFFIC_STATS);
SET_METHOD(module, MibModule, finish_module);
SET_METHOD(module, SingleLevelMibModule, get_scalar);
SET_METHOD(module, SingleLevelMibModule, set_scalar);
SET_METHOD(module, SingleLevelMibModule, get_tabular);
SET_METHOD(module, SingleLevelMibModule, set_tabular);
return &module->public;
}
| 31.369881 | 93 | 0.649808 |
dcd5f62ab7e096a39bde1c52174ba4b1d3a5a86a | 25,275 | h | C | examples/chat/node_modules/php-embed/src/values.h | jehovahsays/MMOSOCKETHTML5JSCHAT | 3ae5956184ee1a1b63b1a8083fd3a43edd30dffd | [
"MIT"
] | 34 | 2015-10-28T06:08:50.000Z | 2021-12-22T06:34:28.000Z | examples/chat/node_modules/php-embed/src/values.h | jehovahsays/MMOSOCKETHTML5JSCHAT | 3ae5956184ee1a1b63b1a8083fd3a43edd30dffd | [
"MIT"
] | 3 | 2016-02-15T22:09:42.000Z | 2019-10-06T23:19:01.000Z | examples/chat/node_modules/php-embed/src/values.h | jehovahsays/MMOSOCKETHTML5JSCHAT | 3ae5956184ee1a1b63b1a8083fd3a43edd30dffd | [
"MIT"
] | 6 | 2015-11-19T14:27:34.000Z | 2019-10-09T23:36:51.000Z | // Value union type for representing values in messages in an
// engine-independent manner.
// Also: a ZVal helper for managing zvals on the stack.
// Copyright (c) 2015 C. Scott Ananian <cscott@cscott.net>
#ifndef NODE_PHP_EMBED_VALUES_H_
#define NODE_PHP_EMBED_VALUES_H_
#include <cassert>
#include <cstdlib>
#include <limits>
#include <new>
#include <sstream>
#include <string>
#include "nan.h"
extern "C" {
#include "main/php.h"
#include "Zend/zend_interfaces.h" // for zend_call_method_with_*
}
#include "src/macros.h"
#include "src/node_php_jsbuffer_class.h" // ...to recognize buffers in PHP land
#include "src/node_php_jswait_class.h" // ...to recognize JsWait in PHP land
namespace node_php_embed {
// The integer size used for "object identifiers" shared between threads.
typedef uint32_t objid_t;
// Methods in JsObjectMapper are/should be accessed only from the JS thread.
// The mapper will hold persistent references to the objects for which it
// has ids.
class JsObjectMapper {
public:
virtual ~JsObjectMapper() { }
virtual objid_t IdForJsObj(const v8::Local<v8::Object> o) = 0;
virtual v8::Local<v8::Object> JsObjForId(objid_t id) = 0;
};
// Methods in PhpObjectMapper are/should be accessed only from the PHP thread.
// The mapper will hold references for the zvals it returns.
class PhpObjectMapper {
public:
virtual ~PhpObjectMapper() { }
virtual objid_t IdForPhpObj(zval *o) = 0;
// Returned value is owned by PhpObjectMapper, caller should not
// release it.
virtual zval * PhpObjForId(objid_t id TSRMLS_DC) = 0;
};
// An ObjectMapper is used by both threads, so inherits both interfaces.
class ObjectMapper : public JsObjectMapper, public PhpObjectMapper {
public:
virtual ~ObjectMapper() { }
// Allow clients to ask whether the mapper has been shut down.
virtual bool IsValid() = 0;
};
/** Allocation helper for PHP zval objects. */
class ZVal {
public:
explicit ZVal(ZEND_FILE_LINE_D) : transferred_(false) {
ALLOC_ZVAL_REL(zvalp);
INIT_ZVAL(*zvalp);
}
explicit ZVal(zval *z ZEND_FILE_LINE_DC) : zvalp(z), transferred_(false) {
if (zvalp) {
Z_ADDREF_P(zvalp);
} else {
ALLOC_ZVAL_REL(zvalp);
INIT_ZVAL(*zvalp);
}
}
explicit ZVal(ZVal &&other) // NOLINT(build/c++11)
: zvalp(other.zvalp), transferred_(other.transferred_) {
other.zvalp = NULL;
}
virtual ~ZVal() {
if (!zvalp) {
return; // Move constructor was used
} else if (transferred_) {
efree(zvalp);
} else {
zval_ptr_dtor(&zvalp);
}
}
inline zval * Ptr() const { return zvalp; }
inline zval ** PtrPtr() { return &zvalp; }
inline zval * Escape() { Z_ADDREF_P(zvalp); return zvalp; }
// Ensure an unshared copy of this value.
inline void Separate() {
assert(!transferred_);
SEPARATE_ZVAL_IF_NOT_REF(&zvalp);
}
// A static version that will work on unwrapped zval*
static inline zval *Separate(zval *z) {
SEPARATE_ZVAL_IF_NOT_REF(&z);
return z;
}
// Unwrap references protected by Js\ByRef
inline void UnwrapByRef(TSRMLS_D) {
if (!IsObject()) { return; }
assert(zvalp && !transferred_);
zend_class_entry *ce = Z_OBJCE_P(zvalp);
// XXX cache the zend_class_entry at startup so we can do a simple
// pointer comparison instead of looking at the class name
if (ce->name_length == 8 && strcmp("Js\\ByRef", ce->name) == 0) {
// Unwrap!
zval *rv;
zend_call_method_with_0_params(&zvalp, nullptr, nullptr, "getValue", &rv);
if (rv) {
zval_ptr_dtor(&zvalp);
zvalp = rv;
}
}
}
// Support a PHP calling convention where the actual zval object
// is owned by the caller, but the contents are transferred to the
// callee.
inline zval * Transfer(TSRMLS_D) {
if (IsObject()) {
zend_objects_store_add_ref(zvalp TSRMLS_CC);
} else {
transferred_ = true;
}
return zvalp;
}
inline zval * operator*() const { return Ptr(); } // Shortcut operator.
inline int Type() const { return Z_TYPE_P(zvalp); }
inline bool IsNull() const { return Type() == IS_NULL; }
inline bool IsBool() const { return Type() == IS_BOOL; }
inline bool IsLong() const { return Type() == IS_LONG; }
inline bool IsDouble() const { return Type() == IS_DOUBLE; }
inline bool IsString() const { return Type() == IS_STRING; }
inline bool IsArray() const { return Type() == IS_ARRAY; }
inline bool IsObject() const { return Type() == IS_OBJECT; }
inline bool IsResource() const { return Type() == IS_RESOURCE; }
inline bool IsUninitialized(TSRMLS_D) const {
return zvalp == EG(uninitialized_zval_ptr);
}
inline void Set(zval *z ZEND_FILE_LINE_DC) {
zval_ptr_dtor(&zvalp);
zvalp = z;
if (zvalp) {
Z_ADDREF_P(zvalp);
} else {
ALLOC_ZVAL_REL(zvalp);
INIT_ZVAL(*zvalp);
}
}
inline void SetNull() { PerhapsDestroy(); ZVAL_NULL(zvalp); }
inline void SetBool(bool b) { PerhapsDestroy(); ZVAL_BOOL(zvalp, b ? 1 : 0); }
inline void SetLong(long l) { // NOLINT(runtime/int)
PerhapsDestroy();
ZVAL_LONG(zvalp, l);
}
inline void SetDouble(double d) { PerhapsDestroy(); ZVAL_DOUBLE(zvalp, d); }
inline void SetString(const char *str, int len, bool dup) {
PerhapsDestroy();
ZVAL_STRINGL(zvalp, str, len, dup);
}
inline void SetStringConstant(const char *str) {
PerhapsDestroy();
ZVAL_STRINGL(zvalp, str, strlen(str), 0);
transferred_ = true;
}
private:
void PerhapsDestroy() {
if (!transferred_) {
zval_dtor(zvalp);
}
transferred_ = false;
}
zval *zvalp;
bool transferred_;
NAN_DISALLOW_ASSIGN_COPY(ZVal)
};
/* A poor man's tagged union, so that we can stack allocate messages
* containing values without having to pay for heap allocation.
* It also provides safe storage for values independent of the PHP or
* JS runtimes.
*/
class Value {
class Base {
public:
Base() { }
virtual ~Base() { }
virtual v8::Local<v8::Value> ToJs(JsObjectMapper *m) const = 0;
virtual void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const = 0;
/* For debugging. The returned value should not be deallocated. */
virtual const char *TypeString() const = 0;
/* For debugging purposes. Caller (implicitly) deallocates. */
virtual std::string ToString() const {
return std::string(TypeString());
}
NAN_DISALLOW_ASSIGN_COPY_MOVE(Base)
};
class Null : public Base {
public:
Null() { }
const char *TypeString() const override { return "Null"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Null());
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
RETURN_NULL();
}
};
template <class T>
class Prim : public Base {
friend class Value;
public:
explicit Prim(T value) : value_(value) { }
std::string ToString() const override {
std::stringstream ss;
ss << TypeString() << "(" << value_ << ")";
return ss.str();
}
private:
T value_;
};
class Bool : public Prim<bool> {
public:
using Prim::Prim;
const char *TypeString() const override { return "Bool"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(value_));
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
RETURN_BOOL(value_);
}
};
class Int : public Prim<int64_t> {
public:
using Prim::Prim;
const char *TypeString() const override { return "Int"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
if (value_ >= 0 && value_ <= std::numeric_limits<uint32_t>::max()) {
return scope.Escape(Nan::New((uint32_t)value_));
} else if (value_ >= std::numeric_limits<int32_t>::min() &&
value_ <= std::numeric_limits<int32_t>::max()) {
return scope.Escape(Nan::New((int32_t)value_));
}
return scope.Escape(Nan::New(static_cast<double>(value_)));
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
if (value_ >= std::numeric_limits<long>::min() && // NOLINT(runtime/int)
value_ <= std::numeric_limits<long>::max()) { // NOLINT(runtime/int)
RETURN_LONG((long)value_); // NOLINT(runtime/int)
}
RETURN_DOUBLE((double)value_);
}
};
class Double : public Prim<double> {
public:
using Prim::Prim;
const char *TypeString() const override { return "Double"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(value_));
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
RETURN_DOUBLE(value_);
}
};
enum OwnerType { NOT_OWNED, PHP_OWNED, CPP_OWNED };
class Str : public Base {
friend class Value;
protected:
const char *data_;
std::size_t length_;
virtual OwnerType Owner() const { return NOT_OWNED; }
public:
explicit Str(const char *data, std::size_t length)
: data_(data), length_(length) { }
virtual ~Str() { Destroy(); }
const char *TypeString() const override { return "Str"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::New(data_, length_).ToLocalChecked());
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
// If we ever wanted to set `dup=0`, we'd need to ensure that the
// data was null-terminated, since Buffers aren't, necessarily,
// and PHP expects null-terminated strings.
RETURN_STRINGL(data_, length_, 1);
}
std::string ToString() const override {
std::stringstream ss;
ss << TypeString() << "(" << length_ << ",";
if (length_ > 10) {
ss << std::string(data_, 7) << "...";
} else {
ss << std::string(data_, length_);
}
ss << ")";
return ss.str();
}
private:
void Destroy() {
if (data_ == nullptr) { return; }
switch (Owner()) {
case NOT_OWNED: break;
case PHP_OWNED: efree(const_cast<char*>(data_)); break;
case CPP_OWNED: delete[] data_; break;
}
data_ = nullptr;
}
};
class OStr : public Str {
// An "owned string", will copy data on creation and free it on delete.
public:
explicit OStr(const char *data, std::size_t length)
: Str(nullptr, length) {
char *ndata = new char[length + 1];
memcpy(ndata, data, length);
ndata[length] = 0;
data_ = ndata;
}
virtual ~OStr() { Destroy(); }
const char *TypeString() const override { return "OStr"; }
protected:
OwnerType Owner() const override { return CPP_OWNED; }
};
class Buf : public Str {
friend class Value;
public:
Buf(const char *data, std::size_t length) : Str(data, length) { }
virtual ~Buf() { Destroy(); }
const char *TypeString() const override { return "Buf"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::CopyBuffer(data_, length_).ToLocalChecked());
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
node_php_jsbuffer_create(return_value, data_, length_,
OwnershipType::PHP_OWNED TSRMLS_CC);
}
};
class OBuf : public Buf {
public:
OBuf(const char *data, std::size_t length) : Buf(nullptr, length) {
char *tmp = new char[length];
memcpy(tmp, data, length);
data_ = tmp;
}
virtual ~OBuf() { Destroy(); }
const char *TypeString() const override { return "OBuf"; }
protected:
OwnerType Owner() const override { return CPP_OWNED; }
};
class Obj : public Base {
objid_t id_;
public:
explicit Obj(objid_t id) : id_(id) { }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
return scope.Escape(m->JsObjForId(id_));
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
zval_ptr_dtor(&return_value);
*return_value_ptr = return_value = m->PhpObjForId(id_ TSRMLS_CC);
// The object mapper owns the reference returned, but we need a
// reference owned by the caller --- so increment reference count.
Z_ADDREF_P(return_value);
}
std::string ToString() const override {
std::stringstream ss;
ss << TypeString() << "(" << id_ << ")";
return ss.str();
}
};
class JsObj : public Obj {
public:
using Obj::Obj;
explicit JsObj(JsObjectMapper *m, v8::Local<v8::Object> o)
: Obj(m->IdForJsObj(o)) { }
const char *TypeString() const override { return "JsObj"; }
};
class PhpObj : public Obj {
public:
using Obj::Obj;
explicit PhpObj(PhpObjectMapper *m, zval *o)
: Obj(m->IdForPhpObj(o)) { }
const char *TypeString() const override { return "PhpObj"; }
};
// Wait objects are empty marker values used to indicate that
// the callee should substitute a node-style callback function
// for this value.
class Wait : public Base {
public:
Wait() { }
const char *TypeString() const override { return "Wait"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
// Default serialize as a null for safety; the MessageToJs should
// handle this specially by calling MessageToJs::MakeCallback() and
// replacing the value.
return scope.Escape(Nan::Null());
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
node_php_jswait_create(return_value TSRMLS_CC);
}
};
// Method thunks are empty marker values which are returned to
// signal that the caller should create a callback thunk.
// (That is, that the named property is a method on the PHP side.)
class MethodThunk : public Base {
public:
MethodThunk() { }
const char *TypeString() const override { return "MethodThunk"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
assert(false); /* should never reach here */
return scope.Escape(Nan::Undefined());
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
assert(false); /* should never reach here */
RETURN_NULL();
}
};
// Normally arrays are passed "by reference" between Node and PHP;
// that is, they are wrapped in proxies and the actual manipulation
// happens on the "host" side. However, for implementing certain
// messages (invocations with variable arguments, property enumeration)
// it can be useful to transfer multiple Value objects as a single
// Value. This type allows that, and it provides ToJs and ToPhp
// implementations that create appropriate "native" arrays.
// However `ArrayByValue` is never created by the `Set` methods
// which convert native values; it is only created explicitly for
// internal use.
class ArrayByValue : public Base {
friend class Value;
uint32_t length_;
Value *item_;
public:
explicit ArrayByValue(uint32_t length)
: length_(length), item_(new Value[length]) { }
virtual ~ArrayByValue() { delete[] item_; }
const char *TypeString() const override { return "ArrayByValue"; }
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const override {
Nan::EscapableHandleScope scope;
v8::Local<v8::Array> arr = Nan::New<v8::Array>(length_);
for (uint32_t i = 0; i < length_; i++) {
Nan::Set(arr, i, item_[i].ToJs(m));
}
return scope.Escape(arr);
}
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const override {
array_init(return_value);
for (uint32_t i = 0; i < length_; i++) {
ZVal item{ZEND_FILE_LINE_C};
item_[i].ToPhp(m, item TSRMLS_CC);
add_index_zval(return_value, i, item.Escape());
}
}
std::string ToString() const override {
std::stringstream ss;
ss << TypeString() << "[" << length_ << "](";
for (uint32_t i = 0; i < length_ && i < 10; i++) {
if (i > 0) { ss << ", "; }
ss << item_[i].ToString();
}
if (length_ > 10) { ss << ", ..."; }
ss << ")";
return ss.str();
}
};
public:
Value() : type_(VALUE_EMPTY), empty_(0) { }
virtual ~Value() { PerhapsDestroy(); }
explicit Value(JsObjectMapper *m, v8::Local<v8::Value> v)
: type_(VALUE_EMPTY), empty_(0) {
Set(m, v);
}
explicit Value(PhpObjectMapper *m, zval *v TSRMLS_DC)
: type_(VALUE_EMPTY), empty_(0) {
Set(m, v TSRMLS_CC);
}
void Set(JsObjectMapper *m, v8::Local<v8::Value> v) {
if (v->IsUndefined() || v->IsNull()) {
/* Fall through to the default case. */
} else if (v->IsBoolean()) {
SetBool(Nan::To<bool>(v).FromJust());
return;
} else if (v->IsInt32() || v->IsUint32()) {
SetInt(Nan::To<int64_t>(v).FromJust());
return;
} else if (v->IsNumber()) {
SetDouble(Nan::To<double>(v).FromJust());
return;
} else if (v->IsString()) {
Nan::Utf8String str(v);
if (*str) {
SetOwnedString(*str, str.length());
return;
}
} else if (node::Buffer::HasInstance(v)) {
SetOwnedBuffer(node::Buffer::Data(v), node::Buffer::Length(v));
return;
} else if (v->IsObject()) {
SetJsObject(m, Nan::To<v8::Object>(v).ToLocalChecked());
return;
}
// Null for all other object types.
SetNull();
}
inline void Set(PhpObjectMapper *m, const ZVal &z TSRMLS_DC) {
Set(m, z.Ptr() TSRMLS_CC);
}
void Set(PhpObjectMapper *m, const zval *v TSRMLS_DC) {
switch (Z_TYPE_P(v)) {
default:
case IS_NULL:
SetNull();
return;
case IS_BOOL:
SetBool(Z_BVAL_P(v));
return;
case IS_LONG:
long l; // NOLINT(runtime/int)
l = Z_LVAL_P(v);
if (l >= std::numeric_limits<int32_t>::min() &&
l <= (int64_t)std::numeric_limits<uint32_t>::max()) {
SetInt((int64_t)l);
} else {
SetDouble(static_cast<double>(l));
}
return;
case IS_DOUBLE:
SetDouble(Z_DVAL_P(v));
return;
case IS_STRING:
// Since PHP blocks, it is fine to let PHP
// own the buffer; avoids needless copying.
SetString(Z_STRVAL_P(v), Z_STRLEN_P(v));
return;
case IS_OBJECT:
// Special case for JsBuffer wrappers.
if (Z_OBJCE_P(v) == php_ce_jsbuffer) {
node_php_jsbuffer *b = reinterpret_cast<node_php_jsbuffer *>
(zend_object_store_get_object(v TSRMLS_CC));
// Since PHP blocks, it is fine to let PHP
// own the buffer; avoids needless copying.
SetBuffer(b->data, b->length);
return;
}
// Special case for JsWait objects.
if (Z_OBJCE_P(v) == php_ce_jswait) {
SetWait();
return;
}
SetPhpObject(m, v);
return;
case IS_ARRAY:
SetPhpObject(m, v);
return;
}
}
void SetEmpty() {
PerhapsDestroy();
type_ = VALUE_EMPTY;
empty_ = 0;
}
void SetNull() {
PerhapsDestroy();
type_ = VALUE_NULL;
new (&null_) Null();
}
void SetBool(bool value) {
PerhapsDestroy();
type_ = VALUE_BOOL;
new (&bool_) Bool(value);
}
void SetInt(int64_t value) {
PerhapsDestroy();
type_ = VALUE_INT;
new (&int_) Int(value);
}
void SetDouble(double value) {
PerhapsDestroy();
type_ = VALUE_DOUBLE;
new (&double_) Double(value);
}
void SetString(const char *data, std::size_t length) {
PerhapsDestroy();
type_ = VALUE_STR;
new (&str_) Str(data, length);
}
void SetOwnedString(const char *data, std::size_t length) {
PerhapsDestroy();
type_ = VALUE_OSTR;
new (&ostr_) OStr(data, length);
}
void SetBuffer(const char *data, std::size_t length) {
PerhapsDestroy();
type_ = VALUE_BUF;
new (&buf_) Buf(data, length);
}
void SetOwnedBuffer(const char *data, std::size_t length) {
PerhapsDestroy();
type_ = VALUE_OBUF;
new (&obuf_) OBuf(data, length);
}
void SetJsObject(JsObjectMapper *m, v8::Local<v8::Object> o) {
SetJsObject(m->IdForJsObj(o));
}
void SetJsObject(objid_t id) {
PerhapsDestroy();
type_ = VALUE_JSOBJ;
new (&jsobj_) JsObj(id);
}
void SetPhpObject(PhpObjectMapper *m, const zval *o) {
SetPhpObject(m->IdForPhpObj(const_cast<zval*>(o)));
}
void SetPhpObject(objid_t id) {
PerhapsDestroy();
type_ = VALUE_PHPOBJ;
new (&phpobj_) PhpObj(id);
}
void SetWait() {
PerhapsDestroy();
type_ = VALUE_WAIT;
new (&wait_) Wait();
}
void SetMethodThunk() {
PerhapsDestroy();
type_ = VALUE_METHOD_THUNK;
new (&method_thunk_) MethodThunk();
}
template<typename Func>
void SetArrayByValue(uint32_t length, Func func) {
PerhapsDestroy();
type_ = VALUE_ARRAY_BY_VALUE;
new (&array_by_value_) ArrayByValue(length);
for (uint32_t i = 0; i < length; i++) {
func(i, array_by_value_.item_[i]);
}
}
// Helper.
void SetConstantString(const char *str) {
SetString(str, strlen(str));
}
v8::Local<v8::Value> ToJs(JsObjectMapper *m) const {
return AsBase().ToJs(m);
}
// The caller owns the zval.
void ToPhp(PhpObjectMapper *m, zval *return_value,
zval **return_value_ptr TSRMLS_DC) const {
AsBase().ToPhp(m, return_value, return_value_ptr TSRMLS_CC);
}
// Caller owns the ZVal, and is responsible for freeing it.
inline void ToPhp(PhpObjectMapper *m, ZVal &z TSRMLS_DC) const {
if (!z.IsNull()) { z.SetNull(); /* deallocate previous value */ }
ToPhp(m, z.Ptr(), z.PtrPtr() TSRMLS_CC);
}
inline bool IsEmpty() const {
return (type_ == VALUE_EMPTY);
}
inline bool IsWait() const {
return (type_ == VALUE_WAIT);
}
inline bool IsMethodThunk() const {
return (type_ == VALUE_METHOD_THUNK);
}
inline bool IsArrayByValue() const {
return (type_ == VALUE_ARRAY_BY_VALUE);
}
inline Value& operator[](int i) const {
assert(IsArrayByValue());
return array_by_value_.item_[i];
}
bool AsBool() const {
switch (type_) {
case VALUE_BOOL:
return bool_.value_;
case VALUE_INT:
return int_.value_ != 0;
default:
return false;
}
}
// Convert unowned values into owned values so the caller can disappear.
void TakeOwnership() {
switch (type_) {
case VALUE_STR:
SetOwnedString(str_.data_, str_.length_);
break;
case VALUE_BUF:
SetOwnedBuffer(buf_.data_, buf_.length_);
break;
case VALUE_ARRAY_BY_VALUE:
for (uint32_t i = 0; i < array_by_value_.length_; i++) {
array_by_value_.item_[i].TakeOwnership();
}
break;
default:
break;
}
}
/* For debugging: describe the value. Caller implicitly deallocates. */
std::string ToString() const {
if (IsEmpty()) {
return std::string("Empty");
} else {
return AsBase().ToString();
}
}
private:
void PerhapsDestroy() {
if (!IsEmpty()) {
AsBase().~Base();
}
type_ = VALUE_EMPTY;
}
enum ValueTypes {
VALUE_EMPTY, VALUE_NULL, VALUE_BOOL, VALUE_INT, VALUE_DOUBLE,
VALUE_STR, VALUE_OSTR, VALUE_BUF, VALUE_OBUF,
VALUE_JSOBJ, VALUE_PHPOBJ,
VALUE_WAIT, VALUE_METHOD_THUNK, VALUE_ARRAY_BY_VALUE
} type_;
union {
int empty_; Null null_; Bool bool_; Int int_; Double double_;
Str str_; OStr ostr_; Buf buf_; OBuf obuf_;
JsObj jsobj_; PhpObj phpobj_;
Wait wait_; MethodThunk method_thunk_;
ArrayByValue array_by_value_;
};
const Base &AsBase() const {
switch (type_) {
default:
assert(false); // Should never get here.
case VALUE_NULL:
return null_;
case VALUE_BOOL:
return bool_;
case VALUE_INT:
return int_;
case VALUE_DOUBLE:
return double_;
case VALUE_STR:
return str_;
case VALUE_OSTR:
return ostr_;
case VALUE_BUF:
return buf_;
case VALUE_OBUF:
return obuf_;
case VALUE_JSOBJ:
return jsobj_;
case VALUE_PHPOBJ:
return phpobj_;
case VALUE_WAIT:
return wait_;
case VALUE_METHOD_THUNK:
return method_thunk_;
case VALUE_ARRAY_BY_VALUE:
return array_by_value_;
}
}
NAN_DISALLOW_ASSIGN_COPY_MOVE(Value)
};
} // namespace node_php_embed
#endif // NODE_PHP_EMBED_VALUES_H_
| 31.59375 | 80 | 0.631058 |
89afd99f91e16da037aee1ba639c2f97ee707726 | 3,254 | h | C | common/kernel_utils.h | intel/cm-cpu-emulation | 22f9102c8702d97c0d2a0e1864c5bf974b83752b | [
"MIT"
] | null | null | null | common/kernel_utils.h | intel/cm-cpu-emulation | 22f9102c8702d97c0d2a0e1864c5bf974b83752b | [
"MIT"
] | null | null | null | common/kernel_utils.h | intel/cm-cpu-emulation | 22f9102c8702d97c0d2a0e1864c5bf974b83752b | [
"MIT"
] | 2 | 2020-12-08T14:11:46.000Z | 2021-01-04T10:17:09.000Z | /*===================== begin_copyright_notice ==================================
Copyright (c) 2021, Intel Corporation
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.
======================= end_copyright_notice ==================================*/
#pragma once
#include <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include "os_utils.h"
#include "emu_api_export.h"
#include "emu_utils.h"
enum class CmArgumentType
{
SurfaceIndex,
Fp,
Scalar,
Invalid
};
struct KernelInfo
{
std::string signature;
void *func;
};
using Kernel2SigMap = std::unordered_map<std::string, KernelInfo>;
using CmArgTypeVector = std::vector<CmArgumentType>;
using ProgramHandle = os::SharedLibHandle;
struct ProgramInfo
{
struct KernelData
{
CmArgTypeVector args;
void* entry_point;
KernelData(void* ep, const CmArgTypeVector& arguments);
KernelData(void* ep, CmArgTypeVector&& arguments);
KernelData(const KernelData&) = delete;
KernelData(KernelData&&) = delete;
KernelData() = delete;
};
using KernelMap = std::unordered_map<std::string, KernelData>;
ProgramHandle handle = ProgramHandle();
KernelMap kernels;
GFX_EMU_API bool isValid();
};
class ProgramManager
{
public:
GFX_EMU_API ProgramInfo AddProgram(const unsigned char* const bytes, size_t size);
GFX_EMU_API bool IsProgramValid(ProgramHandle program);
GFX_EMU_API bool FreeProgram(ProgramHandle program);
GFX_EMU_API static ProgramManager& instance();
private:
GFX_EMU_API bool FreeProgramInternal(ProgramHandle program);
ProgramManager();
void Complete();
~ProgramManager() = default;
private:
std::unordered_set<ProgramHandle> m_programs;
public:
ProgramManager(const ProgramManager&) = delete;
ProgramManager(ProgramManager&&) = delete;
ProgramManager& operator=(const ProgramManager&) = delete;
};
static auto& g_shimProgramManagerInit_ = ProgramManager::instance();
GFX_EMU_API extern CmArgumentType CmArgumentTypeFromString(const std::string& s);
GFX_EMU_API extern Kernel2SigMap EnumerateKernels(os::SharedLibHandle dll);
GFX_EMU_API extern CmArgTypeVector ParseKernelSignature(const std::string &signature);
| 30.698113 | 86 | 0.728949 |
a65afd1e86dc44908149858d4c9d0f7d1139ec13 | 628 | c | C | Chapter05/Inf_Nan.c | jeffszuhay/Learn-C-Programming-Second-Edition | d668a7d9b01625879c9cfc7e7a8abf052c3ed44c | [
"MIT"
] | 12 | 2021-08-09T19:43:30.000Z | 2022-03-07T13:41:03.000Z | Chapter05/Inf_Nan.c | jeffszuhay/Learn-C-Programming-Second-Edition | d668a7d9b01625879c9cfc7e7a8abf052c3ed44c | [
"MIT"
] | null | null | null | Chapter05/Inf_Nan.c | jeffszuhay/Learn-C-Programming-Second-Edition | d668a7d9b01625879c9cfc7e7a8abf052c3ed44c | [
"MIT"
] | 7 | 2021-04-18T12:28:48.000Z | 2022-02-04T23:32:16.000Z | // Inf_Nan.c
// Chapter 5: Exploring Operators and Expressions
// Learn C Programming, 2nd Edition
//
// Program to demonstrate a complex expression
// two different ways.
// First compute the value with a complex expression.
// Then compute the value again with a sequence of simple expressions.
#include <stdio.h>
#include <math.h>
int main( void ) {
double y = 1 / 0.0;
printf( " 1 / 0.0 = %f\n" , y );
y = -1/0.0;
printf( "-1 / 0.0 = %f\n" , y );
y = log( 0 );
printf( "log( 0 ) = %f\n" , y );
y = sqrt( -1 );
printf( "Square root of -1 = %f\n" , y );
return 0;
}
// eof
| 20.258065 | 72 | 0.568471 |
f9d790d0d0bef4bd6b2a8b47e2b56c4b1fa799d6 | 69 | cats | C | data/1/174050.cats | ks2002119/EmailAnalysis | ea7b7499794061f73ac8141694833acdf813bdb3 | [
"Apache-2.0"
] | null | null | null | data/1/174050.cats | ks2002119/EmailAnalysis | ea7b7499794061f73ac8141694833acdf813bdb3 | [
"Apache-2.0"
] | null | null | null | data/1/174050.cats | ks2002119/EmailAnalysis | ea7b7499794061f73ac8141694833acdf813bdb3 | [
"Apache-2.0"
] | null | null | null | 1,1,1
2,1,1
2,2,1
2,6,1
3,1,1
3,2,1
3,6,1
3,11,1
4,2,1
4,10,1
4,11,1
| 5.75 | 6 | 0.521739 |
f9e42b48a64efeca00458f5ed76083b77e6d5c2e | 696 | h | C | ios/OnTheWay/OnTheWay/Pages/Personal/Model/OTWUserModel.h | 1259416448/android | d95421e563a91b19fe8f499d46c613ecb89663f8 | [
"Unlicense"
] | null | null | null | ios/OnTheWay/OnTheWay/Pages/Personal/Model/OTWUserModel.h | 1259416448/android | d95421e563a91b19fe8f499d46c613ecb89663f8 | [
"Unlicense"
] | null | null | null | ios/OnTheWay/OnTheWay/Pages/Personal/Model/OTWUserModel.h | 1259416448/android | d95421e563a91b19fe8f499d46c613ecb89663f8 | [
"Unlicense"
] | 1 | 2019-09-28T02:01:12.000Z | 2019-09-28T02:01:12.000Z | //
// OTWUserModel.h
// OnTheWay
//
// Created by 周扬扬 on 2017/7/11.
// Copyright © 2017年 WeiHuan. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface OTWUserModel : NSObject <NSCoding>
@property (nonatomic,copy) NSString *userId;
@property (nonatomic,copy) NSString *gender;
@property (nonatomic,copy) NSString *headImgYuan;
@property (nonatomic,copy) NSString *username;
@property (nonatomic,copy) NSString *mobilePhoneNumber;
@property (nonatomic,copy) NSString *headImg;
@property (nonatomic,copy) NSString *name;
+ (instancetype)shared;
/**
* 归档 将user对象保存到本地文件夹
*/
- (void)dump;
/**
* 取档 从本地文件夹中获取user对象
*/
- (void)load;
/**
* 清空数据
*/
- (void)logout;
@end
| 17.4 | 55 | 0.70546 |
9be503f666f9c92d340a0ff6820a5b8ecf991849 | 915 | h | C | linux-2.6.0/include/asm-ppc64/topology.h | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | 1 | 2020-11-10T12:47:02.000Z | 2020-11-10T12:47:02.000Z | linux-2.6.0/include/asm-ppc64/topology.h | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | null | null | null | linux-2.6.0/include/asm-ppc64/topology.h | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | null | null | null | #ifndef _ASM_PPC64_TOPOLOGY_H
#define _ASM_PPC64_TOPOLOGY_H
#include <linux/config.h>
#include <asm/mmzone.h>
#ifdef CONFIG_NUMA
static inline int cpu_to_node(int cpu)
{
int node;
node = numa_cpu_lookup_table[cpu];
#ifdef DEBUG_NUMA
if (node == -1)
BUG();
#endif
return node;
}
#define memblk_to_node(memblk) (memblk)
#define parent_node(node) (node)
static inline cpumask_t node_to_cpumask(int node)
{
return numa_cpumask_lookup_table[node];
}
static inline int node_to_first_cpu(int node)
{
cpumask_t tmp;
tmp = node_to_cpumask(node);
return first_cpu(tmp);
}
#define node_to_memblk(node) (node)
#define pcibus_to_cpumask(bus) (cpu_online_map)
#define nr_cpus_node(node) (nr_cpus_in_node[node])
/* Cross-node load balancing interval. */
#define NODE_BALANCE_RATE 10
#else /* !CONFIG_NUMA */
#include <asm-generic/topology.h>
#endif /* CONFIG_NUMA */
#endif /* _ASM_PPC64_TOPOLOGY_H */
| 16.636364 | 50 | 0.749727 |
da68049a8c0e7d43775d8a2f8b2365f4480e4a87 | 3,896 | c | C | GoL.c | egentry/Game_of_Life | 8c300a842d0e85dbba81f22c63af76402dc6b9f7 | [
"MIT"
] | 1 | 2016-10-30T22:07:31.000Z | 2016-10-30T22:07:31.000Z | GoL.c | egentry/Game_of_Life | 8c300a842d0e85dbba81f22c63af76402dc6b9f7 | [
"MIT"
] | null | null | null | GoL.c | egentry/Game_of_Life | 8c300a842d0e85dbba81f22c63af76402dc6b9f7 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "GoL.h"
short ** allocate_matrix(short ** matrix, int size_x, int size_y)
{
int i;
matrix = (short**) malloc(size_x * sizeof(short*));
for (i=0; i<size_x; ++i)
{
matrix[i] = (short*) malloc(size_y * sizeof(short));
}
return matrix;
}
void free_matrix(short ** matrix, int size_x, int size_y)
{
int i;
for (i=0; i<size_x; ++i)
{
free(matrix[i]);
}
free(matrix);
}
void init_matrix(short ** matrix, int size_x, int size_y, int num_guard_cells, int seed)
{
int i, j;
srand(seed);
for (i=num_guard_cells; i<size_x-num_guard_cells; ++i)
{
for (j=num_guard_cells; j<size_y-num_guard_cells; ++j)
{
matrix[i][j] = rand()%2;
}
}
return;
}
void print_matrix(short ** matrix, int size_x, int size_y)
{
int i,j;
for (i=0; i<size_x; ++i)
{
for (j=0; j<size_y; ++j)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return;
}
void dead_or_alive(short ** matrix_old, short ** matrix_new,
int size_x, int size_y, int num_guard_cells, int verbose)
{
int i,j;
for (i=num_guard_cells; i<size_x-num_guard_cells; ++i)
{
for (j=num_guard_cells; j<size_y-num_guard_cells; ++j)
{
matrix_new[i][j] = 0;
// adjacent conditions
matrix_new[i][j] += matrix_old[i-1][j];
matrix_new[i][j] += matrix_old[i][j-1];
matrix_new[i][j] += matrix_old[i+1][j];
matrix_new[i][j] += matrix_old[i][j+1];
// corner conditions
matrix_new[i][j] += matrix_old[i-1][j-1];
matrix_new[i][j] += matrix_old[i+1][j+1];
matrix_new[i][j] += matrix_old[i-1][j+1];
matrix_new[i][j] += matrix_old[i+1][j-1];
}
}
// if (verbose)
// {
// printf("neighbors matrix: \n");
// print_matrix(matrix_new, size_x, size_y);
// }
// update if cells are alive or dead
for (i=0; i<size_x; ++i)
{
for (j=0; j<size_y; ++j)
{
if (matrix_new[i][j] ==3)
{
matrix_new[i][j] = ALIVE;
}
else if (matrix_new[i][j]==2)
{
matrix_new[i][j] = matrix_old[i][j];
}
else
{
matrix_new[i][j] = DEAD;
}
}
}
return;
}
void enforce_boundary_conditions(short ** matrix, int size_x, int size_y, int num_guard_cells)
{
// enforces PERIODIC boundary conditions, including across corners
int i,j;
const int inner_valid_edge_x = num_guard_cells;
const int outer_valid_edge_x = size_x - num_guard_cells - 1;
const int inner_valid_edge_y = num_guard_cells;
const int outer_valid_edge_y = size_y - num_guard_cells - 1;
// edges
for (i=num_guard_cells; i<size_x-num_guard_cells; ++i)
{
matrix[i][inner_valid_edge_y-1] = matrix[i][outer_valid_edge_y];
matrix[i][outer_valid_edge_y+1] = matrix[i][inner_valid_edge_y];
}
for (j=num_guard_cells; j<size_y-num_guard_cells; ++j)
{
matrix[inner_valid_edge_x-1][j] = matrix[outer_valid_edge_x][j];
matrix[outer_valid_edge_x+1][j] = matrix[inner_valid_edge_x][j];
}
// corners
matrix[inner_valid_edge_x-1][inner_valid_edge_y-1] = matrix[outer_valid_edge_x][outer_valid_edge_y];
matrix[inner_valid_edge_x-1][outer_valid_edge_y+1] = matrix[outer_valid_edge_x][inner_valid_edge_y];
matrix[outer_valid_edge_x+1][inner_valid_edge_y-1] = matrix[inner_valid_edge_x][outer_valid_edge_y];
matrix[outer_valid_edge_x+1][outer_valid_edge_y+1] = matrix[inner_valid_edge_x][inner_valid_edge_y];
return;
}
void enforce_boundary_conditions_leftright(short ** matrix, int size_x, int size_y, int num_guard_cells)
{
int i,j;
const int inner_valid_edge_y = num_guard_cells;
const int outer_valid_edge_y = size_y - num_guard_cells - 1;
// edges
for (i=num_guard_cells; i<size_x-num_guard_cells; ++i)
{
matrix[i][inner_valid_edge_y-1] = matrix[i][outer_valid_edge_y];
matrix[i][outer_valid_edge_y+1] = matrix[i][inner_valid_edge_y];
}
return;
}
void swap(void **a, void **b)
{
// must be dynamically allocated array
void *tmp = *a;
*a = *b;
*b = tmp;
return;
}
| 21.289617 | 104 | 0.665811 |
fd3536b3a3e5968f752971f10e1fa460f6c14f65 | 41 | c | C | scripts/4_World/Entities/Firearms/Pistol/Makarov.c | Da0ne/DayZCommunityOfflineMode | 77ebd221a877270e704c75bcc529a7b97c918f2e | [
"MIT"
] | 1 | 2018-11-07T18:38:15.000Z | 2018-11-07T18:38:15.000Z | SourceCode/scripts/4_World/Entities/Firearms/Pistol/Makarov.c | DevulTj/DayZOfflineMode | 0ba7e58858c7cd62e6a08f451ba60a3961575353 | [
"MIT"
] | null | null | null | SourceCode/scripts/4_World/Entities/Firearms/Pistol/Makarov.c | DevulTj/DayZOfflineMode | 0ba7e58858c7cd62e6a08f451ba60a3961575353 | [
"MIT"
] | null | null | null | class MakarovIJ70_Base : Pistol_Base
{
}; | 13.666667 | 36 | 0.780488 |
a16ce98549075b570d52c3add5459e8bd5fa4c37 | 2,000 | c | C | Chap09_Functions/knkcch09e03.c | Yaachaka/C_book_solutions | c386df35701c07cae35d5511a061259de64ce005 | [
"Unlicense"
] | 1 | 2020-12-04T09:28:58.000Z | 2020-12-04T09:28:58.000Z | Chap09_Functions/knkcch09e03.c | Yaachaka/C_book_solutions | c386df35701c07cae35d5511a061259de64ce005 | [
"Unlicense"
] | null | null | null | Chap09_Functions/knkcch09e03.c | Yaachaka/C_book_solutions | c386df35701c07cae35d5511a061259de64ce005 | [
"Unlicense"
] | null | null | null | /*
@@@@ PROGRAM NAME: knkcch09e03.c
@@@@ FLAGS: -std=c99
@@@@ PROGRAM STATEMENT: Write a function gcd (m, n) that calculates
the greatest common divisor of the integers m and n. (Programming Project 2 in Chapter 6
describes Euclid’s algorithm for computing the GCD.)
*/
#include<stdio.h>
//---------------------------------------------------------------------------
int gcd(int m,int n);
//------------------------START OF MAIN()--------------------------------------
int main(void)
{
printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
int numerator,denominator,gcd_value;
printf("Enter numerator and denominator (both positive): ");
scanf("%d %d",&numerator, &denominator);
gcd_value=gcd(numerator,denominator);
printf("The GCD of %d and %d is %d",numerator,denominator,gcd_value);
printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
return 0;
}
//-------------------------END OF MAIN()---------------------------------------
int gcd(int m,int n)
{
int remainder;
do
{
remainder=m%n;
m=n;
n=remainder;
} while (remainder!=0);
return m;
}
//---------------------------------------------------------------------------
/*
OUTPUT:
@@@@ Trial1:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Enter numerator and denominator (both positive): 26 22
The GCD of 26 and 22 is 2
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@@@ Trial2:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Enter numerator and denominator (both positive): 13 15
The GCD of 13 and 15 is 1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@@@ Trial3:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Enter numerator and denominator (both positive): 32 48
The GCD of 32 and 48 is 16
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
//--------------------------------------------------------------------------- | 32.786885 | 89 | 0.3745 |
3e14b3cd62ca59dc93af60858236c474913a4d0a | 3,514 | c | C | mod_myvhost_cache.c | sshutdownow/mod-myvhost | 225d4b8ba0a18ce04ae646ca4c1704209dd91153 | [
"Apache-2.0"
] | 4 | 2015-10-05T13:46:02.000Z | 2017-01-12T12:51:20.000Z | mod_myvhost_cache.c | olegpyriy/mod-myvhost | 225d4b8ba0a18ce04ae646ca4c1704209dd91153 | [
"Apache-2.0"
] | 1 | 2017-11-14T14:59:52.000Z | 2017-11-14T14:59:52.000Z | mod_myvhost_cache.c | olegpyriy/mod-myvhost | 225d4b8ba0a18ce04ae646ca4c1704209dd91153 | [
"Apache-2.0"
] | 5 | 2016-01-25T23:22:33.000Z | 2019-04-18T18:24:20.000Z | /*
* Copyright (c) 2005-2010 Igor Popov <ipopovi@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#ifdef WITH_CACHE
#include "myvhost_include.h"
#include "mod_myvhost.h"
#include "mod_myvhost_cache.h"
static const char __unused cvsid[] = "$Id$";
p_cache_t cache_vhost_find(myvhost_cfg_t *cfg, const char *hostname)
{
p_cache_t vhost;
apr_time_t cur;
if (!cfg->cache_enabled) {
return NULL;
}
vhost = apr_hash_get(cfg->cache, hostname, APR_HASH_KEY_STRING);
if (!vhost) {
return NULL;
}
cur = apr_time_now();
if (vhost->hits > 0 && vhost->hits < 512 && vhost->access_time + 300 >= cur) {
vhost->hits++;
} else if (vhost->hits < 0 && vhost->hits > -256 && vhost->access_time + 180 >= cur) {
vhost->hits--;
} else {
apr_hash_set(cfg->cache, hostname, APR_HASH_KEY_STRING, NULL); /* delete hash entry */
vhost = NULL;
}
return vhost;
}
void cache_vhost_add(myvhost_cfg_t *cfg,
const char *hostname,
const char *root,
const char *admin,
#ifdef WITH_PHP
const char *php_ini_conf,
#endif
#ifdef WITH_UID_GID
const int uid, const int gid,
#endif
const int hits)
{
p_cache_t vhost;
if (!cfg->cache_enabled) {
return;
}
vhost = apr_pcalloc(cfg->pool, sizeof(cache_t));
vhost->access_time = apr_time_now();
vhost->root = apr_pstrdup(cfg->pool, root);
vhost->admin = apr_pstrdup(cfg->pool, admin);
#ifdef WITH_PHP
vhost->php_ini_conf = apr_pstrdup(cfg->pool, php_ini_conf);
#endif
vhost->hits = hits;
#ifdef WITH_UID_GID
vhost->uid = uid;
vhost->gid = gid;
#endif
apr_hash_set(cfg->cache, hostname, APR_HASH_KEY_STRING, vhost);
}
void cache_vhost_del(myvhost_cfg_t *cfg, apr_hash_t *cache, const char *host)
{
if (!cfg->cache_enabled) {
return;
}
apr_hash_set(cache, host, APR_HASH_KEY_STRING, NULL); /* delete hash entry */
}
/*
* apr_hash_clear appeared in apr 1.3.0
*/
#if !defined(APR_VERSION_AT_LEAST)
struct apr_hash_entry_t {
struct apr_hash_entry_t *next;
unsigned int hash;
const void *key;
apr_ssize_t klen;
const void *val;
};
struct apr_hash_index_t {
apr_hash_t *ht;
struct apr_hash_entry_t *this, *next;
unsigned int index;
};
apr_hash_index_t *hi;
#endif
/* FIXME: delete entries that is really older */
void cache_vhost_flush(myvhost_cfg_t *cfg, apr_hash_t *cache, time_t older __unused)
{
#if !defined(APR_VERSION_AT_LEAST)
apr_hash_index_t *hi;
#endif
if (!cfg->cache_enabled) {
return;
}
if (!cache) {
return;
}
#if !defined(APR_VERSION_AT_LEAST)
for (hi = apr_hash_first(NULL, cache); hi; hi = apr_hash_next(hi))
apr_hash_set(cache, hi->this->key, hi->this->klen, NULL);
#else
apr_hash_clear(cache);
#endif
}
#endif /* WITH_CACHE */
| 25.280576 | 94 | 0.640011 |
e37d6c60f4903e9da343cfe495031158cf3b2da3 | 885 | h | C | templates/inc_reduction_init.h | JumpyWizardEni/kernel_slicer | 6f8eb09797b5d2a97ff059e89c9793a2687cd0ac | [
"MIT"
] | 5 | 2020-10-29T18:00:14.000Z | 2021-07-08T14:20:41.000Z | templates/inc_reduction_init.h | JumpyWizardEni/kernel_slicer | 6f8eb09797b5d2a97ff059e89c9793a2687cd0ac | [
"MIT"
] | 1 | 2021-08-11T16:14:43.000Z | 2021-08-25T16:45:36.000Z | templates/inc_reduction_init.h | JumpyWizardEni/kernel_slicer | 6f8eb09797b5d2a97ff059e89c9793a2687cd0ac | [
"MIT"
] | 1 | 2021-11-17T19:10:34.000Z | 2021-11-17T19:10:34.000Z | {% for redvar in Kernel.SubjToRed %}
__local {{redvar.Type}} {{redvar.Name}}Shared[{{Kernel.WGSizeX}}*{{Kernel.WGSizeY}}*{{Kernel.WGSizeZ}}];
{% endfor %}
{% for redvar in Kernel.ArrsToRed %}
__local {{redvar.Type}} {{redvar.Name}}Shared[{{redvar.ArraySize}}][{{Kernel.WGSizeX}}*{{Kernel.WGSizeY}}*{{Kernel.WGSizeZ}}];
{% endfor %}
{
{% if Kernel.threadDim == 1 %}
const uint localId = get_local_id(0);
{% else %}
const uint localId = get_local_id(0) + {{Kernel.WGSizeX}}*get_local_id(1);
{% endif %}
{% for redvar in Kernel.SubjToRed %}
{{redvar.Name}}Shared[localId] = {{redvar.Init}};
{% endfor %}
{% for redvar in Kernel.ArrsToRed %}
{% for index in range(redvar.ArraySize) %}
{{redvar.Name}}Shared[{{loop.index}}][localId] = {{redvar.Init}};
{% endfor %}
{% endfor %}
}
barrier(CLK_LOCAL_MEM_FENCE); | 40.227273 | 129 | 0.60452 |
8730e13cd65fe69618a3f685f2151bc1b849f470 | 3,629 | c | C | core/shared-lib/platform/linux-sgx/bh_thread.c | oubotong/wasm-micro-runtime | dbdd1949316f0eed58e2dfcca3f080fa30897ce7 | [
"Apache-2.0"
] | null | null | null | core/shared-lib/platform/linux-sgx/bh_thread.c | oubotong/wasm-micro-runtime | dbdd1949316f0eed58e2dfcca3f080fa30897ce7 | [
"Apache-2.0"
] | 1 | 2019-08-19T20:15:48.000Z | 2019-08-21T02:50:27.000Z | core/shared-lib/platform/linux-sgx/bh_thread.c | oubotong/wasm-micro-runtime | dbdd1949316f0eed58e2dfcca3f080fa30897ce7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2019 Intel Corporation. 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.
*/
#include "bh_thread.h"
#include "bh_assert.h"
#include "bh_memory.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int _vm_thread_sys_init()
{
return 0;
}
void vm_thread_sys_destroy(void)
{
}
int _vm_thread_create_with_prio(korp_tid *tid, thread_start_routine_t start,
void *arg, unsigned int stack_size, int prio)
{
return BHT_ERROR;
// return BHT_OK;
}
int _vm_thread_create(korp_tid *tid, thread_start_routine_t start, void *arg,
unsigned int stack_size)
{
return _vm_thread_create_with_prio(tid, start, arg, stack_size,
BH_THREAD_DEFAULT_PRIORITY);
}
korp_tid _vm_self_thread()
{
return 0;
}
void vm_thread_exit(void * code)
{
}
// storage for one thread
static void *_tls_store = NULL;
void *_vm_tls_get(unsigned idx)
{
return _tls_store;
}
int _vm_tls_put(unsigned idx, void * tls)
{
_tls_store = tls;
return BHT_OK;
//return BHT_ERROR;
}
int _vm_mutex_init(korp_mutex *mutex)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_recursive_mutex_init(korp_mutex *mutex)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_mutex_destroy(korp_mutex *mutex)
{
return BHT_OK;
//return BHT_ERROR;
}
/* Returned error (EINVAL, EAGAIN and EDEADLK) from
locking the mutex indicates some logic error present in
the program somewhere.
Don't try to recover error for an existing unknown error.*/
void vm_mutex_lock(korp_mutex *mutex)
{
}
int vm_mutex_trylock(korp_mutex *mutex)
{
return BHT_OK;
//return BHT_ERROR;
}
/* Returned error (EINVAL, EAGAIN and EPERM) from
unlocking the mutex indicates some logic error present
in the program somewhere.
Don't try to recover error for an existing unknown error.*/
void vm_mutex_unlock(korp_mutex *mutex)
{
}
int _vm_sem_init(korp_sem* sem, unsigned int c)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_sem_destroy(korp_sem *sem)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_sem_wait(korp_sem *sem)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_sem_reltimedwait(korp_sem *sem, int mills)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_sem_post(korp_sem *sem)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_cond_init(korp_cond *cond)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_cond_destroy(korp_cond *cond)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_cond_wait(korp_cond *cond, korp_mutex *mutex)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_cond_reltimedwait(korp_cond *cond, korp_mutex *mutex, int mills)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_cond_signal(korp_cond *cond)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_cond_broadcast(korp_cond *cond)
{
return BHT_OK;
//return BHT_ERROR;
}
int _vm_thread_cancel(korp_tid thread)
{
return 0;
}
int _vm_thread_join(korp_tid thread, void **value_ptr, int mills)
{
return 0;
}
int _vm_thread_detach(korp_tid thread)
{
return 0;
}
| 19 | 77 | 0.708735 |
eebafb6e047046cb26ea0cc459656c28a6080cde | 262 | h | C | VideoPlayer/VideoPlayerTests/VideoPlayerTests.h | apperian/template-apps | b886ad7cea7715d991b05c039de389e983302969 | [
"MIT"
] | null | null | null | VideoPlayer/VideoPlayerTests/VideoPlayerTests.h | apperian/template-apps | b886ad7cea7715d991b05c039de389e983302969 | [
"MIT"
] | null | null | null | VideoPlayer/VideoPlayerTests/VideoPlayerTests.h | apperian/template-apps | b886ad7cea7715d991b05c039de389e983302969 | [
"MIT"
] | null | null | null | //
// VideoPlayerTests.h
// VideoPlayerTests
//
// Created by Jeremy Debate on 5/31/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <SenTestingKit/SenTestingKit.h>
@interface VideoPlayerTests : SenTestCase {
@private
}
@end
| 14.555556 | 58 | 0.71374 |
eecb5cc198c521b9780c9ec8b34122aac1005778 | 2,832 | h | C | lsyscpp/filesystem.h | smilingthax/unpdf | abe6082a59ce899362f862d7cf04765600ee1096 | [
"MIT"
] | 2 | 2015-04-21T10:01:50.000Z | 2019-06-04T22:09:23.000Z | lsyscpp/filesystem.h | smilingthax/unpdf | abe6082a59ce899362f862d7cf04765600ee1096 | [
"MIT"
] | null | null | null | lsyscpp/filesystem.h | smilingthax/unpdf | abe6082a59ce899362f862d7cf04765600ee1096 | [
"MIT"
] | null | null | null | #ifndef _FILESYSTEM_H
#define _FILESYSTEM_H
#include <string>
#include <stdexcept>
#include <unistd.h>
class FS_except : public std::exception {
public:
explicit FS_except(int errnum,const char *cmd=NULL,const char *extra=NULL) throw();
~FS_except() throw() {}
const char *what() const throw() { return errtext.c_str(); }
int err_no() const throw() { return errnum; }
private:
std::string errtext;
int errnum;
};
#ifdef _WIN32
#include <minwindef.h>
struct Win32_except : public std::runtime_error {
Win32_except(DWORD code, const char *cmd=NULL,const char *extra=NULL)
: std::runtime_error(_formatMsg(code, cmd, extra))
{ }
static std::string _formatMsg(DWORD code, const char *cmd=NULL, const char *extra=NULL);
};
#endif
namespace FS {
std::string cwd();
std::string dirname(const std::string &filename);
std::string basename(const std::string &filename);
bool exists(const std::string &filename);
bool is_file(const std::string &path);
bool is_dir(const std::string &path);
void create_dir(const std::string &dirname,bool skip_existing=false,unsigned int mode=0755); // mode is ignored on win32
inline void create_dir(const std::string &dirname,unsigned int mode) {
create_dir(dirname,false,mode);
}
void create_dirs(const std::string &dirname,unsigned int mode=0755); // mode is ignored on win32; does not support C:\... or \\server\...
std::string joinPath(const std::string &a1,const std::string &a2); // will return only a2, if absolute.
std::string joinPathRel(const std::string &a1,const std::string &a2); // will always concatenate
std::pair<std::string,std::string> extension(const std::string &filename);
int remove_all(const std::string &path); // returns number of removed entries
inline std::string abspath(const std::string &filename) { return joinPath(cwd(),filename); }
inline bool is_special_dot(const std::string &name) {
return (!name.empty())&&(name[0]=='.')&&
( (name.size()==1)||( (name[1]=='.')&&(name.size()==2) ) );
}
inline bool is_abspath(const std::string &name) {
return (!name.empty())&&(name[0]=='/');
}
#if (defined(_LARGEFILE64_SOURCE) && !defined(__x86_64__) && !defined(__ppc64__)) || defined(_WIN32)
// #if (defined _FILE_OFFSET_BITS && _FILE_OFFSET_BITS == 64) || defined _WIN32 // TODO?!
std::string humanreadable_size(off64_t size);
#endif
std::string humanreadable_size(off_t size);
struct dstat_t {
long long sum_space;
long long free_space;
// used_space=sum_space-free_space;
bool readonly;
};
dstat_t get_diskstat(const std::string &path,bool rootspace=false);
void copy_file(const std::string &from,const std::string &to,bool overwrite=false);
void move_file(const std::string &from,const std::string &to,bool overwrite=false);
} // namespace FS
#endif
| 36.307692 | 140 | 0.699859 |
eef5bcedc2563a04e167332b1ffc09caabf69162 | 3,549 | c | C | openwrt-18.06/target/linux/ar71xx/files/arch/mips/ath79/mach-som9331.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 1,144 | 2018-12-18T09:46:47.000Z | 2022-03-07T14:51:46.000Z | openwrt-18.06/target/linux/ar71xx/files/arch/mips/ath79/mach-som9331.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 16 | 2019-01-28T06:08:40.000Z | 2019-12-04T10:26:41.000Z | openwrt-18.06/target/linux/ar71xx/files/arch/mips/ath79/mach-som9331.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 129 | 2018-12-18T09:46:50.000Z | 2022-03-30T07:30:13.000Z | /*
* OpenEmbed SOM9331 board support
*
* Copyright (C) 2011 dongyuqi <729650915@qq.com>
* Copyright (C) 2011-2012 Gabor Juhos <juhosg@openwrt.org>
*
* 5/27/2016 - Modified by Allan Nick Pedrana <nik9993@gmail.com>
*
* 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.
*/
#include <linux/gpio.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-eth.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-m25p80.h"
#include "dev-usb.h"
#include "dev-wmac.h"
#include "machtypes.h"
#define SOM9331_GPIO_LED_WLAN 27
#define SOM9331_GPIO_LED_SYSTEM 0
#define SOM9331_GPIO_LED_2 13
#define SOM9331_GPIO_LED_3 14
#define SOM9331_GPIO_LED_5 16
#define SOM9331_GPIO_LED_WAN SOM9331_GPIO_LED_2
#define SOM9331_GPIO_LED_LAN1 SOM9331_GPIO_LED_3
#define SOM9331_GPIO_LED_LAN2 SOM9331_GPIO_LED_5
#define SOM9331_GPIO_BTN_RESET 11
#define SOM9331_KEYS_POLL_INTERVAL 20 /* msecs */
#define SOM9331_KEYS_DEBOUNCE_INTERVAL (3 * SOM9331_KEYS_POLL_INTERVAL)
static const char *som9331_part_probes[] = {
"tp-link",
NULL,
};
static struct flash_platform_data som9331_flash_data = {
.part_probes = som9331_part_probes,
};
static struct gpio_led som9331_leds_gpio[] __initdata = {
{
.name = "som9331:red:wlan",
.gpio = SOM9331_GPIO_LED_WLAN,
.active_low = 1,
},
{
.name = "som9331:orange:wan",
.gpio = SOM9331_GPIO_LED_WAN,
.active_low = 0,
},
{
.name = "som9331:orange:lan1",
.gpio = SOM9331_GPIO_LED_LAN1,
.active_low = 0,
},
{
.name = "som9331:orange:lan2",
.gpio = SOM9331_GPIO_LED_LAN2,
.active_low = 0,
},
{
.name = "som9331:blue:system",
.gpio = SOM9331_GPIO_LED_SYSTEM,
.active_low = 0,
},
};
static struct gpio_keys_button som9331_gpio_keys[] __initdata = {
{
.desc = "reset",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = SOM9331_KEYS_DEBOUNCE_INTERVAL,
.gpio = SOM9331_GPIO_BTN_RESET,
.active_low = 0,
}
};
static void __init som9331_setup(void)
{
u8 *mac = (u8 *) KSEG1ADDR(0x1f01fc00);
u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000);
ath79_setup_ar933x_phy4_switch(true, true);
ath79_gpio_function_disable(AR933X_GPIO_FUNC_ETH_SWITCH_LED0_EN |
AR933X_GPIO_FUNC_ETH_SWITCH_LED1_EN |
AR933X_GPIO_FUNC_ETH_SWITCH_LED2_EN |
AR933X_GPIO_FUNC_ETH_SWITCH_LED3_EN |
AR933X_GPIO_FUNC_ETH_SWITCH_LED4_EN);
ath79_register_m25p80(&som9331_flash_data);
ath79_register_leds_gpio(-1, ARRAY_SIZE(som9331_leds_gpio),
som9331_leds_gpio);
ath79_register_gpio_keys_polled(-1, SOM9331_KEYS_POLL_INTERVAL,
ARRAY_SIZE(som9331_gpio_keys),
som9331_gpio_keys);
ath79_register_usb();
ath79_init_mac(ath79_eth0_data.mac_addr, mac, 0);
ath79_init_mac(ath79_eth1_data.mac_addr, mac, -1);
ath79_register_mdio(0, 0x0);
/* LAN ports */
ath79_register_eth(1);
/* WAN port */
ath79_register_eth(0);
ath79_register_wmac(ee, mac);
}
MIPS_MACHINE(ATH79_MACH_SOM9331, "SOM9331", "OpenEmbed SOM9331", som9331_setup);
| 28.166667 | 80 | 0.65765 |
40fd260c31a66a4c1c4c3f48d0d6b1a250547067 | 777 | h | C | include/fsm/private.h | yxiong99/webtool | f7eaa202af144ac4f0ef87d0f8c69f635bd73579 | [
"Unlicense"
] | null | null | null | include/fsm/private.h | yxiong99/webtool | f7eaa202af144ac4f0ef87d0f8c69f635bd73579 | [
"Unlicense"
] | null | null | null | include/fsm/private.h | yxiong99/webtool | f7eaa202af144ac4f0ef87d0f8c69f635bd73579 | [
"Unlicense"
] | null | null | null | #ifndef _PRIVATE_H_
#define _PRIVATE_H_
#include "public.h"
//
// Private Variables
//
extern int fsm_state;
extern bool initialized;
extern bool data_sending;
/* Transition input word extern */
extern uint32_t fsm_trans_input;
/* Input word processing function prototype */
void fsm_process_inputs(void);
/* Entry action prototypes */
void init_state_entry(void);
void idle_state_entry(void);
void send_state_entry(void);
/* Activity function prototypes */
void init_state_act(void);
void idle_state_act(void);
void send_state_act(void);
/* Exit action prototypes */
void send_state_exit(void);
/* Transition action prototypes */
void idle_state_to_send_state1(void);
void send_state_to_send_state2(void);
#endif /* _PRIVATE_H_ */
| 21 | 47 | 0.7426 |
8cea880f5dee17d187319267eaa6d491cf8cda14 | 1,548 | h | C | libsel4platsupport/src/timer_common.h | GaloisInc/seL4_libs | da16411463cdeb3188ba47f5cc620aa479de9530 | [
"BSD-2-Clause"
] | null | null | null | libsel4platsupport/src/timer_common.h | GaloisInc/seL4_libs | da16411463cdeb3188ba47f5cc620aa479de9530 | [
"BSD-2-Clause"
] | null | null | null | libsel4platsupport/src/timer_common.h | GaloisInc/seL4_libs | da16411463cdeb3188ba47f5cc620aa479de9530 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2017, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(DATA61_BSD)
*/
#ifndef _SEL4PLATSUPPORT_TIMER_INTERNAL_H
#define _SEL4PLATSUPPORT_TIMER_INTERNAL_H
#include <vspace/vspace.h>
#include <vka/vka.h>
#include <simple/simple.h>
#include <sel4platsupport/timer.h>
/**
*
* Some of our timers require 1 irq, 1 frame and an notification.
*
* If this is true, timers can do most of their sel4 based init with this function.
*
* @param irq_number the irq that the timer needs a cap for.
* @param paddr the paddr that the timer needs mapped in.
* @param notification the badged notification object that the irq should be delivered to.
*/
seL4_timer_t *timer_common_init(vspace_t *vspace, simple_t *simple,
vka_t *vka, seL4_CPtr notification, uint32_t irq_number, void *paddr);
/*
* clean up functions
*/
void timer_common_destroy_frame(seL4_timer_t *timer, vka_t *vka, vspace_t *vspace);
void timer_common_destroy(seL4_timer_t *timer, vka_t *vka, vspace_t *vspace);
void timer_common_cleanup_irq(vka_t *vka, seL4_CPtr irq);
void timer_common_handle_irq(seL4_timer_t *timer, uint32_t irq);
int timer_common_init_frame(seL4_timer_t *timer, vspace_t *vspace, vka_t *vka, uintptr_t paddr);
#endif /* _SEL4PLATSUPPORT_TIMER_INTERNAL_H */
| 32.25 | 109 | 0.74677 |
86f1ffe2081622c722ae3f57dbfe0326fe19d7a0 | 1,745 | h | C | src/app/modelloader.h | jackeri/ModelTool | 8484ca275ee00919c4a3a09c5b17f00be0deb8e0 | [
"MIT"
] | null | null | null | src/app/modelloader.h | jackeri/ModelTool | 8484ca275ee00919c4a3a09c5b17f00be0deb8e0 | [
"MIT"
] | null | null | null | src/app/modelloader.h | jackeri/ModelTool | 8484ca275ee00919c4a3a09c5b17f00be0deb8e0 | [
"MIT"
] | null | null | null | #pragma once
#include "mt.h"
#include "model.h"
#include "filesystem.h"
#include <unordered_map>
namespace mt::model {
using ModelLoaderMap = std::unordered_map<std::string, const std::function<Model *(const Ref<IO::MTFile> &)>>;
using AnimationLoaderMap = std::unordered_map<std::string, const std::function<void(Model *,
const Ref<IO::MTFile> &)>>;
/*! Static loader class for centralized model and animation loading, multiple loaders can be registered for use */
class ModelLoader {
public:
/**
* load and parse a model file
* @param file file instance to parse
* @return Model instance or nullptr if the loading fails
*/
static Model *loadModel(const Ref<IO::MTFile> &file);
/**
* load and parse a model file
* @param file file instance to parse
* @return Model instance of nullptr if the loading fails
*/
static Ref<Model> loadModel_ref(const Ref<IO::MTFile> &file);
/**
* load and parse an animation file
* @param parent parent model to which to load the animation information
* @param file file instance to parse
*/
static void loadAnimation(Model *parent, const Ref<IO::MTFile> &file);
/**
* load and parse an animation file
* @param parent parent model to which to load the animation information
* @param file file instance to parse
*/
static void loadAnimation(const Ref<Model> &parent, const Ref<IO::MTFile> &file);
private:
ModelLoader() = default;
/**
* Init the model and animation loaders
*/
static void init();
static ModelLoaderMap m_modelLoaders; ///< List of available model loaders with extensions
static AnimationLoaderMap m_animationLoaders; ///< List of available animation loaders with extensions
};
}
| 30.614035 | 115 | 0.699713 |
87d59383af42d4d6070774cb07e8993d78a1000a | 201 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/torture/pr71987.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/torture/pr71987.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/torture/pr71987.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* PR tree-optimization/71987 */
int a, b, *c, *d;
short fn1 (int p1)
{
return a ? p1 : a;
}
void fn2 ()
{
int e, *f = &e;
b = fn1 (d != &e);
c = f;
}
int main ()
{
fn2 ();
return 0;
}
| 9.136364 | 32 | 0.452736 |
7b70530266f6338d5cd97b267dcd7e3b7e661a8d | 1,334 | h | C | disabledCode/MGInsider/RemoteConsole.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | 1 | 2018-03-18T16:29:16.000Z | 2018-03-18T16:29:16.000Z | disabledCode/MGInsider/RemoteConsole.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | null | null | null | disabledCode/MGInsider/RemoteConsole.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | null | null | null | /*
* Generated by cppsrc.sh
* On
* by Paweu
*/
/*--END OF HEADER BLOCK--*/
#pragma once
#ifndef RemoteConsole_H
#define RemoteConsole_H
#include <Shared/MoonGlareInsider/Api.h>
namespace InsiderApi = MoonGlare::Debug::InsiderApi;
#include "RemoteConsoleObserver.h"
class RemoteConsoleObserver;
using SharedRemoteConsoleObserver = std::shared_ptr < RemoteConsoleObserver >;
enum class RemoteConsoleState {
Unknown,
NotStarted,
Starting,
Ready,
Working,
Broken,
Stopping,
};
class RemoteConsole : public QObject {
Q_OBJECT;
public:
static RemoteConsole* get();
RemoteConsoleState GetState();
void Delete();
void RequestTimedout(SharedRemoteConsoleObserver observer);
void MakeRequest(SharedRemoteConsoleObserver observer);
void ExecuteCode(const QString &code);
signals:
void StateChanged(RemoteConsoleState state);
protected:
RemoteConsole();
~RemoteConsole();
bool Initialize();
bool Finalize();
void SetState(RemoteConsoleState st);
void ProcessMessage(InsiderApi::InsiderMessageBuffer &buffer);
void ProcessSelfMessage(InsiderApi::InsiderMessageBuffer &buffer);
private slots:
void DataReady();
void Tick();
private:
std::unique_ptr<QTimer> m_TickTimer;
struct Impl;
std::unique_ptr<Impl> m_Impl;
};
inline RemoteConsole& GetRemoteConsole() { return *RemoteConsole::get(); }
#endif
| 20.84375 | 78 | 0.768366 |
f456c29cc2ee395f91b058f5569e1771b68406c3 | 9,760 | c | C | svmpredict.c | Leven1113/Prediction-Model-for-Brain-Glioma-Image-Segmentation- | 7c79a10c53f385e9abec83f0a934431f4a320642 | [
"BSD-3-Clause"
] | null | null | null | svmpredict.c | Leven1113/Prediction-Model-for-Brain-Glioma-Image-Segmentation- | 7c79a10c53f385e9abec83f0a934431f4a320642 | [
"BSD-3-Clause"
] | null | null | null | svmpredict.c | Leven1113/Prediction-Model-for-Brain-Glioma-Image-Segmentation- | 7c79a10c53f385e9abec83f0a934431f4a320642 | [
"BSD-3-Clause"
] | 1 | 2022-01-16T03:24:14.000Z | 2022-01-16T03:24:14.000Z | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "mex.h"
#include "svm.h"
#include "svm_model_matlab.h"
struct svm_node *x_space;
void exit_with_help()
{
mexPrintf(
"Usage: [predict_label, accuracy] = svmpredict(testing_label_matrix, testing_instance_matrix, model, 'libsvm_options')\n"
"libsvm_options:\n"
"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n"
);
}
void matlab_matrix_to_model(struct svm_model *model, mxArray **input_array)
{
int mrows, ncols;
int total_l, feature_number;
int i, j, n;
double *ptr;
bool bpredict_probability;
int id = 0;
model->rho = NULL;
model->probA = NULL;
model->probB = NULL;
model->label = NULL;
model->nSV = NULL;
ptr = mxGetPr(input_array[id]);
model->param.svm_type = (int)ptr[0];
model->param.kernel_type = (int)ptr[1];
model->param.degree = ptr[2];
model->param.gamma = ptr[3];
model->param.coef0 = ptr[4];
id++;
ptr = mxGetPr(input_array[id]);
model->nr_class = (int)ptr[0];
id++;
ptr = mxGetPr(input_array[id]);
model->l = (int)ptr[0];
id++;
// rho
n = model->nr_class * (model->nr_class-1)/2;
model->rho = (double*) malloc(n*sizeof(double));
ptr = mxGetPr(input_array[id]);
for(i=0;i<n;i++)
model->rho[i] = ptr[i];
id++;
// label
if (mxIsEmpty(input_array[id]) == 0)
{
model->label = (int*) malloc(model->nr_class*sizeof(int));
ptr = mxGetPr(input_array[id]);
for(i=0;i<model->nr_class;i++)
model->label[i] = (int)ptr[i];
}
id++;
// probA, probB
if(mxIsEmpty(input_array[id]) == 0 &&
mxIsEmpty(input_array[id+1]) == 0)
{
model->probA = (double*) malloc(n*sizeof(double));
model->probB = (double*) malloc(n*sizeof(double));
ptr = mxGetPr(input_array[id]);
for(i=0;i<n;i++)
model->probA[i] = ptr[i];
ptr = mxGetPr(input_array[id+1]);
for(i=0;i<n;i++)
model->probB[i] = ptr[i];
}
id += 2;
// nSV
if (mxIsEmpty(input_array[id]) == 0)
{
model->nSV = (int*) malloc(model->nr_class*sizeof(int));
ptr = mxGetPr(input_array[id]);
for(i=0;i<model->nr_class;i++)
model->nSV[i] = (int)ptr[i];
}
id++;
// sv_coef
ptr = mxGetPr(input_array[id]);
model->sv_coef = (double**) malloc((model->nr_class-1)*sizeof(double));
for( i=0 ; i< model->nr_class -1 ; i++ )
model->sv_coef[i] = (double*) malloc((model->l)*sizeof(double));
for(i = 0; i < model->nr_class - 1; i++)
for(j = 0; j < model->l; j++)
model->sv_coef[i][j] = ptr[i*(model->l)+j];
id++;
// SV
{
int sr, sc, elements;
int num_samples, num_ir, num_jc;
int *ir, *jc, *tmp_row_index;
int tmp_index_sum, tmp_jc_num, pr_ir_index;
sr = mxGetM(input_array[id]);
sc = mxGetN(input_array[id]);
ptr = mxGetPr(input_array[id]);
ir = mxGetIr(input_array[id]);
jc = mxGetJc(input_array[id]);
num_jc = sc + 1;
num_samples = num_ir = jc[num_jc-1];
elements = num_samples + sr;
model->SV = (struct svm_node **) malloc(sr * sizeof(struct svm_node *));
x_space = (struct svm_node *)malloc(elements * sizeof(struct svm_node));
tmp_row_index = (int *)malloc(sr * sizeof(int));
memset(tmp_row_index, 0, sr * sizeof(int));
for(i = 0; i < num_ir; i++)
tmp_row_index[ir[i]]++;
for(i = tmp_index_sum = 0; i < sr; i++) {
model->SV[i] = &x_space[tmp_index_sum];
tmp_index_sum += (tmp_row_index[i] + 1);
x_space[tmp_index_sum - 1].index = -1;
}
pr_ir_index = 0;
memset(tmp_row_index, 0, sr * sizeof(int));
for(i = 1; i < num_jc; i++)
{
tmp_jc_num = jc[i] - jc[i-1];
for(j = 0; j < tmp_jc_num; j++)
{
model->SV[ir[pr_ir_index]][tmp_row_index[ir[pr_ir_index]]].index = i;
model->SV[ir[pr_ir_index]][tmp_row_index[ir[pr_ir_index]]].value = ptr[pr_ir_index];
tmp_row_index[ir[pr_ir_index]]++;
pr_ir_index++;
}
}
free(tmp_row_index);
id++;
}
}
void read_sparse_instance(const mxArray *prhs[], int index, struct svm_node *x)
{
int sr, sc, *ir, *jc, i, j;
int num_samples, num_ir, num_jc, x_index;
int low, mid, high;
double *samples;
sr = mxGetM(prhs[1]);
sc = mxGetN(prhs[1]);
samples = mxGetPr(prhs[1]);
ir = mxGetIr(prhs[1]);
jc = mxGetJc(prhs[1]);
num_samples = num_ir = mxGetNzmax(prhs[1]);
num_jc = sc + 1;
for(i = x_index = 0; i < num_jc - 1; i++)
{
low = jc[i], high = jc[i+1] - 1, mid = (low+high)/2;
while(low <= high)
{
if(ir[mid] == index)
{
x[x_index].index = i + 1;
x[x_index].value = samples[mid];
x_index++;
break;
}
else if(ir[mid] > index)
high = mid - 1;
else
low = mid + 1;
mid = (low+high)/2;
}
}
x[x_index].index = -1;
}
void predict(mxArray *plhs[], const mxArray *prhs[], struct svm_model *model, const int predict_probability)
{
int instance_matrix_row_num, instance_matrix_col_num;
int type_matrix_row_num, type_matrix_col_num;
int feature_number, testing_instance_number;
int i, j, instance_index;
int matrix_width;
double *ptr_instance, *ptr_type, *ptr_predict_type, *ptr;
struct svm_node *x;
int correct = 0;
int total = 0;
int svm_type=svm_get_svm_type(model);
int nr_class=svm_get_nr_class(model);
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
double target,v;
double *prob_estimates=NULL;
int *labels=(int *) malloc(nr_class*sizeof(int));
//prhs[1] = testing instance vectors
feature_number = instance_matrix_col_num = mxGetN(prhs[1]);
testing_instance_number = instance_matrix_row_num = mxGetM(prhs[1]);
type_matrix_row_num = mxGetM(prhs[0]);
type_matrix_col_num = mxGetN(prhs[0]);
if(type_matrix_row_num!=instance_matrix_row_num)
{
mexPrintf("prhs[1](Instance)'s row number should be the same as prhs[0](Type)'s row number, but not.\n");
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
return;
}
if(type_matrix_col_num!=1)
{
mexPrintf("prhs[0](Type)'s col number should be 1, but not.\n");
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
return;
}
ptr_instance = mxGetPr(prhs[1]);
ptr_type = mxGetPr(prhs[0]);
if(predict_probability)
{
if(svm_type==NU_SVR || svm_type==EPSILON_SVR)
mexPrintf("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\n",svm_get_svr_probability(model));
else
prob_estimates = (double *) malloc(nr_class*sizeof(double));
}
if(predict_probability && (svm_type==C_SVC || svm_type==NU_SVC))
plhs[0] = mxCreateDoubleMatrix(testing_instance_number, 1+nr_class, mxREAL);
else
plhs[0] = mxCreateDoubleMatrix(testing_instance_number, 1, mxREAL);
ptr_predict_type = mxGetPr(plhs[0]);
x = (struct svm_node*)malloc((feature_number+1)*sizeof(struct svm_node) );
for(instance_index=0;instance_index<testing_instance_number;instance_index++)
{
target = ptr_type[instance_index];
if(mxIsSparse(prhs[1]))
read_sparse_instance(prhs, instance_index, x);
else
{
for(i=0;i<feature_number;i++)
{
x[i].index = i+1;
x[i].value = ptr_instance[testing_instance_number*i+instance_index];
}
x[feature_number].index = -1;
}
if(predict_probability && (svm_type==C_SVC || svm_type==NU_SVC))
{
v = svm_predict_probability(model, x, prob_estimates);
ptr_predict_type[instance_index] = v;
for(i=1;i<=nr_class;i++)
ptr_predict_type[instance_index + i * testing_instance_number] = prob_estimates[i-1];
}
else
{
v = svm_predict(model,x);
ptr_predict_type[instance_index] = v;
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
mexPrintf("Accuracy = %g%% (%d/%d) (classification)\n",
(double)correct/total*100,correct,total);
mexPrintf("Mean squared error = %g (regression)\n",error/total);
mexPrintf("Squared correlation coefficient = %g (regression)\n",
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))
);
// return accuracy, mean squared error, squared correlation coefficient
plhs[1] = mxCreateDoubleMatrix(3, 1, mxREAL);
ptr = mxGetPr(plhs[1]);
ptr[0] = (double)correct/total*100;
ptr[1] = error/total;
ptr[2] = ((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy));
free(x);
if(predict_probability)
{
if(prob_estimates != NULL)
free(prob_estimates);
free(labels);
}
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
int i, num_of_cell_elements, prob_estimate_flag;
struct svm_model *model;
mxArray **rhs;
char option[2048], *tmp_option;
model = (struct svm_model *) malloc(sizeof(struct svm_model));
if(nrhs > 4 || nrhs < 3){
exit_with_help();
return;
}
if(mxIsCell(prhs[2]))
{
num_of_cell_elements = mxGetNumberOfElements(prhs[2]);
rhs = (mxArray **) malloc(sizeof(mxArray *)*num_of_cell_elements);
for(i=0;i<num_of_cell_elements;i++)
rhs[i] = mxGetCell(prhs[2], i);
matlab_matrix_to_model(model, rhs);
prob_estimate_flag = 0;
// option -b
if(nrhs==4)
{
mxGetString(prhs[3], option, mxGetN(prhs[3])+1);
tmp_option = strtok(option, " ");
if(strcmp(tmp_option, "-b"))
{
mexPrintf("The option should be -b\n");
return;
}
tmp_option = strtok(NULL, " ");
prob_estimate_flag = atoi(tmp_option);
if(prob_estimate_flag==1 && (model->probA==NULL || model->probB==NULL))
{
mexPrintf("There is no probability estimate model in the model file.\n");
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
return;
}
}
predict(plhs, prhs, model, prob_estimate_flag);
// destroy model
svm_destroy_model(model);
}
else
mexPrintf("model file should be a cell array\n");
return;
}
| 25.820106 | 170 | 0.651537 |
4c56a0f6fc68cc02e19adfc06bc6384c9a5627e2 | 719 | h | C | include/iris/core/utils.h | irisengine/iris | 0deb12f5d00c67bf0dde1a702344a2cf73925db6 | [
"BSL-1.0"
] | 85 | 2021-10-16T14:58:23.000Z | 2022-03-26T11:05:37.000Z | include/iris/core/utils.h | MaximumProgrammer/iris | cbc2f571bd8d485cdd04f903dcb867e699314682 | [
"BSL-1.0"
] | null | null | null | include/iris/core/utils.h | MaximumProgrammer/iris | cbc2f571bd8d485cdd04f903dcb867e699314682 | [
"BSL-1.0"
] | 2 | 2021-10-17T16:57:13.000Z | 2021-11-14T19:11:30.000Z | ////////////////////////////////////////////////////////////////////////////////
// Distributed under the Boost Software License, Version 1.0. //
// (See accompanying file LICENSE or copy at //
// https://www.boost.org/LICENSE_1_0.txt) //
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <cstdint>
namespace iris
{
/**
* Compare two floating point numbers using a scaling epsilon.
*
* @param a
* First float.
*
* @param b
* Second float.
*
* @returns
* True if both floats are equal (within an epsilon), false otherwise.
*/
bool compare(float a, float b);
}
| 24.793103 | 80 | 0.438108 |
1eff6b06d3a7c2eeb4b4bc3fe8503418b4a645b7 | 72,228 | c | C | test/test_mm.c | christianb93/ctOS | 644d92636b4fa2d9d355ce20c59cd567a5579ae4 | [
"MIT"
] | 19 | 2018-08-13T18:35:53.000Z | 2022-01-19T10:21:50.000Z | test/test_mm.c | christianb93/ctOS | 644d92636b4fa2d9d355ce20c59cd567a5579ae4 | [
"MIT"
] | 4 | 2018-05-07T20:57:15.000Z | 2018-06-16T18:37:50.000Z | test/test_mm.c | christianb93/ctOS | 644d92636b4fa2d9d355ce20c59cd567a5579ae4 | [
"MIT"
] | 5 | 2020-03-15T20:37:47.000Z | 2022-02-25T13:35:54.000Z | /*
* test_mm.c
* Unit tests for memory manager
*
* The main difficulty when setting up unit tests for the manager arises from the fact that
* in a normal environment, the kernel will find the page tables themselves mapped at a given
* location into the virtual address space, which is not the case in a unit test environment. To
* deal with this, the function get_pt_address which the memory manager itself uses to access
* a page table is stubbed here. Two different modes are possible:
* 1) we keep track of all page tables within the address space and return the address of
* the respective page table in the stub (set the flag pg_enabled_override to 1 for this). An example
* for this method is the setup used for testcase 2
* 2) when a page table is requested, we return the address stored as physical address in the
* page table directory (pg_enabled_override=0)
*
* Another important setup step - at least when functions which call mm_get_ptd are tested - is to
* set the variable test_ptd to the location of the page table directory. The easiest way to do this
* is to use the variable cr3. Remember that one of the steps done by mm_init_page_tables is to put
* the physical address of the page table directory into CR3 by calling put_cr3. In our stub for put_cr3,
* we copy the passed address into the static variable cr3 so that we can create a pointer to the page
* table directory from this address
*
* Finally most test cases require that the stub for mm_get_phys_page is prepared to deliver a given number
* of physical pages and simulate an out-of-memory condition if more pages are requested. This is done by
* the utility function setup_phys_pages
*/
#include "kunit.h"
#include "mm.h"
#include "vga.h"
#include "locks.h"
#include "lists.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int mm_map_page(pte_t* pd, u32 phys_base, u32 virtual_base, u8 rw,
u8 us, u8 pcd, u32 pid);
extern void mm_init_page_tables();
extern int mm_validate_address_spaces();
extern void mm_init_address_spaces();
extern int mm_clone_ptd(pte_t* source_ptd, pte_t* target_ptd,
u32 phys_target_ptd);
extern int __mm_log;
/*
* Stubs
*/
static int do_putchar = 0;
void win_putchar(win_t* win, u8 c) {
if (do_putchar)
printf("%c", c);
}
void debug_main(ir_context_t* ir_context) {
}
static int panic = 0;
void trap() {
panic = 1;
}
int params_get_int(char* name) {
if (0 == strcmp("heap_validate", name))
return 1;
else
return 0;
}
void debug_getline(void* c, int n) {
}
int multiboot_get_next_mmap_entry(memory_map_entry_t* next) {
return 0;
}
int multiboot_locate_ramdisk(multiboot_ramdisk_info_block_t* ramdisk_info_block) {
return 0;
}
/*
* Stub for pm functions
*/
int pm_get_pid() {
return 0;
}
int do_kill(int pid, int signal) {
return 0;
}
int pm_get_pid_for_task_id(u32 task_id) {
return 0;
}
static int my_task_id = 0;
int pm_get_task_id() {
return my_task_id;
}
int smp_get_cpu() {
return 0;
}
/*
* This is a bitmask describing usage of physical memory
* A set bit indicates that the page is in use
*/
static u8 phys_mem[MM_PHYS_MEM_PAGES / 8];
/*
* Stub for mm_get_phys_page. We keep a repository of
* PHYS_MAX_PAGES pages which are returned one at a time
* by this function
*/
#define PHYS_PAGES_MAX 512
static u32 phys_page[PHYS_PAGES_MAX];
static int mm_get_phys_page_called = 0;
u32 mm_get_phys_page_stub() {
u32 page;
if (mm_get_phys_page_called >= PHYS_PAGES_MAX)
return 0;
page = phys_page[mm_get_phys_page_called];
mm_get_phys_page_called++;
BITFIELD_SET_BIT(phys_mem, MM_PAGE(page));
return page;
}
static u32 last_released_page = 0;
void mm_put_phys_page_stub(u32 page) {
last_released_page = page;
BITFIELD_CLEAR_BIT(phys_mem, MM_PAGE(page));
}
/*
* Stub for mm_get_ptd. By setting the variable test_ptd,
* the function can be made to point to a given test page
* table directory so that all access of code in mm.c to the
* page table directory of the current process is diverted to
* this test ptd
*/
static pte_t* test_ptd = 0;
pte_t* mm_get_ptd_stub() {
return test_ptd;
}
pte_t* (*mm_get_ptd_orig)();
pte_t* mm_get_ptd_for_pid_stub() {
return test_ptd;
}
/*
* Utility function to translate a virtual into a physical address
* Assumes that virtual and physical addresses are identical for all
* page table addresses
* Sets errno if no mapping was possible
*/
static u32 virt_to_phys(pte_t* ptd, u32 virtual, int* errno) {
u32 ptd_offset;
u32 pt_offset;
pte_t* pt;
ptd_offset = virtual >> 22;
pt_offset = (virtual >> 12) & 1023;
*errno = 0;
if (0 == ptd[ptd_offset].p) {
*errno = 1;
return 0;
}
/* At this point, we assume that the virtual address
* of the page table is equal to its physical address
* - to be ensured by test setup
*/
pt = (pte_t*) (ptd[ptd_offset].page_base << 12);
if (0 == pt[pt_offset].p) {
*errno = 2;
return 0;
}
return (virtual % 4096) + (pt[pt_offset].page_base << 12);
}
/*
* Deliver end of kernel bss section
*/
u32 mm_get_bss_end_stub() {
return 0x111200;
}
/*
* Stub for mm_get_pt_address. This stub can operate in two modes
* 1) if pg_enabled_override = 0 or paging is disabled, the function
* will return the physical base address as stored in the ptd
* 2) otherwise the function will simply return the value
* of the static variable next_pt_address
*/
static pte_t* next_pt_address;
static int pg_enabled_override = 1;
pte_t* mm_get_pt_address_stub(pte_t* ptd, int ptd_offset, int pg_enabled) {
if ((pg_enabled == 0) || (0 == pg_enabled_override)) {
return (pte_t*) (ptd[ptd_offset].page_base * MM_PAGE_SIZE);
}
return next_pt_address;
}
/*
* Stub for mm_attach_page
*/
u32 mm_attach_page_stub(u32 phys_page) {
return phys_page;
}
/*
* Stub for mm_detach_page
*/
void mm_detach_page_stub(u32 phys_page) {
}
/*
* Stub for mm_copy_page
*/
static pte_t* root_ptd = 0;
int mm_copy_page_stub(u32 virtual_source, u32 physical_target) {
int errno;
if (root_ptd) {
memcpy((void*) physical_target, (void*) virt_to_phys(root_ptd,
virtual_source, &errno), 4096);
}
return 0;
}
/*
* Stubs for locking operations. We maintain the counter cpulocks
* to check that all locks have been released at some point
*/
int cpulocks = 0;
void spinlock_get(spinlock_t* lock, u32* flags) {
cpulocks++;
}
void spinlock_release(spinlock_t* lock, u32* flags) {
cpulocks--;
}
void spinlock_init(spinlock_t* lock) {
}
/*
* Dummy for invalidation of TLB
*/
void invlpg(u32 virtual_address) {
}
/*
* Stub for writing into CR3
*/
static u32 cr3 = 0;
void put_cr3(u32 _cr3) {
cr3 = _cr3;
}
/*
* Stub for access to CR0
*/
static int paging_enabled = 0;
u32 get_cr0() {
return paging_enabled << 31;
}
/*
* Declaration of function pointers inside mm.c
*/
extern u32 (*mm_get_phys_page)();
extern void (*mm_put_phys_page)(u32 page);
extern pte_t* (*mm_get_pt_address)(pte_t* ptd, int ptd_offset, int pg_enabled);
extern u32 (*mm_get_bss_end)();
extern u32 (*mm_attach_page)(u32);
extern void (*mm_detach_page)(u32);
extern int (*mm_copy_page)(u32, u32);
extern pte_t* (*mm_get_ptd)();
extern pte_t* (*mm_get_ptd_for_pid)(u32);
/*
* Utility function to validate whether the physical
* pages pointed to by two page table entries
* have the same content
*/
int validate_page_content(pte_t* a, pte_t* b) {
char* base_a;
char* base_b;
u32 ptr;
base_a = (char*) (a->page_base * 4096);
base_b = (char*) (b->page_base * 4096);
for (ptr = 0; ptr < 4096; ptr++)
if (base_a[ptr] != base_b[ptr])
return 1;
return 0;
}
/*
* Utility function to validate a process
* address space after it has been cloned
* Parameter:
* @source_ptd - pointer to source page table directory
* @target_ptd - pointer to target page table directory
* @stack_base - address of lowest page in stack of current task
* @stack_top - address of highest page in stack of current task
*/
static int validate_address_space(pte_t* source_ptd, pte_t* target_ptd,
u32 stack_base, u32 stack_top) {
int i;
u32 page;
u32 ptd_offset;
u32 pt_offset;
pte_t* source_pt;
pte_t* target_pt;
int errno;
/*
* For the first MM_SHARED_PAGE_TABLES entries, verify that entries in source and target coincide
*/
for (i = 0; i < MM_SHARED_PAGE_TABLES; i++) {
ASSERT(source_ptd[i].p==target_ptd[i].p);
ASSERT(source_ptd[i].page_base==target_ptd[i].page_base);
ASSERT(source_ptd[i].pcd==target_ptd[i].pcd);
ASSERT(source_ptd[i].pwt==target_ptd[i].pwt);
ASSERT(source_ptd[i].rw==target_ptd[i].rw);
ASSERT(source_ptd[i].us==target_ptd[i].us);
}
/* Go through all pages within user space
* and the kernel stack area and verify that
* - they are mapped
* - on the level of PTD entries, the attributes are the same as in the source
* - on the level of PT entries, the attributes are the same as in the source
* - the physical base address of source and target are not the same
* - the physical pages pointed to by both page table entries have identical content
*/
for (page = MM_PT_ENTRIES * MM_PAGE_SIZE * MM_SHARED_PAGE_TABLES; page
<=MM_VIRTUAL_TOS_USER; page += 4096) {
ptd_offset = page >> 22;
pt_offset = (page >> 12) & 1023;
ASSERT(target_ptd[ptd_offset].p==source_ptd[ptd_offset].p);
if (1 == source_ptd[ptd_offset].p) {
ASSERT(source_ptd[ptd_offset].pcd==target_ptd[ptd_offset].pcd);
ASSERT(source_ptd[ptd_offset].pwt==target_ptd[ptd_offset].pwt);
ASSERT(source_ptd[ptd_offset].rw==target_ptd[ptd_offset].rw);
ASSERT(source_ptd[ptd_offset].us==target_ptd[ptd_offset].us);
source_pt = mm_get_pt_address_stub(source_ptd, ptd_offset, 0);
target_pt = mm_get_pt_address_stub(target_ptd, ptd_offset, 0);
ASSERT(source_pt[pt_offset].p==target_pt[pt_offset].p);
if (1 == source_pt[pt_offset].p) {
ASSERT(source_pt[pt_offset].pcd==target_pt[pt_offset].pcd);
ASSERT(source_pt[pt_offset].rw==target_pt[pt_offset].rw);
ASSERT(source_pt[pt_offset].pwt==target_pt[pt_offset].pwt);
ASSERT(source_pt[pt_offset].us==target_pt[pt_offset].us);
ASSERT(source_pt[pt_offset].page_base!=target_pt[pt_offset].page_base);
ASSERT(validate_page_content(source_pt+pt_offset, target_pt+pt_offset)==0);
}
}
}
/* Test that
* - a mapping for the kernel stack of the currently active task has been set up
* - all physical pages for the kernel stack have been copied over
* - the highest 4 MB of the virtual address space point to the page tables, i.e. the entry 1023 in the
* PTD points to the PTD itself
* - the page immediately below 0xffc0:0000 is mapped to the PTD
*
*/
for (page
= MM_PAGE_START(MM_PAGE(MM_VIRTUAL_TOS-MM_STACK_PAGES_TASK*MM_PAGE_SIZE+1)); page
<= MM_VIRTUAL_TOS; page += 4096) {
ptd_offset = page >> 22;
pt_offset = (page >> 12) & 1023;
if ((page < stack_base) || (page > stack_top)) {
continue;
}
ASSERT(target_ptd[ptd_offset].p==1);
ASSERT(source_ptd[ptd_offset].pcd==target_ptd[ptd_offset].pcd);
ASSERT(source_ptd[ptd_offset].pwt==target_ptd[ptd_offset].pwt);
ASSERT(source_ptd[ptd_offset].rw==target_ptd[ptd_offset].rw);
ASSERT(source_ptd[ptd_offset].us==target_ptd[ptd_offset].us);
source_pt = mm_get_pt_address_stub(source_ptd, ptd_offset, 0);
target_pt = mm_get_pt_address_stub(target_ptd, ptd_offset, 0);
ASSERT(source_pt[pt_offset].p==1);
ASSERT(source_pt[pt_offset].pcd==target_pt[pt_offset].pcd);
ASSERT(source_pt[pt_offset].rw==target_pt[pt_offset].rw);
ASSERT(source_pt[pt_offset].pwt==target_pt[pt_offset].pwt);
ASSERT(source_pt[pt_offset].us==target_pt[pt_offset].us);
ASSERT(source_pt[pt_offset].page_base!=target_pt[pt_offset].page_base);
}
ASSERT(target_ptd[1023].page_base == (((u32) target_ptd)/4096) );
return 0;
}
/*
* Utility function to set up the stub for physical page
* allocation. This function will malloc sufficient pages and
* set up the array phys_pages accordingly
* Parameter:
* @nr_of_pages - number of pages to reserve
*/
static u32 setup_phys_pages(int nr_of_pages) {
u32 my_base;
int i;
u32 my_mem = (u32) malloc((nr_of_pages + 2) * 4096);
if (nr_of_pages >= PHYS_PAGES_MAX) {
printf("Header file has been changed, please correct test setup!\n");
exit(1);
}
my_base = (my_mem / 4096) * 4096 + 4096;
for (i = 0; i <= nr_of_pages; i++)
phys_page[i] = my_base + i * 4096;
for (i = nr_of_pages + 1; i < PHYS_PAGES_MAX; i++)
phys_page[i] = 0;
return my_mem;
}
/*
* Testcase 1
* Function: mm_map_page
* Testcase: Map a page, starting with an empty page table directory, paging disabled
* Expected result: a new page table is allocated and an entry is added
*/
int testcase1() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
pte_t* pt;
/* This is the page we are going to deliver
* to the function when a physical page
* is requested
*/
char __attribute__ ((aligned(4096))) page[4096];
u32 virtual = 0xa1230000;
u32 physical = 0xbedf0000;
u32 ptd_offset;
u32 pt_offset;
int i;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) ptd)[i] = 0;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
(page)[i] = 0;
/* Set up stub for physical page allocation */
mm_get_phys_page = mm_get_phys_page_stub;
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
phys_page[0] = (u32) page;
phys_page[1] = 0;
/* Set up stub for read access to CR0 */
paging_enabled = 0;
/* And call function */
mm_map_page(ptd, physical, virtual, 1, 1, 1, 0);
/*
* Now validate result
* We expect that
* - a new entry has been added to the page table directory at offset given by virtual
* - the present bit of this entry is one
* - the entry points to the test page on our stack
* - the entry in the page table has present bit set to one
* - the entry in the page table points to the correct physical address
*/
ptd_offset = virtual >> 22;
pt_offset = (virtual >> 12) & 1023;
ASSERT(1==ptd[ptd_offset].p);
ASSERT((u32) page==(ptd[ptd_offset].page_base<<12));
pt = (pte_t*) page;
ASSERT(1==pt[pt_offset].p);
ASSERT(physical==(pt[pt_offset].page_base<<12));
ASSERT(0==cpulocks);
return 0;
}
/*
* Testcase 2
* Function: mm_map_page
* Testcase: Map a page, starting with an empty page table directory, paging enabled
* Expected result: a new page table is allocated and an entry is added
*/
int testcase2() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
pte_t* pt;
/*
* This is our test page table which we are going to
* present to mm_map_page via the stubbed version of
* mm_get_pt_address
*/
char __attribute__ ((aligned(4096))) page[4096];
u32 virtual = 0xa1230000;
u32 physical = 0xbedf0000;
u32 phys_page_table = (u32) page;
u32 ptd_offset;
u32 pt_offset;
int i;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
(page)[i] = 0;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) ptd)[i] = 0;
/*
* Set up stub for physical page allocation
* We use an address different from the virtual address
* as this address is not used except to generate the PTD entry
*/
mm_get_phys_page = mm_get_phys_page_stub;
mm_get_phys_page_called = 0;
phys_page[0] = phys_page_table;
phys_page[1] = 0;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/* Set up stub for translation of PTD entry
* to pointer.
* In this setup, we know that only one page table is
* used. We therefore divert all access to this page table
* to the array page declared above (set pg_enabled_override=1).
* Thus the function mm_map_page which is under test here will access
* this memory area when adding entries to the page table and we can
* run our verifications against this area as well.
*/
mm_get_pt_address = mm_get_pt_address_stub;
next_pt_address = (pte_t*) page;
pg_enabled_override = 1;
mm_map_page(ptd, physical, virtual, 1, 1, 1, 0);
/*
* Now validate result
* We expect that
* - a new entry has been added to the page table directory at offset given by virtual
* - the present bit of this entry is one
* - the entry points to the test page on our stack
* - the entry in the page table has present bit set to one
* - the entry in the page table points to the correct physical address
*/
ptd_offset = virtual >> 22;
pt_offset = (virtual >> 12) & 1023;
ASSERT(1==ptd[ptd_offset].p);
ASSERT(phys_page_table==(ptd[ptd_offset].page_base<<12));
pt = (pte_t*) page;
ASSERT(1==pt[pt_offset].p);
ASSERT(physical==(pt[pt_offset].page_base<<12));
ASSERT(0==cpulocks);
return 0;
}
/*
* Testcase 3
* Function: mm_map_page
* Testcase: Map a page while paging still disabled, page table entry in ptd exists
* Expected result: a new entry is added to the page table, no new physical page is allocated
*/
int testcase3() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
pte_t __attribute__ ((aligned(4096))) pt[1024];
u32 virtual = 0xa1230000;
u32 physical = 0xbedf0000;
u32 ptd_offset = virtual >> 22;
u32 pt_offset = (virtual >> 12) & 1023;
int i;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) ptd)[i] = 0;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) pt)[i] = 0;
/*
* Create entry in PTD so that we do not start with an empty PTD
*/
ptd[ptd_offset] = pte_create(1, 0, 0, (u32) pt);
/* Set up stub for physical page allocation
* We set next_phys_page to zero as we do not expect any allocations
* */
mm_get_phys_page = mm_get_phys_page_stub;
mm_get_phys_page_called = 0;
phys_page[0] = 0;
/* Set up stub for read access to CR0 */
paging_enabled = 0;
/* Do test call */
mm_map_page(ptd, physical, virtual, 1, 1, 1, 0);
/*
* Now validate result
* We expect that
* - an entry has been added to the page table
* - the entry in the page table has present bit set to one
* - the entry in the page table points to the correct physical address
* - no new physical page has been requested
*/
ASSERT(1==pt[pt_offset].p);
ASSERT(physical==(pt[pt_offset].page_base<<12));
ASSERT(0==mm_get_phys_page_called);
ASSERT(0==cpulocks);
return 0;
}
/*
* Testcase 4
* Function: mm_map_page
* Testcase: Map a page, page table entry in ptd exists, paging enabled
* Expected result: a new entry is added to the page table, no new physical page is allocated
*/
int testcase4() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
pte_t __attribute__ ((aligned(4096))) pt[1024];
u32 virtual = 0xa1230000;
u32 physical = 0xbedf0000;
u32 ptd_offset = virtual >> 22;
u32 pt_offset = (virtual >> 12) & 1023;
int i;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) ptd)[i] = 0;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) pt)[i] = 0;
/*
* Create entry in PTD so that we do not start with an empty PTD
*/
ptd[ptd_offset] = pte_create(1, 0, 0, (u32) pt);
/* Set up stub for physical page allocation
* We set next_phys_page to zero as we do not expect any allocations
* */
mm_get_phys_page = mm_get_phys_page_stub;
mm_get_phys_page_called = 0;
phys_page[0] = 0;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/* Set up stub for translation of PTD entry
* to pointer
*/
mm_get_pt_address = mm_get_pt_address_stub;
next_pt_address = pt;
pg_enabled_override = 1;
/* Do test call */
mm_map_page(ptd, physical, virtual, 1, 1, 1, 0);
/*
* Now validate result
* We expect that
* - an entry has been added to the page table
* - the entry in the page table has present bit set to one
* - the entry in the page table points to the correct physical address
* - no additional physical page has been requested
*/
ASSERT(1==pt[pt_offset].p);
ASSERT(physical==(pt[pt_offset].page_base<<12));
ASSERT(0==mm_get_phys_page_called);
ASSERT(0==cpulocks);
return 0;
}
/*
* Testcase 5
* Function: mm_init_page_tables
* Test initialization of paging
*/
int testcase5() {
/*
* Set up stub for mm_get_phys_page
* In total, we need 1 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK = 7 physical pages
* all of them aligned to page boundaries
*/
int errno;
u32 my_base;
int i;
pte_t* ptd;
u32 phys;
int nr_of_pages = 1 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/* Set up stub for read access to CR0 */
paging_enabled = 0;
/* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file. With this method, the course of events is as follows
* 1) Initially, the page table directory is empty
* 2) when a new mapping is requested, mm_map_page will allocate a new physical page
* via a call to mm_get_phys_page for the page table
* 3) it will then add an entry to the page table directory which contains the physical address
* of this page table
* 4) when it calls mm_get_pt_address, our stub kicks in and simply returns a pointer to this
* physical address
* Essentially, we simulate the case that all page tables are contained in an area in memory
* which is mapped one-to-one
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/* and call function */
mm_init_page_tables();
/*
* Now do the following checks:
* - exactly nr_of_pages physical pages have been allocated
* - cr3 has been loaded
* - the first MM_SHARED_PAGE_TABLES entries within the page table directory are
* pointing to existing page tables
* - the first virtual pages up to the end of the kernel BSS section are mapped one-to-one
* - the highest 4 MB of the virtual address space point to the page tables, i.e. the entry 1023 in the
* PTD points to the PTD itself
* - the page immediately below 0xffc0:0000 is mapped to the PTD
* - MM_STACK_PAGES_TASK are allocated immediately below MM_VIRTUAL_TOS
*/
ASSERT(nr_of_pages==mm_get_phys_page_called);
ASSERT(cr3);
ptd = (pte_t*) cr3;
for (i = 0; i < MM_SHARED_PAGE_TABLES; i++)
ASSERT(1==ptd[i].p);
/* Now check 1-1 mapping of kernel memory */
i = 0;
while (i * 4096 < mm_get_bss_end_stub()) {
phys = virt_to_phys(ptd, i * 4096, &errno);
ASSERT(phys==i*4096);
ASSERT(0 == errno);
i++;
}
/* Check mapping of PTD and page tables */
ASSERT(1==ptd[1023].p);
ASSERT(ptd[1023].page_base == (((u32) ptd)/4096) );
/* Check that kernel stack is mapped somewhere */
u32 stack_base = (MM_VIRTUAL_TOS / 4096) * 4096 - (MM_STACK_PAGES_TASK - 1)
* 4096;
for (i = stack_base; i < MM_VIRTUAL_TOS; i += 4096)
ASSERT(virt_to_phys(ptd, i, &errno));
free((void*) my_mem);
ASSERT(0==cpulocks);
return 0;
}
/*
* Testcase 6
* Tested function: mm_clone_ptd
* Testcase: verify that the address space is correctly cloned
*/
int testcase6() {
pte_t __attribute__ ((aligned(4096))) target_ptd[1024];
pte_t* source_ptd;
u32 my_base;
int i;
u32 stack_top_page = (MM_VIRTUAL_TOS / MM_PAGE_SIZE) * MM_PAGE_SIZE;
u32 stack_bottom_page = stack_top_page - (MM_STACK_PAGES_TASK - 1)
* MM_PAGE_SIZE;
/*
* Zero out target PTD
*/
memset((void*) target_ptd, 0, 4096);
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_page_tables();
mm_init_address_spaces();
source_ptd = (pte_t*) cr3;
/* Set up stub for mm_copy_page */
root_ptd = source_ptd;
mm_copy_page = mm_copy_page_stub;
/* Now clone */
mm_clone_ptd(source_ptd, target_ptd, (u32) target_ptd);
ASSERT(0==validate_address_space(source_ptd, target_ptd, stack_bottom_page, stack_top_page));
ASSERT(0==cpulocks);
free((void*) my_mem);
return 0;
}
/*
* Testcase 7
* Tested function: mm_clone
* Testcase: clone a process with only one task
*/
int testcase7() {
pte_t* source_ptd;
pte_t* target_ptd;
u32 my_base;
int i;
u32 stack_top_page = (MM_VIRTUAL_TOS / MM_PAGE_SIZE) * MM_PAGE_SIZE;
u32 stack_bottom_page = stack_top_page - (MM_STACK_PAGES_TASK - 1)
* MM_PAGE_SIZE;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
source_ptd = (pte_t*) cr3;
/* Set up stub for mm_copy_page */
root_ptd = source_ptd;
mm_copy_page = mm_copy_page_stub;
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
/*
* Clone
*/
target_ptd = (pte_t*) mm_clone(1, 1);
ASSERT(target_ptd);
ASSERT(0==validate_address_space(test_ptd, target_ptd, stack_bottom_page, stack_top_page));
free((void*) my_mem);
return 0;
}
/*
* Testcase 8
* Tested function: mm_reserve_task_stack
* Testcase: verify that the return value
* is different from zero and mapped
*/
int testcase8() {
int errno;
u32 page;
u32 tos;
pte_t __attribute__ ((aligned(4096))) target_ptd[1024];
int i;
u32 my_base;
/*
* Zero out target PTD
*/
memset((void*) target_ptd, 0, 4096);
u32 my_mem = setup_phys_pages(8);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
/*
* Set up stub for mm_get_ptd
*/
test_ptd = target_ptd;
mm_get_ptd = mm_get_ptd_stub;
mm_init_address_spaces();
tos = mm_reserve_task_stack(1, 0, &page);
/*
* Validate return values
*/
ASSERT(MM_STACK_PAGES_TASK==page);
ASSERT(tos);
ASSERT(0==((tos+1) % MM_PAGE_SIZE));
/*
* Validate mapping
*/
ASSERT(virt_to_phys(target_ptd, tos, &errno));
ASSERT(virt_to_phys(target_ptd, tos-4096, &errno));
virt_to_phys(target_ptd, tos - page * 4096, &errno);
ASSERT(errno);
ASSERT(0==cpulocks);
/*
* Validate data structures
*/
ASSERT(0==mm_validate_address_spaces());
free((void*) my_mem);
return 0;
}
/*
* Testcase 9
* Tested function: mm_reserve_task_stack
* Testcase: add two stack allocators
*/
int testcase9() {
int errno;
u32 page;
u32 tos1, tos2;
pte_t __attribute__ ((aligned(4096))) target_ptd[1024];
int i;
u32 my_base;
/*
* Zero out target PTD
*/
memset((void*) target_ptd, 0, 4096);
/*
* Set up memory - we have 12 pages available
*/
u32 my_mem = setup_phys_pages(12);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
paging_enabled = 1;
/*
* Set up stub for mm_get_ptd
*/
test_ptd = target_ptd;
mm_get_ptd = mm_get_ptd_stub;
mm_init_address_spaces();
ASSERT(0==mm_validate_address_spaces());
tos1 = mm_reserve_task_stack(1, 0, &page);
/*
* Validate return values
*/
ASSERT(MM_STACK_PAGES_TASK==page);
ASSERT(tos1);
ASSERT(0==((tos1+1) % MM_PAGE_SIZE));
/*
* Validate mapping
*/
ASSERT(virt_to_phys(target_ptd, tos1, &errno));
ASSERT(virt_to_phys(target_ptd, tos1-4096, &errno));
virt_to_phys(target_ptd, tos1 - page * 4096, &errno);
ASSERT(errno);
/*
* Get second allocator
*/
tos2 = mm_reserve_task_stack(1, 0, &page);
ASSERT(tos2);
ASSERT(tos2>tos1);
ASSERT(virt_to_phys(target_ptd, tos2, &errno));
ASSERT(virt_to_phys(target_ptd, tos2-4096, &errno));
ASSERT(0==cpulocks);
/*
* Validate data structures
*/
ASSERT(0==mm_validate_address_spaces());
free((void*) my_mem);
return 0;
}
/*
* Testcase 10
* Tested function: mm_reserve_task_stack
* Testcase: add stack allocators until stack is filled up
*/
int testcase10() {
int errno;
u32 page;
u32 tos;
u32 tos_old;
pte_t __attribute__ ((aligned(4096))) target_ptd[1024];
int i;
u32 my_base;
int pages;
int allocations;
/*
* Zero out target PTD
*/
memset((void*) target_ptd, 0, 4096);
/*
* Set up memory
*/
u32 my_mem = setup_phys_pages(PHYS_PAGES_MAX - 1);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
paging_enabled = 1;
/*
* Set up stub for mm_get_ptd
*/
test_ptd = target_ptd;
mm_get_ptd = mm_get_ptd_stub;
mm_init_address_spaces();
ASSERT(0==mm_validate_address_spaces());
/*
* Setup done
* Our stack area has MM_STACK_PAGES in total. Initially, we have used the top
* MM_STACK_PAGES_TASK for the first kernel stack. Each new allocation requires
* MM_STACK_PAGES_TASK + MM_STACK_PAGES_GAP pages. So we can do
* (MM_STACK_PAGES - MM_STACK_PAGES_TASK) / (MM_STACK_PAGES_TASK + MM_STACK_PAGES_GAP)
* allocations
*/
allocations = (MM_STACK_PAGES - MM_STACK_PAGES_TASK) / (MM_STACK_PAGES_TASK
+ MM_STACK_PAGES_GAP);
tos = 0;
for (i = 0; i < allocations; i++) {
tos_old = tos;
tos = mm_reserve_task_stack(i + 1,0, &pages);
ASSERT(tos);
ASSERT(tos > tos_old);
}
tos = mm_reserve_task_stack(i + 1, 0, &pages);
ASSERT(0==mm_validate_address_spaces());
ASSERT(0==tos);
free((void*) my_mem);
return 0;
}
/*
* Testcase 11
* Tested function: mm_clone
* Testcase: clone a process with two tasks
* and make sure that only one task is copied
* Active task is task 0
*/
int testcase11() {
pte_t* source_ptd;
pte_t* target_ptd;
u32 my_base;
u32 tos;
int i;
int errno;
u32 pages;
u32 stack_top_page = (MM_VIRTUAL_TOS / MM_PAGE_SIZE) * MM_PAGE_SIZE;
u32 stack_bottom_page = stack_top_page - (MM_STACK_PAGES_TASK - 1)
* MM_PAGE_SIZE;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
paging_enabled = 1;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
source_ptd = (pte_t*) cr3;
/* Set up stub for mm_copy_page */
root_ptd = source_ptd;
mm_copy_page = mm_copy_page_stub;
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
/*
* Create an additional stack area for a new task
*/
tos = mm_reserve_task_stack(1, 0, &pages);
ASSERT(tos);
ASSERT(virt_to_phys(source_ptd, tos, &errno));
/*
* Clone
*/
target_ptd = (pte_t*) mm_clone(1, 2);
ASSERT(target_ptd);
ASSERT(0==validate_address_space(test_ptd, target_ptd, stack_bottom_page, stack_top_page));
/*
* Validate stack allocators
*/
ASSERT(0==mm_validate_address_spaces());
/*
* Verify that stack area of second task has not been cloned
*/
ASSERT(0==virt_to_phys(target_ptd, tos, &errno));
/*
* Verify that stack area of first task has been cloned
*/
for (i = 0; i < MM_STACK_PAGES_TASK; i++)
ASSERT(virt_to_phys(target_ptd, stack_bottom_page+i*MM_PAGE_SIZE, &errno));
free((void*) my_mem);
return 0;
}
/*
* Testcase 12
* Tested function: mm_clone
* Testcase: clone a process with two tasks
* and make sure that only one task is copied
* Active task is task 1
*/
int testcase12() {
pte_t* source_ptd;
pte_t* target_ptd;
u32 my_base;
u32 tos;
int i;
int errno;
u32 pages;
u32 stack_top_page = (MM_VIRTUAL_TOS / MM_PAGE_SIZE) * MM_PAGE_SIZE;
u32 stack_bottom_page = stack_top_page - (MM_STACK_PAGES_TASK - 1)
* MM_PAGE_SIZE;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
paging_enabled = 1;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
source_ptd = (pte_t*) cr3;
/* Set up stub for mm_copy_page */
root_ptd = source_ptd;
mm_copy_page = mm_copy_page_stub;
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
/*
* Create an additional stack area for a new task
* this will be task 1
*/
tos = mm_reserve_task_stack(1, 0, &pages);
ASSERT(tos);
ASSERT(virt_to_phys(source_ptd, tos, &errno));
/*
* Switch to task 1
*/
my_task_id = 1;
/*
* Clone
*/
target_ptd = (pte_t*) mm_clone(1, 2);
ASSERT(target_ptd);
ASSERT(0==validate_address_space(test_ptd, target_ptd,
tos+1-MM_PAGE_SIZE*MM_STACK_PAGES_TASK, tos-(MM_PAGE_SIZE-1)));
/*
* Validate stack allocators
*/
ASSERT(0==mm_validate_address_spaces());
/*
* Verify that stack area of first task has not been cloned
*/
ASSERT(0==virt_to_phys(target_ptd, stack_bottom_page, &errno));
/*
* Verify that stack area of first task has been cloned
*/
for (i = 0; i < MM_STACK_PAGES_TASK; i++)
ASSERT(virt_to_phys(target_ptd, tos+1-MM_PAGE_SIZE*MM_STACK_PAGES_TASK+i*MM_PAGE_SIZE, &errno));
free((void*) my_mem);
return 0;
}
/*
* Testcase 13
* Test memory layout constants for consistency
*/
int testcase13() {
/*
* Validate that the start of the page tables
* in virtual memory plus the size of the page tables
* is exactly the end of the virtual 32 bit address space
*/
u32 page_tables_start = MM_VIRTUAL_PT_ENTRY(0,0);
ASSERT((page_tables_start + MM_PT_ENTRIES*sizeof(pte_t)*MM_PT_ENTRIES)==0);
/*
* Validate that the top of the kernel stack plus 1 is page aligned
*/
ASSERT(((MM_VIRTUAL_TOS+1) % MM_PAGE_SIZE)==0);
/*
* Validate that the top of the kernel stack plus one
* is the bottom of the last special page
*/
ASSERT(MM_VIRTUAL_TOS+1+MM_RESERVED_PAGES*MM_PAGE_SIZE==page_tables_start);
/*
* Validate that the top of the user space stack plus 1 is the bottom of
* the kernel stack
*/
ASSERT(MM_VIRTUAL_TOS+1-MM_PAGE_SIZE*MM_STACK_PAGES==MM_VIRTUAL_TOS_USER+1);
/*
* Validate that MM_MEMIO_PAGE_TABLES fits into MM_SHARED_PAGE_TABLES
*/
ASSERT(MM_MEMIO_PAGE_TABLES < MM_SHARED_PAGE_TABLES);
/*
* Verify that the lowest address within user space is below the top
* of the user stack
*/
ASSERT(MM_COMMON_AREA_SIZE<MM_VIRTUAL_TOS_USER);
/*
* Make sure that stack is also above start of code section
*/
ASSERT(MM_START_CODE<MM_VIRTUAL_TOS_USER);
/*
* Make sure that MM_HIGH_MEM_START is correctly set
*/
ASSERT(MM_HIGH_MEM_START==1024*1024);
return 0;
}
/*
* Testcase 14
* Function: mm_unmap_page
* Testcase: Map a page, then unmap it again
* Expected result: after unmapping the page, no translation takes place any more
*/
int testcase14() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
pte_t* pt;
/*
* Here we use a similar setup as in test case 2
*/
char __attribute__ ((aligned(4096))) page[4096];
u32 virtual = 0xa1230000;
u32 physical = 0xbedf0000;
u32 phys_page_table = (u32) page;
u32 ptd_offset;
u32 pt_offset;
int i;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
(page)[i] = 0;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) ptd)[i] = 0;
/* Set up stub for physical page allocation
* We use an address different from the virtual address
* as this address is not used except to generate the PTD entry
*/
mm_get_phys_page = mm_get_phys_page_stub;
mm_get_phys_page_called = 0;
phys_page[0] = phys_page_table;
phys_page[1] = 0;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/*
* Set up stub for translation of PTD entry
* to pointer. We divert page table access
* to our test page
*/
mm_get_pt_address = mm_get_pt_address_stub;
next_pt_address = (pte_t*) page;
pg_enabled_override = 1;
/*
* First map page and validate that mapping worked
*/
mm_map_page(ptd, physical, virtual, 1, 1, 1, 0);
ptd_offset = virtual >> 22;
pt_offset = (virtual >> 12) & 1023;
ASSERT(1==ptd[ptd_offset].p);
ASSERT(phys_page_table==(ptd[ptd_offset].page_base<<12));
pt = (pte_t*) page;
ASSERT(1==pt[pt_offset].p);
ASSERT(physical==(pt[pt_offset].page_base<<12));
ASSERT(0==cpulocks);
/*
* Set up stub for mm_put_phys_page
*/
mm_put_phys_page = mm_put_phys_page_stub;
/*
* Then remove page again
*/
mm_unmap_page(ptd, virtual);
/*
* And verify that mapping has become invalid
* and that page has been returned
*/
ASSERT(0==pt[pt_offset].p);
ASSERT(last_released_page==physical);
return 0;
}
/*
* Testcase 15
* Tested function: mm_release_task_stack
* Testcase: verify that the virtual memory mapping for a
* task stack is reverted
*/
int testcase15() {
int errno;
u32 page;
u32 tos;
pte_t __attribute__ ((aligned(4096))) target_ptd[1024];
int i;
u32 my_base;
/*
* Zero out target PTD
*/
memset((void*) target_ptd, 0, 4096);
u32 my_mem = setup_phys_pages(8);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/*
* Set up stub for translation.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
/*
* Set up stub for mm_get_ptd and for mm_get_ptd_for_pid
*/
test_ptd = target_ptd;
mm_get_ptd = mm_get_ptd_stub;
mm_get_ptd_for_pid = mm_get_ptd_for_pid_stub;
mm_init_address_spaces();
tos = mm_reserve_task_stack(1, 0, &page);
/*
* Validate return values
*/
ASSERT(MM_STACK_PAGES_TASK==page);
ASSERT(tos);
ASSERT(0==((tos+1) % MM_PAGE_SIZE));
/*
* Validate mapping
*/
ASSERT(virt_to_phys(target_ptd, tos, &errno));
ASSERT(virt_to_phys(target_ptd, tos-4096, &errno));
virt_to_phys(target_ptd, tos - page * 4096, &errno);
ASSERT(errno);
ASSERT(0==cpulocks);
/*
* Validate data structures
*/
ASSERT(0==mm_validate_address_spaces());
/*
* Now call mm_release_task_stack and verify that mapping
* has been removed
*/
ASSERT(0==mm_release_task_stack(1, 0));
errno = 0;
virt_to_phys(target_ptd, tos, &errno);
ASSERT(errno);
errno = 0;
virt_to_phys(target_ptd, tos - 4096, &errno);
ASSERT(errno);
ASSERT(0==mm_validate_address_spaces());
/*
* Now verify that we can again reserve the stack region
*/
ASSERT(tos == mm_reserve_task_stack(1, 0, &page));
free((void*) my_mem);
return 0;
}
/*
* Testcase 16
* Tested function: mm_map_user_segment
* Testcase: add two pages in user space
*/
int testcase16() {
u32 my_base;
int errno;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
* and page table access
*/
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Remove stub for mm_get_ptd!!!
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_orig;
/*
* Setup done. Now request two pages in user space
*/
ASSERT(MM_START_CODE==mm_map_user_segment(MM_START_CODE, MM_START_CODE+2*MM_PAGE_SIZE-1));
/*
* verify that they have been mapped
*/
ASSERT(virt_to_phys(test_ptd, MM_START_CODE, &errno));
ASSERT(virt_to_phys(test_ptd, MM_START_CODE+MM_PAGE_SIZE, &errno));
return 0;
}
/*
* Testcase 17
* Tested function: mm_init_user_area
* Testcase: verify that pages for the stack have been added
*/
int testcase17() {
u32 my_base;
int errno;
u32 page;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
/*
* Setup done. Now initialize user ara
*/
ASSERT(MM_VIRTUAL_TOS_USER-3==mm_init_user_area());
/*
* verify that pages for the user space stack have been mapped
*/
for (page = MM_VIRTUAL_TOS_USER - 4095; page > MM_VIRTUAL_TOS_USER + 1
- MM_STACK_PAGES_TASK * MM_PAGE_SIZE; page -= 4096) {
ASSERT(virt_to_phys(test_ptd, page, &errno));
}
return 0;
}
/*
* Testcase 18
* Tested function: mm_teardown_user_area
* Testcase: verify that all pages within the user area have been released
*/
int testcase18() {
u32 my_base;
int errno;
u32 page;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
/*
* Setup done. Now initialize user area
*/
ASSERT(MM_VIRTUAL_TOS_USER-3==mm_init_user_area());
/*
* verify that pages for the user space stack have been mapped
*/
for (page = MM_VIRTUAL_TOS_USER - 4095; page > MM_VIRTUAL_TOS_USER + 1
- MM_STACK_PAGES_TASK * MM_PAGE_SIZE; page -= 4096) {
ASSERT(virt_to_phys(test_ptd, page, &errno));
}
/*
* Next we add two pages to the code segment and verify that the mapping
* was successful
*/
ASSERT(MM_START_CODE==mm_map_user_segment(MM_START_CODE, MM_START_CODE+2*MM_PAGE_SIZE-1));
/*
* verify that they have been mapped
*/
ASSERT(virt_to_phys(test_ptd, MM_START_CODE, &errno));
ASSERT(virt_to_phys(test_ptd, MM_START_CODE+MM_PAGE_SIZE, &errno));
/*
* Now the actual test starts. We call mm_teardown_user_area and then check
* that all the pages above are no longer mapped
*/
mm_teardown_user_area();
for (page = MM_VIRTUAL_TOS_USER - 4095; page > MM_VIRTUAL_TOS_USER + 1
- MM_STACK_PAGES_TASK * MM_PAGE_SIZE; page -= 4096) {
ASSERT(0==virt_to_phys(test_ptd, page, &errno));
}
ASSERT(0==virt_to_phys(test_ptd, MM_START_CODE, &errno));
ASSERT(0==virt_to_phys(test_ptd, MM_START_CODE+MM_PAGE_SIZE, &errno));
return 0;
}
/*
* Testcase 19
* Tested function: mm_release_page_tables
* Testcase: verify that all page tables above the common area have been
* removed
*/
int testcase19() {
u32 my_base;
int errno;
u32 page;
int i;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
mm_get_ptd_for_pid = mm_get_ptd_for_pid_stub;
/*
* Setup done. Now we start the actual test.
*/
mm_release_page_tables(0);
/*
* Walk page table directory and check that all pages above common area
* are not present, whereas all pages in the common area are still there
*/
for (i = 0; i < MM_PT_ENTRIES; i++) {
if (i<MM_SHARED_PAGE_TABLES) {
ASSERT(1==test_ptd[i].p);
}
else {
ASSERT(0==test_ptd[i].p);
ASSERT(0==BITFIELD_GET_BIT(phys_mem, MM_PAGE(test_ptd[i].page_base*MM_PAGE_SIZE)));
}
}
return 0;
}
/*
* Testcase 20
* Function: mm_virt_to_phys
* Testcase: Map a page, starting with an empty page table directory, paging enabled. Then call
* mm_virt_to_phys
* Expected result: correct physical address is returned
*/
int testcase20() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
pte_t* pt;
/*
* This is our test page table which we are going to
* present to mm_map_page via the stubbed version of
* mm_get_pt_address
*/
char __attribute__ ((aligned(4096))) page[4096];
u32 virtual = 0xa1230000;
u32 physical = 0xbedf0000;
u32 phys_page_table = (u32) page;
u32 ptd_offset;
u32 pt_offset;
int i;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
(page)[i] = 0;
for (i = 0; i < sizeof(pte_t) * 1024; i++)
((char*) ptd)[i] = 0;
/*
* Set up stub for physical page allocation
* We use an address different from the virtual address
* as this address is not used except to generate the PTD entry
*/
mm_get_phys_page = mm_get_phys_page_stub;
mm_get_phys_page_called = 0;
phys_page[0] = phys_page_table;
phys_page[1] = 0;
/* Set up stub for read access to CR0 */
paging_enabled = 1;
/* Set up stub for translation of PTD entry
* to pointer.
* In this setup, we know that only one page table is
* used. We therefore divert all access to this page table
* to the array page declared above (set pg_enabled_override=1).
* Thus the function mm_map_page which is under test here will access
* this memory area when adding entries to the page table and we can
* run our verifications against this area as well.
*/
mm_get_pt_address = mm_get_pt_address_stub;
test_ptd = ptd;
mm_get_ptd=mm_get_ptd_stub;
next_pt_address = (pte_t*) page;
pg_enabled_override = 1;
mm_map_page(ptd, physical, virtual, 1, 1, 1, 0);
/*
* Now call translation function
*/
ASSERT(physical==mm_virt_to_phys(virtual));
ASSERT(physical+1==mm_virt_to_phys(virtual+1));
return 0;
}
/*
* Testcase 21
* Tested function: mm_map_memio
* Testcase: map one mem I/O page and verify that a virtual
* address different from zero is returned which is located
* in the area reserved for memory mapped I/O
*/
int testcase21() {
u32 my_base;
int errno;
u32 memio;
u32 page;
int i;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
mm_get_ptd_for_pid = mm_get_ptd_for_pid_stub;
/*
* Setup done. Now we start the actual test.
*/
memio = mm_map_memio(0xfec00000, 14);
ASSERT(memio);
ASSERT(memio>=MM_MEMIO_START);
ASSERT((memio+13)<=MM_MEMIO_END);
return 0;
}
/*
* Testcase 22
* Tested function: mm_map_memio
* Testcase: map two mem I/O page and verify that both pages
* are mapped to adjacent physical addresses
*/
int testcase22() {
u32 my_base;
int errno;
u32 memio;
u32 page;
int i;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
mm_get_ptd_for_pid = mm_get_ptd_for_pid_stub;
/*
* Setup done. Now we start the actual test.
*/
memio = mm_map_memio(0xfec00000, 4097);
ASSERT(memio);
ASSERT(memio>=MM_MEMIO_START);
ASSERT((memio+13)<=MM_MEMIO_END);
ASSERT(mm_virt_to_phys(memio));
ASSERT(mm_virt_to_phys(memio+4096));
ASSERT(mm_virt_to_phys(memio+4096)==(mm_virt_to_phys(memio)+4096));
return 0;
}
/*
* Testcase 23
* Tested function: mm_map_memio
* Testcase: map one mem I/O page and verify that a second
* mapping returns a different virtual address
*/
int testcase23() {
u32 my_base;
int errno;
u32 memio1;
u32 memio2;
u32 page;
int i;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
mm_get_ptd_for_pid = mm_get_ptd_for_pid_stub;
/*
* Setup done. Now we start the actual test.
*/
memio1 = mm_map_memio(0xfec00000, 14);
ASSERT(memio1);
ASSERT(memio1>=MM_MEMIO_START);
memio2 = mm_map_memio(0xfec00000, 14);
ASSERT(memio2);
ASSERT(memio2>=MM_MEMIO_START);
ASSERT(memio1 != memio2);
return 0;
}
/*
* Testcase 24
* Tested function: mm_map_memio
* Testcase: map two mem I/O page and verify that
* another call returns a region which does not overlap with that
* returned by the first call
*/
int testcase24() {
u32 my_base;
int errno;
u32 memio;
u32 page;
int i;
int nr_of_pages = 2 * (2 + MM_SHARED_PAGE_TABLES + MM_STACK_PAGES_TASK);
u32 my_mem = setup_phys_pages(nr_of_pages);
/*
* Zero out target memory
*/
memset((void*) my_mem, 0, nr_of_pages * 4096);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
paging_enabled = 1;
pg_enabled_override = 0;
mm_get_pt_address = mm_get_pt_address_stub;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Stub for mm_attach_page
*/
mm_attach_page = mm_attach_page_stub;
mm_detach_page = mm_detach_page_stub;
/* and call function to set up source page tables */
mm_init_address_spaces();
mm_init_page_tables();
/*
* Set up stub for mm_get_ptd
*/
test_ptd = (pte_t*) cr3;
mm_get_ptd = mm_get_ptd_stub;
mm_get_ptd_for_pid = mm_get_ptd_for_pid_stub;
/*
* Setup done. Now we start the actual test.
*/
memio = mm_map_memio(0xfec00000, 4097);
ASSERT(memio);
ASSERT(memio>=MM_MEMIO_START);
ASSERT((memio+13)<=MM_MEMIO_END);
ASSERT(mm_virt_to_phys(memio));
ASSERT(mm_virt_to_phys(memio+4096));
ASSERT(mm_virt_to_phys(memio+4096)==(mm_virt_to_phys(memio)+4096));
ASSERT(mm_map_memio(0xfec00000, 4) > (memio+4096));
return 0;
}
/*
* Testcase 25
* Function: mm_validate_buffer
* Test case that a buffer is valid, i.e. entirely contained in user space
*/
int testcase25() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now map a physical page at address 0 for write in user mode
*/
ASSERT(0 == mm_map_page(ptd, 0x10000, 0x20000, MM_READ_WRITE, MM_USER_PAGE, 0, 0));
/*
* and a second page
*/
ASSERT(0 == mm_map_page(ptd, 0x10000 + 4096, 0x20000 + 4096, MM_READ_WRITE, MM_USER_PAGE, 0, 0));
/*
* and call mm_validate_buffer
*/
ASSERT(0 == mm_validate_buffer(0x20000, 8192, 1));
__mm_log = 0;
do_putchar = 0;
return 0;
}
/*
* Testcase 26
* Function: mm_validate_buffer
* Test case that a buffer is mapped, but not as user space page
*/
int testcase26() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now map a physical page at address 0 for write in kernel mode
*/
ASSERT(0 == mm_map_page(ptd, 0x10000, 0x20000, MM_READ_WRITE, MM_SUPERVISOR_PAGE, 0, 0));
/*
* and a second page
*/
ASSERT(0 == mm_map_page(ptd, 0x10000 + 4096, 0x20000 + 4096, MM_READ_WRITE, MM_SUPERVISOR_PAGE, 0, 0));
/*
* and call mm_validate_buffer
*/
__mm_log = 0;
ASSERT(-1 == mm_validate_buffer(0x20000, 8192, 1));
return 0;
}
/*
* Testcase 27
* Function: mm_validate_buffer
* Test case that a buffer is mapped, but not writable
*/
int testcase27() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now map a physical page at address 0 for read in user mode
*/
ASSERT(0 == mm_map_page(ptd, 0x10000, 0x20000, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and a second page
*/
ASSERT(0 == mm_map_page(ptd, 0x10000 + 4096, 0x20000 + 4096, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and call mm_validate_buffer
*/
ASSERT(-1 == mm_validate_buffer(0x20000, 8192, 1));
ASSERT(0 == mm_validate_buffer(0x20000, 8192, 0));
return 0;
}
/*
* Testcase 28
* Function: mm_validate_buffer
* Borderline case - page is exactly one page / one byte plus one page
*/
int testcase28() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now map a physical page at address 0 for read in user mode
*/
ASSERT(0 == mm_map_page(ptd, 0x10000, 0x20000, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and call mm_validate_buffer
*/
ASSERT(0 == mm_validate_buffer(0x20000, 4096, 0));
ASSERT(-1 == mm_validate_buffer(0x20000, 4096 + 1, 0));
return 0;
}
/*
* Testcase 29
* Function: mm_validate_buffer
* Validate a string
*/
int testcase29() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
unsigned char __attribute__ ((aligned(4096))) mybuffer[4096];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now we map the physical page mybuffer 1:1 as readable
* user space page
*/
ASSERT(0 == mm_map_page(ptd, (u32) mybuffer, (u32) mybuffer, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and place a string in the first few bytes
*/
memset((void*) mybuffer, 0, 4096);
strcpy(mybuffer, "hello");
/*
* We should now be able to validate the string buffer successfully
*/
ASSERT(0 == mm_validate_buffer((u32) mybuffer, 0, 0));
return 0;
}
/*
* Testcase 30
* Function: mm_validate_buffer
* Validate a string that crosses a page boundary
*/
int testcase30() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
unsigned char __attribute__ ((aligned(4096))) mybuffer[8192];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now we map the physical page mybuffer 1:1 as readable
* user space page
*/
ASSERT(0 == mm_map_page(ptd, (u32) mybuffer, (u32) mybuffer, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and place a string near the page end which crosses the page boundary
*/
memset((void*) mybuffer, 0, 8192);
strcpy(mybuffer+4094, "some_string");
/*
* Validation should fail
*/
ASSERT(-1 == mm_validate_buffer((u32) mybuffer + 4094, 0, 0));
/*
* Now map second page
*/
ASSERT(0 == mm_map_page(ptd, (u32) mybuffer + 4096, (u32) mybuffer + 4096, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and repeat validation - this time it should work
*/
ASSERT(0 == mm_validate_buffer((u32) mybuffer + 4094, 0, 0));
return 0;
}
/*
* Testcase 31
* Function: mm_validate_buffer
* Validate a string that ends at a page boundary, i.e. 0 is last byte of page
*/
int testcase31() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
unsigned char __attribute__ ((aligned(4096))) mybuffer[8192];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now we map the physical page mybuffer 1:1 as readable
* user space page
*/
ASSERT(0 == mm_map_page(ptd, (u32) mybuffer, (u32) mybuffer, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and place a string near the page end which ends at the page boundary. More specifically, we
* place the string abcde in the bytes 4090, 4091, 4092, 4093, 4094 so that the trailing 0 is the
* last byte of the page
*/
memset((void*) mybuffer, 0, 8192);
strcpy(mybuffer + 4090, "abcde");
ASSERT('e' == mybuffer[4094]);
ASSERT(0 == mybuffer[4095]);
/*
* Validation should be successful
*/
ASSERT(0 == mm_validate_buffer((u32) mybuffer + 4090, 0, 0));
return 0;
}
/*
* Testcase 32
* Function: mm_validate_buffer
* Validate a string that ends at a page boundary, i.e. 0 is last byte of page
*/
int testcase32() {
pte_t __attribute__ ((aligned(4096))) ptd[1024];
unsigned char __attribute__ ((aligned(4096))) mybuffer[8192];
/*
* Set up stub for mm_get_phys_page. We are going to map two pages, so we need
* one page table directory and one page table
*/
int errno;
u32 my_base;
int i;
u32 phys;
int nr_of_pages = 2;
u32 my_mem = setup_phys_pages(nr_of_pages);
mm_get_phys_page_called = 0;
mm_get_phys_page = mm_get_phys_page_stub;
/*
* Set up stub for read access to CR0
*/
paging_enabled = 0;
/*
* Zero page table directory
*/
memset((void*) ptd, 0, sizeof(pte_t)*1024);
/*
* Set up stub for translation. Here we use method 2 outlined in the comment
* at the beginning of this file.
*/
mm_get_pt_address = mm_get_pt_address_stub;
pg_enabled_override = 0;
test_ptd = ptd;
/*
* Stub for end of kernel BSS section
*/
mm_get_bss_end = mm_get_bss_end_stub;
/*
* Now we map the physical page mybuffer 1:1 as readable
* user space page
*/
ASSERT(0 == mm_map_page(ptd, (u32) mybuffer, (u32) mybuffer, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and place a string near the page end which crosses at the page boundary. More specifically, we
* place the string abcdef in the bytes 4090, 4091, 4092, 4093, 4094 and 4095 so that the trailing 0 is the
* first byte of the following page
*/
memset((void*) mybuffer, 0, 8192);
strcpy(mybuffer + 4090, "abcdef");
ASSERT('f' == mybuffer[4095]);
ASSERT(0 == mybuffer[4096]);
/*
* Validation should not be successful
*/
ASSERT(-1 == mm_validate_buffer((u32) mybuffer + 4090, 0, 0));
/*
* Now map second page
*/
ASSERT(0 == mm_map_page(ptd, (u32) mybuffer + 4096, (u32) mybuffer + 4096, MM_READ_ONLY, MM_USER_PAGE, 0, 0));
/*
* and repeat validation - this time it should work
*/
ASSERT(0 == mm_validate_buffer((u32) mybuffer + 4090, 0, 0));
return 0;
}
int main() {
INIT;
/*
* Save original pointer to mm_get_ptd
*/
mm_get_ptd_orig = mm_get_ptd;
RUN_CASE(1);
RUN_CASE(2);
RUN_CASE(3);
RUN_CASE(4);
RUN_CASE(5);
RUN_CASE(6);
RUN_CASE(7);
RUN_CASE(8);
RUN_CASE(9);
RUN_CASE(10);
RUN_CASE(11);
RUN_CASE(12);
RUN_CASE(13);
RUN_CASE(14);
RUN_CASE(15);
RUN_CASE(16);
RUN_CASE(17);
RUN_CASE(18);
RUN_CASE(19);
RUN_CASE(20);
RUN_CASE(21);
RUN_CASE(22);
RUN_CASE(23);
RUN_CASE(24);
RUN_CASE(25);
RUN_CASE(26);
RUN_CASE(27);
RUN_CASE(28);
RUN_CASE(29);
RUN_CASE(30);
RUN_CASE(31);
RUN_CASE(32);
END;
}
| 30.220921 | 114 | 0.650108 |
29a2603e9910a64df00a8590643653b02762096f | 7,744 | h | C | main/cli_ure/source/uno_bridge/cli_base.h | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/cli_ure/source/uno_bridge/cli_base.h | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/cli_ure/source/uno_bridge/cli_base.h | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
#if ! defined INCLUDED_CLI_BASE_H
#define INCLUDED_CLI_BASE_H
#pragma unmanaged
// Workaround: osl/mutex.h contains only a forward declaration of _oslMutexImpls.
// When using the inline class in Mutex in osl/mutex.hxx, the loader needs to find
// a declaration for the struct. If not found a TypeLoadException is being thrown.
struct _oslMutexImpl
{
};
#pragma managed
#include <memory>
#include "rtl/ustring.hxx"
#include "typelib/typedescription.hxx"
#using <mscorlib.dll>
#using <system.dll>
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
namespace cli_uno
{
System::Type* loadCliType(System::String * typeName);
System::Type* mapUnoType(typelib_TypeDescription const * pTD);
System::Type* mapUnoType(typelib_TypeDescriptionReference const * pTD);
typelib_TypeDescriptionReference* mapCliType(System::Type* cliType);
rtl::OUString mapCliString(System::String const * data);
System::String* mapUnoString(rtl_uString const * data);
System::String* mapUnoTypeName(rtl_uString const * typeName);
__gc struct Constants
{
static const System::String* sXInterfaceName= new System::String(
S"unoidl.com.sun.star.uno.XInterface");
static const System::String* sObject= new System::String(S"System.Object");
static const System::String* sType= new System::String(S"System.Type");
static const System::String* sUnoidl= new System::String(S"unoidl.");
static const System::String* sVoid= new System::String(S"System.Void");
static const System::String* sAny= new System::String(S"uno.Any");
static const System::String* sArArray= new System::String(S"System.Array[]");
static const System::String* sBoolean= new System::String(S"System.Boolean");
static const System::String* sChar= new System::String(S"System.Char");
static const System::String* sByte= new System::String(S"System.Byte");
static const System::String* sInt16= new System::String(S"System.Int16");
static const System::String* sUInt16= new System::String(S"System.UInt16");
static const System::String* sInt32= new System::String(S"System.Int32");
static const System::String* sUInt32= new System::String(S"System.UInt32");
static const System::String* sInt64= new System::String(S"System.Int64");
static const System::String* sUInt64= new System::String(S"System.UInt64");
static const System::String* sString= new System::String(S"System.String");
static const System::String* sSingle= new System::String(S"System.Single");
static const System::String* sDouble= new System::String(S"System.Double");
static const System::String* sArBoolean= new System::String(S"System.Boolean[]");
static const System::String* sArChar= new System::String(S"System.Char[]");
static const System::String* sArByte= new System::String(S"System.Byte[]");
static const System::String* sArInt16= new System::String(S"System.Int16[]");
static const System::String* sArUInt16= new System::String(S"System.UInt16[]");
static const System::String* sArInt32= new System::String(S"System.Int32[]");
static const System::String* sArUInt32= new System::String(S"System.UInt32[]");
static const System::String* sArInt64= new System::String(S"System.Int64[]");
static const System::String* sArUInt64= new System::String(S"System.UInt64[]");
static const System::String* sArString= new System::String(S"System.String[]");
static const System::String* sArSingle= new System::String(S"System.Single[]");
static const System::String* sArDouble= new System::String(S"System.Double[]");
static const System::String* sArType= new System::String(S"System.Type[]");
static const System::String* sArObject= new System::String(S"System.Object[]");
static const System::String* sBrackets= new System::String(S"[]");
static const System::String* sAttributeSet= new System::String(S"set_");
static const System::String* sAttributeGet= new System::String(S"get_");
static const System::String* usXInterface = S"com.sun.star.uno.XInterface";
static const System::String* usVoid = S"void";
static const System::String* usType = S"type";
static const System::String* usAny = S"any";
static const System::String* usBrackets = S"[]";
static const System::String* usBool = S"boolean";
static const System::String* usByte = S"byte";
static const System::String* usChar = S"char";
static const System::String* usShort = S"short";
static const System::String* usUShort = S"unsigned short";
static const System::String* usLong = S"long";
static const System::String* usULong = S"unsigned long";
static const System::String* usHyper = S"hyper";
static const System::String* usUHyper = S"unsigned hyper";
static const System::String* usString = S"string";
static const System::String* usFloat = S"float";
static const System::String* usDouble = S"double";
};
struct BridgeRuntimeError
{
::rtl::OUString m_message;
inline BridgeRuntimeError( ::rtl::OUString const & message )
: m_message( message )
{}
};
//==================================================================================================
struct rtl_mem
{
inline static void * operator new ( size_t nSize )
{ return rtl_allocateMemory( nSize ); }
inline static void operator delete ( void * mem )
{ if (mem) rtl_freeMemory( mem ); }
inline static void * operator new ( size_t, void * mem )
{ return mem; }
inline static void operator delete ( void *, void * )
{}
static inline ::std::auto_ptr< rtl_mem > allocate( ::std::size_t bytes );
};
//--------------------------------------------------------------------------------------------------
inline ::std::auto_ptr< rtl_mem > rtl_mem::allocate( ::std::size_t bytes )
{
void * p = rtl_allocateMemory( bytes );
if (0 == p)
throw BridgeRuntimeError(OUSTR("out of memory!") );
return ::std::auto_ptr< rtl_mem >( (rtl_mem *)p );
}
//==================================================================================================
class TypeDescr
{
typelib_TypeDescription * m_td;
TypeDescr( TypeDescr & ); // not impl
void operator = ( TypeDescr ); // not impl
public:
inline explicit TypeDescr( typelib_TypeDescriptionReference * td_ref );
inline ~TypeDescr() SAL_THROW( () )
{ TYPELIB_DANGER_RELEASE( m_td ); }
inline typelib_TypeDescription * get() const
{ return m_td; }
};
inline TypeDescr::TypeDescr( typelib_TypeDescriptionReference * td_ref )
: m_td( 0 )
{
TYPELIB_DANGER_GET( &m_td, td_ref );
if (0 == m_td)
{
throw BridgeRuntimeError(
OUSTR("cannot get comprehensive type description for ") +
*reinterpret_cast< ::rtl::OUString const * >( &td_ref->pTypeName ) );
}
}
} //end namespace cli_uno
#endif
| 43.751412 | 100 | 0.670971 |
958d9c4ce7584e6a3a6257aa338308141766d43b | 529 | h | C | CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/BizMessageList.h | ceekay1991/CallTraceForWeChat | 5767cb6f781821b6bf9facc8c87e58e15fa88541 | [
"MIT"
] | 30 | 2020-03-22T12:30:21.000Z | 2022-02-09T08:49:13.000Z | CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/BizMessageList.h | ceekay1991/CallTraceForWeChat | 5767cb6f781821b6bf9facc8c87e58e15fa88541 | [
"MIT"
] | null | null | null | CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/BizMessageList.h | ceekay1991/CallTraceForWeChat | 5767cb6f781821b6bf9facc8c87e58e15fa88541 | [
"MIT"
] | 8 | 2020-03-22T12:30:23.000Z | 2020-09-22T04:01:47.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "WXPBGeneratedMessage.h"
@class BizProfileV2PagingInfo, NSMutableArray;
@interface BizMessageList : WXPBGeneratedMessage
{
}
+ (void)initialize;
// Remaining properties
@property(retain, nonatomic) NSMutableArray *msg; // @dynamic msg;
@property(retain, nonatomic) BizProfileV2PagingInfo *pagingInfo; // @dynamic pagingInfo;
@end
| 23 | 90 | 0.73535 |
19bc8dd933b92df56d67af894d151eba5b199d16 | 69,283 | h | C | HAP/HAPLog+Attributes.h | Raspberry-Pi-4-MCU/apple_homekit_example | 22970d352d064108a1f86e199be91952fff91ec8 | [
"Apache-2.0"
] | 2,443 | 2019-12-18T13:21:14.000Z | 2022-03-28T07:41:17.000Z | HAP/HAPLog+Attributes.h | Raspberry-Pi-4-MCU/apple_homekit_example | 22970d352d064108a1f86e199be91952fff91ec8 | [
"Apache-2.0"
] | 86 | 2019-12-19T15:11:09.000Z | 2022-03-14T06:04:31.000Z | HAP/HAPLog+Attributes.h | Raspberry-Pi-4-MCU/apple_homekit_example | 22970d352d064108a1f86e199be91952fff91ec8 | [
"Apache-2.0"
] | 266 | 2019-12-18T17:54:09.000Z | 2022-03-27T13:41:45.000Z | // Copyright (c) 2015-2019 The HomeKit ADK Contributors
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// See [CONTRIBUTORS.md] for the list of HomeKit ADK project authors.
#ifndef HAP_LOG_ATTRIBUTES_H
#define HAP_LOG_ATTRIBUTES_H
#ifdef __cplusplus
extern "C" {
#endif
#include "HAP+Internal.h"
#if __has_feature(nullability)
#pragma clang assume_nonnull begin
#endif
// ISO C99 requires at least one argument for the "..." in a variadic macro.
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC system_header
#endif
/**
* Logs the contents of a buffer and a message related to an accessory at a specific logging level.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogAccessoryBufferWithType(logObject, accessory, bytes, numBytes, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogAccessoryBufferDebug(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogAccessoryBufferInfo(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogAccessoryBuffer(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogAccessoryBufferError(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogAccessoryBufferFault(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs the contents of a buffer and a default-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryBuffer(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogBuffer( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an info-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryBufferInfo(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogBufferInfo( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a debug-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryBufferDebug(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogBufferDebug( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an error-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryBufferError(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogBufferError( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a fault-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryBufferFault(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogBufferFault( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs a message related to an accessory at a specific logging level.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogAccessoryWithType(logObject, accessory, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogAccessoryDebug(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogAccessoryInfo(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogAccessory(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogAccessoryError(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogAccessoryFault(logObject, accessory, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs a default-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessory(logObject, accessory, format, ...) \
HAPLog(logObject, "[%016llX %s] " format, (unsigned long long) (accessory)->aid, (accessory)->name, ##__VA_ARGS__)
/**
* Logs an info-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryInfo(logObject, accessory, format, ...) \
HAPLogInfo( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs a debug-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryDebug(logObject, accessory, format, ...) \
HAPLogDebug( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs an error-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryError(logObject, accessory, format, ...) \
HAPLogError( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs a fault-level message related to an accessory.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogAccessoryFault(logObject, accessory, format, ...) \
HAPLogFault( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a message related to an accessory
* at a specific logging level that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogSensitiveAccessoryBufferWithType(logObject, accessory, bytes, numBytes, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogSensitiveAccessoryBufferDebug(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogSensitiveAccessoryBufferInfo(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogSensitiveAccessoryBuffer(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogSensitiveAccessoryBufferError(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogSensitiveAccessoryBufferFault(logObject, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs the contents of a buffer and a default-level message related to an accessory
* that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryBuffer(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBuffer( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an info-level message related to an accessory
* that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryBufferInfo(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferInfo( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a debug-level message related to an accessory
* that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryBufferDebug(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferDebug( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an error-level message related to an accessory
* that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryBufferError(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferError( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a fault-level message related to an accessory
* that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryBufferFault(logObject, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferFault( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs a message related to an accessory at a specific logging level that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogSensitiveAccessoryWithType(logObject, accessory, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogSensitiveAccessoryDebug(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogSensitiveAccessoryInfo(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogSensitiveAccessory(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogSensitiveAccessoryError(logObject, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogSensitiveAccessoryFault(logObject, accessory, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs a default-level message related to an accessory that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessory(logObject, accessory, format, ...) \
HAPLogSensitive( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs an info-level message related to an accessory that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryInfo(logObject, accessory, format, ...) \
HAPLogSensitiveInfo( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs a debug-level message related to an accessory that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryDebug(logObject, accessory, format, ...) \
HAPLogSensitiveDebug( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs an error-level message related to an accessory that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryError(logObject, accessory, format, ...) \
HAPLogSensitiveError( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
/**
* Logs a fault-level message related to an accessory that may contain sensitive information.
*
* @param logObject Log object.
* @param accessory Accessory.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveAccessoryFault(logObject, accessory, format, ...) \
HAPLogSensitive( \
logObject, \
"[%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
##__VA_ARGS__)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Logs the contents of a buffer and a message related to a service at a specific logging level.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogServiceBufferWithType(logObject, service, accessory, bytes, numBytes, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogServiceBufferDebug(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogServiceBufferInfo(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogServiceBuffer(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogServiceBufferError(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogServiceBufferFault(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs the contents of a buffer and a default-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceBuffer(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogBuffer( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an info-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceBufferInfo(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferInfo( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a debug-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceBufferDebug(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferDebug( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an error-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceBufferError(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferError( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a fault-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceBufferFault(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferFault( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs a message related to a service at a specific logging level.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogServiceWithType(logObject, service, accessory, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogServiceDebug(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogServiceInfo(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogService(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogServiceError(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogServiceFault(logObject, service, accessory, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs a default-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogService(logObject, service, accessory, format, ...) \
HAPLog(logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs an info-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceInfo(logObject, service, accessory, format, ...) \
HAPLogInfo( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs a debug-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceDebug(logObject, service, accessory, format, ...) \
HAPLogDebug( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs an error-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceError(logObject, service, accessory, format, ...) \
HAPLogError( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs a fault-level message related to a service.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogServiceFault(logObject, service, accessory, format, ...) \
HAPLogFault( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a message related to a service
* at a specific logging level that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogSensitiveServiceBufferWithType(logObject, service, accessory, bytes, numBytes, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogSensitiveServiceBufferDebug(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogSensitiveServiceBufferInfo(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogSensitiveServiceBuffer(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogSensitiveServiceBufferError(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogSensitiveServiceBufferFault(logObject, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs the contents of a buffer and a default-level message related to a service
* that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceBuffer(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBuffer( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an info-level message related to a service
* that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceBufferInfo(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferInfo( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a debug-level message related to a service
* that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceBufferDebug(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferDebug( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an error-level message related to a service
* that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceBufferError(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferError( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a fault-level message related to a service
* that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceBufferFault(logObject, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferFault( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs a message related to a service at a specific logging level that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogSensitiveServiceWithType(logObject, service, accessory, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogSensitiveServiceDebug(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogSensitiveServiceInfo(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogSensitiveService(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogSensitiveServiceError(logObject, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogSensitiveServiceFault(logObject, service, accessory, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs a default-level message related to a service that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveService(logObject, service, accessory, format, ...) \
HAPLogSensitive( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs an info-level message related to a service that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceInfo(logObject, service, accessory, format, ...) \
HAPLogSensitiveInfo( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs a debug-level message related to a service that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceDebug(logObject, service, accessory, format, ...) \
HAPLogSensitiveDebug( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs an error-level message related to a service that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceError(logObject, service, accessory, format, ...) \
HAPLogSensitiveError( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
/**
* Logs a fault-level message related to a service that may contain sensitive information.
*
* @param logObject Log object.
* @param service Service.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveServiceFault(logObject, service, accessory, format, ...) \
HAPLogSensitive( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) (service)->iid, \
(service)->debugDescription, \
##__VA_ARGS__)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Logs the contents of a buffer and a message related to a characteristic at a specific logging level.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogCharacteristicBufferWithType(logObject, characteristic, service, accessory, bytes, numBytes, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogCharacteristicBufferDebug( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogCharacteristicBufferInfo( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogCharacteristicBuffer( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogCharacteristicBufferError( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogCharacteristicBufferFault( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs the contents of a buffer and a default-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicBuffer(logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogBuffer( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an info-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicBufferInfo(logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferInfo( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a debug-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicBufferDebug(logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferDebug( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an error-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicBufferError(logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferError( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a fault-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicBufferFault(logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogBufferFault( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs a message related to a characteristic at a specific logging level.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogCharacteristicWithType(logObject, characteristic, service, accessory, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogCharacteristicDebug(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogCharacteristicInfo(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogCharacteristic(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogCharacteristicError(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogCharacteristicFault(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs a default-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristic(logObject, characteristic, service, accessory, format, ...) \
HAPLog(logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs an info-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicInfo(logObject, characteristic, service, accessory, format, ...) \
HAPLogInfo( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs a debug-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicDebug(logObject, characteristic, service, accessory, format, ...) \
HAPLogDebug( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs an error-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicError(logObject, characteristic, service, accessory, format, ...) \
HAPLogError( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs a fault-level message related to a characteristic.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogCharacteristicFault(logObject, characteristic, service, accessory, format, ...) \
HAPLogFault( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a message related to a characteristic
* at a specific logging level that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogSensitiveCharacteristicBufferWithType( \
logObject, characteristic, service, accessory, bytes, numBytes, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogSensitiveCharacteristicBufferDebug( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogSensitiveCharacteristicBufferInfo( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogSensitiveCharacteristicBuffer( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogSensitiveCharacteristicBufferError( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogSensitiveCharacteristicBufferFault( \
logObject, characteristic, service, accessory, bytes, numBytes, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs the contents of a buffer and a default-level message related to a characteristic
* that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicBuffer( \
logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBuffer( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an info-level message related to a characteristic
* that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicBufferInfo( \
logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferInfo( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a debug-level message related to a characteristic
* that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicBufferDebug( \
logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferDebug( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and an error-level message related to a characteristic
* that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicBufferError( \
logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferError( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs the contents of a buffer and a fault-level message related to a characteristic
* that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param bytes Buffer containing data to log.
* @param numBytes Length of buffer.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicBufferFault( \
logObject, characteristic, service, accessory, bytes, numBytes, format, ...) \
HAPLogSensitiveBufferFault( \
logObject, \
bytes, \
numBytes, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs a message related to a characteristic at a specific logging level that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param type A log type constant, indicating the level of logging to perform.
*/
#define HAPLogSensitiveCharacteristicWithType(logObject, characteristic, service, accessory, type, ...) \
do { \
switch (type) { \
case kHAPLogType_Debug: { \
HAPLogSensitiveCharacteristicDebug(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Info: { \
HAPLogSensitiveCharacteristicInfo(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Default: { \
HAPLogSensitiveCharacteristic(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Error: { \
HAPLogSensitiveCharacteristicError(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
case kHAPLogType_Fault: { \
HAPLogSensitiveCharacteristicFault(logObject, characteristic, service, accessory, __VA_ARGS__); \
} break; \
} \
} while (0)
/**
* Logs a default-level message related to a characteristic that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristic(logObject, characteristic, service, accessory, format, ...) \
HAPLogSensitive( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs an info-level message related to a characteristic that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicInfo(logObject, characteristic, service, accessory, format, ...) \
HAPLogSensitiveInfo( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs a debug-level message related to a characteristic that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicDebug(logObject, characteristic, service, accessory, format, ...) \
HAPLogSensitiveDebug( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs an error-level message related to a characteristic that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicError(logObject, characteristic, service, accessory, format, ...) \
HAPLogSensitiveError( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
/**
* Logs a fault-level message related to a characteristic that may contain sensitive information.
*
* @param logObject Log object.
* @param characteristic Characteristic.
* @param service The service that contains the characteristic.
* @param accessory The accessory that provides the service.
* @param format Format string that produces a human-readable log message.
*/
#define HAPLogSensitiveCharacteristicFault(logObject, characteristic, service, accessory, format, ...) \
HAPLogSensitive( \
logObject, \
"[%016llX %s] [%016llX %s] " format, \
(unsigned long long) (accessory)->aid, \
(accessory)->name, \
(unsigned long long) ((const HAPBaseCharacteristic*) (characteristic))->iid, \
((const HAPBaseCharacteristic*) (characteristic))->debugDescription, \
##__VA_ARGS__)
#if __has_feature(nullability)
#pragma clang assume_nonnull end
#endif
#ifdef __cplusplus
}
#endif
#endif
| 43.711672 | 120 | 0.579594 |
c92f19d839ff636c257607caa729c185b10f940b | 792 | h | C | PlugIns/IDESceneKitEditor/SKEPreferencesManager.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | 1 | 2016-03-30T10:07:37.000Z | 2016-03-30T10:07:37.000Z | PlugIns/IDESceneKitEditor/SKEPreferencesManager.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | null | null | null | PlugIns/IDESceneKitEditor/SKEPreferencesManager.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@interface SKEPreferencesManager : NSObject
{
}
+ (id)keyPathsForValuesAffectingBakeryNeedsAttenuation;
+ (id)sharedPreferencesManager;
@property(readonly, nonatomic) BOOL bakeryNeedsAttenuation;
@property(nonatomic) float bakeryAttenuationFactor;
@property(nonatomic) float bakeryQuality;
@property(nonatomic) unsigned long long bakeryDestination;
@property(nonatomic) unsigned long long bakeryType;
@property(readonly, nonatomic) BOOL nodeInspectorCoordinatesSystemIsLocal;
@property(readonly, nonatomic) BOOL nodeInspectorCoordinatesSystemIsWorld;
@property(nonatomic) unsigned long long nodeInspectorCoordinatesSystem;
@end
| 30.461538 | 83 | 0.80303 |
4519f2119058d614dce204bdddb49cc400045bd6 | 782 | h | C | service/src/properties/source/JsonPropertySource.h | darvik80/rover-cpp | 8da7b7f07efe7096843ae17536603277f55debea | [
"Apache-2.0"
] | 2 | 2020-01-13T07:32:50.000Z | 2020-03-03T14:32:25.000Z | service/src/properties/source/JsonPropertySource.h | darvik80/rover-cpp | 8da7b7f07efe7096843ae17536603277f55debea | [
"Apache-2.0"
] | 16 | 2019-06-16T05:51:02.000Z | 2020-02-03T01:59:23.000Z | service/src/properties/source/JsonPropertySource.h | darvik80/rover-cpp | 8da7b7f07efe7096843ae17536603277f55debea | [
"Apache-2.0"
] | 1 | 2020-03-03T14:32:27.000Z | 2020-03-03T14:32:27.000Z | //
// Created by Ivan Kishchenko on 11.04.2021.
//
#pragma once
#include "PropertySource.h"
#include <nlohmann/json.hpp>
#include <fstream>
class JsonPropertySource : public PropertySource {
nlohmann::json _json;
public:
explicit JsonPropertySource(std::string_view source);
explicit JsonPropertySource(std::ifstream& stream) {
stream >> _json;
}
void getProperties(NetworkProperties& props) override;
void getProperties(LoggingProperties &props) override;
void getProperties(HttpProperties &props) override;
void getProperties(GrpcProperties &props) override;
void getProperties(SerialProperties &props) override;
void getProperties(MqttProperties &props) override;
void getProperties(JoystickProperties &props) override;
};
| 28.962963 | 59 | 0.750639 |
c7c1c15e52a10ba3dc6c42026a40d9aa6d427e4d | 1,199 | c | C | src/cmd/sh/echo.c | 610t/retrobsd | a0c256c1f0129ee6eb0d00f385e98da9b28d94c1 | [
"BSD-3-Clause"
] | 236 | 2015-01-13T12:33:26.000Z | 2022-03-16T07:18:49.000Z | src/cmd/sh/echo.c | 610t/retrobsd | a0c256c1f0129ee6eb0d00f385e98da9b28d94c1 | [
"BSD-3-Clause"
] | 21 | 2015-04-26T07:35:34.000Z | 2020-12-18T13:31:55.000Z | src/cmd/sh/echo.c | 610t/retrobsd | a0c256c1f0129ee6eb0d00f385e98da9b28d94c1 | [
"BSD-3-Clause"
] | 53 | 2015-01-21T12:54:44.000Z | 2022-01-14T07:01:39.000Z | /*
* UNIX shell
*
* Bell Telephone Laboratories
*/
#include "defs.h"
#define Exit(a) flushb();return(a)
extern int exitval;
echo(argc, argv)
char **argv;
{
register char *cp;
register int i, wd;
int j;
int nonl = 0; /* echo -n */
if(--argc == 0) {
prc_buff('\n');
Exit(0);
}
if ( cf(argv[1], "-n" ) == 0 ){
nonl++;
argv++;
argc--;
}
for(i = 1; i <= argc; i++)
{
sigchk();
for(cp = argv[i]; *cp; cp++)
{
if(*cp == '\\')
switch(*++cp)
{
case 'b':
prc_buff('\b');
continue;
case 'c':
Exit(0);
case 'f':
prc_buff('\f');
continue;
case 'n':
prc_buff('\n');
continue;
case 'r':
prc_buff('\r');
continue;
case 't':
prc_buff('\t');
continue;
case 'v':
prc_buff('\v');
continue;
case '\\':
prc_buff('\\');
continue;
case '\0':
j = wd = 0;
while ((*++cp >= '0' && *cp <= '7') && j++ < 3) {
wd <<= 3;
wd |= (*cp - '0');
}
prc_buff(wd);
--cp;
continue;
default:
cp--;
}
prc_buff(*cp);
}
if( nonl ) prc_buff( ' ' );
else prc_buff(i == argc? '\n': ' ');
}
Exit(0);
}
| 13.47191 | 54 | 0.422018 |
d5cef222c93fc836d6c01db3e7e5a704c6d3fe34 | 1,347 | c | C | simulator/cpu/373/static_rom.c | lab11/M-ulator | 95b49c6194678c74accca4a20af71380efbcac5f | [
"Apache-2.0",
"MIT"
] | 19 | 2015-01-26T10:47:23.000Z | 2021-08-13T11:07:54.000Z | simulator/cpu/373/static_rom.c | lab11/M-ulator | 95b49c6194678c74accca4a20af71380efbcac5f | [
"Apache-2.0",
"MIT"
] | 14 | 2015-08-24T02:35:46.000Z | 2021-05-05T03:53:44.000Z | simulator/cpu/373/static_rom.c | lab11/M-ulator | 95b49c6194678c74accca4a20af71380efbcac5f | [
"Apache-2.0",
"MIT"
] | 9 | 2015-05-27T23:27:35.000Z | 2020-10-05T22:02:43.000Z | /* Mulator - An extensible {e,si}mulator
* Copyright 2011-2020 Pat Pannuto <pat.pannuto@gmail.com>
*
* Licensed under either of the Apache License, Version 2.0
* or the MIT license, at your option.
*/
// bintoarray.sh; "echo.bin"
#include <stdint.h>
uint32_t static_rom[107] = {0x20007FFC,0x81,0x53,0x57,0x5B,0x5F,0x63,0x51,0x51,0x51,0x51,0x67,0x6B,0x51,0x6F,0x73,0x77,0x79,0x7B,0x7D,0xF7FFE7FE,0xF7FFBFFD,0xF7FFBFFB,0xF7FFBFF9,0xF7FFBFF7,0xF7FFBFF5,0xF7FFBFF3,0xF7FFBFF1,0xF7FFBFEF,0x4770BFED,0x47704770,0xBF004770,0xF832F000,0xBFE4F7FF,0x4603B510,0xF811E004,0x3A014B01,0x4B01F803,0xD1F82A00,0xBF00BD10,0xB087B480,0x60F8AF00,0x607A60B9,0x617B68FB,0x68BBE007,0x697BB2DA,0x697B701A,0x301F103,0x687B617B,0xBF0C2B00,0x23012300,0x687AB2DB,0x32FFF102,0x2B00607A,0x68FBD1EB,0xF1074618,0x46BD071C,0x4770BC80,0xB082B580,0xF000AF00,0x4603F80B,0x79FB71FB,0xF0004618,0x2300F823,0x37084618,0xBD8046BD,0xB083B480,0xF44FAF00,0xF2C44382,0x607B0300,0x1304F244,0x300F2C4,0xBF00603B,0x781B687B,0xF003B2DB,0x2B000302,0x683BD0F8,0xB2DB781B,0x370C4618,0xF85D46BD,0x47707B04,0xB085B480,0x4603AF00,0xF44F71FB,0xF2C44382,0x60FB0300,0x1308F244,0x300F2C4,0xBF0060BB,0x781B68FB,0xF003B2DB,0x2B000304,0x68BBD1F8,0x701A79FA,0x46BD3714,0x7B04F85D,0xBF004770,0xB082B580,0x6078AF00,0x687BE007,0x4618781B,0xFFD6F7FF,0x3301687B,0x687B607B,0x2B00781B,0x3708D1F3,0xBD8046BD,};
| 122.454545 | 1,090 | 0.856719 |
f3101ad6f4d7801ed9f98ba409b0074317780e9d | 2,354 | h | C | FEAlertController/FEAlertController.h | Feelinging/FEAlertController | 0d11e8dad79bb4b7afb29ce0465c6e921195f6f3 | [
"MIT"
] | 1 | 2016-05-19T08:51:45.000Z | 2016-05-19T08:51:45.000Z | FEAlertController/FEAlertController.h | Feelinging/FEAlertController | 0d11e8dad79bb4b7afb29ce0465c6e921195f6f3 | [
"MIT"
] | null | null | null | FEAlertController/FEAlertController.h | Feelinging/FEAlertController | 0d11e8dad79bb4b7afb29ce0465c6e921195f6f3 | [
"MIT"
] | null | null | null | //
// FEAlertController.h
// FEAlertControllerDemo
//
// Created by feeling on 16/2/23.
// Copyright © 2016年 feeling. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "FEAlertContentView.h"
@class FEAlertController;
typedef void(^FEAlertControllerCallback)(FEAlertController *alertController, NSInteger buttonIndex);
@interface FEAlertController : UIViewController
@property (nonatomic, strong) FEAlertContentView *contentView;
@property (nonatomic, copy) id alertTitle; // NSString or NSAttributedString
@property (nonatomic, strong) UIImage *alertImage;
@property (nonatomic, strong) NSArray *alertAnimationImages; // for animation
@property (nonatomic, copy) id alertDescription; // NSString or NSAttributedString
@property (nonatomic, strong) NSArray *alertButtons;
@property (nonatomic, assign) NSInteger highlightButtonIndex;
/**
* If YES, then popup will get dismissed when background is touched. default = NO.
*/
@property (assign, nonatomic) BOOL shouldDismissOnBackgroundTouch;
/**
* method for initialization
*
* @param title At the top of the central
* @param image a photo
* @param description some text
* @param buttons The operation button list
* @param callback callback when tap operation button
*
* @return a alert ready to present
*/
+(instancetype)alertWithTitle:(id)title
image:(UIImage *)image
description:(id)description
buttons:(NSArray *)buttons
highlightButtonIndex:(NSInteger)highlightButtonIndex
callback:(FEAlertControllerCallback)callback;
/**
* initialize method, the alert will show on a new window
*
* @param title At the top of the central
* @param image a photo
* @param description some text
* @param buttons The operation button list
* @param callback callback when tap operation button
*
* @return a alert ready to present
*/
+ (instancetype)showWithTitle:(id)title
image:(UIImage *)image
description:(id)description
buttons:(NSArray *)buttons
highlightButtonIndex:(NSInteger)highlightButtonIndex
callback:(FEAlertControllerCallback)callback;
-(void)showInViewController:(UIViewController *)viewController;
-(void)dismiss;
@end
| 32.246575 | 100 | 0.696262 |
7e54d93859ef4d953d22769a2f7ce17ebe486d78 | 119 | c | C | STM32CubeFunctionPack_AWS1_V1.0.0/Projects/Multi/Applications/MQTT_AWS/Src/healthparameter.c | nguyendinhthi/learn_asw | 02dc3e609b5cbd3fbeb3dc4d1f5c7e7309a1fe3b | [
"Apache-2.0"
] | null | null | null | STM32CubeFunctionPack_AWS1_V1.0.0/Projects/Multi/Applications/MQTT_AWS/Src/healthparameter.c | nguyendinhthi/learn_asw | 02dc3e609b5cbd3fbeb3dc4d1f5c7e7309a1fe3b | [
"Apache-2.0"
] | null | null | null | STM32CubeFunctionPack_AWS1_V1.0.0/Projects/Multi/Applications/MQTT_AWS/Src/healthparameter.c | nguyendinhthi/learn_asw | 02dc3e609b5cbd3fbeb3dc4d1f5c7e7309a1fe3b | [
"Apache-2.0"
] | null | null | null | #include "stdint.h"
uint32_t PINGRESPCount;
uint32_t PINGREQCount;
uint32_t WifiUartRxCount;
uint32_t WifiUartTxCount;
| 19.833333 | 25 | 0.848739 |
f21682a672c1c03f949b891ca92322003dfee69c | 595 | c | C | lib/libc/platform/ananas/functions/posix/munmap.c | otaviopace/ananas | 849925915b0888543712a8ca625318cd7bca8dd9 | [
"Zlib"
] | 52 | 2015-11-27T13:56:00.000Z | 2021-12-01T16:33:58.000Z | lib/libc/platform/ananas/functions/posix/munmap.c | otaviopace/ananas | 849925915b0888543712a8ca625318cd7bca8dd9 | [
"Zlib"
] | 4 | 2017-06-26T17:59:51.000Z | 2021-09-26T17:30:32.000Z | lib/libc/platform/ananas/functions/posix/munmap.c | otaviopace/ananas | 849925915b0888543712a8ca625318cd7bca8dd9 | [
"Zlib"
] | 8 | 2016-08-26T09:42:27.000Z | 2021-12-04T00:21:05.000Z | /*-
* SPDX-License-Identifier: Zlib
*
* Copyright (c) 2009-2018 Rink Springer <rink@rink.nu>
* For conditions of distribution and use, see LICENSE file
*/
#include <ananas/types.h>
#include <ananas/syscall-vmops.h>
#include <ananas/syscalls.h>
#include <sys/mman.h>
#include <string.h>
#include "_map_statuscode.h"
int munmap(void* addr, size_t len)
{
struct VMOP_OPTIONS vo;
memset(&vo, 0, sizeof(vo));
vo.vo_size = sizeof(vo);
vo.vo_op = OP_UNMAP;
vo.vo_addr = addr;
vo.vo_len = len;
statuscode_t status = sys_vmop(&vo);
return map_statuscode(status);
}
| 22.884615 | 59 | 0.678992 |
f1b2a479cb8077524f589faef0cc77980f7e1c0b | 7,570 | c | C | MSP430G2xx3_Code_Examples/C/msp430g2xx3_ta_uart2400.c | collin-allen/ELEC327 | bde156ac3d1e5f3a7320d84068ccc8da93be8a91 | [
"MIT"
] | 4 | 2015-05-18T12:55:02.000Z | 2020-06-11T18:00:05.000Z | MSP430G2xx3_Code_Examples/C/msp430g2xx3_ta_uart2400.c | collin-allen/ELEC327 | bde156ac3d1e5f3a7320d84068ccc8da93be8a91 | [
"MIT"
] | null | null | null | MSP430G2xx3_Code_Examples/C/msp430g2xx3_ta_uart2400.c | collin-allen/ELEC327 | bde156ac3d1e5f3a7320d84068ccc8da93be8a91 | [
"MIT"
] | 22 | 2015-02-02T05:08:10.000Z | 2022-02-09T23:37:57.000Z | /* --COPYRIGHT--,BSD_EX
* Copyright (c) 2012, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*******************************************************************************
*
* MSP430 CODE EXAMPLE DISCLAIMER
*
* MSP430 code examples are self-contained low-level programs that typically
* demonstrate a single peripheral function or device feature in a highly
* concise manner. For this the code may rely on the device's power-on default
* register values and settings such as the clock configuration and care must
* be taken when combining code from several examples to avoid potential side
* effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware
* for an API functional library-approach to peripheral configuration.
*
* --/COPYRIGHT--*/
//******************************************************************************
// MSP430G2xx3 Demo - Timer_A, Ultra-Low Pwr UART 2400 Echo, 32kHz ACLK
//
// Description: Use Timer_A CCR0 hardware output modes and SCCI data latch
// to implement UART function @ 2400 baud. Software does not directly read and
// write to RX and TX pins, instead proper use of output modes and SCCI data
// latch are demonstrated. Use of these hardware features eliminates ISR
// latency effects as hardware insures that output and input bit latching and
// timing are perfectly synchronised with Timer_A regardless of other
// software activity. In the Mainloop the UART function readies the UART to
// receive one character and waits in LPM3 with all activity interrupt driven.
// After a character has been received, the UART receive function forces exit
// from LPM3 in the Mainloop which echo's back the received character.
// ACLK = TACLK = LFXT1 = 32768Hz, MCLK = SMCLK = default DCO
// //* An external watch crystal is required on XIN XOUT for ACLK *//
//
// MSP430G2xx3
// -----------------
// /|\| XIN|-
// | | | 32kHz
// --|RST XOUT|-
// | |
// | CCI0B/TXD/P1.5|-------->
// | | 2400 8N1
// | CCI0A/RXD/P1.1|<--------
//
#define RXD 0x02 // RXD on P1.1
#define TXD 0x20 // TXD on P1.5
// Conditions for 2400 Baud SW UART, ACLK = 32768
#define Bitime_5 0x06 // ~ 0.5 bit length + small adjustment
#define Bitime 0x0E // 427us bit length ~ 2341 baud
unsigned int RXTXData;
unsigned char BitCnt;
void TX_Byte (void);
void RX_Ready (void);
// D. Dang
// Texas Instruments Inc.
// December 2010
// Built with CCS Version 4.2.0 and IAR Embedded Workbench Version: 5.10
//******************************************************************************
#include <msp430.h>
int main (void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
CCTL0 = OUT; // TXD Idle as Mark
TACTL = TASSEL_1 + MC_2; // ACLK, continuous mode
P1SEL = TXD + RXD; //
P1DIR = TXD; //
// Mainloop
for (;;)
{
RX_Ready(); // UART ready to RX one Byte
__bis_SR_register(LPM3_bits + GIE); // Enter LPM3 w/ interr until char RXed
TX_Byte(); // TX Back RXed Byte Received
}
}
// Function Transmits Character from RXTXData Buffer
void TX_Byte (void)
{
BitCnt = 0xA; // Load Bit counter, 8data + ST/SP
while (CCR0 != TAR) // Prevent async capture
CCR0 = TAR; // Current state of TA counter
CCR0 += Bitime; // Some time till first bit
RXTXData |= 0x100; // Add mark stop bit to RXTXData
RXTXData = RXTXData << 1; // Add space start bit
CCTL0 = CCIS0 + OUTMOD0 + CCIE; // TXD = mark = idle
while ( CCTL0 & CCIE ); // Wait for TX completion
}
// Function Readies UART to Receive Character into RXTXData Buffer
void RX_Ready (void)
{
BitCnt = 0x8; // Load Bit counter
CCTL0 = SCS + OUTMOD0 + CM1 + CAP + CCIE; // Sync, Neg Edge, Cap
}
// Timer A0 interrupt service routine
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(TIMER0_A0_VECTOR))) Timer_A (void)
#else
#error Compiler not supported!
#endif
{
CCR0 += Bitime; // Add Offset to CCR0
// TX
if (CCTL0 & CCIS0) // TX on CCI0B?
{
if ( BitCnt == 0)
CCTL0 &= ~ CCIE; // All bits TXed, disable interrupt
else
{
CCTL0 |= OUTMOD2; // TX Space
if (RXTXData & 0x01)
CCTL0 &= ~ OUTMOD2; // TX Mark
RXTXData = RXTXData >> 1;
BitCnt --;
}
}
// RX
else
{
if( CCTL0 & CAP ) // Capture mode = start bit edge
{
CCTL0 &= ~ CAP; // Switch from capture to compare mode
CCR0 += Bitime_5;
}
else
{
RXTXData = RXTXData >> 1;
if (CCTL0 & SCCI) // Get bit waiting in receive latch
RXTXData |= 0x80;
BitCnt --; // All bits RXed?
if ( BitCnt == 0)
//>>>>>>>>>> Decode of Received Byte Here <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
{
CCTL0 &= ~ CCIE; // All bits RXed, disable interrupt
__bic_SR_register_on_exit(LPM3_bits); // Clear LPM3 bits from 0(SR)
}
//>>>>>>>>>> Decode of Received Byte Here <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
}
| 41.36612 | 84 | 0.564993 |
0be62c73ba6611da6770f5b877a34a7e854aa18a | 279 | h | C | glass/src/app/native/cpp/camerasupport.h | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 707 | 2016-05-11T16:54:13.000Z | 2022-03-30T13:03:15.000Z | glass/src/app/native/cpp/camerasupport.h | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 2,308 | 2016-05-12T00:17:17.000Z | 2022-03-30T20:08:10.000Z | glass/src/app/native/cpp/camerasupport.h | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 539 | 2016-05-11T20:33:26.000Z | 2022-03-28T20:20:25.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
namespace glass {
bool HasCameraSupport();
} // namespace glass
| 27.9 | 74 | 0.752688 |
6052f5cb6faba7419680c25a4dbd61d2a408fed4 | 1,275 | h | C | H624OwnPlayer/TrackSelector.h | tyazid/XMediaPlayer | cffceb1b19974af8a9d8f2c805b847ab037335d4 | [
"Apache-2.0"
] | 10 | 2017-06-11T22:52:21.000Z | 2021-12-22T02:48:54.000Z | H624OwnPlayer/TrackSelector.h | tyazid/XMediaPlayer | cffceb1b19974af8a9d8f2c805b847ab037335d4 | [
"Apache-2.0"
] | 1 | 2019-04-03T21:33:30.000Z | 2019-04-03T21:33:30.000Z | H624OwnPlayer/TrackSelector.h | tyazid/XMediaPlayer | cffceb1b19974af8a9d8f2c805b847ab037335d4 | [
"Apache-2.0"
] | null | null | null | //
// TrackSelector.h
// XMediaPlayer
//
// Created by tyazid on 29/01/2017.
// Copyright © 2017 tyazid. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "M3U8Kit.h"
#import "ABRStat.h"
#import "M3U8PlaylistModel.h"
#import "DefaultBandwidthMeter.h"
@interface TrackSelector : NSObject
@property double bandwidthFraction;
@property (readonly) NSUInteger selectedIndex;
@property (readonly) M3U8ExtXStreamInf * selectedFormat;
@property (readonly) NSUInteger length;
-(instancetype) init __attribute__((unavailable("init not available")));
-(NSUInteger) determineIdealSelectedIndex:(NSTimeInterval) nowSec;
-(NSUInteger) playlisIndex:(M3U8ExtXStreamInf *) format;
-(void)updateSelectedTrack:(NSTimeInterval) bufferedDurationSec;
-(BOOL)continueLoadSegs : (NSTimeInterval)bufferedDurationSec : (BOOL) loading;
-(NSUInteger) determineMinBitrateIndex;
-(NSUInteger) determineMaxBitrateIndex;
-(NSUInteger) resolveSegIndex:(M3U8SegmentInfo*) previous playPos:(NSUInteger)playbackPositionUs
playlist:(M3U8MediaPlaylist*)mediaPlaylist switched:(BOOL)switched;
-(ABRStat*)peekStat;
-(ABRStat*)pullStat;
-(instancetype)initWithModel: (M3U8PlaylistModel*)model andBandWidthMeter: (DefaultBandwidthMeter*)meter;//Meter
@end
| 33.552632 | 113 | 0.774902 |
00a5958bdd9ebce9e235d86708799a67b4a366e3 | 1,622 | h | C | chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chromecast/cast_core/runtime/browser/url_rewrite/url_request_rewrite_type_converters.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_
#define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_
#include "components/url_rewrite/mojom/url_request_rewrite.mojom.h"
#include "mojo/public/cpp/bindings/type_converter.h"
#include "third_party/cast_core/public/src/proto/v2/url_rewrite.pb.h"
namespace mojo {
// This conversion is done with a TypeCoverter rather than a typemap because
// it is only done one way, from the gRPC type to the Mojo type. This conversion
// is only done once, in the browser process. These rules are validated after
// they have been converted into Mojo.
// In Core Runtime, we have a one-way flow from the untrusted embedder into the
// browser process, via a gRPC API. From there, the rules are converted into
// Mojo and then validated before being sent to renderer processes. No further
// conversion is performed, the Mojo types are used as is to apply the rewrites
// on URL requests.
// Converter returns |nullptr| if conversion is not possible.
template <>
struct TypeConverter<url_rewrite::mojom::UrlRequestRewriteRulesPtr,
cast::v2::UrlRequestRewriteRules> {
static url_rewrite::mojom::UrlRequestRewriteRulesPtr Convert(
const cast::v2::UrlRequestRewriteRules& input);
};
} // namespace mojo
#endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_
| 47.705882 | 98 | 0.795931 |
446fb2513f18e1b6d6809dae0172bdde19637e92 | 1,028 | h | C | src/color.h | paracelso93/bizlib | e37615526c5d1284bef1ed4a1677a40d4e2604fc | [
"MIT"
] | null | null | null | src/color.h | paracelso93/bizlib | e37615526c5d1284bef1ed4a1677a40d4e2604fc | [
"MIT"
] | null | null | null | src/color.h | paracelso93/bizlib | e37615526c5d1284bef1ed4a1677a40d4e2604fc | [
"MIT"
] | null | null | null | //
// Created by edoardo biasio on 2021-01-21.
//
#ifndef OPENGL_COLOR_H
#define OPENGL_COLOR_H
namespace biz {
struct ColorFloat {
float r, g, b, a;
ColorFloat() {
r = g = b = a = 0.f;
}
ColorFloat(float r, float g, float b, float a) {
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
};
struct Color {
unsigned char r, g, b, a;
Color() {
r = g = b = a = 0;
}
Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
ColorFloat normalize() {
return ColorFloat(
static_cast<float>(r) / 255.f,
static_cast<float>(g) / 255.f,
static_cast<float>(b) / 255.f,
static_cast<float>(a) / 255.f);
}
};
}
#endif //OPENGL_COLOR_H
| 21.416667 | 83 | 0.427043 |
1390c132729424ba9b0ef783bb459e63d37041e6 | 786 | h | C | TimeCountDownFour/CETimeCountDownLabelManager.h | GitNilCom/CountDownFour | 700b4bf4259129a5cb2b6ff0ada3f859cd873df1 | [
"MIT"
] | 1 | 2020-06-30T02:07:27.000Z | 2020-06-30T02:07:27.000Z | TimeCountDownFour/CETimeCountDownLabelManager.h | GitNilCom/CountDownFour | 700b4bf4259129a5cb2b6ff0ada3f859cd873df1 | [
"MIT"
] | null | null | null | TimeCountDownFour/CETimeCountDownLabelManager.h | GitNilCom/CountDownFour | 700b4bf4259129a5cb2b6ff0ada3f859cd873df1 | [
"MIT"
] | null | null | null | //
// CETimeCountDownLabelManager.h
// CountDownFour
//
// Created by CE on 2017/7/14.
// Copyright © 2017年 CE. All rights reserved.
//
#import <Foundation/Foundation.h>
@class CETimeCountDownLabel;
@protocol CETimeCountDownLabelManagerDelegate <NSObject>
- (NSAttributedString *)labelTimeStringWithModel:(id)model timeLabel:(CETimeCountDownLabel *)timeLabel;
- (void)labelOutDateWithTimeLabel:(CETimeCountDownLabel *)timeLabel;
@end
@interface CETimeCountDownLabelManager : NSObject
@property (nonatomic ,weak) id <CETimeCountDownLabelManagerDelegate> delegate;
/**
添加倒计时,添加后自动启动定时器 ,一般用于页面上可见少量的定时器
@param timeLabel 时间视图
@param time 时间
*/
- (void)addTimeLabel:(CETimeCountDownLabel *)timeLabel time:(NSString *)time;
/**
销毁定时器
*/
- (void)destoryLabelTimer;
@end
| 20.684211 | 103 | 0.768448 |
7aa1e64ec59e86071437b56ff7fbfdd8e6bf1c23 | 1,249 | h | C | main.h | cppf/interpreter_expression | 9a83c1fb9f2d4289dedfc4b9320c5aa2fd2d2a2e | [
"MIT"
] | 1 | 2021-03-02T16:16:03.000Z | 2021-03-02T16:16:03.000Z | main.h | cppf/interpreter_expression | 9a83c1fb9f2d4289dedfc4b9320c5aa2fd2d2a2e | [
"MIT"
] | null | null | null | main.h | cppf/interpreter_expression | 9a83c1fb9f2d4289dedfc4b9320c5aa2fd2d2a2e | [
"MIT"
] | null | null | null | #pragma once
#include <string>
using namespace std;
struct Ast {
virtual void postfix(string*) {}
virtual int eval() { return 0; }
};
struct Int : Ast {
int v;
Int(int _v) { v = _v; }
void postfix(string *s) { char b[32]; sprintf(b, "%d", v); s->append(b); }
int eval() { return v; }
};
struct Add : Ast {
Ast *x, *y;
Add(Ast *_x, Ast *_y) { x = _x; y = _y; }
void postfix(string *s) { s->append("(+ "); x->postfix(s); s->append(" "); y->postfix(s); s->append(")"); }
int eval() { return x->eval() + y->eval(); }
};
struct Sub : Ast {
Ast *x, *y;
Sub(Ast *_x, Ast *_y) { x = _x; y = _y; }
void postfix(string *s) { s->append("(- "); x->postfix(s); s->append(" "); y->postfix(s); s->append(")"); }
int eval() { return x->eval() - y->eval(); }
};
struct Mul : Ast {
Ast *x, *y;
Mul(Ast *_x, Ast *_y) { x = _x; y = _y; }
void postfix(string *s) { s->append("(* "); x->postfix(s); s->append(" "); y->postfix(s); s->append(")"); }
int eval() { return x->eval() * y->eval(); }
};
struct Div : Ast {
Ast *x, *y;
Div(Ast *_x, Ast *_y) { x = _x; y = _y; }
void postfix(string *s) { s->append("(/ "); x->postfix(s); s->append(" "); y->postfix(s); s->append(")"); }
int eval() { return x->eval() / y->eval(); }
};
| 31.225 | 109 | 0.514011 |
ff07304fe818b12da991e50f428f911b2597768d | 117 | h | C | build/stx/support/tools/splint-3.1.2/src/Headers/signature2.h | GunterMueller/ST_STX_Fork | d891b139f3c016b81feeb5bf749e60585575bff7 | [
"MIT"
] | 1 | 2020-01-23T20:46:08.000Z | 2020-01-23T20:46:08.000Z | build/stx/support/tools/splint-3.1.2/src/Headers/signature2.h | GunterMueller/ST_STX_Fork | d891b139f3c016b81feeb5bf749e60585575bff7 | [
"MIT"
] | null | null | null | build/stx/support/tools/splint-3.1.2/src/Headers/signature2.h | GunterMueller/ST_STX_Fork | d891b139f3c016b81feeb5bf749e60585575bff7 | [
"MIT"
] | null | null | null | # ifndef SIGNATURE2_H
# define SIGNATURE2_H
# include "signature_gen.h"
# else
# error "Multiple includes"
# endif
| 13 | 27 | 0.74359 |
9e4b0a925f76921d5903f7336b05915e486d5b33 | 454 | c | C | LAB09/test.c | Kiszczomb/pwr-itp | 544f55331ff2be81ea91567af7755bcf440f997d | [
"MIT"
] | null | null | null | LAB09/test.c | Kiszczomb/pwr-itp | 544f55331ff2be81ea91567af7755bcf440f997d | [
"MIT"
] | null | null | null | LAB09/test.c | Kiszczomb/pwr-itp | 544f55331ff2be81ea91567af7755bcf440f997d | [
"MIT"
] | null | null | null | #include <stdio.h>
// TODO: test this behavior from inside a function
char *modi(char *str, int pos, char ch) {
char *ptr = str + pos;
*ptr = ch;
return str;
}
int main() {
char arr[] = "Welcome to Wroclaw";
printf("%s\n", arr);
char *p_arr = &arr[0];
printf("%c\n", *p_arr);
p_arr+=2;
*p_arr = 't';
printf("%c\n", *p_arr);
printf("%s\n", arr);
printf("%s\n", modi(arr, 10 ,'\0'));
return 0;
}
| 18.916667 | 50 | 0.515419 |
9e59c42b14abcbdac0c6b5c79523c5c80144a24b | 33,911 | h | C | libs/graphs/include/mrpt/graphs/CNetworkOfPoses_impl.h | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 4 | 2017-08-04T15:44:04.000Z | 2021-02-02T02:00:18.000Z | libs/graphs/include/mrpt/graphs/CNetworkOfPoses_impl.h | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | null | null | null | libs/graphs/include/mrpt/graphs/CNetworkOfPoses_impl.h | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 2 | 2017-10-03T23:10:09.000Z | 2018-07-29T09:41:33.000Z | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#ifndef CONSTRAINED_POSE_NETWORK_IMPL_H
#define CONSTRAINED_POSE_NETWORK_IMPL_H
#include <mrpt/graphs/dijkstra.h>
#include <mrpt/utils/CTextFileLinesParser.h>
#include <mrpt/math/lightweight_geom_data.h>
#include <mrpt/math/CArrayNumeric.h>
#include <mrpt/math/wrap2pi.h>
#include <mrpt/math/ops_matrices.h> // multiply_*()
#include <mrpt/math/matrix_serialization.h>
#include <mrpt/system/string_utils.h>
#include <mrpt/poses/CPose2D.h>
#include <mrpt/poses/CPose3D.h>
#include <mrpt/poses/CPose3DQuat.h>
#include <mrpt/poses/CPosePDFGaussian.h>
#include <mrpt/poses/CPosePDFGaussianInf.h>
#include <mrpt/poses/CPose3DPDFGaussian.h>
#include <mrpt/poses/CPose3DPDFGaussianInf.h>
#include <mrpt/graphs/TNodeAnnotations.h>
namespace mrpt
{
namespace graphs
{
namespace detail
{
using namespace std;
using namespace mrpt;
using namespace mrpt::utils;
using namespace mrpt::poses;
using namespace mrpt::graphs;
template <class POSE_PDF>
struct TPosePDFHelper
{
static inline void copyFrom2D(POSE_PDF& p, const CPosePDFGaussianInf& pdf)
{
p.copyFrom(pdf);
}
static inline void copyFrom3D(POSE_PDF& p, const CPose3DPDFGaussianInf& pdf)
{
p.copyFrom(pdf);
}
};
template <>
struct TPosePDFHelper<CPose2D>
{
static inline void copyFrom2D(CPose2D& p, const CPosePDFGaussianInf& pdf)
{
p = pdf.mean;
}
static inline void copyFrom3D(CPose2D& p, const CPose3DPDFGaussianInf& pdf)
{
p = CPose2D(pdf.mean);
}
};
template <>
struct TPosePDFHelper<CPose3D>
{
static inline void copyFrom2D(CPose3D& p, const CPosePDFGaussianInf& pdf)
{
p = CPose3D(pdf.mean);
}
static inline void copyFrom3D(CPose3D& p, const CPose3DPDFGaussianInf& pdf)
{
p = pdf.mean;
}
};
/// a helper struct with static template functions \sa CNetworkOfPoses
template <class graph_t>
struct graph_ops
{
static void write_VERTEX_line(
const TNodeID id, const mrpt::poses::CPose2D& p, std::ofstream& f)
{
// VERTEX2 id x y phi
f << "VERTEX2 " << id << " " << p.x() << " " << p.y() << " " << p.phi();
}
static void write_VERTEX_line(
const TNodeID id, const mrpt::poses::CPose3D& p, std::ofstream& f)
{
// VERTEX3 id x y z roll pitch yaw
// **CAUTION** In the TORO graph format angles are in the RPY order vs.
// MRPT's YPR.
f << "VERTEX3 " << id << " " << p.x() << " " << p.y() << " " << p.z()
<< " " << p.roll() << " " << p.pitch() << " " << p.yaw();
}
static void write_EDGE_line(
const TPairNodeIDs& edgeIDs, const CPosePDFGaussianInf& edge,
std::ofstream& f)
{
// EDGE2 from_id to_id Ax Ay Aphi inf_xx inf_xy inf_yy inf_pp inf_xp
// inf_yp
// **CAUTION** TORO docs say "from_id" "to_id" in the opposite order,
// but it seems from the data that this is the correct expected format.
f << "EDGE2 " << edgeIDs.first << " " << edgeIDs.second << " "
<< edge.mean.x() << " " << edge.mean.y() << " " << edge.mean.phi()
<< " " << edge.cov_inv(0, 0) << " " << edge.cov_inv(0, 1) << " "
<< edge.cov_inv(1, 1) << " " << edge.cov_inv(2, 2) << " "
<< edge.cov_inv(0, 2) << " " << edge.cov_inv(1, 2) << endl;
}
static void write_EDGE_line(
const TPairNodeIDs& edgeIDs, const CPose3DPDFGaussianInf& edge,
std::ofstream& f)
{
// EDGE3 from_id to_id Ax Ay Az Aroll Apitch Ayaw inf_11 inf_12 ..
// inf_16 inf_22 .. inf_66
// **CAUTION** In the TORO graph format angles are in the RPY order vs.
// MRPT's YPR.
// **CAUTION** TORO docs say "from_id" "to_id" in the opposite order,
// but it seems from the data that this is the correct expected format.
f << "EDGE3 " << edgeIDs.first << " " << edgeIDs.second << " "
<< edge.mean.x() << " " << edge.mean.y() << " " << edge.mean.z()
<< " " << edge.mean.roll() << " " << edge.mean.pitch() << " "
<< edge.mean.yaw() << " " << edge.cov_inv(0, 0) << " "
<< edge.cov_inv(0, 1) << " " << edge.cov_inv(0, 2) << " "
<< edge.cov_inv(0, 5) << " " << edge.cov_inv(0, 4) << " "
<< edge.cov_inv(0, 3) << " " << edge.cov_inv(1, 1) << " "
<< edge.cov_inv(1, 2) << " " << edge.cov_inv(1, 5) << " "
<< edge.cov_inv(1, 4) << " " << edge.cov_inv(1, 3) << " "
<< edge.cov_inv(2, 2) << " " << edge.cov_inv(2, 5) << " "
<< edge.cov_inv(2, 4) << " " << edge.cov_inv(2, 3) << " "
<< edge.cov_inv(5, 5) << " " << edge.cov_inv(5, 4) << " "
<< edge.cov_inv(5, 3) << " " << edge.cov_inv(4, 4) << " "
<< edge.cov_inv(4, 3) << " " << edge.cov_inv(3, 3) << endl;
}
static void write_EDGE_line(
const TPairNodeIDs& edgeIDs, const CPosePDFGaussian& edge,
std::ofstream& f)
{
CPosePDFGaussianInf p;
p.copyFrom(edge);
write_EDGE_line(edgeIDs, p, f);
}
static void write_EDGE_line(
const TPairNodeIDs& edgeIDs, const CPose3DPDFGaussian& edge,
std::ofstream& f)
{
CPose3DPDFGaussianInf p;
p.copyFrom(edge);
write_EDGE_line(edgeIDs, p, f);
}
static void write_EDGE_line(
const TPairNodeIDs& edgeIDs, const mrpt::poses::CPose2D& edge,
std::ofstream& f)
{
CPosePDFGaussianInf p;
p.mean = edge;
p.cov_inv.unit(3, 1.0);
write_EDGE_line(edgeIDs, p, f);
}
static void write_EDGE_line(
const TPairNodeIDs& edgeIDs, const mrpt::poses::CPose3D& edge,
std::ofstream& f)
{
CPose3DPDFGaussianInf p;
p.mean = edge;
p.cov_inv.unit(6, 1.0);
write_EDGE_line(edgeIDs, p, f);
}
// =================================================================
// save_graph_of_poses_to_text_file
// =================================================================
static void save_graph_of_poses_to_text_file(
const graph_t* g, const std::string& fil)
{
std::ofstream f;
f.open(fil.c_str());
if (!f.is_open())
THROW_EXCEPTION_FMT(
"Error opening file '%s' for writing", fil.c_str());
// 1st: Nodes
for (typename graph_t::global_poses_t::const_iterator itNod =
g->nodes.begin();
itNod != g->nodes.end(); ++itNod)
{
write_VERTEX_line(itNod->first, itNod->second, f);
// write whatever the NODE_ANNOTATION instance want's to write.
f << " | " << itNod->second.retAnnotsAsString() << endl;
}
// 2nd: Edges:
for (typename graph_t::const_iterator it = g->begin(); it != g->end();
++it)
if (it->first.first != it->first.second) // Ignore self-edges,
// typically from
// importing files with
// EQUIV's
write_EDGE_line(it->first, it->second, f);
} // end save_graph
// =================================================================
// save_graph_of_poses_to_binary_file
// =================================================================
static void save_graph_of_poses_to_binary_file(
const graph_t* g, mrpt::utils::CStream& out)
{
// Store class name:
const std::string sClassName = TTypeName<graph_t>::get();
out << sClassName;
// Store serialization version & object data:
const uint32_t version = 0;
out << version;
out << g->nodes << g->edges << g->root;
}
// =================================================================
// read_graph_of_poses_from_binary_file
// =================================================================
static void read_graph_of_poses_from_binary_file(
graph_t* g, mrpt::utils::CStream& in)
{
// Compare class name:
const std::string sClassName = TTypeName<graph_t>::get();
std::string sStoredClassName;
in >> sStoredClassName;
ASSERT_EQUAL_(sStoredClassName, sClassName)
// Check serialization version:
uint32_t stored_version;
in >> stored_version;
g->clear();
switch (stored_version)
{
case 0:
in >> g->nodes >> g->edges >> g->root;
break;
default:
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(stored_version)
}
}
// =================================================================
// load_graph_of_poses_from_text_file
// =================================================================
static void load_graph_of_poses_from_text_file(
graph_t* g, const std::string& fil)
{
using mrpt::system::strCmpI;
using namespace mrpt::math;
typedef typename graph_t::constraint_t CPOSE;
set<string> alreadyWarnedUnknowns; // for unknown line types, show a
// warning to cerr just once.
// First, empty the graph:
g->clear();
// Determine if it's a 2D or 3D graph, just to raise an error if loading
// a 3D graph in a 2D one, since
// it would be an unintentional loss of information:
const bool graph_is_3D = CPOSE::is_3D();
CTextFileLinesParser filParser(fil); // raises an exception on error
// -------------------------------------------
// 1st PASS: Read EQUIV entries only
// since processing them AFTER loading the data
// is much much slower.
// -------------------------------------------
map<TNodeID, TNodeID> lstEquivs; // List of EQUIV entries: NODEID ->
// NEWNODEID. NEWNODEID will be always
// the lowest ID number.
// Read & process lines each at once until EOF:
istringstream s;
while (filParser.getNextLine(s))
{
const unsigned int lineNum = filParser.getCurrentLineNumber();
const string lin = s.str();
string key;
if (!(s >> key) || key.empty())
THROW_EXCEPTION(
format(
"Line %u: Can't read string for entry type in: '%s'",
lineNum, lin.c_str()));
if (mrpt::system::strCmpI(key, "EQUIV"))
{
// Process these ones at the end, for now store in a list:
TNodeID id1, id2;
if (!(s >> id1 >> id2))
THROW_EXCEPTION(
format(
"Line %u: Can't read id1 & id2 in EQUIV line: '%s'",
lineNum, lin.c_str()));
lstEquivs[std::max(id1, id2)] = std::min(id1, id2);
}
} // end 1st pass
// -------------------------------------------
// 2nd PASS: Read all other entries
// -------------------------------------------
filParser.rewind();
// Read & process lines each at once until EOF:
while (filParser.getNextLine(s))
{
const unsigned int lineNum = filParser.getCurrentLineNumber();
const string lin = s.str();
// Recognized strings:
// VERTEX2 id x y phi
// =(VERTEX_SE2)
// EDGE2 from_id to_id Ax Ay Aphi inf_xx inf_xy inf_yy inf_pp
// inf_xp inf_yp
// =(EDGE or EDGE_SE2 or ODOMETRY)
// VERTEX3 id x y z roll pitch yaw
// VERTEX_SE3:QUAT id x y z qx qy qz qw
// EDGE3 from_id to_id Ax Ay Az Aroll Apitch Ayaw inf_11 inf_12 ..
// inf_16 inf_22 .. inf_66
// EDGE_SE3:QUAT from_id to_id Ax Ay Az qx qy qz qw inf_11 inf_12
// .. inf_16 inf_22 .. inf_66
// EQUIV id1 id2
string key;
if (!(s >> key) || key.empty())
THROW_EXCEPTION(
format(
"Line %u: Can't read string for entry type in: '%s'",
lineNum, lin.c_str()));
if (strCmpI(key, "VERTEX2") || strCmpI(key, "VERTEX") ||
strCmpI(key, "VERTEX_SE2"))
{
TNodeID id;
TPose2D p2D;
if (!(s >> id >> p2D.x >> p2D.y >> p2D.phi))
THROW_EXCEPTION(
format(
"Line %u: Error parsing VERTEX2 line: '%s'",
lineNum, lin.c_str()));
// Make sure the node is new:
if (g->nodes.find(id) != g->nodes.end())
THROW_EXCEPTION(
format(
"Line %u: Error, duplicated verted ID %u in line: "
"'%s'",
lineNum, static_cast<unsigned int>(id),
lin.c_str()));
// EQUIV? Replace ID by new one.
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(id);
if (itEq != lstEquivs.end()) id = itEq->second;
}
// Add to map: ID -> absolute pose:
if (g->nodes.find(id) == g->nodes.end())
{
typedef typename CNetworkOfPoses<
CPOSE>::constraint_t::type_value pose_t;
pose_t& newNode = g->nodes[id];
newNode = pose_t(
CPose2D(
p2D)); // Convert to mrpt::poses::CPose3D if needed
}
}
else if (strCmpI(key, "VERTEX3"))
{
if (!graph_is_3D)
THROW_EXCEPTION(
format(
"Line %u: Try to load VERTEX3 into a 2D graph: "
"'%s'",
lineNum, lin.c_str()));
// VERTEX3 id x y z roll pitch yaw
TNodeID id;
TPose3D p3D;
// **CAUTION** In the TORO graph format angles are in the RPY
// order vs. MRPT's YPR.
if (!(s >> id >> p3D.x >> p3D.y >> p3D.z >> p3D.roll >>
p3D.pitch >> p3D.yaw))
THROW_EXCEPTION(
format(
"Line %u: Error parsing VERTEX3 line: '%s'",
lineNum, lin.c_str()));
// Make sure the node is new:
if (g->nodes.find(id) != g->nodes.end())
THROW_EXCEPTION(
format(
"Line %u: Error, duplicated verted ID %u in line: "
"'%s'",
lineNum, static_cast<unsigned int>(id),
lin.c_str()));
// EQUIV? Replace ID by new one.
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(id);
if (itEq != lstEquivs.end()) id = itEq->second;
}
// Add to map: ID -> absolute pose:
if (g->nodes.find(id) == g->nodes.end())
{
g->nodes[id] = typename CNetworkOfPoses<CPOSE>::
constraint_t::type_value(
CPose3D(
p3D)); // Auto converted to CPose2D if needed
}
}
else if (strCmpI(key, "VERTEX_SE3:QUAT"))
{
if (!graph_is_3D)
THROW_EXCEPTION(
format(
"Line %u: Try to load VERTEX_SE3:QUAT into a 2D "
"graph: '%s'",
lineNum, lin.c_str()));
// VERTEX_SE3:QUAT id x y z qx qy qz qw
TNodeID id;
TPose3DQuat p3D;
if (!(s >> id >> p3D.x >> p3D.y >> p3D.z >> p3D.qx >> p3D.qy >>
p3D.qz >> p3D.qr))
THROW_EXCEPTION(
format(
"Line %u: Error parsing VERTEX_SE3:QUAT line: '%s'",
lineNum, lin.c_str()));
// Make sure the node is new:
if (g->nodes.find(id) != g->nodes.end())
THROW_EXCEPTION(
format(
"Line %u: Error, duplicated verted ID %u in line: "
"'%s'",
lineNum, static_cast<unsigned int>(id),
lin.c_str()));
// EQUIV? Replace ID by new one.
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(id);
if (itEq != lstEquivs.end()) id = itEq->second;
}
// Add to map: ID -> absolute pose:
if (g->nodes.find(id) == g->nodes.end())
{
g->nodes[id] = typename CNetworkOfPoses<CPOSE>::
constraint_t::type_value(
CPose3D(CPose3DQuat(p3D))); // Auto converted to
// CPose2D if needed
}
}
else if (
strCmpI(key, "EDGE2") || strCmpI(key, "EDGE") ||
strCmpI(key, "ODOMETRY") || strCmpI(key, "EDGE_SE2"))
{
// EDGE2 from_id to_id Ax Ay Aphi inf_xx inf_xy inf_yy inf_pp
// inf_xp inf_yp
// s00 s01 s11 s22
// s02 s12
// Read values are:
// [ s00 s01 s02 ]
// [ - s11 s12 ]
// [ - - s22 ]
//
TNodeID to_id, from_id;
if (!(s >> from_id >> to_id))
THROW_EXCEPTION(
format(
"Line %u: Error parsing EDGE2 line: '%s'", lineNum,
lin.c_str()));
// EQUIV? Replace ID by new one.
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(to_id);
if (itEq != lstEquivs.end()) to_id = itEq->second;
}
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(from_id);
if (itEq != lstEquivs.end()) from_id = itEq->second;
}
if (from_id != to_id) // Don't load self-edges! (probably come
// from an EQUIV)
{
TPose2D Ap_mean;
mrpt::math::CMatrixDouble33 Ap_cov_inv;
if (!(s >> Ap_mean.x >> Ap_mean.y >> Ap_mean.phi >>
Ap_cov_inv(0, 0) >> Ap_cov_inv(0, 1) >>
Ap_cov_inv(1, 1) >> Ap_cov_inv(2, 2) >>
Ap_cov_inv(0, 2) >> Ap_cov_inv(1, 2)))
THROW_EXCEPTION(
format(
"Line %u: Error parsing EDGE2 line: '%s'",
lineNum, lin.c_str()));
// Complete low triangular part of inf matrix:
Ap_cov_inv(1, 0) = Ap_cov_inv(0, 1);
Ap_cov_inv(2, 0) = Ap_cov_inv(0, 2);
Ap_cov_inv(2, 1) = Ap_cov_inv(1, 2);
// Convert to 2D cov, 3D cov or 3D inv_cov as needed:
typename CNetworkOfPoses<CPOSE>::edge_t newEdge;
TPosePDFHelper<CPOSE>::copyFrom2D(
newEdge,
CPosePDFGaussianInf(CPose2D(Ap_mean), Ap_cov_inv));
g->insertEdge(from_id, to_id, newEdge);
}
}
else if (strCmpI(key, "EDGE3"))
{
if (!graph_is_3D)
THROW_EXCEPTION(
format(
"Line %u: Try to load EDGE3 into a 2D graph: '%s'",
lineNum, lin.c_str()));
// EDGE3 from_id to_id Ax Ay Az Aroll Apitch Ayaw inf_11 inf_12
// .. inf_16 inf_22 .. inf_66
TNodeID to_id, from_id;
if (!(s >> from_id >> to_id))
THROW_EXCEPTION(
format(
"Line %u: Error parsing EDGE3 line: '%s'", lineNum,
lin.c_str()));
// EQUIV? Replace ID by new one.
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(to_id);
if (itEq != lstEquivs.end()) to_id = itEq->second;
}
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(from_id);
if (itEq != lstEquivs.end()) from_id = itEq->second;
}
if (from_id != to_id) // Don't load self-edges! (probably come
// from an EQUIV)
{
TPose3D Ap_mean;
mrpt::math::CMatrixDouble66 Ap_cov_inv;
// **CAUTION** In the TORO graph format angles are in the
// RPY order vs. MRPT's YPR.
if (!(s >> Ap_mean.x >> Ap_mean.y >> Ap_mean.z >>
Ap_mean.roll >> Ap_mean.pitch >> Ap_mean.yaw))
THROW_EXCEPTION(
format(
"Line %u: Error parsing EDGE3 line: '%s'",
lineNum, lin.c_str()));
// **CAUTION** Indices are shuffled to the change YAW(3) <->
// ROLL(5) in the order of the data.
if (!(s >> Ap_cov_inv(0, 0) >> Ap_cov_inv(0, 1) >>
Ap_cov_inv(0, 2) >> Ap_cov_inv(0, 5) >>
Ap_cov_inv(0, 4) >> Ap_cov_inv(0, 3) >>
Ap_cov_inv(1, 1) >> Ap_cov_inv(1, 2) >>
Ap_cov_inv(1, 5) >> Ap_cov_inv(1, 4) >>
Ap_cov_inv(1, 3) >> Ap_cov_inv(2, 2) >>
Ap_cov_inv(2, 5) >> Ap_cov_inv(2, 4) >>
Ap_cov_inv(2, 3) >> Ap_cov_inv(5, 5) >>
Ap_cov_inv(5, 4) >> Ap_cov_inv(5, 3) >>
Ap_cov_inv(4, 4) >> Ap_cov_inv(4, 3) >>
Ap_cov_inv(3, 3)))
{
// Cov may be omitted in the file:
Ap_cov_inv.unit(6, 1.0);
if (alreadyWarnedUnknowns.find("MISSING_3D") ==
alreadyWarnedUnknowns.end())
{
alreadyWarnedUnknowns.insert("MISSING_3D");
cerr << "[CNetworkOfPoses::loadFromTextFile] "
<< fil << ":" << lineNum
<< ": Warning: Information matrix missing, "
"assuming unity.\n";
}
}
else
{
// Complete low triangular part of inf matrix:
for (size_t r = 1; r < 6; r++)
for (size_t c = 0; c < r; c++)
Ap_cov_inv(r, c) = Ap_cov_inv(c, r);
}
// Convert as needed:
typename CNetworkOfPoses<CPOSE>::edge_t newEdge;
TPosePDFHelper<CPOSE>::copyFrom3D(
newEdge,
CPose3DPDFGaussianInf(CPose3D(Ap_mean), Ap_cov_inv));
g->insertEdge(from_id, to_id, newEdge);
}
}
else if (strCmpI(key, "EDGE_SE3:QUAT"))
{
if (!graph_is_3D)
THROW_EXCEPTION(
format(
"Line %u: Try to load EDGE3 into a 2D graph: '%s'",
lineNum, lin.c_str()));
// EDGE_SE3:QUAT from_id to_id Ax Ay Az qx qy qz qw inf_11
// inf_12 .. inf_16 inf_22 .. inf_66
// EDGE3 from_id to_id Ax Ay Az Aroll Apitch Ayaw inf_11 inf_12
// .. inf_16 inf_22 .. inf_66
TNodeID to_id, from_id;
if (!(s >> from_id >> to_id))
THROW_EXCEPTION(
format(
"Line %u: Error parsing EDGE_SE3:QUAT line: '%s'",
lineNum, lin.c_str()));
// EQUIV? Replace ID by new one.
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(to_id);
if (itEq != lstEquivs.end()) to_id = itEq->second;
}
{
const map<TNodeID, TNodeID>::const_iterator itEq =
lstEquivs.find(from_id);
if (itEq != lstEquivs.end()) from_id = itEq->second;
}
if (from_id != to_id) // Don't load self-edges! (probably come
// from an EQUIV)
{
TPose3DQuat Ap_mean;
mrpt::math::CMatrixDouble66 Ap_cov_inv;
if (!(s >> Ap_mean.x >> Ap_mean.y >> Ap_mean.z >>
Ap_mean.qx >> Ap_mean.qy >> Ap_mean.qz >> Ap_mean.qr))
THROW_EXCEPTION(
format(
"Line %u: Error parsing EDGE_SE3:QUAT line: "
"'%s'",
lineNum, lin.c_str()));
// **CAUTION** Indices are shuffled to the change YAW(3) <->
// ROLL(5) in the order of the data.
if (!(s >> Ap_cov_inv(0, 0) >> Ap_cov_inv(0, 1) >>
Ap_cov_inv(0, 2) >> Ap_cov_inv(0, 5) >>
Ap_cov_inv(0, 4) >> Ap_cov_inv(0, 3) >>
Ap_cov_inv(1, 1) >> Ap_cov_inv(1, 2) >>
Ap_cov_inv(1, 5) >> Ap_cov_inv(1, 4) >>
Ap_cov_inv(1, 3) >> Ap_cov_inv(2, 2) >>
Ap_cov_inv(2, 5) >> Ap_cov_inv(2, 4) >>
Ap_cov_inv(2, 3) >> Ap_cov_inv(5, 5) >>
Ap_cov_inv(5, 4) >> Ap_cov_inv(5, 3) >>
Ap_cov_inv(4, 4) >> Ap_cov_inv(4, 3) >>
Ap_cov_inv(3, 3)))
{
// Cov may be omitted in the file:
Ap_cov_inv.unit(6, 1.0);
if (alreadyWarnedUnknowns.find("MISSING_3D") ==
alreadyWarnedUnknowns.end())
{
alreadyWarnedUnknowns.insert("MISSING_3D");
cerr << "[CNetworkOfPoses::loadFromTextFile] "
<< fil << ":" << lineNum
<< ": Warning: Information matrix missing, "
"assuming unity.\n";
}
}
else
{
// Complete low triangular part of inf matrix:
for (size_t r = 1; r < 6; r++)
for (size_t c = 0; c < r; c++)
Ap_cov_inv(r, c) = Ap_cov_inv(c, r);
}
// Convert as needed:
typename CNetworkOfPoses<CPOSE>::edge_t newEdge;
TPosePDFHelper<CPOSE>::copyFrom3D(
newEdge,
CPose3DPDFGaussianInf(
CPose3D(CPose3DQuat(Ap_mean)), Ap_cov_inv));
g->insertEdge(from_id, to_id, newEdge);
}
}
else if (strCmpI(key, "EQUIV"))
{
// Already read in the 1st pass.
}
else
{ // Unknown entry: Warn the user just once:
if (alreadyWarnedUnknowns.find(key) ==
alreadyWarnedUnknowns.end())
{
alreadyWarnedUnknowns.insert(key);
cerr << "[CNetworkOfPoses::loadFromTextFile] " << fil << ":"
<< lineNum << ": Warning: unknown entry type: " << key
<< endl;
}
}
} // end while
} // end load_graph
// --------------------------------------------------------------------------------
// Implements: collapseDuplicatedEdges
//
// Look for duplicated edges (even in opposite directions) between all pairs
// of nodes and fuse them.
// Upon return, only one edge remains between each pair of nodes with the
// mean
// & covariance (or information matrix) corresponding to the Bayesian
// fusion of all the Gaussians.
// --------------------------------------------------------------------------------
static size_t graph_of_poses_collapse_dup_edges(graph_t* g)
{
MRPT_START
typedef typename graph_t::edges_map_t::iterator TEdgeIterator;
// Data structure: (id1,id2) -> all edges between them
// (with id1 < id2)
typedef map<pair<TNodeID, TNodeID>, vector<TEdgeIterator>>
TListAllEdges; // For god's sake... when will ALL compilers support
// auto!! :'-(
TListAllEdges lstAllEdges;
// Clasify all edges to identify duplicated ones:
for (TEdgeIterator itEd = g->edges.begin(); itEd != g->edges.end();
++itEd)
{
// Build a pair <id1,id2> with id1 < id2:
const pair<TNodeID, TNodeID> arc_id = make_pair(
std::min(itEd->first.first, itEd->first.second),
std::max(itEd->first.first, itEd->first.second));
// get (or create the first time) the list of edges between them:
vector<TEdgeIterator>& lstEdges = lstAllEdges[arc_id];
// And add this one:
lstEdges.push_back(itEd);
}
// Now, remove all but the first edge:
size_t nRemoved = 0;
for (typename TListAllEdges::const_iterator it = lstAllEdges.begin();
it != lstAllEdges.end(); ++it)
{
const size_t N = it->second.size();
for (size_t i = 1; i < N; i++) // i=0 is NOT removed
g->edges.erase(it->second[i]);
if (N >= 2) nRemoved += N - 1;
}
return nRemoved;
MRPT_END
} // end of graph_of_poses_collapse_dup_edges
// --------------------------------------------------------------------------------
// Implements: dijkstra_nodes_estimate
//
// Compute a simple estimation of the global coordinates of each node just
// from the information in all edges, sorted in a Dijkstra tree based on the
// current "root" node.
// Note that "global" coordinates are with respect to the node with the ID
// specified in \a root.
// --------------------------------------------------------------------------------
static void graph_of_poses_dijkstra_init(graph_t* g)
{
MRPT_START;
using namespace std;
// Do Dijkstra shortest path from "root" to all other nodes:
typedef CDijkstra<graph_t, typename graph_t::maps_implementation_t>
dijkstra_t;
typedef typename graph_t::constraint_t constraint_t;
// initialize corresponding dijkstra object from root.
dijkstra_t dijkstra(*g, g->root);
// Get the tree representation of the graph and traverse it
// from its root toward the leafs:
typename dijkstra_t::tree_graph_t treeView;
dijkstra.getTreeGraph(treeView);
// This visitor class performs the real job of
struct VisitorComputePoses : public dijkstra_t::tree_graph_t::Visitor
{
graph_t* m_g; // The original graph
VisitorComputePoses(graph_t* g) : m_g(g) {}
virtual void OnVisitNode(
const TNodeID parent_id,
const typename dijkstra_t::tree_graph_t::Visitor::tree_t::
TEdgeInfo& edge_to_child,
const size_t depth_level) override
{
MRPT_UNUSED_PARAM(depth_level);
const TNodeID child_id = edge_to_child.id;
// Compute the pose of "child_id" as parent_pose (+)
// edge_delta_pose,
// taking into account that that edge may be in reverse order
// and then have to invert the delta_pose:
if ((!edge_to_child.reverse &&
!m_g->edges_store_inverse_poses) ||
(edge_to_child.reverse && m_g->edges_store_inverse_poses))
{ // pose_child = p_parent (+) p_delta
m_g->nodes[child_id].composeFrom(
m_g->nodes[parent_id],
edge_to_child.data->getPoseMean());
}
else
{ // pose_child = p_parent (+) [(-)p_delta]
m_g->nodes[child_id].composeFrom(
m_g->nodes[parent_id],
-edge_to_child.data->getPoseMean());
}
}
};
// Remove all global poses except for the root node, which is the
// origin:
//
// Keep track of the NODE_ANNOTATIONS for each node and put it after
// the global pose computation
bool empty_node_annots = g->nodes.begin()->second.is_node_annots_empty;
map<const TNodeID, TNodeAnnotations*> nodeID_to_annots;
if (!empty_node_annots)
{
for (typename graph_t::global_poses_t::const_iterator poses_cit =
g->nodes.begin();
poses_cit != g->nodes.end(); ++poses_cit)
{
nodeID_to_annots.insert(
make_pair(
poses_cit->first, poses_cit->second.getCopyOfAnnots()));
}
}
g->nodes.clear();
g->nodes[g->root] =
typename constraint_t::type_value(); // Typ: CPose2D() or CPose3D()
// Run the visit thru all nodes in the tree:
VisitorComputePoses myVisitor(g);
treeView.visitBreadthFirst(treeView.root, myVisitor);
// Fill the NODE_ANNOTATIONS part again
if (!empty_node_annots)
{
for (typename graph_t::global_poses_t::iterator poses_cit =
g->nodes.begin();
poses_cit != g->nodes.end(); ++poses_cit)
{
TNodeAnnotations* node_annots =
nodeID_to_annots.at(poses_cit->first);
bool res = poses_cit->second.setAnnots(*node_annots);
// free dynamically allocated mem
delete node_annots;
node_annots = NULL;
// make sure setting annotations was successful
ASSERTMSG_(
res, mrpt::format(
"Setting annotations for nodeID \"%lu\" was "
"unsuccessful",
static_cast<unsigned long>(poses_cit->first)));
}
}
MRPT_END
} // end of graph_of_poses_dijkstra_init
// Auxiliary funcs:
template <class VEC>
static inline double auxMaha2Dist(VEC& err, const CPosePDFGaussianInf& p)
{
math::wrapToPiInPlace(err[2]);
return mrpt::math::multiply_HCHt_scalar(
err, p.cov_inv); // err^t*cov_inv*err
}
template <class VEC>
static inline double auxMaha2Dist(VEC& err, const CPose3DPDFGaussianInf& p)
{
math::wrapToPiInPlace(err[3]);
math::wrapToPiInPlace(err[4]);
math::wrapToPiInPlace(err[5]);
return mrpt::math::multiply_HCHt_scalar(
err, p.cov_inv); // err^t*cov_inv*err
}
template <class VEC>
static inline double auxMaha2Dist(VEC& err, const CPosePDFGaussian& p)
{
math::wrapToPiInPlace(err[2]);
mrpt::math::CMatrixDouble33 COV_INV(mrpt::math::UNINITIALIZED_MATRIX);
p.cov.inv(COV_INV);
return mrpt::math::multiply_HCHt_scalar(
err, COV_INV); // err^t*cov_inv*err
}
template <class VEC>
static inline double auxMaha2Dist(VEC& err, const CPose3DPDFGaussian& p)
{
math::wrapToPiInPlace(err[3]);
math::wrapToPiInPlace(err[4]);
math::wrapToPiInPlace(err[5]);
mrpt::math::CMatrixDouble66 COV_INV(mrpt::math::UNINITIALIZED_MATRIX);
p.cov.inv(COV_INV);
return mrpt::math::multiply_HCHt_scalar(
err, COV_INV); // err^t*cov_inv*err
}
// These two are for simulating maha2 distances for non-PDF types: fallback
// to squared-norm:
template <class VEC>
static inline double auxMaha2Dist(VEC& err, const mrpt::poses::CPose2D& p)
{
math::wrapToPiInPlace(err[2]);
return square(err[0]) + square(err[1]) + square(err[2]);
}
template <class VEC>
static inline double auxMaha2Dist(VEC& err, const mrpt::poses::CPose3D& p)
{
math::wrapToPiInPlace(err[3]);
math::wrapToPiInPlace(err[4]);
math::wrapToPiInPlace(err[5]);
return square(err[0]) + square(err[1]) + square(err[2]) +
square(err[3]) + square(err[4]) + square(err[5]);
}
static inline double auxEuclid2Dist(
const mrpt::poses::CPose2D& p1, const mrpt::poses::CPose2D& p2)
{
return square(p1.x() - p2.x()) + square(p1.y() - p2.y()) +
square(mrpt::math::wrapToPi(p1.phi() - p2.phi()));
}
static inline double auxEuclid2Dist(
const mrpt::poses::CPose3D& p1, const mrpt::poses::CPose3D& p2)
{
return square(p1.x() - p2.x()) + square(p1.y() - p2.y()) +
square(p1.z() - p2.z()) +
square(mrpt::math::wrapToPi(p1.yaw() - p2.yaw())) +
square(mrpt::math::wrapToPi(p1.pitch() - p2.pitch())) +
square(mrpt::math::wrapToPi(p1.roll() - p2.roll()));
}
// --------------------------------------------------------------------------------
// Implements: detail::graph_edge_sqerror
//
// Compute the square error of a single edge, in comparison to the nodes
// global poses.
// --------------------------------------------------------------------------------
static double graph_edge_sqerror(
const graph_t* g,
const typename mrpt::graphs::CDirectedGraph<
typename graph_t::constraint_t>::edges_map_t::const_iterator&
itEdge,
bool ignoreCovariances)
{
MRPT_START
// Get node IDs:
const TNodeID from_id = itEdge->first.first;
const TNodeID to_id = itEdge->first.second;
// And their global poses as stored in "nodes"
typename graph_t::global_poses_t::const_iterator itPoseFrom =
g->nodes.find(from_id);
typename graph_t::global_poses_t::const_iterator itPoseTo =
g->nodes.find(to_id);
ASSERTMSG_(
itPoseFrom != g->nodes.end(),
format(
"Node %u doesn't have a global pose in 'nodes'.",
static_cast<unsigned int>(from_id)))
ASSERTMSG_(
itPoseTo != g->nodes.end(),
format(
"Node %u doesn't have a global pose in 'nodes'.",
static_cast<unsigned int>(to_id)))
// The global poses:
typedef typename graph_t::constraint_t constraint_t;
const typename constraint_t::type_value& from_mean = itPoseFrom->second;
const typename constraint_t::type_value& to_mean = itPoseTo->second;
// The delta_pose as stored in the edge:
const constraint_t& edge_delta_pose = itEdge->second;
const typename constraint_t::type_value& edge_delta_pose_mean =
edge_delta_pose.getPoseMean();
if (ignoreCovariances)
{ // Square Euclidean distance: Just use the mean values, ignore covs.
// from_plus_delta = from_mean (+) edge_delta_pose_mean
typename constraint_t::type_value from_plus_delta(
UNINITIALIZED_POSE);
from_plus_delta.composeFrom(from_mean, edge_delta_pose_mean);
// (auxMaha2Dist will also take into account the 2PI wrapping)
return auxEuclid2Dist(from_plus_delta, to_mean);
}
else
{
// Square Mahalanobis distance
// from_plus_delta = from_mean (+) edge_delta_pose (as a Gaussian)
constraint_t from_plus_delta = edge_delta_pose;
from_plus_delta.changeCoordinatesReference(from_mean);
// "from_plus_delta" is now a 3D or 6D Gaussian, to be compared to
// "to_mean":
// We want to compute the squared Mahalanobis distance:
// err^t * INV_COV * err
//
mrpt::math::CArrayDouble<constraint_t::type_value::static_size> err;
for (size_t i = 0; i < constraint_t::type_value::static_size; i++)
err[i] = from_plus_delta.getPoseMean()[i] - to_mean[i];
// (auxMaha2Dist will also take into account the 2PI wrapping)
return auxMaha2Dist(err, from_plus_delta);
}
MRPT_END
}
}; // end of graph_ops<graph_t>
} // end NS
} // end NS
} // end NS
#endif
| 32.450718 | 84 | 0.597594 |
9e7ef7b4c79b511e5e08cac775a7457f3b526710 | 821 | c | C | platform/busybox/debianutils/mktemp.c | CentecNetworks/Lantern | a32604a1df796a550bf6ffa5ded63020b875658e | [
"Apache-2.0"
] | 55 | 2015-01-20T00:09:45.000Z | 2021-08-19T05:40:27.000Z | platform/busybox/debianutils/mktemp.c | hehehexdc/Lantern | a32604a1df796a550bf6ffa5ded63020b875658e | [
"Apache-2.0"
] | 1 | 2017-04-22T18:17:57.000Z | 2017-09-15T11:28:26.000Z | platform/busybox/debianutils/mktemp.c | hehehexdc/Lantern | a32604a1df796a550bf6ffa5ded63020b875658e | [
"Apache-2.0"
] | 36 | 2015-02-13T00:58:22.000Z | 2021-08-19T08:08:07.000Z | /* vi: set sw=4 ts=4: */
/*
* Mini mktemp implementation for busybox
*
*
* Copyright (C) 2000 by Daniel Jacobowitz
* Written by Daniel Jacobowitz <dan@debian.org>
*
* Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
*/
#include "libbb.h"
int mktemp_main(int argc, char **argv);
int mktemp_main(int argc, char **argv)
{
unsigned long flags = getopt32(argc, argv, "dqt");
char *chp;
if (optind + 1 != argc)
bb_show_usage();
chp = argv[optind];
if (flags & 4) {
char *dir = getenv("TMPDIR");
if (dir && *dir != '\0')
chp = concat_path_file(dir, chp);
else
chp = concat_path_file("/tmp/", chp);
}
if (flags & 1) {
if (mkdtemp(chp) == NULL)
return EXIT_FAILURE;
} else {
if (mkstemp(chp) < 0)
return EXIT_FAILURE;
}
puts(chp);
return EXIT_SUCCESS;
}
| 18.244444 | 76 | 0.62972 |
cf9e6e4fd0b5cdf09d7e1b4e67a1c6a3e4683bd8 | 533 | h | C | Classes/gui/game/GameModeTypeViewController.h | fedelopez/closeup-ios | 1ea831ce55965b6e388251d614f27500dcf7ca8c | [
"CC-BY-4.0"
] | null | null | null | Classes/gui/game/GameModeTypeViewController.h | fedelopez/closeup-ios | 1ea831ce55965b6e388251d614f27500dcf7ca8c | [
"CC-BY-4.0"
] | null | null | null | Classes/gui/game/GameModeTypeViewController.h | fedelopez/closeup-ios | 1ea831ce55965b6e388251d614f27500dcf7ca8c | [
"CC-BY-4.0"
] | null | null | null | //
// GameModeTypeViewController.h
// CloseUp
//
// Created by Federico Lopez Laborda on 10/19/12.
// Copyright (c) 2012 FLL. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Game.h"
@interface GameModeTypeViewController : UIViewController {
UIImageView *heroView;
UILabel *heroLabel;
UIImage *heroImage;
NSString *heroText;
}
@property(nonatomic, assign) GameMode gameMode;
@property(nonatomic, retain) IBOutlet UIImageView *heroView;
@property(nonatomic, retain) IBOutlet UILabel *heroLabel;
@end
| 20.5 | 60 | 0.731707 |
d52b1cc62c8d5df35b77723cae7d2453fa3161c5 | 23,305 | h | C | tests/highwayhash/vector256.h | odidev/t1ha | 783e66f68814726308e6f4957583d2babce52a29 | [
"Zlib"
] | 108 | 2018-11-02T08:41:11.000Z | 2022-02-17T22:27:23.000Z | tests/highwayhash/vector256.h | odidev/t1ha | 783e66f68814726308e6f4957583d2babce52a29 | [
"Zlib"
] | 19 | 2018-11-02T06:54:37.000Z | 2021-09-02T15:45:40.000Z | tests/highwayhash/vector256.h | odidev/t1ha | 783e66f68814726308e6f4957583d2babce52a29 | [
"Zlib"
] | 17 | 2018-11-08T14:14:31.000Z | 2021-12-16T15:57:38.000Z | // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 HIGHWAYHASH_VECTOR256_H_
#define HIGHWAYHASH_VECTOR256_H_
// Defines SIMD vector classes ("V4x64U") with overloaded arithmetic operators:
// const V4x64U masked_sum = (a + b) & m;
// This is shorter and more readable than compiler intrinsics:
// const __m256i masked_sum = _mm256_and_si256(_mm256_add_epi64(a, b), m);
// There is typically no runtime cost for these abstractions.
//
// The naming convention is VNxBBT where N is the number of lanes, BB the
// number of bits per lane and T is the lane type: unsigned integer (U),
// signed integer (I), or floating-point (F).
// WARNING: this is a "restricted" header because it is included from
// translation units compiled with different flags. This header and its
// dependencies must not define any function unless it is static inline and/or
// within namespace HH_TARGET_NAME. See arch_specific.h for details.
#include <stddef.h>
#include <stdint.h>
#include "highwayhash/arch_specific.h"
#include "highwayhash/compiler_specific.h"
// For auto-dependency generation, we need to include all headers but not their
// contents (otherwise compilation fails because -mavx2 is not specified).
#ifndef HH_DISABLE_TARGET_SPECIFIC
// (This include cannot be moved within a namespace due to conflicts with
// other system headers; see the comment in hh_sse41.h.)
#include <immintrin.h>
namespace highwayhash {
// To prevent ODR violations when including this from multiple translation
// units (TU) that are compiled with different flags, the contents must reside
// in a namespace whose name is unique to the TU. NOTE: this behavior is
// incompatible with precompiled modules and requires textual inclusion instead.
namespace HH_TARGET_NAME {
// Primary template for 256-bit AVX2 vectors; only specializations are used.
template <typename T> class V256 {};
#if (defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER < 1900) && \
!defined(_mm_set_epi64x)
#define _mm_set_epi64x(A, B) \
_mm_set_epi32((uint32_t)((uint64_t)(A) >> 32), (uint32_t)(A), \
(uint32_t)((uint64_t)(B) >> 32), (uint32_t)(B))
#endif
#if !(defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || \
defined(_M_X64)) && \
!defined(_mm_cvtsi64_si128)
#define _mm_cvtsi64_si128(V64) _mm_set_epi64x(0, V64)
#endif
#if (HH_GCC_VERSION && HH_GCC_VERSION < 490 && !HH_CLANG_VERSION) || \
(HH_CLANG_VERSION && !__has_builtin(__builtin_ia32_undef256))
extern __inline __m256i __attribute__((__gnu_inline__, __always_inline__))
_mm256_undefined_si256(void) {
__m256i __Y = __Y;
return __Y;
}
#endif
template <> class V256<uint8_t> {
public:
using Intrinsic = __m256i;
using T = uint8_t;
static constexpr size_t N = 32;
// Leaves v_ uninitialized - typically used for output parameters.
HH_INLINE V256() : v_(_mm256_undefined_si256()) {}
// Broadcasts i to all lanes.
HH_INLINE explicit V256(T i)
: v_(_mm256_broadcastb_epi8(_mm_cvtsi32_si128(i))) {}
// Copy from other vector.
HH_INLINE explicit V256(const V256 &other) : v_(other.v_) {}
template <typename U>
HH_INLINE explicit V256(const V256<U> &other) : v_(other) {}
HH_INLINE V256 &operator=(const V256 &other) {
v_ = other.v_;
return *this;
}
// Convert from/to intrinsics.
HH_INLINE V256(const Intrinsic &v) : v_(v) {}
HH_INLINE V256 &operator=(const Intrinsic &v) {
v_ = v;
return *this;
}
HH_INLINE operator Intrinsic() const { return v_; }
// There are no greater-than comparison instructions for unsigned T.
HH_INLINE V256 operator==(const V256 &other) const {
return V256(_mm256_cmpeq_epi8(v_, other.v_));
}
HH_INLINE V256 &operator+=(const V256 &other) {
v_ = _mm256_add_epi8(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator-=(const V256 &other) {
v_ = _mm256_sub_epi8(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator&=(const V256 &other) {
v_ = _mm256_and_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator|=(const V256 &other) {
v_ = _mm256_or_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator^=(const V256 &other) {
v_ = _mm256_xor_si256(v_, other.v_);
return *this;
}
private:
Intrinsic v_;
};
template <> class V256<uint16_t> {
public:
using Intrinsic = __m256i;
using T = uint16_t;
static constexpr size_t N = 16;
// Leaves v_ uninitialized - typically used for output parameters.
HH_INLINE V256() {}
// Lane 0 (p_0) is the lowest.
HH_INLINE V256(T p_F, T p_E, T p_D, T p_C, T p_B, T p_A, T p_9, T p_8, T p_7,
T p_6, T p_5, T p_4, T p_3, T p_2, T p_1, T p_0)
: v_(_mm256_set_epi16(p_F, p_E, p_D, p_C, p_B, p_A, p_9, p_8, p_7, p_6,
p_5, p_4, p_3, p_2, p_1, p_0)) {}
// Broadcasts i to all lanes.
HH_INLINE explicit V256(T i)
: v_(_mm256_broadcastw_epi16(_mm_cvtsi32_si128(i))) {}
// Copy from other vector.
HH_INLINE explicit V256(const V256 &other) : v_(other.v_) {}
template <typename U>
HH_INLINE explicit V256(const V256<U> &other) : v_(other) {}
HH_INLINE V256 &operator=(const V256 &other) {
v_ = other.v_;
return *this;
}
// Convert from/to intrinsics.
HH_INLINE V256(const Intrinsic &v) : v_(v) {}
HH_INLINE V256 &operator=(const Intrinsic &v) {
v_ = v;
return *this;
}
HH_INLINE operator Intrinsic() const { return v_; }
// There are no greater-than comparison instructions for unsigned T.
HH_INLINE V256 operator==(const V256 &other) const {
return V256(_mm256_cmpeq_epi16(v_, other.v_));
}
HH_INLINE V256 &operator+=(const V256 &other) {
v_ = _mm256_add_epi16(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator-=(const V256 &other) {
v_ = _mm256_sub_epi16(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator&=(const V256 &other) {
v_ = _mm256_and_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator|=(const V256 &other) {
v_ = _mm256_or_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator^=(const V256 &other) {
v_ = _mm256_xor_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator<<=(const int count) {
v_ = _mm256_slli_epi16(v_, count);
return *this;
}
HH_INLINE V256 &operator>>=(const int count) {
v_ = _mm256_srli_epi16(v_, count);
return *this;
}
private:
Intrinsic v_;
};
template <> class V256<uint32_t> {
public:
using Intrinsic = __m256i;
using T = uint32_t;
static constexpr size_t N = 8;
// Leaves v_ uninitialized - typically used for output parameters.
HH_INLINE V256() {}
// Lane 0 (p_0) is the lowest.
HH_INLINE V256(T p_7, T p_6, T p_5, T p_4, T p_3, T p_2, T p_1, T p_0)
: v_(_mm256_set_epi32(p_7, p_6, p_5, p_4, p_3, p_2, p_1, p_0)) {}
// Broadcasts i to all lanes.
HH_INLINE explicit V256(T i)
: v_(_mm256_broadcastd_epi32(_mm_cvtsi32_si128(i))) {}
// Copy from other vector.
HH_INLINE explicit V256(const V256 &other) : v_(other.v_) {}
template <typename U>
HH_INLINE explicit V256(const V256<U> &other) : v_(other) {}
HH_INLINE V256 &operator=(const V256 &other) {
v_ = other.v_;
return *this;
}
// Convert from/to intrinsics.
HH_INLINE V256(const Intrinsic &v) : v_(v) {}
HH_INLINE V256 &operator=(const Intrinsic &v) {
v_ = v;
return *this;
}
HH_INLINE operator Intrinsic() const { return v_; }
// There are no greater-than comparison instructions for unsigned T.
HH_INLINE V256 operator==(const V256 &other) const {
return V256(_mm256_cmpeq_epi32(v_, other.v_));
}
HH_INLINE V256 &operator+=(const V256 &other) {
v_ = _mm256_add_epi32(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator-=(const V256 &other) {
v_ = _mm256_sub_epi32(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator&=(const V256 &other) {
v_ = _mm256_and_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator|=(const V256 &other) {
v_ = _mm256_or_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator^=(const V256 &other) {
v_ = _mm256_xor_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator<<=(const int count) {
v_ = _mm256_slli_epi32(v_, count);
return *this;
}
HH_INLINE V256 &operator>>=(const int count) {
v_ = _mm256_srli_epi32(v_, count);
return *this;
}
private:
Intrinsic v_;
};
template <> class V256<uint64_t> {
public:
using Intrinsic = __m256i;
using T = uint64_t;
static constexpr size_t N = 4;
// Leaves v_ uninitialized - typically used for output parameters.
HH_INLINE V256() {}
// Lane 0 (p_0) is the lowest.
HH_INLINE V256(T p_3, T p_2, T p_1, T p_0)
#if defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER < 1900
{
union {
uint64_t u64x4[4];
__m256i m256i;
} x;
x.u64x4[0] = p_0;
x.u64x4[1] = p_1;
x.u64x4[2] = p_2;
x.u64x4[3] = p_3;
v_ = x.m256i;
}
#else
: v_(_mm256_set_epi64x(p_3, p_2, p_1, p_0)) {
}
#endif
// Broadcasts i to all lanes.
HH_INLINE explicit V256(T i)
: v_(_mm256_broadcastq_epi64(_mm_cvtsi64_si128(i))) {}
// Copy from other vector.
HH_INLINE explicit V256(const V256 &other) : v_(other.v_) {}
template <typename U>
HH_INLINE explicit V256(const V256<U> &other) : v_(other) {}
HH_INLINE V256 &operator=(const V256 &other) {
v_ = other.v_;
return *this;
}
// Convert from/to intrinsics.
HH_INLINE V256(const Intrinsic &v) : v_(v) {}
HH_INLINE V256 &operator=(const Intrinsic &v) {
v_ = v;
return *this;
}
HH_INLINE operator Intrinsic() const { return v_; }
// There are no greater-than comparison instructions for unsigned T.
HH_INLINE V256 operator==(const V256 &other) const {
return V256(_mm256_cmpeq_epi64(v_, other.v_));
}
HH_INLINE V256 &operator+=(const V256 &other) {
v_ = _mm256_add_epi64(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator-=(const V256 &other) {
v_ = _mm256_sub_epi64(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator&=(const V256 &other) {
v_ = _mm256_and_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator|=(const V256 &other) {
v_ = _mm256_or_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator^=(const V256 &other) {
v_ = _mm256_xor_si256(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator<<=(const int count) {
v_ = _mm256_slli_epi64(v_, count);
return *this;
}
HH_INLINE V256 &operator>>=(const int count) {
v_ = _mm256_srli_epi64(v_, count);
return *this;
}
private:
Intrinsic v_;
};
template <> class V256<float> {
public:
using Intrinsic = __m256;
using T = float;
static constexpr size_t N = 8;
// Leaves v_ uninitialized - typically used for output parameters.
HH_INLINE V256() {}
// Lane 0 (p_0) is the lowest.
HH_INLINE V256(T p_7, T p_6, T p_5, T p_4, T p_3, T p_2, T p_1, T p_0)
: v_(_mm256_set_ps(p_7, p_6, p_5, p_4, p_3, p_2, p_1, p_0)) {}
// Broadcasts to all lanes.
HH_INLINE explicit V256(T f) : v_(_mm256_set1_ps(f)) {}
// Copy from other vector.
HH_INLINE explicit V256(const V256 &other) : v_(other.v_) {}
template <typename U>
HH_INLINE explicit V256(const V256<U> &other) : v_(other) {}
HH_INLINE V256 &operator=(const V256 &other) {
v_ = other.v_;
return *this;
}
// Convert from/to intrinsics.
HH_INLINE V256(const Intrinsic &v) : v_(v) {}
HH_INLINE V256 &operator=(const Intrinsic &v) {
v_ = v;
return *this;
}
HH_INLINE operator Intrinsic() const { return v_; }
HH_INLINE V256 operator==(const V256 &other) const {
return V256(_mm256_cmp_ps(v_, other.v_, 0));
}
HH_INLINE V256 operator<(const V256 &other) const {
return V256(_mm256_cmp_ps(v_, other.v_, 1));
}
HH_INLINE V256 operator>(const V256 &other) const {
return V256(_mm256_cmp_ps(other.v_, v_, 1));
}
HH_INLINE V256 &operator*=(const V256 &other) {
v_ = _mm256_mul_ps(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator/=(const V256 &other) {
v_ = _mm256_div_ps(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator+=(const V256 &other) {
v_ = _mm256_add_ps(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator-=(const V256 &other) {
v_ = _mm256_sub_ps(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator&=(const V256 &other) {
v_ = _mm256_and_ps(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator|=(const V256 &other) {
v_ = _mm256_or_ps(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator^=(const V256 &other) {
v_ = _mm256_xor_ps(v_, other.v_);
return *this;
}
private:
Intrinsic v_;
};
template <> class V256<double> {
public:
using Intrinsic = __m256d;
using T = double;
static constexpr size_t N = 4;
// Leaves v_ uninitialized - typically used for output parameters.
HH_INLINE V256() {}
// Lane 0 (p_0) is the lowest.
HH_INLINE V256(T p_3, T p_2, T p_1, T p_0)
: v_(_mm256_set_pd(p_3, p_2, p_1, p_0)) {}
// Broadcasts to all lanes.
HH_INLINE explicit V256(T f) : v_(_mm256_set1_pd(f)) {}
// Copy from other vector.
HH_INLINE explicit V256(const V256 &other) : v_(other.v_) {}
template <typename U>
HH_INLINE explicit V256(const V256<U> &other) : v_(other) {}
HH_INLINE V256 &operator=(const V256 &other) {
v_ = other.v_;
return *this;
}
// Convert from/to intrinsics.
HH_INLINE V256(const Intrinsic &v) : v_(v) {}
HH_INLINE V256 &operator=(const Intrinsic &v) {
v_ = v;
return *this;
}
HH_INLINE operator Intrinsic() const { return v_; }
HH_INLINE V256 operator==(const V256 &other) const {
return V256(_mm256_cmp_pd(v_, other.v_, 0));
}
HH_INLINE V256 operator<(const V256 &other) const {
return V256(_mm256_cmp_pd(v_, other.v_, 1));
}
HH_INLINE V256 operator>(const V256 &other) const {
return V256(_mm256_cmp_pd(other.v_, v_, 1));
}
HH_INLINE V256 &operator*=(const V256 &other) {
v_ = _mm256_mul_pd(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator/=(const V256 &other) {
v_ = _mm256_div_pd(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator+=(const V256 &other) {
v_ = _mm256_add_pd(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator-=(const V256 &other) {
v_ = _mm256_sub_pd(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator&=(const V256 &other) {
v_ = _mm256_and_pd(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator|=(const V256 &other) {
v_ = _mm256_or_pd(v_, other.v_);
return *this;
}
HH_INLINE V256 &operator^=(const V256 &other) {
v_ = _mm256_xor_pd(v_, other.v_);
return *this;
}
private:
Intrinsic v_;
};
// Nonmember functions for any V256 via member functions.
template <typename T>
HH_INLINE V256<T> operator*(const V256<T> &left, const V256<T> &right) {
V256<T> t(left);
return t *= right;
}
template <typename T>
HH_INLINE V256<T> operator/(const V256<T> &left, const V256<T> &right) {
V256<T> t(left);
return t /= right;
}
template <typename T>
HH_INLINE V256<T> operator+(const V256<T> &left, const V256<T> &right) {
V256<T> t(left);
return t += right;
}
template <typename T>
HH_INLINE V256<T> operator-(const V256<T> &left, const V256<T> &right) {
V256<T> t(left);
return t -= right;
}
template <typename T>
HH_INLINE V256<T> operator&(const V256<T> &left, const V256<T> &right) {
V256<T> t(left);
return t &= right;
}
template <typename T>
HH_INLINE V256<T> operator|(const V256<T> &left, const V256<T> &right) {
V256<T> t(left);
return t |= right;
}
template <typename T>
HH_INLINE V256<T> operator^(const V256<T> &left, const V256<T> &right) {
V256<T> t(left);
return t ^= right;
}
template <typename T>
HH_INLINE V256<T> operator<<(const V256<T> &v, const int count) {
V256<T> t(v);
return t <<= count;
}
template <typename T>
HH_INLINE V256<T> operator>>(const V256<T> &v, const int count) {
V256<T> t(v);
return t >>= count;
}
// We do not provide operator<<(V, __m128i) because it has 4 cycle latency
// (to broadcast the shift count). It is faster to use sllv_epi64 etc. instead.
using V32x8U = V256<uint8_t>;
using V16x16U = V256<uint16_t>;
using V8x32U = V256<uint32_t>;
using V4x64U = V256<uint64_t>;
using V8x32F = V256<float>;
using V4x64F = V256<double>;
// Load/Store for any V256.
// We differentiate between targets' vector types via template specialization.
// Calling Load<V>(floats) is more natural than Load(V8x32F(), floats) and may
// generate better code in unoptimized builds. Only declare the primary
// templates to avoid needing mutual exclusion with vector128.
template <class V>
HH_INLINE V Load(const typename V::T *const HH_RESTRICT from);
template <class V>
HH_INLINE V LoadUnaligned(const typename V::T *const HH_RESTRICT from);
template <> HH_INLINE V32x8U Load(const V32x8U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V32x8U(_mm256_load_si256(p));
}
template <> HH_INLINE V16x16U Load(const V16x16U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V16x16U(_mm256_load_si256(p));
}
template <> HH_INLINE V8x32U Load(const V8x32U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V8x32U(_mm256_load_si256(p));
}
template <> HH_INLINE V4x64U Load(const V4x64U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V4x64U(_mm256_load_si256(p));
}
template <> HH_INLINE V8x32F Load(const V8x32F::T *const HH_RESTRICT from) {
return V8x32F(_mm256_load_ps(from));
}
template <> HH_INLINE V4x64F Load(const V4x64F::T *const HH_RESTRICT from) {
return V4x64F(_mm256_load_pd(from));
}
template <>
HH_INLINE V32x8U LoadUnaligned(const V32x8U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V32x8U(_mm256_loadu_si256(p));
}
template <>
HH_INLINE V16x16U LoadUnaligned(const V16x16U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V16x16U(_mm256_loadu_si256(p));
}
template <>
HH_INLINE V8x32U LoadUnaligned(const V8x32U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V8x32U(_mm256_loadu_si256(p));
}
template <>
HH_INLINE V4x64U LoadUnaligned(const V4x64U::T *const HH_RESTRICT from) {
const __m256i *const HH_RESTRICT p = reinterpret_cast<const __m256i *>(from);
return V4x64U(_mm256_loadu_si256(p));
}
template <>
HH_INLINE V8x32F LoadUnaligned(const V8x32F::T *const HH_RESTRICT from) {
return V8x32F(_mm256_loadu_ps(from));
}
template <>
HH_INLINE V4x64F LoadUnaligned(const V4x64F::T *const HH_RESTRICT from) {
return V4x64F(_mm256_loadu_pd(from));
}
// "to" must be vector-aligned.
template <typename T>
HH_INLINE void Store(const V256<T> &v, T *const HH_RESTRICT to) {
_mm256_store_si256(reinterpret_cast<__m256i * HH_RESTRICT>(to), v);
}
HH_INLINE void Store(const V256<float> &v, float *const HH_RESTRICT to) {
_mm256_store_ps(to, v);
}
HH_INLINE void Store(const V256<double> &v, double *const HH_RESTRICT to) {
_mm256_store_pd(to, v);
}
template <typename T>
HH_INLINE void StoreUnaligned(const V256<T> &v, T *const HH_RESTRICT to) {
_mm256_storeu_si256(reinterpret_cast<__m256i * HH_RESTRICT>(to), v);
}
HH_INLINE void StoreUnaligned(const V256<float> &v,
float *const HH_RESTRICT to) {
_mm256_storeu_ps(to, v);
}
HH_INLINE void StoreUnaligned(const V256<double> &v,
double *const HH_RESTRICT to) {
_mm256_storeu_pd(to, v);
}
// Writes directly to (aligned) memory, bypassing the cache. This is useful for
// data that will not be read again in the near future.
template <typename T>
HH_INLINE void Stream(const V256<T> &v, T *const HH_RESTRICT to) {
_mm256_stream_si256(reinterpret_cast<__m256i * HH_RESTRICT>(to), v);
}
HH_INLINE void Stream(const V256<float> &v, float *const HH_RESTRICT to) {
_mm256_stream_ps(to, v);
}
HH_INLINE void Stream(const V256<double> &v, double *const HH_RESTRICT to) {
_mm256_stream_pd(to, v);
}
// Miscellaneous functions.
template <typename T>
HH_INLINE V256<T> RotateLeft(const V256<T> &v, const int count) {
constexpr size_t num_bits = sizeof(T) * 8;
return (v << count) | (v >> (num_bits - count));
}
template <typename T>
HH_INLINE V256<T> AndNot(const V256<T> &neg_mask, const V256<T> &values) {
return V256<T>(_mm256_andnot_si256(neg_mask, values));
}
template <>
HH_INLINE V256<float> AndNot(const V256<float> &neg_mask,
const V256<float> &values) {
return V256<float>(_mm256_andnot_ps(neg_mask, values));
}
template <>
HH_INLINE V256<double> AndNot(const V256<double> &neg_mask,
const V256<double> &values) {
return V256<double>(_mm256_andnot_pd(neg_mask, values));
}
HH_INLINE V8x32F Select(const V8x32F &a, const V8x32F &b, const V8x32F &mask) {
return V8x32F(_mm256_blendv_ps(a, b, mask));
}
HH_INLINE V4x64F Select(const V4x64F &a, const V4x64F &b, const V4x64F &mask) {
return V4x64F(_mm256_blendv_pd(a, b, mask));
}
// Min/Max
HH_INLINE V32x8U Min(const V32x8U &v0, const V32x8U &v1) {
return V32x8U(_mm256_min_epu8(v0, v1));
}
HH_INLINE V32x8U Max(const V32x8U &v0, const V32x8U &v1) {
return V32x8U(_mm256_max_epu8(v0, v1));
}
HH_INLINE V16x16U Min(const V16x16U &v0, const V16x16U &v1) {
return V16x16U(_mm256_min_epu16(v0, v1));
}
HH_INLINE V16x16U Max(const V16x16U &v0, const V16x16U &v1) {
return V16x16U(_mm256_max_epu16(v0, v1));
}
HH_INLINE V8x32U Min(const V8x32U &v0, const V8x32U &v1) {
return V8x32U(_mm256_min_epu32(v0, v1));
}
HH_INLINE V8x32U Max(const V8x32U &v0, const V8x32U &v1) {
return V8x32U(_mm256_max_epu32(v0, v1));
}
HH_INLINE V8x32F Min(const V8x32F &v0, const V8x32F &v1) {
return V8x32F(_mm256_min_ps(v0, v1));
}
HH_INLINE V8x32F Max(const V8x32F &v0, const V8x32F &v1) {
return V8x32F(_mm256_max_ps(v0, v1));
}
HH_INLINE V4x64F Min(const V4x64F &v0, const V4x64F &v1) {
return V4x64F(_mm256_min_pd(v0, v1));
}
HH_INLINE V4x64F Max(const V4x64F &v0, const V4x64F &v1) {
return V4x64F(_mm256_max_pd(v0, v1));
}
} // namespace HH_TARGET_NAME
} // namespace highwayhash
#endif // HH_DISABLE_TARGET_SPECIFIC
#endif // HIGHWAYHASH_VECTOR256_H_
| 29.763729 | 80 | 0.680884 |
57b103bd4787fce6cd51e25bb1c646fd5227f77d | 2,681 | h | C | tracker_ptr.h | yuvalif/tracker_ptr | 38b644dbc4c4df8525059e1ccc22a1c67699a555 | [
"MIT"
] | null | null | null | tracker_ptr.h | yuvalif/tracker_ptr | 38b644dbc4c4df8525059e1ccc22a1c67699a555 | [
"MIT"
] | 3 | 2017-06-29T11:22:55.000Z | 2018-01-14T06:42:51.000Z | tracker_ptr.h | yuvalif/tracker_ptr | 38b644dbc4c4df8525059e1ccc22a1c67699a555 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
// this class is used to track a pointer that it managed elsewhere
// the tracker just wraps the pointer
// and make sure that it could be set to null if deleted by its real owner
template<class T>
class tracker_ptr
{
private:
// the pointer, owned elsewhere
T* m_ptr;
public:
// ctor
explicit tracker_ptr(T* ptr) : m_ptr(ptr)
{
if (m_ptr)
{
m_ptr->register_tracker(this);
}
}
// std::unique_ptr ctor
explicit tracker_ptr(const std::unique_ptr<T>& ptr) : m_ptr(ptr.get())
{
if (m_ptr)
{
m_ptr->register_tracker(this);
}
}
// non copyable
tracker_ptr(const tracker_ptr<T>& other) = delete;
tracker_ptr<T>& operator=(const tracker_ptr<T>& other) = delete;
// reset to another pointer or to nullptr
void reset(T* ptr)
{
if (m_ptr)
{
m_ptr->unregister_tracker(this);
}
m_ptr = ptr;
if (m_ptr)
{
m_ptr->register_tracker(this);
}
}
T* operator->() const
{
return m_ptr;
}
T& operator*() const
{
return *m_ptr;
}
T* get() const
{
return m_ptr;
}
// check whether pointer is null
explicit operator bool() const
{
return m_ptr != nullptr;
}
// dtor
~tracker_ptr()
{
if (m_ptr)
{
m_ptr->unregister_tracker(this);
}
}
};
// a class that want its pointers to be trackedby the tracker_ptr
// may inherit from the trackable_ptr_concept class.
// but do not have to: any class that implements register_tracker() and unregister_tracker()
// and make sure to call reset() on the tracker before actual deletion would work
template<class T>
class trackable_ptr_concept
{
private:
// the tracker that tracks this pointer
tracker_ptr<T>* m_tracker;
public:
// ctor
trackable_ptr_concept() : m_tracker(nullptr) {}
// register a tracker that would be notified upon deletion
void register_tracker(tracker_ptr<T>* tracker)
{
// no check if th tracker was already set
// we implicitly unregister
m_tracker = tracker;
}
// unregister a tracker
void unregister_tracker(const tracker_ptr<T>* tracker)
{
if (tracker == m_tracker)
{
m_tracker = nullptr;
}
// else - this may happen if a tracker was
// registered without unregistering first
}
// dtor
~trackable_ptr_concept()
{
if (m_tracker)
{
m_tracker->reset(nullptr);
}
}
};
| 21.277778 | 92 | 0.580753 |
5108db7037b21a4aa1330c67962488e3ec3d86e2 | 662 | c | C | C/Array/AcessArray.c | piovezan/SOpt | a5ec90796b7bdf98f0675457fc4bb99c8695bc40 | [
"MIT"
] | 148 | 2017-08-03T01:49:27.000Z | 2022-03-26T10:39:30.000Z | C/Array/AcessArray.c | piovezan/SOpt | a5ec90796b7bdf98f0675457fc4bb99c8695bc40 | [
"MIT"
] | 3 | 2017-11-23T19:52:05.000Z | 2020-04-01T00:44:40.000Z | C/Array/AcessArray.c | piovezan/SOpt | a5ec90796b7bdf98f0675457fc4bb99c8695bc40 | [
"MIT"
] | 59 | 2017-08-03T01:49:19.000Z | 2022-03-31T23:24:38.000Z | #include <stdio.h>
#define TAM 5
int main(void) {
struct {
int cod;
char nome_da_obra[41];
char nome_do_autor[41];
char nome_da_editora[41];
} livro[TAM];
for (int i = 0; i < TAM; i++) {
printf("\n---------- Cadastro dos Livros -----------\n");
livro[i].cod = i;
printf("Insira o nome da Obra: ");
fgets(livro[i].nome_da_obra, 40, stdin);
printf("Insira o nome do autor: ");
fgets(livro[i].nome_do_autor, 40, stdin);
printf("Insira o nome da Editora: ");
fgets(livro[i].nome_da_editora, 40, stdin);
}
}
//https://pt.stackoverflow.com/q/394438/101
| 26.48 | 65 | 0.543807 |
cb3f8e5cb9d0f58b2d08692176b770318cc1fac4 | 2,934 | h | C | examples/modelview/playlists/metadata.h | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | examples/modelview/playlists/metadata.h | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | examples/modelview/playlists/metadata.h | PatrickTrentin88/intro_c-_qt | 1d73ef364711fac7b46cd3752258c0273c689835 | [
"MIT"
] | null | null | null | #ifndef METADATA_H
#define METADATA_H
#include <QTime>
#include <QTextStream>
#include <QString>
#include "starrating.h"
class MetaData : public QObject {
Q_OBJECT
Q_PROPERTY( QString TrackTitle
READ trackTitle WRITE setTrackTitle );
Q_PROPERTY( QString Artist READ
artist WRITE setArtist );
Q_PROPERTY( QTime TrackTime
READ trackTime WRITE setTrackTime);
Q_PROPERTY( QString AlbumTitle READ
albumTitle WRITE setAlbumTitle );
Q_PROPERTY(int TrackNumber
READ trackNumber WRITE setTrackNumber );
Q_PROPERTY( QString Genre READ
genre WRITE setGenre);
Q_PROPERTY( StarRating Rating READ rating WRITE setRating );
Q_PROPERTY( QString Comment READ
comment WRITE setComment);
Q_PROPERTY( QString FileName READ
fileName WRITE setFileName );
public:
MetaData(QObject* parent=0) : QObject(parent) {}
virtual ~MetaData() {};
public:
// Getters
virtual QString fileName() const {return m_fileName;}
virtual QString url() const {
return QString("file://%1").arg(fileName());
}
virtual StarRating rating() const {return m_rating;}
virtual QString genre() const {return m_genre; }
virtual QString artist() const {return m_artist; }
virtual QString albumTitle() const {return m_albumTitle;}
virtual QString trackTitle() const {return m_trackTitle;}
virtual int trackNumber() const {return m_trackNumber;}
virtual QTime trackTime() const {return m_trackTime;}
virtual QString trackTimeString() const {
QTime t=m_trackTime;
if (t.hour() > 0) {
return t.toString("hh:mm:ss");
}
else {
return t.toString("m:ss");
}
}
virtual QString comment() const {return m_comment;}
public slots:
// Setters
virtual void setFileName(const QString& fileName) {
m_fileName = fileName;
}
virtual void setRating(StarRating rating) {
m_rating = rating;
}
virtual void setGenre(const QString& genre) {
m_genre = genre;
}
virtual void setArtist(const QString& artist) {
m_artist = artist;
}
virtual void setTrackNumber(int tn) {
m_trackNumber = tn;
}
virtual void setTrackTitle(const QString& title) {
m_trackTitle = title;
}
virtual void setTrackTime(const QTime& time) {
m_trackTime = time;
}
virtual void setAlbumTitle(const QString& albumTitle) {
m_albumTitle = albumTitle;
}
virtual void setComment(const QString& comment) {
m_comment = comment;
}
protected:
QString m_fileName;
QString m_trackTitle;
QString m_comment;
QString m_genre;
QString m_artist;
QString m_albumTitle;
QTime m_trackTime;
StarRating m_rating;
int m_trackNumber;
};
#endif // #ifndef METADATA_H
| 28.764706 | 64 | 0.645876 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.