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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3656ad1f1d3e9d6263375d3d8fe88f0fdd8e0652 | 5,760 | c | C | C/read_bincl.c | servesh/alcl | 221578ccb6731b14b8e4d11c94dc8f2dbbb7f9f1 | [
"Unlicense"
] | null | null | null | C/read_bincl.c | servesh/alcl | 221578ccb6731b14b8e4d11c94dc8f2dbbb7f9f1 | [
"Unlicense"
] | null | null | null | C/read_bincl.c | servesh/alcl | 221578ccb6731b14b8e4d11c94dc8f2dbbb7f9f1 | [
"Unlicense"
] | null | null | null | // Includes
#include <stdio.h>
#include <CL/cl.h>
#include "./cl_utils.h"
int main(int argc, char* argv[]) {
cl_int err;
if (argc < 5)
exit_msg("Not enought arguments.");
// _ _ _
// |_) | _. _|_ _|_ _ ._ ._ _ () | \ _ o _ _
// | | (_| |_ | (_) | | | | (_X |_/ (/_ \/ | (_ (/_
//
printf(">>> Initializing OpenCL Platform and Device...\n");
cl_uint platform_idx = (cl_uint) atoi(argv[1]);
cl_uint device_idx = (cl_uint) atoi(argv[2]);
char name[128];
/* - - -
Plateform
- - - - */
//A platform is a specific OpenCL implementation, for instance AMD, NVIDIA or Intel.
// Intel may have a different OpenCL implementation for the CPU and GPU.
// Discover the number of platforms:
cl_uint platform_count;
err = clGetPlatformIDs(0, NULL, &platform_count);
check_error(err, "clGetPlatformIds");
// Now ask OpenCL for the platform IDs:
cl_platform_id* platforms = (cl_platform_id*)malloc(sizeof(cl_platform_id) * platform_count);
err = clGetPlatformIDs(platform_count, platforms, NULL);
check_error(err, "clGetPlatformIds");
cl_platform_id platform = platforms[platform_idx];
err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, 128, name, NULL);
check_error(err, "clGetPlatformInfo");
printf("Platform #%d: %s\n", platform_idx, name);
/* - - - -
Device
- - - - */
// Device gather data
cl_uint device_count;
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL , 0, NULL, &device_count);
check_error(err, "clGetdeviceIds");
cl_device_id* devices = (cl_device_id*)malloc(sizeof(cl_device_id) * device_count);
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL , device_count, devices, NULL);
check_error(err, "clGetdeviceIds");
cl_device_id device = devices[device_idx];
err = clGetDeviceInfo(device, CL_DEVICE_NAME, 128, name, NULL);
check_error(err, "clGetPlatformInfo");
printf("-- Device #%d: %s\n", device_idx, name);
// _ _
// / _ ._ _|_ _ _|_ () / \ _ _
// \_ (_) | | |_ (/_ >< |_ (_X \_X |_| (/_ |_| (/_
//
/* - - - -
Context
- - - - */
// A context is a platform with the selected device for that platform.
cl_context context = clCreateContext(0, 1, &device, NULL, NULL, &err);
check_error(err,"clCreateContext");
/* - - - -
Command queue
- - - - */
// The OpenCL functions that are submitted to a command-queue are enqueued in the order the calls are made but can be configured to execute in-order or out-of-order.
cl_command_queue queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &err);
check_error(err,"clCreateCommandQueue");
// |/ _ ._ ._ _ |
// |\ (/_ | | | (/_ |
//
printf(">>> Kernel configuration...\n");
// Readed from file
unsigned char* program_file; size_t program_size;
err = read_from_binary(&program_file, &program_size, "hwv.bin");
// Create the program from binary
cl_program program = clCreateProgramWithBinary(context, 1, &device, &program_size,
(const unsigned char **)&program_file,
NULL, &err);
check_error(err,"clCreateProgramWithBinary");
//Build / Compile the program executable
err = clBuildProgram(program, 1, &device, "-cl-unsafe-math-optimizations", NULL, NULL);
if (err != CL_SUCCESS)
{
printf("Error: Failed to build program executable!\n");
size_t logSize;
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
// there's no information in the reference whether the string is 0 terminated or not.
char* messages = (char*)malloc((1+logSize)*sizeof(char));
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, logSize, messages, NULL);
messages[logSize] = '\0';
printf("%s", messages);
free(messages);
return EXIT_FAILURE;
}
/* - - - -
Create
- - - - */
cl_kernel kernel = clCreateKernel(program, "hello_world", &err);
check_error(err,"clCreateKernel");
/* - - - -
ND range
- - - - */
printf(">>> NDrange configuration...\n");
#define WORK_DIM 1
// Describe the number of global work-items in work_dim dimensions that will execute the kernel function
size_t global0 = (size_t) atoi(argv[3]);
const size_t global[WORK_DIM] = { global0 };
// Describe the number of work-items that make up a work-group (also referred to as the size of the work-group).
// local_work_size can also be a NULL value in which case the OpenCL implementation will determine how to be break the global work-items into appropriate work-group instances.
size_t local0 = (size_t) atoi(argv[4]);
const size_t local[WORK_DIM] = { local0 };
printf("Global work size: %zu \n", global[0]);
printf("Local work size: %zu \n", local[0]);
/* - - - -
Execute
- - - - */
printf(">>> Kernel Execution...\n");
err = clEnqueueNDRangeKernel(queue, kernel, WORK_DIM, NULL, global, local, 0, NULL, NULL);
check_error(err,"clEnqueueNDRangeKernel");
// _
// / | _ _. ._ o ._ _
// \_ | (/_ (_| | | | | | (_|
// _|
clReleaseCommandQueue(queue);
clReleaseContext(context);
clReleaseProgram(program);
clReleaseKernel(kernel);
// Exit
return 0;
}
// =================================================================================================
| 35.121951 | 179 | 0.584201 |
cfce07d5a13376fcb663807a20ecc0031781b747 | 1,054 | c | C | corewar/src/create_champion/create_list_champion.c | FlorianMarcon/CPE_corewar | 26b2cfb24604d89ee2ca4ede4aa1411a94b6e646 | [
"MIT"
] | null | null | null | corewar/src/create_champion/create_list_champion.c | FlorianMarcon/CPE_corewar | 26b2cfb24604d89ee2ca4ede4aa1411a94b6e646 | [
"MIT"
] | null | null | null | corewar/src/create_champion/create_list_champion.c | FlorianMarcon/CPE_corewar | 26b2cfb24604d89ee2ca4ede4aa1411a94b6e646 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2017
** create_list_champion
** File description:
** create_list_champion
*/
#include "header_corewar.h"
#include "my.h"
linked_list_t *add_in_list_champion(linked_list_t *list, char *path,
int load_address, int *nb)
{
int number = *nb;
champion_t *champ;
champ = create_champion(number++, load_address, path);
if (champ != NULL && list == NULL)
list = create_list(champ);
else if (champ != NULL)
create_node(list, champ);
else
number--;
*nb = number;
return (list);
}
linked_list_t *create_list_champion(char **path)
{
linked_list_t *list = NULL;
int nb = 1;
int load_address = -1;
if (path == NULL)
return (NULL);
for (unsigned int i = 0; path[i] != NULL; i++) {
if (my_strcmp("-n", path[i]) == 0 && my_str_isnum(path[++i]))
nb = my_getnbr(path[i]);
else if (my_strcmp("-a", path[i]) == 0 &&
my_str_isnum(path[++i]))
load_address = my_getnbr(path[i]);
else {
list = add_in_list_champion(list, path[i],
load_address, &nb);
load_address = -1;
}
}
return (list);
}
| 21.510204 | 68 | 0.63852 |
322397a66cbbd9c3d9a57f45d7f07603bbbfef92 | 1,490 | c | C | core/bus_center/lnn/net_builder/src/lnn_node_weight.c | czy0538/ohos_dsoftbus_read | f38516f077f147fa835b0ad22c2733d385d91517 | [
"Apache-2.0"
] | null | null | null | core/bus_center/lnn/net_builder/src/lnn_node_weight.c | czy0538/ohos_dsoftbus_read | f38516f077f147fa835b0ad22c2733d385d91517 | [
"Apache-2.0"
] | null | null | null | core/bus_center/lnn/net_builder/src/lnn_node_weight.c | czy0538/ohos_dsoftbus_read | f38516f077f147fa835b0ad22c2733d385d91517 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "lnn_node_weight.h"
#include <string.h>
#include "softbus_adapter_crypto.h"
#include "softbus_errcode.h"
#include "softbus_log.h"
#define MAX_WEIGHT_VALUE 1000
int32_t LnnGetLocalWeight(void)
{
static int32_t weight;
static bool isGenWeight = false;
uint8_t randVal = 0;
if (isGenWeight) {
return weight;
}
if (SoftBusGenerateRandomArray(&randVal, sizeof(randVal)) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "generate random weight fail");
return randVal;
}
weight = (randVal * MAX_WEIGHT_VALUE) / UINT8_MAX;
isGenWeight = true;
return weight;
}
int32_t LnnCompareNodeWeight(int32_t weight1, const char *masterUdid1,
int32_t weight2, const char *masterUdid2)
{
if (weight1 != weight2) {
return weight1 - weight2;
}
return strcmp(masterUdid1, masterUdid2);
} | 29.215686 | 86 | 0.712752 |
2c976e000307eed09f7889766552c43b32574215 | 312 | h | C | src/app_constants.h | pghalliday/bitpin | af68c8202ae5c1c4baabf3fa9bffcbfc3c93c1a3 | [
"MIT"
] | null | null | null | src/app_constants.h | pghalliday/bitpin | af68c8202ae5c1c4baabf3fa9bffcbfc3c93c1a3 | [
"MIT"
] | null | null | null | src/app_constants.h | pghalliday/bitpin | af68c8202ae5c1c4baabf3fa9bffcbfc3c93c1a3 | [
"MIT"
] | 1 | 2021-09-23T16:29:17.000Z | 2021-09-23T16:29:17.000Z | #ifndef APP_CONSTANTS_H__
#define APP_CONSTANTS_H__
#include "bip39_constants.h"
#define APP_MNEMONIC_PREFIX "mnemonic:"
#define APP_MNEMONIC_PREFIX_LENGTH (sizeof(APP_MNEMONIC_PREFIX) - 1)
#define APP_PREFIXED_MNEMONIC_MAX_SIZE (MNEMONIC_MAX_SIZE + APP_MNEMONIC_PREFIX_LENGTH)
char * app_init(void);
#endif
| 24 | 87 | 0.833333 |
1921e137e651a5867cd025a01b86e27f6fc964a3 | 379 | h | C | loadMNIST.h | phy710/loadMNIST-Cpp | c8c6a1154d834e109a3787729ea5d6d401a1acb3 | [
"Apache-2.0"
] | null | null | null | loadMNIST.h | phy710/loadMNIST-Cpp | c8c6a1154d834e109a3787729ea5d6d401a1acb3 | [
"Apache-2.0"
] | null | null | null | loadMNIST.h | phy710/loadMNIST-Cpp | c8c6a1154d834e109a3787729ea5d6d401a1acb3 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdio.h>
using namespace std;
bool loadMNISTImages(string fileName, vector<vector<unsigned char>> &images);
bool loadMNISTLabels(string fileName, vector<char> &labels);
void showMNIST(vector<vector<unsigned char>> &images, vector<char> &labels, int number);
int reverseInt(int n);
| 31.583333 | 88 | 0.770449 |
d0748f659ef3841b6a368f5665067f00106f51c9 | 13,175 | h | C | models/lnd/clm/src/iac/giac/gcam/cvs/objects/technologies/include/production_technology.h | E3SM-Project/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 9 | 2018-05-15T02:10:40.000Z | 2020-01-10T18:27:31.000Z | models/lnd/clm/src/iac/giac/gcam/cvs/objects/technologies/include/production_technology.h | zhangyue292/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 3 | 2018-10-12T18:41:56.000Z | 2019-11-12T15:18:49.000Z | models/lnd/clm/src/iac/giac/gcam/cvs/objects/technologies/include/production_technology.h | zhangyue292/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 3 | 2018-05-15T02:10:33.000Z | 2021-04-06T17:45:49.000Z | #ifndef _PRODUCTION_TECHNOLOGY_H_
#define _PRODUCTION_TECHNOLOGY_H_
#if defined(_MSC_VER)
#pragma once
#endif
/*
* LEGAL NOTICE
* This computer software was prepared by Battelle Memorial Institute,
* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830
* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE
* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY
* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this
* sentence must appear on any copies of this computer software.
*
* EXPORT CONTROL
* User agrees that the Software will not be shipped, transferred or
* exported into any country or used in any manner prohibited by the
* United States Export Administration Act or any other applicable
* export laws, restrictions or regulations (collectively the "Export Laws").
* Export of the Software may require some form of license or other
* authority from the U.S. Government, and failure to obtain such
* export control license may result in criminal liability under
* U.S. laws. In addition, if the Software is identified as export controlled
* items under the Export Laws, User represents and warrants that User
* is not a citizen, or otherwise located within, an embargoed nation
* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)
* and that User is not otherwise prohibited
* under the Export Laws from receiving the Software.
*
* Copyright 2011 Battelle Memorial Institute. All Rights Reserved.
* Distributed as open-source under the terms of the Educational Community
* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php
*
* For further details, see: http://www.globalchange.umd.edu/models/gcam/
*
*/
/*!
* \file production_technology.h
* \ingroup Objects
* \brief ProductionTechnology class header file.
* \author Pralit Patel
* \author Sonny Kim
*/
#include <string>
#include <xercesc/dom/DOMNode.hpp>
#include <memory>
#include "technologies/include/base_technology.h"
#include "functions/include/ifunction.h" // could remove if mTechChange was a pointer, but need a copyctor.
class Tabs;
class Demographic;
class MoreSectorInfo;
class IVisitor;
class IExpectedProfitRateCalculator;
class IShutdownDecider;
/*!
* \ingroup Objects
* \brief A technology which accepts investment and produces output for SGM
* production sectors.
* \details Represents a single vintage of an SGM production technology. This technology
* is responsible calculating its own coefficients, passing its self forward,
* converting to an old vintage, calculating a technology cost, supply output
* and input demands based on investment, calculating emissions, and collecting
* taxes and various other accounting.
*
* <b>XML specification for ProductionTechnology</b>
* - XML name: \c productionTechnology
* - Contained by: Subsector
* - Parsing inherited from class: BaseTechnology
* - Elements:
* - \c lifeTime TradeInput::lifeTime
* The lifetime in years of this technology.
* - \c basePhysicalOutput TradeInput::mBasePhysicalOutput
* Base year physical output of this technology. This value is utilized
* in conjunction with the total currency demand from the inputs to determine
* the base year technology cost to use when initializing coefficients. Note
* that if this value is not provided we assume the cost is equal to the sector
* price recieved.
* - \c fixed-investment TradeInput::mFixedInvestment
* Fixed investment our output level of this technology. Note that reading
* this value implies this technology is a fixed technology and the investor will
* not attempt to invest in this technology. The technology cost will however
* factor into the levelized cost of the sector. Also note that even though
* a fixed amount is read when the technology is an old vintage it is still
* susceptible to the shutdown coef.
* - \c technicalChangeHicks TradeInput::mTechChange.mHicksTechChange
* Hicks neutral tech change applied in the initial investment year of this
* technology.
* - \c technicalChangeEnergy TradeInput::mTechChange.mEnergyTechChange
* Tech change for energy inputs applied in the initial investment year of this
* technology.
* - \c technicalChangeMaterial TradeInput::mTechChange.mMaterialTechChange
* Tech change for material inputs applied in the initial investment year of this
* technology.
*
* \author Pralit Patel, Sonny Kim
*/
class ProductionTechnology : public BaseTechnology
{
friend class SocialAccountingMatrix;
friend class DemandComponentsTable;
friend class SectorReport;
friend class SGMGenTable;
friend class SectorResults;
friend class GovtResults;
friend class XMLDBOutputter;
// either these are friends or move isAvailable and isRetired to public
friend class EnergyBalanceTable;
friend class InputOutputTable;
public:
ProductionTechnology();
ProductionTechnology* clone() const;
~ProductionTechnology();
virtual void copyParam( const BaseTechnology* baseTech,
const int aPeriod );
void copyParamsInto( ProductionTechnology& prodTechIn,
const int aPeriod ) const;
virtual void completeInit( const std::string& aRegionName,
const std::string& aSectorName,
const std::string& aSubsectorName );
virtual void initCalc( const MoreSectorInfo* aMoreSectorInfo,
const std::string& aRegionName,
const std::string& aSectorName,
NationalAccount& aNationalAccount,
const Demographic* aDemographics,
const double aCapitalStock,
const int aPeriod );
static const std::string& getXMLNameStatic();
bool isNewInvestment( const int period ) const;
virtual void operate( NationalAccount& aNationalAccount, const Demographic* aDemographic,
const MoreSectorInfo* aMoreSectorInfo, const std::string& aRegionName, const std::string& aSectorName,
const bool aIsNewVintageMode, const int aPeriod );
virtual double setInvestment( const std::string& aRegionName, const double aAnnualInvestment,
const double aTotalInvestment, const int aPeriod );
virtual double getCapitalStock() const;
virtual double getAnnualInvestment( const int aPeriod ) const;
double getExpectedProfitRate( const NationalAccount& aNationalAccount,
const std::string& aRegionName,
const std::string& aSectorName,
const IExpectedProfitRateCalculator* aExpProfitRateCalc,
const double aInvestmentLogitExp,
const bool aIsShareCalc,
const bool aIsDistributing,
const int aPeriod ) const;
virtual double getCapitalOutputRatio( const IDistributor* aDistributor,
const IExpectedProfitRateCalculator* aExpProfitRateCalc,
const NationalAccount& aNationalAccount,
const std::string& aRegionName,
const std::string& aSectorName,
const int aPeriod ) const;
double getFixedInvestment( const int aPeriod ) const;
double distributeInvestment( const IDistributor* aDistributor, NationalAccount& aNationalAccount,
const IExpectedProfitRateCalculator* aExpProfitRateCalc,
const std::string& aRegionName, const std::string& aSectorName,
const double aNewInvestment, const int aPeriod );
void updateMarketplace( const std::string& sectorName, const std::string& regionName,
const int period );
void csvSGMOutputFile( std::ostream& aFile, const int period ) const;
void accept( IVisitor* aVisitor, const int aPeriod ) const;
void setTypeHelper( TechnologyType* aTechType );
void postCalc( const std::string& aRegionName, const std::string& aSectorName, const int aPeriod );
protected:
virtual bool isCoefBased() const { return true; }
virtual void calcEmissions( const std::string& aGoodName, const std::string& aRegionName, const int aPeriod );
virtual const std::string& getXMLName() const;
virtual bool XMLDerivedClassParse( const std::string& nodeName, const xercesc::DOMNode* curr );
virtual void toInputXMLDerived( std::ostream& out, Tabs* tabs ) const;
virtual void toDebugXMLDerived( const int period, std::ostream& out, Tabs* tabs ) const;
private:
//! Costs stored by period for reporting.
std::vector<double> mCostsReporting;
//! Total profits stored by period.
std::vector<double> mProfits;
//! Structure containing types of technological change.
TechChange mTechChange;
//! Technology type containing this vintage. This may change.
TechnologyType* mParentTechType;
//! Expected profit rate stored for reporting.
double mExpectedProfitRateReporting;
/*! \brief An enum which describes the types of cached function return
* values for a specific year.
*/
enum CacheValues {
//! The return value of the isAvailable function.
AVAILABLE,
//! The return value of the isRetired function.
RETIRED,
//! The return value of the isNewInvestment function.
NEW_INVESTMENT,
//! A market for the last enum value, insert new enum values prior to this.
END
};
//! A vector of cached results indexed by year for frequently called checks.
std::vector<bool> mCachedValues;
double mCapitalStock; //!< capital stock
double indBusTax; //!< indirect business tax
double mBasePhysicalOutput; //!< base year physical output for calculating conversion factor
double mAnnualInvestment; //!< Annual investment
double mFixedInvestment; //!< Quantity of fixed investment in the initial year for the technology.
// All times must be in years because some periods are < 0.
//! The period for which all cached values stored in mCachedValues are valid for.
int mValidCachePeriod;
int lifeTime; //!< nameplate lifetime of the technology
int delayedInvestTime; //!< number of years between initial investment and first operation
int maxLifeTime; //!< maximum allowable lifetime
int retrofitLifeTime; //!< lifetime of the technology renovation
int periodIniInvest; //!< number of periods until initial investment
int periodInvestUnallowed; //!< period in which investment is no longer allowed
void calcTaxes( NationalAccount& aNationalAccount, const MoreSectorInfo* aMoreSectorInfo,
const std::string& aRegionName, const std::string aSectorName, const int aPeriod );
bool calcIsNewInvestment( const int aPeriod ) const;
inline bool isAvailable( const int aPeriod ) const;
bool calcIsAvailable( const int aPeriod ) const;
inline bool isRetired( const int aPeriod ) const;
bool calcIsRetired( const int aPeriod ) const;
double calcShutdownCoef( const std::string& aRegionName,
const std::string& aSectorName,
const int aPeriod ) const;
};
/*! \brief Return whether a technology is available to go online.
* \param aPeriod The current period.
* \return Whether the technology has gone online.
* \author Josh Lurz
*/
bool ProductionTechnology::isAvailable( const int aPeriod ) const {
// Check if we have a valid cached result for the period.
if( aPeriod == mValidCachePeriod ){
return mCachedValues[ AVAILABLE ];
}
// There is no cached result available for this period, so calculate it
// dynamically.
return calcIsAvailable( aPeriod );
}
/*! \brief Return whether a technology has been retired yet.
* \param aPeriod The current period.
* \return Whether the technology has been retired.
* \author Josh Lurz
*/
bool ProductionTechnology::isRetired( const int aPeriod ) const {
// Check if we have a valid cached result for the period.
if( aPeriod == mValidCachePeriod ){
return mCachedValues[ RETIRED ];
}
// There is no cached result available for this period, so calculate it
// dynamically.
return calcIsRetired( aPeriod );
}
#endif // _PRODUCTION_TECHNOLOGY_H_
| 46.390845 | 114 | 0.670285 |
ecf96ef82429e4bfe0aaa85a70ed33067a4eb3d3 | 2,286 | h | C | include/swift/Threading/Thread.h | xjc90s/swift | cafe5ccbd1b7aa9cc9c837c5be2cdf3d5acd8a49 | [
"Apache-2.0"
] | 1 | 2022-03-15T08:31:21.000Z | 2022-03-15T08:31:21.000Z | include/swift/Threading/Thread.h | xjc90s/swift | cafe5ccbd1b7aa9cc9c837c5be2cdf3d5acd8a49 | [
"Apache-2.0"
] | null | null | null | include/swift/Threading/Thread.h | xjc90s/swift | cafe5ccbd1b7aa9cc9c837c5be2cdf3d5acd8a49 | [
"Apache-2.0"
] | null | null | null | //===--- Thread.h - Thread abstraction ------------------------ -*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Provides an abstract Thread class that identifies a system thread,
// and can fetch the current and main threads as well as being comparable
// with other Thread instances.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_THREADING_THREAD_H
#define SWIFT_THREADING_THREAD_H
#include "llvm/ADT/Optional.h"
#include "Impl.h"
namespace swift {
/// Identifies a thread
class Thread {
public:
using Id = threading_impl::thread_id;
using StackBounds = threading_impl::stack_bounds;
private:
Id id_;
public:
Thread() {}
explicit Thread(Id platformId) : id_(platformId) {}
Thread(const Thread &other) : id_(other.id_) {}
Thread(Thread &&other) : id_(std::move(other.id_)) {}
Thread &operator=(const Thread &other) {
id_ = other.id_;
return *this;
}
Thread &operator=(Thread &&other) {
id_ = other.id_;
return *this;
}
/// Returns the platform specific thread ID
Id platformThreadId() const { return id_; }
/// Returns the currently executing thread
static Thread current() {
return Thread(threading_impl::thread_get_current());
}
/// Returns true iff executed on the main thread
static bool onMainThread() { return threading_impl::thread_is_main(); }
/// Returns true if the two Thread values are equal
bool operator==(const Thread &other) const {
return threading_impl::threads_same(id_, other.id_);
}
bool operator!=(const Thread &other) const {
return !threading_impl::threads_same(id_, other.id_);
}
// Retrieve the bounds of the current thread's stack
static llvm::Optional<StackBounds> stackBounds() {
return threading_impl::thread_get_current_stack_bounds();
}
};
} // namespace swift
#endif // SWIFT_THREADING_THREAD_H
| 28.222222 | 80 | 0.651794 |
10c88c7c5f4dc689a6320cc20a079c618fab5791 | 484 | c | C | C/code case/code case 175.c | amazing-2020/pdf | 8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d | [
"Apache-2.0"
] | 3 | 2021-01-01T13:08:24.000Z | 2021-02-03T09:27:56.000Z | C/code case/code case 175.c | amazing-2020/pdf | 8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d | [
"Apache-2.0"
] | null | null | null | C/code case/code case 175.c | amazing-2020/pdf | 8cd3f5f510a1c1ed89b51b1354f4f8c000c5b24d | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <string.h>
int main(void) {
int a=12021;
char s[10] = {'\0'}, s1[10] = {'\0'};
sprintf(s, "%d", a);
int n=strlen(s);
int j=0;
for (int i=n-1; i>=0; i--) {
s1[j++] = s[i];
printf("%2d", i);
}
printf("%s %s \n", s, s1);
if (!strcmp(s, s1)) {//如果字符串的结果相同则返回0,!0 = 1
printf("%d is oalinfrome number \n", a);
} else {
printf("%d is not oalinfrome number. \n", a);
}
return 0;
} | 21.043478 | 53 | 0.452479 |
10e78d41329a211839424b3a3ea2ed8012262b6a | 6,015 | c | C | sdsoc/hash/SDDebug/_sds/swstubs/portinfo.c | chris-wood/yield | 61f2bf399e98bbb0bc9107cdc58ae1e18d02231c | [
"MIT"
] | null | null | null | sdsoc/hash/SDDebug/_sds/swstubs/portinfo.c | chris-wood/yield | 61f2bf399e98bbb0bc9107cdc58ae1e18d02231c | [
"MIT"
] | null | null | null | sdsoc/hash/SDDebug/_sds/swstubs/portinfo.c | chris-wood/yield | 61f2bf399e98bbb0bc9107cdc58ae1e18d02231c | [
"MIT"
] | null | null | null | /* File: C:/Users/sskalick/Xilinx/hash/hash/SDDebug/_sds/p0/.cf_work/portinfo.c */
#include "cf_lib.h"
#include "cf_request.h"
#include "devreg.h"
#include "portinfo.h"
#include "stdio.h" // for printf
#include "xlnk_core_cf.h"
#include "accel_info.h"
#include "axi_lite_dm.h"
#include "zero_copy_dm.h"
extern accel_info_t _sds__p0_get_0;
extern accel_info_t _sds__p0_set_0;
axi_lite_info_t _p0_swinst_get_0_cmd_get_info = {
.accel_info = &_sds__p0_get_0,
.reg_name = "0x28"
};
zero_copy_info_t _p0_swinst_get_0_data_info = {
.accel_info = &_sds__p0_get_0,
.reg_name = "0x80",
.needs_cache_flush_invalidate = 0,
.dir_chan = XLNK_BI_DIRECTIONAL
};
axi_lite_info_t _p0_swinst_get_0_key_info = {
.accel_info = &_sds__p0_get_0,
.reg_name = "0x84"
};
axi_lite_info_t _p0_swinst_get_0_val_r_info = {
.accel_info = &_sds__p0_get_0,
.reg_name = "0xC4"
};
axi_lite_info_t _p0_swinst_get_0_ap_return_info = {
.accel_info = &_sds__p0_get_0,
.reg_name = "0xC0"
};
axi_lite_info_t _p0_swinst_set_0_cmd_set_info = {
.accel_info = &_sds__p0_set_0,
.reg_name = "0x28"
};
zero_copy_info_t _p0_swinst_set_0_data_info = {
.accel_info = &_sds__p0_set_0,
.reg_name = "0x80",
.needs_cache_flush_invalidate = 0,
.dir_chan = XLNK_BI_DIRECTIONAL
};
axi_lite_info_t _p0_swinst_set_0_key_info = {
.accel_info = &_sds__p0_set_0,
.reg_name = "0x84"
};
axi_lite_info_t _p0_swinst_set_0_val_r_info = {
.accel_info = &_sds__p0_set_0,
.reg_name = "0x88"
};
axi_lite_info_t _p0_swinst_set_0_ap_return_info = {
.accel_info = &_sds__p0_set_0,
.reg_name = "0xC0"
};
struct _p0_swblk_get _p0_swinst_get_0 = {
.cmd_get = { .base = {
.channel_info = &_p0_swinst_get_0_cmd_get_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.send_i = &axi_lite_send },
.data = { .base = {
.channel_info = &_p0_swinst_get_0_data_info,
.open_i = &zero_copy_open,
.close_i = &zero_copy_close },
.send_ref_i = &zero_copy_send_ref_i },
.key = { .base = {
.channel_info = &_p0_swinst_get_0_key_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.send_i = &axi_lite_send },
.val_r = { .base = {
.channel_info = &_p0_swinst_get_0_val_r_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.receive_i = &axi_lite_recv },
.ap_return = { .base = {
.channel_info = &_p0_swinst_get_0_ap_return_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.receive_i = &axi_lite_recv },
};
struct _p0_swblk_set _p0_swinst_set_0 = {
.cmd_set = { .base = {
.channel_info = &_p0_swinst_set_0_cmd_set_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.send_i = &axi_lite_send },
.data = { .base = {
.channel_info = &_p0_swinst_set_0_data_info,
.open_i = &zero_copy_open,
.close_i = &zero_copy_close },
.send_ref_i = &zero_copy_send_ref_i },
.key = { .base = {
.channel_info = &_p0_swinst_set_0_key_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.send_i = &axi_lite_send },
.val_r = { .base = {
.channel_info = &_p0_swinst_set_0_val_r_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.send_i = &axi_lite_send },
.ap_return = { .base = {
.channel_info = &_p0_swinst_set_0_ap_return_info,
.open_i = &axi_lite_open,
.close_i = &axi_lite_close },
.receive_i = &axi_lite_recv },
};
void _p0_cf_open_port (cf_port_base_t *port)
{
port->open_i(port, NULL);
}
void _p0_cf_framework_open(int first)
{
cf_context_init();
xlnkCounterMap();
_p0_cf_register(first);
cf_get_current_context();
accel_open(&_sds__p0_get_0);
accel_open(&_sds__p0_set_0);
_p0_cf_open_port( &_p0_swinst_get_0.cmd_get.base );
_p0_cf_open_port( &_p0_swinst_get_0.data.base );
_p0_cf_open_port( &_p0_swinst_get_0.key.base );
_p0_cf_open_port( &_p0_swinst_get_0.val_r.base );
_p0_cf_open_port( &_p0_swinst_get_0.ap_return.base );
_p0_cf_open_port( &_p0_swinst_set_0.cmd_set.base );
_p0_cf_open_port( &_p0_swinst_set_0.data.base );
_p0_cf_open_port( &_p0_swinst_set_0.key.base );
_p0_cf_open_port( &_p0_swinst_set_0.val_r.base );
_p0_cf_open_port( &_p0_swinst_set_0.ap_return.base );
}
void _p0_cf_framework_close(int last)
{
cf_close_i( &_p0_swinst_get_0.cmd_get, NULL);
cf_close_i( &_p0_swinst_get_0.data, NULL);
cf_close_i( &_p0_swinst_get_0.key, NULL);
cf_close_i( &_p0_swinst_get_0.val_r, NULL);
cf_close_i( &_p0_swinst_get_0.ap_return, NULL);
cf_close_i( &_p0_swinst_set_0.cmd_set, NULL);
cf_close_i( &_p0_swinst_set_0.data, NULL);
cf_close_i( &_p0_swinst_set_0.key, NULL);
cf_close_i( &_p0_swinst_set_0.val_r, NULL);
cf_close_i( &_p0_swinst_set_0.ap_return, NULL);
accel_close(&_sds__p0_get_0);
accel_close(&_sds__p0_set_0);
_p0_cf_unregister(last);
}
#define TOTAL_PARTITIONS 1
int current_partition_num = 0;
struct {
void (*open)(int);
void (*close)(int);
}
_ptable[TOTAL_PARTITIONS] = {
{.open = &_p0_cf_framework_open, .close= &_p0_cf_framework_close},
};
void switch_to_next_partition(int partition_num)
{
#ifdef __linux__
if (current_partition_num != partition_num) {
_ptable[current_partition_num].close(0);
char buf[128];
sprintf(buf, "cat /mnt/_sds/_p%d_.bin > /dev/xdevcfg", partition_num);
system(buf);
_ptable[partition_num].open(0);
current_partition_num = partition_num;
}
#endif
}
void init_first_partition() __attribute__ ((constructor));
void close_last_partition() __attribute__ ((destructor));
void init_first_partition()
{
current_partition_num = 0;
_ptable[current_partition_num].open(1);
sds_trace_setup();
}
void close_last_partition()
{
#ifdef PERF_EST
apf_perf_estimation_exit();
#endif
sds_trace_cleanup();
_ptable[current_partition_num].close(1);
current_partition_num = 0;
}
| 27.847222 | 83 | 0.697922 |
43ea5359e0114fb4b7b7f2343f14759b1df2924a | 1,817 | h | C | Unreal/Plugins/AirSim/Source/Vehicles/ComputerVision/ComputerVisionPawn.h | aszego/AirSim | 74fb9108e7a8426a17fd4ad3a34d97fe070cc35e | [
"MIT"
] | 1 | 2021-09-27T13:37:49.000Z | 2021-09-27T13:37:49.000Z | Unreal/Plugins/AirSim/Source/Vehicles/ComputerVision/ComputerVisionPawn.h | aszego/AirSim | 74fb9108e7a8426a17fd4ad3a34d97fe070cc35e | [
"MIT"
] | 1 | 2018-06-27T13:08:46.000Z | 2018-06-27T13:08:46.000Z | Unreal/Plugins/AirSim/Source/Vehicles/ComputerVision/ComputerVisionPawn.h | aszego/AirSim | 74fb9108e7a8426a17fd4ad3a34d97fe070cc35e | [
"MIT"
] | 1 | 2020-01-14T02:12:48.000Z | 2020-01-14T02:12:48.000Z | #pragma once
#include "CoreMinimal.h"
#include "UObject/ConstructorHelpers.h"
#include "physics/Kinematics.hpp"
#include "common/AirSimSettings.hpp"
#include "AirBlueprintLib.h"
#include "api/VehicleSimApiBase.hpp"
#include "common/common_utils/UniqueValueMap.hpp"
#include "PawnEvents.h"
#include "PIPCamera.h"
#include "ManualPoseController.h"
#include "ComputerVisionPawn.generated.h"
UCLASS()
class AComputerVisionPawn : public APawn
{
GENERATED_BODY()
public:
AComputerVisionPawn();
virtual void BeginPlay() override;
virtual void Tick(float Delta) override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void NotifyHit(class UPrimitiveComponent* MyComp, class AActor* Other, class UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation,
FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit) override;
//interface
void initializeForBeginPlay();
common_utils::UniqueValueMap<std::string, APIPCamera*> getCameras() const;
PawnEvents* getPawnEvents()
{
return &pawn_events_;
}
private:
UPROPERTY() UClass* pip_camera_class_;
PawnEvents pawn_events_;
UPROPERTY() USceneComponent* camera_front_center_base_;
UPROPERTY() USceneComponent* camera_front_left_base_;
UPROPERTY() USceneComponent* camera_front_right_base_;
UPROPERTY() USceneComponent* camera_bottom_center_base_;
UPROPERTY() USceneComponent* camera_back_center_base_;
UPROPERTY() APIPCamera* camera_front_center_;
UPROPERTY() APIPCamera* camera_front_left_;
UPROPERTY() APIPCamera* camera_front_right_;
UPROPERTY() APIPCamera* camera_bottom_center_;
UPROPERTY() APIPCamera* camera_back_center_;
UPROPERTY() UManualPoseController* manual_pose_controller_;
};
| 30.283333 | 158 | 0.766098 |
a15142ea9fe0ab805f157082ada923567f696faf | 95 | h | C | main/interface/uart/web3/web3_http.h | chesterliliang/esp-at | 9ed19a5c100597c839c9548724ea3b429bb2eb63 | [
"MIT-0"
] | null | null | null | main/interface/uart/web3/web3_http.h | chesterliliang/esp-at | 9ed19a5c100597c839c9548724ea3b429bb2eb63 | [
"MIT-0"
] | null | null | null | main/interface/uart/web3/web3_http.h | chesterliliang/esp-at | 9ed19a5c100597c839c9548724ea3b429bb2eb63 | [
"MIT-0"
] | null | null | null | #include "web3_inc.h"
uint32_t http_post(const char* url, const char* post_data, char* result); | 47.5 | 73 | 0.768421 |
bd98be79eca9bfb6adaf5ca22c691d06d9cea93a | 388 | h | C | CartoonWorld/CartoonWorld/Models/SearchHotModel.h | luo6luo/CartoonWorld | f4cab1eeff3d85fccd4ea6ba370a47a763df5291 | [
"MIT"
] | 3 | 2018-12-11T10:35:01.000Z | 2019-05-09T09:03:33.000Z | CartoonWorld/CartoonWorld/Models/SearchHotModel.h | luo6luo/CartoonWorld | f4cab1eeff3d85fccd4ea6ba370a47a763df5291 | [
"MIT"
] | null | null | null | CartoonWorld/CartoonWorld/Models/SearchHotModel.h | luo6luo/CartoonWorld | f4cab1eeff3d85fccd4ea6ba370a47a763df5291 | [
"MIT"
] | 2 | 2018-01-02T02:58:48.000Z | 2019-05-09T09:03:34.000Z | //
// SearchHotModel.h
// CartoonWorld
//
// Created by dundun on 2017/11/6.
// Copyright © 2017年 顿顿. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SearchHotModel : NSObject
@property (nonatomic, strong) NSString *bgColor; // 字体颜色
@property (nonatomic, assign) NSInteger search_num; // 搜索id
@property (nonatomic, strong) NSString *tagName; // 标签
@end
| 21.555556 | 59 | 0.703608 |
311968c27f24a06b13a3a29280253783b072d044 | 680 | h | C | iOS/UnityTapticPlugin.h | SoyYuma/unity-taptic-plugin | 0f5df6c82140d8f831094e1b9f544af3e82908af | [
"MIT"
] | null | null | null | iOS/UnityTapticPlugin.h | SoyYuma/unity-taptic-plugin | 0f5df6c82140d8f831094e1b9f544af3e82908af | [
"MIT"
] | null | null | null | iOS/UnityTapticPlugin.h | SoyYuma/unity-taptic-plugin | 0f5df6c82140d8f831094e1b9f544af3e82908af | [
"MIT"
] | null | null | null | //
// UnityTapticPlugin.h
// unity-taptic-plugin
//
// Created by Koki Ibukuro on 12/6/16.
// Modified by Ale Cámara in 2019.
//
// Licensed under MIT License.
// See LICENSE in root directory.
//
#ifndef UnityTapticPlugin_h
#define UnityTapticPlugin_h
#import <UIKit/UIKit.h>
@interface UnityTapticPlugin : NSObject
{}
+ (UnityTapticPlugin*) shared;
- (void) prepareNotification;
- (void) triggerNotification:(UINotificationFeedbackType) type;
- (void) prepareSelection;
- (void) triggerSelection;
- (void) prepareImpact:(UIImpactFeedbackStyle) style;
- (void) triggerImpact:(UIImpactFeedbackStyle) style;
+ (BOOL) isSupported;
@end
#endif /* UnityTapticPlugin_h */
| 20.606061 | 63 | 0.739706 |
236e7277ca513774a11ae20cbb3e13d2f475f698 | 13,370 | h | C | libminifi/include/core/state/nodes/DeviceInformation.h | dtrodrigues/nifi-minifi-cpp | 87147e2dffcda6cc6e4e0510a57cc88011fda37f | [
"Apache-2.0",
"OpenSSL"
] | 113 | 2016-04-30T15:00:13.000Z | 2022-03-26T20:42:58.000Z | libminifi/include/core/state/nodes/DeviceInformation.h | dtrodrigues/nifi-minifi-cpp | 87147e2dffcda6cc6e4e0510a57cc88011fda37f | [
"Apache-2.0",
"OpenSSL"
] | 688 | 2016-04-28T17:52:38.000Z | 2022-03-29T07:58:05.000Z | libminifi/include/core/state/nodes/DeviceInformation.h | dtrodrigues/nifi-minifi-cpp | 87147e2dffcda6cc6e4e0510a57cc88011fda37f | [
"Apache-2.0",
"OpenSSL"
] | 104 | 2016-04-28T15:20:51.000Z | 2022-03-01T13:39:20.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.
*/
#ifndef LIBMINIFI_INCLUDE_CORE_STATE_NODES_DEVICEINFORMATION_H_
#define LIBMINIFI_INCLUDE_CORE_STATE_NODES_DEVICEINFORMATION_H_
#ifndef WIN32
#if ( defined(__APPLE__) || defined(__MACH__) || defined(BSD))
#include <net/if_dl.h>
#include <net/if_types.h>
#endif
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netdb.h>
#include <unistd.h>
#else
#pragma comment(lib, "iphlpapi.lib")
#include <Windows.h>
#include <iphlpapi.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <set>
#include <string>
#include <vector>
#include <fstream>
#include <functional>
#include <map>
#include <sstream>
#include "../nodes/MetricsBase.h"
#include "Connection.h"
#include "io/ClientSocket.h"
#include "utils/OsUtils.h"
#include "utils/NetworkInterfaceInfo.h"
#include "utils/SystemCpuUsageTracker.h"
#include "utils/Export.h"
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace state {
namespace response {
class Device {
public:
Device() {
initialize();
}
void initialize() {
addrinfo hints;
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
hints.ai_protocol = 0; /* any protocol */
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
std::ifstream device_id_file(".device_id");
if (device_id_file) {
std::string line;
while (device_id_file) {
if (std::getline(device_id_file, line))
device_id_ += line;
}
device_id_file.close();
} else {
device_id_ = getDeviceId();
std::ofstream outputFile(".device_id");
if (outputFile) {
outputFile.write(device_id_.c_str(), device_id_.length());
}
outputFile.close();
}
canonical_hostname_ = hostname;
std::stringstream ips;
auto ipaddressess = getIpAddresses();
for (auto ip : ipaddressess) {
if (ipaddressess.size() > 1 && (ip.find("127") == 0 || ip.find("192") == 0))
continue;
ip_ = ip;
break;
}
}
std::string canonical_hostname_;
std::string ip_;
std::string device_id_;
protected:
std::vector<std::string> getIpAddresses() {
static std::vector<std::string> ips;
if (ips.empty()) {
const auto filter = [](const utils::NetworkInterfaceInfo& interface_info) {
return !interface_info.isLoopback() && interface_info.isRunning();
};
auto network_interface_infos = utils::NetworkInterfaceInfo::getNetworkInterfaceInfos(filter);
for (const auto& network_interface_info : network_interface_infos)
for (const auto& ip_v4_address : network_interface_info.getIpV4Addresses())
ips.push_back(ip_v4_address);
}
return ips;
}
#if __linux__
std::string getDeviceId() {
std::hash<std::string> hash_fn;
std::string macs;
struct ifaddrs *ifaddr, *ifa;
int family, s, n;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1) {
exit(EXIT_FAILURE);
}
/* Walk through linked list, maintaining head pointer so we
can free list later */
for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
/* Display interface name and family (including symbolic
form of the latter for the common families) */
/* For an AF_INET* interface address, display the address */
if (family == AF_INET || family == AF_INET6) {
s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST,
NULL,
0, NI_NUMERICHOST);
if (s != 0) {
printf("getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
}
}
freeifaddrs(ifaddr);
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
struct ifreq ifr;
struct ifconf ifc;
char buf[1024];
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */
}
struct ifreq* it = ifc.ifc_req;
const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (; it != end; ++it) {
strcpy(ifr.ifr_name, it->ifr_name); // NOLINT
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
if (!(ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
unsigned char mac[6];
memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
char mac_add[13];
snprintf(mac_add, 13, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); // NOLINT
macs += mac_add;
}
}
} else { /* handle error */
}
}
close(sock);
return std::to_string(hash_fn(macs));
}
#elif(defined(__unix__) || defined(__APPLE__) || defined(__MACH__) || defined(BSD)) // should work on bsd variants as well
std::string getDeviceId() {
ifaddrs* iflist;
std::hash<std::string> hash_fn;
std::set<std::string> macs;
if (getifaddrs(&iflist) == 0) {
for (ifaddrs* cur = iflist; cur; cur = cur->ifa_next) {
if (cur->ifa_addr && (cur->ifa_addr->sa_family == AF_LINK) && (reinterpret_cast<sockaddr_dl*>(cur->ifa_addr))->sdl_alen) {
sockaddr_dl* sdl = reinterpret_cast<sockaddr_dl*>(cur->ifa_addr);
if (sdl->sdl_type != IFT_ETHER) {
continue;
} else {
}
char mac[32];
memcpy(mac, LLADDR(sdl), sdl->sdl_alen);
char mac_add[13];
snprintf(mac_add, 13, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); // NOLINT
// macs += mac_add;
macs.insert(mac_add);
}
}
freeifaddrs(iflist);
}
std::string macstr;
for (auto &mac : macs) {
macstr += mac;
}
return macstr.length() > 0 ? std::to_string(hash_fn(macstr)) : "8675309";
}
#else
std::string getDeviceId() {
PIP_ADAPTER_INFO adapterPtr;
PIP_ADAPTER_INFO adapter = NULL;
DWORD dwRetVal = 0;
std::hash<std::string> hash_fn;
std::set<std::string> macs;
ULONG adapterLen = sizeof(IP_ADAPTER_INFO);
adapterPtr = reinterpret_cast<IP_ADAPTER_INFO*>(malloc(sizeof(IP_ADAPTER_INFO)));
if (adapterPtr == NULL) {
return "";
}
if (GetAdaptersInfo(adapterPtr, &adapterLen) == ERROR_BUFFER_OVERFLOW) {
free(adapterPtr);
adapterPtr = reinterpret_cast<IP_ADAPTER_INFO*>(malloc(adapterLen));
if (adapterPtr == NULL) {
return "";
}
}
if ((dwRetVal = GetAdaptersInfo(adapterPtr, &adapterLen)) == NO_ERROR) {
adapter = adapterPtr;
while (adapter) {
char mac_add[13];
snprintf(mac_add, 13, "%02X%02X%02X%02X%02X%02X", adapter->Address[0], adapter->Address[1], adapter->Address[2], adapter->Address[3], adapter->Address[4], adapter->Address[5]); // NOLINT
macs.insert(mac_add);
adapter = adapter->Next;
}
}
if (adapterPtr)
free(adapterPtr);
std::string macstr;
for (auto &mac : macs) {
macstr += mac;
}
return macstr.length() > 0 ? std::to_string(hash_fn(macstr)) : "8675309";
}
#endif
// connection information
int32_t socket_file_descriptor_;
addrinfo *addr_info_;
};
/**
* Justification and Purpose: Provides Device Information
*/
class DeviceInfoNode : public DeviceInformation {
public:
DeviceInfoNode(const std::string& name, const utils::Identifier& uuid)
: DeviceInformation(name, uuid) {
static Device device;
hostname_ = device.canonical_hostname_;
ip_ = device.ip_;
device_id_ = device.device_id_;
}
DeviceInfoNode(const std::string &name) // NOLINT
: DeviceInformation(name) {
static Device device;
hostname_ = device.canonical_hostname_;
ip_ = device.ip_;
device_id_ = device.device_id_;
}
std::string getName() const {
return "deviceInfo";
}
std::vector<SerializedResponseNode> serialize() {
std::vector<SerializedResponseNode> serialized;
serialized.push_back(serializeIdentifier());
serialized.push_back(serializeSystemInfo());
serialized.push_back(serializeNetworkInfo());
return serialized;
}
protected:
SerializedResponseNode serializeIdentifier() const {
SerializedResponseNode identifier;
identifier.name = "identifier";
identifier.value = device_id_;
return identifier;
}
SerializedResponseNode serializeVCoreInfo() const {
SerializedResponseNode v_cores;
v_cores.name = "vCores";
v_cores.value = std::thread::hardware_concurrency();
return v_cores;
}
SerializedResponseNode serializeOperatingSystemType() const {
SerializedResponseNode os_type;
os_type.name = "operatingSystem";
os_type.value = getOperatingSystem();
return os_type;
}
SerializedResponseNode serializeTotalPhysicalMemoryInformation() const {
SerializedResponseNode total_physical_memory;
total_physical_memory.name = "physicalMem";
total_physical_memory.value = utils::OsUtils::getSystemTotalPhysicalMemory();
return total_physical_memory;
}
SerializedResponseNode serializePhysicalMemoryUsageInformation() const {
SerializedResponseNode used_physical_memory;
used_physical_memory.name = "memoryUsage";
used_physical_memory.value = utils::OsUtils::getSystemPhysicalMemoryUsage();
return used_physical_memory;
}
SerializedResponseNode serializeSystemCPUUsageInformation() const {
double system_cpu_usage = -1.0;
{
std::lock_guard<std::mutex> guard(cpu_load_tracker_mutex_);
system_cpu_usage = cpu_load_tracker_.getCpuUsageAndRestartCollection();
}
SerializedResponseNode cpu_usage;
cpu_usage.name = "cpuUtilization";
cpu_usage.value = system_cpu_usage;
return cpu_usage;
}
SerializedResponseNode serializeArchitectureInformation() const {
SerializedResponseNode arch;
arch.name = "machinearch";
arch.value = utils::OsUtils::getMachineArchitecture();
return arch;
}
SerializedResponseNode serializeSystemInfo() const {
SerializedResponseNode systemInfo;
systemInfo.name = "systemInfo";
systemInfo.children.push_back(serializeVCoreInfo());
systemInfo.children.push_back(serializeOperatingSystemType());
systemInfo.children.push_back(serializeTotalPhysicalMemoryInformation());
systemInfo.children.push_back(serializeArchitectureInformation());
systemInfo.children.push_back(serializePhysicalMemoryUsageInformation());
systemInfo.children.push_back(serializeSystemCPUUsageInformation());
return systemInfo;
}
SerializedResponseNode serializeHostNameInfo() const {
SerializedResponseNode hostname;
hostname.name = "hostname";
hostname.value = hostname_;
return hostname;
}
SerializedResponseNode serializeIPAddress() const {
SerializedResponseNode ip;
ip.name = "ipAddress";
ip.value = !ip_.empty() ? ip_ : "127.0.0.1";
return ip;
}
SerializedResponseNode serializeNetworkInfo() const {
SerializedResponseNode network_info;
network_info.name = "networkInfo";
network_info.children.push_back(serializeHostNameInfo());
network_info.children.push_back(serializeIPAddress());
return network_info;
}
/**
* Have found various ways of identifying different operating system variants
* so these were either pulled from header files or online.
*/
static inline std::string getOperatingSystem() {
/**
* We define WIN32, but *most* compilers should provide _WIN32.
*/
#if defined(WIN32) || defined(_WIN32) || defined(_WIN64)
return "Windows";
#elif defined(__APPLE__) || defined(__MACH__)
return "Mac OSX";
#elif defined(__linux__)
return "Linux";
#elif defined(__unix) || defined(__unix__) || defined(__FreeBSD__)
return "Unix";
#else
return "Other";
#endif
}
std::string hostname_;
std::string ip_;
std::string device_id_;
MINIFIAPI static utils::SystemCpuUsageTracker cpu_load_tracker_;
MINIFIAPI static std::mutex cpu_load_tracker_mutex_;
};
} // namespace response
} // namespace state
} // namespace minifi
} // namespace nifi
} // namespace apache
} // namespace org
#endif // LIBMINIFI_INCLUDE_CORE_STATE_NODES_DEVICEINFORMATION_H_
| 29.449339 | 194 | 0.672401 |
03c761e754ef2cdc18f65253dec93f90b6088d04 | 4,098 | h | C | RecvMsg.h | JakeMont/OpenBFDD | 841b82ce9562175843e21bcb26f194a12e399a54 | [
"BSD-3-Clause"
] | null | null | null | RecvMsg.h | JakeMont/OpenBFDD | 841b82ce9562175843e21bcb26f194a12e399a54 | [
"BSD-3-Clause"
] | null | null | null | RecvMsg.h | JakeMont/OpenBFDD | 841b82ce9562175843e21bcb26f194a12e399a54 | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************
* Copyright (c) 2011, Dynamic Network Services, Inc.
* Jake Montgomery (jmontgomery@dyn.com) & Tom Daly (tom@dyn.com)
* Distributed under the FreeBSD License - see LICENSE
***************************************************************/
#pragma once
#include "SockAddr.h"
#include "SmartPointer.h"
namespace openbfdd
{
class Socket;
/**
* A container for recv or recvmsg results.
*/
class RecvMsg
{
public:
/**
* Creates an empty RecvMsgData.
*
* Must call AllocBuffers() before calling RecvMsg().
*/
RecvMsg();
/**
* Creates a RecvMsg and allocates storage.
*
* @throw - yes
*
* @param bufferSize [in] - The size of the buffer for receiving data.
*
* @param controlSize [in] - The size of the buffer for receiving control
* messages. This should be large enough for all enabled
* messages. Use CMSG_SPACE to calculate desired size. May be
* 0 when used for recv.
*/
RecvMsg(size_t bufferSize, size_t controlSize);
/**
* Allocates storage.
*
* @throw - yes
*
* @param bufferSize [in] - The size of the buffer for receiving data.
*
* @param controlSize [in] - The size of the buffer for receiving control
* messages. This should be large enough for all enabled
* messages. Use CMSG_SPACE to calculate desired size. May be
* 0 when used for recv.
*/
void AllocBuffers(size_t bufferSize, size_t controlSize);
/**
* Call recvmsg for the given socket.
* Call GetLastError() on failure to get the errno.
*
* @param socket
*
* @return bool - false on failure.
*/
bool DoRecvMsg(const Socket &socket);
/**
* Call recv for the given socket. Call GetLastError() on failure to get the
* errno.
*
* @param socket
* @param flags - Flags for recv.
*
* @return bool - false on failure.
*/
bool DoRecv(const Socket &socket, int flags);
/**
* @return - The error from the last DoRecvMsg call. 0 if it succeeded.
*/
int GetLastError() { return m_error;}
/**
* Gets the TTL or Hops (for IPv6).
*
*
* @param success [out] - False on failure.
*
* @return uint8_t - The ttl or hops. 0 on failure. (Note 0 is also a valid
* value, use success to determine failure).
*/
uint8_t GetTTLorHops(bool *success = NULL);
/**
* Gets the destination address.
*
* @return IpAddr - IsValid() will return false on failure.
*/
const IpAddr& GetDestAddress() { return m_destAddress;}
/**
* The source address.
*
* @return SockAddr - IsValid() will return true on failure.
*/
const SockAddr& GetSrcAddress() { return m_sourceAddress;}
/**
* Gets the data from the last DoRecvMsg(), if successful.
*
*
* @return - Data from the last DoRecvMsg(), if successful. NULL if DoRecvMsg
* was never called, or it failed.
*/
uint8_t* GetData() { return m_dataBufferValidSize ? m_dataBuffer.val : NULL;}
/**
* Gets the size of the data from the last DoRecvMsg(), if successful.
*
*
* @return - The size of valid data from the last DoRecvMsg(), if
* successful. 0 if DoRecvMsg was never called, or it failed.
*/
size_t GetDataSize() { return m_dataBufferValidSize;}
private:
void clear();
private:
Raii<uint8_t>::DeleteArray m_controlBuffer; // Not using vector, because we do not want initialization.
size_t m_controlBufferSize;
Raii<uint8_t>::DeleteArray m_dataBuffer; // Not using vector, because we do not want initialization.
size_t m_dataBufferSize;
size_t m_dataBufferValidSize; // Only valid after successful DoRecvMsg
SockAddr m_sourceAddress;
IpAddr m_destAddress;
int16_t m_ttlOrHops; // -1 for invalid
int m_error;
};
}
| 29.271429 | 107 | 0.588336 |
ea824dc3ac01377c4560ff72593f41a5d1378749 | 22,238 | c | C | test/performance-regression/full-apps/hpcc-1.5.0/PTRANS/cblacslt.c | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 55 | 2015-07-28T01:32:58.000Z | 2022-02-27T16:27:46.000Z | test/performance-regression/full-apps/hpcc-1.5.0/PTRANS/cblacslt.c | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | test/performance-regression/full-apps/hpcc-1.5.0/PTRANS/cblacslt.c | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | 26 | 2015-10-26T22:11:51.000Z | 2021-03-02T22:09:15.000Z | /* -*- mode: C; tab-width: 2; indent-tabs-mode: nil; -*- */
/*
cblacslt.c
-- V0.0 Stripped-down BLACS routines --
University of Tennessee, October, 2003
Written by Piotr Luszczek.
*/
#include <hpcc.h>
#include <mpi.h>
#include "cblacslt.h"
#define DPRN(i,v) do{printf(__FILE__ "(%d)@%d:" #v "=%g\n",__LINE__,i,(double)(v));fflush(stdout);}while(0)
/* ---------------------------------------------------------------------- */
/*FIXME: what about parameter checking: context, etc? have a macro too? */
#define CBLACS_INIT if (! CblacsInitialized) CblacsInit(); else if (CblacsFinalized) do{CblacsWarn();return;}while(0)
#define CBLACS_INIT1(v) if (! CblacsInitialized) CblacsInit();else if (CblacsFinalized)do{CblacsWarn();return(v);}while(0)
#define CblacsWarn() CblacsWarnImp( __FILE__, __LINE__ )
static int CblacsInitialized = 0, CblacsFinalized;
double
dcputime00(void) {return HPL_ptimer_cputime();}
double
dwalltime00(void) {return MPI_Wtime();}
static void
CblacsWarnImp(char *file, int line) {
int rank;
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
printf( "%s(%d)@%d: CBLACS warning.\n", file, line, rank );
fflush(stdout);
}
static struct {MPI_Comm comm, rowComm, colComm; unsigned int taken;} CblacsComms[10];
static int CblacsNComms;
#define CBLACS_CHK_CTXT(v) if (ctxt < 1 || ctxt > CblacsNComms) return v
static MPI_Comm
CblacsGetComm(int ctxt) {
CBLACS_CHK_CTXT(MPI_COMM_NULL);
return CblacsComms[ctxt - 1].comm;
}
static MPI_Comm
CblacsGetRowComm(int ctxt) {
CBLACS_CHK_CTXT(MPI_COMM_NULL);
return CblacsComms[ctxt - 1].rowComm;
}
static MPI_Comm
CblacsGetColComm(int ctxt) {
CBLACS_CHK_CTXT(MPI_COMM_NULL);
return CblacsComms[ctxt - 1].colComm;
}
static int
CblacsSetComm(int ctxt, MPI_Comm comm) {
CBLACS_CHK_CTXT(-1);
CblacsComms[ctxt - 1].comm = comm;
return 0;
}
static int
CblacsSetRowComm(int ctxt, MPI_Comm comm) {
CBLACS_CHK_CTXT(-1);
CblacsComms[ctxt - 1].rowComm = comm;
return 0;
}
static int
CblacsSetColComm(int ctxt, MPI_Comm comm) {
CBLACS_CHK_CTXT(-1);
CblacsComms[ctxt - 1].colComm = comm;
return 0;
}
static int
CblacsNewCtxt() {
int i;
for (i = 1; i < CblacsNComms; i++)
if (! CblacsComms[i].taken) {
CblacsComms[i].taken = 1;
return i + 1;
}
return 0;
}
static int
CblacsDeleteCtxt(int *ctxtP) {
int idx = *ctxtP - 1;
if (idx < 1 || idx >= CblacsNComms) {
CblacsWarn();
return -1;
}
if (0 == CblacsComms[idx].taken) {
CblacsWarn();
return -1;
}
if (MPI_COMM_NULL != CblacsComms[idx].colComm) MPI_Comm_free( &(CblacsComms[idx].colComm) );
if (MPI_COMM_NULL != CblacsComms[idx].rowComm) MPI_Comm_free( &(CblacsComms[idx].rowComm) );
if (MPI_COMM_NULL != CblacsComms[idx].comm) MPI_Comm_free( &(CblacsComms[idx].comm) );
CblacsComms[idx].taken = 0;
*ctxtP = 0; /* deleted contexts are 0 */
return 0;
}
/*
static void *
CblacsNewBuf(int count, int esize) {
return malloc( count * esize );
}
*/
#define CblacsNewBuf(c,s) malloc((c)*(s))
#define CblacsDeleteBuf(b) free(b)
static int
CblacsInit() {
int i, flag;
if (MPI_SUCCESS != MPI_Initialized( &flag ) || ! flag) {CblacsWarn();return 1;}
CblacsInitialized = 1;
CblacsFinalized = 0;
CblacsNComms = 10;
for (i = 0; i < CblacsNComms; i++) {
CblacsComms[i].comm = MPI_COMM_NULL;
CblacsComms[i].rowComm = MPI_COMM_NULL;
CblacsComms[i].colComm = MPI_COMM_NULL;
CblacsComms[i].taken = 0;
}
/* FIXME: setup system context to be a cartesian grid with row and column comm's*/
CblacsComms[0].comm = MPI_COMM_WORLD;
CblacsComms[0].rowComm = MPI_COMM_NULL;
CblacsComms[0].colComm = MPI_COMM_NULL;
CblacsComms[0].taken = 1;
return 0;
}
void
Cblacs_pinfo(int *mypnum, int *nprocs) {
CBLACS_INIT;
MPI_Comm_rank( MPI_COMM_WORLD, mypnum );
MPI_Comm_size( MPI_COMM_WORLD, nprocs );
}
void
Cblacs_exit(int NotDone) {
CBLACS_INIT;
CblacsFinalized = 0;
if (! NotDone) MPI_Finalize();
}
void
Cblacs_abort(int ConTxt, int ErrNo) {
int nprow, npcol, myrow, mycol, rank;
CBLACS_INIT;
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
Cblacs_gridinfo(ConTxt, &nprow, &npcol, &myrow, &mycol);
fprintf(stderr, "{%d,%d}, pnum=%d, Contxt=%d, killed other procs, exiting with error #%d.\n\n",
myrow, mycol, rank, ConTxt, ErrNo);
fflush(stderr);
fflush(stdout);
MPI_Abort( MPI_COMM_WORLD, ErrNo );
}
void
Cblacs_get(int ConTxt, int what, int *val) {
CBLACS_INIT;
switch (what) {
case SGET_SYSCONTXT:
*val = 1;
break;
default:
*val = -1;
CblacsWarn();
break;
}
}
static int
CblacsGridNew(int nprow, int npcol, int *ConTxt, MPI_Comm *comm) {
int size;
CBLACS_INIT1(-1);
*comm = CblacsGetComm(*ConTxt);
if (MPI_COMM_NULL == *comm) return -1;
MPI_Comm_size( *comm, &size );
if (nprow < 1 || nprow > size) return -1;
if (npcol < 1 || npcol > size) return -1;
if (nprow * npcol > size) return -1;
*ConTxt = CblacsNewCtxt();
return 0;
}
void
Cblacs_gridmap(int *ConTxt, int *umap, int ldumap, int nprow, int npcol) {
int i, j, np_me, npall, npwho, myrow, mycol, color, key, rv;
MPI_Comm comm, newComm, rowComm, colComm;
if (CblacsGridNew( nprow, npcol, ConTxt, &comm )) {
CblacsWarn();
goto gmapErr;
}
Cblacs_pinfo( &np_me, &npall );
myrow = mycol = -1;
color = MPI_UNDEFINED;
key = 0;
for (i = 0; i < nprow; ++i)
for (j = 0; j < npcol; ++j) {
npwho = umap[j + i * ldumap];
if (np_me == npwho) {
color = 0;
key = j + i * npcol;
myrow = i;
mycol = j;
goto gmapFound;
}
}
gmapFound:
/* communicator of all grid processes */
rv = MPI_Comm_split( comm, color, key, &newComm );
if (MPI_SUCCESS != rv) {
/* make contexts for non-participating processes a 0 value so gridinfo() works correctly */
CblacsDeleteCtxt( ConTxt );
goto gmapErr;
}
CblacsSetComm( *ConTxt, newComm );
if (MPI_COMM_NULL == newComm) { /* this process does not participate in this grid */
CblacsDeleteCtxt( ConTxt );
return;
}
/* row communicator */
rv = MPI_Comm_split( newComm, myrow, mycol, &rowComm );
if (MPI_SUCCESS != rv) {
CblacsDeleteCtxt( ConTxt );
goto gmapErr;
}
CblacsSetRowComm( *ConTxt, rowComm );
/* column communicator */
rv = MPI_Comm_split( newComm, mycol, myrow, &colComm );
if (MPI_SUCCESS != rv) {
CblacsDeleteCtxt( ConTxt );
goto gmapErr;
}
CblacsSetColComm( *ConTxt, colComm );
return;
gmapErr:
*ConTxt = 0;
CblacsWarn();
return;
}
void
Cblacs_gridexit(int ConTxt) {
CBLACS_INIT;
CblacsDeleteCtxt( &ConTxt );
}
void
Cblacs_gridinfo(int ConTxt, int *nprow, int *npcol, int *myrow, int *mycol) {
MPI_Comm comm;
CBLACS_INIT;
comm = CblacsGetComm( ConTxt );
/* deleted contexts (or the contexts for non-participating processes) are 0 */
if (MPI_COMM_NULL == comm) {
*nprow = *npcol = *myrow = *mycol = -1;
} else {
MPI_Comm_size( CblacsGetRowComm(ConTxt), npcol );
MPI_Comm_rank( CblacsGetRowComm(ConTxt), mycol );
MPI_Comm_size( CblacsGetColComm(ConTxt), nprow );
MPI_Comm_rank( CblacsGetColComm(ConTxt), myrow );
}
}
/* ---------------------------------------------------------------------- */
/* Communication routines */
void
Cblacs_barrier(int ConTxt, char *scope) {
MPI_Comm comm;
CBLACS_INIT;
switch (*scope) {
case 'A': case 'a': comm = CblacsGetComm( ConTxt ); break;
case 'C': case 'c': comm = CblacsGetColComm( ConTxt ); break;
case 'R': case 'r': comm = CblacsGetRowComm( ConTxt ); break;
default: comm = MPI_COMM_NULL; CblacsWarn(); break;
}
if (MPI_COMM_NULL == comm) {
CblacsWarn();
return;
}
MPI_Barrier( comm );
}
static void
Cvgred2d(int ConTxt, char *scope, int m, int n, void *A, int lda, int rowRank,
int colRank, MPI_Datatype dtype, int dsize, MPI_Op op) {
int j, rank, root, count, coords[2], dest_rank, npcol;
void *sbuf, *rbuf;
MPI_Comm comm;
/* if the answer should be left on all processes */
if (-1 == rowRank || -1 == colRank) root = 0;
else root = 1;
switch (*scope) {
case 'A': case 'a':
comm = CblacsGetComm( ConTxt );
coords[0] = rowRank;
coords[1] = colRank;
MPI_Comm_size( CblacsGetRowComm( ConTxt ), &npcol );
dest_rank = colRank + rowRank * npcol;
break;
case 'C': case 'c':
comm = CblacsGetColComm( ConTxt );
coords[0] = rowRank;
dest_rank = rowRank;
break;
case 'R': case 'r':
comm = CblacsGetRowComm( ConTxt );
coords[0] = colRank;
dest_rank = colRank;
break;
default: comm = MPI_COMM_NULL; CblacsWarn(); break;
}
if (MPI_COMM_NULL == comm) {
CblacsWarn();
return;
}
/* if not leave-on-all then get rank of the destination */
if (root) root = dest_rank; /* MPI_Cart_rank( comm, coords, &root ); */
else root = MPI_PROC_NULL;
/* FIXME: what if contiguous buffer cannot be allocated */
count = m * n;
if (m == lda || n == 1) sbuf = A; /* A is contiguous, reuse it */
else {
/* a new data type could be created to reflect layout of `A' but then the
* receiving buffer would have to be the same, and if `lda' is large in
* comparison to `m' then it might be unfeasible */
sbuf = CblacsNewBuf( count, dsize );
for (j = 0; j < n; j++)
memcpy( (char *)sbuf + j * m * dsize, (char *)A + j * lda * dsize, m * dsize );
}
rbuf = CblacsNewBuf( count, dsize );
if (MPI_PROC_NULL == root) {
MPI_Allreduce( sbuf, rbuf, count, dtype, op, comm );
} else {
MPI_Reduce( sbuf, rbuf, count, dtype, op, root, comm );
MPI_Comm_rank( comm, &rank );
}
if (MPI_PROC_NULL == root || root == rank) {
if (A == sbuf) memcpy( A, rbuf, count * dsize ); /* A is contiguous */
else {
for (j = 0; j < n; j++)
memcpy( (char *)A + j * lda * dsize, (char *)rbuf + j * m * dsize, m * dsize );
}
}
CblacsDeleteBuf( rbuf );
if (sbuf != A) CblacsDeleteBuf( sbuf );
}
/*
* Purpose
*
* Combine sum operation for double precision rectangular matrices.
*
* Arguments
*
* ConTxt (input) int
* Index into MyConTxts00 (my contexts array).
*
* scope (input) Ptr to char
* Limit the scope of the operation.
* = 'R' : Operation is performed by a process row
* = 'C' : Operation is performed by a process column.
* = 'A' : Operation is performed by all processes in grid.
* If both `rdest' and `cdest' are not -1 then for 'R' scope `rdest' is ignored and for `C' - `cdest'
* is ignored (row or column of the scope are used, respectively).
*
* top (input) Ptr to char
* Controls fashion in which messages flow within the operation.
*
* m (input) int
* The number of rows of the matrix A. m >= 0.
*
* n (input) int
* The number of columns of the matrix A. n >= 0.
*
* A (output) Ptr to double precision two dimensional array
* The m by n matrix A. Fortran 77 (column-major) storage
* assumed.
*
* lda (input) int
* The leading dimension of the array A. lda >= m.
*
* rdest (input) int
* The process row of the destination of the sum.
* If rdest == -1, then result is left on all processes in scope.
*
* cdest (input) int
* The process column of the destination of the sum.
* If cdest == -1, then result is left on all processes in scope.
*/
void
Cdgsum2d(int ConTxt, char *scope, char *top, int m, int n, double *A, int lda, int rdest, int cdest){
CBLACS_INIT;
Cvgred2d( ConTxt, scope, m, n, A, lda, rdest, cdest, MPI_DOUBLE, sizeof(double), MPI_SUM );
}
void
Cigsum2d(int ConTxt, char *scope, char *top, int m, int n, int *A, int lda, int rdest, int cdest){
CBLACS_INIT;
Cvgred2d( ConTxt, scope, m, n, A, lda, rdest, cdest, MPI_INT, sizeof(int), MPI_SUM );
}
void
CblacsAbsMax(void *invec, void *inoutvec, int *len, MPI_Datatype *datatype) {
int i, n = *len; double *dinvec, *dinoutvec;
if (MPI_DOUBLE == *datatype) {
dinvec = (double *)invec;
dinoutvec = (double *)inoutvec;
for (i = n; i; i--, dinvec++, dinoutvec++)
if (fabs(*dinvec) > fabs(*dinoutvec)) *dinoutvec = *dinvec;
} else
CblacsWarn();
}
void
CblacsAbsMin(void *invec, void *inoutvec, int *len, MPI_Datatype *datatype) {
int i, n = *len; double *dinvec, *dinoutvec;
if (MPI_DOUBLE == *datatype) {
dinvec = (double *)invec;
dinoutvec = (double *)inoutvec;
for (i = n; i; i--, dinvec++, dinoutvec++)
if (fabs(*dinvec) < fabs(*dinoutvec)) *dinoutvec = *dinvec;
} else
CblacsWarn();
}
/*
* Purpose
*
* Combine amx operation for double precision rectangular matrices.
*
* Arguments
*
* ConTxt (input) Ptr to int
* Index into MyConTxts00 (my contexts array).
*
* SCOPE (input) Ptr to char
* Limit the scope of the operation.
* = 'R' : Operation is performed by a process row.
* = 'C' : Operation is performed by a process column.
* = 'A' : Operation is performed by all processes in grid.
*
* TOP (input) Ptr to char
* Controls fashion in which messages flow within the operation.
*
* M (input) Ptr to int
* The number of rows of the matrix A. M >= 0.
*
* N (input) Ptr to int
* The number of columns of the matrix A. N >= 0.
*
* A (output) Ptr to double precision two dimensional array
* The m by n matrix A. Fortran77 (column-major) storage
* assumed.
*
* LDA (input) Ptr to int
* The leading dimension of the array A. LDA >= M.
*
* RA (output) Integer Array, dimension (LDIA, N)
* Contains process row that the amx of each element
* of A was found on: i.e., rA(1,2) contains the process
* row that the amx of A(1,2) was found on.
* Values are left on process {rdest, cdest} only, others
* may be modified, but not left with interesting data.
* If rdest == -1, then result is left on all processes in scope.
* If LDIA == -1, this array is not accessed, and need not exist.
*
* CA (output) Integer Array, dimension (LDIA, N)
* Contains process column that the amx of each element
* of A was found on: i.e., cA(1,2) contains the process
* column that the max/min of A(1,2) was found on.
* Values are left on process {rdest, cdest} only, others
* may be modified, but not left with interesting data.
* If rdest == -1, then result is left on all processes in scope.
* If LDIA == -1, this array is not accessed, and need not exist.
*
* LDIA (input) Ptr to int
* If (LDIA == -1), then the arrays RA and CA are not accessed.
* ELSE leading dimension of the arrays RA and CA. LDIA >= M.
*
* RDEST (input) Ptr to int
* The process row of the destination of the amx.
* If rdest == -1, then result is left on all processes in scope.
*
* CDEST (input) Ptr to int
* The process column of the destination of the amx.
* If rdest == -1, then CDEST ignored.
*/
void
Cdgamx2d(int ConTxt, char *scope, char *top, int m, int n, double *A, int lda, int *rA, int *cA,
int ldia, int rdest, int cdest) {
MPI_Op op;
CBLACS_INIT;
if (ldia > 0) {CblacsWarn(); rA = cA; return;} /* no AMAX_LOC yet */
MPI_Op_create( CblacsAbsMax, 1, &op );
Cvgred2d( ConTxt, scope, m, n, A, lda, rdest, cdest, MPI_DOUBLE, sizeof(double), op );
MPI_Op_free( &op );
}
void
Cdgamn2d(int ConTxt, char *scope, char *top, int m, int n, double *A, int lda, int *rA, int *cA,
int ldia, int rdest, int cdest) {
MPI_Op op;
CBLACS_INIT;
if (ldia > 0) {CblacsWarn(); rA = cA; return;} /* no AMAX_LOC yet */
MPI_Op_create( CblacsAbsMin, 1, &op );
Cvgred2d( ConTxt, scope, m, n, A, lda, rdest, cdest, MPI_DOUBLE, sizeof(double), op );
MPI_Op_free( &op );
}
void
Cblacs_dSendrecv(int ctxt, int mSrc, int nSrc, double *Asrc, int ldaSrc, int rdest, int cdest,
int mDest, int nDest, double *Adest, int ldaDest, int rsrc, int csrc) {
MPI_Comm comm, rowComm;
MPI_Datatype typeSrc, typeDest;
MPI_Status stat;
int src, dest, dataIsContiguousSrc, dataIsContiguousDest, countSrc, countDest, npcol;
long int lSrc = mSrc * (long int)nSrc, lDest = mDest * (long int)nDest, li;
CBLACS_INIT;
comm = CblacsGetComm( ctxt );
if (MPI_COMM_NULL == comm) {CblacsWarn(); return;}
if (mSrc == ldaSrc || 1 == nSrc) {
dataIsContiguousSrc = 1;
countSrc = mSrc * nSrc;
typeSrc = MPI_DOUBLE;
} else {
dataIsContiguousSrc = 0;
countSrc = 1;
MPI_Type_vector( nSrc, mSrc, ldaSrc, MPI_DOUBLE, &typeSrc );
MPI_Type_commit( &typeSrc );
}
if (mDest == ldaDest || 1 == nDest) {
dataIsContiguousDest = 1;
countDest = mDest * nDest;
typeDest = MPI_DOUBLE;
} else {
dataIsContiguousDest = 0;
countDest = 1;
MPI_Type_vector( nDest, mDest, ldaDest, MPI_DOUBLE, &typeDest );
MPI_Type_commit( &typeDest );
}
rowComm = CblacsGetRowComm( ctxt );
MPI_Comm_size( rowComm, &npcol );
dest = cdest + rdest * npcol;
src = csrc + rsrc * npcol;
if (dataIsContiguousSrc && dataIsContiguousDest && lSrc == lDest) {
int mlength, maxpayload = 12500000; /* 100 MB at a time */
for (li = 0; li < lSrc; li += maxpayload) {
mlength = maxpayload;
if (lSrc - li < maxpayload)
mlength = lSrc - li;
MPI_Sendrecv( Asrc + li, mlength, typeSrc, dest, 0, Adest + li, mlength, typeDest, src, 0, comm, &stat );
}
} else {
MPI_Sendrecv( Asrc, countSrc, typeSrc, dest, 0, Adest, countDest, typeDest, src, 0, comm,
&stat ); /* IBM's (old ?) MPI doesn't have: MPI_STATUS_IGNORE */
}
if (! dataIsContiguousSrc) MPI_Type_free( &typeSrc );
if (! dataIsContiguousDest) MPI_Type_free( &typeDest );
}
static void
CblacsBcast(int ConTxt, char *scope, int m, int n, void *A, int lda, int rowRank, int colRank,
MPI_Datatype baseType){
MPI_Comm comm;
MPI_Datatype type;
int root, coords[2], dest_rank, npcol;
/* if this process is the root of broadcast */
if (-1 == rowRank || -1 == colRank) root = 0;
else root = 1;
switch (*scope) {
case 'A': case 'a':
comm = CblacsGetComm( ConTxt );
coords[0] = rowRank;
coords[1] = colRank;
MPI_Comm_size( CblacsGetRowComm( ConTxt ), &npcol );
dest_rank = colRank + rowRank * npcol;
break;
case 'C': case 'c':
comm = CblacsGetColComm( ConTxt );
coords[0] = rowRank;
dest_rank = rowRank;
break;
case 'R': case 'r':
comm = CblacsGetRowComm( ConTxt );
coords[0] = colRank;
dest_rank = colRank;
break;
default: comm = MPI_COMM_NULL; CblacsWarn(); break;
}
if (MPI_COMM_NULL == comm) {
CblacsWarn();
return;
}
if (MPI_COMM_NULL == comm) {
CblacsWarn();
return;
}
/* if broadcast/receive */
if (root) root = dest_rank; /* MPI_Cart_rank( comm, coords, &root ); */
else MPI_Comm_rank( comm, &root ); /* else broadcast/send - I'm the root */
MPI_Type_vector( n, m, lda, baseType, &type );
MPI_Type_commit( &type );
MPI_Bcast( A, 1, type, root, comm );
MPI_Type_free( &type );
}
/*
* Purpose
*
* Broadcast/send for general double precision arrays.
*
* Arguments
*
* ConTxt (input) Ptr to int
* Index into MyConTxts00 (my contexts array).
*
* SCOPE (input) Ptr to char
* Limit the scope of the operation.
* = 'R' : Operation is performed by a process row.
* = 'C' : Operation is performed by a process column.
* = 'A' : Operation is performed by all processes in grid.
*
* TOP (input) Ptr to char
* Controls fashion in which messages flow within the operation.
*
* M (input) Ptr to int
* The number of rows of the matrix A. M >= 0.
*
* N (input) Ptr to int
* The number of columns of the matrix A. N >= 0.
*
* A (input) Ptr to double precision two dimensional array
* The m by n matrix A. Fortran77 (column-major) storage
* assumed.
*
* LDA (input) Ptr to int
* The leading dimension of the array A. LDA >= M.
*/
void
Cdgebs2d(int ConTxt, char *scope, char *top, int m, int n, double *A, int lda) {
CBLACS_INIT;
CblacsBcast( ConTxt, scope, m, n, A, lda, -1, -1, MPI_DOUBLE );
}
/*
* Purpose
*
* Broadcast/receive for general double precision arrays.
*
* Arguments
*
* ConTxt (input) Ptr to int
* Index into MyConTxts00 (my contexts array).
*
* SCOPE (input) Ptr to char
* Limit the scope of the operation.
* = 'R' : Operation is performed by a process row.
* = 'C' : Operation is performed by a process column.
* = 'A' : Operation is performed by all processes in grid.
*
* TOP (input) Ptr to char
* Controls fashion in which messages flow within the operation.
*
* M (input) Ptr to int
* The number of rows of the matrix A. M >= 0.
*
* N (input) Ptr to int
* The number of columns of the matrix A. N >= 0.
*
* A (output) Ptr to double precision two dimensional array
* The m by n matrix A. Fortran77 (column-major) storage
* assumed.
*
* LDA (input) Ptr to int
* The leading dimension of the array A. LDA >= M.
*
*
* RSRC (input) Ptr to int
* The process row of the source of the matrix.
*
* CSRC (input) Ptr to int
* The process column of the source of the matrix.
*/
void
Cdgebr2d(int ConTxt, char *scope, char *top, int m, int n, double *A, int lda, int rsrc, int csrc) {
CBLACS_INIT;
CblacsBcast( ConTxt, scope, m, n, A, lda, rsrc, csrc, MPI_DOUBLE );
}
void
Cigebs2d(int ConTxt, char *scope, char *top, int m, int n, int *A, int lda) {
CBLACS_INIT;
CblacsBcast( ConTxt, scope, m, n, A, lda, -1, -1, MPI_INT );
}
void
Cigebr2d(int ConTxt, char *scope, char *top, int m, int n, int *A, int lda, int rsrc, int csrc) {
CBLACS_INIT;
CblacsBcast( ConTxt, scope, m, n, A, lda, rsrc, csrc, MPI_INT );
}
| 29.183727 | 122 | 0.616737 |
c189dec44ed642b239aeccdd04dff723ff123eaa | 304 | h | C | TMTTabBar/Styles/TMTTabBarStyle.h | TobiasMende/TMTTabBar | 172b6158a1cda4a11ade12fbae8d0a71b48d4d78 | [
"MIT"
] | 9 | 2015-12-24T10:54:07.000Z | 2020-07-06T08:57:10.000Z | TMTTabBar/Styles/TMTTabBarStyle.h | TobiasMende/TMTTabBar | 172b6158a1cda4a11ade12fbae8d0a71b48d4d78 | [
"MIT"
] | 10 | 2015-11-08T09:50:16.000Z | 2015-11-10T07:10:37.000Z | TMTTabBar/Styles/TMTTabBarStyle.h | TobiasMende/TMTTabBar | 172b6158a1cda4a11ade12fbae8d0a71b48d4d78 | [
"MIT"
] | null | null | null | //
// Created by Tobias Mende on 27.10.15.
// Copyright (c) 2015 Tobias Mende. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface TMTTabBarStyle : NSObject
@property NSColor* backgroundColor;
@property CGFloat addButtonSpacing;
@property BOOL shouldShowAddButton;
- (instancetype)init;
@end | 17.882353 | 56 | 0.753289 |
1e8324e49b64dc746c11e06330c085c5b5aa4260 | 24,402 | h | C | Validation/pyFrame3DD-master/gcc-master/gcc/common/config/i386/cpuinfo.h | djamal2727/Main-Bearing-Analytical-Model | 2f00c2219c71be0175c6f4f8f1d4cca231d97096 | [
"Apache-2.0"
] | null | null | null | Validation/pyFrame3DD-master/gcc-master/gcc/common/config/i386/cpuinfo.h | djamal2727/Main-Bearing-Analytical-Model | 2f00c2219c71be0175c6f4f8f1d4cca231d97096 | [
"Apache-2.0"
] | null | null | null | Validation/pyFrame3DD-master/gcc-master/gcc/common/config/i386/cpuinfo.h | djamal2727/Main-Bearing-Analytical-Model | 2f00c2219c71be0175c6f4f8f1d4cca231d97096 | [
"Apache-2.0"
] | null | null | null | /* Get CPU type and Features for x86 processors.
Copyright (C) 2012-2020 Free Software Foundation, Inc.
Contributed by Sriraman Tallam (tmsriram@google.com)
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
struct __processor_model
{
unsigned int __cpu_vendor;
unsigned int __cpu_type;
unsigned int __cpu_subtype;
/* The first 32 features are stored as bitmasks in __cpu_features.
The rest of features are stored as bitmasks in a separate array
of unsigned int. */
unsigned int __cpu_features[1];
};
struct __processor_model2
{
unsigned int __cpu_family;
unsigned int __cpu_model;
unsigned int __cpu_max_level;
unsigned int __cpu_ext_level;
};
#ifndef CHECK___builtin_cpu_is
# define CHECK___builtin_cpu_is(cpu)
#endif
/* Return non-zero if the processor has feature F. */
static inline int
has_cpu_feature (struct __processor_model *cpu_model,
unsigned int *cpu_features2,
enum processor_features f)
{
unsigned int i;
if (f < 32)
{
/* The first 32 features. */
return cpu_model->__cpu_features[0] & (1U << (f & 31));
}
/* The rest of features. cpu_features2[i] contains features from
(32 + i * 32) to (31 + 32 + i * 32), inclusively. */
for (i = 0; i < SIZE_OF_CPU_FEATURES; i++)
if (f < (32 + 32 + i * 32))
return cpu_features2[i] & (1U << ((f - (32 + i * 32)) & 31));
gcc_unreachable ();
}
static inline void
set_cpu_feature (struct __processor_model *cpu_model,
unsigned int *cpu_features2,
enum processor_features f)
{
unsigned int i;
if (f < 32)
{
/* The first 32 features. */
cpu_model->__cpu_features[0] |= (1U << (f & 31));
return;
}
/* The rest of features. cpu_features2[i] contains features from
(32 + i * 32) to (31 + 32 + i * 32), inclusively. */
for (i = 0; i < SIZE_OF_CPU_FEATURES; i++)
if (f < (32 + 32 + i * 32))
{
cpu_features2[i] |= (1U << ((f - (32 + i * 32)) & 31));
return;
}
gcc_unreachable ();
}
/* Get the specific type of AMD CPU and return AMD CPU name. Return
NULL for unknown AMD CPU. */
static inline const char *
get_amd_cpu (struct __processor_model *cpu_model,
struct __processor_model2 *cpu_model2,
unsigned int *cpu_features2)
{
const char *cpu = NULL;
unsigned int family = cpu_model2->__cpu_family;
unsigned int model = cpu_model2->__cpu_model;
switch (family)
{
case 0x10:
/* AMD Family 10h. */
cpu = "amdfam10";
cpu_model->__cpu_type = AMDFAM10H;
switch (model)
{
case 0x2:
/* Barcelona. */
CHECK___builtin_cpu_is ("amdfam10h");
CHECK___builtin_cpu_is ("barcelona");
cpu_model->__cpu_subtype = AMDFAM10H_BARCELONA;
break;
case 0x4:
/* Shanghai. */
CHECK___builtin_cpu_is ("amdfam10h");
CHECK___builtin_cpu_is ("shanghai");
cpu_model->__cpu_subtype = AMDFAM10H_SHANGHAI;
break;
case 0x8:
/* Istanbul. */
CHECK___builtin_cpu_is ("amdfam10h");
CHECK___builtin_cpu_is ("istanbul");
cpu_model->__cpu_subtype = AMDFAM10H_ISTANBUL;
break;
default:
break;
}
break;
case 0x14:
/* AMD Family 14h "btver1". */
cpu = "btver1";
CHECK___builtin_cpu_is ("btver1");
cpu_model->__cpu_type = AMD_BTVER1;
break;
case 0x15:
/* AMD Family 15h "Bulldozer". */
cpu_model->__cpu_type = AMDFAM15H;
if (model == 0x2)
{
/* Bulldozer version 2 "Piledriver" */
cpu = "bdver2";
CHECK___builtin_cpu_is ("bdver2");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER2;
}
else if (model <= 0xf)
{
/* Bulldozer version 1. */
cpu = "bdver1";
CHECK___builtin_cpu_is ("bdver1");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER1;
}
else if (model <= 0x2f)
{
/* Bulldozer version 2 "Piledriver" */
cpu = "bdver2";
CHECK___builtin_cpu_is ("bdver2");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER2;
}
else if (model <= 0x4f)
{
/* Bulldozer version 3 "Steamroller" */
cpu = "bdver3";
CHECK___builtin_cpu_is ("bdver3");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER3;
}
else if (model <= 0x7f)
{
/* Bulldozer version 4 "Excavator" */
cpu = "bdver4";
CHECK___builtin_cpu_is ("bdver4");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER4;
}
else if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_AVX2))
{
cpu = "bdver4";
CHECK___builtin_cpu_is ("bdver4");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER4;
}
else if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_XSAVEOPT))
{
cpu = "bdver3";
CHECK___builtin_cpu_is ("bdver3");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER3;
}
else if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_BMI))
{
cpu = "bdver2";
CHECK___builtin_cpu_is ("bdver2");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER2;
}
else if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_XOP))
{
cpu = "bdver1";
CHECK___builtin_cpu_is ("bdver1");
cpu_model->__cpu_subtype = AMDFAM15H_BDVER1;
}
break;
case 0x16:
/* AMD Family 16h "btver2" */
cpu = "btver2";
CHECK___builtin_cpu_is ("btver2");
cpu_model->__cpu_type = AMD_BTVER2;
break;
case 0x17:
cpu_model->__cpu_type = AMDFAM17H;
if (model <= 0x1f)
{
/* AMD family 17h version 1. */
cpu = "znver1";
CHECK___builtin_cpu_is ("znver1");
cpu_model->__cpu_subtype = AMDFAM17H_ZNVER1;
}
else if (model >= 0x30)
{
cpu = "znver2";
CHECK___builtin_cpu_is ("znver2");
cpu_model->__cpu_subtype = AMDFAM17H_ZNVER2;
}
else if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_CLWB))
{
cpu = "znver2";
CHECK___builtin_cpu_is ("znver2");
cpu_model->__cpu_subtype = AMDFAM17H_ZNVER2;
}
else if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_CLZERO))
{
cpu = "znver1";
CHECK___builtin_cpu_is ("znver1");
cpu_model->__cpu_subtype = AMDFAM17H_ZNVER1;
}
break;
default:
break;
}
return cpu;
}
/* Get the specific type of Intel CPU and return Intel CPU name. Return
NULL for unknown Intel CPU. */
static inline const char *
get_intel_cpu (struct __processor_model *cpu_model,
struct __processor_model2 *cpu_model2,
unsigned int *cpu_features2)
{
const char *cpu = NULL;
/* Parse family and model only for model 6. */
if (cpu_model2->__cpu_family != 0x6)
return cpu;
switch (cpu_model2->__cpu_model)
{
case 0x1c:
case 0x26:
/* Bonnell. */
cpu = "bonnell";
CHECK___builtin_cpu_is ("atom");
cpu_model->__cpu_type = INTEL_BONNELL;
break;
case 0x37:
case 0x4a:
case 0x4d:
case 0x5d:
/* Silvermont. */
case 0x4c:
case 0x5a:
case 0x75:
/* Airmont. */
cpu = "silvermont";
CHECK___builtin_cpu_is ("silvermont");
cpu_model->__cpu_type = INTEL_SILVERMONT;
break;
case 0x5c:
case 0x5f:
/* Goldmont. */
cpu = "goldmont";
CHECK___builtin_cpu_is ("goldmont");
cpu_model->__cpu_type = INTEL_GOLDMONT;
break;
case 0x7a:
/* Goldmont Plus. */
cpu = "goldmont-plus";
CHECK___builtin_cpu_is ("goldmont-plus");
cpu_model->__cpu_type = INTEL_GOLDMONT_PLUS;
break;
case 0x86:
case 0x96:
case 0x9c:
/* Tremont. */
cpu = "tremont";
CHECK___builtin_cpu_is ("tremont");
cpu_model->__cpu_type = INTEL_TREMONT;
break;
case 0x57:
/* Knights Landing. */
cpu = "knl";
CHECK___builtin_cpu_is ("knl");
cpu_model->__cpu_type = INTEL_KNL;
break;
case 0x85:
/* Knights Mill. */
cpu = "knm";
CHECK___builtin_cpu_is ("knm");
cpu_model->__cpu_type = INTEL_KNM;
break;
case 0x1a:
case 0x1e:
case 0x1f:
case 0x2e:
/* Nehalem. */
cpu = "nehalem";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("nehalem");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_NEHALEM;
break;
case 0x25:
case 0x2c:
case 0x2f:
/* Westmere. */
cpu = "westmere";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("westmere");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_WESTMERE;
break;
case 0x2a:
case 0x2d:
/* Sandy Bridge. */
cpu = "sandybridge";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("sandybridge");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_SANDYBRIDGE;
break;
case 0x3a:
case 0x3e:
/* Ivy Bridge. */
cpu = "ivybridge";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("ivybridge");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_IVYBRIDGE;
break;
case 0x3c:
case 0x3f:
case 0x45:
case 0x46:
/* Haswell. */
cpu = "haswell";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("haswell");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_HASWELL;
break;
case 0x3d:
case 0x47:
case 0x4f:
case 0x56:
/* Broadwell. */
cpu = "broadwell";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("broadwell");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_BROADWELL;
break;
case 0x4e:
case 0x5e:
/* Skylake. */
case 0x8e:
case 0x9e:
/* Kaby Lake. */
case 0xa5:
case 0xa6:
/* Comet Lake. */
case 0xa7:
/* Rocket Lake. */
cpu = "skylake";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("skylake");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_SKYLAKE;
break;
case 0x55:
CHECK___builtin_cpu_is ("corei7");
cpu_model->__cpu_type = INTEL_COREI7;
if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_AVX512BF16))
{
/* Cooper Lake. */
cpu = "cooperlake";
CHECK___builtin_cpu_is ("cooperlake");
cpu_model->__cpu_subtype = INTEL_COREI7_COOPERLAKE;
}
else if (has_cpu_feature (cpu_model, cpu_features2,
FEATURE_AVX512VNNI))
{
/* Cascade Lake. */
cpu = "cascadelake";
CHECK___builtin_cpu_is ("cascadelake");
cpu_model->__cpu_subtype = INTEL_COREI7_CASCADELAKE;
}
else
{
/* Skylake with AVX-512 support. */
cpu = "skylake-avx512";
CHECK___builtin_cpu_is ("skylake-avx512");
cpu_model->__cpu_subtype = INTEL_COREI7_SKYLAKE_AVX512;
}
break;
case 0x66:
/* Cannon Lake. */
cpu = "cannonlake";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("cannonlake");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_CANNONLAKE;
break;
case 0x6a:
case 0x6c:
/* Ice Lake server. */
cpu = "icelake-server";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("icelake-server");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_ICELAKE_SERVER;
break;
case 0x7e:
case 0x7d:
case 0x9d:
/* Ice Lake client. */
cpu = "icelake-client";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("icelake-client");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_ICELAKE_CLIENT;
break;
case 0x8c:
case 0x8d:
/* Tiger Lake. */
cpu = "tigerlake";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("tigerlake");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_TIGERLAKE;
break;
case 0x97:
/* Alder Lake. */
cpu = "alderlake";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("alderlake");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_ALDERLAKE;
break;
case 0x8f:
/* Sapphire Rapids. */
cpu = "sapphirerapids";
CHECK___builtin_cpu_is ("corei7");
CHECK___builtin_cpu_is ("sapphirerapids");
cpu_model->__cpu_type = INTEL_COREI7;
cpu_model->__cpu_subtype = INTEL_COREI7_SAPPHIRERAPIDS;
break;
case 0x17:
case 0x1d:
/* Penryn. */
case 0x0f:
/* Merom. */
cpu = "core2";
CHECK___builtin_cpu_is ("core2");
cpu_model->__cpu_type = INTEL_CORE2;
break;
default:
break;
}
return cpu;
}
/* ECX and EDX are output of CPUID at level one. */
static inline void
get_available_features (struct __processor_model *cpu_model,
struct __processor_model2 *cpu_model2,
unsigned int *cpu_features2,
unsigned int ecx, unsigned int edx)
{
unsigned int max_cpuid_level = cpu_model2->__cpu_max_level;
unsigned int eax, ebx;
unsigned int ext_level;
/* Get XCR_XFEATURE_ENABLED_MASK register with xgetbv. */
#define XCR_XFEATURE_ENABLED_MASK 0x0
#define XSTATE_FP 0x1
#define XSTATE_SSE 0x2
#define XSTATE_YMM 0x4
#define XSTATE_OPMASK 0x20
#define XSTATE_ZMM 0x40
#define XSTATE_HI_ZMM 0x80
#define XSTATE_TILECFG 0x20000
#define XSTATE_TILEDATA 0x40000
#define XCR_AVX_ENABLED_MASK \
(XSTATE_SSE | XSTATE_YMM)
#define XCR_AVX512F_ENABLED_MASK \
(XSTATE_SSE | XSTATE_YMM | XSTATE_OPMASK | XSTATE_ZMM | XSTATE_HI_ZMM)
#define XCR_AMX_ENABLED_MASK \
(XSTATE_TILECFG | XSTATE_TILEDATA)
/* Check if AVX and AVX512 are usable. */
int avx_usable = 0;
int avx512_usable = 0;
int amx_usable = 0;
if ((ecx & bit_OSXSAVE))
{
/* Check if XMM, YMM, OPMASK, upper 256 bits of ZMM0-ZMM15 and
ZMM16-ZMM31 states are supported by OSXSAVE. */
unsigned int xcrlow;
unsigned int xcrhigh;
__asm__ (".byte 0x0f, 0x01, 0xd0"
: "=a" (xcrlow), "=d" (xcrhigh)
: "c" (XCR_XFEATURE_ENABLED_MASK));
if ((xcrlow & XCR_AVX_ENABLED_MASK) == XCR_AVX_ENABLED_MASK)
{
avx_usable = 1;
avx512_usable = ((xcrlow & XCR_AVX512F_ENABLED_MASK)
== XCR_AVX512F_ENABLED_MASK);
}
amx_usable = ((xcrlow & XCR_AMX_ENABLED_MASK)
== XCR_AMX_ENABLED_MASK);
}
#define set_feature(f) \
set_cpu_feature (cpu_model, cpu_features2, f)
if (edx & bit_CMOV)
set_feature (FEATURE_CMOV);
if (edx & bit_MMX)
set_feature (FEATURE_MMX);
if (edx & bit_SSE)
set_feature (FEATURE_SSE);
if (edx & bit_SSE2)
set_feature (FEATURE_SSE2);
if (edx & bit_CMPXCHG8B)
set_feature (FEATURE_CMPXCHG8B);
if (edx & bit_FXSAVE)
set_feature (FEATURE_FXSAVE);
if (ecx & bit_POPCNT)
set_feature (FEATURE_POPCNT);
if (ecx & bit_AES)
set_feature (FEATURE_AES);
if (ecx & bit_PCLMUL)
set_feature (FEATURE_PCLMUL);
if (ecx & bit_SSE3)
set_feature (FEATURE_SSE3);
if (ecx & bit_SSSE3)
set_feature (FEATURE_SSSE3);
if (ecx & bit_SSE4_1)
set_feature (FEATURE_SSE4_1);
if (ecx & bit_SSE4_2)
set_feature (FEATURE_SSE4_2);
if (ecx & bit_OSXSAVE)
set_feature (FEATURE_OSXSAVE);
if (ecx & bit_CMPXCHG16B)
set_feature (FEATURE_CMPXCHG16B);
if (ecx & bit_MOVBE)
set_feature (FEATURE_MOVBE);
if (ecx & bit_AES)
set_feature (FEATURE_AES);
if (ecx & bit_F16C)
set_feature (FEATURE_F16C);
if (ecx & bit_RDRND)
set_feature (FEATURE_RDRND);
if (ecx & bit_XSAVE)
set_feature (FEATURE_XSAVE);
if (avx_usable)
{
if (ecx & bit_AVX)
set_feature (FEATURE_AVX);
if (ecx & bit_FMA)
set_feature (FEATURE_FMA);
}
/* Get Advanced Features at level 7 (eax = 7, ecx = 0/1). */
if (max_cpuid_level >= 7)
{
__cpuid_count (7, 0, eax, ebx, ecx, edx);
if (ebx & bit_BMI)
set_feature (FEATURE_BMI);
if (ebx & bit_SGX)
set_feature (FEATURE_SGX);
if (ebx & bit_HLE)
set_feature (FEATURE_HLE);
if (ebx & bit_RTM)
set_feature (FEATURE_RTM);
if (avx_usable)
{
if (ebx & bit_AVX2)
set_feature (FEATURE_AVX2);
if (ecx & bit_VPCLMULQDQ)
set_feature (FEATURE_VPCLMULQDQ);
}
if (ebx & bit_BMI2)
set_feature (FEATURE_BMI2);
if (ebx & bit_FSGSBASE)
set_feature (FEATURE_FSGSBASE);
if (ebx & bit_RDSEED)
set_feature (FEATURE_RDSEED);
if (ebx & bit_ADX)
set_feature (FEATURE_ADX);
if (ebx & bit_SHA)
set_feature (FEATURE_SHA);
if (ebx & bit_CLFLUSHOPT)
set_feature (FEATURE_CLFLUSHOPT);
if (ebx & bit_CLWB)
set_feature (FEATURE_CLWB);
if (ecx & bit_PREFETCHWT1)
set_feature (FEATURE_PREFETCHWT1);
/* NB: bit_OSPKE indicates that OS supports PKU. */
if (ecx & bit_OSPKE)
set_feature (FEATURE_PKU);
if (ecx & bit_RDPID)
set_feature (FEATURE_RDPID);
if (ecx & bit_VAES)
set_feature (FEATURE_VAES);
if (ecx & bit_GFNI)
set_feature (FEATURE_GFNI);
if (ecx & bit_MOVDIRI)
set_feature (FEATURE_MOVDIRI);
if (ecx & bit_MOVDIR64B)
set_feature (FEATURE_MOVDIR64B);
if (ecx & bit_ENQCMD)
set_feature (FEATURE_ENQCMD);
if (ecx & bit_CLDEMOTE)
set_feature (FEATURE_CLDEMOTE);
if (ecx & bit_WAITPKG)
set_feature (FEATURE_WAITPKG);
if (ecx & bit_SHSTK)
set_feature (FEATURE_SHSTK);
if (edx & bit_SERIALIZE)
set_feature (FEATURE_SERIALIZE);
if (edx & bit_TSXLDTRK)
set_feature (FEATURE_TSXLDTRK);
if (edx & bit_PCONFIG)
set_feature (FEATURE_PCONFIG);
if (edx & bit_IBT)
set_feature (FEATURE_IBT);
if (amx_usable)
{
if (edx & bit_AMX_TILE)
set_feature (FEATURE_AMX_TILE);
if (edx & bit_AMX_INT8)
set_feature (FEATURE_AMX_INT8);
if (edx & bit_AMX_BF16)
set_feature (FEATURE_AMX_BF16);
}
if (avx512_usable)
{
if (ebx & bit_AVX512F)
set_feature (FEATURE_AVX512F);
if (ebx & bit_AVX512VL)
set_feature (FEATURE_AVX512VL);
if (ebx & bit_AVX512BW)
set_feature (FEATURE_AVX512BW);
if (ebx & bit_AVX512DQ)
set_feature (FEATURE_AVX512DQ);
if (ebx & bit_AVX512CD)
set_feature (FEATURE_AVX512CD);
if (ebx & bit_AVX512PF)
set_feature (FEATURE_AVX512PF);
if (ebx & bit_AVX512ER)
set_feature (FEATURE_AVX512ER);
if (ebx & bit_AVX512IFMA)
set_feature (FEATURE_AVX512IFMA);
if (ecx & bit_AVX512VBMI)
set_feature (FEATURE_AVX512VBMI);
if (ecx & bit_AVX512VBMI2)
set_feature (FEATURE_AVX512VBMI2);
if (ecx & bit_AVX512VNNI)
set_feature (FEATURE_AVX512VNNI);
if (ecx & bit_AVX512BITALG)
set_feature (FEATURE_AVX512BITALG);
if (ecx & bit_AVX512VPOPCNTDQ)
set_feature (FEATURE_AVX512VPOPCNTDQ);
if (edx & bit_AVX5124VNNIW)
set_feature (FEATURE_AVX5124VNNIW);
if (edx & bit_AVX5124FMAPS)
set_feature (FEATURE_AVX5124FMAPS);
if (edx & bit_AVX512VP2INTERSECT)
set_feature (FEATURE_AVX512VP2INTERSECT);
if (edx & bit_UINTR)
set_feature (FEATURE_UINTR);
__cpuid_count (7, 1, eax, ebx, ecx, edx);
if (eax & bit_AVX512BF16)
set_feature (FEATURE_AVX512BF16);
if (eax & bit_HRESET)
set_feature (FEATURE_HRESET);
}
}
/* Get Advanced Features at level 0xd (eax = 0xd, ecx = 1). */
if (max_cpuid_level >= 0xd)
{
__cpuid_count (0xd, 1, eax, ebx, ecx, edx);
if (eax & bit_XSAVEOPT)
set_feature (FEATURE_XSAVEOPT);
if (eax & bit_XSAVEC)
set_feature (FEATURE_XSAVEC);
if (eax & bit_XSAVES)
set_feature (FEATURE_XSAVES);
}
/* Get Advanced Features at level 0x14 (eax = 0x14, ecx = 0). */
if (max_cpuid_level >= 0x14)
{
__cpuid_count (0x14, 0, eax, ebx, ecx, edx);
if (ebx & bit_PTWRITE)
set_feature (FEATURE_PTWRITE);
}
/* Check cpuid level of extended features. */
__cpuid (0x80000000, ext_level, ebx, ecx, edx);
cpu_model2->__cpu_ext_level = ext_level;
if (ext_level >= 0x80000001)
{
__cpuid (0x80000001, eax, ebx, ecx, edx);
if (ecx & bit_SSE4a)
set_feature (FEATURE_SSE4_A);
if (ecx & bit_LAHF_LM)
set_feature (FEATURE_LAHF_LM);
if (ecx & bit_ABM)
set_feature (FEATURE_ABM);
if (ecx & bit_LWP)
set_feature (FEATURE_LWP);
if (ecx & bit_TBM)
set_feature (FEATURE_TBM);
if (ecx & bit_LZCNT)
set_feature (FEATURE_LZCNT);
if (ecx & bit_PRFCHW)
set_feature (FEATURE_PRFCHW);
if (ecx & bit_MWAITX)
set_feature (FEATURE_MWAITX);
if (edx & bit_LM)
set_feature (FEATURE_LM);
if (edx & bit_3DNOWP)
set_feature (FEATURE_3DNOWP);
if (edx & bit_3DNOW)
set_feature (FEATURE_3DNOW);
if (avx_usable)
{
if (ecx & bit_FMA4)
set_feature (FEATURE_FMA4);
if (ecx & bit_XOP)
set_feature (FEATURE_XOP);
}
}
if (ext_level >= 0x80000008)
{
__cpuid (0x80000008, eax, ebx, ecx, edx);
if (ebx & bit_CLZERO)
set_feature (FEATURE_CLZERO);
if (ebx & bit_WBNOINVD)
set_feature (FEATURE_WBNOINVD);
}
#undef set_feature
}
static inline int
cpu_indicator_init (struct __processor_model *cpu_model,
struct __processor_model2 *cpu_model2,
unsigned int *cpu_features2)
{
unsigned int eax, ebx, ecx, edx;
int max_level;
unsigned int vendor;
unsigned int model, family;
unsigned int extended_model, extended_family;
/* This function needs to run just once. */
if (cpu_model->__cpu_vendor)
return 0;
/* Assume cpuid insn present. Run in level 0 to get vendor id. */
if (!__get_cpuid (0, &eax, &ebx, &ecx, &edx))
{
cpu_model->__cpu_vendor = VENDOR_OTHER;
return -1;
}
vendor = ebx;
max_level = eax;
if (max_level < 1)
{
cpu_model->__cpu_vendor = VENDOR_OTHER;
return -1;
}
if (!__get_cpuid (1, &eax, &ebx, &ecx, &edx))
{
cpu_model->__cpu_vendor = VENDOR_OTHER;
return -1;
}
cpu_model2->__cpu_max_level = max_level;
model = (eax >> 4) & 0x0f;
family = (eax >> 8) & 0x0f;
extended_model = (eax >> 12) & 0xf0;
extended_family = (eax >> 20) & 0xff;
if (vendor == signature_INTEL_ebx)
{
/* Adjust model and family for Intel CPUS. */
if (family == 0x0f)
{
family += extended_family;
model += extended_model;
}
else if (family == 0x06)
model += extended_model;
cpu_model2->__cpu_family = family;
cpu_model2->__cpu_model = model;
/* Find available features. */
get_available_features (cpu_model, cpu_model2, cpu_features2,
ecx, edx);
/* Get CPU type. */
get_intel_cpu (cpu_model, cpu_model2, cpu_features2);
cpu_model->__cpu_vendor = VENDOR_INTEL;
}
else if (vendor == signature_AMD_ebx)
{
/* Adjust model and family for AMD CPUS. */
if (family == 0x0f)
{
family += extended_family;
model += extended_model;
}
cpu_model2->__cpu_family = family;
cpu_model2->__cpu_model = model;
/* Find available features. */
get_available_features (cpu_model, cpu_model2, cpu_features2,
ecx, edx);
/* Get CPU type. */
get_amd_cpu (cpu_model, cpu_model2, cpu_features2);
cpu_model->__cpu_vendor = VENDOR_AMD;
}
else if (vendor == signature_CENTAUR_ebx)
cpu_model->__cpu_vendor = VENDOR_CENTAUR;
else if (vendor == signature_CYRIX_ebx)
cpu_model->__cpu_vendor = VENDOR_CYRIX;
else if (vendor == signature_NSC_ebx)
cpu_model->__cpu_vendor = VENDOR_NSC;
else
cpu_model->__cpu_vendor = VENDOR_OTHER;
gcc_assert (cpu_model->__cpu_vendor < VENDOR_MAX);
gcc_assert (cpu_model->__cpu_type < CPU_TYPE_MAX);
gcc_assert (cpu_model->__cpu_subtype < CPU_SUBTYPE_MAX);
return 0;
}
| 27.417978 | 72 | 0.655233 |
e7a831fcfb9df118e5fa94919f74b1ca1dfcb328 | 1,974 | c | C | chapter08/8.31.c | kaiiak/APUE | 5c0606a031bdf290a266c7192f70d3683fce4635 | [
"MIT"
] | 3 | 2017-06-14T05:21:36.000Z | 2018-02-10T01:58:41.000Z | chapter08/8.31.c | kaiiak/APUE | 5c0606a031bdf290a266c7192f70d3683fce4635 | [
"MIT"
] | null | null | null | chapter08/8.31.c | kaiiak/APUE | 5c0606a031bdf290a266c7192f70d3683fce4635 | [
"MIT"
] | null | null | null | #include "apue.h"
#include <sys/times.h>
static void pr_times(clock_t, struct tms *, struct tms *);
static void do_cmd(char *);
void
pr_exit(int status)
{
if(WIFEXITED(status))
printf("normal termination, exit status = %d\n",
WEXITSTATUS(status));
else if(WIFSIGNALED(status))
printf("abnormal termination, signal number = %d%s\n",
WTERMSIG(status),
#ifdef WCOREDUMP
WCOREDUMP(status) ? " (core file generated)" : "");
#else
"");
#endif
else if(WIFSTOPPED(status))
printf("child stopped, signal number = %d\n",
WSTOPSIG(status));
}
int
main(int argc, char *argv[])
{
int i;
setbuf(stdout, NULL);
for (i = 1; i < argc; i++)
do_cmd(argv[i]); /* once for each command-line arg */
exit(0);
}
static void
do_cmd(char *cmd) /* execute and time the "cmd" */
{
struct tms tmsstart, tmsend;
clock_t start, end;
int status;
printf("\ncommand: %s\n", cmd);
if ((start = times(&tmsstart)) == -1) /* starting values */
err_sys("times error");
if ((status = system(cmd)) < 0) /* execute command */
err_sys("system() error");
if ((end = times(&tmsend)) == -1) /* ending values */
err_sys("times error");
pr_times(end-start, &tmsstart, &tmsend);
pr_exit(status);
}
static void
pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend)
{
static long clktck = 0;
if (clktck == 0) /* fetch clock ticks per second first time */
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
err_sys("sysconf error");
printf(" real: %7.2f\n", real / (double) clktck);
printf(" user: %7.2f\n",
(tmsend->tms_utime - tmsstart->tms_utime) / (double) clktck);
printf(" sys: %7.2f\n",
(tmsend->tms_stime - tmsstart->tms_stime) / (double) clktck);
printf(" child user: %7.2f\n",
(tmsend->tms_cutime - tmsstart->tms_cutime) / (double) clktck);
printf(" child sys: %7.2f\n",
(tmsend->tms_cstime - tmsstart->tms_cstime) / (double) clktck);
}
| 30.369231 | 67 | 0.614995 |
1b33f973f35ffb451d4fa44971eeb6b8c730b3bd | 5,345 | h | C | src/atlas/domain/Domain.h | wdeconinck/atlas | 8949d2b362b9b5431023a967bcf4ca84f6b8ce05 | [
"Apache-2.0"
] | 3 | 2021-08-17T03:08:45.000Z | 2021-09-09T09:22:54.000Z | src/atlas/domain/Domain.h | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | 62 | 2020-10-21T15:27:38.000Z | 2022-03-28T12:42:43.000Z | src/atlas/domain/Domain.h | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | 1 | 2021-03-10T19:19:08.000Z | 2021-03-10T19:19:08.000Z | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#pragma once
#include <array>
#include <string>
#include "atlas/library/config.h"
#include "atlas/util/ObjectHandle.h"
//---------------------------------------------------------------------------------------------------------------------
// Forward declarations
namespace eckit {
class Parametrisation;
class Hash;
} // namespace eckit
//---------------------------------------------------------------------------------------------------------------------
namespace atlas {
class PointXY;
namespace util {
class Config;
} // namespace util
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace domain {
class Domain;
class GlobalDomain;
class ZonalBandDomain;
class RectangularDomain;
class RectangularLonLatDomain;
} // namespace domain
#endif
//---------------------------------------------------------------------------------------------------------------------
class Domain : DOXYGEN_HIDE( public util::ObjectHandle<atlas::domain::Domain> ) {
public:
using Spec = util::Config;
public:
using Handle::Handle;
Domain() = default;
Domain( const eckit::Parametrisation& );
/// Type of the domain
std::string type() const;
/// Checks if the point is contained in the domain
bool contains( double x, double y ) const;
/// Checks if the point is contained in the domain
bool contains( const PointXY& p ) const;
// Specification of Domain
Spec spec() const;
/// Check if domain represents the complete globe surface
bool global() const;
/// Check if domain does not represent any area on the globe surface
bool empty() const;
/// Add domain to the given hash
void hash( eckit::Hash& ) const;
/// Check if grid includes the North pole (can only be true when units are in
/// degrees)
bool containsNorthPole() const;
/// Check if grid includes the South pole (can only be true when units are in
/// degrees)
bool containsSouthPole() const;
/// String that defines units of the domain ("degrees" or "meters")
std::string units() const;
private:
/// Output to stream
void print( std::ostream& ) const;
friend std::ostream& operator<<( std::ostream& s, const Domain& d );
};
//---------------------------------------------------------------------------------------------------------------------
class RectangularDomain : public Domain {
public:
using Interval = std::array<double, 2>;
public:
using Domain::Domain;
RectangularDomain() : Domain() {}
RectangularDomain( const Interval& x, const Interval& y, const std::string& units = "degrees" );
RectangularDomain( const Domain& );
operator bool() const { return domain_; }
/// Checks if the x-value is contained in the domain
bool contains_x( double x ) const;
/// Checks if the y-value is contained in the domain
bool contains_y( double y ) const;
bool zonal_band() const;
double xmin() const;
double xmax() const;
double ymin() const;
double ymax() const;
private:
const ::atlas::domain::RectangularDomain* domain_;
};
//---------------------------------------------------------------------------------------------------------------------
class RectangularLonLatDomain : public RectangularDomain {
public:
using RectangularDomain::RectangularDomain;
RectangularLonLatDomain( const Interval& x, const Interval& y ) : RectangularDomain( x, y, "degrees" ) {}
RectangularLonLatDomain( const double& north, const double& west, const double& south, const double& east ) :
RectangularLonLatDomain( {west, east}, {south, north} ) {}
operator bool() const { return RectangularDomain::operator bool() && units() == "degrees"; }
double west() const { return xmin(); }
double east() const { return xmax(); }
double north() const { return ymax(); }
double south() const { return ymin(); }
};
//---------------------------------------------------------------------------------------------------------------------
class ZonalBandDomain : public RectangularLonLatDomain {
public:
using Interval = std::array<double, 2>;
public:
using RectangularLonLatDomain::RectangularLonLatDomain;
ZonalBandDomain( const Interval& y, const double& west );
ZonalBandDomain( const Interval& y );
ZonalBandDomain( const Domain& );
operator bool() const { return domain_; }
private:
const ::atlas::domain::ZonalBandDomain* domain_;
};
//---------------------------------------------------------------------------------------------------------------------
class GlobalDomain : public ZonalBandDomain {
public:
GlobalDomain( const double& west );
GlobalDomain();
GlobalDomain( const Domain& );
operator bool() const { return domain_; }
private:
const ::atlas::domain::GlobalDomain* domain_;
};
//---------------------------------------------------------------------------------------------------------------------
} // namespace atlas
| 29.694444 | 119 | 0.566324 |
29cb2e1f68ffc531e0ab39e6d5ab9c1341fcb454 | 1,996 | h | C | GWToolboxdll/Windows/HotkeysWindow.h | franneck94/GWToolboxpp | 7968764b088949cf79974632a4541767e82a585c | [
"MIT"
] | 2 | 2019-03-21T19:36:58.000Z | 2020-11-19T02:06:14.000Z | GWToolboxdll/Windows/HotkeysWindow.h | BearsMan/GWToolboxpp | ab04aeb3b1fd9e53fda8245686a8c732dfc58eb1 | [
"MIT"
] | null | null | null | GWToolboxdll/Windows/HotkeysWindow.h | BearsMan/GWToolboxpp | ab04aeb3b1fd9e53fda8245686a8c732dfc58eb1 | [
"MIT"
] | null | null | null | #pragma once
#include <Logger.h>
#include <Timer.h>
#include <ToolboxWindow.h>
#include <Windows/Hotkeys.h>
// class used to keep a list of hotkeys, capture keyboard event and fire hotkeys as needed
class HotkeysWindow : public ToolboxWindow {
HotkeysWindow() {};
~HotkeysWindow() {};
public:
static HotkeysWindow& Instance() {
static HotkeysWindow instance;
return instance;
}
const char* Name() const override { return "Hotkeys"; }
const char* Icon() const override { return ICON_FA_KEYBOARD; }
void Initialize() override;
void Terminate() override;
inline bool ToggleClicker() { return clickerActive = !clickerActive; }
inline bool ToggleCoinDrop() { return dropCoinsActive = !dropCoinsActive; }
TBHotkey* current_hotkey = nullptr;
bool IsMapReady();
// Update. Will always be called every frame.
void Update(float delta) override;
// Draw user interface. Will be called every frame if the element is visible
void Draw(IDirect3DDevice9* pDevice) override;
bool WndProc(UINT Message, WPARAM wParam, LPARAM lParam) override;
void DrawSettingInternal() override;
void LoadSettings(CSimpleIni* ini) override;
void SaveSettings(CSimpleIni* ini) override;
private:
std::vector<TBHotkey*> hotkeys; // list of hotkeys
long max_id_ = 0;
bool block_hotkeys = false;
bool clickerActive = false; // clicker is active or not
bool dropCoinsActive = false; // coin dropper is active or not
bool map_change_triggered = false;
clock_t clickerTimer = 0; // timer for clicker
clock_t dropCoinsTimer = 0; // timer for coin dropper
float movementX = 0; // X coordinate of the destination of movement macro
float movementY = 0; // Y coordinate of the destination of movement macro
void MapChanged();
uint32_t map_id = 0;
uint32_t prof_id = 0;
};
| 31.1875 | 96 | 0.665331 |
29e1d03f98bfe8b8c3f9b1367b1794b3c879bde7 | 2,625 | h | C | software/atmega324p_u1/hwc_u1/src/sys.h | greenenergyprojects/rpi-hot-water-controller | 74fe24d7410fc97e39176c0ca31ebdca7afd343d | [
"MIT"
] | null | null | null | software/atmega324p_u1/hwc_u1/src/sys.h | greenenergyprojects/rpi-hot-water-controller | 74fe24d7410fc97e39176c0ca31ebdca7afd343d | [
"MIT"
] | 3 | 2022-02-13T20:55:08.000Z | 2022-02-27T10:40:57.000Z | software/atmega324p_u1/hwc_u1/src/sys.h | greenenergyprojects/rpi-hot-water-controller | 74fe24d7410fc97e39176c0ca31ebdca7afd343d | [
"MIT"
] | null | null | null | #ifndef SYS_H_
#define SYS_H_
#include <stdio.h>
#include "global.h"
#if GLOBAL_UART0_RXBUFSIZE > 255
#error "Error: GLOBAL_UART0_RXBUFSIZE value over maximum (255)"
#endif
typedef unsigned char uint8_t;
// declarations
typedef uint8_t Sys_Event;
struct Sys_Uart0_RXBuffer {
uint8_t rpos_u8;
uint8_t wpos_u8;
uint8_t buffer_u8[GLOBAL_UART0_RXBUFSIZE];
};
struct Sys_Uart0_TXBuffer {
uint8_t rpos_u8;
uint8_t wpos_u8;
uint8_t buffer_u8[GLOBAL_UART0_TXBUFSIZE];
};
struct Sys_Uart0 {
uint8_t errcnt_u8;
struct Sys_Uart0_RXBuffer rxbuf;
struct Sys_Uart0_TXBuffer txbuf;
};
struct Sys_Uart1 {
uint8_t errcnt_u8;
uint8_t fillByte;
};
struct Sys_ErrorCnt { // size word aligned !
uint16_t taskErr_u16;
};
struct Sys {
uint8_t version;
uint8_t debugLevel;
struct Sys_ErrorCnt err;
uint8_t flags;
FILE* fOutModbus;
Sys_Event eventFlag;
uint8_t adc0_u8;
struct Sys_Uart0 uart0;
struct Sys_Uart1 uart1;
};
// declaration and definations
extern struct Sys sys;
// defines
// SYS_FLAG_SREG_I must have same position as I-Bit in Status-Register!!
#define SYS_FLAG_SREG_I 0x80
#define SYS_MODBUS_STATUS_ERR7 7
#define SYS_MODBUS_STATUS_ERR6 6
#define SYS_MODBUS_STATUS_ERR5 5
#define SYS_MODBUS_STATUS_ERR_FRAME 1
#define SYS_MODBUS_STATUS_NEWFRAME 0
// functions
void sys_init (void);
void sys_main (void);
void sys_sei (void);
void sys_cli (void);
void sys_inc8BitCnt (uint8_t *count);
void sys_inc16BitCnt (uint16_t *count);
void sys_newline (void);
Sys_Event sys_setEvent (Sys_Event event);
Sys_Event sys_clearEvent (Sys_Event event);
Sys_Event sys_isEventPending (Sys_Event event);
uint8_t sys_uart0_available ();
int16_t sys_uart0_getBufferByte (uint8_t pos);
void sys_uart0_flush ();
void sys_setSSR (uint8_t index, uint8_t on);
void sys_setSSR1 (uint8_t on);
void sys_setSSR2 (uint8_t on);
void sys_setSSR3 (uint8_t on);
void sys_setSSR4 (uint8_t on);
uint8_t sys_isSw2On ();
uint8_t sys_isSensor1On ();
uint8_t sys_isSensor2On ();
void sys_setPwm4To20mA (uint8_t value);
void sys_setLedLife (uint8_t on);
void sys_setLedPwmGreen (uint8_t on);
void sys_setLedPT1000Red (uint8_t index, uint8_t on);
void sys_setLedPT1000Green (uint8_t index, uint8_t on);
void sys_setLedSensor (uint8_t index, uint8_t on);
void sys_setLedSensor1 (uint8_t on);
void sys_setLedSensor2 (uint8_t on);
void sys_toggleLifeLed ();
void sys_toggleLedPwmGreen ();
#endif // SYS_H_
| 21.694215 | 72 | 0.719619 |
49f2e23b2873a5ecc0034ae72cdb05fa9c1e623e | 1,229 | h | C | multiscale/amsiAssemblable.h | SCOREC/amsi | a9d33804e951b397b3a0ca5f07efe854536c8e0a | [
"BSD-3-Clause"
] | null | null | null | multiscale/amsiAssemblable.h | SCOREC/amsi | a9d33804e951b397b3a0ca5f07efe854536c8e0a | [
"BSD-3-Clause"
] | null | null | null | multiscale/amsiAssemblable.h | SCOREC/amsi | a9d33804e951b397b3a0ca5f07efe854536c8e0a | [
"BSD-3-Clause"
] | null | null | null | #ifndef AMSI_ASSEMBLABLE_H_
#define AMSI_ASSEMBLABLE_H_
#include <mpi.h>
namespace amsi
{
class Assemblable
{
public:
virtual void Assemble(MPI_Comm) = 0;
bool isAssembled() {return assembled;}
protected:
void unassembled() {assembled = false;}
bool assembled;
};
class Reconcilable
{
public:
virtual void Reconcile(MPI_Comm) = 0;
bool isReconciled() {return reconciled;}
protected:
void unreconciled() {reconciled = false;}
bool reconciled;
};
void Assemble(Assemblable * a, MPI_Comm cm);
/**
* Get the number of peer-to-peer sends required from rank
* t1rnk to complete reconciliation of a piece of control
* data from a scale of size t1s to a scale of size t2s.
*/
int getReconcileSendCount(int t1s, int t2s, int t1rnk);
/**
* Get an array of the foreign scale ranks required for
* completion of a reconciliation operation from rank t1rnk
* in a scale of size t1s to a scale of size t2s.
*
*/
void getReconcileSendRanks(int t1s, int t2s, int t1rnk, int * rnks);
/**
*
* todo : incorporate into test case
*/
int getNthReconcileSendRank(int t1s, int t2s, int t1rnk, int nth);
}
#endif
| 27.311111 | 71 | 0.662327 |
632ba820f3d578f34b8ae244c87f2c5c496460b0 | 5,526 | c | C | galpy/orbit/orbit_c_ext/integrateLinearOrbit.c | itsx/galpy | d7fec24568347776ad89b4d4d1fc71a3f2f8d5e1 | [
"BSD-3-Clause"
] | 1 | 2019-02-28T08:54:38.000Z | 2019-02-28T08:54:38.000Z | galpy/orbit/orbit_c_ext/integrateLinearOrbit.c | itsx/galpy | d7fec24568347776ad89b4d4d1fc71a3f2f8d5e1 | [
"BSD-3-Clause"
] | null | null | null | galpy/orbit/orbit_c_ext/integrateLinearOrbit.c | itsx/galpy | d7fec24568347776ad89b4d4d1fc71a3f2f8d5e1 | [
"BSD-3-Clause"
] | null | null | null | /*
Wrappers around the C integration code for linear Orbits
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <bovy_symplecticode.h>
#include <bovy_rk.h>
//Potentials
#include <galpy_potentials.h>
#include <integrateFullOrbit.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
//Macros to export functions in DLL on different OS
#if defined(_WIN32)
#define EXPORT __declspec(dllexport)
#elif defined(__GNUC__)
#define EXPORT __attribute__((visibility("default")))
#else
// Just do nothing?
#define EXPORT
#endif
/*
Function Declarations
*/
void evalLinearForce(double, double *, double *,
int, struct potentialArg *);
void evalLinearDeriv(double, double *, double *,
int, struct potentialArg *);
/*
Actual functions
*/
void parse_leapFuncArgs_Linear(int npot,struct potentialArg * potentialArgs,
int ** pot_type,
double ** pot_args){
int ii,jj;
init_potentialArgs(npot,potentialArgs);
for (ii=0; ii < npot; ii++){
switch ( *(*pot_type)++ ) {
default: //verticalPotential
potentialArgs->linearForce= &verticalPotentialLinearForce;
break;
case 31: // KGPotential
potentialArgs->linearForce= &KGPotentialLinearForce;
potentialArgs->nargs= 4;
break;
//////////////////////////////// WRAPPERS /////////////////////////////////////
// NOT CURRENTLY SUPPORTED
/*
case -1: //DehnenSmoothWrapperPotential
potentialArgs->linearForce= &DehnenSmoothWrapperPotentialPlanarRforce;
potentialArgs->nargs= (int) 3;
break;
case -2: //SolidBodyRotationWrapperPotential
potentialArgs->linearForce= &SolidBodyRotationWrapperPotentialPlanarRforce;
potentialArgs->nargs= (int) 3;
break;
case -4: //CorotatingRotationWrapperPotential
potentialArgs->linearForce= &CorotatingRotationWrapperPotentialPlanarRforce;
potentialArgs->nargs= (int) 5;
break;
case -5: //GaussianAmplitudeWrapperPotential
potentialArgs->linearForce= &GaussianAmplitudeWrapperPotentialPlanarRforce;
potentialArgs->nargs= (int) 3;
break;
*/
}
/*
if ( *(*pot_type-1) < 0) { // Parse wrapped potential for wrappers
potentialArgs->nwrapped= (int) *(*pot_args)++;
potentialArgs->wrappedPotentialArg= \
(struct potentialArg *) malloc ( potentialArgs->nwrapped \
* sizeof (struct potentialArg) );
parse_leapFuncArgs_Linear(potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg,
pot_type,pot_args);
}
*/
// linear from 3D: assign R location parameter as the only one, rest
// of potential as wrapped
if ( potentialArgs->linearForce == &verticalPotentialLinearForce ) {
potentialArgs->nwrapped= (int) 1;
potentialArgs->wrappedPotentialArg= \
(struct potentialArg *) malloc ( potentialArgs->nwrapped \
* sizeof (struct potentialArg) );
*(pot_type)-= 1; // Do FullOrbit processing for same potential
parse_leapFuncArgs_Full(potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg,
pot_type,pot_args);
potentialArgs->nargs= 2; // R, phi
}
potentialArgs->args= (double *) malloc( potentialArgs->nargs * sizeof(double));
for (jj=0; jj < potentialArgs->nargs; jj++){
*(potentialArgs->args)= *(*pot_args)++;
potentialArgs->args++;
}
potentialArgs->args-= potentialArgs->nargs;
potentialArgs++;
}
potentialArgs-= npot;
}
EXPORT void integrateLinearOrbit(double *yo,
int nt,
double *t,
int npot,
int * pot_type,
double * pot_args,
double dt,
double rtol,
double atol,
double *result,
int * err,
int odeint_type){
//Set up the forces, first count
int dim;
struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Linear(npot,potentialArgs,&pot_type,&pot_args);
//Integrate
void (*odeint_func)(void (*func)(double, double *, double *,
int, struct potentialArg *),
int,
double *,
int, double, double *,
int, struct potentialArg *,
double, double,
double *,int *);
void (*odeint_deriv_func)(double, double *, double *,
int,struct potentialArg *);
switch ( odeint_type ) {
case 0: //leapfrog
odeint_func= &leapfrog;
odeint_deriv_func= &evalLinearForce;
dim= 1;
break;
case 1: //RK4
odeint_func= &bovy_rk4;
odeint_deriv_func= &evalLinearDeriv;
dim= 2;
break;
case 2: //RK6
odeint_func= &bovy_rk6;
odeint_deriv_func= &evalLinearDeriv;
dim= 2;
break;
case 3: //symplec4
odeint_func= &symplec4;
odeint_deriv_func= &evalLinearForce;
dim= 1;
break;
case 4: //symplec6
odeint_func= &symplec6;
odeint_deriv_func= &evalLinearForce;
dim= 1;
break;
case 5: //DOPR54
odeint_func= &bovy_dopr54;
odeint_deriv_func= &evalLinearDeriv;
dim= 2;
break;
}
odeint_func(odeint_deriv_func,dim,yo,nt,dt,t,npot,potentialArgs,rtol,atol,
result,err);
//Free allocated memory
free_potentialArgs(npot,potentialArgs);
free(potentialArgs);
//Done!
}
void evalLinearForce(double t, double *q, double *a,
int nargs, struct potentialArg * potentialArgs){
*a= calcLinearForce(*q,t,nargs,potentialArgs);
}
void evalLinearDeriv(double t, double *q, double *a,
int nargs, struct potentialArg * potentialArgs){
*a++= *(q+1);
*a= calcLinearForce(*q,t,nargs,potentialArgs);
}
| 30.7 | 110 | 0.666486 |
5b74e0e7e418ea6be416f78086ffa379b79b62d5 | 1,105 | h | C | src/orninstalledappsmodel.h | Acidburn0zzz/harbour-storeman | beda8d3aa7b580b35200816a5494532102eff7ba | [
"MIT"
] | 1 | 2019-08-26T04:02:24.000Z | 2019-08-26T04:02:24.000Z | src/orninstalledappsmodel.h | Acidburn0zzz/harbour-storeman | beda8d3aa7b580b35200816a5494532102eff7ba | [
"MIT"
] | null | null | null | src/orninstalledappsmodel.h | Acidburn0zzz/harbour-storeman | beda8d3aa7b580b35200816a5494532102eff7ba | [
"MIT"
] | null | null | null | #ifndef ORNINSTALLEDAPPSMODEL_H
#define ORNINSTALLEDAPPSMODEL_H
#include <QAbstractListModel>
#include "orninstalledpackage.h"
class OrnInstalledAppsModel : public QAbstractListModel
{
Q_OBJECT
public:
enum Roles
{
NameRole = Qt::UserRole + 1,
TitleRole,
VersionRole,
IconRole,
SortRole,
SectionRole,
UpdateAvailableRole,
UpdateVersionRole,
IdRole
};
Q_ENUM(Roles)
explicit OrnInstalledAppsModel(QObject *parent = nullptr);
public slots:
void reset();
private slots:
void onInstalledPackages(const OrnInstalledPackageList &packages);
void onPackageInstalled(const QString &packageName);
void onPackageRemoved(const QString &packageName);
void onUpdatablePackagesChanged();
private:
bool mResetting;
OrnInstalledPackageList mData;
// QAbstractItemModel interface
public:
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QHash<int, QByteArray> roleNames() const;
};
#endif // ORNINSTALLEDAPPSMODEL_H
| 21.666667 | 70 | 0.710407 |
85a3810d7bb5a0226431e6baca23d5208f9cba2c | 823 | h | C | kernel/linux-4.13/drivers/staging/wilc1000/wilc_wfi_cfgoperations.h | ShawnZhong/SplitFS | 7e21a6fc505ff70802e5666d097326ecb97a4ae3 | [
"Apache-2.0"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | kernel/linux-4.13/drivers/staging/wilc1000/wilc_wfi_cfgoperations.h | braymill/SplitFS | 00a42bb1b51718048e4c15dde31e9d358932575e | [
"Apache-2.0"
] | 5 | 2020-04-04T09:24:09.000Z | 2020-04-19T12:33:55.000Z | kernel/linux-4.13/drivers/staging/wilc1000/wilc_wfi_cfgoperations.h | braymill/SplitFS | 00a42bb1b51718048e4c15dde31e9d358932575e | [
"Apache-2.0"
] | 30 | 2018-05-02T08:43:27.000Z | 2022-01-23T03:25:54.000Z | /*!
* @file wilc_wfi_cfgoperations.h
* @brief Definitions for the network module
* @author syounan
* @sa wilc_oswrapper.h top level OS wrapper file
* @date 31 Aug 2010
* @version 1.0
*/
#ifndef NM_WFI_CFGOPERATIONS
#define NM_WFI_CFGOPERATIONS
#include "wilc_wfi_netdevice.h"
struct wireless_dev *wilc_create_wiphy(struct net_device *net, struct device *dev);
void wilc_free_wiphy(struct net_device *net);
int wilc_deinit_host_int(struct net_device *net);
int wilc_init_host_int(struct net_device *net);
void WILC_WFI_monitor_rx(u8 *buff, u32 size);
int WILC_WFI_deinit_mon_interface(void);
struct net_device *WILC_WFI_init_mon_interface(const char *name, struct net_device *real_dev);
void wilc_mgmt_frame_register(struct wiphy *wiphy, struct wireless_dev *wdev,
u16 frame_type, bool reg);
#endif
| 34.291667 | 94 | 0.783718 |
85b46b347f91b2832ec88ed51227e56d408a67c9 | 1,676 | h | C | XADMaster/PPMd/VariantH.h | d4rkie/Simple-Comic | 3ef3b8502a7adb02b673ef63561b2e782d01bf5d | [
"MIT"
] | 1 | 2017-09-24T02:54:11.000Z | 2017-09-24T02:54:11.000Z | XADMaster/PPMd/VariantH.h | d4rkie/Simple-Comic | 3ef3b8502a7adb02b673ef63561b2e782d01bf5d | [
"MIT"
] | null | null | null | XADMaster/PPMd/VariantH.h | d4rkie/Simple-Comic | 3ef3b8502a7adb02b673ef63561b2e782d01bf5d | [
"MIT"
] | null | null | null | /*
* VariantH.h
*
* Copyright (c) 2017-present, MacPaw Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#ifndef __PPMD_VARIANT_H_H__
#define __PPMD_VARIANT_H_H__
#include "Context.h"
#include "SubAllocatorVariantH.h"
// PPMd Variant H. Used by RAR and 7-Zip.
typedef struct PPMdModelVariantH
{
PPMdCoreModel core;
PPMdSubAllocatorVariantH *alloc;
PPMdContext *MinContext,*MaxContext;
int MaxOrder,HiBitsFlag;
bool SevenZip;
SEE2Context SEE2Cont[25][16],DummySEE2Cont;
uint8_t NS2BSIndx[256],HB2Flag[256],NS2Indx[256];
uint16_t BinSumm[128][64]; // binary SEE-contexts
} PPMdModelVariantH;
void StartPPMdModelVariantH(PPMdModelVariantH *self,
PPMdReadFunction *readfunc,void *inputcontext,
PPMdSubAllocatorVariantH *alloc,int maxorder,bool sevenzip);
void RestartPPMdVariantHRangeCoder(PPMdModelVariantH *self,
PPMdReadFunction *readfunc,void *inputcontext,
bool sevenzip);
int NextPPMdVariantHByte(PPMdModelVariantH *self);
#endif
| 32.230769 | 70 | 0.778043 |
8b89b6bd2eef147454918e3d75222be83243358b | 542 | h | C | src/Hittable.h | robbiesri/ray-tracing-one-wknd-sdl | 64d1fd3b6214ec8e9c799c5df628c920e1815c62 | [
"Apache-2.0"
] | null | null | null | src/Hittable.h | robbiesri/ray-tracing-one-wknd-sdl | 64d1fd3b6214ec8e9c799c5df628c920e1815c62 | [
"Apache-2.0"
] | null | null | null | src/Hittable.h | robbiesri/ray-tracing-one-wknd-sdl | 64d1fd3b6214ec8e9c799c5df628c920e1815c62 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Ray.h"
#include "Vec3.h"
#include <memory>
class IMaterial;
struct HitRecord {
Point3 hitPoint;
Vec3 normal;
double t;
bool frontFace;
std::shared_ptr<IMaterial> matPtr;
void SetFaceNormal(const Ray& ray, const Vec3& outwardNormal) {
frontFace = Dot(ray.Direction(), outwardNormal) < 0.0;
normal = frontFace ? outwardNormal : -outwardNormal;
}
};
class Hittable {
public:
virtual bool Hit(const Ray& r, double tMin, double tMax, HitRecord& hitRecord) const = 0;
}; | 20.846154 | 92 | 0.669742 |
eb0cb49001042682cddec9066a2d1d3d292c9adc | 3,149 | h | C | ODAF.iPhoneApp/route-me/MapView/Map/RMLatLong.h | openlab/ODAF-OpenTurf | ab413a7dc913a86b40db8edf6373017fdd696fad | [
"MS-PL"
] | 1 | 2015-04-16T04:11:06.000Z | 2015-04-16T04:11:06.000Z | ODAF.iPhoneApp/route-me/MapView/Map/RMLatLong.h | openlab/ODAF-OpenTurf | ab413a7dc913a86b40db8edf6373017fdd696fad | [
"MS-PL"
] | null | null | null | ODAF.iPhoneApp/route-me/MapView/Map/RMLatLong.h | openlab/ODAF-OpenTurf | ab413a7dc913a86b40db8edf6373017fdd696fad | [
"MS-PL"
] | null | null | null | //
// RMLatLong.h
//
// Copyright (c) 2008-2009, Route-Me Contributors
// 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 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.
#ifndef _RMLATLONG_H_
#define _RMLATLONG_H_
#import <TargetConditionals.h>
#if TARGET_OS_IPHONE
#import <CoreLocation/CoreLocation.h>
#import "RMGlobalConstants.h"
/*! \struct RMSphericalTrapezium
\brief Specifies a spherical trapezium by northwest and southeast corners, each given as CLLocationCoordinate2D, similar to specifying the corners of a box.
A spherical trapezium is the surface of a sphere or ellipsoid bounded by two meridians and two parallels. Note that in almost all cases, the lengths of the northern and southern sides of the box are different.
*/
typedef struct {
CLLocationCoordinate2D northeast;
CLLocationCoordinate2D southwest;
} RMSphericalTrapezium;
#else
/* From CoreLocation by Apple inc. Copyright 2008 Apple Computer, Inc. All rights reserved. */
/*
* CLLocationDegrees
*
* Discussion:
* Type used to represent a latitude or longitude coordinate in degrees under the WGS 84 reference
* frame. The degree can be positive (North and East) or negative (South and West).
*/
typedef double CLLocationDegrees;
/*
* CLLocationCoordinate2D
*
* Discussion:
* A structure that contains a geographical coordinate.
*
* Fields:
* latitude:
* The latitude in degrees.
* longitude:
* The longitude in degrees.
*/
typedef struct {
CLLocationDegrees latitude;
CLLocationDegrees longitude;
} CLLocationCoordinate2D;
#endif
/*! \struct RMLatLong
\brief latitude/longitude of a point, in WGS-84 degrees
*/
typedef CLLocationCoordinate2D RMLatLong;
/// \bug magic numbers
static const double kRMMinLatitude = -kMaxLat;
static const double kRMMaxLatitude = kMaxLat;
static const double kRMMinLongitude = -kMaxLong;
static const double kRMMaxLongitude = kMaxLong;
#endif | 35.382022 | 210 | 0.765322 |
6ab9c6b1da853b4aa43775be30c93961e5c9097c | 27,830 | h | C | include/libnode/detail/net/socket.h | plenluno/libnode | 9dea4f2390422e70544186df3f5c032cb4a7db08 | [
"BSD-2-Clause",
"MIT"
] | 255 | 2015-01-06T15:11:26.000Z | 2022-03-30T20:52:58.000Z | include/libnode/detail/net/socket.h | plenluno/libnode | 9dea4f2390422e70544186df3f5c032cb4a7db08 | [
"BSD-2-Clause",
"MIT"
] | 2 | 2018-12-18T22:50:25.000Z | 2019-01-09T16:57:11.000Z | include/libnode/detail/net/socket.h | plenluno/libnode | 9dea4f2390422e70544186df3f5c032cb4a7db08 | [
"BSD-2-Clause",
"MIT"
] | 36 | 2015-03-28T03:23:57.000Z | 2022-01-16T12:51:30.000Z | // Copyright (c) 2012-2015 Plenluno All rights reserved.
#ifndef LIBNODE_DETAIL_NET_SOCKET_H_
#define LIBNODE_DETAIL_NET_SOCKET_H_
#include <libnode/config.h>
#include <libnode/dns.h>
#include <libnode/net.h>
#include <libnode/process.h>
#include <libnode/string_decoder.h>
#include <libnode/timer.h>
#include <libnode/uv/error.h>
#include <libnode/detail/uv/stream_common.h>
#include <libnode/detail/events/event_emitter.h>
#include <libj/json.h>
#include <libj/this.h>
#include <assert.h>
namespace libj {
namespace node {
namespace detail {
namespace http {
class Parser;
class OutgoingMessage;
} // namespace http
} // namespace detail
} // namespace node
} // namespace libj
namespace libj {
namespace node {
namespace detail {
namespace net {
class Socket : public events::EventEmitter<node::net::Socket> {
public:
LIBJ_MUTABLE_DEFS(Socket, LIBNODE_NET_SOCKET);
static Ptr create(libj::JsObject::CPtr options = libj::JsObject::null()) {
LIBJ_STATIC_SYMBOL_DEF(OPTION_HANDLE, "handle");
if (options) {
Boolean allowHalfOpen =
to<Boolean>(options->get(OPTION_ALLOW_HALF_OPEN));
uv_file fd;
if (to<uv_file>(options->get(OPTION_FD), &fd)) {
return create(fd, allowHalfOpen);
} else {
uv::Stream* handle =
to<uv::Stream*>(options->get(OPTION_HANDLE));
return create(handle, allowHalfOpen);
}
} else {
return create(static_cast<uv::Stream*>(NULL), false);
}
}
static Ptr create(uv::Stream* handle, Boolean allowHalfOpen) {
Socket* sock = new Socket();
sock->handle_ = handle;
if (allowHalfOpen) sock->setFlag(ALLOW_HALF_OPEN);
return create(sock);
}
virtual Boolean readable() const {
return hasFlag(READABLE);
}
virtual Boolean writable() const {
return hasFlag(WRITABLE);
}
virtual Boolean setEncoding(Buffer::Encoding enc) {
switch (enc) {
case Buffer::UTF8:
case Buffer::UTF16BE:
case Buffer::UTF16LE:
case Buffer::UTF32BE:
case Buffer::UTF32LE:
case Buffer::HEX:
case Buffer::NONE:
decoder_ = StringDecoder::create(enc);
return true;
default:
decoder_ = StringDecoder::null();
return false;
}
}
virtual Boolean pause() {
setFlag(PAUSED);
return handle_ && !hasFlag(CONNECTING) && !handle_->readStop();
}
virtual Boolean resume() {
unsetFlag(PAUSED);
return handle_ && !hasFlag(CONNECTING) && !handle_->readStart();
}
virtual Boolean write(
const Value& data,
Buffer::Encoding enc = Buffer::NONE) {
return write(data, enc, JsFunction::null());
}
virtual Boolean end(
const Value& data = UNDEFINED,
Buffer::Encoding enc = Buffer::NONE) {
if (hasFlag(CONNECTING) && !hasFlag(SHUTDOWN_QUEUED)) {
if (!data.isUndefined()) write(data, enc);
unsetFlag(WRITABLE);
setFlag(SHUTDOWN_QUEUED);
}
if (!hasFlag(WRITABLE)) {
return false;
} else {
unsetFlag(WRITABLE);
}
if (!data.isUndefined()) write(data, enc);
if (!hasFlag(READABLE)) {
return destroySoon();
} else {
setFlag(SHUTDOWN);
AfterShutdown::Ptr afterShutdown(new AfterShutdown(this));
int err = handle_->shutdown(afterShutdown);
if (err) {
destroy(LIBNODE_UV_ERROR(err));
return false;
}
return true;
}
}
virtual Boolean destroy() {
return destroy(Error::null());
}
virtual Boolean destroySoon() {
if (hasFlag(DESTROYED)) return false;
unsetFlag(WRITABLE);
setFlag(DESTROY_SOON);
if (pendingWriteReqs_) {
return true;
} else {
return destroy();
}
}
virtual libj::JsObject::Ptr address() {
if (handle_ && handle_->type() == UV_TCP) {
uv::Tcp* tcp = static_cast<uv::Tcp*>(handle_);
return tcp->getSockName();
} else {
return libj::JsObject::null();
}
}
virtual String::CPtr remoteAddress() {
LIBJ_STATIC_SYMBOL_DEF(symAddress, "address");
if (handle_ && handle_->type() == UV_TCP) {
uv::Tcp* tcp = static_cast<uv::Tcp*>(handle_);
return tcp->getPeerName()->getCPtr<String>(symAddress);
} else {
return String::null();
}
}
virtual Int remotePort() {
LIBJ_STATIC_SYMBOL_DEF(symPort, "port");
if (handle_ && handle_->type() == UV_TCP) {
uv::Tcp* tcp = static_cast<uv::Tcp*>(handle_);
Int port = to<Int>(tcp->getPeerName()->get(symPort), -1);
return port;
} else {
return -1;
}
}
virtual Size bytesRead() const {
return bytesRead_;
}
virtual Size bytesWritten() const {
Size bytes = bytesDispatched_;
Size len = connectBufQueue_->length();
for (Size i = 0; i < len; i++) {
bytes += connectBufQueue_->getCPtr<Buffer>(i)->length();
}
return bytes;
}
virtual Boolean connect(
Int port,
String::CPtr host = String::null(),
JsFunction::Ptr cb = JsFunction::null()) {
if (port < 0) {
return false;
} else {
connect(port, host, String::null(), String::null(), cb);
return true;
}
}
virtual Boolean connect(
String::CPtr path,
JsFunction::Ptr cb = JsFunction::null()) {
if (path) {
connect(0, String::null(), String::null(), path, cb);
return true;
} else {
return false;
}
}
virtual void setTimeout(
UInt timeout,
JsFunction::Ptr callback = JsFunction::null()) {
if (timeout) {
startTimer(timeout);
if (callback) {
once(EVENT_TIMEOUT, callback);
}
} else {
finishTimer();
if (callback) {
removeListener(EVENT_TIMEOUT, callback);
}
}
}
virtual Boolean setNoDelay(Boolean noDelay) {
if (handle_ && handle_->type() == UV_TCP) {
uv::Tcp* tcp = static_cast<uv::Tcp*>(handle_);
return !tcp->setNoDelay(noDelay);
} else {
return false;
}
}
virtual Boolean setKeepAlive(
Boolean enable = false,
UInt initialDelay = 0) {
if (handle_ && handle_->type() == UV_TCP) {
uv::Tcp* tcp = static_cast<uv::Tcp*>(handle_);
return !tcp->setKeepAlive(enable, initialDelay / 1000);
} else {
return false;
}
}
public:
Buffer::Encoding encoding() const {
return decoder_ ? decoder_->encoding() : Buffer::NONE;
}
Boolean write(
const Value& data,
JsFunction::Ptr cb) {
return write(data, Buffer::NONE, cb);
}
Boolean write(
const Value& data,
Buffer::Encoding enc,
JsFunction::Ptr cb) {
Buffer::CPtr buf;
if (data.is<String>()) {
String::CPtr str = toCPtr<String>(data);
if (enc == Buffer::NONE) enc = Buffer::UTF8;
buf = Buffer::create(str, enc);
} else if (data.is<StringBuilder>()) {
StringBuilder::CPtr sb = toCPtr<StringBuilder>(data);
if (enc == Buffer::NONE) enc = Buffer::UTF8;
buf = Buffer::create(sb, enc);
} else {
buf = toCPtr<Buffer>(data);
}
if (!buf) return false;
if (hasFlag(CONNECTING)) {
connectQueueSize_ += buf->length();
if (!connectBufQueue_) {
assert(!connectCbQueue_);
connectBufQueue_ = JsArray::create();
connectCbQueue_ = JsArray::create();
}
connectBufQueue_->push(buf);
connectCbQueue_->push(cb);
return false;
}
return writeBuffer(buf, cb);
}
Boolean destroy(Error::CPtr err) {
return destroy(err, JsFunction::null());
}
Boolean connect(
libj::JsObject::CPtr options,
JsFunction::Ptr cb = JsFunction::null()) {
if (!options) return false;
Int port = -1;
const Value& vPort = options->get(node::net::OPTION_PORT);
if (!vPort.isUndefined()) {
String::CPtr sPort = String::valueOf(vPort);
if (sPort) {
Long lPort = to<Long>(json::parse(sPort), -1);
port = static_cast<Int>(lPort);
}
}
String::CPtr path =
options->getCPtr<String>(node::net::OPTION_PATH);
String::CPtr host =
options->getCPtr<String>(node::net::OPTION_HOST);
String::CPtr localAddress =
options->getCPtr<String>(node::net::OPTION_LOCAL_ADDRESS);
if (path) {
return connect(path, cb);
} else if (port >= 0) {
connect(port, host, localAddress, String::null(), cb);
return true;
} else {
return false;
}
}
JsFunction::Ptr setOnData(JsFunction::Ptr onData) {
JsFunction::Ptr previous = onData_;
onData_ = onData;
return previous;
}
JsFunction::Ptr setOnEnd(JsFunction::Ptr onEnd) {
JsFunction::Ptr previous = onEnd_;
onEnd_ = onEnd;
return previous;
}
JsFunction::Ptr setOnDrain(JsFunction::Ptr onDrain) {
if (onDrain_) {
removeListener(EVENT_DRAIN, onDrain_);
}
if (onDrain) {
addListener(EVENT_DRAIN, onDrain);
}
JsFunction::Ptr previous = onDrain_;
onDrain_ = onDrain;
return previous;
}
JsFunction::Ptr setOnClose(JsFunction::Ptr onClose) {
if (onClose_) {
removeListener(EVENT_CLOSE, onClose_);
}
if (onClose) {
addListener(EVENT_CLOSE, onClose);
}
JsFunction::Ptr previous = onClose_;
onClose_ = onClose;
return previous;
}
http::Parser* parser() const {
return parser_;
}
void setParser(http::Parser* parser) {
parser_ = parser;
}
http::OutgoingMessage* httpMessage() const {
return httpMessage_;
}
void setHttpMessage(http::OutgoingMessage* msg) {
httpMessage_ = msg;
}
void active() {
if (hasTimer()) {
finishTimer();
startTimer(timeout_);
}
}
void ref() {
if (handle_) handle_->ref();
}
void unref() {
if (handle_) handle_->unref();
}
private:
static Ptr create(int fd, Boolean allowHalfOpen = false) {
uv::Pipe* pipe = new uv::Pipe();
pipe->open(fd);
Socket* sock = new Socket();
sock->handle_ = pipe;
sock->setFlag(READABLE);
sock->setFlag(WRITABLE);
if (allowHalfOpen) sock->setFlag(ALLOW_HALF_OPEN);
return create(sock);
}
static Ptr create(Socket* self) {
LIBJ_STATIC_SYMBOL_DEF(EVENT_DESTROY, "destroy");
initSocketHandle(self);
Ptr socket(self);
JsFunction::Ptr onDestroy(new OnDestroy(socket));
socket->on(EVENT_DESTROY, onDestroy);
return socket;
}
static void initSocketHandle(Socket* self) {
self->flags_ = 0;
self->pendingWriteReqs_ = 0;
self->connectQueueSize_ = 0;
self->bytesRead_ = 0;
self->bytesDispatched_ = 0;
uv::Stream* handle = self->handle_;
if (handle) {
OnRead::Ptr onRead(new OnRead(self, handle));
handle->setOnRead(onRead);
handle->setOwner(self);
}
}
static void connect(
Socket* self,
uv::Pipe* handle,
String::CPtr path) {
assert(self->hasFlag(CONNECTING));
AfterConnect::Ptr afterConnect(new AfterConnect(self));
handle->connect(path, afterConnect);
}
static void connect(
Socket* self,
uv::Tcp* handle,
String::CPtr address,
Int port,
Int addressType,
String::CPtr localAddress = String::null()) {
assert(self->hasFlag(CONNECTING));
if (localAddress) {
int err;
if (addressType == 6) {
err = handle->bind6(localAddress);
} else {
err = handle->bind(localAddress);
}
if (err) {
self->destroy(LIBNODE_UV_ERROR(err));
return;
}
}
int err;
AfterConnect::Ptr afterConnect(new AfterConnect(self));
if (addressType == 6) {
err = handle->connect6(address, port, afterConnect);
} else { // addressType == 4
err = handle->connect(address, port, afterConnect);
}
if (err) {
self->destroy(LIBNODE_UV_ERROR(err));
}
}
void connect(
Int port,
String::CPtr host,
String::CPtr localAddress,
String::CPtr path,
JsFunction::Ptr cb) {
LIBJ_STATIC_SYMBOL_DEF(symLocalhost4, "127.0.0.1");
Boolean pipe = !!path;
if (hasFlag(DESTROYED) || !handle_) {
handle_ = pipe
? reinterpret_cast<uv::Stream*>(new uv::Pipe())
: reinterpret_cast<uv::Stream*>(new uv::Tcp());
initSocketHandle(this);
}
if (cb) on(EVENT_CONNECT, cb);
active();
setFlag(CONNECTING);
setFlag(WRITABLE);
if (pipe) {
uv::Pipe* pipe = reinterpret_cast<uv::Pipe*>(handle_);
connect(this, pipe, path);
} else {
uv::Tcp* tcp = reinterpret_cast<uv::Tcp*>(handle_);
if (!host) {
connect(this, tcp, symLocalhost4, port, 4);
} else {
AfterLookup::Ptr afterLookup(
new AfterLookup(
LIBJ_THIS_PTR(Socket), tcp, port, localAddress));
dns::lookup(host, afterLookup);
}
}
}
void connectQueueCleanUp() {
unsetFlag(CONNECTING);
connectQueueSize_ = 0;
connectBufQueue_ = JsArray::null();
connectCbQueue_ = JsArray::null();
}
void fireErrorCallbacks(Error::CPtr err, JsFunction::Ptr cb) {
if (cb) invoke(cb, err);
if (err && !hasFlag(ERROR_EMITTED)) {
EmitError::Ptr emitErr(new EmitError(this, err));
process::nextTick(emitErr);
setFlag(ERROR_EMITTED);
}
}
Boolean destroy(Error::CPtr err, JsFunction::Ptr cb) {
if (hasFlag(DESTROYED)) {
#ifdef LIBNODE_REMOVE_LISTENER
// OnDestroy has already called removeAllListeners
// check the return value 'false' instead of calling:
#else
fireErrorCallbacks(err, cb);
#endif
return false;
}
connectQueueCleanUp();
unsetFlag(READABLE);
unsetFlag(WRITABLE);
finishTimer();
if (handle_) {
handle_->close();
handle_->setOnRead(JsFunction::null());
handle_ = NULL;
}
fireErrorCallbacks(err, cb);
EmitClose::Ptr emitClose(new EmitClose(this, err));
process::nextTick(emitClose);
setFlag(DESTROYED);
// this.server has already registered a 'close' listener
// which will do the following:
// if (this.server) {
// this.server._connections--;
// if (this.server._emitCloseIfDrained) {
// this.server._emitCloseIfDrained();
// }
// }
return true;
}
Boolean writeBuffer(Buffer::CPtr buf, JsFunction::Ptr cb) {
active();
if (!handle_) {
destroy(Error::create(Error::ILLEGAL_STATE), cb);
return false;
}
AfterWrite::Ptr afterWrite(new AfterWrite(this, cb));
int err = handle_->writeBuffer(buf, afterWrite, cb);
if (err) {
destroy(LIBNODE_UV_ERROR(err), cb);
return false;
}
pendingWriteReqs_++;
bytesDispatched_ += buf->length();
return true;
}
Boolean hasTimer() {
return !timer_.isUndefined();
}
void startTimer(Int timeout) {
if (hasTimer()) finishTimer();
JsFunction::Ptr emitTimeout(new EmitTimeout(this));
timer_ = node::setTimeout(emitTimeout, timeout);
timeout_ = timeout;
}
void finishTimer() {
clearTimeout(timer_);
timer_ = UNDEFINED;
}
private:
class OnRead : LIBJ_JS_FUNCTION(OnRead)
public:
OnRead(
Socket* sock,
uv::Stream* handle)
: self_(sock)
, handle_(handle) {}
virtual Value operator()(JsArray::Ptr args) {
assert(self_->handle_ == handle_);
self_->active();
ssize_t nread = to<ssize_t>(args->get(0));
if (!nread) return Status::OK;
if (nread < 0) {
if (nread == node::uv::Error::_EOF) {
self_->unsetFlag(READABLE);
assert(!self_->hasFlag(GOT_EOF));
self_->setFlag(GOT_EOF);
if (!self_->hasFlag(WRITABLE)) self_->destroy();
if (!self_->hasFlag(ALLOW_HALF_OPEN)) self_->end();
// if (self_->decoder_) {
// String::CPtr ret = self_->decoder_->end();
// if (ret) self_->emit(EVENT_DATA, ret);
// }
self_->emit(EVENT_END);
if (self_->onEnd_) (*self_->onEnd_)();
} else {
self_->destroy(LIBNODE_UV_ERROR(nread));
}
return nread;
}
Buffer::CPtr buffer = args->getCPtr<Buffer>(1);
assert(nread > 0);
assert(buffer);
if (self_->decoder_) {
String::CPtr str = self_->decoder_->write(buffer);
if (str && str->length()) {
self_->emit(EVENT_DATA, str);
}
} else {
self_->emit(EVENT_DATA, buffer);
}
self_->bytesRead_ += buffer->length();
if (self_->onData_) (*self_->onData_)(args);
return Status::OK;
}
private:
Socket* self_;
uv::Stream* handle_;
};
class AfterShutdown : LIBJ_JS_FUNCTION(AfterShutdown)
public:
AfterShutdown(Socket* self) : self_(self) {}
virtual Value operator()(JsArray::Ptr args) {
assert(self_->hasFlag(SHUTDOWN));
assert(!self_->hasFlag(WRITABLE));
if (self_->hasFlag(DESTROYED)) {
return Status::OK;
} else if (self_->hasFlag(GOT_EOF) || !self_->hasFlag(READABLE)) {
self_->destroy();
}
return Status::OK;
}
private:
Socket* self_;
};
class AfterWrite : LIBJ_JS_FUNCTION(AfterWrite)
public:
AfterWrite(
Socket* sock,
JsFunction::Ptr cb)
: self_(sock)
, cb_(cb) {}
virtual Value operator()(JsArray::Ptr args) {
if (self_->hasFlag(DESTROYED)) {
return Error::ILLEGAL_STATE;
}
assert(args->get(0).is<int>());
int status = to<int>(args->get(0));
if (status) {
self_->destroy(LIBNODE_UV_ERROR(status), cb_);
return status;
}
self_->active();
self_->pendingWriteReqs_--;
if (self_->pendingWriteReqs_ == 0) {
self_->emit(EVENT_DRAIN);
}
if (cb_) (*cb_)();
if (self_->pendingWriteReqs_ == 0 &&
self_->hasFlag(DESTROY_SOON)) {
self_->destroy();
}
return Status::OK;
}
private:
Socket* self_;
JsFunction::Ptr cb_;
};
class AfterConnect : LIBJ_JS_FUNCTION(AfterConnect)
public:
AfterConnect(Socket* sock) : self_(sock) {}
virtual Value operator()(JsArray::Ptr args) {
if (self_->hasFlag(DESTROYED)) return Status::OK;
assert(self_->hasFlag(CONNECTING));
self_->unsetFlag(CONNECTING);
assert(args->get(0).is<int>());
assert(args->get(3).is<Boolean>());
assert(args->get(4).is<Boolean>());
int status = to<int>(args->get(0));
Boolean readable = to<Boolean>(args->get(3));
Boolean writable = to<Boolean>(args->get(4));
if (status) {
self_->connectQueueCleanUp();
self_->destroy(LIBNODE_UV_ERROR(status));
return status;
}
if (readable) {
self_->setFlag(READABLE);
} else {
self_->unsetFlag(READABLE);
}
if (writable) {
self_->setFlag(WRITABLE);
} else {
self_->unsetFlag(WRITABLE);
}
self_->active();
if (readable && !self_->hasFlag(PAUSED)) {
self_->handle_->readStart();
}
if (self_->connectQueueSize_) {
JsArray::Ptr connectBufQueue = self_->connectBufQueue_;
JsArray::Ptr connectCbQueue = self_->connectCbQueue_;
Size len = connectBufQueue->length();
assert(connectCbQueue->length() == len);
for (Size i = 0; i < len; i++) {
JsFunction::Ptr cb =
connectCbQueue->getPtr<JsFunction>(i);
self_->write(connectBufQueue->get(i), cb);
}
self_->connectQueueCleanUp();
}
self_->emit(EVENT_CONNECT);
if (self_->hasFlag(SHUTDOWN_QUEUED)) {
self_->unsetFlag(SHUTDOWN_QUEUED);
self_->end();
}
return Status::OK;
}
private:
Socket* self_;
};
class AfterLookup : LIBJ_JS_FUNCTION(AfterLookup)
public:
AfterLookup(
Socket::Ptr self,
uv::Tcp* tcp,
Int port,
String::CPtr localAddress)
: self_(self)
, tcp_(tcp)
, port_(port)
, localAddress_(localAddress) {}
virtual Value operator()(JsArray::Ptr args) {
LIBJ_STATIC_SYMBOL_DEF(symLocalhost4, "127.0.0.1");
LIBJ_STATIC_SYMBOL_DEF(symLocalhost6, "0:0:0:0:0:0:0:1");
if (!self_->hasFlag(CONNECTING)) return Status::OK;
Error::CPtr err = args->getCPtr<Error>(0);
String::CPtr ip = args->getCPtr<String>(1);
Int addressType = to<Int>(args->get(2));
if (err) {
JsFunction::Ptr destroy(
new EmitErrorAndDestroy(&(*self_), err));
process::nextTick(destroy);
} else {
self_->active();
if (!addressType) {
addressType = 4;
}
if (!ip) {
ip = addressType == 4 ? symLocalhost4 : symLocalhost6;
}
connect(
&(*self_), tcp_, ip, port_, addressType, localAddress_);
}
return Status::OK;
}
private:
Socket::Ptr self_;
uv::Tcp* tcp_;
Int port_;
String::CPtr localAddress_;
};
class EmitError : LIBJ_JS_FUNCTION(EmitError)
public:
EmitError(
Socket* sock,
Error::CPtr err)
: self_(sock)
, error_(err) {}
virtual Value operator()(JsArray::Ptr args) {
self_->emit(EVENT_ERROR, error_);
return Status::OK;
}
private:
Socket* self_;
Error::CPtr error_;
};
class EmitErrorAndDestroy : LIBJ_JS_FUNCTION(EmitErrorAndDestroy)
public:
EmitErrorAndDestroy(
Socket* sock,
Error::CPtr err)
: self_(sock)
, error_(err) {}
virtual Value operator()(JsArray::Ptr args) {
self_->emit(EVENT_ERROR, error_);
self_->destroy();
return Status::OK;
}
private:
Socket* self_;
Error::CPtr error_;
};
class EmitClose : LIBJ_JS_FUNCTION(EmitClose)
public:
EmitClose(
Socket* sock,
Error::CPtr err)
: self_(sock)
, error_(err) {}
virtual Value operator()(JsArray::Ptr args) {
LIBJ_STATIC_SYMBOL_DEF(EVENT_DESTROY, "destroy");
self_->emit(EVENT_CLOSE, !!error_);
self_->emit(EVENT_DESTROY);
return Status::OK;
}
private:
Socket* self_;
Error::CPtr error_;
};
class EmitTimeout : LIBJ_JS_FUNCTION(EmitTimeout)
public:
EmitTimeout(Socket* self) : self_(self) {}
virtual Value operator()(JsArray::Ptr args) {
self_->emit(EVENT_TIMEOUT);
return Status::OK;
}
private:
Socket* self_;
};
class OnDestroy : LIBJ_JS_FUNCTION(OnDestroy)
public:
OnDestroy(Socket::Ptr sock) : self_(sock) {}
virtual Value operator()(JsArray::Ptr args) {
assert(!self_->handle_);
assert(self_->hasFlag(DESTROYED));
#ifdef LIBNODE_REMOVE_LISTENER
self_->removeAllListeners();
#endif
return Status::OK;
}
private:
Socket::Ptr self_;
};
public:
enum Flag {
READABLE = 1 << 0,
WRITABLE = 1 << 1,
CONNECTING = 1 << 2,
PAUSED = 1 << 3,
GOT_EOF = 1 << 4,
DESTROYED = 1 << 5,
DESTROY_SOON = 1 << 6,
SHUTDOWN = 1 << 7,
SHUTDOWN_QUEUED = 1 << 8,
ERROR_EMITTED = 1 << 9,
ALLOW_HALF_OPEN = 1 << 10,
};
private:
uv::Stream* handle_;
Value timer_;
Int timeout_;
Size pendingWriteReqs_;
Size connectQueueSize_;
JsArray::Ptr connectBufQueue_;
JsArray::Ptr connectCbQueue_;
Size bytesRead_;
Size bytesDispatched_;
StringDecoder::Ptr decoder_;
JsFunction::Ptr onData_;
JsFunction::Ptr onEnd_;
JsFunction::Ptr onDrain_;
JsFunction::Ptr onClose_;
http::Parser* parser_;
http::OutgoingMessage* httpMessage_;
Socket()
: handle_(NULL)
, timer_(UNDEFINED)
, timeout_(0)
, pendingWriteReqs_(0)
, connectQueueSize_(0)
, connectBufQueue_(JsArray::null())
, connectCbQueue_(JsArray::null())
, bytesRead_(0)
, bytesDispatched_(0)
, decoder_(StringDecoder::null())
, onData_(JsFunction::null())
, onEnd_(JsFunction::null())
, onDrain_(JsFunction::null())
, onClose_(JsFunction::null())
, parser_(NULL)
, httpMessage_(NULL) {}
public:
virtual ~Socket() {
if (handle_) handle_->close();
}
};
} // namespace net
} // namespace detail
} // namespace node
} // namespace libj
#endif // LIBNODE_DETAIL_NET_SOCKET_H_
| 27.636544 | 78 | 0.519224 |
6adb26ea0665494dfaa6bac15af6848f4f8087b7 | 1,169 | h | C | services/viz/public/cpp/compositing/selection_mojom_traits.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | services/viz/public/cpp/compositing/selection_mojom_traits.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | services/viz/public/cpp/compositing/selection_mojom_traits.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"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 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_VIZ_PUBLIC_CPP_COMPOSITING_SELECTION_MOJOM_TRAITS_H_
#define SERVICES_VIZ_PUBLIC_CPP_COMPOSITING_SELECTION_MOJOM_TRAITS_H_
#include "components/viz/common/quads/selection.h"
#include "services/viz/public/mojom/compositing/selection.mojom-shared.h"
#include "ui/gfx/selection_bound.h"
namespace mojo {
template <>
struct StructTraits<viz::mojom::SelectionDataView,
viz::Selection<gfx::SelectionBound>> {
static const gfx::SelectionBound& start(
const viz::Selection<gfx::SelectionBound>& selection) {
return selection.start;
}
static const gfx::SelectionBound& end(
const viz::Selection<gfx::SelectionBound>& selection) {
return selection.end;
}
static bool Read(viz::mojom::SelectionDataView data,
viz::Selection<gfx::SelectionBound>* out) {
return data.ReadStart(&out->start) && data.ReadEnd(&out->end);
}
};
} // namespace mojo
#endif // SERVICES_VIZ_PUBLIC_CPP_COMPOSITING_SELECTION_MOJOM_TRAITS_H_
| 32.472222 | 73 | 0.742515 |
fee61aa66738b444143e783358b02e2da5ee6868 | 1,205 | c | C | test_inputs/codegen/cloog/reservoir-QR.c | chelini/isl-haystack | 61c4ee2a58021f9515cce4ee73adc3bd887d55d0 | [
"MIT"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | test_inputs/codegen/cloog/reservoir-QR.c | chelini/isl-haystack | 61c4ee2a58021f9515cce4ee73adc3bd887d55d0 | [
"MIT"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | test_inputs/codegen/cloog/reservoir-QR.c | chelini/isl-haystack | 61c4ee2a58021f9515cce4ee73adc3bd887d55d0 | [
"MIT"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | if (N >= 1) {
S1(0);
if (N == 1) {
for (int c1 = 0; c1 < M; c1 += 1)
S2(0, c1);
S3(0);
for (int c1 = 0; c1 < M; c1 += 1)
S4(0, c1);
S10(0);
S5(0);
} else {
for (int c1 = 0; c1 < M; c1 += 1)
S2(0, c1);
S3(0);
for (int c1 = 0; c1 < M; c1 += 1)
S4(0, c1);
S10(0);
S1(1);
S5(0);
}
for (int c0 = 2; c0 < N; c0 += 1) {
for (int c1 = c0 - 1; c1 < N; c1 += 1) {
S6(c0 - 2, c1);
for (int c2 = c0 - 2; c2 < M; c2 += 1)
S7(c0 - 2, c1, c2);
S8(c0 - 2, c1);
for (int c2 = c0 - 2; c2 < M; c2 += 1)
S9(c0 - 2, c1, c2);
}
for (int c1 = c0 - 1; c1 < M; c1 += 1)
S2(c0 - 1, c1);
S3(c0 - 1);
for (int c1 = c0 - 1; c1 < M; c1 += 1)
S4(c0 - 1, c1);
S10(c0 - 1);
S1(c0);
S5(c0 - 1);
}
if (N >= 2) {
S6(N - 2, N - 1);
for (int c2 = N - 2; c2 < M; c2 += 1)
S7(N - 2, N - 1, c2);
S8(N - 2, N - 1);
for (int c2 = N - 2; c2 < M; c2 += 1)
S9(N - 2, N - 1, c2);
for (int c1 = N - 1; c1 < M; c1 += 1)
S2(N - 1, c1);
S3(N - 1);
for (int c1 = N - 1; c1 < M; c1 += 1)
S4(N - 1, c1);
S10(N - 1);
S5(N - 1);
}
}
| 21.909091 | 44 | 0.3361 |
3a032ca2c913605e4691addde321759cafbdec5b | 2,483 | h | C | dependencies/panda/Panda3D-1.10.0-x64/include/textGraphic.h | CrankySupertoon01/Toontown-2 | 60893d104528a8e7eb4aced5d0015f22e203466d | [
"MIT"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/text/textGraphic.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 1 | 2018-07-28T20:07:04.000Z | 2018-07-30T18:28:34.000Z | panda/src/text/textGraphic.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 2 | 2019-12-02T01:39:10.000Z | 2021-02-13T22:41:00.000Z | // Filename: textGraphic.h
// Created by: drose (18Aug06)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#ifndef TEXTGRAPHIC_H
#define TEXTGRAPHIC_H
#include "pandabase.h"
#include "config_text.h"
#include "nodePath.h"
////////////////////////////////////////////////////////////////////
// Class : TextGraphic
// Description : This defines a special model that has been
// constructed for the purposes of embedding an
// arbitrary graphic image within a text paragraph.
//
// It can be any arbitrary model, though it should be
// built along the same scale as the text, and it should
// probably be at least mostly two-dimensional.
// Typically, this means it should be constructed in the
// X-Z plane, and it should have a maximum vertical (Z)
// height of 1.0.
//
// The frame specifies an arbitrary bounding volume in
// the form (left, right, bottom, top). This indicates
// the amount of space that will be reserved within the
// paragraph. The actual model is not actually required
// to fit within this rectangle, but if it does not, it
// may visually overlap with nearby text.
////////////////////////////////////////////////////////////////////
class EXPCL_PANDA_TEXT TextGraphic {
PUBLISHED:
INLINE TextGraphic();
INLINE TextGraphic(const NodePath &model, const LVecBase4 &frame);
INLINE TextGraphic(const NodePath &model, PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top);
INLINE NodePath get_model() const;
INLINE void set_model(const NodePath &model);
INLINE LVecBase4 get_frame() const;
INLINE void set_frame(const LVecBase4 &frame);
INLINE void set_frame(PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top);
INLINE bool get_instance_flag() const;
INLINE void set_instance_flag(bool instance_flag);
private:
NodePath _model;
LVecBase4 _frame;
bool _instance_flag;
};
#include "textGraphic.I"
#endif
| 36.514706 | 118 | 0.607733 |
0e5071f53dbe02955d7a77cbfda158a9dfcf592a | 2,621 | h | C | 3rdparty/webkit/Source/WebKit/UIProcess/API/gtk/WebKitAuthenticationDialog.h | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2021-05-27T07:29:31.000Z | 2021-05-27T07:29:31.000Z | WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/UIProcess/API/gtk/WebKitAuthenticationDialog.h | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebKit/UIProcess/API/gtk/WebKitAuthenticationDialog.h | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | /*
* Copyright (C) 2012 Igalia S.L.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef WebKitAuthenticationDialog_h
#define WebKitAuthenticationDialog_h
#include "WebKitAuthenticationRequest.h"
#include <gtk/gtk.h>
enum CredentialStorageMode {
AllowPersistentStorage, // The user is asked whether to store credential information.
DisallowPersistentStorage // Credential information is only kept in the session.
};
G_BEGIN_DECLS
#define WEBKIT_TYPE_AUTHENTICATION_DIALOG (webkit_authentication_dialog_get_type())
#define WEBKIT_AUTHENTICATION_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_AUTHENTICATION_DIALOG, WebKitAuthenticationDialog))
#define WEBKIT_IS_AUTHENTICATION_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_AUTHENTICATION_DIALOG))
#define WEBKIT_AUTHENTICATION_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_AUTHENTICATION_DIALOG, WebKitAuthenticationDialogClass))
#define WEBKIT_IS_AUTHENTICATION_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_AUTHENTICATION_DIALOG))
#define WEBKIT_AUTHENTICATION_DIALOG_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_AUTHENTICATION_DIALOG, WebKitAuthenticationDialogClass))
typedef struct _WebKitAuthenticationDialog WebKitAuthenticationDialog;
typedef struct _WebKitAuthenticationDialogClass WebKitAuthenticationDialogClass;
typedef struct _WebKitAuthenticationDialogPrivate WebKitAuthenticationDialogPrivate;
struct _WebKitAuthenticationDialog {
GtkEventBox parent;
WebKitAuthenticationDialogPrivate* priv;
};
struct _WebKitAuthenticationDialogClass {
GtkEventBoxClass parentClass;
};
GType webkit_authentication_dialog_get_type();
GtkWidget* webkitAuthenticationDialogNew(WebKitAuthenticationRequest*, CredentialStorageMode);
G_END_DECLS
#endif // WebKitAuthenticationDialog_h
| 43.683333 | 156 | 0.814193 |
cdc4c991799dbf9b7465332a5fbf3bcab6beac43 | 820 | h | C | Source/UtilsDevice/UtEspresso/espresso_cubestr.h | keshbach/PEP | 75071aee89a718d318e13c55eee9eb5b9ae4e987 | [
"Apache-2.0"
] | 1 | 2021-12-11T14:21:55.000Z | 2021-12-11T14:21:55.000Z | Source/UtilsDevice/UtEspresso/espresso_cubestr.h | keshbach/PEP | 75071aee89a718d318e13c55eee9eb5b9ae4e987 | [
"Apache-2.0"
] | null | null | null | Source/UtilsDevice/UtEspresso/espresso_cubestr.h | keshbach/PEP | 75071aee89a718d318e13c55eee9eb5b9ae4e987 | [
"Apache-2.0"
] | 1 | 2021-06-23T14:01:55.000Z | 2021-06-23T14:01:55.000Z | /***************************************************************************/
/* Copyright (c) 1988, 1989, Regents of the University of California. */
/* All rights reserved. */
/***************************************************************************/
#if !defined(espresso_cubestr_h)
#define espresso_cubestr_h
void cube_setup(TPCubeContext pCubeContext);
void setdown_cube(TPCubeContext pCubeContext);
#endif /* end of espresso_cubestr_h */
/***************************************************************************/
/* Copyright (c) 1988, 1989, Regents of the University of California. */
/* All rights reserved. */
/***************************************************************************/
| 43.157895 | 77 | 0.362195 |
35edebfe8860d7b78a4f4609770cd1c7089448ae | 8,904 | c | C | luat/packages/epaper/EPD_5in65f.c | pengxxxxx/LuatOS | dc163e7dc2d5230901b7ce57566d662d1954546e | [
"MIT"
] | 217 | 2019-12-29T15:52:46.000Z | 2022-03-29T05:44:29.000Z | luat/packages/epaper/EPD_5in65f.c | zhangyinpeng/LuatOS | 7543d59cbfe0fbb9c9ba1c3a0b506660c783367a | [
"MIT"
] | 64 | 2019-12-30T05:50:04.000Z | 2022-03-06T03:48:56.000Z | luat/packages/epaper/EPD_5in65f.c | zhangyinpeng/LuatOS | 7543d59cbfe0fbb9c9ba1c3a0b506660c783367a | [
"MIT"
] | 59 | 2020-01-09T03:46:01.000Z | 2022-03-27T03:17:36.000Z | /*****************************************************************************
* | File : EPD_5in65f.c
* | Author : Waveshare team
* | Function : 5.65inch e-paper
* | Info :
*----------------
* | This version: V1.0
* | Date : 2020-07-07
* | Info :
* -----------------------------------------------------------------------------
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation 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
# furished 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 OR 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 "EPD_5in65f.h"
/******************************************************************************
function : Software reset
parameter:
******************************************************************************/
static void EPD_5IN65F_Reset(void)
{
DEV_Digital_Write(EPD_RST_PIN, 1);
DEV_Delay_ms(200);
DEV_Digital_Write(EPD_RST_PIN, 0);
DEV_Delay_ms(1);
DEV_Digital_Write(EPD_RST_PIN, 1);
DEV_Delay_ms(200);
}
/******************************************************************************
function : send command
parameter:
Reg : Command register
******************************************************************************/
static void EPD_5IN65F_SendCommand(UBYTE Reg)
{
DEV_Digital_Write(EPD_DC_PIN, 0);
DEV_Digital_Write(EPD_CS_PIN, 0);
DEV_SPI_WriteByte(Reg);
DEV_Digital_Write(EPD_CS_PIN, 1);
}
/******************************************************************************
function : send data
parameter:
Data : Write data
******************************************************************************/
static void EPD_5IN65F_SendData(UBYTE Data)
{
DEV_Digital_Write(EPD_DC_PIN, 1);
DEV_Digital_Write(EPD_CS_PIN, 0);
DEV_SPI_WriteByte(Data);
DEV_Digital_Write(EPD_CS_PIN, 1);
}
static void EPD_5IN65F_BusyHigh(void)// If BUSYN=0 then waiting
{
while(!(DEV_Digital_Read(EPD_BUSY_PIN)));
}
static void EPD_5IN65F_BusyLow(void)// If BUSYN=1 then waiting
{
while(DEV_Digital_Read(EPD_BUSY_PIN));
}
/******************************************************************************
function : Initialize the e-Paper register
parameter:
******************************************************************************/
void EPD_5IN65F_Init(void)
{
EPD_5IN65F_Reset();
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x00);
EPD_5IN65F_SendData(0xEF);
EPD_5IN65F_SendData(0x08);
EPD_5IN65F_SendCommand(0x01);
EPD_5IN65F_SendData(0x37);
EPD_5IN65F_SendData(0x00);
EPD_5IN65F_SendData(0x23);
EPD_5IN65F_SendData(0x23);
EPD_5IN65F_SendCommand(0x03);
EPD_5IN65F_SendData(0x00);
EPD_5IN65F_SendCommand(0x06);
EPD_5IN65F_SendData(0xC7);
EPD_5IN65F_SendData(0xC7);
EPD_5IN65F_SendData(0x1D);
EPD_5IN65F_SendCommand(0x30);
EPD_5IN65F_SendData(0x3C);
EPD_5IN65F_SendCommand(0x40);
EPD_5IN65F_SendData(0x00);
EPD_5IN65F_SendCommand(0x50);
EPD_5IN65F_SendData(0x37);
EPD_5IN65F_SendCommand(0x60);
EPD_5IN65F_SendData(0x22);
EPD_5IN65F_SendCommand(0x61);
EPD_5IN65F_SendData(0x02);
EPD_5IN65F_SendData(0x58);
EPD_5IN65F_SendData(0x01);
EPD_5IN65F_SendData(0xC0);
EPD_5IN65F_SendCommand(0xE3);
EPD_5IN65F_SendData(0xAA);
DEV_Delay_ms(100);
EPD_5IN65F_SendCommand(0x50);
EPD_5IN65F_SendData(0x37);
}
/******************************************************************************
function : Clear screen
parameter:
******************************************************************************/
void EPD_5IN65F_Clear(UBYTE color)
{
EPD_5IN65F_SendCommand(0x61);//Set Resolution setting
EPD_5IN65F_SendData(0x02);
EPD_5IN65F_SendData(0x58);
EPD_5IN65F_SendData(0x01);
EPD_5IN65F_SendData(0xC0);
EPD_5IN65F_SendCommand(0x10);
for(int i=0; i<EPD_5IN65F_WIDTH/2; i++) {
for(int j=0; j<EPD_5IN65F_HEIGHT; j++)
EPD_5IN65F_SendData((color<<4)|color);
}
EPD_5IN65F_SendCommand(0x04);//0x04
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x12);//0x12
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x02); //0x02
EPD_5IN65F_BusyLow();
DEV_Delay_ms(500);
}
/******************************************************************************
function : show 7 kind of color block
parameter:
******************************************************************************/
void EPD_5IN65F_Show7Block(void)
{
unsigned long i,j,k;
unsigned char const Color_seven[8] =
{EPD_5IN65F_BLACK,EPD_5IN65F_BLUE,EPD_5IN65F_GREEN,EPD_5IN65F_ORANGE,
EPD_5IN65F_RED,EPD_5IN65F_YELLOW,EPD_5IN65F_WHITE,EPD_5IN65F_WHITE};
EPD_5IN65F_SendCommand(0x61);//Set Resolution setting
EPD_5IN65F_SendData(0x02);
EPD_5IN65F_SendData(0x58);
EPD_5IN65F_SendData(0x01);
EPD_5IN65F_SendData(0xC0);
EPD_5IN65F_SendCommand(0x10);
for(i=0; i<224; i++) {
for(k = 0 ; k < 4; k ++) {
for(j = 0 ; j < 75; j ++) {
EPD_5IN65F_SendData((Color_seven[k]<<4) |Color_seven[k]);
}
}
}
for(i=0; i<224; i++) {
for(k = 4 ; k < 8; k ++) {
for(j = 0 ; j < 75; j ++) {
EPD_5IN65F_SendData((Color_seven[k]<<4) |Color_seven[k]);
}
}
}
EPD_5IN65F_SendCommand(0x04);//0x04
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x12);//0x12
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x02); //0x02
EPD_5IN65F_BusyLow();
DEV_Delay_ms(200);
}
/******************************************************************************
function : Sends the image buffer in RAM to e-Paper and displays
parameter:
******************************************************************************/
void EPD_5IN65F_Display(const UBYTE *image)
{
unsigned long i,j;
EPD_5IN65F_SendCommand(0x61);//Set Resolution setting
EPD_5IN65F_SendData(0x02);
EPD_5IN65F_SendData(0x58);
EPD_5IN65F_SendData(0x01);
EPD_5IN65F_SendData(0xC0);
EPD_5IN65F_SendCommand(0x10);
for(i=0; i<EPD_5IN65F_HEIGHT; i++) {
for(j=0; j<EPD_5IN65F_WIDTH/2; j++)
EPD_5IN65F_SendData(image[j+((EPD_5IN65F_WIDTH/2)*i)]);
}
EPD_5IN65F_SendCommand(0x04);//0x04
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x12);//0x12
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x02); //0x02
EPD_5IN65F_BusyLow();
DEV_Delay_ms(200);
}
/******************************************************************************
function : Sends the part image buffer in RAM to e-Paper and displays
parameter:
******************************************************************************/
void EPD_5IN65F_Display_part(const UBYTE *image, UWORD xstart, UWORD ystart,
UWORD image_width, UWORD image_heigh)
{
unsigned long i,j;
EPD_5IN65F_SendCommand(0x61);//Set Resolution setting
EPD_5IN65F_SendData(0x02);
EPD_5IN65F_SendData(0x58);
EPD_5IN65F_SendData(0x01);
EPD_5IN65F_SendData(0xC0);
EPD_5IN65F_SendCommand(0x10);
for(i=0; i<EPD_5IN65F_HEIGHT; i++) {
for(j=0; j< EPD_5IN65F_WIDTH/2; j++) {
if(i<image_heigh+ystart && i>=ystart && j<(image_width+xstart)/2 && j>=xstart/2) {
EPD_5IN65F_SendData(image[(j-xstart/2) + (image_width/2*(i-ystart))]);
}
else {
EPD_5IN65F_SendData(0x11);
}
}
}
EPD_5IN65F_SendCommand(0x04);//0x04
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x12);//0x12
EPD_5IN65F_BusyHigh();
EPD_5IN65F_SendCommand(0x02); //0x02
EPD_5IN65F_BusyLow();
DEV_Delay_ms(200);
}
/******************************************************************************
function : Enter sleep mode
parameter:
******************************************************************************/
void EPD_5IN65F_Sleep(void)
{
DEV_Delay_ms(100);
EPD_5IN65F_SendCommand(0x07);
EPD_5IN65F_SendData(0xA5);
DEV_Delay_ms(100);
DEV_Digital_Write(EPD_RST_PIN, 0); // Reset
}
| 33.473684 | 88 | 0.569407 |
e05e8c59efe601cf96c9f60b6fe1f1790c7d5c6d | 34 | h | C | modules/lpc4337_m4/osek/inc/cortexM4/StartOs_Arch_SysTick.h | mmarando/workspace | 62afb4f9ae2ef4f7cab28ce63ceb2c7a7a83ed4b | [
"BSD-3-Clause"
] | 19 | 2017-06-08T23:23:03.000Z | 2021-04-15T03:33:11.000Z | modules/lpc4337_m4/osek/inc/cortexM4/StartOs_Arch_SysTick.h | mmarando/workspace | 62afb4f9ae2ef4f7cab28ce63ceb2c7a7a83ed4b | [
"BSD-3-Clause"
] | 21 | 2017-01-05T23:52:21.000Z | 2022-02-02T18:26:23.000Z | modules/lpc4337_m4/osek/inc/cortexM4/StartOs_Arch_SysTick.h | mmarando/workspace | 62afb4f9ae2ef4f7cab28ce63ceb2c7a7a83ed4b | [
"BSD-3-Clause"
] | 50 | 2016-12-14T20:28:43.000Z | 2021-12-20T09:30:02.000Z |
void StartOs_Arch_SysTick(void);
| 11.333333 | 32 | 0.823529 |
0d8b2c91bc640ca656b520b0b15edb266e360e32 | 2,845 | c | C | mtcp/src/schedule.c | acceltcp/AccelTCP | b1d36680fd370cfdc6b2cb182b26b4c55c468754 | [
"BSD-3-Clause"
] | 53 | 2019-11-14T12:47:44.000Z | 2022-03-19T15:11:58.000Z | host/mtcp_ssl_offload/mtcp/src/schedule.c | SmartTLS/SmartTLS | 8e8b37161577a08feb7d59f242cf53949ef47646 | [
"BSD-3-Clause"
] | 2 | 2019-12-06T23:12:52.000Z | 2020-09-17T04:27:53.000Z | host/mtcp_ssl_offload/mtcp/src/schedule.c | SmartTLS/SmartTLS | 8e8b37161577a08feb7d59f242cf53949ef47646 | [
"BSD-3-Clause"
] | 11 | 2020-02-28T00:41:36.000Z | 2022-03-19T15:13:46.000Z | #include <signal.h>
#include <time.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <assert.h>
#include "schedule.h"
#include "lthread_api.h"
#include "debug.h"
#ifdef ENABLE_APP_INTERRUPT
static inline int
UnregisterTimerInterrupt(timer_t timerid)
{
int ret;
struct itimerspec its = {
.it_value = {
.tv_sec = 0,
.tv_nsec = 0,
},
.it_interval = {
.tv_sec = 0,
.tv_nsec = 0,
},
};
ret = timer_settime(timerid, 0, &its, NULL);
if (ret < 0)
TRACE_ERROR("Failed to unregister timer interrupt: (reason: %d)\n", errno);
return ret;
}
static inline int
RegisterTimerInterrupt(timer_t timerid, uint32_t timeout)
{
int ret;
struct itimerspec its = {
.it_value = {
.tv_sec = 0,
.tv_nsec = timeout,
},
.it_interval = {
.tv_sec = 0,
.tv_nsec = 0,
},
};
ret = timer_settime(timerid, 0, &its, NULL);
if (ret < 0)
TRACE_ERROR("Failed to register timer interrupt: (reason: %d)\n", errno);
return ret;
}
void
HandleTimerInterrupt(int sig, siginfo_t *si, void *uc)
{
int nif, pending_nic;
if (si->si_code != SI_TIMER) {
fprintf(stderr, "No\n");
}
mtcp_thread_context_t ctx;
ctx = (mtcp_thread_context_t) si->si_value.sival_ptr;
if (ctx != NULL) {
// TODO update stat schedule
}
/* check if there's any pending RX packet in NIC */
pending_nic = 0;
for (nif = 0; nif < CONFIG.eths_num; nif++)
pending_nic += ctx->mtcp_manager->iom->dev_ioctl(ctx, nif, DRV_PENDING_RX_PKT, NULL);
if (!pending_nic) {
RegisterTimerInterrupt(ctx->timerid, ctx->tick);
return;
}
/* yield to stack if app is not in mTCP API */
ctx->int_app = TRUE;
YieldToStack(ctx, YIELD_REASON_TIMER);
}
int
InitTimer(mtcp_thread_context_t ctx)
{
int ret;
struct sigevent sev;
memset(&sev, -1, sizeof(struct sigevent));
sev.sigev_signo = TIMER_SIGNAL;
sev.sigev_notify = SIGEV_THREAD_ID;
sev.sigev_value.sival_ptr = ctx;
sev._sigev_un._tid = syscall(SYS_gettid);
ret = timer_create(CLOCK_REALTIME, &sev, &ctx->timerid);
if (ret < 0)
perror("timer_create");
/* FIXME currently using static 50us */
ctx->tick = 50000;
ctx->int_app = FALSE;
ctx->in_api = FALSE;
UnregisterTimerInterrupt(ctx->timerid);
return ret;
}
int
DeleteTimer(mtcp_thread_context_t ctx)
{
int ret;
ret = timer_delete(ctx->timerid);
if (ret < 0)
perror("timer_delete");
return ret;
}
#endif
inline void
YieldToStack(mtcp_thread_context_t ctx, int reason)
{
assert(mtcp);
#ifdef ENABLE_APP_INTERRUPT
if (reason == YIELD_REASON_TIMER) {
if (ctx->int_app)
UnregisterTimerInterrupt(ctx->timerid);
else
return;
}
#endif
lthread_yield();
}
inline void
YieldToApp(mtcp_thread_context_t ctx, int interrupt)
{
assert(mtcp);
#ifdef ENABLE_APP_INTERRUPT
if (interrupt)
RegisterTimerInterrupt(ctx->timerid, ctx->tick);
#endif
lthread_yield();
}
| 18.121019 | 93 | 0.679438 |
c71eb0e0503eb9100165f68fd273245f095da69e | 20,640 | c | C | src/3rd/libvorbis/src/info.c | koron0902/BGMPlayer | cc00454b463ae6c339235ee59f4249c33263438e | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | src/3rd/libvorbis/src/info.c | koron0902/BGMPlayer | cc00454b463ae6c339235ee59f4249c33263438e | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2019-12-04T01:47:08.000Z | 2019-12-04T01:47:08.000Z | src/3rd/libvorbis/src/info.c | koron0902/Cocoa | cc00454b463ae6c339235ee59f4249c33263438e | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | /********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2015 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: maintain the info structure, info <-> header packets
last mod: $Id: info.c 19441 2015-01-21 01:17:41Z xiphmont $
********************************************************************/
/* general handling of the header and the vorbis_info structure (and
substructures) */
#include "codebook.h"
#include "codec_internal.h"
#include "misc.h"
#include "os.h"
#include "psy.h"
#include "registry.h"
#include "vorbis/codec.h"
#include "window.h"
#include <ctype.h>
#include <ogg/ogg.h>
#include <stdlib.h>
#include <string.h>
#define GENERAL_VENDOR_STRING "Xiph.Org libVorbis 1.3.5"
#define ENCODE_VENDOR_STRING "Xiph.Org libVorbis I 20150105 (⛄⛄⛄⛄)"
/* helpers */
static void _v_writestring(oggpack_buffer *o, const char *s, int bytes) {
while (bytes--) {
oggpack_write(o, *s++, 8);
}
}
static void _v_readstring(oggpack_buffer *o, char *buf, int bytes) {
while (bytes--) {
*buf++ = oggpack_read(o, 8);
}
}
void vorbis_comment_init(vorbis_comment *vc) { memset(vc, 0, sizeof(*vc)); }
void vorbis_comment_add(vorbis_comment *vc, const char *comment) {
vc->user_comments = _ogg_realloc(
vc->user_comments, (vc->comments + 2) * sizeof(*vc->user_comments));
vc->comment_lengths = _ogg_realloc(
vc->comment_lengths, (vc->comments + 2) * sizeof(*vc->comment_lengths));
vc->comment_lengths[vc->comments] = strlen(comment);
vc->user_comments[vc->comments] =
_ogg_malloc(vc->comment_lengths[vc->comments] + 1);
strcpy(vc->user_comments[vc->comments], comment);
vc->comments++;
vc->user_comments[vc->comments] = NULL;
}
void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag,
const char *contents) {
char *comment =
alloca(strlen(tag) + strlen(contents) + 2); /* +2 for = and \0 */
strcpy(comment, tag);
strcat(comment, "=");
strcat(comment, contents);
vorbis_comment_add(vc, comment);
}
/* This is more or less the same as strncasecmp - but that doesn't exist
* everywhere, and this is a fairly trivial function, so we include it */
static int tagcompare(const char *s1, const char *s2, int n) {
int c = 0;
while (c < n) {
if (toupper(s1[c]) != toupper(s2[c]))
return !0;
c++;
}
return 0;
}
char *vorbis_comment_query(vorbis_comment *vc, const char *tag, int count) {
long i;
int found = 0;
int taglen = strlen(tag) + 1; /* +1 for the = we append */
char *fulltag = alloca(taglen + 1);
strcpy(fulltag, tag);
strcat(fulltag, "=");
for (i = 0; i < vc->comments; i++) {
if (!tagcompare(vc->user_comments[i], fulltag, taglen)) {
if (count == found)
/* We return a pointer to the data, not a copy */
return vc->user_comments[i] + taglen;
else
found++;
}
}
return NULL; /* didn't find anything */
}
int vorbis_comment_query_count(vorbis_comment *vc, const char *tag) {
int i, count = 0;
int taglen = strlen(tag) + 1; /* +1 for the = we append */
char *fulltag = alloca(taglen + 1);
strcpy(fulltag, tag);
strcat(fulltag, "=");
for (i = 0; i < vc->comments; i++) {
if (!tagcompare(vc->user_comments[i], fulltag, taglen))
count++;
}
return count;
}
void vorbis_comment_clear(vorbis_comment *vc) {
if (vc) {
long i;
if (vc->user_comments) {
for (i = 0; i < vc->comments; i++)
if (vc->user_comments[i])
_ogg_free(vc->user_comments[i]);
_ogg_free(vc->user_comments);
}
if (vc->comment_lengths)
_ogg_free(vc->comment_lengths);
if (vc->vendor)
_ogg_free(vc->vendor);
memset(vc, 0, sizeof(*vc));
}
}
/* blocksize 0 is guaranteed to be short, 1 is guaranteed to be long.
They may be equal, but short will never ge greater than long */
int vorbis_info_blocksize(vorbis_info *vi, int zo) {
codec_setup_info *ci = vi->codec_setup;
return ci ? ci->blocksizes[zo] : -1;
}
/* used by synthesis, which has a full, alloced vi */
void vorbis_info_init(vorbis_info *vi) {
memset(vi, 0, sizeof(*vi));
vi->codec_setup = _ogg_calloc(1, sizeof(codec_setup_info));
}
void vorbis_info_clear(vorbis_info *vi) {
codec_setup_info *ci = vi->codec_setup;
int i;
if (ci) {
for (i = 0; i < ci->modes; i++)
if (ci->mode_param[i])
_ogg_free(ci->mode_param[i]);
for (i = 0; i < ci->maps; i++) /* unpack does the range checking */
if (ci->map_param[i]) /* this may be cleaning up an aborted
unpack, in which case the below type
cannot be trusted */
_mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
for (i = 0; i < ci->floors; i++) /* unpack does the range checking */
if (ci->floor_param[i]) /* this may be cleaning up an aborted
unpack, in which case the below type
cannot be trusted */
_floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
for (i = 0; i < ci->residues; i++) /* unpack does the range checking */
if (ci->residue_param[i]) /* this may be cleaning up an aborted
unpack, in which case the below type
cannot be trusted */
_residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
for (i = 0; i < ci->books; i++) {
if (ci->book_param[i]) {
/* knows if the book was not alloced */
vorbis_staticbook_destroy(ci->book_param[i]);
}
if (ci->fullbooks)
vorbis_book_clear(ci->fullbooks + i);
}
if (ci->fullbooks)
_ogg_free(ci->fullbooks);
for (i = 0; i < ci->psys; i++)
_vi_psy_free(ci->psy_param[i]);
_ogg_free(ci);
}
memset(vi, 0, sizeof(*vi));
}
/* Header packing/unpacking ********************************************/
static int _vorbis_unpack_info(vorbis_info *vi, oggpack_buffer *opb) {
codec_setup_info *ci = vi->codec_setup;
if (!ci)
return (OV_EFAULT);
vi->version = oggpack_read(opb, 32);
if (vi->version != 0)
return (OV_EVERSION);
vi->channels = oggpack_read(opb, 8);
vi->rate = oggpack_read(opb, 32);
vi->bitrate_upper = oggpack_read(opb, 32);
vi->bitrate_nominal = oggpack_read(opb, 32);
vi->bitrate_lower = oggpack_read(opb, 32);
ci->blocksizes[0] = 1 << oggpack_read(opb, 4);
ci->blocksizes[1] = 1 << oggpack_read(opb, 4);
if (vi->rate < 1)
goto err_out;
if (vi->channels < 1)
goto err_out;
if (ci->blocksizes[0] < 64)
goto err_out;
if (ci->blocksizes[1] < ci->blocksizes[0])
goto err_out;
if (ci->blocksizes[1] > 8192)
goto err_out;
if (oggpack_read(opb, 1) != 1)
goto err_out; /* EOP check */
return (0);
err_out:
vorbis_info_clear(vi);
return (OV_EBADHEADER);
}
static int _vorbis_unpack_comment(vorbis_comment *vc, oggpack_buffer *opb) {
int i;
int vendorlen = oggpack_read(opb, 32);
if (vendorlen < 0)
goto err_out;
if (vendorlen > opb->storage - 8)
goto err_out;
vc->vendor = _ogg_calloc(vendorlen + 1, 1);
_v_readstring(opb, vc->vendor, vendorlen);
i = oggpack_read(opb, 32);
if (i < 0)
goto err_out;
if (i > ((opb->storage - oggpack_bytes(opb)) >> 2))
goto err_out;
vc->comments = i;
vc->user_comments = _ogg_calloc(vc->comments + 1, sizeof(*vc->user_comments));
vc->comment_lengths =
_ogg_calloc(vc->comments + 1, sizeof(*vc->comment_lengths));
for (i = 0; i < vc->comments; i++) {
int len = oggpack_read(opb, 32);
if (len < 0)
goto err_out;
if (len > opb->storage - oggpack_bytes(opb))
goto err_out;
vc->comment_lengths[i] = len;
vc->user_comments[i] = _ogg_calloc(len + 1, 1);
_v_readstring(opb, vc->user_comments[i], len);
}
if (oggpack_read(opb, 1) != 1)
goto err_out; /* EOP check */
return (0);
err_out:
vorbis_comment_clear(vc);
return (OV_EBADHEADER);
}
/* all of the real encoding details are here. The modes, books,
everything */
static int _vorbis_unpack_books(vorbis_info *vi, oggpack_buffer *opb) {
codec_setup_info *ci = vi->codec_setup;
int i;
/* codebooks */
ci->books = oggpack_read(opb, 8) + 1;
if (ci->books <= 0)
goto err_out;
for (i = 0; i < ci->books; i++) {
ci->book_param[i] = vorbis_staticbook_unpack(opb);
if (!ci->book_param[i])
goto err_out;
}
/* time backend settings; hooks are unused */
{
int times = oggpack_read(opb, 6) + 1;
if (times <= 0)
goto err_out;
for (i = 0; i < times; i++) {
int test = oggpack_read(opb, 16);
if (test < 0 || test >= VI_TIMEB)
goto err_out;
}
}
/* floor backend settings */
ci->floors = oggpack_read(opb, 6) + 1;
if (ci->floors <= 0)
goto err_out;
for (i = 0; i < ci->floors; i++) {
ci->floor_type[i] = oggpack_read(opb, 16);
if (ci->floor_type[i] < 0 || ci->floor_type[i] >= VI_FLOORB)
goto err_out;
ci->floor_param[i] = _floor_P[ci->floor_type[i]]->unpack(vi, opb);
if (!ci->floor_param[i])
goto err_out;
}
/* residue backend settings */
ci->residues = oggpack_read(opb, 6) + 1;
if (ci->residues <= 0)
goto err_out;
for (i = 0; i < ci->residues; i++) {
ci->residue_type[i] = oggpack_read(opb, 16);
if (ci->residue_type[i] < 0 || ci->residue_type[i] >= VI_RESB)
goto err_out;
ci->residue_param[i] = _residue_P[ci->residue_type[i]]->unpack(vi, opb);
if (!ci->residue_param[i])
goto err_out;
}
/* map backend settings */
ci->maps = oggpack_read(opb, 6) + 1;
if (ci->maps <= 0)
goto err_out;
for (i = 0; i < ci->maps; i++) {
ci->map_type[i] = oggpack_read(opb, 16);
if (ci->map_type[i] < 0 || ci->map_type[i] >= VI_MAPB)
goto err_out;
ci->map_param[i] = _mapping_P[ci->map_type[i]]->unpack(vi, opb);
if (!ci->map_param[i])
goto err_out;
}
/* mode settings */
ci->modes = oggpack_read(opb, 6) + 1;
if (ci->modes <= 0)
goto err_out;
for (i = 0; i < ci->modes; i++) {
ci->mode_param[i] = _ogg_calloc(1, sizeof(*ci->mode_param[i]));
ci->mode_param[i]->blockflag = oggpack_read(opb, 1);
ci->mode_param[i]->windowtype = oggpack_read(opb, 16);
ci->mode_param[i]->transformtype = oggpack_read(opb, 16);
ci->mode_param[i]->mapping = oggpack_read(opb, 8);
if (ci->mode_param[i]->windowtype >= VI_WINDOWB)
goto err_out;
if (ci->mode_param[i]->transformtype >= VI_WINDOWB)
goto err_out;
if (ci->mode_param[i]->mapping >= ci->maps)
goto err_out;
if (ci->mode_param[i]->mapping < 0)
goto err_out;
}
if (oggpack_read(opb, 1) != 1)
goto err_out; /* top level EOP check */
return (0);
err_out:
vorbis_info_clear(vi);
return (OV_EBADHEADER);
}
/* Is this packet a vorbis ID header? */
int vorbis_synthesis_idheader(ogg_packet *op) {
oggpack_buffer opb;
char buffer[6];
if (op) {
oggpack_readinit(&opb, op->packet, op->bytes);
if (!op->b_o_s)
return (0); /* Not the initial packet */
if (oggpack_read(&opb, 8) != 1)
return 0; /* not an ID header */
memset(buffer, 0, 6);
_v_readstring(&opb, buffer, 6);
if (memcmp(buffer, "vorbis", 6))
return 0; /* not vorbis */
return 1;
}
return 0;
}
/* The Vorbis header is in three packets; the initial small packet in
the first page that identifies basic parameters, a second packet
with bitstream comments and a third packet that holds the
codebook. */
int vorbis_synthesis_headerin(vorbis_info *vi, vorbis_comment *vc,
ogg_packet *op) {
oggpack_buffer opb;
if (op) {
oggpack_readinit(&opb, op->packet, op->bytes);
/* Which of the three types of header is this? */
/* Also verify header-ness, vorbis */
{
char buffer[6];
int packtype = oggpack_read(&opb, 8);
memset(buffer, 0, 6);
_v_readstring(&opb, buffer, 6);
if (memcmp(buffer, "vorbis", 6)) {
/* not a vorbis header */
return (OV_ENOTVORBIS);
}
switch (packtype) {
case 0x01: /* least significant *bit* is read first */
if (!op->b_o_s) {
/* Not the initial packet */
return (OV_EBADHEADER);
}
if (vi->rate != 0) {
/* previously initialized info header */
return (OV_EBADHEADER);
}
return (_vorbis_unpack_info(vi, &opb));
case 0x03: /* least significant *bit* is read first */
if (vi->rate == 0) {
/* um... we didn't get the initial header */
return (OV_EBADHEADER);
}
if (vc->vendor != NULL) {
/* previously initialized comment header */
return (OV_EBADHEADER);
}
return (_vorbis_unpack_comment(vc, &opb));
case 0x05: /* least significant *bit* is read first */
if (vi->rate == 0 || vc->vendor == NULL) {
/* um... we didn;t get the initial header or comments yet */
return (OV_EBADHEADER);
}
if (vi->codec_setup == NULL) {
/* improperly initialized vorbis_info */
return (OV_EFAULT);
}
if (((codec_setup_info *)vi->codec_setup)->books > 0) {
/* previously initialized setup header */
return (OV_EBADHEADER);
}
return (_vorbis_unpack_books(vi, &opb));
default:
/* Not a valid vorbis header type */
return (OV_EBADHEADER);
break;
}
}
}
return (OV_EBADHEADER);
}
/* pack side **********************************************************/
static int _vorbis_pack_info(oggpack_buffer *opb, vorbis_info *vi) {
codec_setup_info *ci = vi->codec_setup;
if (!ci || ci->blocksizes[0] < 64 || ci->blocksizes[1] < ci->blocksizes[0]) {
return (OV_EFAULT);
}
/* preamble */
oggpack_write(opb, 0x01, 8);
_v_writestring(opb, "vorbis", 6);
/* basic information about the stream */
oggpack_write(opb, 0x00, 32);
oggpack_write(opb, vi->channels, 8);
oggpack_write(opb, vi->rate, 32);
oggpack_write(opb, vi->bitrate_upper, 32);
oggpack_write(opb, vi->bitrate_nominal, 32);
oggpack_write(opb, vi->bitrate_lower, 32);
oggpack_write(opb, ov_ilog(ci->blocksizes[0] - 1), 4);
oggpack_write(opb, ov_ilog(ci->blocksizes[1] - 1), 4);
oggpack_write(opb, 1, 1);
return (0);
}
static int _vorbis_pack_comment(oggpack_buffer *opb, vorbis_comment *vc) {
int bytes = strlen(ENCODE_VENDOR_STRING);
/* preamble */
oggpack_write(opb, 0x03, 8);
_v_writestring(opb, "vorbis", 6);
/* vendor */
oggpack_write(opb, bytes, 32);
_v_writestring(opb, ENCODE_VENDOR_STRING, bytes);
/* comments */
oggpack_write(opb, vc->comments, 32);
if (vc->comments) {
int i;
for (i = 0; i < vc->comments; i++) {
if (vc->user_comments[i]) {
oggpack_write(opb, vc->comment_lengths[i], 32);
_v_writestring(opb, vc->user_comments[i], vc->comment_lengths[i]);
} else {
oggpack_write(opb, 0, 32);
}
}
}
oggpack_write(opb, 1, 1);
return (0);
}
static int _vorbis_pack_books(oggpack_buffer *opb, vorbis_info *vi) {
codec_setup_info *ci = vi->codec_setup;
int i;
if (!ci)
return (OV_EFAULT);
oggpack_write(opb, 0x05, 8);
_v_writestring(opb, "vorbis", 6);
/* books */
oggpack_write(opb, ci->books - 1, 8);
for (i = 0; i < ci->books; i++)
if (vorbis_staticbook_pack(ci->book_param[i], opb))
goto err_out;
/* times; hook placeholders */
oggpack_write(opb, 0, 6);
oggpack_write(opb, 0, 16);
/* floors */
oggpack_write(opb, ci->floors - 1, 6);
for (i = 0; i < ci->floors; i++) {
oggpack_write(opb, ci->floor_type[i], 16);
if (_floor_P[ci->floor_type[i]]->pack)
_floor_P[ci->floor_type[i]]->pack(ci->floor_param[i], opb);
else
goto err_out;
}
/* residues */
oggpack_write(opb, ci->residues - 1, 6);
for (i = 0; i < ci->residues; i++) {
oggpack_write(opb, ci->residue_type[i], 16);
_residue_P[ci->residue_type[i]]->pack(ci->residue_param[i], opb);
}
/* maps */
oggpack_write(opb, ci->maps - 1, 6);
for (i = 0; i < ci->maps; i++) {
oggpack_write(opb, ci->map_type[i], 16);
_mapping_P[ci->map_type[i]]->pack(vi, ci->map_param[i], opb);
}
/* modes */
oggpack_write(opb, ci->modes - 1, 6);
for (i = 0; i < ci->modes; i++) {
oggpack_write(opb, ci->mode_param[i]->blockflag, 1);
oggpack_write(opb, ci->mode_param[i]->windowtype, 16);
oggpack_write(opb, ci->mode_param[i]->transformtype, 16);
oggpack_write(opb, ci->mode_param[i]->mapping, 8);
}
oggpack_write(opb, 1, 1);
return (0);
err_out:
return (-1);
}
int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op) {
oggpack_buffer opb;
oggpack_writeinit(&opb);
if (_vorbis_pack_comment(&opb, vc)) {
oggpack_writeclear(&opb);
return OV_EIMPL;
}
op->packet = _ogg_malloc(oggpack_bytes(&opb));
memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
op->bytes = oggpack_bytes(&opb);
op->b_o_s = 0;
op->e_o_s = 0;
op->granulepos = 0;
op->packetno = 1;
oggpack_writeclear(&opb);
return 0;
}
int vorbis_analysis_headerout(vorbis_dsp_state *v, vorbis_comment *vc,
ogg_packet *op, ogg_packet *op_comm,
ogg_packet *op_code) {
int ret = OV_EIMPL;
vorbis_info *vi = v->vi;
oggpack_buffer opb;
private_state *b = v->backend_state;
if (!b || vi->channels <= 0) {
ret = OV_EFAULT;
goto err_out;
}
/* first header packet **********************************************/
oggpack_writeinit(&opb);
if (_vorbis_pack_info(&opb, vi))
goto err_out;
/* build the packet */
if (b->header)
_ogg_free(b->header);
b->header = _ogg_malloc(oggpack_bytes(&opb));
memcpy(b->header, opb.buffer, oggpack_bytes(&opb));
op->packet = b->header;
op->bytes = oggpack_bytes(&opb);
op->b_o_s = 1;
op->e_o_s = 0;
op->granulepos = 0;
op->packetno = 0;
/* second header packet (comments) **********************************/
oggpack_reset(&opb);
if (_vorbis_pack_comment(&opb, vc))
goto err_out;
if (b->header1)
_ogg_free(b->header1);
b->header1 = _ogg_malloc(oggpack_bytes(&opb));
memcpy(b->header1, opb.buffer, oggpack_bytes(&opb));
op_comm->packet = b->header1;
op_comm->bytes = oggpack_bytes(&opb);
op_comm->b_o_s = 0;
op_comm->e_o_s = 0;
op_comm->granulepos = 0;
op_comm->packetno = 1;
/* third header packet (modes/codebooks) ****************************/
oggpack_reset(&opb);
if (_vorbis_pack_books(&opb, vi))
goto err_out;
if (b->header2)
_ogg_free(b->header2);
b->header2 = _ogg_malloc(oggpack_bytes(&opb));
memcpy(b->header2, opb.buffer, oggpack_bytes(&opb));
op_code->packet = b->header2;
op_code->bytes = oggpack_bytes(&opb);
op_code->b_o_s = 0;
op_code->e_o_s = 0;
op_code->granulepos = 0;
op_code->packetno = 2;
oggpack_writeclear(&opb);
return (0);
err_out:
memset(op, 0, sizeof(*op));
memset(op_comm, 0, sizeof(*op_comm));
memset(op_code, 0, sizeof(*op_code));
if (b) {
oggpack_writeclear(&opb);
if (b->header)
_ogg_free(b->header);
if (b->header1)
_ogg_free(b->header1);
if (b->header2)
_ogg_free(b->header2);
b->header = NULL;
b->header1 = NULL;
b->header2 = NULL;
}
return (ret);
}
double vorbis_granule_time(vorbis_dsp_state *v, ogg_int64_t granulepos) {
if (granulepos == -1)
return -1;
/* We're not guaranteed a 64 bit unsigned type everywhere, so we
have to put the unsigned granpo in a signed type. */
if (granulepos >= 0) {
return ((double)granulepos / v->vi->rate);
} else {
ogg_int64_t granuleoff = 0xffffffff;
granuleoff <<= 31;
granuleoff |= 0x7ffffffff;
return (((double)granulepos + 2 + granuleoff + granuleoff) / v->vi->rate);
}
}
const char *vorbis_version_string(void) { return GENERAL_VENDOR_STRING; }
| 28.666667 | 80 | 0.591182 |
6096866c9bb72f1282da43fef564dcd39275b09d | 2,228 | h | C | iverilog-parser/PDelays.h | gokhankici/iodine | 7b5d00eb37bf31b9d1c4e69e176271244e86b26f | [
"MIT"
] | 9 | 2019-05-31T08:52:38.000Z | 2021-12-12T15:31:00.000Z | iverilog-parser/PDelays.h | gokhankici/xenon | d749abd865f2017cda323cf63cf38b585de9e7af | [
"MIT"
] | 1 | 2019-08-16T23:42:16.000Z | 2019-09-01T20:06:52.000Z | iverilog-parser/PDelays.h | gokhankici/iodine | 7b5d00eb37bf31b9d1c4e69e176271244e86b26f | [
"MIT"
] | null | null | null | #ifndef IVL_PDelays_H
#define IVL_PDelays_H
/*
* Copyright (c) 1999-2014 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
# include "svector.h"
# include <string>
# include <list>
# include <iostream>
#include "Visitor.h"
#ifdef __GNUC__
#if __GNUC__ > 2
using namespace std;
#endif
#endif
class Design;
class NetScope;
class NetExpr;
class PExpr;
/*
* Various PForm objects can carry delays. These delays include rise,
* fall and decay times. This class arranges to carry the triplet.
*/
class PDelays {
public:
PDelays();
~PDelays();
/* Set the delay expressions. If the delete_flag is true, then
this object takes ownership of the expressions, and will
delete it in the destructor. */
void set_delay(PExpr*);
void set_delays(const list<PExpr*>*del, bool delete_flag=true);
unsigned delay_count() const;
void eval_delays(Design*des, NetScope*scope,
NetExpr*&rise_time,
NetExpr*&fall_time,
NetExpr*&decay_time,
bool as_nets_flag =false) const;
void dump_delays(ostream&out) const;
private:
VISITOR_FRIENDS;
PExpr* delay_[3];
bool delete_flag_;
private: // not implemented
PDelays(const PDelays&);
PDelays& operator= (const PDelays&);
public:
virtual void accept(Visitor* v) {
v->visit(this);
}
};
ostream& operator << (ostream&o, const PDelays&);
#endif /* IVL_PDelays_H */
| 26.52381 | 84 | 0.679533 |
e4f0d8f5b3c38d9f3aee74566f6c0a77c98cf25e | 714 | h | C | tools/miso/pysplicing/include/pyerror.h | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
] | 1 | 2021-02-05T13:19:58.000Z | 2021-02-05T13:19:58.000Z | tools/miso/pysplicing/include/pyerror.h | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
] | null | null | null | tools/miso/pysplicing/include/pyerror.h | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
] | null | null | null |
#ifndef PYSPLICING_ERROR_H
#define PYSPLICING_ERROR_H
#include <Python.h>
#include "splicing_error.h"
PyObject* splicingmodule_handle_splicing_error(void);
void splicingmodule_splicing_warning_hook(const char *reason,
const char *file,
int line, int splicing_errno);
void splicingmodule_splicing_error_hook(const char *reason, const char *file,
int line, int splicing_errno);
extern PyObject* splicingmodule_InternalError;
#define SPLICING_PYCHECK(a) do { \
int splicing_i_pyret=(a); \
if (SPLICING_UNLIKELY(splicing_i_pyret != 0)) { \
splicingmodule_handle_splicing_error(); \
SPLICING_FINALLY_FREE(); \
return 0; \
} } while (0)
#endif
| 27.461538 | 77 | 0.717087 |
c275b7d365b4494864fa1f6cf81a6d43a59795c2 | 58 | h | C | implementations/ugene/src/include/U2Core/CopyFileTask.h | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/include/U2Core/CopyFileTask.h | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/include/U2Core/CopyFileTask.h | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | #include "../../corelibs/U2Core/src/tasks/CopyFileTask.h"
| 29 | 57 | 0.724138 |
5279738b3c34b894771257ac86c64af0177a05e4 | 426 | h | C | macgyver/FastMath.h | fmidev/smartmet-library-macgyver | c91c28535c5df15856caf59e1d29f96917378eca | [
"MIT"
] | null | null | null | macgyver/FastMath.h | fmidev/smartmet-library-macgyver | c91c28535c5df15856caf59e1d29f96917378eca | [
"MIT"
] | 2 | 2017-03-13T18:40:43.000Z | 2022-02-08T11:47:22.000Z | macgyver/FastMath.h | fmidev/smartmet-library-macgyver | c91c28535c5df15856caf59e1d29f96917378eca | [
"MIT"
] | 1 | 2017-03-16T07:47:23.000Z | 2017-03-16T07:47:23.000Z | #pragma once
/*!
* \brief Fast replacements for math commands when compiler fast math options cannot be enabled
*/
namespace Fmi
{
// https://stackoverflow.com/questions/824118/why-is-floor-so-slow/30308919#30308919
inline long floor(double x)
{
return static_cast<long>(x) - (x < static_cast<long>(x));
}
inline long ceil(double x)
{
return static_cast<long>(x) + (x > static_cast<long>(x));
}
} // namespace Fmi
| 19.363636 | 95 | 0.706573 |
0a0d4c58f18c4a5761f7806648ee5bd02b2b64c8 | 12,565 | h | C | 3rdParty/ArNetworking/include/ArServerHandlerPopup.h | bellonemauro/myARIAtestApp | 8223b5833ccf37cf9f503337858a46544d36a19c | [
"Linux-OpenIB"
] | null | null | null | 3rdParty/ArNetworking/include/ArServerHandlerPopup.h | bellonemauro/myARIAtestApp | 8223b5833ccf37cf9f503337858a46544d36a19c | [
"Linux-OpenIB"
] | null | null | null | 3rdParty/ArNetworking/include/ArServerHandlerPopup.h | bellonemauro/myARIAtestApp | 8223b5833ccf37cf9f503337858a46544d36a19c | [
"Linux-OpenIB"
] | null | null | null | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#ifndef ARSERVERHANDLERPOPUP_H
#define ARSERVERHANDLERPOPUP_H
#include "Aria.h"
#include "ArServerBase.h"
class ArServerClient;
class ArServerHandlerPopupInfo;
/// Class for having generic popups appear in MobileEyes (created on the server)
/**
TODO make the callbacks actually happen
**/
class ArServerHandlerPopup
{
public:
/// Constructor
AREXPORT ArServerHandlerPopup(ArServerBase *server);
/// Destructor
AREXPORT virtual ~ArServerHandlerPopup();
/// Creates a new popup
AREXPORT ArTypes::Byte4 createPopup(
ArServerHandlerPopupInfo *popupInfo,
ArFunctor2<ArTypes::Byte4, int> *callback = NULL);
/// Cancels a popup with the ID
AREXPORT void closePopup(ArTypes::Byte4 id,
const char *closeMessage);
/// The call from the network that the popup was clicked
/// @internal
AREXPORT void netPopupClicked(ArServerClient *client,
ArNetPacket *packet);
/// The call from the network for getting the popup list
/// @internal
AREXPORT void netPopupList(ArServerClient *client,
ArNetPacket *packet);
/// Our cycle callback
/// @internal
AREXPORT void serverCycleCallback(void);
enum PopupType {
NOICON = 0, ///< No icon at all
INFORMATION = 1, ///< Just an informational message
WARNING = 2, ///< A warning
CRITICAL = 3, ///< A critical problem (program failure likely)
QUESTION = 4 ///< A question
};
protected:
ArServerBase *myServer;
class PopupData {
public:
/// Constructor (copies and owns popupInfo, leaves callback)
PopupData(ArServerHandlerPopupInfo *popupInfo,
ArTypes::Byte4 id,
ArFunctor2<ArTypes::Byte4, int> *callback);
/// Destructor, deleted the popup info
virtual ~PopupData();
/// The popup info
ArServerHandlerPopupInfo *myPopupInfo;
/// The functor to call when its done
ArFunctor2<ArTypes::Byte4, int> *myCallback;
/// When we started this popup
ArTime myStarted;
/// The popup this was serving
ArTypes::Byte4 myID;
};
void buildPacket(ArNetPacket *sendingPacket, PopupData *popupData);
ArMutex myDataMutex;
std::map<ArTypes::Byte4, PopupData *> myMap;
ArTypes::Byte4 myLastID;
ArTime myLastTimeCheck;
ArFunctor2C<ArServerHandlerPopup, ArServerClient*,
ArNetPacket *> myNetPopupClickedCB;
ArFunctor2C<ArServerHandlerPopup, ArServerClient*,
ArNetPacket *> myNetPopupListCB;
ArFunctorC<ArServerHandlerPopup> myServerCycleCB;
};
/// Holds the information for a popup
/**
This holds the information for the popup.... So there's a message
box with the title which has in it the message, and has between 1
and 3 buttons (button0, button1, and button2) with labels of
button0Label, button1Label, and button2Label (if the label is empty
or NULL then there'll be no button), the default button of
defaultButtonNumber (0 - 2) and the escape button number of
escapeButtonNumber (0 - 2)... when a button is pushed the
@param ignoreIdentifier The identifier to use for ignoring these
boxes, this should be NULL or empty if you don't want this
particular box to be able to be ignored (if any popup with this
identifier is already being ignored this one will be too)
@param title The title of the box (displayed in the titlebar)
@param message The string that will be displayed in the message box
(the point of the whole thing)
@param popupType The type of popup this is, which controls the icon
displayed, may someday affect behavior
@param defaultButtonPressed The button that enter defaults to (This
should be whatever is most likely)
@param escapeButtonPressed The button that escape defaults to (this
should be doesn't change the state, ie like cancel), this also
should be whats returned if the X is hit.
@param button0Label The label that is displayed on button 0, the
leftmost button
@param timeoutInSeconds the number of seconds we should give people
to respond to the popup before timing it out, 0 means leave it up
forever (note that no clients may be watching this or no one may be
at the console and use this option wisely (way too many untimed out
popups could bog down the server))
@param timeoutString The string that will be displayed if a timeout
happens
@param button0Pressed The string that will be put into the box if
button0 is pressed (this is mainly so that with multiple clients
connected the other clients will get feedback)
@param button1Label The label that is displayed on button 1 (the
middle button if there are 3, right button if there are two)
@param button1Pressed The string that will be put into the box if
button1 is pressed (this is mainly so that with multiple clients
connected the other clients will get feedback)
@param button2Label The label that is displayed on button 2 (the
right button)
@param button2Pressed The string that will be put into the box if
button2 is pressed (this is mainly so that with multiple clients
connected the other clients will get feedback)
**/
class ArServerHandlerPopupInfo
{
public:
/// Constructor
AREXPORT ArServerHandlerPopupInfo(
const char *ignoreIdentifier, const char *title,
const char *message, ArServerHandlerPopup::PopupType popupType,
ArTypes::Byte defaultButtonNumber,
ArTypes::Byte escapeButtonNumber,
int timeoutInSeconds, const char *timeoutString,
const char *button0Label, const char *button0Pressed,
const char *button1Label = "", const char *button1Pressed = "",
const char *button2Label = "", const char *button2Pressed = "");
/// Destructor
AREXPORT virtual ~ArServerHandlerPopupInfo();
/// Copy constructor
AREXPORT ArServerHandlerPopupInfo(const ArServerHandlerPopupInfo &popupInfo);
/// Assignment operator
AREXPORT ArServerHandlerPopupInfo &operator=(
const ArServerHandlerPopupInfo &popupInfo);
/// Gets the popup identifer (this is used only for ignoring popups, if empty or NULL then it can't be ignored)
const char *getIgnoreIdentifier(void) { return myIgnoreIdentifier.c_str(); }
/// Gets the title (the title of the popup box)
const char *getTitle(void) { return myTitle.c_str(); }
/// Gets the message (the long string that is displayed that explains things)
const char *getMessage(void) { return myMessage.c_str(); }
/// Gets the type (the icon thats displayed and what type of popup it is)
ArServerHandlerPopup::PopupType getPopupType(void) { return myPopupType; }
/// Gets the default button number (whats pressed when enter is hit)
ArTypes::Byte getDefaultButtonNumber(void) { return myDefaultButtonNumber; }
/// Gets the escape button number (whats pressed when escape is hit)
ArTypes::Byte getEscapeButtonNumber(void) { return myEscapeButtonNumber; }
/// Gets the timeout in seconds (0 is never)
int getTimeout(void) { return myTimeout; }
/// Gets the timeout string (the string that is displayed on the popup if timeout occurs)
const char * getTimeoutString(void)
{ return myTimeoutString.c_str(); }
/// Gets the button0Label (the label on the leftmost button, must have a label)
const char *getButton0Label(void) { return myButton0Label.c_str(); }
/// Gets the button0Pressed (string sent as box disppears if this button is pressed)
const char *getButton0Pressed(void) { return myButton0Pressed.c_str(); }
/// Gets the button1Label (the label on the middle button, empty string or NULL for no button)
const char *getButton1Label(void) { return myButton1Label.c_str(); }
/// Gets the button1Pressed (string sent as box disppears if this button is pressed)
const char *getButton1Pressed(void) { return myButton1Pressed.c_str(); }
/// Gets the button2Label (the label on the right button, empty string or NULL for no button)
const char *getButton2Label(void) { return myButton2Label.c_str(); }
/// Gets the button2Pressed (string sent as box disppears if this button is pressed)
const char *getButton2Pressed(void) { return myButton2Pressed.c_str(); }
/// Gets the popup identifer (this is used only for ignoring popups, if empty or NULL then it can't be ignored)
void setIgnoreIdentifier(const char *identifier)
{ if (identifier != NULL) myIgnoreIdentifier = identifier; else myIgnoreIdentifier = ""; }
/// Sets the title (the title of the popup box)
void setTitle(const char *title)
{ if (title != NULL) myTitle = title; else myTitle = ""; }
/// Sets the message (the long string that is displayed that explains things)
void setMessage(const char *message)
{ if (message != NULL) myMessage = message; else myMessage = ""; }
/// Sets the type (the icon thats displayed and what type of popup it is)
void setPopupType(ArServerHandlerPopup::PopupType popupType)
{ myPopupType = popupType; }
/// Sets the default button number (whats pressed when enter is hit)
void setDefaultButtonNumber(ArTypes::Byte defaultButtonNumber)
{ myDefaultButtonNumber = defaultButtonNumber; }
/// Sets the escape button number (whats pressed when escape is hit)
void setEscapeButtonNumber(ArTypes::Byte escapeButtonNumber)
{ myEscapeButtonNumber = escapeButtonNumber; }
/// Sets the timeout in seconds (0 is never)
void setTimeout(int timeoutInSeconds)
{ myTimeout = timeoutInSeconds; }
/// Sets the timeout string (the string that is displayed on the popup if timeout occurs)
void setTimeoutString(const char *timeoutString)
{ if (timeoutString != NULL) myTimeoutString = timeoutString; else myTimeoutString = ""; }
/// Sets the button0Label (the label on the leftmost button, must have a label)
void setButton0Label(const char *label)
{ if (label != NULL) myButton0Label = label; else myButton0Label = ""; }
/// Sets the button0Pressed (string sent as box disppears if this button is pressed)
void setButton0Pressed(const char *pressed)
{ if (pressed != NULL) myButton0Pressed = pressed; else myButton0Pressed = ""; }
/// Sets the button1Label (the label on the middle button, empty string or NULL for no button)
void setButton1Label(const char *label)
{ if (label != NULL) myButton1Label = label; else myButton1Label = ""; }
/// Sets the button1Pressed (string sent as box disppears if this button is pressed)
void setButton1Pressed(const char *pressed)
{ if (pressed != NULL) myButton1Pressed = pressed; else myButton1Pressed = ""; }
/// Sets the button2Label (the label on the right button, empty string or NULL for no button)
void setButton2Label(const char *label)
{ if (label != NULL) myButton2Label = label; else myButton2Label = ""; }
/// Sets the button2Pressed (string sent as box disppears if this button is pressed)
void setButton2Pressed(const char *pressed)
{ if (pressed != NULL) myButton2Pressed = pressed; else myButton2Pressed = ""; }
protected:
std::string myIgnoreIdentifier;
std::string myTitle;
std::string myMessage;
ArServerHandlerPopup::PopupType myPopupType;
ArTypes::Byte myDefaultButtonNumber;
ArTypes::Byte myEscapeButtonNumber;
int myTimeout;
std::string myTimeoutString;
std::string myButton0Label;
std::string myButton0Pressed;
std::string myButton1Label;
std::string myButton1Pressed;
std::string myButton2Label;
std::string myButton2Pressed;
};
#endif // ARSERVERHANDLERPOPUP_H
| 44.399293 | 113 | 0.737923 |
ddf7127a0017abd246976c5d0c54d8f3d944d593 | 2,575 | c | C | src/Problem19.c | jonarivas/EulerProject | 6542102f5ad9f778183804b31fc4c53e7649379a | [
"MIT"
] | 1 | 2015-02-13T18:20:18.000Z | 2015-02-13T18:20:18.000Z | src/Problem19.c | jonarivas/EulerProject | 6542102f5ad9f778183804b31fc4c53e7649379a | [
"MIT"
] | null | null | null | src/Problem19.c | jonarivas/EulerProject | 6542102f5ad9f778183804b31fc4c53e7649379a | [
"MIT"
] | null | null | null | /*
============================================================================
Name : Euler.c
Author : Jonathan Rivas
Version :
Copyright :
Description : Problem #19
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
struct date{
int day;
int month;
int year;
int dayofweek;
};
enum months{
january = 0,
february,
march,
april,
may,
june,
july,
august,
september,
october,
november,
december,
totalmonths
};
enum DAY
{
sunday = 0,
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
totaldays
};
int isLeapYear(int year){
if (year % 4 == 0){
if (year % 100 == 0){
if (year % 400 == 0){
return 1;
}
else{
return 0;
}
}
return 1;
}
return 0;
}
void nextDay(struct date *current){
int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
months[february] += isLeapYear(current->year);
current->day = (current->day+1) % months[current->month];
if (current->day == 0){
current->month = (current->month + 1) % totalmonths;
if (current->month == 0){
current->year++;
}
}
current->dayofweek = (current->dayofweek + 1 )% totaldays;
}
int compareDays(struct date *date1, struct date *date2){
if (date1->year == date2->year && date1->month == date2->month && date1->day == date2->day){
return 1;
}
return 0;
}
void printDay(struct date *current){
printf("current day is %d %d/%d/%d\n", current->dayofweek, current->day +1 , current->month + 1, current->year);
}
struct date * createDate(int dayofweek, int day, int month, int year){
struct date *date;
date = (struct date *)malloc(sizeof(struct date));
date->dayofweek = dayofweek;
date->day = day - 1;
date->month = month;
date->year = year;
return date;
}
int isFirstDayofMonth(struct date * day){
if (day->day == 0){
return 1;
}
else{
return 0;
}
}
int main(void) {
struct timeval stop, start;
gettimeofday(&start, NULL);
struct date *day, *lastday, *startdate;
int numberofSundays = 0;
day = createDate(monday, 1, january, 1900);
startdate = createDate(monday, 1, january, 1901);
lastday = createDate(monday,31, december, 2000);
while(!compareDays(day, startdate)){
nextDay(day);
}
nextDay(lastday);
while(!compareDays(day, lastday)){
if (day->dayofweek == sunday && isFirstDayofMonth(day)){
numberofSundays++;
}
nextDay(day);
}
printf("number of sundays: %d", numberofSundays);
gettimeofday(&stop, NULL);
printf("\ntook %lu usec\n", stop.tv_usec - start.tv_usec);
return 0;
}
| 19.360902 | 113 | 0.596505 |
25e5e67131ad42ea0df0fcbd6b74fb573ee6d5e1 | 1,003 | c | C | C00/ex04/ft_is_negative.c | Karlsons/42_Wolfsburg | 3ea66f1b50126e9d2e700e5861ac086c37f2436e | [
"MIT"
] | null | null | null | C00/ex04/ft_is_negative.c | Karlsons/42_Wolfsburg | 3ea66f1b50126e9d2e700e5861ac086c37f2436e | [
"MIT"
] | null | null | null | C00/ex04/ft_is_negative.c | Karlsons/42_Wolfsburg | 3ea66f1b50126e9d2e700e5861ac086c37f2436e | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_is_negative.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kkalnins <kkalnins@student.42wolfsburg. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/10 19:47:38 by kkalnins #+# #+# */
/* Updated: 2021/02/12 22:47:24 by kkalnins ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_is_negative(int n)
{
if (n >= 0)
write(1, "P", 1);
else
write(1, "N", 1);
}
| 45.590909 | 80 | 0.174477 |
202785eb48b30d84ba5ebabd95fe608383b5bbdb | 1,160 | h | C | tool/ResultFile.h | akb825/VertexFormatConvert | 3e664b07f94ae36a7ab9cfbaed29d5254975c138 | [
"Apache-2.0"
] | 1 | 2020-09-20T16:27:08.000Z | 2020-09-20T16:27:08.000Z | tool/ResultFile.h | akb825/VertexFormatConvert | 3e664b07f94ae36a7ab9cfbaed29d5254975c138 | [
"Apache-2.0"
] | null | null | null | tool/ResultFile.h | akb825/VertexFormatConvert | 3e664b07f94ae36a7ab9cfbaed29d5254975c138 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020-2021 Aaron Barany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <VFC/Config.h>
#include <VFC/IndexData.h>
#include <VFC/VertexFormat.h>
#include <VFC/VertexValue.h>
struct IndexFileData
{
std::uint32_t count;
std::int32_t baseVertex;
const char* dataFile;
};
struct Bounds
{
vfc::VertexValue min;
vfc::VertexValue max;
};
std::string resultFile(const std::vector<vfc::VertexFormat>& vertexFormat,
const std::vector<std::vector<Bounds>>& bounds, const std::vector<std::string>& vertexData,
std::uint32_t vertexCount, vfc::IndexType indexType,
const std::vector<IndexFileData>& indexData);
| 28.292683 | 92 | 0.742241 |
ee7e4152fd7c9283a8103e413ca141dd4deab9fb | 19,784 | h | C | src/infact/environment.h | alex-quiterio/infact | 478b005263534b5809dcd67bef280fbdecec6392 | [
"BSD-3-Clause"
] | 79 | 2015-04-27T17:15:04.000Z | 2021-12-28T14:03:09.000Z | src/infact/environment.h | alan0526/infact | 449cff906c46de086111d65fd7b15897d3e1f05f | [
"BSD-3-Clause"
] | null | null | null | src/infact/environment.h | alan0526/infact | 449cff906c46de086111d65fd7b15897d3e1f05f | [
"BSD-3-Clause"
] | 23 | 2015-04-22T10:06:54.000Z | 2021-09-10T11:18:32.000Z | // Copyright 2014, Google 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:
//
// * 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 Google 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
// 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.
// -----------------------------------------------------------------------------
//
//
/// \file
/// Provides an interface for an Environment, which contains a map
/// from variables of a specific type (primitives, \link
/// infact::Factory Factory\endlink-constructible objects, or
/// vectors thereof) to their values.
/// \author dbikel@google.com (Dan Bikel)
#ifndef INFACT_ENVIRONMENT_H_
#define INFACT_ENVIRONMENT_H_
#define VAR_MAP_DEBUG 0
#include <sstream>
#include <vector>
#include "error.h"
#include "stream-init.h"
#include "stream-tokenizer.h"
namespace infact {
using std::cerr;
using std::endl;
using std::ostream;
using std::ostringstream;
using std::shared_ptr;
using std::unordered_map;
using std::unordered_set;
using std::vector;
class Environment;
/// A base class for a mapping from variables of a specific type to their
/// values.
class VarMapBase {
public:
/// Constructs a base class for a concrete implementation providing
/// a mapping from variables of a particular type to their values.
///
/// \param name the type name of the variables in this instance
/// \param env the \link infact::Environment Environment \endlink
/// that wraps this VarMapBase instance
/// \param is_primitive whether this instance contains primitive or primitive
/// vector variables
VarMapBase(const string &name, Environment *env, bool is_primitive) :
name_(name), env_(env), is_primitive_(is_primitive) { }
virtual ~VarMapBase() { }
/// Returns whether this instance contains primitive or primtive
/// vector variables.
virtual bool IsPrimitive() const { return is_primitive_; }
/// Returns the type name of the variables of this instance.
virtual const string &Name() const { return name_; }
/// Returns whether the specified variable has a definition in this
/// environment.
virtual bool Defined(const string &varname) const = 0;
/// Reads the next value (primitive or spec for constructing a \link
/// infact::Factory Factory\endlink-constructible object) from the
/// specified stream tokenizer and sets the specified variable to
/// that value.
virtual void ReadAndSet(const string &varname, StreamTokenizer &st) = 0;
/// Prints out a human-readable string to the specified output
/// stream containing the variables, their type and, if primitive,
/// their values.
virtual void Print(ostream &os) const = 0;
/// Returns a newly constructed copy of this VarMap.
virtual VarMapBase *Copy(Environment *env) const = 0;
protected:
/// To allow proper implementation of Copy in VarMapBase implementation,
/// since we don't get copying of base class' members for free.
void SetMembers(const string &name, Environment *env, bool is_primitive) {
name_ = name;
env_ = env;
is_primitive_ = is_primitive;
}
/// The type name of this VarMap.
string name_;
/// The Environment that holds this VarMap instance.
Environment *env_;
/// Whether this VarMap instance holds variables of primitive type
/// or vector of primitives.
bool is_primitive_;
};
/// An interface for an environment in which variables of various
/// types are mapped to their values.
class Environment {
public:
virtual ~Environment() { }
/// Returns whether the specified variable has been defined in this
/// environment.
virtual bool Defined(const string &varname) const = 0;
/// Sets the specified variable to the value obtained from the following
/// tokens available from the specified token stream.
virtual void ReadAndSet(const string &varname, StreamTokenizer &st,
const string type = "") = 0;
/// Retrieves the type name of the specified variable.
virtual const string &GetType(const string &varname) const = 0;
/// Retrieves the VarMap instance for the specified variable.
virtual VarMapBase *GetVarMap(const string &varname) = 0;
/// Retrieves the VarMap instance for the specified type, or nullptr if
/// there is no such VarMap. The specified type must either be a
/// primitive type, a primitive vector type, a \link
/// infact::Factory Factory\endlink-constructible type or a vector
/// of \link infact::Factory Factory\endlink-constructible types.
///
/// If the specified type is a concrete implementation of a \link
/// infact::Factory Factory\endlink-constructible type, then the
/// pointer to the VarMap for its abstract base type is returned;
/// for example, if the specified type is <tt>"RankFeatureExtactor"</tt>
/// then this method will return the VarMap containing
/// <tt>"FeatureExtractor"</tt> instances.
///
/// TODO(dbikel): Support returning the VarMap for vectors of
/// abstract type when the user specifies a vector of concrete type.
/// E.g., if the specified type is "RankFeatureExtractor[]" then
/// this method should return the VarMap containing
/// "FeatureExtractor[]" instances.
virtual VarMapBase *GetVarMapForType(const string &type) = 0;
/// Prints a human-readable string of all the variables in this environment,
/// their types and, if primitive, their values.
virtual void Print(ostream &os) const = 0;
/// Returns a copy of this environment.
virtual Environment *Copy() const = 0;
/// Prints out a human-readable string with the names of all abstract base
/// types and their concrete implementations that may be constructed.
/// \see infact::FactoryContainer::Print
virtual void PrintFactories(ostream &os) const = 0;
/// A static factory method to create a new, empty Environment instance.
static Environment *CreateEmpty();
};
/// A template class that helps print out values with ostream& operator
/// support and vectors of those values.
///
/// \tparam T the type to print to an ostream
template <typename T>
class ValueString {
public:
string ToString(const T &value) const {
ostringstream oss;
oss << value;
return oss.str();
}
};
/// A specialization of the ValueString class to support printing of
/// string values.
template<>
class ValueString<string> {
public:
string ToString(const string &value) const {
return "\"" + value + "\"";
}
};
/// A specialization of the ValueString class to support printing of
/// boolean values.
template<>
class ValueString<bool> {
public:
string ToString(const bool &value) const {
return value ? "true" : "false";
}
};
/// A partial specialization of the ValueString class to support
/// printing of shared_ptr's to objects, where we simply print the typeid
/// name followed by a colon character followed by the pointer address.
template<typename T>
class ValueString<shared_ptr<T> > {
public:
string ToString(const shared_ptr<T> &value) const {
ostringstream oss;
oss << "<" << typeid(shared_ptr<T>).name() << ":" << value.get() << ">";
return oss.str();
}
};
/// A partial specialization of the ValueString class to support
/// printing of vectors of values.
///
/// \tparam T the element type for a vector to be printed out to an ostream
template <typename T>
class ValueString<vector<T> > {
public:
string ToString(const vector<T> &value) const {
ostringstream oss;
oss << "{";
typename vector<T>::const_iterator it = value.begin();
ValueString<T> value_string;
if (it != value.end()) {
oss << value_string.ToString(*it);
++it;
}
for (; it != value.end(); ++it) {
oss << ", " << value_string.ToString(*it);
}
oss << "}";
return oss.str();
}
};
/// A partial implementation of the VarMapBase interface that is common
/// to both VarMap<T> and the VarMap<vector<T> > partial specialization.
///
/// In a delightful twist, this partial implementation of VarMapBase
/// uses the curiously recurring template pattern (CRTP) in order to
/// implement the \link infact::VarMapBase::Copy VarMapBase::Copy
/// \endlink method, as well as the protected method \link
/// ReadAndSetFromExistingVariable\endlink.
///
/// \tparam T the type of variables stored in this (partial
/// implementation of a) variable map
/// \tparam Derived the type of the class using this as its base class
/// (a.k.a. CRTP, or the "curiously recurring template pattern")
template <typename T, typename Derived>
class VarMapImpl : public VarMapBase {
public:
VarMapImpl(const string &name, Environment *env, bool is_primitive = true) :
VarMapBase(name, env, is_primitive) { }
virtual ~VarMapImpl() { }
// Accessor methods
/// Assigns the value of the specified variable to the object pointed to
/// by the <tt>value</tt> parameter.
///
/// \return whether the specified variable exists and the assignment
/// was successful
bool Get(const string &varname, T *value) const {
typename unordered_map<string, T>::const_iterator it = vars_.find(varname);
if (it == vars_.end()) {
return false;
} else {
*value = it->second;
return true;
}
}
/// \copydoc VarMapBase::Defined
virtual bool Defined(const string &varname) const {
return vars_.find(varname) != vars_.end();
}
/// Sets the specified variable to the specified value.
void Set(const string &varname, T value) {
vars_[varname] = value;
}
/// \copydoc VarMapBase::Print
virtual void Print(ostream &os) const {
ValueString<T> value_string;
for (typename unordered_map<string, T>::const_iterator it = vars_.begin();
it != vars_.end(); ++it) {
const T& value = it->second;
os << Name() << " "
<< it->first
<< " = "
<< value_string.ToString(value)
<< ";\n";
}
os.flush();
}
/// \copydoc VarMapBase::Copy
virtual VarMapBase *Copy(Environment *env) const {
// Invoke Derived class' copy constructor.
const Derived *derived = dynamic_cast<const Derived *>(this);
if (derived == nullptr) {
Error("bad dynamic cast");
}
Derived *var_map_copy = new Derived(*derived);
var_map_copy->SetMembers(name_, env, is_primitive_);
return var_map_copy;
}
protected:
/// Checks if the next token is an identifier and is a variable in
/// the environment, and, if so, sets varname to the variable’s value.
bool ReadAndSetFromExistingVariable(const string &varname,
StreamTokenizer &st) {
if (env()->Defined(st.Peek())) {
VarMapBase *var_map = env()->GetVarMap(st.Peek());
Derived *typed_var_map = dynamic_cast<Derived *>(var_map);
if (typed_var_map != nullptr) {
// Finally consume variable.
string rhs_variable = st.Next();
T value = T();
// Retrieve rhs variable's value.
bool success = typed_var_map->Get(rhs_variable, &value);
// Set varname to the same value.
if (VAR_MAP_DEBUG >= 1) {
cerr << "VarMap<" << Name() << ">::ReadAndSet: "
<< "setting variable "
<< varname << " to same value as rhs variable " << rhs_variable
<< endl;
}
if (success) {
Set(varname, value);
} else {
// Error: we couldn't find the varname in this VarMap.
if (VAR_MAP_DEBUG >= 1) {
cerr << "VarMap<" << Name() << ">::ReadAndSet: no variable "
<< rhs_variable << " found " << endl;
}
}
} else {
// Error: inferred or declared type of varname is different
// from the type of the rhs variable.
if (VAR_MAP_DEBUG >= 1) {
cerr << "VarMap<" << Name() << ">::ReadAndSet: variable "
<< st.Peek() << " is of type " << var_map->Name()
<< " but expecting " << typeid(T).name() << endl;
}
}
return true;
} else {
return false;
}
}
/// A protected method to access the environment contained by this
/// VarMapBase instance, for the two concrete VarMap implementations, below.
Environment *env() { return VarMapBase::env_; }
private:
unordered_map<string, T> vars_;
};
/// A container to hold the mapping between named variables of a specific
/// type and their values.
///
/// \tparam T the type of variables held by this variable map
template <typename T>
class VarMap : public VarMapImpl<T, VarMap<T> > {
public:
typedef VarMapImpl<T, VarMap<T> > Base;
/// Constructs a mapping from variables of a particular type to their values.
///
/// \param name the type name of the variables in this instance
/// \param env the \link infact::Environment Environment \endlink
/// that contains this VarMap instance
/// \param is_primitive whether this instance contains primitive or primitive
/// vector variables
VarMap(const string &name, Environment *env, bool is_primitive = true) :
Base(name, env, is_primitive) { }
virtual ~VarMap() { }
/// \copydoc VarMapBase::ReadAndSet
virtual void ReadAndSet(const string &varname, StreamTokenizer &st) {
if (VAR_MAP_DEBUG >= 1) {
cerr << "VarMap<" << Base::Name() << ">::ReadAndSet: "
<< "about to set varname " << varname << " of type "
<< typeid(T).name()
<< "; prev_token=" << st.PeekPrev() << "; next_tok=" << st.Peek()
<< endl;
}
if (!Base::ReadAndSetFromExistingVariable(varname, st)) {
T value;
Initializer<T> initializer(&value);
initializer.Init(st, Base::env());
this->Set(varname, value);
if (VAR_MAP_DEBUG >= 1) {
ValueString<T> value_string;
cerr << "VarMap<" << Base::Name() << ">::ReadAndSet: set varname "
<< varname << " to value " << value_string.ToString(value)<< endl;
}
}
}
};
/// A partial specialization to allow initialization of a vector of
/// values, where the values can either be literals (if T is a
/// primitive type), spec strings for constructing
/// \link Factory\endlink-constructible objects, or variable names (where each
/// variable must be of type T).
///
/// TODO(dbikel): Avoid repeating much of the unchanged implementation
/// from the non-specialized VarMap<T>, above, by using the PIMPL
/// design pattern (i.e., create VarMapImpl<T> that does the generic
/// stuff and have VarMap<T> contain a VarMapImpl<T> data member, and
/// have VarMap<vector<T>> contain a VarMapImpl<vector<T>> data
/// member.
///
/// \tparam T the element type for vectors stored in this variable map
template <typename T>
class VarMap<vector<T> > : public VarMapImpl<vector<T>, VarMap<vector<T> > > {
public:
typedef VarMapImpl<vector<T>, VarMap<vector<T> > > Base;
/// Constructs a mapping from variables of a particular type to their values.
///
/// \param name the type name of the variables in this instance
/// \param element_typename the type name of the elements of the vectors
/// held by this instance
/// \param env the \link infact::Environment Environment \endlink
/// that contains this VarMap instance
/// \param is_primitive whether the variables held in this variable map
/// are primitives or vectors of primitives
VarMap(const string &name, const string &element_typename, Environment *env,
bool is_primitive = true)
: Base(name, env, is_primitive), element_typename_(element_typename) { }
virtual ~VarMap() { }
virtual void ReadAndSet(const string &varname, StreamTokenizer &st) {
// First check if next token is an identifier and is a variable in
// the environment, set varname to its value.
if (!Base::ReadAndSetFromExistingVariable(varname, st)) {
// This entire block reads the array of values.
// Either the next token is an open brace (if reading tokens from
// within a Factory-constructible object's member init list), or
// else we just read an open brace (if Interpreter is reading tokens).
if (st.Peek() == "{") {
// Consume open brace.
st.Next();
} else {
ostringstream err_ss;
err_ss << "VarMap<vector<T>>: "
<< "error: expected '{' at stream position "
<< st.PeekPrevTokenStart() << " but found \""
<< st.PeekPrev() << "\"";
Error(err_ss.str());
}
vector<T> value;
int element_idx = 0;
while (st.Peek() != "}") {
// Copy the environment, since we create fake names for each element.
shared_ptr<Environment> env_ptr(Base::env()->Copy());
ostringstream element_name_oss;
element_name_oss << "____" << varname << "_" << (element_idx++)
<< "____";
string element_name = element_name_oss.str();
env_ptr->ReadAndSet(element_name, st, element_typename_);
VarMapBase *element_var_map =
env_ptr->GetVarMapForType(element_typename_);
VarMap<T> *typed_element_var_map =
dynamic_cast<VarMap<T> *>(element_var_map);
T element;
if (typed_element_var_map->Get(element_name, &element)) {
value.push_back(element);
} else {
ostringstream err_ss;
err_ss << "VarMap<" << Base::Name() << ">::ReadAndSet: trouble "
<< "initializing element " << (element_idx - 1)
<< " of variable " << varname;
Error(err_ss.str());
}
// Each vector element initializer must be followed by a comma
// or the final closing parenthesis.
if (st.Peek() != "," && st.Peek() != "}") {
ostringstream err_ss;
err_ss << "Initializer<vector<T>>: "
<< "error: expected ',' or '}' at stream position "
<< st.PeekTokenStart() << " but found \"" << st.Peek() << "\"";
Error(err_ss.str());
}
// Read comma, if present.
if (st.Peek() == ",") {
st.Next();
}
}
// Consume close brace.
st.Next();
// Finally, set the newly-constructed value.
this->Set(varname, value);
}
}
private:
string element_typename_;
};
} // namespace infact
#endif
| 37.048689 | 80 | 0.649717 |
ee347d248f18802b1bc8f2bea1ede415da8d4ce9 | 1,580 | h | C | patches/llvm/src/tools/clang/include/clang/CodeGen/PrefetchBuilder.h | systems-nuts/popcorn-compiler-alpine | 5c225c7d3055db83dc654b6b5525c34bbdacded1 | [
"Linux-OpenIB"
] | 30 | 2019-04-07T14:58:31.000Z | 2021-05-24T19:07:20.000Z | patches/llvm/src/tools/clang/include/clang/CodeGen/PrefetchBuilder.h | XRDevIEEE/popcorn-compiler | 2cb2eccc0c75b5963d9fec26ad80a7b881316b1d | [
"Linux-OpenIB"
] | 11 | 2018-07-24T19:31:26.000Z | 2020-09-03T08:56:23.000Z | patches/llvm/src/tools/clang/include/clang/CodeGen/PrefetchBuilder.h | XRDevIEEE/popcorn-compiler | 2cb2eccc0c75b5963d9fec26ad80a7b881316b1d | [
"Linux-OpenIB"
] | 17 | 2018-08-26T12:43:15.000Z | 2022-03-18T12:08:40.000Z | //===- Prefetch.h - Prefetching Analysis for Statements -----------*- C++ --*-//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface for building prefetching calls based on the
// prefetching analysis.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_PREFETCHBUILDER_H
#define LLVM_CLANG_CODEGEN_PREFETCHBUILDER_H
#include "CodeGenFunction.h"
#include "clang/Sema/PrefetchAnalysis.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
/// Generate calls to the prefetching API for analyzed regions.
class PrefetchBuilder {
public:
PrefetchBuilder(clang::CodeGen::CodeGenFunction *CGF)
: CGM(CGF->CGM), CGF(*CGF), Ctx(CGF->getContext()) {}
/// Emit prefetching API declarations.
void EmitPrefetchCallDeclarations();
/// Emit a prefetch call for a particular range of memory.
void EmitPrefetchCall(const PrefetchRange &P);
/// Emit a call to send the prefetch requests to the OS.
void EmitPrefetchExecuteCall();
// TODO print & dump
private:
clang::CodeGen::CodeGenModule &CGM;
clang::CodeGen::CodeGenFunction &CGF;
ASTContext &Ctx;
// Prefetch API declarations
llvm::Constant *Prefetch, *Execute;
Expr *buildAddrOf(Expr *ArrSub);
Expr *buildArrayIndex(VarDecl *Base, Expr *Subscript);
};
} // end namespace clang
#endif
| 27.719298 | 80 | 0.647468 |
f6d436995b0d1051bf8c75c2c7a51cae4eb1d890 | 2,377 | h | C | core/src/index/knowhere/knowhere/index/vector_index/IndexKDT.h | NeatNerdPrime/milvus | 98de0f87e99cd1ff86d8e63b91c76589b195abe1 | [
"Apache-2.0"
] | 1 | 2020-05-31T00:34:00.000Z | 2020-05-31T00:34:00.000Z | core/src/index/knowhere/knowhere/index/vector_index/IndexKDT.h | NeatNerdPrime/milvus | 98de0f87e99cd1ff86d8e63b91c76589b195abe1 | [
"Apache-2.0"
] | 1 | 2019-11-22T07:07:47.000Z | 2019-11-22T07:07:47.000Z | core/src/index/knowhere/knowhere/index/vector_index/IndexKDT.h | flydragon2018/milvus | fa1effdb91d9fd9710ff5a9ae519bd538e79b0b0 | [
"Apache-2.0"
] | 1 | 2021-05-23T15:04:01.000Z | 2021-05-23T15:04:01.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 <SPTAG/AnnService/inc/Core/VectorIndex.h>
#include <cstdint>
#include <memory>
#include "VectorIndex.h"
#include "knowhere/index/IndexModel.h"
namespace knowhere {
class CPUKDTRNG : public VectorIndex {
public:
CPUKDTRNG() {
index_ptr_ = SPTAG::VectorIndex::CreateInstance(SPTAG::IndexAlgoType::KDT, SPTAG::VectorValueType::Float);
index_ptr_->SetParameter("DistCalcMethod", "L2");
}
public:
BinarySet
Serialize() override;
VectorIndexPtr
Clone() override;
void
Load(const BinarySet& index_array) override;
public:
// PreprocessorPtr
// BuildPreprocessor(const DatasetPtr &dataset, const Config &config) override;
int64_t
Count() override;
int64_t
Dimension() override;
IndexModelPtr
Train(const DatasetPtr& dataset, const Config& config) override;
void
Add(const DatasetPtr& dataset, const Config& config) override;
DatasetPtr
Search(const DatasetPtr& dataset, const Config& config) override;
void
Seal() override;
private:
void
SetParameters(const Config& config);
private:
PreprocessorPtr preprocessor_;
std::shared_ptr<SPTAG::VectorIndex> index_ptr_;
};
using CPUKDTRNGPtr = std::shared_ptr<CPUKDTRNG>;
class CPUKDTRNGIndexModel : public IndexModel {
public:
BinarySet
Serialize() override;
void
Load(const BinarySet& binary) override;
private:
std::shared_ptr<SPTAG::VectorIndex> index_;
};
using CPUKDTRNGIndexModelPtr = std::shared_ptr<CPUKDTRNGIndexModel>;
} // namespace knowhere
| 27.011364 | 114 | 0.727387 |
c6edc882555afe6d86aee87f3d23297dd7b67bc5 | 4,253 | h | C | User/Drivers/Sensors/ns2009.h | PinoDM/H7PI_Samples | 7c408d9a5b3954173f2e95132e5c2af3ae864792 | [
"BSD-3-Clause"
] | 9 | 2020-03-11T17:21:26.000Z | 2020-08-03T09:19:40.000Z | User/Drivers/Sensors/ns2009.h | PinoDM/H7PI_Samples | 7c408d9a5b3954173f2e95132e5c2af3ae864792 | [
"BSD-3-Clause"
] | null | null | null | User/Drivers/Sensors/ns2009.h | PinoDM/H7PI_Samples | 7c408d9a5b3954173f2e95132e5c2af3ae864792 | [
"BSD-3-Clause"
] | 7 | 2020-03-11T23:48:14.000Z | 2021-08-05T08:31:07.000Z | /**
******************************************************************************
* @file NS2009.h
* @author Taomi Tech Team
* @brief This file contains all the functions prototypes for the NS2009
* module driver.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2017 Taomi Tech.
* All rights reserved.</center></h2>
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef NS2009_H
#define NS2009_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_hal.h"
#include "I2C.h"
#include "stdlib.h"
#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os.h"
/** @addtogroup NS2009
* @{
*/
/** @addtogroup HAL
* @{
*/
/* Exported types ------------------------------------------------------------*/
/** @defgroup
* @{
*/
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
#ifdef NS2009_GLOBAL
#define NS2009_Ext
#else
#define NS2009_Ext extern
#endif //NS2009_GLOBAL
#define NS2009_TOUCH_ERROR_RANGE 40
#define NS2009_MEASURE_TIMES 5
#define NS2009_NOT_TOUCH 0xFFFFFFFF
/***************** NS2009 I2C Address ******************/
#define I2C_NS2009_ADDR_WRITE 0x90
#define I2C_NS2009_ADDR_READ 0x91
/***************** NS2009 Command List ******************/
//12-bits ADC mode
#define I2C_NS2009_12Bits_AccelerateMode_X 0x84
#define I2C_NS2009_12Bits_AccelerateMode_Y 0x94
#define I2C_NS2009_12Bits_AccelerateMode_Z1 0xA4
#define I2C_NS2009_12Bits_AccelerateMode_Z2 0xB4
#define I2C_NS2009_LowPowerMode_X 0xC0
#define I2C_NS2009_LowPowerMode_Y 0xD0
#define I2C_NS2009_LowPowerMode_Z1 0xE0
#define I2C_NS2009_LowPowerMode_Z2 0xF0
//8-bits ADC mode
#define I2C_NS2009_8Bits_AccelerateMode_X 0x86
#define I2C_NS2009_8Bits_AccelerateMode_Y 0x96
#define I2C_NS2009_8Bits_AccelerateMode_Z1 0xA6
#define I2C_NS2009_8Bits_AccelerateMode_Z2 0xB6
#define I2C_NS2009_8Bits_LowPowerMode_X 0xC2
#define I2C_NS2009_8Bits_LowPowerMode_Y 0xD2
#define I2C_NS2009_8Bits_LowPowerMode_Z1 0xE2
#define I2C_NS2009_8Bits_LowPowerMode_Z2 0xF2
#define NS2009_TOUCH_ADC_LEFT 3904
#define NS2009_TOUCH_ADC_RIGHT 210
#define NS2009_TOUCH_ADC_UP 2688
#define NS2009_TOUCH_ADC_DOWN 300
#define PENIRQ GPIOA,GPIO_PIN_15
#define TOUCH_SAMPLES_BUF_MAX 1
typedef struct
{
uint8_t touched;
uint8_t touch_point;
uint16_t x[TOUCH_SAMPLES_BUF_MAX];
uint16_t y[TOUCH_SAMPLES_BUF_MAX];
}TouchSample_t;
/** @defgroup
* @{
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/** @defgroup Exported Macros
* @{
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/**
* @brief NS2009_Read_TouchPosition
* Read touch screen driver IC NS2009 via I2C1, get touch point position
*
* @note
*
* @param None
* @retval uint32_t, high 16-bits is X, low 16-bits is Y
*/
void NS2009_Read_TouchPosition(I2C_HandleTypeDef *hi2c);
uint16_t NS2009_GetX(void);
uint16_t NS2009_GetY(void);
void ns2009_Init(I2C_HandleTypeDef *hi2c);
void ns2009_DeInit(I2C_HandleTypeDef *hi2c);
uint16_t NS2009_IsPressed(void);
//NS2009_Ext uint32_t GetTouchPoint(void);
//NS2009_Ext uint8_t GetTouchPointWithDoubleConfirm(uint16_t* XPos, uint16_t* YPos);
//NS2009_Ext void BubbleSort(uint32_t *values,int length);
/* Initialization and de-initialization functions ******************************/
/* Peripheral Control functions ************************************************/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* NS2009_H */
/************************ (C) COPYRIGHT Taomi Tech *****END OF FILE****/
| 22.036269 | 84 | 0.551611 |
0cbe9016d2f07daabb2090ceaf3272c181499806 | 3,921 | h | C | Barcode Scanner & Generator/DTBarcodeScanner/DTBarcodeScannerController.h | Darktt/DTBarcodeScanner-DTQRCodeGenerator | f01f0b96281beb8e0538d16db85b22fcc04c26be | [
"Apache-2.0"
] | null | null | null | Barcode Scanner & Generator/DTBarcodeScanner/DTBarcodeScannerController.h | Darktt/DTBarcodeScanner-DTQRCodeGenerator | f01f0b96281beb8e0538d16db85b22fcc04c26be | [
"Apache-2.0"
] | null | null | null | Barcode Scanner & Generator/DTBarcodeScanner/DTBarcodeScannerController.h | Darktt/DTBarcodeScanner-DTQRCodeGenerator | f01f0b96281beb8e0538d16db85b22fcc04c26be | [
"Apache-2.0"
] | null | null | null | //
// DTBarcodeScannerController.h
//
// Created by Darktt on 15/6/9.
// Copyright © 2015 Darktt Personal Company. All rights reserved.
//
@import UIKit;
@import AVFoundation;
NS_ASSUME_NONNULL_BEGIN
@protocol DTBarcodeScannerControllerDelegate;
/*!
@class DTBarcodeScannerController
@abstract
DTBarcodeScannerController detect machine readable metadata via AVCaptureMetadataOutput
@discussion
Support Types:<br/>
- AVMetadataObjectTypeUPCECode<br/>
- AVMetadataObjectTypeCode39Code<br/>
- AVMetadataObjectTypeCode39Mod43Code<br/>
- AVMetadataObjectTypeEAN13Code<br/>
- AVMetadataObjectTypeEAN8Code<br/>
- AVMetadataObjectTypeCode93Code<br/>
- AVMetadataObjectTypeCode128Code<br/>
- AVMetadataObjectTypePDF417Code<br/>
- AVMetadataObjectTypeQRCode<br/>
- AVMetadataObjectTypeAztecCode<br/>
- AVMetadataObjectTypeInterleaved2of5Code<br/>
- AVMetadataObjectTypeITF14Code<br/>
- AVMetadataObjectTypeDataMatrixCode<br/>
*/
@interface DTBarcodeScannerController : UIViewController
/**
* @property delegate
* @abstract The delegate for tell detected objects.
*/
@property (nullable, assign) id<DTBarcodeScannerControllerDelegate> delegate;
/**
* Default is AVCaptureDevicePositionBack if passable.
* @property cameraPosition
* @abstract Object that represents the physical camera on the device.
*/
@property (assign) AVCaptureDevicePosition cameraPosition;
/**
* Default is AVCaptureTorchModeAuto
* @property torchMode
* @abstract Indicates current mode of the receiver's torch, if it has one.
*/
@property (assign) AVCaptureTorchMode torchMode;
/**
* Default is Yes.
* @propert showDetectRectangle
* @abstract Show the rectangle when detect barcode, When detect one-dimensional barcode will show a line, not a rectangel.
*/
@property (assign, getter = isShowDetectRectangle) BOOL showDetectRectangle;
/*!
@method barcodeScannerWithMetadataObjectTypes:
@param metadataObjectTypes
Array of AVMetadataObjectTypes to scan for. Only codes with types given in this array will be reported to the delegate.
@abstract
Initialize a scanner.
@result
An instance of DTBarcodeScannerController.
@warning
The barcode scanner did not support AVMetadataObjectTypeFace.
@see
-initWithMetadataObjectTypes:
-barcodeScanner:didScanedMetadataObjects:
*/
+ (instancetype)barcodeScannerWithMetadataObjectTypes:(NSArray<NSString *> *)metadataObjectTypes NS_SWIFT_UNAVAILABLE("Unavalilable");
/*!
@method initWithMetadataObjectTypes:
@param metadataObjectTypes
Array of AVMetadataObjectTypes to scan for. Only codes with types given in this array will be reported to the delegate.
@abstract
Initialize a scanner.
@result
An instance of DTBarcodeScannerController.
@warning
The barcode scanner did not support AVMetadataObjectTypeFace.
@see
+barcodeScannerWithMetadataObjectTypes:
-barcodeScanner:didScanedMetadataObjects:
*/
- (instancetype)initWithMetadataObjectTypes:(NSArray<NSString *> *)metadataObjectTypes;
@end
@protocol DTBarcodeScannerControllerDelegate <NSObject>
/**
* @method barcodeScanner:didScanedMetadataObjects:
*
* @abstract Tells the delegate is detect objects.
*
* @param barcodeScanner The instance of DTBarcodeScannerController.
*
* @param metadataObjects An array of AVMetadataMachineReadableCodeObject for detect objects.
*
*/
- (void)barcodeScanner:(DTBarcodeScannerController *)barcodeScanner didScanedMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects;
/**
* @method barcodeScannerDidCancel:
*
* @abstract Tells the delegate that the user cancelled the scan operation.
*
* @param barcodeScanner The instance of DTBarcodeScannerController.
*
*/
- (void)barcodeScannerDidCancel:(DTBarcodeScannerController *)barcodeScanner;
@end
NS_ASSUME_NONNULL_END | 29.481203 | 149 | 0.768171 |
c64293d6090dc54d1cebbc826279227403d3ffb8 | 1,212 | c | C | samples/getctty.c | skatsuta/linux-programming | f29e21b2ab557745a39066fd8eb9cd89a2453d78 | [
"MIT"
] | null | null | null | samples/getctty.c | skatsuta/linux-programming | f29e21b2ab557745a39066fd8eb9cd89a2453d78 | [
"MIT"
] | null | null | null | samples/getctty.c | skatsuta/linux-programming | f29e21b2ab557745a39066fd8eb9cd89a2453d78 | [
"MIT"
] | null | null | null | /*
getctty.c
Detouch controling tty then get tty again.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#if defined(__digital__) && defined(__unix__)
# define TTYPATH "/dev/tty01"
#else
# define TTYPATH "/dev/tty1"
#endif
int
main(int argc, char *argv[])
{
pid_t id;
int tty;
puts("--- start ---");
system("ps axj | grep getctty | grep -v grep");
id = fork();
if (id < 0) {
perror("fork");
exit(1);
}
if (id != 0) {
_exit(0);
}
if (setsid() < 0) {
perror("setsid");
exit(1);
}
puts("--- ctty detouched ---");
system("ps axj | grep getctty | grep -v grep");
tty = open(TTYPATH, O_RDWR);
if (tty < 0) {
perror("open(" TTYPATH ")");
exit(1);
}
puts("--- open OK ---");
system("ps axj | grep getctty | grep -v grep");
if (ioctl(tty, TIOCSCTTY, 1) < 0) {
perror("ioctl(TIOCSCTTY)");
exit(1);
}
puts("--- ioctl(TIOCSCTTY) OK ---");
system("ps axj | grep getctty | grep -v grep");
exit(0);
}
| 18.9375 | 51 | 0.525578 |
a72303392809810e89f744541dca1fbdc627ace5 | 878 | c | C | src/Utils/test/file.c | polynomialchaos/basec | 29922073b4aca96ab3a4d1cf0509c1d05fdd42e9 | [
"MIT"
] | null | null | null | src/Utils/test/file.c | polynomialchaos/basec | 29922073b4aca96ab3a4d1cf0509c1d05fdd42e9 | [
"MIT"
] | null | null | null | src/Utils/test/file.c | polynomialchaos/basec | 29922073b4aca96ab3a4d1cf0509c1d05fdd42e9 | [
"MIT"
] | null | null | null | /*******************************************************************************
* @file file.c
* @author Florian Eigentler
* @brief
* @version 1.0.0
* @date 2022-02-22
* @copyright Copyright (c) 2022 by Florian Eigentler.
* This work is licensed under terms of the MIT license (<LICENSE>).
******************************************************************************/
#include <stdio.h>
#include "basec/utils_module.h"
/*******************************************************************************
* @brief Main function
* @return int
******************************************************************************/
int main()
{
string_t file_name = "out.dat";
FILE *output = create_file(file_name);
fclose(output);
BM_CHECK_EXPRESSION(file_exists(file_name) == BC_TRUE);
output = open_file(file_name);
fclose(output);
return 0;
} | 30.275862 | 80 | 0.425968 |
bc5600914b9e415a991cef5aab3b6bf3e598cc52 | 3,299 | h | C | bin/ledger/encryption/impl/encryption_service_impl.h | Acidburn0zzz/peridot | 9a3b1fb8e834d0315092478d83d0176ef28cb765 | [
"BSD-3-Clause"
] | 1 | 2018-02-05T23:33:32.000Z | 2018-02-05T23:33:32.000Z | bin/ledger/encryption/impl/encryption_service_impl.h | Acidburn0zzz/peridot | 9a3b1fb8e834d0315092478d83d0176ef28cb765 | [
"BSD-3-Clause"
] | null | null | null | bin/ledger/encryption/impl/encryption_service_impl.h | Acidburn0zzz/peridot | 9a3b1fb8e834d0315092478d83d0176ef28cb765 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia 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 PERIDOT_BIN_LEDGER_ENCRYPTION_IMPL_ENCRYPTION_SERVICE_IMPL_H_
#define PERIDOT_BIN_LEDGER_ENCRYPTION_IMPL_ENCRYPTION_SERVICE_IMPL_H_
#include <functional>
#include <string>
#include "lib/fxl/tasks/task_runner.h"
#include "peridot/bin/ledger/cache/lazy_value.h"
#include "peridot/bin/ledger/cache/lru_cache.h"
#include "peridot/bin/ledger/encryption/public/encryption_service.h"
#include "peridot/lib/callback/scoped_task_runner.h"
#include "peridot/lib/convert/convert.h"
namespace encryption {
class EncryptionServiceImpl : public EncryptionService {
public:
EncryptionServiceImpl(fxl::RefPtr<fxl::TaskRunner> task_runner,
std::string namespace_id);
~EncryptionServiceImpl() override;
// EncryptionService:
storage::ObjectIdentifier MakeObjectIdentifier(
storage::ObjectDigest digest) override;
void EncryptCommit(
std::string commit_storage,
std::function<void(Status, std::string)> callback) override;
void DecryptCommit(
convert::ExtendedStringView storage_bytes,
std::function<void(Status, std::string)> callback) override;
void GetObjectName(
storage::ObjectIdentifier object_identifier,
std::function<void(Status, std::string)> callback) override;
void EncryptObject(
storage::ObjectIdentifier object_identifier,
fsl::SizedVmo content,
std::function<void(Status, std::string)> callback) override;
void DecryptObject(
storage::ObjectIdentifier object_identifier,
std::string encrypted_data,
std::function<void(Status, std::string)> callback) override;
private:
class KeyService;
using DeletionScopeSeed = std::pair<size_t, std::string>;
uint32_t GetCurrentKeyIndex();
void GetReferenceKey(storage::ObjectIdentifier object_identifier,
const std::function<void(const std::string&)>& callback);
void Encrypt(size_t key_index,
std::string data,
std::function<void(Status, std::string)> callback);
void Decrypt(size_t key_index,
std::string encrypted_data,
std::function<void(Status, std::string)> callback);
void FetchMasterKey(size_t key_index,
std::function<void(Status, std::string)> callback);
void FetchNamespaceKey(size_t key_index,
std::function<void(Status, std::string)> callback);
void FetchReferenceKey(DeletionScopeSeed deletion_scope_seed,
std::function<void(Status, std::string)> callback);
const std::string namespace_id_;
std::unique_ptr<KeyService> key_service_;
// Master keys indexed by key_index.
cache::LRUCache<uint32_t, std::string, Status> master_keys_;
// Namespace keys indexed by key_index.
cache::LRUCache<uint32_t, std::string, Status> namespace_keys_;
// Reference keys indexed by deletion scope seed.
cache::LRUCache<DeletionScopeSeed, std::string, Status> reference_keys_;
// This must be the last member of this class.
callback::ScopedTaskRunner task_runner_;
};
} // namespace encryption
#endif // PERIDOT_BIN_LEDGER_ENCRYPTION_IMPL_ENCRYPTION_SERVICE_IMPL_H_
| 38.360465 | 80 | 0.729918 |
ad86acd00e9af7847078a36a1f272cdae33f8812 | 4,424 | c | C | rclc_examples/src/example_lifecycle_node.c | amfern/rclc | f8de341e2f9926d91af765d4587d4ca04954666a | [
"Apache-2.0"
] | null | null | null | rclc_examples/src/example_lifecycle_node.c | amfern/rclc | f8de341e2f9926d91af765d4587d4ca04954666a | [
"Apache-2.0"
] | null | null | null | rclc_examples/src/example_lifecycle_node.c | amfern/rclc | f8de341e2f9926d91af765d4587d4ca04954666a | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020 - for information on the respective copyright owner
// see the NOTICE file and/or the repository https://github.com/ros2/rclc.
// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdio.h>
#include <rcl/error_handling.h>
#include <rcutils/logging_macros.h>
#include <lifecycle_msgs/msg/transition_description.h>
#include <lifecycle_msgs/msg/transition_event.h>
#include <lifecycle_msgs/srv/change_state.h>
#include <lifecycle_msgs/srv/get_state.h>
#include <lifecycle_msgs/srv/get_available_states.h>
#include <lifecycle_msgs/srv/get_available_transitions.h>
#include <rclc/executor.h>
#include "rclc_lifecycle/rclc_lifecycle.h"
#define RCCHECK(fn) {rcl_ret_t temp_rc = fn; if ((temp_rc != RCL_RET_OK)) {printf( \
"Failed status on line %d: %d. Aborting.\n", __LINE__, (int)temp_rc); return 1;}}
#define RCSOFTCHECK(fn) {rcl_ret_t temp_rc = fn; if ((temp_rc != RCL_RET_OK)) {printf( \
"Failed status on line %d: %d. Continuing.\n", __LINE__, (int)temp_rc);}}
rcl_ret_t my_on_configure()
{
printf(" >>> lifecycle_node: on_configure() callback called.\n");
return RCL_RET_OK;
}
rcl_ret_t my_on_activate()
{
printf(" >>> lifecycle_node: on_activate() callback called.\n");
return RCL_RET_OK;
}
rcl_ret_t my_on_deactivate()
{
printf(" >>> lifecycle_node: on_deactivate() callback called.\n");
return RCL_RET_OK;
}
rcl_ret_t my_on_cleanup()
{
printf(" >>> lifecycle_node: on_cleanup() callback called.\n");
return RCL_RET_OK;
}
int main(int argc, const char * argv[])
{
rcl_allocator_t allocator = rcl_get_default_allocator();
rclc_support_t support;
rcl_ret_t rc;
// create init_options
rc = rclc_support_init(&support, argc, argv, &allocator);
if (rc != RCL_RET_OK) {
printf("Error rclc_support_init.\n");
return -1;
}
// create rcl_node
rcl_node_t my_node;
rc = rclc_node_init_default(&my_node, "lifecycle_node", "rclc", &support);
if (rc != RCL_RET_OK) {
printf("Error in rclc_node_init_default\n");
return -1;
}
// make it a lifecycle node
printf("creating lifecycle node...\n");
rcl_lifecycle_state_machine_t state_machine_ = rcl_lifecycle_get_zero_initialized_state_machine();
rclc_lifecycle_node_t lifecycle_node;
rc = rclc_make_node_a_lifecycle_node(
&lifecycle_node,
&my_node,
&state_machine_,
&allocator,
true);
if (rc != RCL_RET_OK) {
printf("Error in creating lifecycle node.\n");
return -1;
}
// Executor
rclc_executor_t executor;
RCCHECK(rclc_executor_init(
&executor,
&support.context,
4, // 1 for the node + 1 for each lifecycle service
&allocator));
unsigned int rcl_wait_timeout = 1000; // in ms
RCCHECK(rclc_executor_set_timeout(&executor, RCL_MS_TO_NS(rcl_wait_timeout)));
// Register lifecycle services
printf("registering lifecycle services...\n");
RCCHECK(rclc_lifecycle_init_get_state_server(&lifecycle_node, &executor));
RCCHECK(rclc_lifecycle_init_get_available_states_server(&lifecycle_node, &executor));
RCCHECK(rclc_lifecycle_init_change_state_server(&lifecycle_node, &executor));
// Register lifecycle service callbacks
printf("registering callbacks...\n");
rclc_lifecycle_register_on_configure(&lifecycle_node, &my_on_configure);
rclc_lifecycle_register_on_activate(&lifecycle_node, &my_on_activate);
rclc_lifecycle_register_on_deactivate(&lifecycle_node, &my_on_deactivate);
rclc_lifecycle_register_on_cleanup(&lifecycle_node, &my_on_cleanup);
// Run
RCSOFTCHECK(rclc_executor_spin(&executor));
// Cleanup
printf("cleaning up...\n");
rc = rclc_lifecycle_node_fini(&lifecycle_node, &allocator);
rc += rcl_node_fini(&my_node);
rc += rclc_executor_fini(&executor);
rc += rclc_support_fini(&support);
if (rc != RCL_RET_OK) {
printf("Error while cleaning up!\n");
return -1;
}
return 0;
}
| 32.057971 | 100 | 0.733725 |
213e2d07271055bd6ab4c9199eab477a98950fd1 | 1,482 | h | C | include/soulblight/BloodseekerPalangquin.h | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 5 | 2019-02-01T01:41:19.000Z | 2021-06-17T02:16:13.000Z | include/soulblight/BloodseekerPalangquin.h | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 2 | 2020-01-14T16:57:42.000Z | 2021-04-01T00:53:18.000Z | include/soulblight/BloodseekerPalangquin.h | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 1 | 2019-03-02T20:03:51.000Z | 2019-03-02T20:03:51.000Z | /*
* Warhammer Age of Sigmar battle simulator.
*
* Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#pragma once
#include <soulblight/SoulblightGravelords.h>
#include <Weapon.h>
namespace Soulblight {
class BloodseekerPalanquin : public SoulblightBase {
public:
static Unit *Create(const ParameterList ¶meters);
static int ComputePoints(const ParameterList& parameters);
static void Init();
BloodseekerPalanquin(CursedBloodline bloodline, Lore lore, CommandTrait trait, Artefact artefact, bool isGeneral);
~BloodseekerPalanquin() override = default;
protected:
void onWounded() override;
void onRestore() override;
Wounds weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const override;
void onStartShooting(PlayerId player) override;
size_t getDamageTableIndex() const;
private:
Weapon m_wail,
m_blade,
m_etherealWeapons;
static bool s_registered;
};
//
// Abilities Implemented
// -------------------------------------------
// Frightful Touch Yes
// A Fine Vintage TODO
// Wail of the Damned Yes
// Blood Siphon TODO
//
} // namespace Soulblight
| 24.7 | 142 | 0.622132 |
3943349c23dda90d77f23a969d2e373aa6aae385 | 1,777 | c | C | mod_global_vars.c | bit4bit/mod_global_vars | d1278af7d19555471a6c8ef30c2571a64953291f | [
"MIT"
] | null | null | null | mod_global_vars.c | bit4bit/mod_global_vars | d1278af7d19555471a6c8ef30c2571a64953291f | [
"MIT"
] | null | null | null | mod_global_vars.c | bit4bit/mod_global_vars | d1278af7d19555471a6c8ef30c2571a64953291f | [
"MIT"
] | null | null | null | #include <switch.h>
SWITCH_MODULE_LOAD_FUNCTION(mod_global_vars_load);
SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_global_vars_shutdown);
SWITCH_MODULE_DEFINITION(mod_global_vars, mod_global_vars_load, mod_global_vars_shutdown, NULL);
static switch_status_t load_variables_from_config(void)
{
char *cf = "global_vars.conf";
switch_xml_t cfg, xml, variables_tag, variable_tag;
if (!(xml = switch_xml_open_cfg(cf, &cfg, NULL))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "open of %s failed\n", cf);
return SWITCH_STATUS_TERM;
}
if (!(variables_tag = switch_xml_child(cfg, "variables"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing <variables> tag!\n");
goto done;
}
for (variable_tag = switch_xml_child(variables_tag, "variable"); variable_tag; variable_tag = variable_tag->next) {
char *vname = (char *) switch_xml_attr_soft(variable_tag, "name");
char *vvalue = (char *) switch_xml_attr_soft(variable_tag, "value");
switch_core_set_variable(vname, vvalue);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "global_vars set variable %s\n", vname);
}
done:
switch_xml_free(xml);
return SWITCH_STATUS_SUCCESS;
}
SWITCH_MODULE_LOAD_FUNCTION(mod_global_vars_load)
{
*module_interface = switch_loadable_module_create_module_interface(pool, modname);
if (load_variables_from_config() != SWITCH_STATUS_SUCCESS) {
return SWITCH_STATUS_FALSE;
}
return SWITCH_STATUS_SUCCESS;
}
SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_global_vars_shutdown)
{
return SWITCH_STATUS_UNLOAD;
}
/* For Emacs:
* Local Variables:
* mode:c
* indent-tabs-mode:t
* tab-width:4
* c-basic-offset:4
* End:
* For VIM:
* vim:set softtabstop=4 shiftwidth=4 tabstop=4 noet:
*/
| 29.131148 | 117 | 0.751266 |
0675770041c79488a373f029c57b99a369735425 | 1,946 | c | C | DSA LAB/20-09-21/2.c | HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo | 8a9d67153797e9a6d438151c70f6726a50079df4 | [
"MIT"
] | 2 | 2021-09-18T10:50:20.000Z | 2021-11-12T13:19:45.000Z | DSA LAB/20-09-21/2.c | HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo | 8a9d67153797e9a6d438151c70f6726a50079df4 | [
"MIT"
] | null | null | null | DSA LAB/20-09-21/2.c | HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo | 8a9d67153797e9a6d438151c70f6726a50079df4 | [
"MIT"
] | 3 | 2021-09-10T14:08:12.000Z | 2021-09-18T10:52:09.000Z | // Q2) Write a menu driven program to implement queue operations such as Enqueue, Dequeue, Peek,
// Display of elements, IsEmpty, IsFull
// using static array.
#include <stdio.h>
#include <stdlib.h>
struct Queue {
int front, rear, size;
int capacity;
int* array;
};
struct Queue* makeQueue(int capacity){
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1;
queue->array = (int*)malloc(queue->capacity * sizeof(int));
return queue;
}
int isFull(struct Queue* queue){
return (queue->size == queue->capacity);
}
int isEmpty(struct Queue* queue){
return (queue->size == 0);
}
void enqueue(struct Queue* queue, int item){
if (isFull(queue))return;
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
printf("%d enqueued to queue\n", item);
}
int dequeue(struct Queue* queue){
if (!isEmpty(queue)){
int item = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size = queue->size - 1;
return item;
}
}
int front(struct Queue* queue){
if (!isEmpty(queue))
return queue->array[queue->front];
}
int rear(struct Queue* queue){
if (!isEmpty(queue))
return queue->array[queue->rear];
}
int display(struct Queue* queue){
printf("Queue -> ");
for(int i=queue->front;i<=queue->rear;i++){
printf("%d ",queue->array[i]);
}
printf("\n");
}
int main(){
struct Queue* queue = makeQueue(1000);
enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
enqueue(queue, 40);
printf("%d dequeued from queue\n\n",dequeue(queue));
display(queue);
printf("Front item is %d\n", front(queue));
printf("Rear item is %d\n", rear(queue));
return 0;
} | 23.731707 | 97 | 0.609455 |
d532dab78d1494fe81856c26e8848be1a9c1eea6 | 136 | h | C | BananaCore/Define.h | kusharami/bananaqt | 79327ecddc769e4df0ebe8109c30c5ae74a31a12 | [
"MIT"
] | null | null | null | BananaCore/Define.h | kusharami/bananaqt | 79327ecddc769e4df0ebe8109c30c5ae74a31a12 | [
"MIT"
] | null | null | null | BananaCore/Define.h | kusharami/bananaqt | 79327ecddc769e4df0ebe8109c30c5ae74a31a12 | [
"MIT"
] | null | null | null | #pragma once
#define CSTRKEY(key) #key
#define WSTRKEY(key) QT_UNICODE_LITERAL(CSTRKEY(key))
#define QSTRKEY(key) QStringLiteral(#key)
| 22.666667 | 53 | 0.779412 |
d5bcc606b1e492109e2d16b32c02acd5cc184146 | 8,704 | h | C | Desktop/bio/Mobility/uparg.h | Smyja/mobility | a05427257ea0cc81f904f8cf9082063e95d00851 | [
"MIT"
] | null | null | null | Desktop/bio/Mobility/uparg.h | Smyja/mobility | a05427257ea0cc81f904f8cf9082063e95d00851 | [
"MIT"
] | null | null | null | Desktop/bio/Mobility/uparg.h | Smyja/mobility | a05427257ea0cc81f904f8cf9082063e95d00851 | [
"MIT"
] | null | null | null | void FOCUS(HWND hwnd){
sprintf(how,"%s\\*",path);
hhh=FindFirstFile(how,&wff);
FindNextFile(hhh,&wff); int a=0; sprintf(asset,"");
while(FindNextFile(hhh,&wff)!=0){
sprintf(how,"%s",wff.cFileName);
sprintf(asset,"%s %s; %s\\%s\n",asset,how,path,how);
sprintf(how,"%s\\%s",path,wff.cFileName);
SHGetFileInfo(how,NULL,&shft,sizeof(shft),SHGFI_ICON);
browse[a]=shft.hIcon; a++;
}
FindClose(hhh);
ValidateRect(hwnd,NULL); InvalidateRect(hwnd,NULL,TRUE);
}
void move(){
if(mup==1){ CLEAN=TRUE;
if(mpo1>fm1){ for(int z=0;z<1000;z++){ scale++; thm3=scale*(csize1-penx-pistx)/100.0; thm5=146*scale/100.0; if(scale>=100){ if(scale!=100){ scale--; } break; } if(csize1-(298-thm5)>=mpo1){ break; } } }
if(mpo1<fm1){ for(int z=0;z<1000;z++){ scale--; thm3=scale*(csize1-penx-pistx)/100.0; thm5=146*scale/100.0; if(scale<=0){ if(scale!=0){ scale++; } break; } if(csize1-(298-thm5)<=mpo1){ break; } } }
ValidateRect(hwnd,NULL); InvalidateRect(hwnd,NULL,TRUE); }
if(mpo1>40&&mpo1<pistx-50&&mpo2>85&&mpo2<jua+30&&selen==0){
for(int r=0;r<impc1;r++){
if(mpo2>=camp[r]&&mpo2<=camp[r]+250&&cam[r]==1){
if(mpo1>47&&mpo1<56&&mpo2>camp[r]+39&&mpo2<camp[r]+54&&selen==0&&drz1==0){ drz=1; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>47&&mpo1<56&&mpo2>camp[r]+56&&mpo2<camp[r]+71&&selen==0&&drz1==0){ drz=2; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>47&&mpo1<56&&mpo2>camp[r]+73&&mpo2<camp[r]+90&&selen==0&&drz1==0){ drz=3; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>47&&mpo1<56&&mpo2>camp[r]+110&&mpo2<camp[r]+127&&selen==0&&drz1==0){ drz=4; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>47&&mpo1<56&&mpo2>camp[r]+127&&mpo2<camp[r]+144&&selen==0&&drz1==0){ drz=5; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>47&&mpo1<56&&mpo2>camp[r]+144&&mpo2<camp[r]+159&&selen==0&&drz1==0){ drz=6; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>47&&mpo1<66&&mpo2>camp[r]+169&&mpo2<camp[r]+184&&selen==0&&drz1==0){ drz=7; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>47&&mpo1<66&&mpo2>camp[r]+186&&mpo2<camp[r]+203&&selen==0&&drz1==0){ drz=8; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>136&&mpo1<156&&mpo2>camp[r]+50&&mpo2<camp[r]+67&&selen==0&&drz1==0){ drz=11; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1<136||mpo1>156||mpo2<camp[r]+50||mpo2>camp[r]+67){ if(drz==11&&drz1==0){drz=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); } }
break; }
}
}
if(mpo1>56&&drz!=0&&drz!=11&&drz1==0&&selen==0){ drz=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(mpo1<50&&mpo1>0&&drz!=0&&drz1==0&&selen==0){ drz=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(drz1==1){ CLEAN=TRUE;
if(drz!=4&&drz!=5&&drz!=6){ if(mpo1>fm1){ adjust++; }else{ adjust--; } }
else{ if(mpo1>fm1){ adjust+=0.03; if(adjust>6.2823){ adjust=0; } }else{ adjust-=0.03; if(adjust<=0){ adjust=6.2823; } } }
sprintf(scene[0],"%s%f%s",adjust1,adjust,adjust2);
ValidateRect(hwnd,NULL); InvalidateRect(hwnd,NULL,TRUE);
if(mpo1>csize1-50){ SetCursorPos(100,mpo2); }
if(mpo1<50){ SetCursorPos(csize1-100,mpo2); }
}
//end
if(mpo1>csize1-penx+6&&mpo1<csize1-penx+25&&mpo2>70&&chase==2){
for(int r=0;r<pic;r++){
if(mpo2>=pivp[r]&&mpo2<=pid[r]&&pivy[r]==0){ drj2=r;
if(mpo1>csize1-penx+6&&mpo1<csize1-penx+25&&mpo2>pivp[r]+35&&mpo2<pivp[r]+48&&chase==2&&drj==0){ drj=1; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+6&&mpo1<csize1-penx+25&&mpo2>pivp[r]+50&&mpo2<pivp[r]+68&&chase==2&&drj1==0){ drj=2; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+6&&mpo1<csize1-penx+25&&mpo2>pivp[r]+70&&mpo2<pivp[r]+90&&chase==2&&drj1==0){ drj=3; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
break; }
}
}
if(mpo1<csize1-penx+6&&drj!=0&&drj1==0&&chase==2){ drj=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(mpo1>csize1-penx+30&&drj!=0&&drj1==0&&chase==2){ drj=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(drj1==1){ CLEAN=TRUE;
if(mpo1>fm1){ if(drj==1){ pivotx[drj2]++; } if(drj==2){ pivoty[drj2]++; } if(drj==3){ pivotz[drj2]++; } }
if(mpo1<fm1){ if(drj==1){ pivotx[drj2]--; } if(drj==2){ pivoty[drj2]--; } if(drj==3){ pivotz[drj2]--; } }
ValidateRect(hwnd,NULL); InvalidateRect(hwnd,NULL,TRUE);
}
//chase 3
if(mpo1>csize1-penx+6&&mpo1<csize1-90&&mpo2>70&&mpo2<ga+30&&chase==3){
for(int r=0;r<phys2;r++){
if(mpo2>=phyp[r]&&mpo2<=phyp[r]+400&&phyc[r]==1){
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+40&&mpo2>phyp[r]+30&&mpo2<phyp[r]+48&&chase==3&&phm1==0){ phm=1; pjm=r; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
break; }
}
}
//end
if(mpo1<csize1-penx+6&&mpo1>0&&phm!=0&&phm1==0&&chase==3){ phm=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(mpo1>csize1-penx+40&&phm!=0&&phm1==0&&chase==3){ phm=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
//end
if(phm1==1){
if(mpo1>fm1){
if(phm==1){ mass[pjm]++; }
}
if(mpo1<fm1){
if(phm==1){ if(mass[pjm]>0){ mass[pjm]--; } }
}
if(mpo1>csize1-50){ SetCursorPos(100,mpo2); }
if(mpo1<50){ SetCursorPos(csize1-100,mpo2); }
ValidateRect(hwnd,NULL); InvalidateRect(hwnd,NULL,TRUE);
}
if(mpo1>csize1-penx+6&&mpo1<csize1-90&&mpo2>70&&mpo2<ga+30&&chase==0){
for(int r=0;r<reho;r++){
if(mpo2>=gp[r]&&mpo2<=gp[r]+400&&ges[sp[r]+1]==-7){
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+39&&mpo2<gp[r]+50&&chase==0&&dr1==0){ dr=3; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+60&&mpo2<gp[r]+76&&chase==0&&dr1==0){ dr=2; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+80&&mpo2<gp[r]+96&&chase==0&&dr1==0){ dr=1; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+120&&mpo2<gp[r]+136&&chase==0&&dr1==0){ dr=4; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+140&&mpo2<gp[r]+156&&chase==0&&dr1==0){ dr=5; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+160&&mpo2<gp[r]+176&&chase==0&&dr1==0){ dr=6; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+200&&mpo2<gp[r]+206&&chase==0&&dr1==0){ dr=7; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+220&&mpo2<gp[r]+226&&chase==0&&dr1==0){ dr=8; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+30&&mpo2>gp[r]+240&&mpo2<gp[r]+246&&chase==0&&dr1==0){ dr=9; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
if(mpo1>csize1-penx+18&&mpo1<csize1-penx+80&&mpo2>gp[r]+314&&mpo2<gp[r]+329&&chase==0&&dr1==0){ dr=10; hc=LoadCursor(GetModuleHandle(NULL),"CUR1"); SetCursor(hc); }
break; }
}
}
if(mpo1<csize1-penx+6&&mpo1>0&&dr!=0&&dr1==0&&chase==0&&dr!=10){ dr=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(mpo1>csize1-penx+30&&dr!=0&&dr1==0&&chase==0&&dr!=10){ dr=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(mpo1<csize1-penx+6&&mpo1>0&&dr!=0&&dr1==0&&chase==0){ dr=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(mpo1>csize1-penx+80&&dr!=0&&dr1==0&&chase==0){ dr=0; hc=LoadCursor(NULL,IDC_ARROW); SetCursor(hc); }
if(dr1==1){ CLEAN=TRUE;
if(mpo1>fm1){
if(dr==1){ trans1[kon]+=1; } else if(dr==2){ trans2[kon]+=1; } else if(dr==3){ trans3[kon]+=1; }
}
else{ if(dr==1){ trans1[kon]-=1; } else if(dr==2){ trans2[kon]-=1; }else if(dr==3){ trans3[kon]-=1; } }
if(mpo1<fm1){
if(dr==7){ if(ges[dame+1]>0){ ges[dame+1]-=1; } }
if(dr==8){ if(ges[dame+2]>0){ ges[dame+2]-=1; } }
if(dr==9){ if(ges[dame+3]>0){ ges[dame+3]-=1; } }
if(dr==10){ if(ges[dame+1]>0){ ges[dame+1]-=1; } }
}
if(mpo1>fm1){
if(dr==7){ ges[dame+1]+=1; }
if(dr==8){ ges[dame+2]+=1; }
if(dr==9){ ges[dame+3]+=1; }
if(dr==10){ if(ges[dame+1]<255){ ges[dame+1]+=1; } }
}
if(mpo1<fm1){
if(dr==4){ ges[dame+1]-=1; if(ges[dame+1]<0){ ges[dame+1]=360; } }
if(dr==5){ ges[dame+2]-=1; if(ges[dame+2]<0){ ges[dame+2]=360; } }
if(dr==6){ ges[dame+3]-=1; if(ges[dame+3]<0){ ges[dame+3]=360; } }
}
if(mpo1>fm1){
if(dr==4){ ges[dame+1]+=1; if(ges[dame+1]>360){ ges[dame+1]=0; } }
if(dr==5){ ges[dame+2]+=1; if(ges[dame+2]>360){ ges[dame+2]=0; } }
if(dr==6){ ges[dame+3]+=1; if(ges[dame+3]>360){ ges[dame+3]=0; } }
}
ValidateRect(hwnd,NULL); InvalidateRect(hwnd,NULL,TRUE);
if(mpo1>csize1-50){ SetCursorPos(100,mpo2); }
if(mpo1<50){ SetCursorPos(csize1-100,mpo2); }
}
}
| 59.210884 | 201 | 0.644876 |
84f143c4d1b6fc7d9c3ed9f9cbd4e0795bb317b8 | 222 | h | C | CommonProject/Feature/Base/Controller/BPTabBarController.h | happyer-lwl/SecMaps | 68c2d598aa6ed645f35134142df6a0bc2d417f5e | [
"MIT"
] | null | null | null | CommonProject/Feature/Base/Controller/BPTabBarController.h | happyer-lwl/SecMaps | 68c2d598aa6ed645f35134142df6a0bc2d417f5e | [
"MIT"
] | null | null | null | CommonProject/Feature/Base/Controller/BPTabBarController.h | happyer-lwl/SecMaps | 68c2d598aa6ed645f35134142df6a0bc2d417f5e | [
"MIT"
] | null | null | null | //
// BPTabBarController.h
// CommonProject
//
// Created by WyzcWin on 16/10/26.
// Copyright © 2016年 runlwl. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BPTabBarController : UITabBarController
@end
| 15.857143 | 50 | 0.711712 |
3be1af491e254a8ec5b2d2e643633c3ae0af503b | 768 | h | C | DDCryptor/DDCryptor/DDCryptor/NSString+DDDES.h | longxdragon/DDCryptor | a7a18aa9bce946f207685a10b1f27c7497ab846c | [
"MIT"
] | 3 | 2017-08-14T08:59:05.000Z | 2018-03-12T15:44:16.000Z | DDCryptor/DDCryptor/DDCryptor/NSString+DDDES.h | longxdragon/DDCryptor | a7a18aa9bce946f207685a10b1f27c7497ab846c | [
"MIT"
] | null | null | null | DDCryptor/DDCryptor/DDCryptor/NSString+DDDES.h | longxdragon/DDCryptor | a7a18aa9bce946f207685a10b1f27c7497ab846c | [
"MIT"
] | 1 | 2018-03-12T09:49:20.000Z | 2018-03-12T09:49:20.000Z | //
// NSString+DDDES.h
// DDCryptor
//
// Created by longxdragon on 2018/3/5.
// Copyright © 2018年 longxdragon. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (DDDES)
// 3DES encrypt
- (NSString *)dd_3desEncryptWithKey:(NSString *)key;
- (NSString *)dd_3desEncryptWithKey:(NSString *)key iv:(NSString *)iv;
// 3DES decrypt
- (NSString *)dd_3desDecryptWithKey:(NSString *)key;
- (NSString *)dd_3desDecryptWithKey:(NSString *)key iv:(NSString *)iv;
// DES encrypt
- (NSString *)dd_desEncryptWithKey:(NSString *)key;
- (NSString *)dd_desEncryptWithKey:(NSString *)key iv:(NSString *)iv;
// DES decrypt
- (NSString *)dd_desDecryptWithKey:(NSString *)key;
- (NSString *)dd_desDecryptWithKey:(NSString *)key iv:(NSString *)iv;
@end
| 25.6 | 70 | 0.717448 |
47d170120e795ebe280aac58945129019e462e24 | 6,288 | h | C | src/DFPlayerMini_Fast.h | cavamora/mongooseos-walle | b6c730c4be6260ea0e1c1ea4ee39be75e4450709 | [
"Apache-2.0"
] | 1 | 2022-01-10T23:26:32.000Z | 2022-01-10T23:26:32.000Z | src/DFPlayerMini_Fast.h | cavamora/mongooseos-walle | b6c730c4be6260ea0e1c1ea4ee39be75e4450709 | [
"Apache-2.0"
] | null | null | null | src/DFPlayerMini_Fast.h | cavamora/mongooseos-walle | b6c730c4be6260ea0e1c1ea4ee39be75e4450709 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Arduino.h"
#include "mgos_uart.h"
//-------------------------------------------------------------------------------------//
// Packet Values
//-------------------------------------------------------------------------------------//
const uint8_t STACK_SIZE = 10; //total number of bytes in a stack/packet (same for cmds and queries)
const uint8_t SB = 0x7E; //start byte
const uint8_t VER = 0xFF; //version
const uint8_t LEN = 0x6; //number of bytes after "LEN" (except for checksum data and EB)
const uint8_t FEEDBACK = 1; //feedback requested
const uint8_t NO_FEEDBACK = 0; //no feedback requested
const uint8_t EB = 0xEF; //end byte
//-------------------------------------------------------------------------------------//
// Control Command Values
//-------------------------------------------------------------------------------------//
const uint8_t NEXT = 0x01;
const uint8_t PREV = 0x02;
const uint8_t PLAY = 0x03;
const uint8_t INC_VOL = 0x04;
const uint8_t DEC_VOL = 0x05;
const uint8_t VOLUME = 0x06;
const uint8_t EQ = 0x07;
const uint8_t PLAYBACK_MODE = 0x08;
const uint8_t PLAYBACK_SRC = 0x09;
const uint8_t STANDBY = 0x0A;
const uint8_t NORMAL = 0x0B;
const uint8_t RESET = 0x0C;
const uint8_t PLAYBACK = 0x0D;
const uint8_t PAUSE = 0x0E;
const uint8_t SPEC_FOLDER = 0x0F;
const uint8_t VOL_ADJ = 0x10;
const uint8_t REPEAT_PLAY = 0x11;
const uint8_t USE_MP3_FOLDER = 0x12;
const uint8_t INSERT_ADVERT = 0x13;
const uint8_t SPEC_TRACK_3000 = 0x14;
const uint8_t STOP_ADVERT = 0x15;
const uint8_t STOP = 0x16;
const uint8_t REPEAT_FOLDER = 0x17;
const uint8_t RANDOM_ALL = 0x18;
const uint8_t REPEAT_CURRENT = 0x19;
const uint8_t SET_DAC = 0x1A;
//-------------------------------------------------------------------------------------//
// Query Command Values
//-------------------------------------------------------------------------------------//
const uint8_t SEND_INIT = 0x3F;
const uint8_t RETRANSMIT = 0x40;
const uint8_t REPLY = 0x41;
const uint8_t GET_STATUS = 0x42;
const uint8_t GET_VOL = 0x43;
const uint8_t GET_EQ = 0x44;
const uint8_t GET_MODE = 0x45;
const uint8_t GET_VERSION = 0x46;
const uint8_t GET_TF_FILES = 0x47;
const uint8_t GET_U_FILES = 0x48;
const uint8_t GET_FLASH_FILES = 0x49;
const uint8_t KEEP_ON = 0x4A;
const uint8_t GET_TF_TRACK = 0x4B;
const uint8_t GET_U_TRACK = 0x4C;
const uint8_t GET_FLASH_TRACK = 0x4D;
const uint8_t GET_FOLDER_FILES = 0x4E;
const uint8_t GET_FOLDERS = 0x4F;
//-------------------------------------------------------------------------------------//
// EQ Values
//-------------------------------------------------------------------------------------//
const uint8_t EQ_NORMAL = 0;
const uint8_t EQ_POP = 1;
const uint8_t EQ_ROCK = 2;
const uint8_t EQ_JAZZ = 3;
const uint8_t EQ_CLASSIC = 4;
const uint8_t EQ_BASE = 5;
//-------------------------------------------------------------------------------------//
// Mode Values
//-------------------------------------------------------------------------------------//
const uint8_t REPEAT = 0;
const uint8_t FOLDER_REPEAT = 1;
const uint8_t SINGLE_REPEAT = 2;
const uint8_t RANDOM = 3;
//-------------------------------------------------------------------------------------//
// Playback Source Values
//-------------------------------------------------------------------------------------//
const uint8_t U = 1;
const uint8_t TF = 2;
const uint8_t AUX = 3;
const uint8_t SLEEP = 4;
const uint8_t FLASH = 5;
//-------------------------------------------------------------------------------------//
// Base Volume Adjust Value
//-------------------------------------------------------------------------------------//
const uint8_t VOL_ADJUST = 0x10;
//-------------------------------------------------------------------------------------//
// Repeat Play Values
//-------------------------------------------------------------------------------------//
const uint8_t STOP_REPEAT = 0;
const uint8_t START_REPEAT = 1;
class DFPlayerMini_Fast
{
public:
int _uart_no;
struct stack {
uint8_t start_byte;
uint8_t version;
uint8_t length;
uint8_t commandValue;
uint8_t feedbackValue;
uint8_t paramMSB;
uint8_t paramLSB;
uint8_t checksumMSB;
uint8_t checksumLSB;
uint8_t end_byte;
} sendStack, recStack;
unsigned long timer;
unsigned long threshold = 500;
bool begin(int uart_no);
void playNext();
void playPrevious();
void play(uint16_t trackNum);
void incVolume();
void decVolume();
void volume(uint8_t volume);
void EQSelect(uint8_t setting);
void loop(uint16_t trackNum);
void playbackSource(uint8_t source);
void standbyMode();
void normalMode();
void reset();
void resume();
void pause();
void playFolder(uint8_t folderNum, uint8_t trackNum);
void volumeAdjustSet(uint8_t gain);
void startRepeatPlay();
void stopRepeatPlay();
void playFromMP3Folder(uint16_t trackNum);
void repeatFolder(uint16_t folder);
void randomAll();
void startRepeat();
void stopRepeat();
void startDAC();
void stopDAC();
void sleep();
void wakeUp();
bool isPlaying();
int16_t currentVolume();
int16_t currentEQ();
int16_t currentMode();
int16_t currentVersion();
int16_t numUsbTracks();
int16_t numSdTracks();
int16_t numFlashTracks();
int16_t currentUsbTrack();
int16_t currentSdTrack();
int16_t currentFlashTrack();
int16_t numTracksInFolder(uint8_t folder);
int16_t numFolders();
void findChecksum(stack *_stack);
void sendData();
void flush();
int16_t query(uint8_t cmd, uint8_t msb=0, uint8_t lsb=0);
bool getStatus(uint8_t cmd);
bool parseFeedback();
bool timeout();
//void printStack(stack _stack);
};
| 33.269841 | 108 | 0.500954 |
a47ad9faebca91a7429dd2bf453e62efba1ccef8 | 130 | c | C | src/runtime/object/any.c | emptyland/yalx | 0bfd54d62fb0c4c4ad205a613a77e57c1b4e6d69 | [
"BSD-2-Clause"
] | null | null | null | src/runtime/object/any.c | emptyland/yalx | 0bfd54d62fb0c4c4ad205a613a77e57c1b4e6d69 | [
"BSD-2-Clause"
] | null | null | null | src/runtime/object/any.c | emptyland/yalx | 0bfd54d62fb0c4c4ad205a613a77e57c1b4e6d69 | [
"BSD-2-Clause"
] | null | null | null | #include "runtime/object/any.h"
struct yalx_value_str *yalx_any_to_string(struct yalx_value_any *any) {
return NULL;
}
| 16.25 | 71 | 0.730769 |
78c094f04549293d104018ef000fd8dc561654fe | 827 | c | C | lib/src/osEepromLongWrite.c | Daviz00/sm64 | fd2ed5e0e72d04732034919f8442f8d2cc40fd67 | [
"Unlicense"
] | 1 | 2020-12-23T13:53:10.000Z | 2020-12-23T13:53:10.000Z | lib/src/osEepromLongWrite.c | Daviz00/sm64 | fd2ed5e0e72d04732034919f8442f8d2cc40fd67 | [
"Unlicense"
] | null | null | null | lib/src/osEepromLongWrite.c | Daviz00/sm64 | fd2ed5e0e72d04732034919f8442f8d2cc40fd67 | [
"Unlicense"
] | null | null | null | #include "libultra_internal.h"
extern u64 osClockRate;
extern u8 D_80365D20;
extern u8 _osCont_numControllers;
extern OSTimer D_80365D28;
extern OSMesgQueue _osContMesgQueue;
extern OSMesg _osContMesgBuff[4];
// exactly the same as osEepromLongRead except for osEepromWrite call
s32 osEepromLongWrite(OSMesgQueue *mq, u8 address, u8 *buffer, int nbytes) {
s32 result = 0;
if (address > 0x40) {
return -1;
}
while (nbytes > 0) {
result = osEepromWrite(mq, address, buffer);
if (result != 0) {
return result;
}
nbytes -= 8;
address += 1;
buffer += 8;
osSetTimer(&D_80365D28, 12000 * osClockRate / 1000000, 0, &_osContMesgQueue, _osContMesgBuff);
osRecvMesg(&_osContMesgQueue, NULL, OS_MESG_BLOCK);
}
return result;
}
| 26.677419 | 102 | 0.65659 |
603a39825e09bd13beb744dc0422ce1bceec1281 | 507 | h | C | phast_gui/interfaces/idatawindowstub.h | stijnhinterding/phast | dad4702eb6401c1eba03ad70eff3659292636d30 | [
"MIT"
] | 1 | 2021-05-22T17:40:51.000Z | 2021-05-22T17:40:51.000Z | phast_gui/interfaces/idatawindowstub.h | stijnhinterding/phast | dad4702eb6401c1eba03ad70eff3659292636d30 | [
"MIT"
] | null | null | null | phast_gui/interfaces/idatawindowstub.h | stijnhinterding/phast | dad4702eb6401c1eba03ad70eff3659292636d30 | [
"MIT"
] | 1 | 2021-03-15T07:09:03.000Z | 2021-03-15T07:09:03.000Z | /* Copyright (c) 2020 Stijn Hinterding, Utrecht University
* This sofware is licensed under the MIT license (see the LICENSE file)
*/
#ifndef IDATAWINDOWSTUB_H
#define IDATAWINDOWSTUB_H
class IDataWindow;
class IDataPlot;
class IBinningClass;
class IDataWindowStub
{
public:
virtual ~IDataWindowStub() {}
virtual IDataWindow* GetDataWindow() = 0;
virtual IDataPlot* GetDataPlot() = 0;
virtual IBinningClass* GetBinningClass() = 0;
};
#endif // IDATAWINDOWSTUB_H
| 22.043478 | 74 | 0.714004 |
2f21068c6d3d1e6fb0e5deaef2b4e15cd3f90dbe | 1,667 | h | C | flashroute/prober.h | maxmouchet/FlashRoute | d4a6782f35cd5873687fee1c020e13bd1624f3df | [
"BSD-3-Clause"
] | 27 | 2020-09-22T21:35:53.000Z | 2022-02-22T01:47:04.000Z | flashroute/prober.h | maxmouchet/FlashRoute | d4a6782f35cd5873687fee1c020e13bd1624f3df | [
"BSD-3-Clause"
] | 3 | 2020-12-12T12:22:32.000Z | 2021-11-01T14:07:59.000Z | flashroute/prober.h | maxmouchet/FlashRoute | d4a6782f35cd5873687fee1c020e13bd1624f3df | [
"BSD-3-Clause"
] | 5 | 2021-02-25T08:08:44.000Z | 2022-01-04T02:12:10.000Z | /* Copyright (C) 2019 Neo Huang - All Rights Reserved */
#pragma once
#include <chrono>
#include <functional>
#include <iostream>
#include <string>
#include <arpa/inet.h>
#include <netinet/ip.h> // ip header
#include <netinet/ip_icmp.h> // icmp header
#include <netinet/tcp.h>
#include <netinet/udp.h> // udp header
#include "flashroute/address.h"
namespace flashroute {
enum class SocketType { UDP, ICMP, TCP };
const uint32_t kPacketMessageDefaultPayloadSize = 1500;
struct PacketIcmp {
struct ip ip;
struct icmp icmp;
} __attribute__((packed));
struct PacketUdp {
struct ip ip;
struct udphdr udp;
char payload[kPacketMessageDefaultPayloadSize];
} __attribute__((packed));
struct PacketTcp {
struct ip ip;
struct tcphdr tcp;
char payload[kPacketMessageDefaultPayloadSize];
} __attribute__((packed));
using PacketReceiverCallback =
std::function<void(const IpAddress& destination, const IpAddress& responder,
uint8_t distance, uint32_t rtt, bool fromDestination,
bool ipv4, void* packetHeader, size_t headerLen)>;
class Prober {
public:
virtual size_t packProbe(const IpAddress& destinationIp,
const IpAddress& sourceIp, const uint8_t ttl,
uint8_t* packetBuffer) = 0;
virtual void parseResponse(uint8_t* buffer, size_t size,
SocketType socketType) = 0;
virtual void setChecksumOffset(int32_t checksumOffset) = 0;
virtual uint64_t getChecksumMismatches() = 0;
virtual uint64_t getDistanceAbnormalities() = 0;
virtual uint64_t getOtherMismatches() = 0;
};
} // namespace flashroute
| 26.887097 | 80 | 0.692861 |
92261bf6dafe37508565a4992f944aa1a5ba0f87 | 230 | h | C | Example/FireBasePod/ggggViewController.h | tthufo/FireBasePod | e2f4aa53f93146c9db0e479c51538018aa77f597 | [
"MIT"
] | null | null | null | Example/FireBasePod/ggggViewController.h | tthufo/FireBasePod | e2f4aa53f93146c9db0e479c51538018aa77f597 | [
"MIT"
] | null | null | null | Example/FireBasePod/ggggViewController.h | tthufo/FireBasePod | e2f4aa53f93146c9db0e479c51538018aa77f597 | [
"MIT"
] | null | null | null | //
// ggggViewController.h
// FireBasePod_Example
//
// Created by Mac on 7/10/18.
// Copyright © 2018 tthufo@gmail.com. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ggggViewController : UIViewController
@end
| 16.428571 | 59 | 0.713043 |
f3ed2cd95d3e481db3026b2a858e18b68c48fa54 | 3,362 | h | C | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/AUImplDatePicker.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-03-29T12:08:37.000Z | 2021-05-26T05:20:11.000Z | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/AUImplDatePicker.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | null | null | null | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/AUImplDatePicker.h | ceekay1991/AliPayForDebug | 5795e5db31e5b649d4758469b752585e63e84d94 | [
"MIT"
] | 5 | 2020-04-17T03:24:04.000Z | 2022-03-30T05:42:17.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 <UIKit/UIPickerView.h>
#import "UIPickerViewDataSource-Protocol.h"
#import "UIPickerViewDelegate-Protocol.h"
@class NSArray, NSCalendar, NSDate, NSDateComponents, NSLocale, NSMutableDictionary, NSString, NSTimeZone;
@protocol AUImplDatePickerDelegate;
@interface AUImplDatePicker : UIPickerView <UIPickerViewDataSource, UIPickerViewDelegate>
{
NSDateComponents *_startComponets;
NSDateComponents *_endComponents;
NSDateComponents *_currentComponents;
NSMutableDictionary *_componentsStartDict;
NSMutableDictionary *_selectedRowDict;
NSArray *_componentModeArray;
_Bool _10165FixRollBack;
_Bool _skipRefreshOnWindow;
long long _datePickerMode;
NSLocale *_locale;
NSCalendar *_calendar;
NSTimeZone *_timeZone;
NSDate *_date;
NSDate *_minimumDate;
NSDate *_maximumDate;
id <AUImplDatePickerDelegate> _pickerDelegate;
}
@property(nonatomic) __weak id <AUImplDatePickerDelegate> pickerDelegate; // @synthesize pickerDelegate=_pickerDelegate;
@property(retain, nonatomic) NSDate *maximumDate; // @synthesize maximumDate=_maximumDate;
@property(retain, nonatomic) NSDate *minimumDate; // @synthesize minimumDate=_minimumDate;
@property(retain, nonatomic) NSDate *date; // @synthesize date=_date;
@property(retain, nonatomic) NSTimeZone *timeZone; // @synthesize timeZone=_timeZone;
@property(copy, nonatomic) NSCalendar *calendar; // @synthesize calendar=_calendar;
@property(retain, nonatomic) NSLocale *locale; // @synthesize locale=_locale;
@property(nonatomic) _Bool skipRefreshOnWindow; // @synthesize skipRefreshOnWindow=_skipRefreshOnWindow;
@property(nonatomic) long long datePickerMode; // @synthesize datePickerMode=_datePickerMode;
- (void).cxx_destruct;
- (double)pickerView:(id)arg1 widthForComponent:(long long)arg2;
- (id)pickerView:(id)arg1 attributedTitleForRow:(long long)arg2 forComponent:(long long)arg3;
- (void)pickerView:(id)arg1 didSelectRow:(long long)arg2 inComponent:(long long)arg3;
- (void)updateSelectedRow:(long long)arg1 components:(long long)arg2;
- (id)pickerView:(id)arg1 titleForRow:(long long)arg2 forComponent:(long long)arg3;
- (long long)pickerView:(id)arg1 numberOfRowsInComponent:(long long)arg2;
- (void)setSelectRow:(long long)arg1 forComponent:(unsigned long long)arg2;
- (void)updateCurrentValue;
- (id)selectedDate;
- (long long)convertToPickerComponent:(unsigned long long)arg1;
- (unsigned long long)convertToDateComponent:(long long)arg1;
- (long long)numberOfComponent:(unsigned long long)arg1;
- (void)willMoveToWindow:(id)arg1;
- (void)updateComponentValueDictForValue:(long long)arg1 forComponent:(unsigned long long)arg2;
- (unsigned long long)allParents:(unsigned long long)arg1;
- (unsigned long long)isSame2:(id)arg1 comp2:(id)arg2 unit:(unsigned long long)arg3;
- (long long)numberOfComponentsInPickerView:(id)arg1;
- (void)setCurrentDate:(id)arg1 animated:(_Bool)arg2;
- (void)reloadData;
- (id)initWithFrame:(struct CGRect)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 45.432432 | 120 | 0.783165 |
fa7f64ec1a03b9986160cffa00985cc5b60733d2 | 1,124 | h | C | Source/OroUnrealPrototype/Public/FXBaseBurstActor.h | sharaquss/OrotheGameUnrealPrototype | feb4e8791a75130b6bc3dd18ce383aea26bf3b3b | [
"MIT"
] | null | null | null | Source/OroUnrealPrototype/Public/FXBaseBurstActor.h | sharaquss/OrotheGameUnrealPrototype | feb4e8791a75130b6bc3dd18ce383aea26bf3b3b | [
"MIT"
] | 16 | 2017-03-01T22:28:08.000Z | 2017-03-11T20:13:14.000Z | Source/OroUnrealPrototype/Public/FXBaseBurstActor.h | sharaquss/OrotheGameUnrealPrototype | feb4e8791a75130b6bc3dd18ce383aea26bf3b3b | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "IFXBurst.h"
#include "FXBaseBurstActor.generated.h"
UCLASS()
class OROUNREALPROTOTYPE_API AFXBaseBurstActor : public AActor, public IIFXBurst
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AFXBaseBurstActor();
public:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
//IFXBurst
UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
void onCreate();
virtual void onCreate_Implementation() override;
UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
void onFxElapsed();
virtual void onFxElapsed_Implementation() override;
UFUNCTION(BlueprintNativeEvent, BlueprintCallable)
void onDestroy();
virtual void onDestroy_Implementation() override;
protected:
UPROPERTY(BlueprintReadOnly, VisibleAnywhere)
class UChildActorComponent *FxsGroup;
public:
UChildActorComponent* fxs_group() const
{
return FxsGroup;
}
};
| 22.039216 | 80 | 0.786477 |
7aae89a7625ca71af613cb13ccc14bd25ad83e99 | 11,200 | h | C | [Lib]__Engine/Sources/Common/ByteStream.h | yexiuph/RanOnline | 7f7be07ef740c8e4cc9c7bef1790b8d099034114 | [
"Apache-2.0"
] | null | null | null | [Lib]__Engine/Sources/Common/ByteStream.h | yexiuph/RanOnline | 7f7be07ef740c8e4cc9c7bef1790b8d099034114 | [
"Apache-2.0"
] | null | null | null | [Lib]__Engine/Sources/Common/ByteStream.h | yexiuph/RanOnline | 7f7be07ef740c8e4cc9c7bef1790b8d099034114 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include <GASSERT.h>
#include "./basestream.h"
class CByteStream : public basestream
{
public:
typedef std::vector<BYTE> BVECT;
typedef std::vector<BYTE>::iterator BVECT_IT;
protected:
BVECT m_Buffer;
DWORD m_dwIter;
public:
virtual BOOL operator << ( short Value );
virtual BOOL operator << ( int Value );
virtual BOOL operator << ( WORD Value );
virtual BOOL operator << ( DWORD Value );
virtual BOOL operator << ( UINT Value );
virtual BOOL operator << ( float Value );
virtual BOOL operator << ( double Value );
virtual BOOL operator << ( D3DVECTOR Value );
virtual BOOL operator << ( D3DCOLORVALUE &Value );
virtual BOOL operator << ( D3DBLEND &Value );
virtual BOOL operator << ( BYTE Value );
virtual BOOL operator << ( char Value );
virtual BOOL operator << ( const std::string &str );
virtual BOOL operator << ( bool Value );
virtual BOOL operator << ( __int64 Value );
template<typename TYPE>
BOOL operator << ( const std::vector<TYPE> &vecVALUE );
virtual BOOL WriteBuffer ( const void* pBuffer, DWORD Size );
public:
virtual BOOL operator >> ( short &Value );
virtual BOOL operator >> ( int &Value );
virtual BOOL operator >> ( WORD &Value );
virtual BOOL operator >> ( DWORD &Value );
virtual BOOL operator >> ( UINT &Value );
virtual BOOL operator >> ( float &Value );
virtual BOOL operator >> ( double &Value );
virtual BOOL operator >> ( D3DVECTOR &Value );
virtual BOOL operator >> ( D3DCOLORVALUE &Value );
virtual BOOL operator >> ( D3DBLEND &Value );
virtual BOOL operator >> ( BYTE &Value );
virtual BOOL operator >> ( char &Value );
virtual BOOL operator >> ( std::string &str );
virtual BOOL operator >> ( bool &Value );
virtual BOOL operator >> ( __int64 &Value );
template<typename TYPE>
BOOL operator >> ( std::vector<TYPE> &vecVALUE );
virtual BOOL ReadBuffer ( void* pBuffer, DWORD Size );
public:
virtual BOOL SetOffSet ( long _OffSet )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
if ( _OffSet>sizeBuff ) return FALSE;
m_dwIter = _OffSet;
return TRUE;
};
virtual long GetfTell ()
{
return m_dwIter;
}
public:
BOOL IsEmpty () { return m_Buffer.empty(); }
void GetBuffer ( LPBYTE &pBuff, DWORD &dwSize );
void ResetIter () { m_dwIter=0; }
void ClearBuffer ()
{
m_Buffer.clear();
m_dwIter=0;
}
public:
CByteStream ( const LPBYTE pBuff, const DWORD dwSize );
public:
CByteStream(void);
virtual ~CByteStream(void);
};
inline CByteStream::CByteStream(void) :
m_dwIter(0)
{
}
inline CByteStream::CByteStream ( const LPBYTE pBuff, const DWORD dwSize ) :
m_dwIter(0)
{
WriteBuffer ( pBuff, dwSize );
}
inline CByteStream::~CByteStream(void)
{
}
inline BOOL CByteStream::operator << ( short Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( int Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( WORD Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( DWORD Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( UINT Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( float Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( double Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( D3DVECTOR Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( D3DCOLORVALUE &Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( D3DBLEND &Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( BYTE Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( char Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( bool Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( __int64 Value )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(&Value), LPBYTE(&Value) + sizeof(Value) );
return TRUE;
}
inline BOOL CByteStream::operator << ( const std::string &str )
{
*this << DWORD(str.length()+1);
m_Buffer.insert ( m_Buffer.end(), LPBYTE(str.c_str()), LPBYTE(str.c_str()) + sizeof(char)*(str.length()+1) );
return TRUE;
}
inline BOOL CByteStream::WriteBuffer ( const void* pBuffer, DWORD Size )
{
m_Buffer.insert ( m_Buffer.end(), LPBYTE(pBuffer), LPBYTE(pBuffer)+Size );
return TRUE;
}
inline BOOL CByteStream::operator >> ( short &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( int &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( WORD &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( DWORD &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( UINT &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( float &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( double &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( D3DVECTOR &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( D3DCOLORVALUE &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( D3DBLEND &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( BYTE &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( char &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( bool &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( __int64 &Value )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(Value)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(Value)], LPBYTE(&Value) );
m_dwIter += sizeof(Value);
return TRUE;
}
inline BOOL CByteStream::operator >> ( std::string &str )
{
DWORD dwSize;
*this >> dwSize;
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
GASSERT ( sizeof(char)*dwSize<=DWORD(sizeBuff) );
char *szBuffer = new char[dwSize];
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+sizeof(char)*dwSize], LPBYTE(szBuffer) );
str = szBuffer;
delete[] szBuffer;
m_dwIter += sizeof(char)*dwSize;
return TRUE;
}
template<typename TYPE>
BOOL CByteStream::operator << ( const std::vector<TYPE> &vecVALUE )
{
BOOL bOK(FALSE);
bOK = operator << ( (DWORD)vecVALUE.size() );
if ( !bOK ) return FALSE;
if ( vecVALUE.empty() ) return TRUE;
return WriteBuffer ( &(vecVALUE[0]), DWORD(sizeof(TYPE)*vecVALUE.size()) );
}
template<typename TYPE>
BOOL CByteStream::operator >> ( std::vector<TYPE> &vecVALUE )
{
BOOL bOK(FALSE);
DWORD dwSize(0);
vecVALUE.clear();
bOK = operator >> ( dwSize );
if ( !bOK ) return FALSE;
if ( dwSize==0 ) return TRUE;
vecVALUE.reserve(dwSize);
for ( DWORD i=0; i<dwSize; ++i )
{
TYPE tVALUE;
bOK = ReadBuffer ( &tVALUE, DWORD(sizeof(TYPE)) );
if ( !bOK ) return FALSE;
vecVALUE.push_back ( tVALUE );
}
return TRUE;
}
inline BOOL CByteStream::ReadBuffer ( void* pBuffer, DWORD Size )
{
int sizeBuff = (int)(m_Buffer.end() - (m_Buffer.begin()+m_dwIter));
if ( (int)Size > sizeBuff ) return FALSE; //ERROR
GASSERT ( int(Size)<=sizeBuff );
std::copy ( &m_Buffer[m_dwIter], &m_Buffer[m_dwIter+Size], (LPBYTE)pBuffer );
m_dwIter += Size;
return TRUE;
}
inline void CByteStream::GetBuffer ( LPBYTE &pBuff, DWORD &dwSize )
{
pBuff = &m_Buffer[0];
dwSize = (DWORD) m_Buffer.size();
} | 24.295011 | 110 | 0.675446 |
ff98becbfd261b3a1d607b87f04890e7473ad6a6 | 168 | h | C | src/level.h | kdiduk/vagabond | 297cd73e6856e72d36222cadd54e556a34d04146 | [
"MIT"
] | 1 | 2020-12-04T18:35:49.000Z | 2020-12-04T18:35:49.000Z | src/level.h | kdiduk/fotd | 297cd73e6856e72d36222cadd54e556a34d04146 | [
"MIT"
] | 3 | 2020-11-24T22:32:39.000Z | 2020-11-28T23:26:09.000Z | src/level.h | kdiduk/vagabond | 297cd73e6856e72d36222cadd54e556a34d04146 | [
"MIT"
] | null | null | null | #ifndef LEVEL_H
#define LEVEL_H
#include <stdint.h>
void level_init(void);
void level_draw(void);
void level_player_move(uint8_t direction);
#endif /* LEVEL_H */
| 12 | 42 | 0.744048 |
9fa73d8d49460d679111763d585847f125c45994 | 1,189 | h | C | ash/mus/touch_transform_setter_mus.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/mus/touch_transform_setter_mus.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/mus/touch_transform_setter_mus.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_MUS_TOUCH_TRANSFORM_SETTER_MUS_H_
#define ASH_MUS_TOUCH_TRANSFORM_SETTER_MUS_H_
#include "base/macros.h"
#include "services/ui/public/interfaces/input_devices/touch_device_server.mojom.h"
#include "ui/display/manager/chromeos/touch_transform_setter.h"
namespace service_manager {
class Connector;
}
namespace ash {
// display::TouchTransformSetter implementation for mus. Updates are applied
// by way of ui::mojom::TouchDeviceServer.
class TouchTransformSetterMus : public display::TouchTransformSetter {
public:
explicit TouchTransformSetterMus(service_manager::Connector* connector);
~TouchTransformSetterMus() override;
// TouchTransformSetter:
void ConfigureTouchDevices(
const std::map<int32_t, double>& scales,
const std::vector<display::TouchDeviceTransform>& transforms) override;
private:
ui::mojom::TouchDeviceServerPtr touch_device_server_;
DISALLOW_COPY_AND_ASSIGN(TouchTransformSetterMus);
};
} // namespace ash
#endif // ASH_MUS_TOUCH_TRANSFORM_SETTER_MUS_H_
| 30.487179 | 82 | 0.798991 |
d72e16d0d174747a1c4b339594cbe1fe5daa57a2 | 1,412 | c | C | src/hdr2ddr/c_pxcopy.c | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 3 | 2017-12-31T05:33:28.000Z | 2021-07-28T01:51:22.000Z | src/asf_meta/c_pxcopy.c | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | null | null | null | src/asf_meta/c_pxcopy.c | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 7 | 2017-04-26T18:18:33.000Z | 2020-05-15T08:01:09.000Z | /*****************************************************************************
NAME pxcopy
PURPOSE Copy an input array to an output array. The
output array will be of the same type as the input array.
PROGRAM HISTORY
PROGRAMMER DATE REASON
---------- ---- ------
D.GORDON 5/7/85 Original development for NEWLAS
J.REED 11/12/85 Optimized byte portion of routine.
B.Ailts 12/87 Changed include directory specifications
Use raw 'C' types
Place bridge routines in a seperate file
B.Ailts 04/88 replaced newlas.a with las.a
B.Ailts 01/88 Added the VAX memory copy call to help speed up
pxcopy
COMPUTER HARDWARE AND/OR SOFTWARE LIMITATIONS
Part of the LAS system.
PROJECT NEWLAS
ALGORITHM
receive:
-the input array and its data type
-the output array
-the number of samples of the input array contains.
Multiply the number of samples times the number of bytes that the input array's
data type takes up
for each byte of the input arrays
copy each byte from each input array the output array
return
ALGORITHM REFERENCES none
*******************************************************************************/
#include "asf.h"
#include "worgen.h"
void FUNCTION c_pxcopy(const unsigned char *frombuf, unsigned char *tobuf, int dtype,int ns)
{
static int datasize[] = {0,1,2,4,4,8};
register int lcnt;
lcnt = ns * datasize[dtype];
memcpy(tobuf,frombuf,lcnt);
}
| 27.153846 | 92 | 0.648725 |
b5fc5c5d7480dc9245f9a1de7cd799e189f6921d | 1,558 | h | C | src/basegui/ToolBarImplementor.h | 0of/WebOS-Magna | a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511 | [
"Apache-2.0"
] | 1 | 2016-03-26T13:25:08.000Z | 2016-03-26T13:25:08.000Z | src/basegui/ToolBarImplementor.h | 0of/WebOS-Magna | a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511 | [
"Apache-2.0"
] | null | null | null | src/basegui/ToolBarImplementor.h | 0of/WebOS-Magna | a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511 | [
"Apache-2.0"
] | null | null | null | #ifndef TOOLBARIMPLEMENTOR_H
#define TOOLBARIMPLEMENTOR_H
#include <vector>
#include "basedef/RectRegion.h"
using namespace Magna::Core;
#include "ControllerImplementor.h"
#include "ToolBarElement.h"
namespace Magna{
namespace GUI{
class ToolBar;
class ToolBarImplementor : public ControllerImplementor{
__Constructor_Destructor public:
ToolBarImplementor( ToolBar& toolBar );
virtual ~ToolBarImplementor();
public:
virtual void mousePressed( MouseEventArgs& event );
virtual void mouseReleased( MouseEventArgs& event );
virtual void rendering( RenderingEventArgs& eventArgs );
public:
void _updateRenderArguments();
__Data_Field public:
FillBrush m_pressedBrush;
Pen m_borderPen;
std::vector<ToolBarElement> m_elements;
uint32 m_renderElementIndex : 30;
uint32 m_renderElementHovered : 1;
uint32 m_renderElementPressed : 1;
IntegerRectRegion m_realRect;
uint32 m_startRenderIndex;
uint32 m_endRenderIndex;
//contains text ,spacing & element size
IntegerSize m_eachElementSize;
//element side length
uint32 m_elmentSideLen;
ToolBar& m_toolBar;
uint32 m_orientation;
uint32 m_textHangingPolicy;
uint32 m_spacing;
uint32 m_logicalVerticalSpacing;
};
}//namespace GUI
}//namespace Magna
#endif /* TOOLBARIMPLEMENTOR_H */ | 24.34375 | 65 | 0.646983 |
80cf7779b306bcafb11b982805f1b59e5eadb79f | 1,439 | h | C | project3D/Scene.h | TorbjornMain/Graphics-Engine-Major-Project | 9fe7d2cd65906b452fdd17e6eafc6d3eefa69d42 | [
"MIT"
] | null | null | null | project3D/Scene.h | TorbjornMain/Graphics-Engine-Major-Project | 9fe7d2cd65906b452fdd17e6eafc6d3eefa69d42 | [
"MIT"
] | null | null | null | project3D/Scene.h | TorbjornMain/Graphics-Engine-Major-Project | 9fe7d2cd65906b452fdd17e6eafc6d3eefa69d42 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include "Model.h"
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "FrameBuffer.h"
#include "ParticleSystem.h"
#include "FieldVisualiser.h"
#include "typedefs.h"
struct Camera
{
glm::mat4 projection;
glm::mat4 view;
glm::mat4 transform;
};
class Scene
{
public:
Scene();
~Scene();
void drawToRenderTarget(const Camera& renderCam, FrameBuffer& buf, float time, int screenWidth, int screenHeight);
void draw(float time, int screenWidth, int screenHeight);
void AddInstance(char* name, Model* model, uint shader, uint texture, glm::mat4 transform);
void AddInstance(char* name, Model* model, uint shader, const char* textureFile, glm::mat4 transform);
void AddParticleSystem(char* name, glm::vec3 position, uint upShader, uint dShader, uint numParticles = 100000);
void AddVisualiser(char* name, glm::mat4 transform, uint field, glm::vec3 fieldShape);
ParticleSystem& GetParticleSystem(char* name);
Instance& GetInstance(char* name);
FieldVisualiser& GetVisualiser(char* name);
Camera getCamera() { return m_camera; }
void setCamera(Camera cam) { m_camera = cam; };
bool b_renderParticles = true;
bool b_renderModels = true;
bool b_renderGizmos = false;
bool b_renderVolumes = true;
private:
std::map<char* , Instance> m_instances;
std::map<char*, ParticleSystem> m_particleSystems;
std::map<char*, FieldVisualiser> m_volumetricFields;
glm::vec3 lightDir;
Camera m_camera;
};
| 29.367347 | 115 | 0.749131 |
c53b681456135051233463801bca942f1cfb7f33 | 1,666 | h | C | src/include/nuodb_common.h | nuodb/dbt2 | f24725f0c8f7a7a0286f077d553f0ad808faf48f | [
"Artistic-1.0"
] | 12 | 2015-03-27T08:57:22.000Z | 2021-06-15T13:43:08.000Z | src/include/nuodb_common.h | nuodb/dbt2 | f24725f0c8f7a7a0286f077d553f0ad808faf48f | [
"Artistic-1.0"
] | 6 | 2015-06-11T10:18:21.000Z | 2020-04-24T12:58:04.000Z | src/include/nuodb_common.h | nuodb/dbt2 | f24725f0c8f7a7a0286f077d553f0ad808faf48f | [
"Artistic-1.0"
] | 17 | 2015-02-26T21:55:02.000Z | 2021-06-15T11:35:02.000Z | #ifndef _NUODB_COMMON_H_
#define _NUODB_COMMON_H_
#include "nuodb_capi.h"
/*
#define NUODB_NEW_ORDER_2 \
"SELECT d_tax, (next value for order_seq) as order_id\n" \
"FROM district \n" \
"WHERE d_w_id = %d\n" \
" AND d_id = %d"
#define NUODB_NEW_ORDER_3 \
"UPDATE district\n" \
"SET d_next_o_id = %d\n" \
"WHERE d_w_id = %d\n" \
" AND d_id = %d"
#define NUODB_STOCK_LEVEL_1 \
"SELECT (next value for order_seq) as d_next_o_id\n" \
"FROM dual"
*/
struct db_context_t
{
nuodb_connection_t * connection;
};
typedef struct sql_result_t
{
nuodb_result_t * result_set;
char const * query;
size_t num_fields;
size_t num_rows;
size_t * lengths;
} sql_result_t;
int _connect_to_db(struct db_context_t * dbc);
int _disconnect_from_db(struct db_context_t * dbc);
int _db_init(
char const * database,
char const * username,
char const * password,
const char * timezone,
char const * schema);
/**
* Commit the transaction.
*/
int commit_transaction(
struct db_context_t * dbc);
/**
* Rollback the transaction.
*/
int rollback_transaction(
struct db_context_t * dbc);
int dbt2_sql_execute(
struct db_context_t * dbc,
char const * query,
struct sql_result_t * sql_result,
char const * query_name);
int dbt2_sql_close_cursor(
struct db_context_t * dbc,
struct sql_result_t * sql_result);
int dbt2_sql_fetchrow(
struct db_context_t * dbc,
struct sql_result_t * sql_result);
char * dbt2_sql_getvalue(
struct db_context_t * dbc,
struct sql_result_t * sql_result,
int field);
#endif /* _NUODB_COMMON_H_ */
| 20.317073 | 66 | 0.672269 |
413d4fe36394425c305183a69bff11de205160b7 | 678 | c | C | bc/1/pyramid 2.c | rulan87/devclab.bc | 04d29c63d2279041f3d1890974d070848bf0b82a | [
"Unlicense"
] | null | null | null | bc/1/pyramid 2.c | rulan87/devclab.bc | 04d29c63d2279041f3d1890974d070848bf0b82a | [
"Unlicense"
] | null | null | null | bc/1/pyramid 2.c | rulan87/devclab.bc | 04d29c63d2279041f3d1890974d070848bf0b82a | [
"Unlicense"
] | null | null | null | // Вывести в консоль числовую пирамидку на total строк.
// В каждой строке числа идут от единицы до номера строки через пробел.
// Пропустить rows строк и cols столбцов.
// В выводе не должно быть пустых строк до и после чисел.
// Целые положительные числа total, rows и cols считать с клавиатуры.
#include <stdio.h>
int main() {
int total, cols, rows;
scanf("%d %d %d", &total, &rows, &cols);
if ( rows < cols ) {
rows = cols;
}
for ( int row = rows + 1; row <= total; row++ ) {
for ( int col = cols + 1; col < row; col++ ) {
printf("%d ", col);
}
printf("%d\n", row);
}
return 0;
}
| 25.111111 | 71 | 0.561947 |
7e026328c9d86b90a8fd69329e9840a75b9cd045 | 2,177 | c | C | test/lanczos_test.c | cmendl/tensor_networks | da47a4699b1efcd6d5854760564f1b8b3c4b094b | [
"BSD-2-Clause"
] | 9 | 2018-12-28T19:11:08.000Z | 2021-08-17T19:31:31.000Z | test/lanczos_test.c | cmendl/tensor_networks | da47a4699b1efcd6d5854760564f1b8b3c4b094b | [
"BSD-2-Clause"
] | 1 | 2022-02-18T00:16:55.000Z | 2022-02-18T00:16:55.000Z | test/lanczos_test.c | cmendl/tensor_networks | da47a4699b1efcd6d5854760564f1b8b3c4b094b | [
"BSD-2-Clause"
] | 3 | 2020-04-08T13:10:47.000Z | 2021-08-17T19:31:47.000Z | #include "lanczos.h"
#include "linalg.h"
#include "util.h"
#include <stdint.h>
#include <math.h>
#include <stdio.h>
static void DenseMatrixVectorMult(const size_t n, const void *restrict data, const double complex *restrict v, double complex *restrict ret)
{
const double complex *A = (double complex *)data;
// perform a conventional matrix-vector multiplication
const double complex one = 1;
const double complex zero = 0;
cblas_zgemv(CblasColMajor, CblasNoTrans, n, n, &one, A, n, v, 1, &zero, ret, 1);
}
int LanczosTest()
{
// "large" matrix dimension
const size_t n = 256;
// number of iterations
const int maxiter = 24;
printf("Testing Lanczos iteration for matrix size %zu and %i iterations...\n", n, maxiter);
// load 'A' matrix from disk
double complex *A = (double complex *)algn_malloc(n*n * sizeof(double complex));
int status;
status = ReadData("../test/lanczos_test_A.dat", A, sizeof(double complex), n*n);
if (status < 0) { return status; }
// load starting vector from disk
double complex *v_start = (double complex *)algn_malloc(n * sizeof(double complex));
status = ReadData("../test/lanczos_test_v_start.dat", v_start, sizeof(double complex), n);
if (status < 0) { return status; }
// perform Lanczos iteration
double lambda_min;
double complex *v_min = (double complex *)algn_malloc(n * sizeof(double complex));
LanczosIteration(n, DenseMatrixVectorMult, A, v_start, maxiter, &lambda_min, v_min);
// load reference data from disk
double lambda_min_ref;
double complex *v_min_ref = algn_malloc(n * sizeof(double complex));
status = ReadData("../test/lanczos_test_lambda_min.dat", &lambda_min_ref, sizeof(double), 1); if (status < 0) { return status; }
status = ReadData("../test/lanczos_test_v_min.dat", v_min_ref, sizeof(double complex), n); if (status < 0) { return status; }
// largest entrywise error
double err = 0;
err = fmax(err, fabs(lambda_min - lambda_min_ref));
err = fmax(err, UniformDistance(n, v_min, v_min_ref));
printf("Largest error: %g\n", err);
// clean up
algn_free(v_min_ref);
algn_free(v_min);
algn_free(v_start);
algn_free(A);
return (err < 2e-14 ? 0 : 1);
}
| 32.492537 | 140 | 0.702802 |
24df5499d54228487b9910247855da01e9f065ab | 4,268 | c | C | customer_app/bl602_demo_joylink/components/joylink_adapter/pal/src/joylink_time.c | hjq-sir/bl_iot_sdk | abdd7b749e73b0655a9364e1a824a60b17f41118 | [
"Apache-2.0"
] | null | null | null | customer_app/bl602_demo_joylink/components/joylink_adapter/pal/src/joylink_time.c | hjq-sir/bl_iot_sdk | abdd7b749e73b0655a9364e1a824a60b17f41118 | [
"Apache-2.0"
] | null | null | null | customer_app/bl602_demo_joylink/components/joylink_adapter/pal/src/joylink_time.c | hjq-sir/bl_iot_sdk | abdd7b749e73b0655a9364e1a824a60b17f41118 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#if 0 //CSRC
#include <time.h>
#include <sys/time.h>
#endif
#include <FreeRTOS.h>
#include <task.h>
#include <bl_timer.h>
#include <utils_time.h>
#include "joylink_stdio.h"
#include "joylink_time.h"
static int64_t jl_time_delta_ms;
/**
* 初始化系统时间
*
* @return: 0 - success or -1 - fail
*
*/
int32_t jl_set_UTCtime(jl_time_stamp_t time_stamp)
{
#if 0 //CSRC
#ifdef __LINUX_PAL__
struct timeval tv;
tv.tv_sec = ts.second;
tv.tv_usec = ts.ms * 1000;
settimeofday(&tv, NULL);
#endif
#endif
// TODO: REPLACE ME
uint64_t timer_now_ms = bl_timer_now_us64() / 1000;
jl_time_delta_ms = ((int64_t)time_stamp.second * 1000 + time_stamp.ms) - (int64_t)timer_now_ms;
return 0;
}
/**
* @brief 获取系统UTC时间,精确到毫秒
* @param none
* @return time ms
*/
int jl_get_time_msec(jl_time_stamp_t *ts)
{
#if 0 //CSRC
#ifdef __LINUX_PAL__
struct timeval now;
if(gettimeofday(&now,NULL) == -1)
return -1;
if(ts)
{
ts->second = (uint32_t) now.tv_sec;
ts->ms = (uint32_t) (now.tv_usec/1000);
}
return 0;
#else
return -1;
#endif
#endif
uint64_t ts_ms = (int64_t)bl_timer_now_us64() / 1000 + jl_time_delta_ms;
if (ts) {
ts->second = ts_ms / 1000;
ts->ms = ts_ms % 1000;
}
return ts_ms;
}
/**
* 获取系统UTC时间,精确到秒
*
* @return: UTC Second
*
*/
uint32_t jl_get_time_second(uint32_t *jl_time)
{
#if 0 //CSRC
#ifdef __LINUX_PAL__
return (uint32_t)time(NULL);
#else
return 0;
#endif
#endif
uint64_t ts_ms = (int64_t)bl_timer_now_us64() / 1000 + jl_time_delta_ms;
return ts_ms / 1000;
}
int jl_get_time(jl_time_t *jl_time)
{
#if 0 //CSRC
#ifdef __LINUX_PAL__
time_t timep;
struct tm *p;
jl_time->timestamp = (uint32_t) jl_get_time_second(NULL);
p = gmtime(&timep);
jl_time->year = p->tm_year;
jl_time->month = p->tm_mon;
jl_time->week = p->tm_wday;
jl_time->day = p->tm_mday;
jl_time->hour = p->tm_hour;
jl_time->minute = p->tm_min;
jl_time->second = p->tm_sec;
#endif
return 0;
#endif
uint32_t ts = jl_get_time_second(NULL);
utils_time_date_t date;
utils_time_date_from_epoch(ts, &date);
jl_time->year = date.ntp_year - 1900;
jl_time->month = date.ntp_month;
jl_time->week = date.ntp_week_day;
jl_time->day = date.ntp_date;
jl_time->hour = date.ntp_hour;
jl_time->minute = date.ntp_minute;
jl_time->second = date.ntp_second;
jl_time->timestamp = ts;
return 0;
}
/**
* 获取时间字符串
*
* @out param: "year-month-day hour:minute:second.millisecond"
* @return: success or fail
*
*/
char *jl_get_time_str(void)
{
static char time_buffer[30];
#if 0 //CSRC
#ifdef __LINUX_PAL__
// 获取“年-月-日 时:分:秒.毫秒”字符串类型的时间戳
time_t timep;
jl_time_stamp_t ts;
struct tm *p;
time(&timep);
p = localtime(&timep);
jl_get_time_msec(&ts);
jl_platform_sprintf(time_buffer, "%02d-%02d-%02d %02d:%02d:%02d.%03d",
1900 + p->tm_year,
1 + p->tm_mon,
p->tm_mday,
p->tm_hour,
p->tm_min,
p->tm_sec,
ts.ms
);
#else
// 如果不能获取“年-月-日 时:分:秒.毫秒”时间戳,则获取UTC毫秒数时间戳
jl_time_stamp_t ts;
jl_get_time_msec(&ts);
jl_platform_sprintf(time_buffer, "%d%03d", ts.second, ts.ms);
#endif
#endif
jl_time_t jl_time;
jl_time_stamp_t ts;
jl_get_time(&jl_time);
jl_get_time_msec(&ts);
jl_platform_sprintf(time_buffer, "%02d-%02d-%02d %02d:%02d:%02d.%03d",
1900 + jl_time.year,
jl_time.month,
jl_time.day,
jl_time.hour,
jl_time.minute,
jl_time.second,
ts.ms
);
return time_buffer;
}
/**
* get os time
*
* @out param: none
* @return: sys time ticks ms since sys start
*/
uint32_t jl_get_os_time(void)
{
#if 0 //CSRC
#ifdef __LINUX_PAL__
return (uint32_t) jl_time_get_timestamp_ms(NULL); // FIXME do not recommand this method
// return clock();
#else
return 0;
#endif
#endif
return xTaskGetTickCount();
}
| 21.664975 | 100 | 0.597704 |
013c4a4eb3e6449fff1d916f084b63a2c1dfc60b | 947 | h | C | clib/stdafx.h | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 8 | 2016-08-29T13:34:18.000Z | 2020-12-04T15:20:36.000Z | clib/stdafx.h | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 221 | 2016-06-20T19:51:48.000Z | 2022-03-29T20:46:46.000Z | clib/stdafx.h | dehilsterlexis/eclide-1 | 0c1685cc7165191b5033d450c59aec479f01010a | [
"Apache-2.0"
] | 13 | 2016-06-24T15:59:31.000Z | 2022-01-01T11:48:20.000Z | #pragma once
#pragma warning(disable:4251)
#pragma warning(disable:4275)
#pragma warning(disable:4503)
#pragma warning(disable:4127)
// Leak Checking ---
#if defined(_DEBUG) && !defined(SEISINT_LIBEXPORTS)
#define _CRTDBG_MAP_ALLOC
#endif
// Target ---
#include "stdversion.h"
// Platform SDK ---
#include "stdplatform.h"
#include "wininet.h"
// ATL ---
#include "stdatl.h"
#include "atltime.h"
// WTL ---
#define _WTL_NO_CSTRING
#define _WTL_NO_WTYPES
#include <wtl/atlapp.h>
#define _Module (*_pModule)
#include "stdwtl.h"
// WTLEX ---
#include "atlwinmisc.h"
#undef _Module
// ATLSERVER ---
//#include <atlhtml.h>
//#include <atlsoap.h>
// STL ---
#include "stdstl.h"
// BOOST ---
#include "stdboost.h"
// Leak Checking ---
#if defined(_DEBUG) && !defined(SEISINT_LIBEXPORTS)
# include <stdlib.h>
# include <crtdbg.h>
# define GJS_DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
# define new GJS_DEBUG_NEW
#endif
| 18.211538 | 62 | 0.689546 |
4aba90e154ecd7268c3db38d319391d93eecd4df | 1,273 | h | C | DTSource/Support/DTLock.h | newby-jay/AshbyaTracking | 9e80513d52281cf51d35bfef1e164148a9d3439e | [
"Apache-2.0"
] | null | null | null | DTSource/Support/DTLock.h | newby-jay/AshbyaTracking | 9e80513d52281cf51d35bfef1e164148a9d3439e | [
"Apache-2.0"
] | null | null | null | DTSource/Support/DTLock.h | newby-jay/AshbyaTracking | 9e80513d52281cf51d35bfef1e164148a9d3439e | [
"Apache-2.0"
] | null | null | null | // Part of DTSource. Copyright 2004-2015. David A. David Adalsteinsson.
// see https://www.visualdatatools.com/DTSource/license.html for more information.
#ifndef _DTLock_Header
#define _DTLock_Header
// Assignment and copy constructors are not thread safe for this class.
#ifndef DTUseThreads
#define DTUseThreads 0
#endif
#if DTUseThreads
#include <pthread.h>
#endif
class DTLock {
public:
#if DTUseThreads
DTLock() : mutexLock(NULL) {mutexLock = new pthread_mutex_t(); pthread_mutex_init(mutexLock,NULL);}
~DTLock() {pthread_mutex_destroy(mutexLock); delete mutexLock;}
bool operator==(const DTLock &L) const {return (mutexLock==L.mutexLock);}
void Lock(void) const {pthread_mutex_lock(mutexLock);}
bool TryLock(void) const {return (pthread_mutex_trylock(mutexLock)==0);}
void Unlock(void) const {pthread_mutex_unlock(mutexLock);}
#else
DTLock() {}
~DTLock() {}
bool operator==(const DTLock &L) const {return false;}
void Lock(void) const {}
bool TryLock(void) const {return true;}
void Unlock(void) const {}
#endif
private:
// Can not copy this object.
DTLock(const DTLock &ToC);
DTLock &operator=(const DTLock &ToC);
#if DTUseThreads
pthread_mutex_t *mutexLock;
#endif
};
#endif
| 24.960784 | 103 | 0.711705 |
006168fbe265cd19f5c8033fc338e5eadbc42391 | 2,525 | h | C | IbAccess/Common/Public/isysutil.h | dsilakov/opa-fm | 72d7942fd7f33c1b67d8cd981efe1bd8733ef54a | [
"Intel"
] | 4 | 2018-05-26T14:03:22.000Z | 2019-05-14T09:56:19.000Z | IbAccess/Common/Public/isysutil.h | dsilakov/opa-fm | 72d7942fd7f33c1b67d8cd981efe1bd8733ef54a | [
"Intel"
] | 10 | 2018-07-24T14:21:58.000Z | 2019-10-30T18:07:00.000Z | IbAccess/Common/Public/isysutil.h | dsilakov/opa-fm | 72d7942fd7f33c1b67d8cd981efe1bd8733ef54a | [
"Intel"
] | 8 | 2018-07-29T18:21:10.000Z | 2020-01-07T18:10:19.000Z | /* BEGIN_ICS_COPYRIGHT3 ****************************************
Copyright (c) 2015, Intel Corporation
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 Intel Corporation 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.
** END_ICS_COPYRIGHT3 ****************************************/
/* [ICS VERSION STRING: unknown] */
#ifndef _IBA_PUBLIC_ISYSUTIL_H_
#define _IBA_PUBLIC_ISYSUTIL_H_
#include "iba/public/datatypes.h"
#include "iba/public/isysutil_osd.h"
/* Assorted System Utility Functions */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(VXWORKS)
/* obtain the System Node Name. Any domain name suffix is removed
* remainder is copied to dest for up to dest_len characters
* if dest_len is < strlen(node name), dest is not \0 terminated.
* returns dest
*/
extern char *SystemGetNodeName(char *dest, uint32 dest_len);
extern void SystemSeedRandom(unsigned long entropy);
extern unsigned long SystemGetRandom(void);
/* OS specific header will define 2 functions:
* boolean SystemIncModuleRefCount(void)
* void SystemDecModuleRefCount(void)
*/
#endif /* defined(VXWORKS) */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _IBA_PUBLIC_ISYSUTIL_H_ */
| 39.453125 | 78 | 0.754455 |
6d4eacf9ad93809340be3ed94cb72931f1def004 | 356 | c | C | university-c-training/HwLab/HwLab5.1_353.c | phumoonlight/ossuary | 7f0465ee83cd127d76ecc04b5e6b87f73274356e | [
"MIT"
] | null | null | null | university-c-training/HwLab/HwLab5.1_353.c | phumoonlight/ossuary | 7f0465ee83cd127d76ecc04b5e6b87f73274356e | [
"MIT"
] | null | null | null | university-c-training/HwLab/HwLab5.1_353.c | phumoonlight/ossuary | 7f0465ee83cd127d76ecc04b5e6b87f73274356e | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<conio.h>
int main()
{
int i=1,v=0,a=0;
char ch;
do
{
printf("Enter your letter = ");
ch=getche();
printf("\n");
i++;
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
{
v++;
}else
{
a++;
}
}
while(i<=10);
printf("\nVowel = %d\n",v);
printf("Alphabet = %d\n",a);
system("pause");
return 0;
}
| 11.866667 | 49 | 0.47191 |
a3a4d3b6bb7f0b75bd6e90db12718f776005c9f0 | 1,504 | h | C | tools/flang1/flang1exe/findloop.h | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | 1 | 2019-12-11T17:43:58.000Z | 2019-12-11T17:43:58.000Z | tools/flang1/flang1exe/findloop.h | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | 2 | 2019-12-29T21:15:40.000Z | 2020-06-15T11:21:10.000Z | tools/flang1/flang1exe/findloop.h | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | 3 | 2019-12-21T06:35:35.000Z | 2020-06-07T23:18:58.000Z | /*
* Copyright (c) 2018, NVIDIA 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.
*
*/
#ifndef FINDLOOP_H_
#define FINDLOOP_H_
#include "universal.h"
#include <stdio.h>
/**
\brief ...
*/
bool contains_loop(int lp1, int lp2);
/**
\brief ...
*/
bool is_childloop(int lp1, int lp2);
/**
\brief ...
*/
bool is_dominator(int v, int w);
/**
\brief ...
*/
bool is_post_dominator(int v, int w);
/**
\brief ...
*/
bool is_tail_aexe(int lp);
/**
\brief ...
*/
bool overlapping_loops(int lp1, int lp2);
/**
\brief ...
*/
void __dump_loop(FILE *ff, int lp);
/**
\brief ...
*/
void dump_loops(void);
/**
\brief ...
*/
void __dump_region(FILE *ff, int lp);
/**
\brief ...
*/
void dump_region(int lp);
/**
\brief ...
*/
void findloop(int hlopt_bv);
/**
\brief ...
*/
void findlooptopsort(void);
/**
\brief ...
*/
void reorderloops(void);
/**
\brief ...
*/
void sortloops(void);
#endif // FINDLOOP_H_
| 15.831579 | 75 | 0.633644 |
9360d22f4c0fbfc3a2ce3a5d8be81406575ee9f7 | 573 | h | C | v1/modules/identitymap/inc/identitymap.h | outotec/iot-edge | 999e2586b597b2ff17544daf63722edfe143b52e | [
"MIT"
] | 138 | 2018-06-28T18:02:55.000Z | 2022-03-18T04:38:15.000Z | v1/modules/identitymap/inc/identitymap.h | outotec/iot-edge | 999e2586b597b2ff17544daf63722edfe143b52e | [
"MIT"
] | 215 | 2016-05-02T11:38:35.000Z | 2017-05-09T11:32:44.000Z | v1/modules/identitymap/inc/identitymap.h | outotec/iot-edge | 999e2586b597b2ff17544daf63722edfe143b52e | [
"MIT"
] | 132 | 2016-04-29T17:23:03.000Z | 2017-05-08T22:09:24.000Z | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#ifndef IDENTITYMAP_H
#define IDENTITYMAP_H
#include "module.h"
#ifdef __cplusplus
extern "C"
{
#endif
typedef struct IDENTITY_MAP_CONFIG_TAG
{
const char* macAddress;
const char* deviceId;
const char* deviceKey;
} IDENTITY_MAP_CONFIG;
MODULE_EXPORT const MODULE_API* MODULE_STATIC_GETAPI(IDENTITYMAP_MODULE)(MODULE_API_VERSION gateway_api_version);
#ifdef __cplusplus
}
#endif
#endif /*IDENTITYMAP_H*/
| 20.464286 | 113 | 0.78185 |
d8f1778462bcd93337b8ed4c93bb91aefaaf7c7e | 62 | h | C | source/script/python/UIModule.h | freneticmonkey/epsilonc | 0fb7c6c4c6342a770e2882bfd67ed34719e79066 | [
"MIT"
] | null | null | null | source/script/python/UIModule.h | freneticmonkey/epsilonc | 0fb7c6c4c6342a770e2882bfd67ed34719e79066 | [
"MIT"
] | null | null | null | source/script/python/UIModule.h | freneticmonkey/epsilonc | 0fb7c6c4c6342a770e2882bfd67ed34719e79066 | [
"MIT"
] | null | null | null | #pragma once
#include "script/ScriptCommon.h"
void initUI(); | 12.4 | 32 | 0.741935 |
7f3f1334995e7905d133cf1888a4aa5beda56597 | 972 | c | C | sim/prog5/ap_prog/main.c | yutongshen/RISC-V-Simulator | 6ba9f6ae516a35829c78542944afa6817a6ff01d | [
"MIT"
] | 7 | 2020-03-24T09:41:13.000Z | 2021-06-18T09:19:39.000Z | sim/prog5/ap_prog/main.c | yutongshen/RISC-V-Simulator | 6ba9f6ae516a35829c78542944afa6817a6ff01d | [
"MIT"
] | null | null | null | sim/prog5/ap_prog/main.c | yutongshen/RISC-V-Simulator | 6ba9f6ae516a35829c78542944afa6817a6ff01d | [
"MIT"
] | 2 | 2020-03-24T18:17:48.000Z | 2021-06-18T09:19:39.000Z | void merge(short *list, int a, int b, int b_end)
{
int start = a;
int a_end = b;
int i = 0;
short buff[b_end - a];
asm("nop");
while (a != a_end && b != b_end) {
if (list[a] <= list[b])
buff[i++] = list[a++];
else
buff[i++] = list[b++];
}
while (a != a_end)
buff[i++] = list[a++];
while (b != b_end)
buff[i++] = list[b++];
while (i--)
list[start + i] = buff[i];
}
void merge_sort(short *list, int left, int right)
{
if (left >= right) {
return;
}
int mid = (left + right) >> 1;
merge_sort(list, left, mid);
merge_sort(list, mid + 1, right);
merge(list, left, mid + 1, right + 1);
}
int main(void)
{
extern int array_size;
extern short array_addr[];
extern short _test_start[];
merge_sort(array_addr, 0, array_size - 1);
for (int i = 0; i < array_size; ++i)
_test_start[i] = array_addr[i];
return 0;
}
| 22.090909 | 49 | 0.501029 |
fa0b3ec0e80f8fcfdfadb55fc7f6ac0c8153b51a | 1,255 | h | C | GI-MonteCarlo/monte-carlo-raytracer/Renderers/OpenMPRenderer.h | micma909/MonteCarloRaytraycer | 7ea086158028deb3c7de340a46d5626faefdfade | [
"MIT"
] | 3 | 2020-01-09T08:30:46.000Z | 2021-08-18T19:08:23.000Z | GI-MonteCarlo/monte-carlo-raytracer/Renderers/OpenMPRenderer.h | micma909/MonteCarloRaytraycer | 7ea086158028deb3c7de340a46d5626faefdfade | [
"MIT"
] | null | null | null | GI-MonteCarlo/monte-carlo-raytracer/Renderers/OpenMPRenderer.h | micma909/MonteCarloRaytraycer | 7ea086158028deb3c7de340a46d5626faefdfade | [
"MIT"
] | 1 | 2022-02-15T08:37:00.000Z | 2022-02-15T08:37:00.000Z | #ifndef OpenMPRenderer_H
#define OpenMPRenderer_H
#include "Renderer.h"
#include "Cameras/Camera.h"
#include "Spectrum/CIE.h"
#include <iomanip>
//#include <ncurses.h>
#include "Util/spectrum.h"
#ifdef __APPLE__
#include <omp.h>
#elif defined _WIN32 || defined _WIN64
#include <C:/MinGW32/lib/gcc/mingw32/4.7.0/include/omp.h>
#endif
template<int W,int H>
class OpenMPRenderer : public Renderer<W,H>{
private:
int samples_per_pixel_;
public:
DYN_FNK(percentage_callback, void,int,float,float,float,float);
DYN_FNK(pass_finished_callback, void,const OpenMPRenderer<W,H> *,const Vec3<float> *image,int);
public:
OpenMPRenderer(const std::shared_ptr<LightModel> &lightModel,
const std::shared_ptr<Camera> &camera
int samples_per_pixel):Renderer<W,H>(lightModel, camera),samples_per_pixel_(samples_per_pixel){
//spectrum_ = Spectrum::visible(100);
}
void compute(Vec3<float> *image) const{
//Rasterizer r(camera);
omp_set_num_threads(8);
#pragma omp parallel shared(image)
{
#pragma omp single
{
std::cout << omp_get_num_threads() << std::endl << "progress:" << std::endl;
}
}
}
};
#endif | 25.1 | 103 | 0.656574 |
368bb4a795213c722c750bf3c6945e58d6f9936b | 4,148 | h | C | couchbasejs/node_modules/couchbase/iojs-1.6.0/src/async-wrap.h | Jacqueline95/nosql | 30de35ac22cda872fcc7330f28632f50692c2218 | [
"MIT"
] | null | null | null | couchbasejs/node_modules/couchbase/iojs-1.6.0/src/async-wrap.h | Jacqueline95/nosql | 30de35ac22cda872fcc7330f28632f50692c2218 | [
"MIT"
] | null | null | null | couchbasejs/node_modules/couchbase/iojs-1.6.0/src/async-wrap.h | Jacqueline95/nosql | 30de35ac22cda872fcc7330f28632f50692c2218 | [
"MIT"
] | null | null | null | #ifndef SRC_ASYNC_WRAP_H_
#define SRC_ASYNC_WRAP_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "base-object.h"
#include "uv.h"
#include "v8.h"
#include <stdint.h>
namespace node {
#define NODE_ASYNC_ID_OFFSET 0xA1C
#define NODE_ASYNC_PROVIDER_TYPES(V) \
V(NONE) \
V(CRYPTO) \
V(FSEVENTWRAP) \
V(FSREQWRAP) \
V(GETADDRINFOREQWRAP) \
V(GETNAMEINFOREQWRAP) \
V(HTTPPARSER) \
V(JSSTREAM) \
V(PIPEWRAP) \
V(PIPECONNECTWRAP) \
V(PROCESSWRAP) \
V(QUERYWRAP) \
V(SHUTDOWNWRAP) \
V(SIGNALWRAP) \
V(STATWATCHER) \
V(TCPWRAP) \
V(TCPCONNECTWRAP) \
V(TIMERWRAP) \
V(TLSWRAP) \
V(TTYWRAP) \
V(UDPWRAP) \
V(UDPSENDWRAP) \
V(WRITEWRAP) \
V(ZLIB)
class Environment;
class AsyncWrap : public BaseObject {
public:
enum ProviderType {
#define V(PROVIDER) \
PROVIDER_ ## PROVIDER,
NODE_ASYNC_PROVIDER_TYPES(V)
#undef V
};
AsyncWrap(Environment* env,
v8::Local<v8::Object> object,
ProviderType provider,
AsyncWrap* parent = nullptr);
virtual ~AsyncWrap();
static void Initialize(v8::Local<v8::Object> target,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context);
static void DestroyIdsCb(uv_idle_t* handle);
inline ProviderType provider_type() const;
inline int64_t get_uid() const;
// Only call these within a valid HandleScope.
v8::Local<v8::Value> MakeCallback(const v8::Local<v8::Function> cb,
int argc,
v8::Local<v8::Value>* argv);
inline v8::Local<v8::Value> MakeCallback(const v8::Local<v8::String> symbol,
int argc,
v8::Local<v8::Value>* argv);
inline v8::Local<v8::Value> MakeCallback(uint32_t index,
int argc,
v8::Local<v8::Value>* argv);
virtual size_t self_size() const = 0;
private:
inline AsyncWrap();
inline bool ran_init_callback() const;
// When the async hooks init JS function is called from the constructor it is
// expected the context object will receive a _asyncQueue object property
// that will be used to call pre/post in MakeCallback.
uint32_t bits_;
const int64_t uid_;
};
void LoadAsyncWrapperInfo(Environment* env);
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_ASYNC_WRAP_H_
| 41.069307 | 80 | 0.375362 |
cfcc38f327526d6a3f0e25bb04b05f3d63b44362 | 1,940 | c | C | assets/levelselect_map.c | irishgreencitrus/maze-rage-demo | d1e79ef6b4b58a5058a63d363442c3b35cbff0b2 | [
"MIT"
] | null | null | null | assets/levelselect_map.c | irishgreencitrus/maze-rage-demo | d1e79ef6b4b58a5058a63d363442c3b35cbff0b2 | [
"MIT"
] | null | null | null | assets/levelselect_map.c | irishgreencitrus/maze-rage-demo | d1e79ef6b4b58a5058a63d363442c3b35cbff0b2 | [
"MIT"
] | 1 | 2021-10-02T17:48:21.000Z | 2021-10-02T17:48:21.000Z | /*
Generated By GameBoyPngConverter
Tiles map
TileMap Size : 20 x 18
*/
const unsigned char levelselect_map[] = {
0x00,0x01,0x01,0x01,0x02,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x03,0x04,0x05,0x06,0x05,0x04,0x07,0x08,0x05,0x04,0x05,0x08,0x09,0x0A,0x01,0x01,0x02,0x00,0x01,0x01,0x0B,0x0C,0x0D,0x0E,0x0D,0x0C,0x0F,0x10,0x0D,0x0C,0x0D,0x11,0x12,0x13,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x14,0x01,0x01,0x15,0x01,0x01,0x16,0x01,0x01,0x14,0x17,0x01,0x14,0x18,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x19,0x01,0x01,0x1A,0x01,0x01,0x1B,0x01,0x01,0x14,0x14,0x01,0x14,0x15,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x18,0x01,0x01,0x1C,0x01,0x01,0x1D,0x01,0x01,0x14,0x19,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x1E,0x1E,0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x1E,0x1E,0x1E,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x2B,0x2C,0x2D,0x2E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x1E,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x2E,0x2F,0x30,0x31,0x01,0x01,0x32,0x2F,0x33,0x2D,0x01,0x01,0x01,0x01,0x02,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02
}; | 176.363636 | 1,801 | 0.786598 |
82b50d0c04520ec3e327a1f6fffbf2c0cf30a86f | 1,358 | h | C | objective c/CtCILibrary/CtCILibrary/AssortedMethods.h | Kiandr/crackingcodinginterview | b499f5bc704ce24f8826d5facfaf6a3cc996a86a | [
"Apache-2.0"
] | null | null | null | objective c/CtCILibrary/CtCILibrary/AssortedMethods.h | Kiandr/crackingcodinginterview | b499f5bc704ce24f8826d5facfaf6a3cc996a86a | [
"Apache-2.0"
] | null | null | null | objective c/CtCILibrary/CtCILibrary/AssortedMethods.h | Kiandr/crackingcodinginterview | b499f5bc704ce24f8826d5facfaf6a3cc996a86a | [
"Apache-2.0"
] | null | null | null | //
// AssortedMethods.h
//
//
// Created by Ryan Moniz on 11/27/2013.
//
//
#import <Foundation/Foundation.h>
@interface AssortedMethods : NSObject
+(AssortedMethods *)sharedInstance;
- (int)randomInt:(int)n;
- (int)randomIntInRange:(int)min to:(int)max;
- (BOOL)randomBoolean;
- (BOOL)randomBoolean:(int)percentTrue;
- (void)randomMatrix:(int **)array sizeOf:(int)m by:(int)n min:(int)min max:(int)max;
- (void)randomArray:(int *)array sizeOf:(int)size min:(int)min max:(int)max;
//- (LinkedListNode)randomLinkedList:(int)n min:(int)min max:(int)max;
//- (LinkedListNode)linkedListWithValue:(int)n value:(int)value;
- (NSString *)arrayToString:(int *)array size:(int)size;
- (NSString *)stringArrayToString:(NSArray *)array;
//- (NSString *)toFullBinaryString:(int)a;
//- (NSString *)toBaseNString:(int)a base:(int)base;
//- (void)printMatrix:(int[][])matrix;
//- (void)printMatrix:(BOOL[][])matrix;
//- (void)printIntArray:(int[])array;
//- (NSString *)charArrayToString:(char [])array;
//- (NSString *)listOfPointsToString:(NSArray *)pointsArray;
//- (TreeNode)randomBST(int)N min:(int)min max:(int)max;
//- (TreeNode)createTreeFromeArray:(int[])array;
//- (NSString *)getLongTextBlob;
//- (NSArray *)getLongTextBlobAsStringList;
//- (Trie)getTrieDictionary;
//- (NSArray *)getListOfWords;
- (NSArray *)getCharacterArray:(NSString *)string;
@end
| 33.121951 | 85 | 0.704713 |
c5bdbf0539f06e47fd689aa8b7f6744b067dd321 | 29,289 | h | C | C/syntax/SyntaxDumper.h | ltcmelo/psychec | 00963d2d18b7a55d8dd469ea8d34424c2d996713 | [
"BSD-3-Clause"
] | 435 | 2016-11-07T23:16:51.000Z | 2022-03-27T16:16:00.000Z | C/syntax/SyntaxDumper.h | ltcmelo/psychec | 00963d2d18b7a55d8dd469ea8d34424c2d996713 | [
"BSD-3-Clause"
] | 46 | 2016-11-09T14:08:41.000Z | 2022-03-08T01:25:36.000Z | C/syntax/SyntaxDumper.h | ltcmelo/psychec | 00963d2d18b7a55d8dd469ea8d34424c2d996713 | [
"BSD-3-Clause"
] | 32 | 2016-11-09T12:54:14.000Z | 2022-03-20T10:08:44.000Z | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** Modifications (apply on the LGPL usage):
** Copyright (c) 2016-20 Leandro T. C. Melo (ltcmelo@gmail.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
/////////////////////////////////////////////////////////////////////
///// Note about copyright/licesing /////
///// /////
///// This file, which is copyrighed by NOKIA/Digia/Qt Company, /////
///// is licensed under LGPL, as opposed to most of the files /////
///// of the Psyche project, which are licensed under BSD. This /////
///// version has been modified by Leandro T. C. Melo. /////
/////////////////////////////////////////////////////////////////////
#ifndef PSYCHE_C_SYNTAX_DUMPER_H__
#define PSYCHE_C_SYNTAX_DUMPER_H__
#include "API.h"
#include "SyntaxLexemes.h"
#include "SyntaxNodes.h"
#include "SyntaxVisitor.h"
namespace psy {
namespace C {
class PSY_C_API SyntaxDumper : protected SyntaxVisitor
{
public:
SyntaxDumper(SyntaxTree* tree)
: SyntaxVisitor(tree)
{}
protected:
virtual void terminal(const SyntaxToken&, const SyntaxNode*) {}
virtual void nonterminal(const SyntaxNode* node) { visit(node); }
//--------------//
// Declarations //
//--------------//
virtual Action visitTranslationUnit(const TranslationUnitSyntax* node) override
{
for (auto iter = node->declarations(); iter; iter = iter->next)
nonterminal(iter->value);
return Action::Skip;
}
void traverseDeclaration(const DeclarationSyntax* node)
{
terminal(node->extensionKeyword(), node);
}
virtual Action visitEmptyDeclaration(const EmptyDeclarationSyntax* node) override
{
traverseDeclaration(node);
for (auto it = node->specifiers(); it; it = it->next)
nonterminal(it->value);
terminal(node->semicolonToken(), node);
return Action::Skip;
}
void traverseTypeDeclaration(const TypeDeclarationSyntax* node)
{
traverseDeclaration(node);
nonterminal(node->typeSpecifier());
terminal(node->semicolonToken(), node);
}
virtual Action visitStructOrUnionDeclaration(const StructOrUnionDeclarationSyntax* node) override
{
traverseTypeDeclaration(node);
return Action::Skip;
}
virtual Action visitEnumDeclaration(const EnumDeclarationSyntax* node) override
{
traverseTypeDeclaration(node);
return Action::Skip;
}
virtual Action visitEnumMemberDeclaration(const EnumMemberDeclarationSyntax* node) override
{
traverseDeclaration(node);
terminal(node->identifierToken(), node);
for (auto iter = node->attributes(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->equalsToken(), node);
nonterminal(node->expression());
terminal(node->commaToken(), node);
return Action::Skip;
}
virtual Action visitVariableAndOrFunctionDeclaration(const VariableAndOrFunctionDeclarationSyntax* node) override
{
traverseDeclaration(node);
for (auto iter = node->specifiers(); iter; iter = iter->next)
nonterminal(iter->value);
for (auto iter = node->declarators(); iter; iter = iter->next) {
nonterminal(iter->value);
terminal(iter->delimiterToken(), node);
}
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitFieldDeclaration(const FieldDeclarationSyntax* node) override
{
traverseDeclaration(node);
for (auto iter = node->specifiers(); iter; iter = iter->next)
nonterminal(iter->value);
for (auto iter = node->declarators(); iter; iter = iter->next) {
nonterminal(iter->value);
terminal(iter->delimiterToken(), node);
}
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitParameterDeclaration(const ParameterDeclarationSyntax* node) override
{
for (auto iter = node->specifiers(); iter; iter = iter->next)
nonterminal(iter->value);
nonterminal(node->declarator());
return Action::Skip;
}
virtual Action visitStaticAssertDeclaration(const StaticAssertDeclarationSyntax* node) override
{
terminal(node->staticAssertKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->expression());
terminal(node->commaToken(), node);
nonterminal(node->stringLiteral());
terminal(node->closeParenthesisToken(), node);
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitFunctionDefinition(const FunctionDefinitionSyntax* node) override
{
traverseDeclaration(node);
for (auto iter = node->specifiers(); iter; iter = iter->next)
nonterminal(iter->value);
nonterminal(node->declarator());
nonterminal(node->body());
return Action::Skip;
}
virtual Action visitExtGNU_AsmStatementDeclaration(const ExtGNU_AsmStatementDeclarationSyntax* node) override
{
traverseDeclaration(node);
terminal(node->asmKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->stringLiteral());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
/* Specifiers */
virtual Action visitTrivialSpecifier_Common(const TrivialSpecifierSyntax* node)
{
terminal(node->specifierToken(), node);
return Action::Skip;
}
virtual Action visitStorageClass(const StorageClassSyntax* node) override
{
return visitTrivialSpecifier_Common(node);
}
virtual Action visitBuiltinTypeSpecifier(const BuiltinTypeSpecifierSyntax* node) override
{
return visitTrivialSpecifier_Common(node);
}
virtual Action visitTaggedTypeSpecifier(const TaggedTypeSpecifierSyntax* node) override
{
terminal(node->taggedKeyword(), node);
for (auto iter = node->attributes(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->identifierToken(), node);
terminal(node->openBraceToken(), node);
for (auto iter = node->declarations(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->closeBraceToken(), node);
for (auto iter = node->attributes_PostCloseBrace(); iter; iter = iter->next)
nonterminal(iter->value);
return Action::Skip;
}
virtual Action visitAtomicTypeSpecifier(const AtomicTypeSpecifierSyntax* node) override
{
terminal(node->atomicKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->typeName());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitTypedefName(const TypedefNameSyntax* node) override
{
terminal(node->identifierToken(), node);
return Action::Skip;
}
virtual Action visitTypeQualifier(const TypeQualifierSyntax* node) override
{
return visitTrivialSpecifier_Common(node);
}
virtual Action visitFunctionSpecifier(const FunctionSpecifierSyntax* node) override
{
return visitTrivialSpecifier_Common(node);
}
virtual Action visitAlignmentSpecifier(const AlignmentSpecifierSyntax* node) override
{
terminal(node->alignasKeyword(), node);
nonterminal(node->tyReference());
return Action::Skip;
}
virtual Action visitExtGNU_Typeof(const ExtGNU_TypeofSyntax* node) override
{
terminal(node->typeofKeyword(), node);
nonterminal(node->tyReference());
return Action::Skip;
}
virtual Action visitExtGNU_AttributeSpecifier(const ExtGNU_AttributeSpecifierSyntax* node) override
{
terminal(node->attributeKeyword(), node);
terminal(node->openOuterParenthesisToken(), node);
terminal(node->openInnerParenthesisToken(), node);
for (auto iter = node->attributes(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->closeInnerParenthesisToken(), node);
terminal(node->closeOuterParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitExtGNU_Attribute(const ExtGNU_AttributeSyntax* node) override
{
terminal(node->keywordOrIdentifierToken(), node);
terminal(node->openParenthesisToken(), node);
for (auto iter = node->expressions(); iter; iter = iter->next) {
nonterminal(iter->value);
terminal(iter->delimiterToken(), node);
}
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitExtGNU_AsmLabel(const ExtGNU_AsmLabelSyntax* node) override
{
terminal(node->asmKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->stringLiteral());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
/* Declarators */
virtual Action visitArrayOrFunctionDeclarator(const ArrayOrFunctionDeclaratorSyntax* node) override
{
for (auto iter = node->attributes(); iter; iter = iter->next)
nonterminal(iter->value);
nonterminal(node->innerDeclarator());
nonterminal(node->suffix());
for (auto iter = node->attributes_PostDeclarator(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->equalsToken(), node);
nonterminal(node->initializer());
return Action::Skip;
}
virtual Action visitPointerDeclarator(const PointerDeclaratorSyntax* node) override
{
for (auto iter = node->attributes(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->asteriskToken(), node);
for (auto iter = node->qualifiersAndAttributes(); iter; iter = iter->next)
nonterminal(iter->value);
nonterminal(node->innerDeclarator());
terminal(node->equalsToken(), node);
nonterminal(node->initializer());
return Action::Skip;
}
virtual Action visitParenthesizedDeclarator(const ParenthesizedDeclaratorSyntax* node) override
{
terminal(node->openParenthesisToken(), node);
nonterminal(node->innerDeclarator());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitIdentifierDeclarator(const IdentifierDeclaratorSyntax* node) override
{
terminal(node->identifierToken(), node);
for (auto iter = node->attributes_PostIdentifier(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->equalsToken(), node);
nonterminal(node->initializer());
return Action::Skip;
}
virtual Action visitSubscriptSuffix(const SubscriptSuffixSyntax* node) override
{
terminal(node->openBracketToken(), node);
for (auto iter = node->qualifiersAndAttributes(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->staticKeyword(), node);
for (auto iter = node->qualifiersAndAttributes_PostStatic(); iter; iter = iter->next)
nonterminal(iter->value);
nonterminal(node->expression());
terminal(node->asteriskToken(), node);
terminal(node->closeBracketToken(), node);
return Action::Skip;
}
virtual Action visitParameterSuffix(const ParameterSuffixSyntax* node) override
{
terminal(node->openParenthesisToken(), node);
for (auto iter = node->parameters(); iter; iter = iter->next) {
nonterminal(iter->value);
terminal(iter->delimiterToken(), node);
}
terminal(node->ellipsisToken(), node);
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitBitfieldDeclarator(const BitfieldDeclaratorSyntax* node) override
{
nonterminal(node->innerDeclarator());
terminal(node->colonToken(), node);
nonterminal(node->expression());
for (auto iter = node->attributes(); iter; iter = iter->next)
nonterminal(iter->value);
return Action::Skip;
}
/* Initializers */
virtual Action visitExpressionInitializer(const ExpressionInitializerSyntax* node) override
{
nonterminal(node->expression());
return Action::Skip;
}
virtual Action visitBraceEnclosedInitializer(const BraceEnclosedInitializerSyntax* node) override
{
terminal(node->openBraceToken(), node);
for (auto iter = node->initializerList(); iter; iter = iter->next) {
nonterminal(iter->value);
terminal(iter->delimiterToken(), node);
}
terminal(node->closeBraceToken(), node);
return Action::Skip;
}
virtual Action visitDesignatedInitializer(const DesignatedInitializerSyntax* node) override
{
for (auto iter = node->designators(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->equalsToken(), node);
nonterminal(node->initializer());
return Action::Skip;
}
virtual Action visitFieldDesignator(const FieldDesignatorSyntax* node) override
{
terminal(node->dotToken(), node);
terminal(node->identifierToken(), node);
return Action::Skip;
}
virtual Action visitArrayDesignator(const ArrayDesignatorSyntax* node) override
{
terminal(node->openBracketToken(), node);
nonterminal(node->expression());
terminal(node->closeBracketToken(), node);
return Action::Skip;
}
//-------------//
// Expressions //
//-------------//
void traverseExpression(const ExpressionSyntax* node)
{
terminal(node->extensionKeyword(), node);
}
virtual Action visitIdentifierExpression(const IdentifierExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->identifierToken(), node);
return Action::Skip;
}
virtual Action visitConstantExpression(const ConstantExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->constantToken(), node);
return Action::Skip;
}
virtual Action visitStringLiteralExpression(const StringLiteralExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->literalToken(), node);
nonterminal(node->adjacent());
return Action::Skip;
}
virtual Action visitParenthesizedExpression(const ParenthesizedExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->expression());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitGenericSelectionExpression(const GenericSelectionExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->genericKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->expression());
terminal(node->commaToken(), node);
for (auto it = node->associations(); it; it = it->next) {
nonterminal(it->value);
terminal(it->delimiterToken(), node);
}
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitGenericAssociation(const GenericAssociationSyntax* node) override
{
nonterminal(node->typeName_or_default());
terminal(node->colonToken(), node);
nonterminal(node->expression());
return Action::Skip;
}
virtual Action visitExtGNU_EnclosedCompoundStatementExpression(const ExtGNU_EnclosedCompoundStatementExpressionSyntax* node) override
{
terminal(node->openParenthesisToken(), node);
nonterminal(node->statement());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
/* Operations */
virtual Action visitPrefixUnaryExpression(const PrefixUnaryExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->operatorToken(), node);
nonterminal(node->expression());
return Action::Skip;
}
virtual Action visitPostfixUnaryExpression(const PostfixUnaryExpressionSyntax* node) override
{
traverseExpression(node);
nonterminal(node->expression());
terminal(node->operatorToken(), node);
return Action::Skip;
}
virtual Action visitMemberAccessExpression(const MemberAccessExpressionSyntax* node) override
{
traverseExpression(node);
nonterminal(node->expression());
terminal(node->operatorToken(), node);
nonterminal(node->identifier());
return Action::Skip;
}
virtual Action visitArraySubscriptExpression(const ArraySubscriptExpressionSyntax* node) override
{
traverseExpression(node);
nonterminal(node->expression());
terminal(node->openBracketToken(), node);
nonterminal(node->argument());
terminal(node->closeBracketToken(), node);
return Action::Skip;
}
virtual Action visitTypeTraitExpression(const TypeTraitExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->operatorToken(), node);
nonterminal(node->tyReference());
return Action::Skip;
}
virtual Action visitCastExpression(const CastExpressionSyntax* node) override
{
traverseExpression(node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->typeName());
terminal(node->closeParenthesisToken(), node);
nonterminal(node->expression());
return Action::Skip;
}
virtual Action visitCallExpression(const CallExpressionSyntax* node) override
{
nonterminal(node->expression());
terminal(node->openParenthesisToken(), node);
for (auto iter = node->arguments(); iter; iter = iter->next) {
nonterminal(iter->value);
terminal(iter->delimiterToken(), node);
}
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
virtual Action visitCompoundLiteralExpression(const CompoundLiteralExpressionSyntax* node) override
{
terminal(node->openParenthesisToken(), node);
nonterminal(node->typeName());
terminal(node->closeParenthesisToken(), node);
nonterminal(node->initializer());
return Action::Skip;
}
virtual Action visitBinaryExpression(const BinaryExpressionSyntax* node) override
{
nonterminal(node->left());
terminal(node->operatorToken(), node);
nonterminal(node->right());
return Action::Skip;
}
virtual Action visitConditionalExpression(const ConditionalExpressionSyntax* node) override
{
nonterminal(node->condition());
terminal(node->questionToken(), node);
nonterminal(node->whenTrue());
terminal(node->colonToken(), node);
nonterminal(node->whenFalse());
return Action::Skip;
}
virtual Action visitAssignmentExpression(const AssignmentExpressionSyntax* node) override
{
nonterminal(node->left());
terminal(node->operatorToken(), node);
nonterminal(node->right());
return Action::Skip;
}
virtual Action visitSequencingExpression(const SequencingExpressionSyntax* node) override
{
nonterminal(node->left());
terminal(node->operatorToken(), node);
nonterminal(node->right());
return Action::Skip;
}
//------------//
// Statements //
//------------//
virtual Action visitCompoundStatement(const CompoundStatementSyntax* node) override
{
terminal(node->openBraceToken(), node);
for (auto iter = node->statements(); iter; iter = iter->next)
nonterminal(iter->value);
terminal(node->closeBraceToken(), node);
return Action::Skip;
}
virtual Action visitDeclarationStatement(const DeclarationStatementSyntax* node) override
{
nonterminal(node->declaration());
return Action::Skip;
}
virtual Action visitExpressionStatement(const ExpressionStatementSyntax* node) override
{
nonterminal(node->expression());
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitLabeledStatement(const LabeledStatementSyntax* node) override
{
terminal(node->labelToken(), node);
nonterminal(node->expression());
terminal(node->colonToken(), node);
nonterminal(node->statement());
return Action::Skip;
}
virtual Action visitIfStatement(const IfStatementSyntax* node) override
{
terminal(node->ifKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->condition());
terminal(node->closeParenthesisToken(), node);
nonterminal(node->statement());
terminal(node->elseKeyword(), node);
nonterminal(node->elseStatement());
return Action::Skip;
}
virtual Action visitSwitchStatement(const SwitchStatementSyntax* node) override
{
terminal(node->switchKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->condition());
terminal(node->closeParenthesisToken(), node);
nonterminal(node->statement());
return Action::Skip;
}
virtual Action visitWhileStatement(const WhileStatementSyntax* node) override
{
terminal(node->whileKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->condition());
terminal(node->closeParenthesisToken(), node);
nonterminal(node->statement());
return Action::Skip;
}
virtual Action visitDoStatement(const DoStatementSyntax* node) override
{
terminal(node->doKeyword(), node);
nonterminal(node->statement());
terminal(node->whileKeyword(), node);
terminal(node->openParenthesisToken(), node);
nonterminal(node->condition());
terminal(node->closeParenthesisToken(), node);
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitForStatement(const ForStatementSyntax* node) override
{
terminal(node->forKeyword(), node);
terminal(node->openParenthesisToken(), node);
terminal(node->extensionKeyword(), node);
nonterminal(node->initializer());
nonterminal(node->condition());
terminal(node->semicolonToken(), node);
nonterminal(node->expression());
terminal(node->closeParenthesisToken(), node);
nonterminal(node->statement());
return Action::Skip;
}
virtual Action visitGotoStatement(const GotoStatementSyntax* node) override
{
terminal(node->gotoKeyword(), node);
terminal(node->identifierToken(), node);
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitContinueStatement(const ContinueStatementSyntax* node) override
{
terminal(node->continueKeyword(), node);
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitBreakStatement(const BreakStatementSyntax* node) override
{
terminal(node->breakKeyword(), node);
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitReturnStatement(const ReturnStatementSyntax* node) override
{
terminal(node->returnKeyword(), node);
nonterminal(node->expression());
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitExtGNU_AsmStatement(const ExtGNU_AsmStatementSyntax* node) override
{
terminal(node->asmKeyword(), node);
for (auto it = node->asmQualifiers(); it; it = it->next)
nonterminal(it->value);
terminal(node->openParenthesisToken(), node);
nonterminal(node->stringLiteral());
terminal(node->colon1Token(), node);
for (auto it = node->outputOperands(); it; it = it->next) {
nonterminal(it->value);
terminal(it->delimiterToken(), node);
}
terminal(node->colon2Token(), node);
for (auto it = node->inputOperands(); it; it = it->next) {
nonterminal(it->value);
terminal(it->delimiterToken(), node);
}
terminal(node->colon3Token(), node);
for (auto it = node->clobbers(); it; it = it->next) {
nonterminal(it->value);
terminal(it->delimiterToken(), node);
}
terminal(node->colon4Token(), node);
for (auto it = node->gotoLabels(); it; it = it->next) {
nonterminal(it->value);
terminal(it->delimiterToken(), node);
}
terminal(node->closeParenthesisToken(), node);
terminal(node->semicolonToken(), node);
return Action::Skip;
}
virtual Action visitExtGNU_AsmQualifier(const ExtGNU_AsmQualifierSyntax* node) override
{
terminal(node->asmQualifier(), node);
return Action::Skip;
}
virtual Action visitExtGNU_AsmOperand(const ExtGNU_AsmOperandSyntax* node) override
{
terminal(node->openBracketToken(), node);
nonterminal(node->identifier());
terminal(node->closeBracketToken(), node);
nonterminal(node->stringLiteral());
terminal(node->openParenthesisToken(), node);
nonterminal(node->expression());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
//--------//
// Common //
//--------//
virtual Action visitTypeName(const TypeNameSyntax* node) override
{
for (auto it = node->specifiers(); it; it = it->next)
nonterminal(it->value);
nonterminal(node->declarator());
return Action::Skip;
}
virtual Action visitExpressionAsTypeReference(const ExpressionAsTypeReferenceSyntax* node) override
{
nonterminal(node->expression());
return Action::Skip;
}
virtual Action visitTypeNameAsTypeReference(const TypeNameAsTypeReferenceSyntax* node) override
{
terminal(node->openParenthesisToken(), node);
nonterminal(node->typeName());
terminal(node->closeParenthesisToken(), node);
return Action::Skip;
}
//-------------//
// Ambiguities //
//-------------//
virtual Action visitAmbiguousTypeNameOrExpressionAsTypeReference(const AmbiguousTypeNameOrExpressionAsTypeReferenceSyntax* node) override
{
nonterminal(node->expressionAsTypeReference());
nonterminal(node->typeNameAsTypeReference());
return Action::Skip;
}
virtual Action visitAmbiguousCastOrBinaryExpression(const AmbiguousCastOrBinaryExpressionSyntax* node) override
{
nonterminal(node->castExpression());
nonterminal(node->binaryExpression());
return Action::Skip;
}
virtual Action visitAmbiguousExpressionOrDeclarationStatement(const AmbiguousExpressionOrDeclarationStatementSyntax* node) override
{
nonterminal(node->declarationStatement());
nonterminal(node->expressionStatement());
return Action::Skip;
}
};
} // C
} // psy
#endif
| 35.718293 | 141 | 0.643211 |
30607cb08f9e9e0494998637076c90c408fc5df3 | 173 | h | C | PG/app/KeyCodeUtils.h | mcdreamer/PG | a047615d9eae7f2229a203a262f239106cf7f39c | [
"MIT"
] | 2 | 2018-01-14T17:47:22.000Z | 2021-11-15T10:34:24.000Z | PG/app/KeyCodeUtils.h | mcdreamer/PG | a047615d9eae7f2229a203a262f239106cf7f39c | [
"MIT"
] | 23 | 2017-07-31T19:43:00.000Z | 2018-11-11T18:51:28.000Z | PG/app/KeyCodeUtils.h | mcdreamer/PG | a047615d9eae7f2229a203a262f239106cf7f39c | [
"MIT"
] | null | null | null | #pragma once
#include <string>
namespace PG {
enum class KeyCode;
namespace KeyCodeUtils {
void addCharacterForKeyCode(const PG::KeyCode& code, std::string& str);
}
}
| 11.533333 | 71 | 0.734104 |
d0713c64c427bd98680c7ec01448d045ecebd540 | 323 | h | C | Project_2/Tests/packet-format.h | Opty1337/CN | bc01cf39bcc017783fdbb84ebd7958f405511e6c | [
"MIT"
] | null | null | null | Project_2/Tests/packet-format.h | Opty1337/CN | bc01cf39bcc017783fdbb84ebd7958f405511e6c | [
"MIT"
] | null | null | null | Project_2/Tests/packet-format.h | Opty1337/CN | bc01cf39bcc017783fdbb84ebd7958f405511e6c | [
"MIT"
] | null | null | null | #include <stdint.h>
#define MAX_WINDOW_SIZE 32
#define TIMEOUT 1000 // ms
#define MAX_RETRIES 3
typedef struct __attribute__((__packed__)) data_pkt_t {
uint32_t seq_num;
char data[1000];
} data_pkt_t;
typedef struct __attribute__((__packed__)) ack_pkt_t {
uint32_t seq_num;
uint32_t selective_acks;
} ack_pkt_t;
| 20.1875 | 55 | 0.767802 |
a90fe853c58a915daa24fc3499de35af093d4271 | 311 | c | C | src/lock-spin.c | jsyou-sor/dlmalloc | 043f8fcfceafcc5bf40ea61c12b586522dfd0001 | [
"CC0-1.0"
] | 1 | 2021-12-27T09:25:36.000Z | 2021-12-27T09:25:36.000Z | src/lock-spin.c | jsyou-sor/dlmalloc | 043f8fcfceafcc5bf40ea61c12b586522dfd0001 | [
"CC0-1.0"
] | null | null | null | src/lock-spin.c | jsyou-sor/dlmalloc | 043f8fcfceafcc5bf40ea61c12b586522dfd0001 | [
"CC0-1.0"
] | 4 | 2020-05-15T04:49:43.000Z | 2022-01-13T11:35:39.000Z | #include "config.h"
#include "lock.h"
#include "assert.h"
MLOCK_T malloc_global_mutex = 0;
/* Plain spin locks use single word (embedded in malloc_states) */
int spin_acquire_lock(int *sl) {
int spins = 0;
while (*(volatile int *) sl != 0 || CAS_LOCK(sl)) {
SPIN(spins);
}
return 0;
}
| 20.733333 | 66 | 0.630225 |
6507ef82fb1fb8698b88438f51f82b310fbdac7d | 3,480 | h | C | FlurryLib/FlurryAPI.h | daveverwer/UncaughtExceptionsDemo | 64442b31f2fd2f6a788229a4d73705b69d93ffd6 | [
"BSD-3-Clause"
] | 1 | 2016-07-11T16:46:10.000Z | 2016-07-11T16:46:10.000Z | FlurryLib/FlurryAPI.h | daveverwer/UncaughtExceptionsDemo | 64442b31f2fd2f6a788229a4d73705b69d93ffd6 | [
"BSD-3-Clause"
] | null | null | null | FlurryLib/FlurryAPI.h | daveverwer/UncaughtExceptionsDemo | 64442b31f2fd2f6a788229a4d73705b69d93ffd6 | [
"BSD-3-Clause"
] | null | null | null | //
// FlurryAPI.h
// Flurry iPhone Analytics Agent
//
// Copyright 2009 Flurry, Inc. All rights reserved.
//
#import <UIKit/UIKit.h>
@class CLLocationManager;
@class CLLocation;
@interface FlurryAPI : NSObject {
}
/*
optional sdk settings that should be called before start session
*/
+ (void)setAppVersion:(NSString *)version; // override the app version
+ (NSString *)getFlurryAgentVersion; // get the Flurry Agent version number
+ (void)setAppCircleEnabled:(BOOL)value; // default is NO
+ (void)setShowErrorInLogEnabled:(BOOL)value; // default is NO
+ (void)unlockDebugMode:(NSString*)debugModeKey apiKey:(NSString *)apiKey; // generate debug logs for Flurry support
+ (void)setPauseSecondsBeforeStartingNewSession:(int)seconds; // default is 10 seconds
/*
start session, attempt to send saved sessions to server
*/
+ (void)startSession:(NSString *)apiKey;
/*
log events or errors after session has started
*/
+ (void)logEvent:(NSString *)eventName;
+ (void)logEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters;
+ (void)logError:(NSString *)errorID message:(NSString *)message exception:(NSException *)exception;
+ (void)logError:(NSString *)errorID message:(NSString *)message error:(NSError *)error;
/*
start or end timed events
*/
+ (void)logEvent:(NSString *)eventName timed:(BOOL)timed;
+ (void)logEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters timed:(BOOL)timed;
+ (void)endTimedEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters; // non-nil parameters will update the parameters
/*
count page views
*/
+ (void)countPageViews:(id)target; // automatically track page view on UINavigationController or UITabBarController
+ (void)countPageView; // manually increment page view by 1
/*
set user info
*/
+ (void)setUserID:(NSString *)userID; // user's id in your system
+ (void)setAge:(int)age; // user's age in years
+ (void)setGender:(NSString *)gender; // user's gender m or f
/*
optional session settings that can be changed after start session
*/
+ (void)setSessionReportsOnCloseEnabled:(BOOL)sendSessionReportsOnClose; // default is YES
+ (void)setSessionReportsOnPauseEnabled:(BOOL)setSessionReportsOnPauseEnabled; // default is YES
+ (void)setEventLoggingEnabled:(BOOL)value; // default is YES
/*
create an AppCircle banner on a hook and a view parent
subsequent calls will return the same banner for the same hook and parent until removed with the API
*/
+ (UIView *)getHook:(NSString *)hook xLoc:(int)x yLoc:(int)y view:(UIView *)view;
/*
create an AppCircle banner on a hook and view parent using optional parameters
*/
+ (UIView *)getHook:(NSString *)hook xLoc:(int)x yLoc:(int)y view:(UIView *)view attachToView:(BOOL)attachToView orientation:(NSString *)orientation canvasOrientation:(NSString *)canvasOrientation autoRefresh:(BOOL)refresh canvasAnimated:(BOOL)canvasAnimated;
/*
update an existing AppCircle banner with a new ad
*/
+ (void)updateHook:(UIView *)banner;
/*
remove an existing AppCircle banner from its hook and parent
a new banner can be created on the same hook and parent after the existing banner is removed
*/
+ (void)removeHook:(UIView *)banner;
/*
open the canvas without using a banner
*/
+ (void)openCatalog:(NSString *)hook canvasOrientation:(NSString *)canvasOrientation canvasAnimated:(BOOL)canvasAnimated;
/*
refer to FlurryAdDelegate.h for delegate details
*/
+ (void)setAppCircleDelegate:(id)delegate;
@end
| 37.419355 | 259 | 0.751437 |
45e392a66a959e961663d5440bbee562559de762 | 14,743 | c | C | libnetutils/dhcpclient.c | nDroidProject/android_system_core | a6d3016791b1b702a8f8010abcc0ad63fc96ab59 | [
"MIT"
] | 29 | 2015-09-20T20:15:22.000Z | 2021-12-23T09:48:19.000Z | libnetutils/dhcpclient.c | jsherman/platform_system_core | 4a4c9f6f98055918f1ebff06b3cc1ed622c058fe | [
"MIT"
] | null | null | null | libnetutils/dhcpclient.c | jsherman/platform_system_core | 4a4c9f6f98055918f1ebff06b3cc1ed622c058fe | [
"MIT"
] | 15 | 2015-03-03T07:49:39.000Z | 2021-01-20T03:02:06.000Z | /*
* Copyright 2008, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <cutils/properties.h>
#define LOG_TAG "DHCP"
#include <cutils/log.h>
#include <dirent.h>
#include "dhcpmsg.h"
#include "ifc_utils.h"
#include "packet.h"
#define VERBOSE 2
static int verbose = 1;
static char errmsg[2048];
typedef unsigned long long msecs_t;
#if VERBOSE
void dump_dhcp_msg();
#endif
msecs_t get_msecs(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
return 0;
} else {
return (((msecs_t) ts.tv_sec) * ((msecs_t) 1000)) +
(((msecs_t) ts.tv_nsec) / ((msecs_t) 1000000));
}
}
void printerr(char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(errmsg, sizeof(errmsg), fmt, ap);
va_end(ap);
LOGD(errmsg);
}
const char *dhcp_lasterror()
{
return errmsg;
}
int fatal(const char *reason)
{
printerr("%s: %s\n", reason, strerror(errno));
return -1;
// exit(1);
}
const char *ipaddr(uint32_t addr)
{
static char buf[32];
sprintf(buf,"%d.%d.%d.%d",
addr & 255,
((addr >> 8) & 255),
((addr >> 16) & 255),
(addr >> 24));
return buf;
}
typedef struct dhcp_info dhcp_info;
struct dhcp_info {
uint32_t type;
uint32_t ipaddr;
uint32_t gateway;
uint32_t netmask;
uint32_t dns1;
uint32_t dns2;
uint32_t serveraddr;
uint32_t lease;
};
dhcp_info last_good_info;
void get_dhcp_info(uint32_t *ipaddr, uint32_t *gateway, uint32_t *mask,
uint32_t *dns1, uint32_t *dns2, uint32_t *server,
uint32_t *lease)
{
*ipaddr = last_good_info.ipaddr;
*gateway = last_good_info.gateway;
*mask = last_good_info.netmask;
*dns1 = last_good_info.dns1;
*dns2 = last_good_info.dns2;
*server = last_good_info.serveraddr;
*lease = last_good_info.lease;
}
static int ifc_configure(const char *ifname, dhcp_info *info)
{
char dns_prop_name[PROPERTY_KEY_MAX];
if (ifc_set_addr(ifname, info->ipaddr)) {
printerr("failed to set ipaddr %s: %s\n", ipaddr(info->ipaddr), strerror(errno));
return -1;
}
if (ifc_set_mask(ifname, info->netmask)) {
printerr("failed to set netmask %s: %s\n", ipaddr(info->netmask), strerror(errno));
return -1;
}
if (ifc_create_default_route(ifname, info->gateway)) {
printerr("failed to set default route %s: %s\n", ipaddr(info->gateway), strerror(errno));
return -1;
}
snprintf(dns_prop_name, sizeof(dns_prop_name), "net.%s.dns1", ifname);
property_set(dns_prop_name, info->dns1 ? ipaddr(info->dns1) : "");
snprintf(dns_prop_name, sizeof(dns_prop_name), "net.%s.dns2", ifname);
property_set(dns_prop_name, info->dns2 ? ipaddr(info->dns2) : "");
last_good_info = *info;
return 0;
}
static const char *dhcp_type_to_name(uint32_t type)
{
switch(type) {
case DHCPDISCOVER: return "discover";
case DHCPOFFER: return "offer";
case DHCPREQUEST: return "request";
case DHCPDECLINE: return "decline";
case DHCPACK: return "ack";
case DHCPNAK: return "nak";
case DHCPRELEASE: return "release";
case DHCPINFORM: return "inform";
default: return "???";
}
}
void dump_dhcp_info(dhcp_info *info)
{
char addr[20], gway[20], mask[20];
LOGD("--- dhcp %s (%d) ---",
dhcp_type_to_name(info->type), info->type);
strcpy(addr, ipaddr(info->ipaddr));
strcpy(gway, ipaddr(info->gateway));
strcpy(mask, ipaddr(info->netmask));
LOGD("ip %s gw %s mask %s", addr, gway, mask);
if (info->dns1) LOGD("dns1: %s", ipaddr(info->dns1));
if (info->dns2) LOGD("dns2: %s", ipaddr(info->dns2));
LOGD("server %s, lease %d seconds",
ipaddr(info->serveraddr), info->lease);
}
int decode_dhcp_msg(dhcp_msg *msg, int len, dhcp_info *info)
{
uint8_t *x;
unsigned int opt;
int optlen;
memset(info, 0, sizeof(dhcp_info));
if (len < (DHCP_MSG_FIXED_SIZE + 4)) return -1;
len -= (DHCP_MSG_FIXED_SIZE + 4);
if (msg->options[0] != OPT_COOKIE1) return -1;
if (msg->options[1] != OPT_COOKIE2) return -1;
if (msg->options[2] != OPT_COOKIE3) return -1;
if (msg->options[3] != OPT_COOKIE4) return -1;
x = msg->options + 4;
while (len > 2) {
opt = *x++;
if (opt == OPT_PAD) {
len--;
continue;
}
if (opt == OPT_END) {
break;
}
optlen = *x++;
len -= 2;
if (optlen > len) {
break;
}
switch(opt) {
case OPT_SUBNET_MASK:
if (optlen >= 4) memcpy(&info->netmask, x, 4);
break;
case OPT_GATEWAY:
if (optlen >= 4) memcpy(&info->gateway, x, 4);
break;
case OPT_DNS:
if (optlen >= 4) memcpy(&info->dns1, x + 0, 4);
if (optlen >= 8) memcpy(&info->dns2, x + 4, 4);
break;
case OPT_LEASE_TIME:
if (optlen >= 4) {
memcpy(&info->lease, x, 4);
info->lease = ntohl(info->lease);
}
break;
case OPT_SERVER_ID:
if (optlen >= 4) memcpy(&info->serveraddr, x, 4);
break;
case OPT_MESSAGE_TYPE:
info->type = *x;
break;
default:
break;
}
x += optlen;
len -= optlen;
}
info->ipaddr = msg->yiaddr;
return 0;
}
#if VERBOSE
static void hex2str(char *buf, const unsigned char *array, int len)
{
int i;
char *cp = buf;
for (i = 0; i < len; i++) {
cp += sprintf(cp, " %02x ", array[i]);
}
}
void dump_dhcp_msg(dhcp_msg *msg, int len)
{
unsigned char *x;
unsigned int n,c;
int optsz;
const char *name;
char buf[2048];
LOGD("===== DHCP message:");
if (len < DHCP_MSG_FIXED_SIZE) {
LOGD("Invalid length %d, should be %d", len, DHCP_MSG_FIXED_SIZE);
return;
}
len -= DHCP_MSG_FIXED_SIZE;
if (msg->op == OP_BOOTREQUEST)
name = "BOOTREQUEST";
else if (msg->op == OP_BOOTREPLY)
name = "BOOTREPLY";
else
name = "????";
LOGD("op = %s (%d), htype = %d, hlen = %d, hops = %d",
name, msg->op, msg->htype, msg->hlen, msg->hops);
LOGD("xid = 0x%08x secs = %d, flags = 0x%04x optlen = %d",
ntohl(msg->xid), ntohs(msg->secs), ntohs(msg->flags), len);
LOGD("ciaddr = %s", ipaddr(msg->ciaddr));
LOGD("yiaddr = %s", ipaddr(msg->yiaddr));
LOGD("siaddr = %s", ipaddr(msg->siaddr));
LOGD("giaddr = %s", ipaddr(msg->giaddr));
c = msg->hlen > 16 ? 16 : msg->hlen;
hex2str(buf, msg->chaddr, c);
LOGD("chaddr = {%s}", buf);
for (n = 0; n < 64; n++) {
if ((msg->sname[n] < ' ') || (msg->sname[n] > 127)) {
if (msg->sname[n] == 0) break;
msg->sname[n] = '.';
}
}
msg->sname[63] = 0;
for (n = 0; n < 128; n++) {
if ((msg->file[n] < ' ') || (msg->file[n] > 127)) {
if (msg->file[n] == 0) break;
msg->file[n] = '.';
}
}
msg->file[127] = 0;
LOGD("sname = '%s'", msg->sname);
LOGD("file = '%s'", msg->file);
if (len < 4) return;
len -= 4;
x = msg->options + 4;
while (len > 2) {
if (*x == 0) {
x++;
len--;
continue;
}
if (*x == OPT_END) {
break;
}
len -= 2;
optsz = x[1];
if (optsz > len) break;
if (x[0] == OPT_DOMAIN_NAME || x[0] == OPT_MESSAGE) {
if ((unsigned int)optsz < sizeof(buf) - 1) {
n = optsz;
} else {
n = sizeof(buf) - 1;
}
memcpy(buf, &x[2], n);
buf[n] = '\0';
} else {
hex2str(buf, &x[2], optsz);
}
if (x[0] == OPT_MESSAGE_TYPE)
name = dhcp_type_to_name(x[2]);
else
name = NULL;
LOGD("op %d len %d {%s} %s", x[0], optsz, buf, name == NULL ? "" : name);
len -= optsz;
x = x + optsz + 2;
}
}
#endif
static int send_message(int sock, int if_index, dhcp_msg *msg, int size)
{
#if VERBOSE > 1
dump_dhcp_msg(msg, size);
#endif
return send_packet(sock, if_index, msg, size, INADDR_ANY, INADDR_BROADCAST,
PORT_BOOTP_CLIENT, PORT_BOOTP_SERVER);
}
static int is_valid_reply(dhcp_msg *msg, dhcp_msg *reply, int sz)
{
if (sz < DHCP_MSG_FIXED_SIZE) {
if (verbose) LOGD("netcfg: Wrong size %d != %d\n", sz, DHCP_MSG_FIXED_SIZE);
return 0;
}
if (reply->op != OP_BOOTREPLY) {
if (verbose) LOGD("netcfg: Wrong Op %d != %d\n", reply->op, OP_BOOTREPLY);
return 0;
}
if (reply->xid != msg->xid) {
if (verbose) LOGD("netcfg: Wrong Xid 0x%x != 0x%x\n", ntohl(reply->xid),
ntohl(msg->xid));
return 0;
}
if (reply->htype != msg->htype) {
if (verbose) LOGD("netcfg: Wrong Htype %d != %d\n", reply->htype, msg->htype);
return 0;
}
if (reply->hlen != msg->hlen) {
if (verbose) LOGD("netcfg: Wrong Hlen %d != %d\n", reply->hlen, msg->hlen);
return 0;
}
if (memcmp(msg->chaddr, reply->chaddr, msg->hlen)) {
if (verbose) LOGD("netcfg: Wrong chaddr %x != %x\n", *(reply->chaddr),*(msg->chaddr));
return 0;
}
return 1;
}
#define STATE_SELECTING 1
#define STATE_REQUESTING 2
#define TIMEOUT_INITIAL 4000
#define TIMEOUT_MAX 32000
int dhcp_init_ifc(const char *ifname)
{
dhcp_msg discover_msg;
dhcp_msg request_msg;
dhcp_msg reply;
dhcp_msg *msg;
dhcp_info info;
int s, r, size;
int valid_reply;
uint32_t xid;
unsigned char hwaddr[6];
struct pollfd pfd;
unsigned int state;
unsigned int timeout;
int if_index;
xid = (uint32_t) get_msecs();
if (ifc_get_hwaddr(ifname, hwaddr)) {
return fatal("cannot obtain interface address");
}
if (ifc_get_ifindex(ifname, &if_index)) {
return fatal("cannot obtain interface index");
}
s = open_raw_socket(ifname, hwaddr, if_index);
timeout = TIMEOUT_INITIAL;
state = STATE_SELECTING;
info.type = 0;
goto transmit;
for (;;) {
pfd.fd = s;
pfd.events = POLLIN;
pfd.revents = 0;
r = poll(&pfd, 1, timeout);
if (r == 0) {
#if VERBOSE
printerr("TIMEOUT\n");
#endif
if (timeout >= TIMEOUT_MAX) {
printerr("timed out\n");
if ( info.type == DHCPOFFER ) {
printerr("no acknowledgement from DHCP server\nconfiguring %s with offered parameters\n", ifname);
return ifc_configure(ifname, &info);
}
errno = ETIME;
close(s);
return -1;
}
timeout = timeout * 2;
transmit:
size = 0;
msg = NULL;
switch(state) {
case STATE_SELECTING:
msg = &discover_msg;
size = init_dhcp_discover_msg(msg, hwaddr, xid);
break;
case STATE_REQUESTING:
msg = &request_msg;
size = init_dhcp_request_msg(msg, hwaddr, xid, info.ipaddr, info.serveraddr);
break;
default:
r = 0;
}
if (size != 0) {
r = send_message(s, if_index, msg, size);
if (r < 0) {
printerr("error sending dhcp msg: %s\n", strerror(errno));
}
}
continue;
}
if (r < 0) {
if ((errno == EAGAIN) || (errno == EINTR)) {
continue;
}
return fatal("poll failed");
}
errno = 0;
r = receive_packet(s, &reply);
if (r < 0) {
if (errno != 0) {
LOGD("receive_packet failed (%d): %s", r, strerror(errno));
if (errno == ENETDOWN || errno == ENXIO) {
return -1;
}
}
continue;
}
#if VERBOSE > 1
dump_dhcp_msg(&reply, r);
#endif
decode_dhcp_msg(&reply, r, &info);
if (state == STATE_SELECTING) {
valid_reply = is_valid_reply(&discover_msg, &reply, r);
} else {
valid_reply = is_valid_reply(&request_msg, &reply, r);
}
if (!valid_reply) {
printerr("invalid reply\n");
continue;
}
if (verbose) dump_dhcp_info(&info);
switch(state) {
case STATE_SELECTING:
if (info.type == DHCPOFFER) {
state = STATE_REQUESTING;
timeout = TIMEOUT_INITIAL;
xid++;
goto transmit;
}
break;
case STATE_REQUESTING:
if (info.type == DHCPACK) {
printerr("configuring %s\n", ifname);
close(s);
return ifc_configure(ifname, &info);
} else if (info.type == DHCPNAK) {
printerr("configuration request denied\n");
close(s);
return -1;
} else {
printerr("ignoring %s message in state %d\n",
dhcp_type_to_name(info.type), state);
}
break;
}
}
close(s);
return 0;
}
int do_dhcp(char *iname)
{
if (ifc_set_addr(iname, 0)) {
printerr("failed to set ip addr for %s to 0.0.0.0: %s\n", iname, strerror(errno));
return -1;
}
if (ifc_up(iname)) {
printerr("failed to bring up interface %s: %s\n", iname, strerror(errno));
return -1;
}
return dhcp_init_ifc(iname);
}
| 26.186501 | 118 | 0.52764 |
30af76ef9b5f8284ed7bcacb4417125a421566e3 | 25,585 | c | C | snapgear_linux/user/w3cam/w3cam.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/w3cam/w3cam.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/w3cam/w3cam.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | 3 | 2016-06-13T13:20:56.000Z | 2019-12-05T02:31:23.000Z | /*
* w3cam.c
*
* Copyright (C) 1998 - 2001 Rasca, Berlin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#ifdef USE_SYSLOG
#include <syslog.h>
#endif
#if defined __GLIBC__ && __GLIBC__ >= 2
#include <libgen.h> /* basename */
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/types.h>
#include <linux/videodev.h>
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#ifdef HAVE_LIBPNG
#include <png.h>
#endif
#ifdef HAVE_LIBJPEG
#include <jpeglib.h>
#endif
#ifdef HAVE_LIBTTF
#include <freetype.h>
#endif
#include "w3cam.h"
#include "cgi.h"
#include "v4l.h"
/*
* some default values, change these to fit your needs
* most of these could be changed at runtime with config file
*/
#define FMT_DEFAULT FMT_JPEG /* FMT_PPM, FMT_JPEG, FMT_PNG */
#define QUALITY_DEFAULT 65 /* JPEG default quality */
#define WIDTH_DEFAULT 240 /* default width and height of the image */
#define HEIGHT_DEFAULT 180
#define MODE_DEFAULT MODE_PLAIN /* MODE_GUI or MODE_PLAIN */
#define USEC_DEFAULT 20000 /* wait microseconds before capturing */
#define REFRESH_DEFAULT OFF /* don't use refreshing */
#define MIN_REFRESH 0.0 /* min refresh time, compile time option */
#define FREQLIST_DEFAULT "878;9076;9844;9460" /* default frequenzies */
#define MAX_TRY_OPEN 20 /* may be the device is locked, so try max*/
/* end of default values
* *********************
*/
/*
*/
void
usage (char *pname, int width, int height, int color, int quality, int usec)
{
cgi_response (http_bad_request, "text/html");
printf (
"<title>w3cam - help</title><pre>W3Cam, Version %s\n\n"
"Usage: %s<?parameters>\n"
"CGI parameters (GET or POST):\n"
" help show this page\n"
" size=#x# geometry of picture "
"[default = %dx%d]\n"
" color={0|1} color or grey mode "
"[default = %d]\n"
" input={tv|composite|composite2|s-video} define input source\n"
" quality={1-100} jpeg quality "
"[default = %d]\n"
" format={ppm|png|jpeg} output format\n"
" freq=# define frequenzy for TV\n"
" usleep=# sleep # micro secs before cap. "
"[default = %d]\n"
" mode=[gui|html] build a page with panel or plain html\n"
" refresh=#.# time in sec to refresh gui\n"
" norm={pal|ntsc|secam} tv norm\n"
" bgr={1|0} swap RGB to BGR (default: no)\n",
VERSION, basename(pname), width, height, color, quality, usec);
printf (
"\nCompiled in features:\n");
#ifdef HAVE_LIBPNG
printf (" PNG file format\n");
#endif
#ifdef HAVE_LIBJPEG
printf (" JPEG file format\n");
#endif
#ifdef HAVE_LIBTTF
printf ( " TTF/TimeStamp\n");
#endif
#ifdef USE_SYSLOG
printf ( " SYSLOG support\n");
#endif
exit (0);
}
/*
*/
void
log (char *info)
{
#ifdef USE_SYSLOG
syslog (LOG_USER, "%s\n", info);
#else
fprintf (stderr, "%s\n", info);
#endif
}
/*
*/
void
log2 (char *s1, char *s2)
{
#ifdef USE_SYSLOG
syslog (LOG_USER, "%s %s\n", s1, s2);
#else
fprintf (stderr, "%s %s\n", s1, s2);
#endif
}
/*
* parse comma seperated frequency list
*/
char **
parse_list (char *freqs)
{
char **flist = NULL;
char *p = freqs, *end = NULL;
int num = 0, i, len;
if (!freqs)
return (NULL);
while ((p = strchr(p, ';')) != NULL) {
p++;
num++;
}
num++;
flist = malloc ((num + 1) * sizeof (char *));
flist[num] = NULL;
p = freqs;
for (i = 0; i < num; i++) {
if (i == (num-1)) {
/* last element */
len = strlen (p);
} else {
end = strchr(p, ';');
len = end - p;
}
flist[i] = malloc (len+1);
strncpy (flist[i], p, len);
p = end+1;
}
return (flist);
}
/*
* read rgb image from v4l device
* return: new allocated buffer
*/
unsigned char *
get_image (int dev, int width, int height, int input, int usec,
unsigned long freq, int palette)
{
struct video_mbuf vid_buf;
struct video_mmap vid_mmap;
char *map;
unsigned char *buff;
int size, len, bpp;
register int i;
if (input == IN_TV) {
if (freq > 0) {
if (ioctl (dev, VIDIOCSFREQ, &freq) == -1)
log2 ("ioctl (VIDIOCSREQ):", strerror(errno));
}
}
/* it seems some cards need a little bit time to come in
sync with the new settings */
if (usec)
usleep (usec);
if (palette != VIDEO_PALETTE_GREY) {
/* RGB or YUV */
size = width * height * 3;
bpp = 3;
} else {
size = width * height * 1;
bpp = 1;
}
vid_mmap.format = palette;
if (ioctl (dev, VIDIOCGMBUF, &vid_buf) == -1) {
/* do a normal read()
*/
struct video_window vid_win;
if (ioctl (dev, VIDIOCGWIN, &vid_win) != -1) {
vid_win.width = width;
vid_win.height = height;
if (ioctl (dev, VIDIOCSWIN, &vid_win) == -1) {
log2 ("ioctl(VIDIOCSWIN):", strerror(errno));
return (NULL);
}
}
map = malloc (size);
if (!map)
return (NULL);
len = read (dev, map, size);
if (len <= 0) {
free (map);
return NULL;
}
if (palette == VIDEO_PALETTE_YUV420P) {
char *convmap;
convmap = malloc ( width * height * bpp );
v4l_yuv420p2rgb (convmap, map, width, height, bpp * 8);
memcpy (map, convmap, (size_t) width * height * bpp);
free (convmap);
} else if (palette == VIDEO_PALETTE_YUV422P) {
char *convmap;
convmap = malloc ( width * height * bpp );
v4l_yuv422p2rgb (convmap, map, width, height, bpp * 8);
memcpy (map, convmap, (size_t) width * height * bpp);
free (convmap);
}
return (map);
}
map = mmap (0, vid_buf.size, PROT_READ|PROT_WRITE,MAP_SHARED,dev,0);
if ((unsigned char *)-1 == (unsigned char *)map) {
log2 ("mmap():", strerror(errno));
return (NULL);
}
vid_mmap.frame = 0;
vid_mmap.width = width;
vid_mmap.height =height;
if (ioctl (dev, VIDIOCMCAPTURE, &vid_mmap) == -1) {
log2 ("ioctl(VIDIOCMCAPTURE):", strerror(errno));
munmap (map, vid_buf.size);
return (NULL);
}
if (ioctl (dev, VIDIOCSYNC, &vid_mmap.frame) == -1) {
log2 ("ioctl(VIDIOCSYNC):", strerror(errno));
munmap (map, vid_buf.size);
return (NULL);
}
buff = (unsigned char *) malloc (size);
if (buff) {
if (palette == VIDEO_PALETTE_YUV420P) {
v4l_yuv420p2rgb (buff, map, width, height, 24);
} else if (palette == VIDEO_PALETTE_YUV422P) {
v4l_yuv422p2rgb (buff, map, width, height, 24);
} else {
for (i = 0; i < size; i++)
buff[i] = map[i];
}
} else {
perror ("malloc()");
}
munmap (map, vid_buf.size);
return (buff);
}
/*
*/
void
put_image_jpeg (char *image, int width, int height, int quality, int color)
{
#ifdef HAVE_LIBJPEG
register int x, y, line_width;
JSAMPROW row_ptr[1];
struct jpeg_compress_struct cjpeg;
struct jpeg_error_mgr jerr;
char *line = NULL;
if (color) {
line_width = width * 3;
line = malloc (line_width);
if (!line)
return;
} else {
line_width = width;
}
cjpeg.err = jpeg_std_error(&jerr);
jpeg_create_compress (&cjpeg);
cjpeg.image_width = width;
cjpeg.image_height= height;
if (color) {
cjpeg.input_components = 3;
cjpeg.in_color_space = JCS_RGB;
} else {
cjpeg.input_components = 1;
cjpeg.in_color_space = JCS_GRAYSCALE;
}
jpeg_set_defaults (&cjpeg);
jpeg_simple_progression (&cjpeg);
jpeg_set_quality (&cjpeg, quality, TRUE);
cjpeg.dct_method = JDCT_FASTEST;
jpeg_stdio_dest (&cjpeg, stdout);
jpeg_start_compress (&cjpeg, TRUE);
if (color) {
row_ptr[0] = line;
for ( y = 0; y < height; y++) {
for (x = 0; x < line_width; x += 3) {
line[x] = image[x+2];
line[x+1] = image[x+1];
line[x+2] = image[x];
}
image += line_width;
jpeg_write_scanlines (&cjpeg, row_ptr, 1);
}
free (line);
} else {
for ( y = 0; y < height; y++) {
row_ptr[0] = image;
jpeg_write_scanlines (&cjpeg, row_ptr, 1);
image += line_width;
}
}
jpeg_finish_compress (&cjpeg);
jpeg_destroy_compress (&cjpeg);
#endif
}
/*
* write png image to stdout
*/
void
put_image_png (char *image, int width, int height, int color)
{
#ifdef HAVE_LIBPNG
register int y;
register char *p;
png_infop info_ptr;
png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL);
if (!png_ptr)
return;
info_ptr = png_create_info_struct (png_ptr);
if (!info_ptr)
return;
png_init_io (png_ptr, stdout);
if (color) {
png_set_IHDR (png_ptr, info_ptr, width, height,
8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_set_bgr (png_ptr);
} else {
png_set_IHDR (png_ptr, info_ptr, width, height,
8, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
}
png_write_info (png_ptr, info_ptr);
p = image;
if (color) {
width *= 3;
for (y = 0; y < height; y++) {
png_write_row (png_ptr, p);
p += width;
}
} else {
for (y = 0; y < height; y++) {
png_write_row (png_ptr, p);
p += width;
}
}
png_write_end (png_ptr, info_ptr);
png_destroy_write_struct (&png_ptr, &info_ptr);
#endif
}
/*
* write ppm image to stdout
*/
void
put_image_ppm (char *image, int width, int height)
{
int x, y, ls=0;
unsigned char *p = (unsigned char *)image;
printf ("P3\n%d %d\n%d\n", width, height, 255);
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
printf ("%03d %03d %03d ", p[2], p[1], p[0]);
p += 3;
if (ls++ > 4) {
printf ("\n");
ls = 0;
}
}
}
}
/*
*/
const char *
palette2string (int palette) {
if (palette == VIDEO_PALETTE_RGB24)
return "rgb24";
if (palette == VIDEO_PALETTE_YUV420P)
return "yuv420p";
if (palette == VIDEO_PALETTE_YUV422P)
return "yuv422p";
if (palette == VIDEO_PALETTE_GREY)
return "grey";
return "color";
}
/*
* create a plain html page
*/
void
make_html (int width, int height, int color, int input, int fmt, int quality,
float refresh, int us, int norm, int freq, char **freqs, int pal,
int swapRGB)
{
cgi_response (http_ok, "text/html");
/* cgi_refresh (refresh, NULL); */
cgi_html_start ("W3Cam");
printf ("<DIV class=image><IMG width=%d height=%d src=\"%s?"
"size=%dx%d&color=%s&id=%d&refresh=%1.2f&usleep=%d&freq=%d"
"&mode=plain",
width, height,
cgi_script_name(),
width, height, palette2string(pal),(int)time(NULL), refresh, us, freq);
if (input != INPUT_DEFAULT)
printf ("&input=%s", input == IN_TV? "tv" :
input == IN_COMP1 ? "composite" :
input == IN_COMP2? "composite2" : "s-video");
if (norm != OFF)
printf ("&norm=%s", norm == NORM_PAL ? "pal":
norm == NORM_NTSC ? "ntsc" : "secam");
if (fmt != FMT_DEFAULT)
printf ("&format=%s", fmt == FMT_PNG? "png":
fmt == FMT_JPEG? "jpeg": "ppm");
if (quality)
printf ("&quality=%d", quality);
if (swapRGB)
printf ("&bgr=1");
printf ("\"></DIV>\n");
}
/*
* create a html page with panel
*/
void
make_gui (int width, int height, int color, int input, int fmt, int quality,
float refresh, int us, int norm, int freq, char **freqs, int pal,
int swapRGB)
{
make_html (width, height, color, input, fmt, quality,
refresh, us, norm, freq, freqs, pal, swapRGB);
printf ("<P><DIV class=panel><FORM>\n");
printf ("<INPUT type=hidden name=width value=%d>", width);
printf ("<INPUT type=hidden name=height value=%d>\n", height);
printf ("<INPUT type=hidden name=mode value=gui>");
printf ("<INPUT type=hidden name=quality value=%d>\n", quality);
printf ("<INPUT type=hidden name=usleep value=%d>\n", us);
printf ("Input:<SELECT name=input>\n");
printf ("<option%s value='-1'>Default</option>",
input == INPUT_DEFAULT? " selected":"");
printf ("<option%s>TV</option>",
input == IN_TV? " selected":"");
printf ("<option%s>Composite</option>",
input == IN_COMP1 ? " selected":"");
printf ("<option%s>Composite2</option>",
input == IN_COMP2? " selected":"");
printf ("<option%s>S-Video</option></SELECT>\n",
input == IN_SVIDEO? " selected":"");
if ((norm != OFF) && (input == IN_TV)) {
printf ("Norm:<SELECT name=norm>\n");
printf ("<option%s>PAL</option>", norm == NORM_PAL ? " selected":"");
printf ("<option%s>NTSC</option>", norm == NORM_NTSC? " selected":"");
printf ("<option%s>SECAM</option>", norm == NORM_SECAM?" selected":"");
printf ("<option>off</option>"); /* hide gui entry */
printf ("</SELECT>\n");
}
if (freqs && (input == IN_TV)) {
int f;
printf ("Freq:<SELECT name=freq>\n");
printf ("<option value=0>default</option>\n");
while (*freqs) {
f = atoi(*freqs);
printf ("<option%s>%d</option>", freq == f ? " selected": "", f);
freqs++;
}
printf ("</SELECT>\n");
}
printf ("Format:<SELECT name=format>\n");
printf ("<option%s>PPM", fmt == FMT_PPM? " selected":"");
printf ("<option%s>PNG", fmt == FMT_PNG? " selected":"");
printf ("<option%s>JPEG</SELECT>\n", fmt == FMT_JPEG? " selected":"");
printf ("Size:<SELECT name=size>\n");
printf ("<option%s>80x60\n", width == 80 ? " selected": "");
printf ("<option%s>160x120", width == 160 ? " selected": "");
printf ("<option%s>240x180", width == 240 ? " selected": "");
printf ("<option%s>320x240", width == 320 ? " selected": "");
printf ("<option%s>400x300", width == 400 ? " selected": "");
printf ("<option%s>480x360", width == 480 ? " selected": "");
printf ("<option%s>640x480", width == 640 ? " selected": "");
printf ("<option%s>720x540", width == 720 ? " selected": "");
printf ("<option%s>768x576</SELECT>\n", width == 768 ? " selected": "");
printf ("Refresh (sec.):<SELECT name=refresh>\n");
printf ("<OPTION value=\"-1\">off\n");
printf ("<OPTION>0.0<OPTION>0.1<OPTION>0.5<OPTION>1.0<OPTION>2.0\n");
printf ("<OPTION>3.0<OPTION>4.0<OPTION>5.0\n");
printf ("<OPTION>10<OPTION>20<OPTION>40<OPTION>80\n");
if (refresh != OFF)
printf ("<option selected>%1.2f</SELECT>\n", refresh);
else
printf ("</SELECT>\n");
printf ("<P><input type=submit value=Update></FORM></DIV><P>\n");
cgi_html_end ("<HR><DIV class=footer>w3cam, © rasca</DIV>");
}
/*
*/
void
on_signal (int signum)
{
exit (0);
}
#ifdef HAVE_LIBTTF
#include "font.c"
#endif
/*
* main()
*/
int
main (int argc, char *argv[])
{
int width = WIDTH_DEFAULT, height = HEIGHT_DEFAULT, dev = -1;
char *val = NULL, **form = NULL, *image;
char *boundary = "--w3cam-ns-boundary--may-not-work-with-ie--";
char *freqlist = FREQLIST_DEFAULT;
char **freqs = NULL;
char *device = VIDEO_DEV;
int max_try = MAX_TRY_OPEN; /* we try 20 times (5 sec) to open the device */
int quality = QUALITY_DEFAULT; /* default jpeg quality setting */
int input = INPUT_DEFAULT;
int norm = NORM_DEFAULT;
int mode = MODE_DEFAULT;
int color = TRUE;
int swapRGB = FALSE;
int palette = VIDEO_PALETTE_RGB24;
float refresh = REFRESH_DEFAULT;
float min_refresh = MIN_REFRESH;
int format = FMT_DEFAULT;
int usec = USEC_DEFAULT;
int freq = 0;
int protected = 0;
char *mime = NULL;
#ifdef HAVE_LIBTTF
char *font = NULL;
char *timestamp = NULL;
int font_size = 12;
#define TS_MAX 128
/* timestamp string */
char ts_buff[TS_MAX+1];
int ts_len;
int border = 2;
int blend = 60;
int align = 1;
time_t t;
struct tm *tm;
TT_Engine engine;
TT_Face face;
TT_Face_Properties properties;
TT_Instance instance;
TT_Glyph *glyphs = NULL;
TT_Raster_Map bit;
TT_Raster_Map sbit;
#endif
#ifdef USE_SYSLOG
openlog (argv[0], LOG_PID, LOG_USER);
#endif
cgi_init (argv[0]);
if (signal (SIGTERM, on_signal) == SIG_ERR) {
log ("couldn't register handler for SIGTERM");
}
if (signal (SIGPIPE, on_signal) == SIG_ERR) {
log ("couldn't register handler for SIGPIPE");
}
/* check some values from the config file
*/
val = cgi_cfg_value ("width");
if (val) width = atoi (val);
val = cgi_cfg_value ("height");
if (val) height = atoi (val);
val = cgi_cfg_value ("color");
if (val) {
if (strcasecmp (val, "yuv420p") == 0) {
color = 1;
palette = VIDEO_PALETTE_YUV420P;
} else if (strcasecmp (val, "yuv422p") == 0) {
color = 1;
palette = VIDEO_PALETTE_YUV422P;
} else if (*val == '0' || *val == 'g') {
color = 0;
palette = VIDEO_PALETTE_GREY;
} else {
color = 1;
}
}
val = cgi_cfg_value ("refresh");
if (val) refresh = atof (val);
val = cgi_cfg_value ("norm");
if (val) norm = atoi (val);
val = cgi_cfg_value ("input");
if (val) input = atoi (val);
val = cgi_cfg_value ("format");
if (val) format = atoi (val);
val = cgi_cfg_value ("quality");
if (val) quality = atoi (val);
val = cgi_cfg_value ("mode");
if (val) mode = atoi (val);
val = cgi_cfg_value ("usleep");
if (val) usec = atoi (val);
val = cgi_cfg_value ("freq");
if (val) freq = atoi (val);
val = cgi_cfg_value ("freqlist");
if (val) freqlist = val;
val = cgi_cfg_value ("protected");
if (val) protected = atoi (val);
val = cgi_cfg_value ("device");
if (val) device = val;
val = cgi_cfg_value ("bgr");
if (val) swapRGB = atoi (val);
#ifdef HAVE_LIBTTF
val = cgi_cfg_value ("font");
if (val) font = val;
val = cgi_cfg_value ("font_size");
if (val) font_size = atoi (val);
val = cgi_cfg_value ("timestamp");
if (val) timestamp = val;
val = cgi_cfg_value ("timestamp_border");
if (val) border = atoi (val);
val = cgi_cfg_value ("timestamp_blend");
if (val) blend = atoi (val);
val = cgi_cfg_value ("timestamp_align");
if (val) align = atoi (val);
#endif
/* parse the form, if there is any
*/
if (!protected)
form = cgi_parse_form ();
if (form && !protected) {
val = cgi_form_value ("help");
if (val) {
usage (argv[0], width, height, color, quality, usec);
}
val = cgi_form_value ("size");
if (val) {
sscanf (val, "%dx%d", &width, &height);
}
val = cgi_form_value ("color");
if (val) {
if (strcasecmp (val, "yuv420p") == 0) {
color = 1;
palette = VIDEO_PALETTE_YUV420P;
} else if (strcasecmp (val, "yuv422p") == 0) {
color = 1;
palette = VIDEO_PALETTE_YUV422P;
} else if (*val == '0' || *val == 'g') {
color = 0;
palette = VIDEO_PALETTE_GREY;
} else {
color = 1;
palette = VIDEO_PALETTE_RGB24;
}
}
val = cgi_form_value ("format");
if (val) {
if ((strcasecmp ("ppm", val) == 0) && color) {
format = FMT_PPM;
} else if (strcasecmp ("png", val) == 0) {
format = FMT_PNG;
} else if (strcasecmp ("jpeg", val) == 0) {
format = FMT_JPEG;
}
}
val = cgi_form_value ("refresh");
if (val) refresh = atof (val);
val = cgi_form_value ("quality");
if (val) quality = atoi (val);
val = cgi_form_value ("usleep");
if (val) usec = atoi (val);
val = cgi_form_value ("freq");
if (val) freq = atoi (val);
val = cgi_form_value ("mode");
if (val) {
if (strcmp ("gui", val) == 0)
mode = MODE_GUI;
else if (strcmp ("html", val) == 0)
mode = MODE_HTML;
else
mode = MODE_PLAIN;
}
val = cgi_form_value ("input");
if (val) {
if (strcasecmp ("tv", val) == 0) {
input = IN_TV;
} else if (strcasecmp ("composite", val) == 0) {
input = IN_COMP1;
} else if (strcasecmp ("composite2", val) ==0) {
input = IN_COMP2;
} else if (strcasecmp ("s-video", val) == 0) {
input = IN_SVIDEO;
} else {
input = INPUT_DEFAULT;
}
}
val = cgi_form_value ("norm");
if (val) {
if (strcasecmp ("pal", val) == 0) {
norm = NORM_PAL;
} else if (strcasecmp ("ntsc", val) == 0) {
norm = NORM_NTSC;
} else if (strcasecmp ("secam", val) == 0) {
norm = NORM_SECAM;
} else {
norm = OFF;
}
}
val = cgi_form_value ("bgr");
if (val) {
/* check for yes,true,1 */
if ((*val == '1') || (*val == 't') || (*val == 'y')) {
swapRGB = 1;
} else {
swapRGB = 0;
}
}
}
if ((refresh > OFF) && (refresh < min_refresh))
refresh = min_refresh;
if (!*freqlist)
freqlist = NULL;
if (mode == MODE_GUI) {
freqs = parse_list (freqlist);
make_gui (width, height, color, input, format, quality, refresh, usec,
norm,freq, freqs, palette, swapRGB);
return (0);
}
if (mode == MODE_HTML) {
freqs = parse_list (freqlist);
make_html (width, height, color, input, format, quality, refresh, usec,
norm,freq, freqs, palette, swapRGB);
return (0);
}
switch (format) {
case FMT_PPM:
mime = "image/ppm";
break;
case FMT_JPEG:
mime = "image/jpeg";
break;
case FMT_PNG:
mime = "image/png";
break;
default:
log ("unknown image format..!?");
break;
}
#ifdef HAVE_LIBTTF
if (font && timestamp) {
if (TT_Init_FreeType (&engine)) {
font = NULL;
goto no_time_stamp;
}
if (Face_Open (font, engine, &face, &properties, &instance, font_size)){
TT_Done_FreeType (engine);
font = NULL;
goto no_time_stamp;
}
}
no_time_stamp:
#endif
if (!color) {
palette = VIDEO_PALETTE_GREY;
}
/* open the video4linux device */
again:
while (max_try) {
dev = open (device, O_RDWR);
if (dev == -1) {
log2 (device, strerror(errno));
if (!--max_try) {
cgi_response (http_ok, "text/plain");
printf ("Can't open device %s: %s\n",device,strerror(errno));
exit (0);
}
/* sleep 1/4 second */
usleep (250000);
} else {
max_try = MAX_TRY_OPEN; /* we may need it in a loop later .. */
break;
}
}
if (v4l_mute_sound (dev) == -1) {
perror ("mute sound");
}
if (v4l_set_input (dev, input, norm) == -1) {
return 1;
}
if (v4l_check_size (dev, &width, &height) == -1) {
return 1;
}
/* if (v4l_check_palette (dev, &palette) == -1) {
return 1;
} */
again_without_open:
image = get_image (dev, width, height, input, usec,freq, palette);
if (image) {
if (swapRGB && (palette == VIDEO_PALETTE_RGB24)) {
int x,y;
unsigned char *p, pt;
p = image;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
pt = *p;
*p = *(p+2);
*(p+2) = pt;
p += 3;
}
}
}
if (refresh != 0.0) {
close (dev);
}
if (refresh != OFF) {
cgi_multipart (boundary);
printf ("Content-Type: %s\n\n", mime);
} else {
cgi_response (http_ok, mime);
}
#ifdef HAVE_LIBTTF
if (font && timestamp) {
time (&t);
tm = localtime (&t);
ts_buff[TS_MAX] = '\0';
strftime (ts_buff, TS_MAX, timestamp, tm);
ts_len = strlen (ts_buff);
glyphs = Glyphs_Load (face, &properties, instance, ts_buff, ts_len);
Raster_Init(face, &properties,instance,ts_buff,ts_len, border, glyphs, &bit);
Raster_Small_Init (&sbit, &instance);
Render_String (glyphs, ts_buff, ts_len, &bit, &sbit, border);
if (bit.bitmap) {
int x, y, psize, i, x_off, y_off;
unsigned char *p;
if (color)
psize = 3;
else
psize = 1;
switch (align) {
case 1:
x_off = (width - bit.width) * psize;
y_off = 0;
break;
case 2:
x_off = 0;
y_off = height - bit.rows;
break;
case 3:
x_off = (width - bit.width) * psize;
y_off = height - bit.rows;
break;
default:
x_off = y_off = 0;
break;
}
for (y = 0; y < bit.rows; y++) {
p = image + (y + y_off) * (width * psize) + x_off;
for (x = 0; x < bit.width; x++) {
switch (((unsigned char *)bit.bitmap)
[((bit.rows-y-1)*bit.cols)+x]) {
case 0:
for (i = 0; i < psize; i++) {
*p = (255 * blend + *p * (100 - blend))/100;
p++;
}
break;
case 1:
for (i = 0; i < psize; i++) {
*p = (220 * blend + *p * (100 - blend))/100;
p++;
}
break;
case 2:
for (i = 0; i < psize; i++) {
*p = (162 * blend + *p * (100 - blend))/100;
p++;
}
break;
case 3:
for (i = 0; i < psize; i++) {
*p = (64 * blend + *p * (100 - blend))/100;
p++;
}
break;
default:
for (i = 0; i < psize; i++) {
*p = (0 * blend + *p * (100 - blend))/100;
p++;
}
break;
}
}
}
}
Raster_Done (&sbit);
Raster_Done (&bit);
Glyphs_Done (glyphs);
glyphs = NULL;
}
#endif
switch (format) {
case FMT_PPM:
put_image_ppm (image, width, height);
printf ("\n%s\n", boundary);
break;
case FMT_PNG:
put_image_png (image, width, height, color);
printf ("\n%s\n", boundary);
break;
case FMT_JPEG:
put_image_jpeg (image, width, height, quality, color);
printf ("\n%s\n", boundary);
break;
default:
/* should never be reached */
printf ("Unknown format (%d)\n", format);
printf ("\n%s\n", boundary);
break;
}
free (image);
if (refresh == 0.0) {
fflush (stdout);
/* wait ? */
goto again_without_open;
}
if (refresh != OFF) {
fflush (stdout);
usleep ((int)(refresh * 1000000));
goto again;
}
} else {
cgi_response (http_ok, "text/plain");
printf ("Error: Can't get image\n");
close (dev);
}
#ifdef HAVE_LIBTTF
if (font && timestamp) {
Face_Done (instance, face);
TT_Done_FreeType (engine);
}
#endif
return (0);
}
| 25.306627 | 83 | 0.599765 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.