code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
//
// PhotoCardViewController.h
// Whetstone-iOS
//
// Created by Philip James on 11/24/13.
// Copyright (c) 2013 Philip James. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface PhotoCardViewController : UIViewController
@property (nonatomic) float duration;
@end
|
ImmaculateObsession/whetstone-ios
|
Whetstone-iOS/Whetstone-iOS/PhotoCardViewController.h
|
C
|
mit
| 279
|
using Starcounter;
namespace People
{
[Database]
public class PhoneNumber : ContactInfo
{
public string Number { get; set; }
public PhoneNumberType Type { get; set; }
public override string Content => Number ?? "";
}
}
|
StarcounterSamples/People
|
src/People/Database/PhoneNumber.cs
|
C#
|
mit
| 265
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CorsStudentClient
{
public partial class About
{
}
}
|
BCIT-ASP/WebAPI-CORS
|
StudentWebApiCorsLab/CorsStudentClient/About.aspx.designer.cs
|
C#
|
mit
| 438
|
package com.tjazi.chatroom.service;
import com.tjazi.chatroom.model.SingleChatroomData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Created by kwasiak on 19/07/15.
*/
@Service
public class ChatroomServiceImpl implements ChatroomService {
private List<SingleChatroomDriver> chatroomData = new ArrayList<>();
@Autowired
private SingleChatroomDriverFactory singleChatroomDriverFactory;
@Override
public boolean isChatroomExist(String chatroomName) {
if (chatroomName == null || chatroomName.isEmpty()) {
throw new IllegalArgumentException("chatroomName is null or empty");
}
return chatroomData.stream()
.anyMatch(
data -> data.getChatroomName()
.equalsIgnoreCase(chatroomName));
}
@Override
public SingleChatroomDriver createNewChatroom(String chatroomName) {
if (chatroomName == null || chatroomName.isEmpty()) {
throw new IllegalArgumentException("chatroomName is null or empty");
}
if (this.isChatroomExist(chatroomName)) {
throw new IllegalArgumentException("There's already chatroom with name: " + chatroomName);
}
SingleChatroomDriver chatroomDriver = singleChatroomDriverFactory.createSingleChatroomDriver(chatroomName);
chatroomData.add(chatroomDriver);
return chatroomDriver;
}
public SingleChatroomDriver findChatroomByUuid(UUID chatroomUuid) {
if (chatroomUuid == null) {
throw new IllegalArgumentException("chatroomUiid is null");
}
Optional<SingleChatroomDriver> matchingElement =
chatroomData.stream()
.filter(element -> element.getChatroomUuid().equals(chatroomUuid))
.findFirst();
// return result of the search or NULL if there's nothing to return
return matchingElement.orElse(null);
}
@Override
public SingleChatroomDriver findChatroomByName(String chatroomName) {
if (chatroomName == null || chatroomName.isEmpty()) {
throw new IllegalArgumentException("chatroomName is null or empty.");
}
Optional<SingleChatroomDriver> matchingElement =
chatroomData.stream()
.filter(element -> element.getChatroomName().equalsIgnoreCase(chatroomName))
.findFirst();
return matchingElement.orElse(null);
}
@Override
public List<SingleChatroomDriver> getChatroomsForUser(String userName) {
if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("userName is null or empty.");
}
return chatroomData.stream()
.filter(x -> x.isUserInChatroom(userName))
.collect(Collectors.toList());
}
}
|
kwasiak/tjazi.com
|
webapp/src/main/java/com/tjazi/chatroom/service/ChatroomServiceImpl.java
|
Java
|
mit
| 3,082
|
import { OfficeService } from './../service/office.service';
import { ImageQueryService } from '../service/image-query.service';
import { SearchResult } from '../service/search-result';
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-search-result',
templateUrl: './search-result.component.html',
styleUrls: ['./search-result.component.css']
})
export class SearchResultComponent implements OnInit {
@Input()
model: SearchResult;
previewURL() {
return this.model.thumbNailURL;
}
user() {
return this.model.user;
}
constructor(private images: ImageQueryService, private office: OfficeService) { }
ngOnInit() {
}
insertImage() {
console.debug('inserting ' + this.model.thumbNailURL);
this.images.getAsBase64(this.model).subscribe(imgData => {
console.info(imgData);
this.office.insertImage(imgData);
},
error => console.error(JSON.stringify(error)));
}
}
|
BitSchupser/pixapoint
|
src/app/search-result/search-result.component.ts
|
TypeScript
|
mit
| 965
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from itertools import groupby
from time import time
from functools import partial
import re
import django
django.setup()
from django.db import transaction
from clldutils.dsv import reader
from clldutils.text import split_text
from clldutils.path import Path
from clldutils import jsonlib
import attr
from dplace_app.models import Source
from loader.util import configure_logging, load_regions
from loader.society import society_locations, load_societies, load_society_relations
from loader.phylogenies import load_phylogenies
from loader.variables import load_vars
from loader.values import load_data
from loader.sources import load_references
from loader.glottocode import load_languages
comma_split = partial(split_text, separators=',', strip=True, brackets={})
semicolon_split = partial(split_text, separators=';', strip=True, brackets={})
def valid_enum_member(choices, instance, attribute, value):
if value not in choices:
raise ValueError(value)
@attr.s
class Variable(object):
category = attr.ib(convert=lambda s: [c.capitalize() for c in comma_split(s)])
id = attr.ib()
title = attr.ib()
definition = attr.ib()
type = attr.ib(
validator=partial(valid_enum_member, ['Continuous', 'Categorical', 'Ordinal']))
units = attr.ib()
source = attr.ib()
changes = attr.ib()
notes = attr.ib()
codes = attr.ib(default=attr.Factory(list))
@attr.s
class Data(object):
soc_id = attr.ib()
sub_case = attr.ib()
year = attr.ib()
var_id = attr.ib()
code = attr.ib()
comment = attr.ib()
references = attr.ib(convert=semicolon_split)
source_coded_data = attr.ib()
admin_comment = attr.ib()
@attr.s
class ObjectWithSource(object):
id = attr.ib()
name = attr.ib()
year = attr.ib()
author = attr.ib()
reference = attr.ib()
base_dir = attr.ib()
@property
def dir(self):
return self.base_dir.joinpath(self.id)
def as_source(self):
return Source.objects.create(
**{k: getattr(self, k) for k in 'year author name reference'.split()})
@attr.s
class RelatedSociety(object):
dataset = attr.ib(convert=lambda s: s.strip())
name = attr.ib(convert=lambda s: s.strip())
id = attr.ib(convert=lambda s: s.strip())
@classmethod
def from_string(cls, s):
match = re.match('([A-Za-z]+):\s*([^\[]+)\[([^\]]+)\]$', s)
if not match:
raise ValueError(s)
return cls(*match.groups())
@attr.s
class RelatedSocieties(object):
id = attr.ib()
related = attr.ib(convert=lambda s: [
RelatedSociety.from_string(ss) for ss in semicolon_split(s)])
@attr.s
class Dataset(ObjectWithSource):
type = attr.ib(validator=partial(valid_enum_member, ['cultural', 'environmental']))
description = attr.ib()
url = attr.ib()
def _items(self, what, **kw):
fname = self.dir.joinpath('{0}.csv'.format(what))
return list(reader(fname, **kw)) if fname.exists() else []
@property
def data(self):
return [Data(**d) for d in self._items('data', dicts=True)]
@property
def references(self):
return self._items('references', namedtuples=True)
@property
def societies(self):
return self._items('societies', namedtuples=True)
@property
def society_relations(self):
return [
RelatedSocieties(**d) for d in self._items('societies_mapping', dicts=True)]
@property
def variables(self):
codes = {vid: list(c) for vid, c in groupby(
sorted(self._items('codes', namedtuples=True), key=lambda c: c.var_id),
lambda c: c.var_id)}
return [
Variable(codes=codes.get(v['id'], []), **v)
for v in self._items('variables', dicts=True)]
@attr.s
class Phylogeny(ObjectWithSource):
scaling = attr.ib()
url = attr.ib()
@property
def trees(self):
return self.dir.joinpath('summary.trees')
@property
def taxa(self):
return list(reader(self.dir.joinpath('taxa.csv'), dicts=True))
class Repos(object):
def __init__(self, dir_):
self.dir = dir_
self.datasets = [
Dataset(base_dir=self.dir.joinpath('datasets'), **r) for r in
reader(self.dir.joinpath('datasets', 'index.csv'), dicts=True)]
self.phylogenies = [
Phylogeny(base_dir=self.dir.joinpath('phylogenies'), **r) for r in
reader(self.dir.joinpath('phylogenies', 'index.csv'), dicts=True)]
def path(self, *comps):
return self.dir.joinpath(*comps)
def read_csv(self, *comps, **kw):
return list(reader(self.path(*comps), **kw))
def read_json(self, *comps):
return jsonlib.load(self.path(*comps))
def load(repos, test=True):
configure_logging(test=test)
repos = Repos(repos)
for func in [
load_societies,
load_society_relations,
load_regions,
society_locations,
load_vars,
load_languages,
load_references,
load_data,
load_phylogenies,
]:
with transaction.atomic():
if not test:
print("%s..." % func.__name__) # pragma: no cover
start = time()
res = func(repos)
if not test: # pragma: no cover
print("{0} loaded in {1:.2f} secs".format(res, time() - start))
if __name__ == '__main__': # pragma: no cover
load(Path(sys.argv[1]), test=False)
sys.exit(0)
|
NESCent/dplace
|
dplace_app/load.py
|
Python
|
mit
| 5,554
|
module ExtraJsonMatchers
def have_json_value(object = nil)
JsonSpec::Matchers::BeJsonEql.new(object.to_json)
end
end
RSpec.configure do |config|
config.include ExtraJsonMatchers, type: :view
end
|
rpearce/rails-template
|
spec/support/matchers/json_matchers.rb
|
Ruby
|
mit
| 206
|
def count_keys_equal(A, n, m):
equal = [0] * (m + 1)
for i in range(0, n): # 0 1 2 3 4 5 6
key = A[i] # 1 3 0 1 1 3 1
equal[key] += 1
return equal
def count_keys_less(equal, m):
less = [0] * (m + 1)
less[0] = 0
for j in range(1, m+1): # 0 1 2 3 4 5 6
less[j]= less[j - 1] + equal[j - 1] # 0 0 0 0 0 0 0
return less
def rearrange(A, less, n, m):
next = [0] * (m + 1)
B = [0] * n
for j in range(0, m + 1): # 1 2 5 5 6 7 10
next[j] = less[j] + 1
for i in range(0, n):
key = A[i]
index = next[key] - 1
B[index] = A[i]
next[key] += 1
return B
def counting_sort(A, n, m):
equal = count_keys_equal(A, n, m)
less = count_keys_less(equal, m)
return rearrange(A, less, n, m)
A = [4, 1, 5, 0, 1, 6, 5, 1, 5, 3]
print A
m = max(A)
n = len(A)
B = counting_sort(A, n, m)
print(B)
|
wastegas/Data-Structures-Algorithms
|
src/Sorting/counting-sort.py
|
Python
|
mit
| 951
|
<center><b>{{book_name}} {{chapter_nr}}</b></center>
<p class='{{scripture.direction.toLowerCase()}}'>
<div ng-repeat='verse in verses track by $id(verse)'>
<small class='ltr'>{{verse.verse_nr | number : 0}}</small>
{{verse.verse}}
</div>
<br>
</p>
|
SergejKasper/AngularGetBible
|
src/angular-get-bible/templates/ViewVerses.template.html
|
HTML
|
mit
| 288
|
const PlayerError = require('./errors.js').UnknownPlayerIdException;
const Player = require('./player.js');
const Map = require('./map.js');
const Resources = require('./resources.js');
const Virus = require('./virus.js');
class Game {
constructor(playerId, id, tick, timeLeft, players, resources, map, viruses) {
this.id = id;
this.tick = tick;
this.timeLeft = timeLeft;
this.players = players;
this.resources = resources;
this.map = map;
this.viruses = viruses;
this.me = players.find(p => p.id === playerId);
if(this.me === undefined) {
throw new PlayerError();
}
this.enemies = players.filter(p => p.id !== playerId);
}
static parse(payload, playerId) {
return new Game(
playerId,
payload.id,
payload.tick,
payload.timeLeft,
payload.players.map(p => Player.parse(p)),
Resources.parse(payload.resources),
Map.parse(payload.map),
payload.viruses.map(v => Virus.parse(v))
);
}
static get RANKED_GAME_ID() {
return -1;
}
static get UPDATE_PER_SECOND() {
return 3;
}
get actions() {
return this.me.actions;
}
}
module.exports = Game;
|
DrPandemic/aigar.io
|
clients/javascript/game/game.js
|
JavaScript
|
mit
| 1,179
|
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
// Windows Internal Libraries (wil)
//! @file
//! Windows Error Handling Helpers: standard error handling mechanisms across return codes, fail fast, exceptions and logging
#pragma once
#ifndef __ERRORHANDLING_H
#error "Please include ErrorHandling.h rather than directly including Result.h"
#endif
#include <WinError.h>
#include <strsafe.h>
#include <IwMalloc.h> // IwMalloc / IwFree used for internal buffer management
#include <intrin.h> // provides the _ReturnAddress() intrinsic
#include "Common.h"
#if defined(WIL_ENABLE_EXCEPTIONS) && !defined(WIL_SUPPRESS_NEW)
#include <new> // provides std::bad_alloc in the windows and public CRT headers
#endif
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
#endif
#if !defined(_NTDEF_)
typedef _Return_type_success_(return >= 0) LONG NTSTATUS;
#endif
#pragma warning(push)
#pragma warning(disable : 4714) // __forceinline not honored
#ifndef WIL_IMPEXP
#define WIL_IMPEXP __declspec(dllimport)
#endif
#ifndef WIL_EXPORT
#ifdef __cplusplus
#define WIL_EXPORT extern "C" WIL_IMPEXP
#else
#define WIL_EXPORT extern WIL_IMPEXP
#endif
#endif
//*****************************************************************************
// Behavioral setup (error handling macro configuration)
//*****************************************************************************
// Set any of the following macros to the values given below before including Result.h to
// control the error handling macro's trade-offs between diagnostics and performance
// RESULT_DIAGNOSTICS_LEVEL
// This define controls the level of diagnostic instrumentation that is built into the binary as a
// byproduct of using the macros. The amount of diagnostic instrumentation that is supplied is
// a trade-off between diagnosibility of issues and code size and performance. The modes are:
// 0 - No diagnostics, smallest & fastest (subject to tail-merge)
// 1 - No diagnostics, unique call sites for each macro (defeat's tail-merge)
// 2 - Line number
// 3 - Line number + source filename
// 4 - Line number + source filename + function name
// 5 - Line number + source filename + function name + code within the macro
// By default, mode 3 is used in free builds and mode 5 is used in checked builds. Note that the
// _ReturnAddress() will always be available through all modes when possible.
// RESULT_INCLUDE_CALLER_RETURNADDRESS
// This controls whether or not the _ReturnAddress() of the function that includes the macro will
// be reported to telemetry. Note that this is in addition to the _ReturnAddress() of the actual
// macro position (which is always reported). The values are:
// 0 - The address is not included
// 1 - The address is included
// The default value is '1'.
// RESULT_INLINE_ERROR_TESTS
// For conditional macros (other than RETURN_XXX), this controls whether branches will be evaluated
// within the call containing the macro or will be forced into the function called by the macros.
// Pushing branching into the called function reduces code size and the number of unique branches
// evaluated, but increases the instruction count executed per macro.
// 0 - Branching will not happen inline to the macros
// 1 - Branching is pushed into the calling function via __forceinline
// The default value is '1'. Note that XXX_MSG functions are always effectively mode '0' due to the
// compiler's unwillingness to inline var-arg functions.
// RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST
// RESULT_INCLUDE_CALLER_RETURNADDRESS_FAIL_FAST
// RESULT_INLINE_ERROR_TESTS_FAIL_FAST
// These defines are identical to those above in form/function, but only applicable to fail fast error
// handling allowing a process to have different diagnostic information and performance characteristics
// for fail fast than for other error handling given the different reporting infrastructure (Watson
// vs Telemetry).
// RESULT_SUPPRESS_PRERELEASE
// RESULT_FORCE_PRERELEASE
// Set one or the other to always force (or deny) pre-release behavior from within the WIL macros.
// Current pre-release behavioral differences are:
// * RETURN_XXX macros (without _MSG or _LOG suffix) include diagnostic information and report
// telemetry (they will not do so in release)
// * More aggressive use of FailFast in scenarios where failures are uncommon to help find bugs
// (an example is use of ::GetLastError() when the last error is not set). This is elevated
// to fail fast in pre-release to raise visibility. In release it reports a generic error (and
// telemetry) given that its likely the failure has gone undiscovered until then.
// * Default use of FailFast when converting an unknown exception to an HRESULT. If the exception is
// unknown, it's like a bug (or a situation where an exception conversion function should be
// supported). In release it reports a generic error given the possibility that the particular
// exception type has not been seen until that point.
// By default, WIL picks up the PRERELEASE define and changes behavior accordingly.
// Setup the debug behavior
#ifndef RESULT_DEBUG
#if (DBG || defined(DEBUG) || defined(_DEBUG)) && !defined(NDEBUG)
#define RESULT_DEBUG
#endif
#endif
// Set the default diagnostic mode
// Note that RESULT_DEBUG_INFO and RESULT_SUPPRESS_DEBUG_INFO are older deprecated models of controlling mode
#ifndef RESULT_DIAGNOSTICS_LEVEL
#if (defined(DBG) || defined(_DEBUG) || defined(RESULT_DEBUG_INFO)) && !defined(RESULT_SUPPRESS_DEBUG_INFO)
#define RESULT_DIAGNOSTICS_LEVEL 5
#else
#define RESULT_DIAGNOSTICS_LEVEL 3
#endif
#endif
#ifndef RESULT_INCLUDE_CALLER_RETURNADDRESS
#define RESULT_INCLUDE_CALLER_RETURNADDRESS 1
#endif
#ifndef RESULT_INLINE_ERROR_TESTS
#define RESULT_INLINE_ERROR_TESTS 1
#endif
#ifndef RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST
#define RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST RESULT_DIAGNOSTICS_LEVEL
#endif
#ifndef RESULT_INCLUDE_CALLER_RETURNADDRESS_FAIL_FAST
#define RESULT_INCLUDE_CALLER_RETURNADDRESS_FAIL_FAST RESULT_INCLUDE_CALLER_RETURNADDRESS
#endif
#ifndef RESULT_INLINE_ERROR_TESTS_FAIL_FAST
#define RESULT_INLINE_ERROR_TESTS_FAIL_FAST RESULT_INLINE_ERROR_TESTS
#endif
// Lock to prerelease behavior. This is a short-term fix to avoid ODR violations.
#define RESULT_FORCE_PRERELEASE
// Setup the default pre-release behavior
#ifndef RESULT_PRERELEASE
#if (defined(RESULT_FORCE_PRERELEASE) || ((defined(DBG) || defined(_DEBUG)) && !defined(RESULT_SUPPRESS_PRERELEASE)))
#define RESULT_PRERELEASE
#endif
#endif
//*****************************************************************************
// Win32 specific error macros
//*****************************************************************************
#define FAILED_WIN32(win32err) ((win32err) != 0)
#define SUCCEEDED_WIN32(win32err) ((win32err) == 0)
//*****************************************************************************
// NT_STATUS specific error macros
//*****************************************************************************
#define FAILED_NTSTATUS(status) (((NTSTATUS)(status)) < 0)
#define SUCCEEDED_NTSTATUS(status) (((NTSTATUS)(status)) >= 0)
//*****************************************************************************
// Testing helpers - redefine to run unit tests against fail fast
//*****************************************************************************
#ifndef RESULT_NORETURN
#define RESULT_NORETURN __declspec(noreturn)
#endif
#ifndef RESULT_NORETURN_NULL
#define RESULT_NORETURN_NULL _Ret_notnull_
#endif
#ifndef RESULT_RAISE_FAST_FAIL_EXCEPTION
#define RESULT_RAISE_FAST_FAIL_EXCEPTION __fastfail(FAST_FAIL_FATAL_APP_EXIT)
#endif
//*****************************************************************************
// Helpers to setup the macros and functions used below... do not directly use.
//*****************************************************************************
//! @cond
#define __R_FN_PARAMS_FULL \
_In_opt_ void *callerReturnAddress, unsigned int lineNumber, _In_opt_ PCSTR fileName, _In_opt_ PCSTR functionName, \
_In_opt_ PCSTR code, void *returnAddress
#define __R_FN_LOCALS_FULL_RA \
void* callerReturnAddress = nullptr; \
unsigned int lineNumber = 0; \
PCSTR fileName = nullptr; \
PCSTR functionName = nullptr; \
PCSTR code = nullptr; \
void* returnAddress = _ReturnAddress();
#define __R_ENABLE_IF_IS_CLASS(ptrType) typename wistd::enable_if_t<wistd::is_class<ptrType>::value, void*> = nullptr
#define __R_ENABLE_IF_IS_NOT_CLASS(ptrType) typename wistd::enable_if_t<!wistd::is_class<ptrType>::value, void*> = nullptr
// NOTE: This BEGINs the common macro handling (__R_ prefix) for non-fail fast handled cases
// This entire section will be repeated below for fail fast (__RFF_ prefix).
#define __R_COMMA ,
#define __R_FN_CALL_FULL callerReturnAddress, lineNumber, fileName, functionName, code, returnAddress
#define __R_FN_CALL_FULL_RA callerReturnAddress, lineNumber, fileName, functionName, code, _ReturnAddress()
// The following macros assemble the varying amount of data we want to collect from the macros, treating it uniformly
#if (RESULT_DIAGNOSTICS_LEVEL >= 2) // line number
#define __R_IF_LINE(term) term
#define __R_IF_NOT_LINE(term)
#define __R_IF_COMMA ,
#else
#define __R_IF_LINE(term)
#define __R_IF_NOT_LINE(term) term
#define __R_IF_COMMA
#endif
#if (RESULT_DIAGNOSTICS_LEVEL >= 3) // line number + file name
#define __R_IF_FILE(term) term
#define __R_IF_NOT_FILE(term)
#else
#define __R_IF_FILE(term)
#define __R_IF_NOT_FILE(term) term
#endif
#if (RESULT_DIAGNOSTICS_LEVEL >= 4) // line number + file name + function name
#define __R_IF_FUNCTION(term) term
#define __R_IF_NOT_FUNCTION(term)
#else
#define __R_IF_FUNCTION(term)
#define __R_IF_NOT_FUNCTION(term) term
#endif
#if (RESULT_DIAGNOSTICS_LEVEL >= 5) // line number + file name + function name + macro code
#define __R_IF_CODE(term) term
#define __R_IF_NOT_CODE(term)
#else
#define __R_IF_CODE(term)
#define __R_IF_NOT_CODE(term) term
#endif
#if (RESULT_INCLUDE_CALLER_RETURNADDRESS == 1)
#define __R_IF_CALLERADDRESS(term) term
#define __R_IF_NOT_CALLERADDRESS(term)
#else
#define __R_IF_CALLERADDRESS(term)
#define __R_IF_NOT_CALLERADDRESS(term) term
#endif
#if (RESULT_INCLUDE_CALLER_RETURNADDRESS == 1) || (RESULT_DIAGNOSTICS_LEVEL >= 2)
#define __R_IF_TRAIL_COMMA ,
#else
#define __R_IF_TRAIL_COMMA
#endif
// Assemble the varying amounts of data into a single macro
#define __R_INFO_ONLY(CODE) \
__R_IF_CALLERADDRESS(_ReturnAddress() __R_IF_COMMA) \
__R_IF_LINE(__LINE__) __R_IF_FILE(__R_COMMA __FILE__) __R_IF_FUNCTION(__R_COMMA __FUNCTION__) __R_IF_CODE(__R_COMMA CODE)
#define __R_INFO(CODE) __R_INFO_ONLY(CODE) __R_IF_TRAIL_COMMA
#define __R_FN_PARAMS_ONLY \
__R_IF_CALLERADDRESS(void* callerReturnAddress __R_IF_COMMA) \
__R_IF_LINE(unsigned int lineNumber) \
__R_IF_FILE(__R_COMMA _In_opt_ PCSTR fileName) \
__R_IF_FUNCTION(__R_COMMA _In_opt_ PCSTR functionName) __R_IF_CODE(__R_COMMA _In_opt_ PCSTR code)
#define __R_FN_PARAMS __R_FN_PARAMS_ONLY __R_IF_TRAIL_COMMA
#define __R_FN_CALL_ONLY \
__R_IF_CALLERADDRESS(callerReturnAddress __R_IF_COMMA) \
__R_IF_LINE(lineNumber) __R_IF_FILE(__R_COMMA fileName) __R_IF_FUNCTION(__R_COMMA functionName) __R_IF_CODE(__R_COMMA code)
#define __R_FN_CALL __R_FN_CALL_ONLY __R_IF_TRAIL_COMMA
#define __R_FN_LOCALS \
__R_IF_NOT_CALLERADDRESS(void* callerReturnAddress = nullptr;) \
__R_IF_NOT_LINE(unsigned int lineNumber = 0;) \
__R_IF_NOT_FILE(PCSTR fileName = nullptr;) __R_IF_NOT_FUNCTION(PCSTR functionName = nullptr;) __R_IF_NOT_CODE(PCSTR code = nullptr;)
#define __R_FN_LOCALS_RA \
__R_IF_NOT_CALLERADDRESS(void* callerReturnAddress = nullptr;) \
__R_IF_NOT_LINE(unsigned int lineNumber = 0;) \
__R_IF_NOT_FILE(PCSTR fileName = nullptr;) \
__R_IF_NOT_FUNCTION(PCSTR functionName = nullptr;) __R_IF_NOT_CODE(PCSTR code = nullptr;) void* returnAddress = _ReturnAddress();
#define __R_FN_UNREFERENCED \
__R_IF_CALLERADDRESS(callerReturnAddress;) \
__R_IF_LINE(lineNumber;) __R_IF_FILE(fileName;) __R_IF_FUNCTION(functionName;) __R_IF_CODE(code;)
// 1) Direct Methods
// * Called Directly by Macros
// * Always noinline
// * May be template-driven to create unique call sites if (RESULT_DIAGNOSTICS_LEVEL == 1)
#if (RESULT_DIAGNOSTICS_LEVEL == 1)
#define __R_DIRECT_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RetType MethodName
#define __R_DIRECT_NORET_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RESULT_NORETURN RetType MethodName
#else
#define __R_DIRECT_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __R_DIRECT_NORET_METHOD(RetType, MethodName) inline __declspec(noinline) RESULT_NORETURN RetType MethodName
#endif
#define __R_DIRECT_FN_PARAMS __R_FN_PARAMS
#define __R_DIRECT_FN_PARAMS_ONLY __R_FN_PARAMS_ONLY
#define __R_DIRECT_FN_CALL __R_FN_CALL_FULL_RA __R_COMMA
#define __R_DIRECT_FN_CALL_ONLY __R_FN_CALL_FULL_RA
// 2) Internal Methods
// * Only called by Conditional routines
// * 'inline' when (RESULT_INLINE_ERROR_TESTS = 0 and RESULT_DIAGNOSTICS_LEVEL != 1), otherwise noinline (directly called by code when
// branching is forceinlined)
// * May be template-driven to create unique call sites if (RESULT_DIAGNOSTICS_LEVEL == 1 and RESULT_INLINE_ERROR_TESTS = 1)
#if (RESULT_DIAGNOSTICS_LEVEL == 1)
#define __R_INTERNAL_NOINLINE_METHOD(MethodName) inline __declspec(noinline) void MethodName
#define __R_INTERNAL_NOINLINE_NORET_METHOD(MethodName) inline __declspec(noinline) RESULT_NORETURN void MethodName
#define __R_INTERNAL_INLINE_METHOD(MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) void MethodName
#define __R_INTERNAL_INLINE_NORET_METHOD(MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RESULT_NORETURN void MethodName
#define __R_CALL_INTERNAL_INLINE_METHOD(MethodName) MethodName<optimizerCounter>
#else
#define __R_INTERNAL_NOINLINE_METHOD(MethodName) inline void MethodName
#define __R_INTERNAL_NOINLINE_NORET_METHOD(MethodName) inline RESULT_NORETURN void MethodName
#define __R_INTERNAL_INLINE_METHOD(MethodName) inline __declspec(noinline) void MethodName
#define __R_INTERNAL_INLINE_NORET_METHOD(MethodName) inline __declspec(noinline) RESULT_NORETURN void MethodName
#define __R_CALL_INTERNAL_INLINE_METHOD(MethodName) MethodName
#endif
#define __R_CALL_INTERNAL_NOINLINE_METHOD(MethodName) MethodName
#define __R_INTERNAL_NOINLINE_FN_PARAMS __R_FN_PARAMS void* returnAddress __R_COMMA
#define __R_INTERNAL_NOINLINE_FN_PARAMS_ONLY __R_FN_PARAMS void* returnAddress
#define __R_INTERNAL_NOINLINE_FN_CALL __R_FN_CALL_FULL __R_COMMA
#define __R_INTERNAL_NOINLINE_FN_CALL_ONLY __R_FN_CALL_FULL
#define __R_INTERNAL_INLINE_FN_PARAMS __R_FN_PARAMS
#define __R_INTERNAL_INLINE_FN_PARAMS_ONLY __R_FN_PARAMS_ONLY
#define __R_INTERNAL_INLINE_FN_CALL __R_FN_CALL_FULL_RA __R_COMMA
#define __R_INTERNAL_INLINE_FN_CALL_ONLY __R_FN_CALL_FULL_RA
#if (RESULT_INLINE_ERROR_TESTS == 0)
#define __R_INTERNAL_METHOD __R_INTERNAL_NOINLINE_METHOD
#define __R_INTERNAL_NORET_METHOD __R_INTERNAL_NOINLINE_NORET_METHOD
#define __R_CALL_INTERNAL_METHOD __R_CALL_INTERNAL_NOINLINE_METHOD
#define __R_INTERNAL_FN_PARAMS __R_INTERNAL_NOINLINE_FN_PARAMS
#define __R_INTERNAL_FN_PARAMS_ONLY __R_INTERNAL_NOINLINE_FN_PARAMS_ONLY
#define __R_INTERNAL_FN_CALL __R_INTERNAL_NOINLINE_FN_CALL
#define __R_INTERNAL_FN_CALL_ONLY __R_INTERNAL_NOINLINE_FN_CALL_ONLY
#else
#define __R_INTERNAL_METHOD __R_INTERNAL_INLINE_METHOD
#define __R_INTERNAL_NORET_METHOD __R_INTERNAL_INLINE_NORET_METHOD
#define __R_CALL_INTERNAL_METHOD __R_CALL_INTERNAL_INLINE_METHOD
#define __R_INTERNAL_FN_PARAMS __R_INTERNAL_INLINE_FN_PARAMS
#define __R_INTERNAL_FN_PARAMS_ONLY __R_INTERNAL_INLINE_FN_PARAMS_ONLY
#define __R_INTERNAL_FN_CALL __R_INTERNAL_INLINE_FN_CALL
#define __R_INTERNAL_FN_CALL_ONLY __R_INTERNAL_INLINE_FN_CALL_ONLY
#endif
// 3) Conditional Methods
// * Called Directly by Macros
// * May be noinline or __forceinline depending upon (RESULT_INLINE_ERROR_TESTS)
// * May be template-driven to create unique call sites if (RESULT_DIAGNOSTICS_LEVEL == 1)
#if (RESULT_DIAGNOSTICS_LEVEL == 1)
#define __R_CONDITIONAL_NOINLINE_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RetType MethodName
#define __R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __R_CONDITIONAL_INLINE_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
__forceinline RetType MethodName
#define __R_CONDITIONAL_INLINE_TEMPLATE_METHOD(RetType, MethodName) __forceinline RetType MethodName
#define __R_CONDITIONAL_PARTIAL_TEMPLATE unsigned int optimizerCounter __R_COMMA
#else
#define __R_CONDITIONAL_NOINLINE_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __R_CONDITIONAL_INLINE_METHOD(RetType, MethodName) __forceinline RetType MethodName
#define __R_CONDITIONAL_INLINE_TEMPLATE_METHOD(RetType, MethodName) __forceinline RetType MethodName
#define __R_CONDITIONAL_PARTIAL_TEMPLATE
#endif
#define __R_CONDITIONAL_NOINLINE_FN_CALL __R_FN_CALL _ReturnAddress() __R_COMMA
#define __R_CONDITIONAL_NOINLINE_FN_CALL_ONLY __R_FN_CALL _ReturnAddress()
#define __R_CONDITIONAL_INLINE_FN_CALL __R_FN_CALL
#define __R_CONDITIONAL_INLINE_FN_CALL_ONLY __R_FN_CALL_ONLY
#if (RESULT_INLINE_ERROR_TESTS == 0)
#define __R_CONDITIONAL_METHOD __R_CONDITIONAL_NOINLINE_METHOD
#define __R_CONDITIONAL_TEMPLATE_METHOD __R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD
#define __R_CONDITIONAL_FN_CALL __R_CONDITIONAL_NOINLINE_FN_CALL
#define __R_CONDITIONAL_FN_CALL_ONLY __R_CONDITIONAL_NOINLINE_FN_CALL_ONLY
#else
#define __R_CONDITIONAL_METHOD __R_CONDITIONAL_INLINE_METHOD
#define __R_CONDITIONAL_TEMPLATE_METHOD __R_CONDITIONAL_INLINE_TEMPLATE_METHOD
#define __R_CONDITIONAL_FN_CALL __R_CONDITIONAL_INLINE_FN_CALL
#define __R_CONDITIONAL_FN_CALL_ONLY __R_CONDITIONAL_INLINE_FN_CALL_ONLY
#endif
#define __R_CONDITIONAL_FN_PARAMS __R_FN_PARAMS
#define __R_CONDITIONAL_FN_PARAMS_ONLY __R_FN_PARAMS_ONLY
// Macro call-site helpers
#define __R_NS_ASSEMBLE2(ri, rd) in##ri##diag##rd // Differing internal namespaces eliminate ODR violations between modes
#define __R_NS_ASSEMBLE(ri, rd) __R_NS_ASSEMBLE2(ri, rd)
#define __R_NS_NAME __R_NS_ASSEMBLE(RESULT_INLINE_ERROR_TESTS, RESULT_DIAGNOSTICS_LEVEL)
#define __R_NS wil::details::__R_NS_NAME
#if (RESULT_DIAGNOSTICS_LEVEL == 1)
#define __R_FN(MethodName) __R_NS::MethodName<__COUNTER__>
#else
#define __R_FN(MethodName) __R_NS::MethodName
#endif
// NOTE: This ENDs the common macro handling (__R_ prefix) for non-fail fast handled cases
// This entire section is repeated below for fail fast (__RFF_ prefix). For ease of editing this section, the
// process is to copy/paste, and search and replace (__R_ -> __RFF_), (RESULT_DIAGNOSTICS_LEVEL ->
// RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST),
// (RESULT_INLINE_ERROR_TESTS -> RESULT_INLINE_ERROR_TESTS_FAIL_FAST) and (RESULT_INCLUDE_CALLER_RETURNADDRESS ->
// RESULT_INCLUDE_CALLER_RETURNADDRESS_FAIL_FAST)
#define __RFF_COMMA ,
#define __RFF_FN_CALL_FULL callerReturnAddress, lineNumber, fileName, functionName, code, returnAddress
#define __RFF_FN_CALL_FULL_RA callerReturnAddress, lineNumber, fileName, functionName, code, _ReturnAddress()
// The following macros assemble the varying amount of data we want to collect from the macros, treating it uniformly
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST >= 2) // line number
#define __RFF_IF_LINE(term) term
#define __RFF_IF_NOT_LINE(term)
#define __RFF_IF_COMMA ,
#else
#define __RFF_IF_LINE(term)
#define __RFF_IF_NOT_LINE(term) term
#define __RFF_IF_COMMA
#endif
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST >= 3) // line number + file name
#define __RFF_IF_FILE(term) term
#define __RFF_IF_NOT_FILE(term)
#else
#define __RFF_IF_FILE(term)
#define __RFF_IF_NOT_FILE(term) term
#endif
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST >= 4) // line number + file name + function name
#define __RFF_IF_FUNCTION(term) term
#define __RFF_IF_NOT_FUNCTION(term)
#else
#define __RFF_IF_FUNCTION(term)
#define __RFF_IF_NOT_FUNCTION(term) term
#endif
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST >= 5) // line number + file name + function name + macro code
#define __RFF_IF_CODE(term) term
#define __RFF_IF_NOT_CODE(term)
#else
#define __RFF_IF_CODE(term)
#define __RFF_IF_NOT_CODE(term) term
#endif
#if (RESULT_INCLUDE_CALLER_RETURNADDRESS_FAIL_FAST == 1)
#define __RFF_IF_CALLERADDRESS(term) term
#define __RFF_IF_NOT_CALLERADDRESS(term)
#else
#define __RFF_IF_CALLERADDRESS(term)
#define __RFF_IF_NOT_CALLERADDRESS(term) term
#endif
#if (RESULT_INCLUDE_CALLER_RETURNADDRESS_FAIL_FAST == 1) || (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST >= 2)
#define __RFF_IF_TRAIL_COMMA ,
#else
#define __RFF_IF_TRAIL_COMMA
#endif
// Assemble the varying amounts of data into a single macro
#define __RFF_INFO_ONLY(CODE) \
__RFF_IF_CALLERADDRESS(_ReturnAddress() __RFF_IF_COMMA) \
__RFF_IF_LINE(__LINE__) __RFF_IF_FILE(__RFF_COMMA __FILE__) __RFF_IF_FUNCTION(__RFF_COMMA __FUNCTION__) __RFF_IF_CODE(__RFF_COMMA CODE)
#define __RFF_INFO(CODE) __RFF_INFO_ONLY(CODE) __RFF_IF_TRAIL_COMMA
#define __RFF_FN_PARAMS_ONLY \
__RFF_IF_CALLERADDRESS(void* callerReturnAddress __RFF_IF_COMMA) \
__RFF_IF_LINE(unsigned int lineNumber) \
__RFF_IF_FILE(__RFF_COMMA _In_opt_ PCSTR fileName) \
__RFF_IF_FUNCTION(__RFF_COMMA _In_opt_ PCSTR functionName) __RFF_IF_CODE(__RFF_COMMA _In_opt_ PCSTR code)
#define __RFF_FN_PARAMS __RFF_FN_PARAMS_ONLY __RFF_IF_TRAIL_COMMA
#define __RFF_FN_CALL_ONLY \
__RFF_IF_CALLERADDRESS(callerReturnAddress __RFF_IF_COMMA) \
__RFF_IF_LINE(lineNumber) \
__RFF_IF_FILE(__RFF_COMMA fileName) __RFF_IF_FUNCTION(__RFF_COMMA functionName) __RFF_IF_CODE(__RFF_COMMA code)
#define __RFF_FN_CALL __RFF_FN_CALL_ONLY __RFF_IF_TRAIL_COMMA
#define __RFF_FN_LOCALS \
__RFF_IF_NOT_CALLERADDRESS(void* callerReturnAddress = nullptr;) \
__RFF_IF_NOT_LINE(unsigned int lineNumber = 0;) \
__RFF_IF_NOT_FILE(PCSTR fileName = nullptr;) \
__RFF_IF_NOT_FUNCTION(PCSTR functionName = nullptr;) __RFF_IF_NOT_CODE(PCSTR code = nullptr;)
#define __RFF_FN_UNREFERENCED \
__RFF_IF_CALLERADDRESS(callerReturnAddress;) \
__RFF_IF_LINE(lineNumber;) __RFF_IF_FILE(fileName;) __RFF_IF_FUNCTION(functionName;) __RFF_IF_CODE(code;)
// 1) Direct Methods
// * Called Directly by Macros
// * Always noinline
// * May be template-driven to create unique call sites if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST == 1)
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST == 1)
#define __RFF_DIRECT_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RetType MethodName
#define __RFF_DIRECT_NORET_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RESULT_NORETURN RetType MethodName
#else
#define __RFF_DIRECT_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __RFF_DIRECT_NORET_METHOD(RetType, MethodName) inline __declspec(noinline) RESULT_NORETURN RetType MethodName
#endif
#define __RFF_DIRECT_FN_PARAMS __RFF_FN_PARAMS
#define __RFF_DIRECT_FN_PARAMS_ONLY __RFF_FN_PARAMS_ONLY
#define __RFF_DIRECT_FN_CALL __RFF_FN_CALL_FULL_RA __RFF_COMMA
#define __RFF_DIRECT_FN_CALL_ONLY __RFF_FN_CALL_FULL_RA
// 2) Internal Methods
// * Only called by Conditional routines
// * 'inline' when (RESULT_INLINE_ERROR_TESTS_FAIL_FAST = 0 and RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST != 1), otherwise noinline (directly
// called by code when branching is forceinlined)
// * May be template-driven to create unique call sites if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST == 1 and
// RESULT_INLINE_ERROR_TESTS_FAIL_FAST = 1)
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST == 1)
#define __RFF_INTERNAL_NOINLINE_METHOD(MethodName) inline __declspec(noinline) void MethodName
#define __RFF_INTERNAL_NOINLINE_NORET_METHOD(MethodName) inline __declspec(noinline) RESULT_NORETURN void MethodName
#define __RFF_INTERNAL_INLINE_METHOD(MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) void MethodName
#define __RFF_INTERNAL_INLINE_NORET_METHOD(MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RESULT_NORETURN void MethodName
#define __RFF_CALL_INTERNAL_INLINE_METHOD(MethodName) MethodName<optimizerCounter>
#else
#define __RFF_INTERNAL_NOINLINE_METHOD(MethodName) inline void MethodName
#define __RFF_INTERNAL_NOINLINE_NORET_METHOD(MethodName) inline RESULT_NORETURN void MethodName
#define __RFF_INTERNAL_INLINE_METHOD(MethodName) inline __declspec(noinline) void MethodName
#define __RFF_INTERNAL_INLINE_NORET_METHOD(MethodName) inline __declspec(noinline) RESULT_NORETURN void MethodName
#define __RFF_CALL_INTERNAL_INLINE_METHOD(MethodName) MethodName
#endif
#define __RFF_CALL_INTERNAL_NOINLINE_METHOD(MethodName) MethodName
#define __RFF_INTERNAL_NOINLINE_FN_PARAMS __RFF_FN_PARAMS void* returnAddress __RFF_COMMA
#define __RFF_INTERNAL_NOINLINE_FN_PARAMS_ONLY __RFF_FN_PARAMS void* returnAddress
#define __RFF_INTERNAL_NOINLINE_FN_CALL __RFF_FN_CALL_FULL __RFF_COMMA
#define __RFF_INTERNAL_NOINLINE_FN_CALL_ONLY __RFF_FN_CALL_FULL
#define __RFF_INTERNAL_INLINE_FN_PARAMS __RFF_FN_PARAMS
#define __RFF_INTERNAL_INLINE_FN_PARAMS_ONLY __RFF_FN_PARAMS_ONLY
#define __RFF_INTERNAL_INLINE_FN_CALL __RFF_FN_CALL_FULL_RA __RFF_COMMA
#define __RFF_INTERNAL_INLINE_FN_CALL_ONLY __RFF_FN_CALL_FULL_RA
#if (RESULT_INLINE_ERROR_TESTS_FAIL_FAST == 0)
#define __RFF_INTERNAL_METHOD __RFF_INTERNAL_NOINLINE_METHOD
#define __RFF_INTERNAL_NORET_METHOD __RFF_INTERNAL_NOINLINE_NORET_METHOD
#define __RFF_CALL_INTERNAL_METHOD __RFF_CALL_INTERNAL_NOINLINE_METHOD
#define __RFF_INTERNAL_FN_PARAMS __RFF_INTERNAL_NOINLINE_FN_PARAMS
#define __RFF_INTERNAL_FN_PARAMS_ONLY __RFF_INTERNAL_NOINLINE_FN_PARAMS_ONLY
#define __RFF_INTERNAL_FN_CALL __RFF_INTERNAL_NOINLINE_FN_CALL
#define __RFF_INTERNAL_FN_CALL_ONLY __RFF_INTERNAL_NOINLINE_FN_CALL_ONLY
#else
#define __RFF_INTERNAL_METHOD __RFF_INTERNAL_INLINE_METHOD
#define __RFF_INTERNAL_NORET_METHOD __RFF_INTERNAL_INLINE_NORET_METHOD
#define __RFF_CALL_INTERNAL_METHOD __RFF_CALL_INTERNAL_INLINE_METHOD
#define __RFF_INTERNAL_FN_PARAMS __RFF_INTERNAL_INLINE_FN_PARAMS
#define __RFF_INTERNAL_FN_PARAMS_ONLY __RFF_INTERNAL_INLINE_FN_PARAMS_ONLY
#define __RFF_INTERNAL_FN_CALL __RFF_INTERNAL_INLINE_FN_CALL
#define __RFF_INTERNAL_FN_CALL_ONLY __RFF_INTERNAL_INLINE_FN_CALL_ONLY
#endif
// 3) Conditional Methods
// * Called Directly by Macros
// * May be noinline or __forceinline depending upon (RESULT_INLINE_ERROR_TESTS_FAIL_FAST)
// * May be template-driven to create unique call sites if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST == 1)
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST == 1)
#define __RFF_CONDITIONAL_NOINLINE_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
inline __declspec(noinline) RetType MethodName
#define __RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __RFF_CONDITIONAL_INLINE_METHOD(RetType, MethodName) \
template <unsigned int optimizerCounter> \
__forceinline RetType MethodName
#define __RFF_CONDITIONAL_INLINE_TEMPLATE_METHOD(RetType, MethodName) __forceinline RetType MethodName
#define __RFF_CONDITIONAL_PARTIAL_TEMPLATE unsigned int optimizerCounter __RFF_COMMA
#else
#define __RFF_CONDITIONAL_NOINLINE_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RetType, MethodName) inline __declspec(noinline) RetType MethodName
#define __RFF_CONDITIONAL_INLINE_METHOD(RetType, MethodName) __forceinline RetType MethodName
#define __RFF_CONDITIONAL_INLINE_TEMPLATE_METHOD(RetType, MethodName) __forceinline RetType MethodName
#define __RFF_CONDITIONAL_PARTIAL_TEMPLATE
#endif
#define __RFF_CONDITIONAL_NOINLINE_FN_CALL __RFF_FN_CALL _ReturnAddress() __RFF_COMMA
#define __RFF_CONDITIONAL_NOINLINE_FN_CALL_ONLY __RFF_FN_CALL _ReturnAddress()
#define __RFF_CONDITIONAL_INLINE_FN_CALL __RFF_FN_CALL
#define __RFF_CONDITIONAL_INLINE_FN_CALL_ONLY __RFF_FN_CALL_ONLY
#if (RESULT_INLINE_ERROR_TESTS_FAIL_FAST == 0)
#define __RFF_CONDITIONAL_METHOD __RFF_CONDITIONAL_NOINLINE_METHOD
#define __RFF_CONDITIONAL_TEMPLATE_METHOD __RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD
#define __RFF_CONDITIONAL_FN_CALL __RFF_CONDITIONAL_NOINLINE_FN_CALL
#define __RFF_CONDITIONAL_FN_CALL_ONLY __RFF_CONDITIONAL_NOINLINE_FN_CALL_ONLY
#else
#define __RFF_CONDITIONAL_METHOD __RFF_CONDITIONAL_INLINE_METHOD
#define __RFF_CONDITIONAL_TEMPLATE_METHOD __RFF_CONDITIONAL_INLINE_TEMPLATE_METHOD
#define __RFF_CONDITIONAL_FN_CALL __RFF_CONDITIONAL_INLINE_FN_CALL
#define __RFF_CONDITIONAL_FN_CALL_ONLY __RFF_CONDITIONAL_INLINE_FN_CALL_ONLY
#endif
#define __RFF_CONDITIONAL_FN_PARAMS __RFF_FN_PARAMS
#define __RFF_CONDITIONAL_FN_PARAMS_ONLY __RFF_FN_PARAMS_ONLY
// Macro call-site helpers
#define __RFF_NS_ASSEMBLE2(ri, rd) in##ri##diag##rd // Differing internal namespaces eliminate ODR violations between modes
#define __RFF_NS_ASSEMBLE(ri, rd) __RFF_NS_ASSEMBLE2(ri, rd)
#define __RFF_NS_NAME __RFF_NS_ASSEMBLE(RESULT_INLINE_ERROR_TESTS_FAIL_FAST, RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST)
#define __RFF_NS wil::details::__RFF_NS_NAME
#if (RESULT_DIAGNOSTICS_LEVEL_FAIL_FAST == 1)
#define __RFF_FN(MethodName) __RFF_NS::MethodName<__COUNTER__>
#else
#define __RFF_FN(MethodName) __RFF_NS::MethodName
#endif
// end-of-repeated fail-fast handling macros
// Helpers for return macros
#define __RETURN_HR_LOG(hr, str) \
do { \
HRESULT __hr = (hr); \
if (FAILED(__hr)) { \
__R_FN(Return_Hr)(__R_INFO(str) __hr); \
} \
return __hr; \
} while (0, 0)
#define __RETURN_HR_LOG_FAIL(hr, str) \
do { \
HRESULT __hr = (hr); \
__R_FN(Return_Hr)(__R_INFO(str) __hr); \
return __hr; \
} while (0, 0)
#define __RETURN_WIN32_LOG(err, str) \
do { \
DWORD __err = (err); \
if (FAILED_WIN32(__err)) { \
return __R_FN(Return_Win32)(__R_INFO(str) __err); \
} \
return S_OK; \
} while (0, 0)
#define __RETURN_WIN32_LOG_FAIL(err, str) \
do { \
DWORD __err = (err); \
return __R_FN(Return_Win32)(__R_INFO(str) __err); \
} while (0, 0)
#define __RETURN_GLE_LOG_FAIL(str) return __R_FN(Return_GetLastError)(__R_INFO_ONLY(str))
#define __RETURN_NTSTATUS_LOG(status, str) \
do { \
NTSTATUS __status = (status); \
if (FAILED_NTSTATUS(__status)) { \
return __R_FN(Return_NtStatus)(__R_INFO(str) __status); \
} \
return S_OK; \
} while (0, 0)
#define __RETURN_NTSTATUS_LOG_FAIL(status, str) \
do { \
NTSTATUS __status = (status); \
return __R_FN(Return_NtStatus)(__R_INFO(str) __status); \
} while (0, 0)
#define __RETURN_HR_MSG(hr, str, fmt, ...) \
do { \
HRESULT __hr = (hr); \
if (FAILED(__hr)) { \
__R_FN(Return_HrMsg)(__R_INFO(str) __hr, fmt, __VA_ARGS__); \
} \
return __hr; \
} while (0, 0)
#define __RETURN_HR_MSG_FAIL(hr, str, fmt, ...) \
do { \
HRESULT __hr = (hr); \
__R_FN(Return_HrMsg)(__R_INFO(str) __hr, fmt, __VA_ARGS__); \
return __hr; \
} while (0, 0)
#define __RETURN_WIN32_MSG(err, str, fmt, ...) \
do { \
DWORD __err = (err); \
if (FAILED_WIN32(__err)) { \
return __R_FN(Return_Win32Msg)(__R_INFO(str) __err, fmt, __VA_ARGS__); \
} \
return S_OK; \
} while (0, 0)
#define __RETURN_WIN32_MSG_FAIL(err, str, fmt, ...) \
do { \
DWORD __err = (err); \
return __R_FN(Return_Win32Msg)(__R_INFO(str) __err, fmt, __VA_ARGS__); \
} while (0, 0)
#define __RETURN_GLE_MSG_FAIL(str, fmt, ...) return __R_FN(Return_GetLastErrorMsg)(__R_INFO(str) fmt, __VA_ARGS__)
#define __RETURN_NTSTATUS_MSG(status, str, fmt, ...) \
do { \
NTSTATUS __status = (status); \
if (FAILED_NTSTATUS(__status)) { \
return __R_FN(Return_NtStatusMsg)(__R_INFO(str) __status, fmt, __VA_ARGS__); \
} \
return S_OK; \
} while (0, 0)
#define __RETURN_NTSTATUS_MSG_FAIL(status, str, fmt, ...) \
do { \
NTSTATUS __status = (status); \
return __R_FN(Return_NtStatusMsg)(__R_INFO(str) __status, fmt, __VA_ARGS__); \
} while (0, 0)
#ifdef RESULT_PRERELEASE
#define __RETURN_HR(hr, str) \
do { \
HRESULT __hr = (hr); \
if (FAILED(__hr)) { \
__R_FN(Return_HrPreRelease)(__R_INFO(str) __hr); \
} \
return __hr; \
} while (0, 0)
#define __RETURN_HR_FAIL(hr, str) \
do { \
HRESULT __hr = (hr); \
__R_FN(Return_HrPreRelease)(__R_INFO(str) __hr); \
return __hr; \
} while (0, 0)
#define __RETURN_NULL_FAIL(hr, str) \
do { \
HRESULT __hr = (hr); \
__R_FN(Return_NullPreRelease)(__R_INFO(str) __hr); \
return nullptr; \
} while (0, 0)
#define __RETURN_WIN32(err, str) \
do { \
DWORD __err = (err); \
if (FAILED_WIN32(__err)) { \
return __R_FN(Return_Win32PreRelease)(__R_INFO(str) __err); \
} \
return S_OK; \
} while (0, 0)
#define __RETURN_WIN32_FAIL(err, str) \
do { \
DWORD __err = (err); \
return __R_FN(Return_Win32PreRelease)(__R_INFO(str) __err); \
} while (0, 0)
#define __RETURN_NULL_WIN32_FAIL(err, str) \
do { \
DWORD __err = (err); \
__R_FN(Return_NullWin32PreRelease)(__R_INFO(str) __err); \
return nullptr; \
} while (0, 0)
#define __RETURN_GLE_FAIL(str) return __R_FN(Return_GetLastErrorPreRelease)(__R_INFO_ONLY(str))
#define __RETURN_NULL_GLE_FAIL(str) return __R_FN(Return_NullGetLastErrorPreRelease)(__R_INFO_ONLY(str))
#define __RETURN_NTSTATUS(status, str) \
do { \
NTSTATUS __status = (status); \
if (FAILED_NTSTATUS(__status)) { \
return __R_FN(Return_NtStatusPreRelease)(__R_INFO(str) __status); \
} \
return S_OK; \
} while (0, 0)
#define __RETURN_NTSTATUS_FAIL(status, str) \
do { \
NTSTATUS __status = (status); \
return __R_FN(Return_NtStatusPreRelease)(__R_INFO(str) __status); \
} while (0, 0)
#else
#define __RETURN_HR(hr, str) return (hr)
#define __RETURN_HR_FAIL(hr, str) return (hr)
#define __RETURN_NULL_FAIL(hr, str) return nullptr
#define __RETURN_WIN32(err, str) return (HRESULT_FROM_WIN32(err))
#define __RETURN_WIN32_FAIL(err, str) return (HRESULT_FROM_WIN32(err))
#define __RETURN_NULL_WIN32_FAIL(str) return nullptr
#define __RETURN_GLE_FAIL(str) return (wil::details::GetLastErrorFailHr())
#define __RETURN_NULL_GLE_FAIL(str) (wil::details::GetLastErrorFailHr(); return nullptr;)
#define __RETURN_NTSTATUS(status, str) return (wil::details::NtStatusToHr(status))
#define __RETURN_NTSTATUS_FAIL(status, str) return (wil::details::NtStatusToHr(status))
#endif
#if defined(_PREFAST_)
#define __WI_ANALYSIS_ASSUME(_exp) _Analysis_assume_(_exp)
#else
#ifdef RESULT_DEBUG
#define __WI_ANALYSIS_ASSUME(_exp) ((void)0)
#else
#define __WI_ANALYSIS_ASSUME(_exp) __noop(_exp)
#endif
#endif // _PREFAST_
//! @endcond
//*****************************************************************************
// Pre-release fail fast helpers (for use only internally to WIL)
//*****************************************************************************
//! @cond
#ifdef RESULT_PRERELEASE
#define __FAIL_FAST_PRERELEASE_ASSERT__(condition) \
do { \
if (!(condition)) { \
__RFF_FN(FailFast_Unexpected)(__RFF_INFO_ONLY(#condition)); \
} \
} while (0, 0)
#define __FAIL_FAST_PRERELEASE_ASSUME__(condition) __FAIL_FAST_PRERELEASE_ASSERT__(condition)
#define __FAIL_FAST_IMMEDIATE_PRERELEASE_ASSERT__(condition) \
do { \
if (!(condition)) { \
RESULT_RAISE_FAST_FAIL_EXCEPTION; \
} \
} while (0, 0)
#define __FAIL_FAST_IMMEDIATE_PRERELEASE_ASSUME__(condition) __FAIL_FAST_IMMEDIATE_PRERELEASE_ASSERT__(condition)
#else
#define __FAIL_FAST_PRERELEASE_ASSERT__(condition)
#define __FAIL_FAST_PRERELEASE_ASSUME__(condition) (condition)
#define __FAIL_FAST_IMMEDIATE_PRERELEASE_ASSERT__(condition)
#define __FAIL_FAST_IMMEDIATE_PRERELEASE_ASSUME__(condition) (condition)
#endif
//! @endcond
//*****************************************************************************
// Macros for returning failures as HRESULTs
//*****************************************************************************
// Always returns a known result (HRESULT) - logs failures in pre-release
#define RETURN_HR(hr) __RETURN_HR(wil::verify_hresult(hr), #hr)
#define RETURN_LAST_ERROR() __RETURN_GLE_FAIL(nullptr)
#define RETURN_WIN32(win32err) __RETURN_WIN32(win32err, #win32err)
#define RETURN_NTSTATUS(status) __RETURN_NTSTATUS(status, #status)
// Conditionally returns failures (HRESULT) - logs failures in pre-release
#define RETURN_IF_FAILED(hr) \
do { \
HRESULT __hrRet = wil::verify_hresult(hr); \
if (FAILED(__hrRet)) { \
__RETURN_HR_FAIL(__hrRet, #hr); \
} \
} while (0, 0)
#define RETURN_IF_WIN32_BOOL_FALSE(win32BOOL) \
do { \
BOOL __boolRet = wil::verify_BOOL(win32BOOL); \
if (!__boolRet) { \
__RETURN_GLE_FAIL(#win32BOOL); \
} \
} while (0, 0)
#define RETURN_IF_WIN32_ERROR(win32err) \
do { \
DWORD __errRet = (win32err); \
if (FAILED_WIN32(__errRet)) { \
__RETURN_WIN32_FAIL(__errRet, #win32err); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_INVALID(handle) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == INVALID_HANDLE_VALUE) { \
__RETURN_GLE_FAIL(#handle); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_NULL(handle) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == nullptr) { \
__RETURN_GLE_FAIL(#handle); \
} \
} while (0, 0)
#define RETURN_IF_NULL_ALLOC(ptr) \
do { \
if ((ptr) == nullptr) { \
__RETURN_HR_FAIL(E_OUTOFMEMORY, #ptr); \
} \
} while (0, 0)
#define RETURN_HR_IF(hr, condition) \
do { \
if (wil::verify_bool(condition)) { \
__RETURN_HR(wil::verify_hresult(hr), #condition); \
} \
} while (0, 0)
#define RETURN_HR_IF_FALSE(hr, condition) RETURN_HR_IF(hr, !(wil::verify_bool(condition)))
#define RETURN_HR_IF_NULL(hr, ptr) \
do { \
if ((ptr) == nullptr) { \
__RETURN_HR(wil::verify_hresult(hr), #ptr); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF(condition) \
do { \
if (wil::verify_bool(condition)) { \
__RETURN_GLE_FAIL(#condition); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF_FALSE(condition) RETURN_LAST_ERROR_IF(!(wil::verify_bool(condition)))
#define RETURN_LAST_ERROR_IF_NULL(ptr) \
do { \
if ((ptr) == nullptr) { \
__RETURN_GLE_FAIL(#ptr); \
} \
} while (0, 0)
#define RETURN_IF_NTSTATUS_FAILED(status) \
do { \
NTSTATUS __statusRet = (status); \
if (FAILED_NTSTATUS(__statusRet)) { \
__RETURN_NTSTATUS_FAIL(__statusRet, #status); \
} \
} while (0, 0)
// Always returns a known result (HRESULT) - always logs failures
#define RETURN_HR_LOG(hr) __RETURN_HR_LOG(wil::verify_hresult(hr), #hr)
#define RETURN_LAST_ERROR_LOG() __RETURN_GLE_LOG_FAIL(nullptr)
#define RETURN_WIN32_LOG(win32err) __RETURN_WIN32_LOG(win32err, #win32err)
#define RETURN_NTSTATUS_LOG(status) __RETURN_NTSTATUS_LOG(status, #status)
// Conditionally returns failures (HRESULT) - always logs failures
#define RETURN_IF_FAILED_LOG(hr) \
do { \
auto __hrRet = wil::verify_hresult(hr); \
if (FAILED(__hrRet)) { \
__RETURN_HR_LOG_FAIL(__hrRet, #hr); \
} \
} while (0, 0)
#define RETURN_IF_WIN32_BOOL_FALSE_LOG(win32BOOL) \
do { \
if (!wil::verify_BOOL(win32BOOL)) { \
__RETURN_GLE_LOG_FAIL(#win32BOOL); \
} \
} while (0, 0)
#define RETURN_IF_WIN32_ERROR_LOG(win32err) \
do { \
auto __errRet = (win32err); \
if (FAILED_WIN32(__errRet)) { \
__RETURN_WIN32_LOG_FAIL(__errRet, #win32err); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_INVALID_LOG(handle) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == INVALID_HANDLE_VALUE) { \
__RETURN_GLE_LOG_FAIL(#handle); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_NULL_LOG(handle) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == nullptr) { \
__RETURN_GLE_LOG_FAIL(#handle); \
} \
} while (0, 0)
#define RETURN_IF_NULL_ALLOC_LOG(ptr) \
do { \
if ((ptr) == nullptr) { \
__RETURN_HR_LOG_FAIL(E_OUTOFMEMORY, #ptr); \
} \
} while (0, 0)
#define RETURN_HR_IF_LOG(hr, condition) \
do { \
if (wil::verify_bool(condition)) { \
__RETURN_HR_LOG(wil::verify_hresult(hr), #condition); \
} \
} while (0, 0)
#define RETURN_HR_IF_FALSE_LOG(hr, condition) RETURN_HR_IF_LOG(hr, !(wil::verify_bool(condition)))
#define RETURN_HR_IF_NULL_LOG(hr, ptr) \
do { \
if ((ptr) == nullptr) { \
__RETURN_HR_LOG(wil::verify_hresult(hr), #ptr); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF_LOG(condition) \
do { \
if (wil::verify_bool(condition)) { \
__RETURN_GLE_LOG_FAIL(#condition); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF_FALSE_LOG(condition) RETURN_LAST_ERROR_IF_LOG(!(wil::verify_bool(condition)))
#define RETURN_LAST_ERROR_IF_NULL_LOG(ptr) \
do { \
if ((ptr) == nullptr) { \
__RETURN_GLE_LOG_FAIL(#ptr); \
} \
} while (0, 0)
#define RETURN_IF_NTSTATUS_FAILED_LOG(status) \
do { \
auto __statusRet = (status); \
if (FAILED_NTSTATUS(__statusRet)) { \
__RETURN_NTSTATUS_LOG_FAIL(__statusRet, #status); \
} \
} while (0, 0)
// Always returns a known failure (HRESULT) - always logs a var-arg message on failure
#define RETURN_HR_MSG(hr, fmt, ...) __RETURN_HR_MSG(wil::verify_hresult(hr), #hr, fmt, __VA_ARGS__)
#define RETURN_LAST_ERROR_MSG(fmt, ...) __RETURN_GLE_MSG_FAIL(nullptr, fmt, __VA_ARGS__)
#define RETURN_WIN32_MSG(win32err, fmt, ...) __RETURN_WIN32_MSG(win32err, #win32err, fmt, __VA_ARGS__)
#define RETURN_NTSTATUS_MSG(status, fmt, ...) __RETURN_NTSTATUS_MSG(status, #status, fmt, __VA_ARGS__)
// Conditionally returns failures (HRESULT) - always logs a var-arg message on failure
#define RETURN_IF_FAILED_MSG(hr, fmt, ...) \
do { \
auto __hrRet = wil::verify_hresult(hr); \
if (FAILED(__hrRet)) { \
__RETURN_HR_MSG_FAIL(__hrRet, #hr, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_IF_WIN32_BOOL_FALSE_MSG(win32BOOL, fmt, ...) \
do { \
if (!wil::verify_BOOL(win32BOOL)) { \
__RETURN_GLE_MSG_FAIL(#win32BOOL, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_IF_WIN32_ERROR_MSG(win32err, fmt, ...) \
do { \
auto __errRet = (win32err); \
if (FAILED_WIN32(__errRet)) { \
__RETURN_WIN32_MSG_FAIL(__errRet, #win32err, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_INVALID_MSG(handle, fmt, ...) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == INVALID_HANDLE_VALUE) { \
__RETURN_GLE_MSG_FAIL(#handle, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_NULL_MSG(handle, fmt, ...) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == nullptr) { \
__RETURN_GLE_MSG_FAIL(#handle, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_IF_NULL_ALLOC_MSG(ptr, fmt, ...) \
do { \
if ((ptr) == nullptr) { \
__RETURN_HR_MSG_FAIL(E_OUTOFMEMORY, #ptr, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_HR_IF_MSG(hr, condition, fmt, ...) \
do { \
if (wil::verify_bool(condition)) { \
__RETURN_HR_MSG(wil::verify_hresult(hr), #condition, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_HR_IF_FALSE_MSG(hr, condition, fmt, ...) RETURN_HR_IF_MSG(hr, !(wil::verify_bool(condition)), fmt, __VA_ARGS__)
#define RETURN_HR_IF_NULL_MSG(hr, ptr, fmt, ...) \
do { \
if ((ptr) == nullptr) { \
__RETURN_HR_MSG(wil::verify_hresult(hr), #ptr, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF_MSG(condition, fmt, ...) \
do { \
if (wil::verify_bool(condition)) { \
__RETURN_GLE_MSG_FAIL(#condition, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF_FALSE_MSG(condition, fmt, ...) RETURN_LAST_ERROR_IF_MSG(!(wil::verify_bool(condition)), fmt, __VA_ARGS__)
#define RETURN_LAST_ERROR_IF_NULL_MSG(ptr, fmt, ...) \
do { \
if ((ptr) == nullptr) { \
__RETURN_GLE_MSG_FAIL(#ptr, fmt, __VA_ARGS__); \
} \
} while (0, 0)
#define RETURN_IF_NTSTATUS_FAILED_MSG(status, fmt, ...) \
do { \
NTSTATUS __statusRet = (status); \
if (FAILED_NTSTATUS(__statusRet)) { \
__RETURN_NTSTATUS_MSG_FAIL(__statusRet, #status, fmt, __VA_ARGS__); \
} \
} while (0, 0)
// Conditionally returns failures (HRESULT) - use for failures that are expected in common use - failures are not logged - macros are only
// for control flow pattern
#define RETURN_IF_FAILED_EXPECTED(hr) \
do { \
auto __hrRet = wil::verify_hresult(hr); \
if (FAILED(__hrRet)) { \
return __hrRet; \
} \
} while (0, 0)
#define RETURN_IF_WIN32_BOOL_FALSE_EXPECTED(win32BOOL) \
do { \
if (!wil::verify_BOOL(win32BOOL)) { \
return wil::details::GetLastErrorFailHr(); \
} \
} while (0, 0)
#define RETURN_IF_WIN32_ERROR_EXPECTED(win32err) \
do { \
auto __errRet = (win32err); \
if (FAILED_WIN32(__errRet)) { \
return HRESULT_FROM_WIN32(__errRet); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_INVALID_EXPECTED(handle) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == INVALID_HANDLE_VALUE) { \
return wil::details::GetLastErrorFailHr(); \
} \
} while (0, 0)
#define RETURN_IF_HANDLE_NULL_EXPECTED(handle) \
do { \
HANDLE __hRet = (handle); \
if (__hRet == nullptr) { \
return wil::details::GetLastErrorFailHr(); \
} \
} while (0, 0)
#define RETURN_IF_NULL_ALLOC_EXPECTED(ptr) \
do { \
if ((ptr) == nullptr) { \
return E_OUTOFMEMORY; \
} \
} while (0, 0)
#define RETURN_HR_IF_EXPECTED(hr, condition) \
do { \
if (wil::verify_bool(condition)) { \
return wil::verify_hresult(hr); \
} \
} while (0, 0)
#define RETURN_HR_IF_FALSE_EXPECTED(hr, condition) RETURN_HR_IF_EXPECTED(hr, !(wil::verify_bool(condition)))
#define RETURN_HR_IF_NULL_EXPECTED(hr, ptr) \
do { \
if ((ptr) == nullptr) { \
return wil::verify_hresult(hr); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF_EXPECTED(condition) \
do { \
if (wil::verify_bool(condition)) { \
return wil::details::GetLastErrorFailHr(); \
} \
} while (0, 0)
#define RETURN_LAST_ERROR_IF_FALSE_EXPECTED(condition) RETURN_LAST_ERROR_IF_EXPECTED(!(wil::verify_bool(condition)))
#define RETURN_LAST_ERROR_IF_NULL_EXPECTED(ptr) \
do { \
if ((ptr) == nullptr) { \
return wil::details::GetLastErrorFailHr(); \
} \
} while (0, 0)
#define RETURN_IF_NTSTATUS_FAILED_EXPECTED(status) \
do { \
auto __statusRet = (status); \
if (FAILED_NTSTATUS(__statusRet)) { \
return wil::details::NtStatusToHr(__statusRet); \
} \
} while (0, 0)
#define RETURN_NULL_IF_FAILED(hr) \
do { \
HRESULT __hrRet = wil::verify_hresult(hr); \
if (FAILED(__hrRet)) { \
__RETURN_NULL_FAIL(__hrRet, #hr); \
} \
} while (0, 0)
#define RETURN_NULL_IF_WIN32_BOOL_FALSE(win32BOOL) \
do { \
BOOL __boolRet = wil::verify_BOOL(win32BOOL); \
if (!__boolRet) { \
__RETURN_NULL_GLE_FAIL(#win32BOOL); \
} \
} while (0, 0)
#define RETURN_NULL_IF_WIN32_ERROR(win32err) \
do { \
DWORD __errRet = (win32err); \
if (FAILED_WIN32(__errRet)) { \
__RETURN_NULL_WIN32_FAIL(win32err, #win32err); \
} \
} while (0, 0)
#define RETURN_NULL_IF(condition) \
do { \
if (wil::verify_bool(condition)) { \
__RETURN_NULL_FAIL(E_FAIL, #condition); \
} \
} while (0, 0)
#define RETURN_NULL_IF_FALSE(condition) RETURN_NULL_IF(!(wil::verify_bool(condition)))
#define RETURN_NULL_IF_NULL_ALLOC(ptr) \
do { \
if ((ptr) == nullptr) { \
wil::verify_hresult(E_OUTOFMEMORY); \
__RETURN_NULL_FAIL(E_OUTOFMEMORY, #ptr); \
} \
} while (0, 0)
#define RETURN_FALSE_IF(condition) \
do { \
if (condition) { \
return false; \
} \
} while (0, 0)
//*****************************************************************************
// Macros for logging failures (ignore or pass-through)
//*****************************************************************************
// Always logs a known failure
#define LOG_HR(hr) __R_FN(Log_Hr)(__R_INFO(#hr) wil::verify_hresult(hr))
#define LOG_LAST_ERROR() __R_FN(Log_GetLastError)(__R_INFO_ONLY(nullptr))
#define LOG_WIN32(win32err) __R_FN(Log_Win32)(__R_INFO(#win32err) win32err)
#define LOG_NTSTATUS(status) __R_FN(Log_NtStatus)(__R_INFO(#status) status)
// Conditionally logs failures - returns parameter value
#define LOG_IF_FAILED(hr) __R_FN(Log_IfFailed)(__R_INFO(#hr) wil::verify_hresult(hr))
#define LOG_IF_WIN32_BOOL_FALSE(win32BOOL) __R_FN(Log_IfWin32BoolFalse)(__R_INFO(#win32BOOL) wil::verify_BOOL(win32BOOL))
#define LOG_IF_WIN32_ERROR(win32err) __R_FN(Log_IfWin32Error)(__R_INFO(#win32err) win32err)
#define LOG_IF_HANDLE_INVALID(handle) __R_FN(Log_IfHandleInvalid)(__R_INFO(#handle) handle)
#define LOG_IF_HANDLE_NULL(handle) __R_FN(Log_IfHandleNull)(__R_INFO(#handle) handle)
#define LOG_IF_NULL_ALLOC(ptr) __R_FN(Log_IfNullAlloc)(__R_INFO(#ptr) ptr)
#define LOG_HR_IF(hr, condition) __R_FN(Log_HrIf)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define LOG_HR_IF_FALSE(hr, condition) __R_FN(Log_HrIfFalse)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define LOG_HR_IF_NULL(hr, ptr) __R_FN(Log_HrIfNull)(__R_INFO(#ptr) wil::verify_hresult(hr), ptr)
#define LOG_LAST_ERROR_IF(condition) __R_FN(Log_GetLastErrorIf)(__R_INFO(#condition) wil::verify_bool(condition))
#define LOG_LAST_ERROR_IF_FALSE(condition) __R_FN(Log_GetLastErrorIfFalse)(__R_INFO(#condition) wil::verify_bool(condition))
#define LOG_LAST_ERROR_IF_NULL(ptr) __R_FN(Log_GetLastErrorIfNull)(__R_INFO(#ptr) ptr)
#define LOG_IF_NTSTATUS_FAILED(status) __R_FN(Log_IfNtStatusFailed)(__R_INFO(#status) status)
// Alternatives for SUCCEEDED(hr) and FAILED(hr) that conditionally log failures
#define SUCCEEDED_LOG(hr) SUCCEEDED(LOG_IF_FAILED(hr))
#define FAILED_LOG(hr) FAILED(LOG_IF_FAILED(hr))
// Always logs a known failure - logs a var-arg message on failure
#define LOG_HR_MSG(hr, fmt, ...) __R_FN(Log_HrMsg)(__R_INFO(#hr) wil::verify_hresult(hr), fmt, __VA_ARGS__)
#define LOG_LAST_ERROR_MSG(fmt, ...) __R_FN(Log_GetLastErrorMsg)(__R_INFO(nullptr) fmt, __VA_ARGS__)
#define LOG_WIN32_MSG(win32err, fmt, ...) __R_FN(Log_Win32Msg)(__R_INFO(#win32err) win32err, fmt, __VA_ARGS__)
#define LOG_NTSTATUS_MSG(status, fmt, ...) __R_FN(Log_NtStatusMsg)(__R_INFO(#status) status, fmt, __VA_ARGS__)
// Conditionally logs failures - returns parameter value - logs a var-arg message on failure
#define LOG_IF_FAILED_MSG(hr, fmt, ...) __R_FN(Log_IfFailedMsg)(__R_INFO(#hr) wil::verify_hresult(hr), fmt, __VA_ARGS__)
#define LOG_IF_WIN32_BOOL_FALSE_MSG(win32BOOL, fmt, ...) \
__R_FN(Log_IfWin32BoolFalseMsg)(__R_INFO(#win32BOOL) wil::verify_BOOL(win32BOOL), fmt, __VA_ARGS__)
#define LOG_IF_WIN32_ERROR_MSG(win32err, fmt, ...) __R_FN(Log_IfWin32ErrorMsg)(__R_INFO(#win32err) win32err, fmt, __VA_ARGS__)
#define LOG_IF_HANDLE_INVALID_MSG(handle, fmt, ...) __R_FN(Log_IfHandleInvalidMsg)(__R_INFO(#handle) handle, fmt, __VA_ARGS__)
#define LOG_IF_HANDLE_NULL_MSG(handle, fmt, ...) __R_FN(Log_IfHandleNullMsg)(__R_INFO(#handle) handle, fmt, __VA_ARGS__)
#define LOG_IF_NULL_ALLOC_MSG(ptr, fmt, ...) __R_FN(Log_IfNullAllocMsg)(__R_INFO(#ptr) ptr, fmt, __VA_ARGS__)
#define LOG_HR_IF_MSG(hr, condition, fmt, ...) \
__R_FN(Log_HrIfMsg)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define LOG_HR_IF_FALSE_MSG(hr, condition, fmt, ...) \
__R_FN(Log_HrIfFalseMsg)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define LOG_HR_IF_NULL_MSG(hr, ptr, fmt, ...) __R_FN(Log_HrIfNullMsg)(__R_INFO(#ptr) wil::verify_hresult(hr), ptr, fmt, __VA_ARGS__)
#define LOG_LAST_ERROR_IF_MSG(condition, fmt, ...) \
__R_FN(Log_GetLastErrorIfMsg)(__R_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define LOG_LAST_ERROR_IF_FALSE_MSG(condition, fmt, ...) \
__R_FN(Log_GetLastErrorIfFalseMsg)(__R_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define LOG_LAST_ERROR_IF_NULL_MSG(ptr, fmt, ...) __R_FN(Log_GetLastErrorIfNullMsg)(__R_INFO(#ptr) ptr, fmt, __VA_ARGS__)
#define LOG_IF_NTSTATUS_FAILED_MSG(status, fmt, ...) __R_FN(Log_IfNtStatusFailedMsg)(__R_INFO(#status) status, fmt, __VA_ARGS__)
//*****************************************************************************
// Macros to fail fast the process on failures
//*****************************************************************************
// Always fail fast a known failure
#define FAIL_FAST_HR(hr) __RFF_FN(FailFast_Hr)(__RFF_INFO(#hr) wil::verify_hresult(hr))
#define FAIL_FAST_LAST_ERROR() __RFF_FN(FailFast_GetLastError)(__RFF_INFO_ONLY(nullptr))
#define FAIL_FAST_WIN32(win32err) __RFF_FN(FailFast_Win32)(__RFF_INFO(#win32err) win32err)
#define FAIL_FAST_NTSTATUS(status) __RFF_FN(FailFast_NtStatus)(__RFF_INFO(#status) status)
// Conditionally fail fast failures - returns parameter value
#define FAIL_FAST_IF_FAILED(hr) __RFF_FN(FailFast_IfFailed)(__RFF_INFO(#hr) wil::verify_hresult(hr))
#define FAIL_FAST_IF_WIN32_BOOL_FALSE(win32BOOL) __RFF_FN(FailFast_IfWin32BoolFalse)(__RFF_INFO(#win32BOOL) wil::verify_BOOL(win32BOOL))
#define FAIL_FAST_IF_WIN32_ERROR(win32err) __RFF_FN(FailFast_IfWin32Error)(__RFF_INFO(#win32err) win32err)
#define FAIL_FAST_IF_HANDLE_INVALID(handle) __RFF_FN(FailFast_IfHandleInvalid)(__RFF_INFO(#handle) handle)
#define FAIL_FAST_IF_HANDLE_NULL(handle) __RFF_FN(FailFast_IfHandleNull)(__RFF_INFO(#handle) handle)
#define FAIL_FAST_IF_NULL_ALLOC(ptr) __RFF_FN(FailFast_IfNullAlloc)(__RFF_INFO(#ptr) ptr)
#define FAIL_FAST_HR_IF(hr, condition) __RFF_FN(FailFast_HrIf)(__RFF_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define FAIL_FAST_HR_IF_FALSE(hr, condition) \
__RFF_FN(FailFast_HrIfFalse)(__RFF_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define FAIL_FAST_HR_IF_NULL(hr, ptr) __RFF_FN(FailFast_HrIfNull)(__RFF_INFO(#ptr) wil::verify_hresult(hr), ptr)
#define FAIL_FAST_LAST_ERROR_IF(condition) __RFF_FN(FailFast_GetLastErrorIf)(__RFF_INFO(#condition) wil::verify_bool(condition))
#define FAIL_FAST_LAST_ERROR_IF_FALSE(condition) __RFF_FN(FailFast_GetLastErrorIfFalse)(__RFF_INFO(#condition) wil::verify_bool(condition))
#define FAIL_FAST_LAST_ERROR_IF_NULL(ptr) __RFF_FN(FailFast_GetLastErrorIfNull)(__RFF_INFO(#ptr) ptr)
#define FAIL_FAST_IF_NTSTATUS_FAILED(status) __RFF_FN(FailFast_IfNtStatusFailed)(__RFF_INFO(#status) status)
// Always fail fast a known failure - fail fast a var-arg message on failure
#define FAIL_FAST_HR_MSG(hr, fmt, ...) __RFF_FN(FailFast_HrMsg)(__RFF_INFO(#hr) wil::verify_hresult(hr), fmt, __VA_ARGS__)
#define FAIL_FAST_LAST_ERROR_MSG(fmt, ...) __RFF_FN(FailFast_GetLastErrorMsg)(__RFF_INFO(nullptr) fmt, __VA_ARGS__)
#define FAIL_FAST_WIN32_MSG(win32err, fmt, ...) __RFF_FN(FailFast_Win32Msg)(__RFF_INFO(#win32err) win32err, fmt, __VA_ARGS__)
#define FAIL_FAST_NTSTATUS_MSG(status, fmt, ...) __RFF_FN(FailFast_NtStatusMsg)(__RFF_INFO(#status) status, fmt, __VA_ARGS__)
// Conditionally fail fast failures - returns parameter value - fail fast a var-arg message on failure
#define FAIL_FAST_IF_FAILED_MSG(hr, fmt, ...) __RFF_FN(FailFast_IfFailedMsg)(__RFF_INFO(#hr) wil::verify_hresult(hr), fmt, __VA_ARGS__)
#define FAIL_FAST_IF_WIN32_BOOL_FALSE_MSG(win32BOOL, fmt, ...) \
__RFF_FN(FailFast_IfWin32BoolFalseMsg)(__RFF_INFO(#win32BOOL) wil::verify_BOOL(win32BOOL), fmt, __VA_ARGS__)
#define FAIL_FAST_IF_WIN32_ERROR_MSG(win32err, fmt, ...) \
__RFF_FN(FailFast_IfWin32ErrorMsg)(__RFF_INFO(#win32err) win32err, fmt, __VA_ARGS__)
#define FAIL_FAST_IF_HANDLE_INVALID_MSG(handle, fmt, ...) \
__RFF_FN(FailFast_IfHandleInvalidMsg)(__RFF_INFO(#handle) handle, fmt, __VA_ARGS__)
#define FAIL_FAST_IF_HANDLE_NULL_MSG(handle, fmt, ...) __RFF_FN(FailFast_IfHandleNullMsg)(__RFF_INFO(#handle) handle, fmt, __VA_ARGS__)
#define FAIL_FAST_IF_NULL_ALLOC_MSG(ptr, fmt, ...) __RFF_FN(FailFast_IfNullAllocMsg)(__RFF_INFO(#ptr) ptr, fmt, __VA_ARGS__)
#define FAIL_FAST_HR_IF_MSG(hr, condition, fmt, ...) \
__RFF_FN(FailFast_HrIfMsg)(__RFF_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define FAIL_FAST_HR_IF_FALSE_MSG(hr, condition, fmt, ...) \
__RFF_FN(FailFast_HrIfFalseMsg)(__RFF_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define FAIL_FAST_HR_IF_NULL_MSG(hr, ptr, fmt, ...) \
__RFF_FN(FailFast_HrIfNullMsg)(__RFF_INFO(#ptr) wil::verify_hresult(hr), ptr, fmt, __VA_ARGS__)
#define FAIL_FAST_LAST_ERROR_IF_MSG(condition, fmt, ...) \
__RFF_FN(FailFast_GetLastErrorIfMsg)(__RFF_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define FAIL_FAST_LAST_ERROR_IF_FALSE_MSG(condition, fmt, ...) \
__RFF_FN(FailFast_GetLastErrorIfFalseMsg)(__RFF_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define FAIL_FAST_LAST_ERROR_IF_NULL_MSG(ptr, fmt, ...) __RFF_FN(FailFast_GetLastErrorIfNullMsg)(__RFF_INFO(#ptr) ptr, fmt, __VA_ARGS__)
#define FAIL_FAST_IF_NTSTATUS_FAILED_MSG(status, fmt, ...) \
__RFF_FN(FailFast_IfNtStatusFailedMsg)(__RFF_INFO(#status) status, fmt, __VA_ARGS__)
// Always fail fast a known failure
#ifndef FAIL_FAST
#define FAIL_FAST() __RFF_FN(FailFast_Unexpected)(__RFF_INFO_ONLY(nullptr))
#endif
// Conditionally fail fast failures - returns parameter value
#define FAIL_FAST_IF(condition) __RFF_FN(FailFast_If)(__RFF_INFO(#condition) wil::verify_bool(condition))
#define FAIL_FAST_IF_FALSE(condition) __RFF_FN(FailFast_IfFalse)(__RFF_INFO(#condition) wil::verify_bool(condition))
#define FAIL_FAST_IF_NULL(ptr) __RFF_FN(FailFast_IfNull)(__RFF_INFO(#ptr) ptr)
// Always fail fast a known failure - fail fast a var-arg message on failure
#define FAIL_FAST_MSG(fmt, ...) __RFF_FN(FailFast_UnexpectedMsg)(__RFF_INFO(nullptr) fmt, __VA_ARGS__)
// Conditionally fail fast failures - returns parameter value - fail fast a var-arg message on failure
#define FAIL_FAST_IF_MSG(condition, fmt, ...) __RFF_FN(FailFast_IfMsg)(__RFF_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define FAIL_FAST_IF_FALSE_MSG(condition, fmt, ...) \
__RFF_FN(FailFast_IfFalseMsg)(__RFF_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define FAIL_FAST_IF_NULL_MSG(ptr, fmt, ...) __RFF_FN(FailFast_IfNullMsg)(__RFF_INFO(#ptr) ptr, fmt, __VA_ARGS__)
// Immediate fail fast (no telemetry - use rarely / only when *already* in an undefined state)
#define FAIL_FAST_IMMEDIATE() __RFF_FN(FailFastImmediate_Unexpected)()
// Conditional immediate fail fast (no telemetry - use rarely / only when *already* in an undefined state)
#define FAIL_FAST_IMMEDIATE_IF_FAILED(hr) __RFF_FN(FailFastImmediate_IfFailed)(wil::verify_hresult(hr))
#define FAIL_FAST_IMMEDIATE_IF(condition) __RFF_FN(FailFastImmediate_If)(wil::verify_bool(condition))
#define FAIL_FAST_IMMEDIATE_IF_FALSE(condition) __RFF_FN(FailFastImmediate_IfFalse)(wil::verify_bool(condition))
#define FAIL_FAST_IMMEDIATE_IF_NULL(ptr) __RFF_FN(FailFastImmediate_IfNull)(ptr)
#define FAIL_FAST_IMMEDIATE_IF_NTSTATUS_FAILED(status) __RFF_FN(FailFastImmediate_IfNtStatusFailed)(status)
// Specializations
#define FAIL_FAST_IMMEDIATE_IF_IN_LOADER_CALLOUT() \
do { \
if (wil::details::g_pfnFailFastInLoaderCallout != nullptr) { \
wil::details::g_pfnFailFastInLoaderCallout(); \
} \
} while (0, 0)
//*****************************************************************************
// Macros to throw exceptions on failure
//*****************************************************************************
#ifdef WIL_ENABLE_EXCEPTIONS
// Always throw a known failure
#define THROW_HR(hr) __R_FN(Throw_Hr)(__R_INFO(#hr) wil::verify_hresult(hr))
#define THROW_LAST_ERROR() __R_FN(Throw_GetLastError)(__R_INFO_ONLY(nullptr))
#define THROW_WIN32(win32err) __R_FN(Throw_Win32)(__R_INFO(#win32err) win32err)
#define THROW_EXCEPTION(exception) wil::details::ReportFailure_CustomException(__R_INFO(#exception) exception)
#define THROW_NTSTATUS(status) __R_FN(Throw_NtStatus)(__R_INFO(#status) status)
// Conditionally throw failures - returns parameter value
#define THROW_IF_FAILED(hr) __R_FN(Throw_IfFailed)(__R_INFO(#hr) wil::verify_hresult(hr))
#define THROW_IF_WIN32_BOOL_FALSE(win32BOOL) __R_FN(Throw_IfWin32BoolFalse)(__R_INFO(#win32BOOL) wil::verify_BOOL(win32BOOL))
#define THROW_IF_WIN32_ERROR(win32err) __R_FN(Throw_IfWin32Error)(__R_INFO(#win32err) win32err)
#define THROW_IF_HANDLE_INVALID(handle) __R_FN(Throw_IfHandleInvalid)(__R_INFO(#handle) handle)
#define THROW_IF_HANDLE_NULL(handle) __R_FN(Throw_IfHandleNull)(__R_INFO(#handle) handle)
#define THROW_IF_NULL_ALLOC(ptr) __R_FN(Throw_IfNullAlloc)(__R_INFO(#ptr) ptr)
#define THROW_HR_IF(hr, condition) __R_FN(Throw_HrIf)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define THROW_HR_IF_FALSE(hr, condition) __R_FN(Throw_HrIfFalse)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define THROW_HR_IF_NULL(hr, ptr) __R_FN(Throw_HrIfNull)(__R_INFO(#ptr) wil::verify_hresult(hr), ptr)
#define THROW_LAST_ERROR_IF(condition) __R_FN(Throw_GetLastErrorIf)(__R_INFO(#condition) wil::verify_bool(condition))
#define THROW_LAST_ERROR_IF_FALSE(condition) __R_FN(Throw_GetLastErrorIfFalse)(__R_INFO(#condition) wil::verify_bool(condition))
#define THROW_LAST_ERROR_IF_NULL(ptr) __R_FN(Throw_GetLastErrorIfNull)(__R_INFO(#ptr) ptr)
#define THROW_IF_NTSTATUS_FAILED(status) __R_FN(Throw_IfNtStatusFailed)(__R_INFO(#status) status)
// Always throw a known failure - throw a var-arg message on failure
#define THROW_HR_MSG(hr, fmt, ...) __R_FN(Throw_HrMsg)(__R_INFO(#hr) wil::verify_hresult(hr), fmt, __VA_ARGS__)
#define THROW_LAST_ERROR_MSG(fmt, ...) __R_FN(Throw_GetLastErrorMsg)(__R_INFO(nullptr) fmt, __VA_ARGS__)
#define THROW_WIN32_MSG(win32err, fmt, ...) __R_FN(Throw_Win32Msg)(__R_INFO(#win32err) win32err, fmt, __VA_ARGS__)
#define THROW_EXCEPTION_MSG(exception, fmt, ...) \
wil::details::ReportFailure_CustomExceptionMsg(__R_INFO(#exception) exception, fmt, __VA_ARGS__)
#define THROW_NTSTATUS_MSG(status, fmt, ...) __R_FN(Throw_NtStatusMsg)(__R_INFO(#status) status, fmt, __VA_ARGS__)
// Conditionally throw failures - returns parameter value - throw a var-arg message on failure
#define THROW_IF_FAILED_MSG(hr, fmt, ...) __R_FN(Throw_IfFailedMsg)(__R_INFO(#hr) wil::verify_hresult(hr), fmt, __VA_ARGS__)
#define THROW_IF_WIN32_BOOL_FALSE_MSG(win32BOOL, fmt, ...) \
__R_FN(Throw_IfWin32BoolFalseMsg)(__R_INFO(#win32BOOL) wil::verify_BOOL(win32BOOL), fmt, __VA_ARGS__)
#define THROW_IF_WIN32_ERROR_MSG(win32err, fmt, ...) __R_FN(Throw_IfWin32ErrorMsg)(__R_INFO(#win32err) win32err, fmt, __VA_ARGS__)
#define THROW_IF_HANDLE_INVALID_MSG(handle, fmt, ...) __R_FN(Throw_IfHandleInvalidMsg)(__R_INFO(#handle) handle, fmt, __VA_ARGS__)
#define THROW_IF_HANDLE_NULL_MSG(handle, fmt, ...) __R_FN(Throw_IfHandleNullMsg)(__R_INFO(#handle) handle, fmt, __VA_ARGS__)
#define THROW_IF_NULL_ALLOC_MSG(ptr, fmt, ...) __R_FN(Throw_IfNullAllocMsg)(__R_INFO(#ptr) ptr, fmt, __VA_ARGS__)
#define THROW_HR_IF_MSG(hr, condition, fmt, ...) \
__R_FN(Throw_HrIfMsg)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define THROW_HR_IF_FALSE_MSG(hr, condition, fmt, ...) \
__R_FN(Throw_HrIfFalseMsg)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define THROW_HR_IF_NULL_MSG(hr, ptr, fmt, ...) __R_FN(Throw_HrIfNullMsg)(__R_INFO(#ptr) wil::verify_hresult(hr), ptr, fmt, __VA_ARGS__)
#define THROW_LAST_ERROR_IF_MSG(condition, fmt, ...) \
__R_FN(Throw_GetLastErrorIfMsg)(__R_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define THROW_LAST_ERROR_IF_FALSE_MSG(condition, fmt, ...) \
__R_FN(Throw_GetLastErrorIfFalseMsg)(__R_INFO(#condition) wil::verify_bool(condition), fmt, __VA_ARGS__)
#define THROW_LAST_ERROR_IF_NULL_MSG(ptr, fmt, ...) __R_FN(Throw_GetLastErrorIfNullMsg)(__R_INFO(#ptr) ptr, fmt, __VA_ARGS__)
#define THROW_IF_NTSTATUS_FAILED_MSG(status, fmt, ...) __R_FN(Throw_IfNtStatusFailedMsg)(__R_INFO(#status) status, fmt, __VA_ARGS__)
//*****************************************************************************
// Macros to catch and convert exceptions on failure
//*****************************************************************************
// Conditionally returns a known failure (HRESULT) (always place immediately after a try { } block)
#define CATCH_RETURN() \
catch (...) { \
__RETURN_HR_LOG_FAIL(wil::ResultFromCaughtException(), nullptr); \
}
#define CATCH_RETURN_MSG(fmt, ...) \
catch (...) { \
__RETURN_HR_MSG_FAIL(wil::ResultFromCaughtException(), nullptr, fmt, __VA_ARGS__); \
}
#define CATCH_RETURN_EXPECTED() \
catch (...) { \
return wil::ResultFromCaughtException(); \
}
// Conditionally logs a known failure (always place immediately after a try { } block)
#define CATCH_LOG() \
catch (...) { \
__R_FN(Log_Hr)(__R_INFO(nullptr) wil::ResultFromCaughtException()); \
}
#define CATCH_LOG_MSG(fmt, ...) \
catch (...) { \
__R_FN(Log_HrMsg)(__R_INFO(nullptr) wil::ResultFromCaughtException(), fmt, __VA_ARGS__); \
}
// Conditionally fail fast (always place immediately after a try { } block)
#define CATCH_FAIL_FAST() \
catch (...) { \
__R_FN(FailFast_Hr)(__R_INFO(nullptr) wil::ResultFromCaughtException()); \
}
#define CATCH_FAIL_FAST_MSG(fmt, ...) \
catch (...) { \
__R_FN(FailFast_HrMsg)(__R_INFO(nullptr) wil::ResultFromCaughtException(), fmt, __VA_ARGS__); \
}
// Conditionally normalize (rethrow) a caught exception to ResultException or NSException (always place immediately after a try { }
// block)
#define CATCH_THROW_NORMALIZED() \
catch (...) { \
wil::details::RethrowNormalizedCaughtException(__R_INFO_ONLY(nullptr)); \
}
#define CATCH_THROW_NORMALIZED_MSG(fmt, ...) \
catch (...) { \
wil::details::RethrowNormalizedCaughtExceptionMsg(__R_INFO(nullptr) fmt, __VA_ARGS__); \
}
#endif // WIL_ENABLE_EXCEPTIONS
//*****************************************************************************
// Assert Macros
//*****************************************************************************
#ifdef RESULT_DEBUG
#define WI_ASSERT(condition) \
(__WI_ANALYSIS_ASSUME(condition), \
((!(condition)) ? (__annotation(L"Debug", L"AssertFail", L#condition), DbgRaiseAssertionFailure(), false) : true))
#define WI_ASSERT_MSG(condition, msg) \
(__WI_ANALYSIS_ASSUME(condition), \
((!(condition)) ? (__annotation(L"Debug", L"AssertFail", L##msg), DbgRaiseAssertionFailure(), false) : true))
#define WI_ASSERT_NOASSUME WI_ASSERT
#define WI_ASSERT_MSG_NOASSUME WI_ASSERT_MSG
#define WI_VERIFY WI_ASSERT
#define WI_VERIFY_MSG WI_ASSERT_MSG
#else
#define WI_ASSERT(condition) (__WI_ANALYSIS_ASSUME(condition), 0)
#define WI_ASSERT_MSG(condition, msg) (__WI_ANALYSIS_ASSUME(condition), 0)
#define WI_ASSERT_NOASSUME(condition) ((void)0)
#define WI_ASSERT_MSG_NOASSUME(condition, msg) ((void)0)
#define WI_VERIFY(condition) (__WI_ANALYSIS_ASSUME(condition), ((condition) ? true : false))
#define WI_VERIFY_MSG(condition, msg) (__WI_ANALYSIS_ASSUME(condition), ((condition) ? true : false))
#endif // RESULT_DEBUG
//*****************************************************************************
// Usage Error Macros
//*****************************************************************************
#ifndef WI_USAGE_ASSERT
#define WI_USAGE_ASSERT(condition) WI_ASSERT(condition)
#endif
// #ifdef RESULT_DEBUG
// #define WI_USAGE_ERROR(msg, ...) do { LOG_HR_MSG(HRESULT_FROM_WIN32(ERROR_ASSERTION_FAILURE), msg,
// __VA_ARGS__); WI_USAGE_ASSERT(false); } while (0, 0)
// #define WI_USAGE_ERROR_FORWARD(msg, ...) do { ReportFailure_ReplaceMsg(__R_FN_CALL_FULL, FailureType::Log,
// HRESULT_FROM_WIN32(ERROR_ASSERTION_FAILURE), msg, __VA_ARGS__); WI_USAGE_ASSERT(false); } while (0, 0)
// #else
#define WI_USAGE_ERROR( \
msg, ...) // do { LOG_HR(HRESULT_FROM_WIN32(ERROR_ASSERTION_FAILURE)); WI_USAGE_ASSERT(false); } while (0, 0)
#define WI_USAGE_ERROR_FORWARD(msg, ...) // do { ReportFailure_Hr(__R_FN_CALL_FULL, FailureType::Log,
// HRESULT_FROM_WIN32(ERROR_ASSERTION_FAILURE)); WI_USAGE_ASSERT(false); } while
// (0, 0)
// #endif
#define WI_USAGE_VERIFY(condition, msg, ...) \
do { \
auto __passed = wil::verify_bool(condition); \
if (!__passed) { \
WI_USAGE_ERROR(msg, __VA_ARGS__); \
} \
} while (0, 0)
#define WI_USAGE_VERIFY_FORWARD(condition, msg, ...) \
do { \
auto __passed = wil::verify_bool(condition); \
if (!__passed) { \
WI_USAGE_ERROR_FORWARD(msg, __VA_ARGS__); \
} \
} while (0, 0)
// [deprecated] Old macros names -- to be removed -- do not use
#define RETURN_HR_IF_TRUE RETURN_HR_IF
#define RETURN_LAST_ERROR_IF_TRUE RETURN_LAST_ERROR_IF
#define RETURN_HR_IF_TRUE_LOG RETURN_HR_IF_LOG
#define RETURN_HR_IF_TRUE_MSG RETURN_HR_IF_MSG
#define RETURN_HR_IF_TRUE_EXPECTED RETURN_HR_IF_EXPECTED
#define LOG_HR_IF_TRUE LOG_HR_IF
#define LOG_HR_IF_TRUE_MSG LOG_HR_IF_MSG
#define LOG_LAST_ERROR_IF_TRUE LOG_LAST_ERROR_IF
#define FAIL_FAST_HR_IF_TRUE FAIL_FAST_HR_IF
#ifdef WIL_ENABLE_EXCEPTIONS
#define THROW_HR_IF_TRUE THROW_HR_IF
#define THROW_LAST_ERROR_IF_TRUE THROW_LAST_ERROR_IF
#define THROW_HR_IF_TRUE_MSG THROW_HR_IF_MSG
#endif // WIL_ENABLE_EXCEPTIONS
//*****************************************************************************
// Objective-C Error Macros
//*****************************************************************************
__declspec(selectany) bool (*g_resultFromUncaughtExceptionObjC)(HRESULT* out) = nullptr;
__declspec(selectany) void (*g_rethrowAsNSException)() = nullptr;
__declspec(selectany) void (*g_objcThrowFailureInfo)(const wil::FailureInfo& fi) = nullptr;
__declspec(selectany) void (*g_rethrowNormalizedCaughtExceptionObjC)(__R_FN_PARAMS_FULL, _In_opt_ PCWSTR message) = nullptr;
#define THROW_NS_HR(hr) __R_FN(Objc_Throw_HrMsg)(__R_INFO(#hr) wil::verify_hresult(hr), nullptr)
#define THROW_NS_HR_MSG(hr, msg, ...) __R_FN(Objc_Throw_HrMsg)(__R_INFO(#hr) wil::verify_hresult(hr), msg, __VA_ARGS__)
#define THROW_NS_IF_FAILED(hr) __R_FN(Objc_Throw_IfFailed)(__R_INFO(#hr) wil::verify_hresult(hr))
#define THROW_NS_IF_FAILED_MSG(hr, fmt, ...) __R_FN(Objc_Throw_IfFailedMsg)(__R_INFO(#hr) wil::verify_hresult(hr), fmt, __VA_ARGS__)
#define THROW_NS_IF(hr, condition) __R_FN(Objc_Throw_HrIf)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define THROW_NS_IF_FALSE(hr, condition) \
__R_FN(Objc_Throw_HrIfFalse)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition))
#define THROW_NS_IF_NULL(hr, ptr) __R_FN(Objc_Throw_HrIfNull)(__R_INFO(#ptr) wil::verify_hresult(hr), ptr)
#define THROW_NS_IF_MSG(hr, condition, fmt, ...) \
__R_FN(Objc_Throw_HrIfMsg)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define THROW_NS_IF_FALSE_MSG(hr, condition, fmt, ...) \
__R_FN(Objc_Throw_HrIfFalseMsg)(__R_INFO(#condition) wil::verify_hresult(hr), wil::verify_bool(condition), fmt, __VA_ARGS__)
#define THROW_NS_IF_NULL_MSG(hr, ptr, fmt, ...) \
__R_FN(Objc_Throw_HrIfNullMsg)(__R_INFO(#ptr) wil::verify_hresult(hr), ptr, fmt, __VA_ARGS__)
#define CATCH_THROW_NSEXCEPTION() \
catch (...) { \
_rethrowAsNSException(); \
}
#define CATCH_POPULATE_NSERROR(error) \
catch (...) { \
_catchAndPopulateNSError(error); \
}
namespace wil {
// Indicates the kind of message / failure type that was used to produce a given error
enum class FailureType {
Exception, // THROW_...
ObjCException, // THROW_NS_...
Return, // RETURN_..._LOG or RETURN_..._MSG
ReturnPreRelease, // RETURN_...
Log, // LOG_...
FailFast // FAIL_FAST_...
};
// Represents the call context information about a given failure
// No constructors, destructors or virtual members should be contained within
struct CallContextInfo {
long contextId; // incrementing ID for this call context (unique across an individual module load within process)
PCSTR contextName; // the explicit name given to this context
PCWSTR contextMessage; // [optional] Message that can be associated with the call context
};
inline void ClearContext(_Out_ CallContextInfo* pContext) WI_NOEXCEPT {
pContext->contextId = 0;
pContext->contextName = nullptr;
pContext->contextMessage = nullptr;
}
// Represents all context information about a given failure
// No constructors, destructors or virtual members should be contained within
struct FailureInfo {
FailureType type;
HRESULT hr;
long failureId; // incrementing ID for this specific failure (unique across an individual module load within process)
PCWSTR pszMessage; // Message is only present for _MSG logging (it's the Sprintf message)
DWORD threadId; // the thread this failure was originally encountered on
PCSTR pszCode; // [debug only] Capture code from the macro
PCSTR pszFunction; // [debug only] The function name
PCSTR pszFile;
unsigned int uLineNumber;
int cFailureCount; // How many failures of 'type' have been reported in this module so far
PCSTR pszCallContext; // General breakdown of the call context stack that generated this failure
CallContextInfo callContextOriginating; // The outermost (first seen) call context
CallContextInfo callContextCurrent; // The most recently seen call context
PCSTR pszModule; // The module where the failure originated
void* returnAddress; // The return address to the point that called the macro
void* callerReturnAddress; // The return address of the function that includes the macro
};
// [optionally] Plug in error logging
// Note: This callback is deprecated. Please use SetResultTelemetryFallback for telemetry or
// SetResultLoggingCallback for observation.
__declspec(selectany) void(__stdcall* g_pfnResultLoggingCallback)(_Inout_ wil::FailureInfo* pFailure,
_Inout_updates_opt_z_(cchDebugMessage) PWSTR pszDebugMessage,
_Pre_satisfies_(cchDebugMessage > 0)
size_t cchDebugMessage) WI_NOEXCEPT = nullptr;
// [optional]
// This can be explicitly set to control whether or not error messages will be output to OutputDebugString. It can also
// be set directly from within the debugger to force console logging for debugging purposes.
#if (defined(DBG) || defined(_DEBUG))
__declspec(selectany) bool g_fResultOutputDebugString = true;
#else
__declspec(selectany) bool g_fResultOutputDebugString = false;
#endif
// [optionally] Plug in additional exception-type support (return S_OK when *unable* to remap the exception)
__declspec(selectany) HRESULT(__stdcall* g_pfnResultFromCaughtException)() WI_NOEXCEPT = nullptr;
// [optionally] Use to configure fast fail of unknown exceptions (turn them off).
__declspec(selectany) bool g_fResultFailFastUnknownExceptions = true;
//! @cond
namespace details {
_Success_(true) _Ret_range_(dest, destEnd) inline PWSTR LogStringPrintf(_Out_writes_to_ptr_(destEnd) _Always_(_Post_z_) PWSTR dest,
_Pre_satisfies_(destEnd >= dest) PCWSTR destEnd,
_In_ _Printf_format_string_ PCWSTR format,
...) {
va_list argList;
va_start(argList, format);
StringCchVPrintfW(dest, (destEnd - dest), format, argList);
return (destEnd == dest) ? dest : (dest + wcslen(dest));
}
}
//! @endcond
// This call generates the default logging string that makes its way to OutputDebugString for
// any particular failure. This string is also used to associate a failure with a PlatformException^ which
// only allows a single string to be associated with the exception.
inline HRESULT GetFailureLogString(_Out_writes_(cchDest) _Always_(_Post_z_) PWSTR pszDest,
_Pre_satisfies_(cchDest > 0) _In_ size_t cchDest,
_In_ FailureInfo const& failure) WI_NOEXCEPT {
PCSTR pszType = "";
switch (failure.type) {
case FailureType::Exception:
pszType = "Exception";
break;
case FailureType::ObjCException:
pszType = "Objective-C Exception";
break;
case FailureType::Return:
pszType = "ReturnHr";
break;
case FailureType::ReturnPreRelease:
pszType = "ReturnHr[PreRelease]";
break;
case FailureType::Log:
pszType = "LogHr";
break;
case FailureType::FailFast:
pszType = "FailFast";
break;
}
wchar_t szErrorText[256];
szErrorText[0] = L'\0';
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
failure.hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
szErrorText,
ARRAYSIZE(szErrorText),
nullptr);
// %FILENAME(%LINE): %TYPE(%count) tid(%threadid) %HRESULT %SystemMessage
// %Caller_MSG [%CODE(%FUNCTION)]
PWSTR dest = pszDest;
PCWSTR destEnd = (pszDest + cchDest);
if (failure.pszFile != nullptr) {
dest = details::LogStringPrintf(
dest, destEnd, L"%hs(%d)\\%hs!%p: ", failure.pszFile, failure.uLineNumber, failure.pszModule, failure.returnAddress);
} else {
dest = details::LogStringPrintf(dest, destEnd, L"%hs!%p: ", failure.pszModule, failure.returnAddress);
}
if (failure.callerReturnAddress != nullptr) {
dest = details::LogStringPrintf(dest, destEnd, L"(caller: %p) ", failure.callerReturnAddress);
}
dest = details::LogStringPrintf(
dest, destEnd, L"%hs(%d) tid(%x) %08X %ws", pszType, failure.cFailureCount, ::GetCurrentThreadId(), failure.hr, szErrorText);
if ((failure.pszMessage != nullptr) || (failure.pszCallContext != nullptr) || (failure.pszFunction != nullptr)) {
dest = details::LogStringPrintf(dest, destEnd, L" ");
if (failure.pszMessage != nullptr) {
dest = details::LogStringPrintf(dest, destEnd, L"Msg:[%ws] ", failure.pszMessage);
}
if (failure.pszCallContext != nullptr) {
dest = details::LogStringPrintf(dest, destEnd, L"CallContext:[%hs] ", failure.pszCallContext);
}
if (failure.pszCode != nullptr) {
dest = details::LogStringPrintf(dest, destEnd, L"[%hs(%hs)]\n", failure.pszFunction, failure.pszCode);
} else if (failure.pszFunction != nullptr) {
dest = details::LogStringPrintf(dest, destEnd, L"[%hs]\n", failure.pszFunction);
} else {
dest = details::LogStringPrintf(dest, destEnd, L"\n");
}
}
// Explicitly choosing to return success in the event of truncation... Current callers
// depend upon it or it would be eliminated.
return S_OK;
}
//! @cond
namespace details {
#ifdef WIL_SUPPRESS_PRIVATE_API_USE
#pragma detect_mismatch("ODR_violation_WIL_SUPPRESS_PRIVATE_API_USE_mismatch", "1")
#else
#pragma detect_mismatch("ODR_violation_WIL_SUPPRESS_PRIVATE_API_USE_mismatch", "0")
#endif
#ifdef RESULT_PRERELEASE
#pragma detect_mismatch("ODR_violation_WIL_RESULT_PRERELEASE_mismatch", "1")
#else
#pragma detect_mismatch("ODR_violation_WIL_RESULT_PRERELEASE_mismatch", "0")
#endif
// Fallback telemetry provider callback (set with wil::SetResultTelemetryFallback)
__declspec(selectany) void(__stdcall* g_pfnTelemetryCallback)(bool alreadyReported, wil::FailureInfo const& failure) WI_NOEXCEPT = nullptr;
// Observe all errors flowing through the system with this callback (set with wil::SetResultLoggingCallback); use with custom logging
// WIL logging callback; exported from our logging binary so the same instance is shared across all of our modules in a given process.
WIL_EXPORT void(__stdcall* g_pfnLoggingCallback)(wil::FailureInfo const& failure) WI_NOEXCEPT;
// True if g_pfnResultLoggingCallback is set (allows cutting off backwards compat calls to the function)
__declspec(selectany) bool g_resultMessageCallbackSet = false;
// Desktop Only: Module fetch function (automatically setup)
__declspec(selectany) PCSTR(__stdcall* g_pfnGetModuleName)() WI_NOEXCEPT = nullptr;
// Desktop Only: Private module load fail fast function (automatically setup)
__declspec(selectany) void(__stdcall* g_pfnFailFastInLoaderCallout)() WI_NOEXCEPT = nullptr;
// Desktop Only: Private module load convert NtStatus to HResult (automatically setup)
__declspec(selectany) ULONG(__stdcall* g_pfnRtlNtStatusToDosErrorNoTeb)(NTSTATUS) = nullptr;
enum class ReportFailureOptions { None = 0x00, ForceObjCException = 0x01, SuppressAction = 0x02 };
DEFINE_ENUM_FLAG_OPERATORS(ReportFailureOptions);
// Forward declarations to enable use of fail fast and reporting internally...
namespace __R_NS_NAME {
__R_DIRECT_METHOD(HRESULT, Log_Hr)(__R_DIRECT_FN_PARAMS HRESULT hr) WI_NOEXCEPT;
__R_DIRECT_METHOD(HRESULT, Log_HrMsg)(__R_DIRECT_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT;
__R_DIRECT_METHOD(DWORD, Log_Win32Msg)(__R_DIRECT_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT;
}
namespace __RFF_NS_NAME {
__RFF_DIRECT_NORET_METHOD(void, FailFast_Unexpected)(__RFF_DIRECT_FN_PARAMS_ONLY) WI_NOEXCEPT;
__RFF_CONDITIONAL_METHOD(bool, FailFast_If)(__RFF_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT;
__RFF_CONDITIONAL_METHOD(bool, FailFast_HrIf)(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) WI_NOEXCEPT;
__RFF_CONDITIONAL_METHOD(bool, FailFast_IfFalse)(__RFF_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT;
}
__declspec(noinline) inline void ReportFailure(__R_FN_PARAMS_FULL,
FailureType type,
HRESULT hr,
_In_opt_ PCWSTR message = nullptr,
ReportFailureOptions options = ReportFailureOptions::None);
inline void ReportFailure_ReplaceMsg(__R_FN_PARAMS_FULL, FailureType type, HRESULT hr, _Printf_format_string_ PCSTR formatString, ...);
__declspec(noinline) inline void ReportFailure_Hr(__R_FN_PARAMS_FULL, FailureType type, HRESULT hr);
_Always_(_Post_satisfies_(return < 0)) inline HRESULT ResultFromUnknownCaughtException();
// A simple ref-counted buffer class. The interface is very similar to shared_ptr<>, only it manages
// an allocated buffer (malloc) and maintains the size.
class shared_buffer {
public:
shared_buffer() WI_NOEXCEPT : m_pCopy(nullptr), m_size(0) {
}
shared_buffer(shared_buffer const& other) WI_NOEXCEPT : m_pCopy(nullptr), m_size(0) {
assign(other.m_pCopy, other.m_size);
}
shared_buffer(shared_buffer&& other) WI_NOEXCEPT : m_pCopy(other.m_pCopy), m_size(other.m_size) {
other.m_pCopy = nullptr;
other.m_size = 0;
}
~shared_buffer() WI_NOEXCEPT {
reset();
}
shared_buffer& operator=(shared_buffer const& other) WI_NOEXCEPT {
assign(other.m_pCopy, other.m_size);
return *this;
}
shared_buffer& operator=(shared_buffer&& other) WI_NOEXCEPT {
reset();
m_pCopy = other.m_pCopy;
m_size = other.m_size;
other.m_pCopy = nullptr;
other.m_size = 0;
return *this;
}
void reset() WI_NOEXCEPT {
if (m_pCopy != nullptr) {
if (0 == ::InterlockedDecrementRelease(m_pCopy)) {
::IwFree(m_pCopy);
}
m_pCopy = nullptr;
m_size = 0;
}
}
bool create(_In_reads_bytes_opt_(cbData) void const* pData, size_t cbData) WI_NOEXCEPT {
if (cbData == 0) {
reset();
return true;
}
long* pCopyRefCount = reinterpret_cast<long*>(::IwMalloc(sizeof(long) + cbData));
if (pCopyRefCount == nullptr) {
return false;
}
*pCopyRefCount = 0;
if (pData != nullptr) {
CopyMemory(pCopyRefCount + 1, pData, cbData); // +1 to advance past sizeof(long) counter
}
assign(pCopyRefCount, cbData);
return true;
}
bool create(size_t cbData) WI_NOEXCEPT {
return create(nullptr, cbData);
}
void* get(_Out_opt_ size_t* pSize = nullptr) const WI_NOEXCEPT {
if (pSize != nullptr) {
*pSize = m_size;
}
return (m_pCopy == nullptr) ? nullptr : (m_pCopy + 1);
}
size_t size() const WI_NOEXCEPT {
return m_size;
}
explicit operator bool() const WI_NOEXCEPT {
return (m_pCopy != nullptr);
}
bool unique() const WI_NOEXCEPT {
return ((m_pCopy != nullptr) && (*m_pCopy == 1));
}
private:
long* m_pCopy; // pointer to allocation: refcount + data
size_t m_size; // size of the data from m_pCopy
void assign(_In_opt_ long* pCopy, size_t cbSize) WI_NOEXCEPT {
reset();
if (pCopy != nullptr) {
m_pCopy = pCopy;
m_size = cbSize;
::InterlockedIncrementNoFence(m_pCopy);
}
}
};
inline shared_buffer make_shared_buffer_nothrow(_In_reads_bytes_opt_(countBytes) void* pData, size_t countBytes) WI_NOEXCEPT {
shared_buffer buffer;
buffer.create(pData, countBytes);
return buffer;
}
inline shared_buffer make_shared_buffer_nothrow(size_t countBytes) WI_NOEXCEPT {
shared_buffer buffer;
buffer.create(countBytes);
return buffer;
}
// A small mimic of the STL shared_ptr class, but unlike shared_ptr, a pointer is not attached to the class, but is
// always simply contained within (it cannot be attached or detached).
template <typename object_t>
class shared_object {
public:
shared_object() WI_NOEXCEPT : m_pCopy(nullptr) {
}
shared_object(shared_object const& other) WI_NOEXCEPT : m_pCopy(other.m_pCopy) {
if (m_pCopy != nullptr) {
::InterlockedIncrementNoFence(&m_pCopy->m_refCount);
}
}
shared_object(shared_object&& other) WI_NOEXCEPT : m_pCopy(other.m_pCopy) {
other.m_pCopy = nullptr;
}
~shared_object() WI_NOEXCEPT {
reset();
}
shared_object& operator=(shared_object const& other) WI_NOEXCEPT {
reset();
m_pCopy = other.m_pCopy;
if (m_pCopy != nullptr) {
::InterlockedIncrementNoFence(&m_pCopy->m_refCount);
}
return *this;
}
shared_object& operator=(shared_object&& other) WI_NOEXCEPT {
reset();
m_pCopy = other.m_pCopy;
other.m_pCopy = nullptr;
return *this;
}
void reset() WI_NOEXCEPT {
if (m_pCopy != nullptr) {
if (0 == ::InterlockedDecrementRelease(&m_pCopy->m_refCount)) {
delete m_pCopy;
}
m_pCopy = nullptr;
}
}
bool create() {
RefAndObject* pObject = new (std::nothrow) RefAndObject();
if (pObject == nullptr) {
return false;
}
reset();
m_pCopy = pObject;
return true;
}
template <typename param_t>
bool create(param_t&& param1) {
RefAndObject* pObject = new (std::nothrow) RefAndObject(wistd::forward<param_t>(param1));
if (pObject == nullptr) {
return false;
}
reset();
m_pCopy = pObject;
return true;
}
object_t* get() const WI_NOEXCEPT {
return (m_pCopy == nullptr) ? nullptr : &m_pCopy->m_object;
}
explicit operator bool() const WI_NOEXCEPT {
return (m_pCopy != nullptr);
}
bool unique() const WI_NOEXCEPT {
return ((m_pCopy != nullptr) && (m_pCopy->m_refCount == 1));
}
object_t* operator->() const WI_NOEXCEPT {
return get();
}
private:
struct RefAndObject {
long m_refCount;
object_t m_object;
RefAndObject() : m_refCount(1), m_object() {
}
template <typename param_t>
RefAndObject(param_t&& param1)
: m_refCount(1), m_object(wistd::forward<param_t>(param1)) {
}
};
RefAndObject* m_pCopy;
};
template <typename object_t>
inline shared_object<object_t> make_shared_object_nothrow() {
shared_object<object_t> object;
object.create();
return object;
}
// Note that this should eventually be switched to variadic template forwarding, but cannot be at the moment due
// to the use of this from Result.h and it's dependence upon an older compiler for the phone build
template <typename object_t, typename param_t>
inline shared_object<object_t> make_shared_object_nothrow(param_t&& param1) {
shared_object<object_t> object;
object.create(wistd::forward<param_t>(param1));
return object;
}
// The following functions are basically the same, but are kept separated to:
// 1) Provide a unique count and last error code per-type
// 2) Avoid merging the types to allow easy debugging (breakpoints, conditional breakpoints based
// upon count of errors from a particular type, etc)
__declspec(noinline) inline int RecordException(HRESULT hr) WI_NOEXCEPT {
static HRESULT volatile s_hrErrorLast = S_OK;
static long volatile s_cErrorCount = 0;
s_hrErrorLast = hr;
return ::InterlockedIncrementNoFence(&s_cErrorCount);
}
__declspec(noinline) inline int RecordReturn(HRESULT hr) WI_NOEXCEPT {
static HRESULT volatile s_hrErrorLast = S_OK;
static long volatile s_cErrorCount = 0;
s_hrErrorLast = hr;
return ::InterlockedIncrementNoFence(&s_cErrorCount);
}
__declspec(noinline) inline int RecordReturnPreRelease(HRESULT hr) WI_NOEXCEPT {
static HRESULT volatile s_hrErrorLast = S_OK;
static long volatile s_cErrorCount = 0;
s_hrErrorLast = hr;
return ::InterlockedIncrementNoFence(&s_cErrorCount);
}
__declspec(noinline) inline int RecordLog(HRESULT hr) WI_NOEXCEPT {
static HRESULT volatile s_hrErrorLast = S_OK;
static long volatile s_cErrorCount = 0;
s_hrErrorLast = hr;
return ::InterlockedIncrementNoFence(&s_cErrorCount);
}
__declspec(noinline) inline int RecordFailFast(HRESULT hr) WI_NOEXCEPT {
static HRESULT volatile s_hrErrorLast = S_OK;
s_hrErrorLast = hr;
return 1;
}
__declspec(noinline) inline HRESULT NtStatusToHr(NTSTATUS status) {
// The following conversions are the only known incorrect mappings in RtlNtStatusToDosErrorNoTeb
if (SUCCEEDED_NTSTATUS(status)) {
// All successful status codes have only one hresult equivalent, S_OK
return S_OK;
}
if (status == STATUS_NO_MEMORY) {
// RtlNtStatusToDosErrorNoTeb maps STATUS_NO_MEMORY to the less popular of two Win32 no memory error codes resulting in an
// unexpected mapping
return E_OUTOFMEMORY;
}
if (g_pfnRtlNtStatusToDosErrorNoTeb != nullptr) {
DWORD err = g_pfnRtlNtStatusToDosErrorNoTeb(status);
if (err != 0) {
return HRESULT_FROM_WIN32(err);
}
}
return HRESULT_FROM_NT(status);
}
// The following set of functions all differ only based upon number of arguments. They are unified in their handling
// of data from each of the various error-handling types (fast fail, exceptions, etc.).
inline DWORD GetLastErrorFail(__R_FN_PARAMS_FULL) WI_NOEXCEPT {
__R_FN_UNREFERENCED;
auto err = ::GetLastError();
if (SUCCEEDED_WIN32(err)) {
// This function should only be called when GetLastError() is set to a FAILURE.
// If you hit this assert (or are reviewing this failure telemetry), then there are one of three issues:
// 1) Your code is using a macro (such as RETURN_IF_WIN32_BOOL_FALSE()) on a function that does not actually
// set the last error (consult MSDN).
// 2) Your macro check against the error is not immediately after the API call. Pushing it later can result
// in another API call between the previous one and the check resetting the last error.
// 3) The API you're calling has a bug in it and does not accurately set the last error (there are a few
// examples here, such as SendMessageTimeout() that don't accurately set the last error). For these,
// please send mail to 'wildisc' when found and work-around with win32errorhelpers.
WI_USAGE_ERROR_FORWARD("CALLER BUG: Macro usage error detected. GetLastError() does not have an error.");
return ERROR_ASSERTION_FAILURE;
}
return err;
}
inline HRESULT GetLastErrorFailHr(__R_FN_PARAMS_FULL) WI_NOEXCEPT {
return HRESULT_FROM_WIN32(GetLastErrorFail(__R_FN_CALL_FULL));
}
inline __declspec(noinline) HRESULT GetLastErrorFailHr() WI_NOEXCEPT {
__R_FN_LOCALS_FULL_RA;
return GetLastErrorFailHr(__R_FN_CALL_FULL);
}
inline void PrintLoggingMessage(_Out_writes_(cchDest) _Post_z_ PWSTR pszDest,
_Pre_satisfies_(cchDest > 0) size_t cchDest,
_In_opt_ _Printf_format_string_ PCSTR formatString,
_In_ va_list argList) WI_NOEXCEPT {
if (formatString == nullptr) {
pszDest[0] = L'\0';
} else {
wchar_t szFormatWide[2048];
StringCchPrintfW(szFormatWide, ARRAYSIZE(szFormatWide), L"%hs", formatString);
StringCchVPrintfW(pszDest, cchDest, szFormatWide, argList);
}
}
#pragma warning(push)
#pragma warning(disable : __WARNING_RETURNING_BAD_RESULT)
// NOTE: The following two functions are unfortunate copies of strsafe.h functions that have been copied to reduce the friction associated
// with using
// Result.h and ResultException.h in a build that does not have WINAPI_PARTITION_DESKTOP defined (where these are conditionally enabled).
STRSAFEWORKERAPI WilStringLengthWorkerA(_In_reads_or_z_(cchMax) STRSAFE_PCNZCH psz,
_In_ _In_range_(<=, STRSAFE_MAX_CCH) size_t cchMax,
_Out_opt_ _Deref_out_range_(<, cchMax) _Deref_out_range_(<=, _String_length_(psz))
size_t* pcchLength) {
HRESULT hr = S_OK;
size_t cchOriginalMax = cchMax;
while (cchMax && (*psz != '\0')) {
psz++;
cchMax--;
}
if (cchMax == 0) {
// the string is longer than cchMax
hr = STRSAFE_E_INVALID_PARAMETER;
}
if (pcchLength) {
if (SUCCEEDED(hr)) {
*pcchLength = cchOriginalMax - cchMax;
} else {
*pcchLength = 0;
}
}
return hr;
}
_Must_inspect_result_ STRSAFEAPI StringCchLengthA(_In_reads_or_z_(cchMax) STRSAFE_PCNZCH psz,
_In_ _In_range_(1, STRSAFE_MAX_CCH) size_t cchMax,
_Out_opt_ _Deref_out_range_(<, cchMax) _Deref_out_range_(<=, _String_length_(psz))
size_t* pcchLength) {
HRESULT hr;
if ((psz == NULL) || (cchMax > STRSAFE_MAX_CCH)) {
hr = STRSAFE_E_INVALID_PARAMETER;
} else {
hr = WilStringLengthWorkerA(psz, cchMax, pcchLength);
}
if (FAILED(hr) && pcchLength) {
*pcchLength = 0;
}
return hr;
}
#pragma warning(pop)
_Ret_range_(sizeof(char), (psz == nullptr) ? sizeof(char) : (_String_length_(psz) + sizeof(char))) inline size_t
ResultStringSize(_In_opt_ PCSTR psz) {
return (psz == nullptr) ? sizeof(char) : (strlen(psz) + sizeof(char));
}
_Ret_range_(sizeof(wchar_t), (psz == nullptr) ? sizeof(wchar_t) : ((_String_length_(psz) + 1) * sizeof(wchar_t))) inline size_t
ResultStringSize(_In_opt_ PCWSTR psz) {
return (psz == nullptr) ? sizeof(wchar_t) : (wcslen(psz) + 1) * sizeof(wchar_t);
}
template <typename TString>
_Ret_range_(pStart, pEnd) inline unsigned char* WriteResultString(_Out_writes_to_ptr_opt_(pEnd) unsigned char* pStart,
_In_opt_ unsigned char* pEnd,
_In_opt_ TString pszString,
_Out_opt_ TString* ppszBufferString = nullptr) {
decltype(pszString[0]) const cZero = 0;
TString const pszLocal = (pszString == nullptr) ? &cZero : pszString;
__analysis_assume(pszLocal != nullptr); // VS2015.RC CA tools don't understand that pszLocal is forcibly non-null due top
size_t const cchWant = ResultStringSize(pszLocal) / sizeof(cZero);
size_t const cchMax = static_cast<size_t>(pEnd - pStart) / sizeof(cZero);
size_t const cchCopy = (cchWant < cchMax) ? cchWant : cchMax;
::CopyMemory(pStart, pszLocal, cchCopy * sizeof(cZero));
wil::AssignToOptParam(ppszBufferString, (cchCopy > 1) ? reinterpret_cast<TString>(pStart) : nullptr);
if ((cchCopy < cchWant) && (cchCopy > 0)) {
auto pZero = pStart + ((cchCopy - 1) * sizeof(cZero));
::ZeroMemory(pZero, sizeof(cZero));
}
#pragma warning(suppress : 28196) // Filed OSG bug 3026886 to address.
return (pStart + (cchCopy * sizeof(cZero)));
}
_Ret_range_(0, (cchMax > 0) ? cchMax - 1 : 0) inline size_t UntrustedStringLength(_In_ PCSTR psz, _In_ size_t cchMax) {
size_t cbLength;
return SUCCEEDED(wil::details::StringCchLengthA(psz, cchMax, &cbLength)) ? cbLength : 0;
}
_Ret_range_(0, (cchMax > 0) ? cchMax - 1 : 0) inline size_t UntrustedStringLength(_In_ PCWSTR psz, _In_ size_t cchMax) {
size_t cbLength;
return SUCCEEDED(::StringCchLengthW(psz, cchMax, &cbLength)) ? cbLength : 0;
}
template <typename TString>
_Ret_range_(pStart, pEnd) inline unsigned char* GetResultString(_In_reads_to_ptr_opt_(pEnd) unsigned char* pStart,
_In_opt_ unsigned char* pEnd,
_Out_ TString* ppszBufferString) {
size_t cchLen = UntrustedStringLength(reinterpret_cast<TString>(pStart), (pEnd - pStart) / sizeof((*ppszBufferString)[0]));
*ppszBufferString = (cchLen > 0) ? reinterpret_cast<TString>(pStart) : nullptr;
auto pReturn = min(pEnd, pStart + ((cchLen + 1) * sizeof((*ppszBufferString)[0])));
__analysis_assume((pReturn >= pStart) && (pReturn <= pEnd));
return pReturn;
}
// A small, no-dependency class meant to enable accessing lock-free thread local storage (roughly
// modeled after ppl::Combinable<>). This is used to service thread-specific failure callbacks
// without requiring any locking when an error is fired.
// Note that *for now*, T must be POD and is ZERO'inited and will not have a constructor/destructor
// ran on it (easy to add, but code including this file does not enable/include placement new.
template <typename T, size_t threadCountEstimate = 20>
class ThreadStorage {
public:
ThreadStorage() WI_NOEXCEPT {
::ZeroMemory(const_cast<Node**>(m_hashArray), sizeof(m_hashArray));
}
~ThreadStorage() WI_NOEXCEPT {
for (auto& entry : m_hashArray) {
Node* pNode = entry;
while (pNode != nullptr) {
auto pCurrent = pNode;
pNode = pNode->pNext;
pCurrent->~Node();
::IwFree(pCurrent);
}
entry = nullptr;
}
}
// Note: Can return nullptr even when (shouldAllocate == true) upon allocation failure
T* GetLocal(bool shouldAllocate = false) WI_NOEXCEPT {
DWORD const threadId = ::GetCurrentThreadId();
size_t const index = (threadId % ARRAYSIZE(m_hashArray));
for (auto pNode = m_hashArray[index]; pNode != nullptr; pNode = pNode->pNext) {
if (pNode->threadId == threadId) {
return &pNode->value;
}
}
if (shouldAllocate) {
Node* pNew = reinterpret_cast<Node*>(::IwMalloc(sizeof(Node)));
if (pNew != nullptr) {
// placement new would be preferred, but components include this file that do not enable it
pNew->Construct(threadId);
Node* pFirst;
do {
pFirst = m_hashArray[index];
pNew->pNext = pFirst;
} while (::InterlockedCompareExchangePointer(reinterpret_cast<PVOID volatile*>(m_hashArray + index), pNew, pFirst) !=
pFirst);
return &pNew->value;
}
}
return nullptr;
}
private:
ThreadStorage(ThreadStorage const&);
ThreadStorage& operator=(ThreadStorage const&);
struct Node {
T value;
DWORD threadId;
Node* pNext;
void Construct(DWORD currentThreadId) {
::ZeroMemory(&value, sizeof(value));
threadId = currentThreadId;
pNext = nullptr;
}
};
Node* volatile m_hashArray[threadCountEstimate];
};
struct IFailureCallback {
virtual bool NotifyFailure(FailureInfo const& failure) WI_NOEXCEPT = 0;
};
class ThreadFailureCallbackHolder;
#ifndef RESULT_SUPPRESS_STATIC_INITIALIZERS
__declspec(selectany) ThreadStorage<ThreadFailureCallbackHolder*> g_threadFailureCallbacks;
__declspec(selectany) ThreadStorage<ThreadFailureCallbackHolder*>* g_pThreadFailureCallbacks = &g_threadFailureCallbacks;
#else
__declspec(selectany) ThreadStorage<ThreadFailureCallbackHolder*>* g_pThreadFailureCallbacks = nullptr;
#endif
class ThreadFailureCallbackHolder {
public:
ThreadFailureCallbackHolder(_In_ IFailureCallback* pCallbackParam,
_In_opt_ CallContextInfo* pCallContext = nullptr,
bool watchNow = true) WI_NOEXCEPT : m_pCallback(pCallbackParam),
m_ppThreadList(nullptr),
m_pNext(nullptr),
m_threadId(0),
m_pCallContext(pCallContext) {
if (watchNow) {
StartWatching();
}
}
ThreadFailureCallbackHolder(ThreadFailureCallbackHolder&& other) WI_NOEXCEPT : m_pCallback(other.m_pCallback),
m_ppThreadList(nullptr),
m_pNext(nullptr),
m_threadId(0),
m_pCallContext(other.m_pCallContext) {
if (other.m_threadId != 0) {
other.StopWatching();
StartWatching();
}
}
~ThreadFailureCallbackHolder() WI_NOEXCEPT {
if (m_threadId != 0) {
StopWatching();
}
}
void SetCallContext(_In_opt_ CallContextInfo* pCallContext) {
m_pCallContext = pCallContext;
}
CallContextInfo* CallContextInfo() {
return m_pCallContext;
}
void StartWatching() {
// out-of balance Start/Stop calls?
__FAIL_FAST_PRERELEASE_ASSERT__(m_threadId == 0);
m_ppThreadList = (g_pThreadFailureCallbacks != nullptr) ? g_pThreadFailureCallbacks->GetLocal(true) :
nullptr; // true = allocate thread list if missing
if (m_ppThreadList) {
m_pNext = *m_ppThreadList;
*m_ppThreadList = this;
m_threadId = ::GetCurrentThreadId();
}
}
void StopWatching() {
if (m_threadId != ::GetCurrentThreadId()) {
// The thread-specific failure holder cannot be stopped on a different thread than it was started on or the
// internal book-keeping list will be corrupted. To fix this change the telemetry pattern in the calling code
// to match one of the patterns available here:
// https://microsoft.sharepoint.com/teams/osg_development/Shared%20Documents/Windows%20TraceLogging%20Helpers.docx
WI_USAGE_ERROR("MEMORY CORRUPTION: Calling code is leaking an activity thread-watcher and releasing it on another thread");
}
m_threadId = 0;
while (*m_ppThreadList != nullptr) {
if (*m_ppThreadList == this) {
*m_ppThreadList = m_pNext;
break;
}
m_ppThreadList = &((*m_ppThreadList)->m_pNext);
}
m_ppThreadList = nullptr;
}
bool IsWatching() {
return (m_threadId != 0);
}
void SetWatching(bool shouldWatch) {
if (shouldWatch && !IsWatching()) {
StartWatching();
} else if (!shouldWatch && IsWatching()) {
StopWatching();
}
}
static bool GetThreadContext(_Inout_ FailureInfo* pFailure,
_In_opt_ ThreadFailureCallbackHolder* pCallback,
_Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString,
_Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength) {
*callContextString = '\0';
bool foundContext = false;
if (pCallback != nullptr) {
foundContext = GetThreadContext(pFailure, pCallback->m_pNext, callContextString, callContextStringLength);
if (pCallback->m_pCallContext != nullptr) {
auto& context = *pCallback->m_pCallContext;
// We generate the next telemetry ID only when we've found an error (avoid always incrementing)
if (context.contextId == 0) {
context.contextId = ::InterlockedIncrementNoFence(&s_telemetryId);
}
if (pFailure->callContextOriginating.contextId == 0) {
pFailure->callContextOriginating = context;
}
pFailure->callContextCurrent = context;
auto callContextStringEnd = callContextString + callContextStringLength;
callContextString += strlen(callContextString);
if ((callContextStringEnd - callContextString) > 2) // room for at least the slash + null
{
*callContextString++ = '\\';
auto nameSizeBytes = strlen(context.contextName) + 1;
size_t remainingBytes = static_cast<size_t>(callContextStringEnd - callContextString);
auto copyBytes = (nameSizeBytes < remainingBytes) ? nameSizeBytes : remainingBytes;
memcpy(callContextString, context.contextName, copyBytes);
*(callContextString + (copyBytes - 1)) = '\0';
}
return true;
}
}
return foundContext;
}
static void GetContextAndNotifyFailure(_Inout_ FailureInfo* pFailure,
_Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString,
_Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength) WI_NOEXCEPT {
*callContextString = '\0';
bool reportedTelemetry = false;
ThreadFailureCallbackHolder** ppListeners =
(g_pThreadFailureCallbacks != nullptr) ? g_pThreadFailureCallbacks->GetLocal() : nullptr;
if ((ppListeners != nullptr) && (*ppListeners != nullptr)) {
callContextString[0] = '\0';
if (GetThreadContext(pFailure, *ppListeners, callContextString, callContextStringLength)) {
pFailure->pszCallContext = callContextString;
}
auto pNode = *ppListeners;
do {
reportedTelemetry |= pNode->m_pCallback->NotifyFailure(*pFailure);
pNode = pNode->m_pNext;
} while (pNode != nullptr);
}
if (g_pfnTelemetryCallback != nullptr) {
g_pfnTelemetryCallback(reportedTelemetry, *pFailure);
}
}
ThreadFailureCallbackHolder(ThreadFailureCallbackHolder const&) = delete;
ThreadFailureCallbackHolder& operator=(ThreadFailureCallbackHolder const&) = delete;
private:
static long volatile s_telemetryId;
IFailureCallback* m_pCallback;
ThreadFailureCallbackHolder** m_ppThreadList;
ThreadFailureCallbackHolder* m_pNext;
DWORD m_threadId;
wil::CallContextInfo* m_pCallContext;
};
__declspec(selectany) long volatile ThreadFailureCallbackHolder::s_telemetryId = 1;
// returns true if telemetry was reported for this error
inline void GetContextAndNotifyFailure(_Inout_ FailureInfo* pFailure,
_Out_writes_(callContextStringLength) _Post_z_ PSTR callContextString,
_Pre_satisfies_(callContextStringLength > 0) size_t callContextStringLength) WI_NOEXCEPT {
ThreadFailureCallbackHolder::GetContextAndNotifyFailure(pFailure, callContextString, callContextStringLength);
}
template <typename TLambda>
class ThreadFailureCallbackFn final : public IFailureCallback {
public:
explicit ThreadFailureCallbackFn(_In_ CallContextInfo* pContext, _Inout_ TLambda&& errorFunction) WI_NOEXCEPT
: m_errorFunction(wistd::move(errorFunction)),
m_callbackHolder(this, pContext) {
}
ThreadFailureCallbackFn(_Inout_ ThreadFailureCallbackFn&& other) WI_NOEXCEPT
: m_errorFunction(wistd::move(other.m_errorFunction)),
m_callbackHolder(this, other.m_callbackHolder.CallContextInfo()) {
}
bool NotifyFailure(FailureInfo const& failure) WI_NOEXCEPT {
return m_errorFunction(failure);
}
private:
ThreadFailureCallbackFn(_In_ ThreadFailureCallbackFn const&);
ThreadFailureCallbackFn& operator=(_In_ ThreadFailureCallbackFn const&);
TLambda m_errorFunction;
ThreadFailureCallbackHolder m_callbackHolder;
};
template <typename TLambda>
class ScopeExitFn {
public:
explicit ScopeExitFn(_Inout_ TLambda&& fnAtExit) WI_NOEXCEPT : m_fnAtExit(wistd::move(fnAtExit)), m_fRun(true) {
static_assert(!wistd::is_lvalue_reference<TLambda>::value && !wistd::is_rvalue_reference<TLambda>::value,
"ScopeExit should only be directly used with R-Value lambdas");
}
ScopeExitFn(_Inout_ ScopeExitFn&& other) WI_NOEXCEPT : m_fnAtExit(wistd::move(other.m_fnAtExit)), m_fRun(other.m_fRun) {
other.m_fRun = false;
}
~ScopeExitFn() WI_NOEXCEPT {
operator()();
}
void operator()() WI_NOEXCEPT {
if (m_fRun) {
m_fRun = false;
m_fnAtExit();
}
}
void Dismiss() WI_NOEXCEPT {
m_fRun = false;
}
private:
ScopeExitFn(_In_ ScopeExitFn const&);
ScopeExitFn& operator=(_In_ ScopeExitFn const&);
TLambda m_fnAtExit;
bool m_fRun;
};
#ifdef WIL_ENABLE_EXCEPTIONS
enum class GuardState { Done = 0, NeedsRunIgnore = 1, NeedsRunLog = 2, NeedsRunFailFast = 3 };
template <typename TLambda>
class ScopeExitFnGuard {
public:
explicit ScopeExitFnGuard(GuardState state, _Inout_ TLambda&& fnAtExit) WI_NOEXCEPT : m_fnAtExit(wistd::move(fnAtExit)),
m_state(state) {
static_assert(!wistd::is_lvalue_reference<TLambda>::value && !wistd::is_rvalue_reference<TLambda>::value,
"ScopeExit should only be directly used with R-Value lambdas");
}
ScopeExitFnGuard(ScopeExitFnGuard&& other) WI_NOEXCEPT : m_fnAtExit(wistd::move(other.m_fnAtExit)), m_state(other.m_state) {
other.m_state = GuardState::Done;
}
~ScopeExitFnGuard() WI_NOEXCEPT {
operator()();
}
void operator()() WI_NOEXCEPT {
if (m_state != GuardState::Done) {
auto state = m_state;
m_state = GuardState::Done;
try {
m_fnAtExit();
} catch (...) {
if (state == GuardState::NeedsRunFailFast) {
FAIL_FAST_HR(wil::ResultFromCaughtException());
} else if (state == GuardState::NeedsRunLog) {
LOG_HR(wil::ResultFromCaughtException());
}
// GuardState::NeedsRunIgnore explicitly ignored
}
}
}
void Dismiss() WI_NOEXCEPT {
m_state = GuardState::Done;
}
private:
ScopeExitFnGuard(ScopeExitFnGuard const&);
ScopeExitFnGuard& operator=(ScopeExitFnGuard const&);
TLambda m_fnAtExit;
GuardState m_state;
};
#endif // WIL_ENABLE_EXCEPTIONS
} // details namespace
//! @endcond
//*****************************************************************************
// Public Error Handling Helpers
//*****************************************************************************
// [optionally] Plug in fallback telemetry reporting
// Normally, the callback is owned by including ResultLogging.h in the including module. Alternatively a module
// could re-route fallback telemetry to any ONE specific provider by calling this method.
inline void SetResultTelemetryFallback(_In_opt_ decltype(details::g_pfnTelemetryCallback) callbackFunction) {
// Only ONE telemetry provider can own the fallback telemetry callback.
__FAIL_FAST_PRERELEASE_ASSERT__((details::g_pfnTelemetryCallback == nullptr) || (callbackFunction == nullptr));
details::g_pfnTelemetryCallback = callbackFunction;
}
// [optionally] Plug in result logging (do not use for telemetry)
// This provides the ability for a module to hook all failures flowing through the system for inspection
// and/or logging.
inline void SetResultLoggingCallback(_In_opt_ decltype(details::g_pfnLoggingCallback) callbackFunction) {
// Only ONE function can own the result logging callback
__FAIL_FAST_PRERELEASE_ASSERT__((details::g_pfnLoggingCallback == nullptr) || (details::g_pfnLoggingCallback == callbackFunction) ||
(callbackFunction == nullptr));
details::g_pfnLoggingCallback = callbackFunction;
}
// [optionally] Plug in custom result messages
// There are some purposes that require translating the full information that is known about a failure
// into a message to be logged (either through the console for debugging OR as the message attached
// to a Platform::Exception^). This callback allows a module to format the string itself away from the
// default.
inline void SetResultMessageCallback(_In_opt_ decltype(wil::g_pfnResultLoggingCallback) callbackFunction) {
// Only ONE function can own the result message callback
__FAIL_FAST_PRERELEASE_ASSERT__((g_pfnResultLoggingCallback == nullptr) || (callbackFunction == nullptr));
details::g_resultMessageCallbackSet = true;
g_pfnResultLoggingCallback = callbackFunction;
}
// [optionally] Plug in exception remapping
// A module can plug a callback in using this function to setup custom exception handling to allow any
// exception type to be converted into an HRESULT from exception barriers.
inline void SetResultFromCaughtExceptionCallback(_In_opt_ decltype(wil::g_pfnResultFromCaughtException) callbackFunction) {
// Only ONE function can own the exception conversion
__FAIL_FAST_PRERELEASE_ASSERT__((g_pfnResultFromCaughtException == nullptr) || (callbackFunction == nullptr));
g_pfnResultFromCaughtException = callbackFunction;
}
// A RAII wrapper around the storage of a FailureInfo struct (which is normally meant to be consumed
// on the stack or from the caller). The storage of FailureInfo needs to copy some data internally
// for lifetime purposes.
class StoredFailureInfo {
public:
StoredFailureInfo() WI_NOEXCEPT {
::ZeroMemory(&m_failureInfo, sizeof(m_failureInfo));
}
StoredFailureInfo(FailureInfo const& other) WI_NOEXCEPT {
SetFailureInfo(other);
}
FailureInfo const& GetFailureInfo() const WI_NOEXCEPT {
return m_failureInfo;
}
void SetFailureInfo(FailureInfo const& failure) WI_NOEXCEPT {
m_failureInfo = failure;
size_t const cbNeed = details::ResultStringSize(failure.pszMessage) + details::ResultStringSize(failure.pszCode) +
details::ResultStringSize(failure.pszFunction) + details::ResultStringSize(failure.pszFile) +
details::ResultStringSize(failure.pszCallContext) + details::ResultStringSize(failure.pszModule) +
details::ResultStringSize(failure.callContextCurrent.contextName) +
details::ResultStringSize(failure.callContextCurrent.contextMessage) +
details::ResultStringSize(failure.callContextOriginating.contextName) +
details::ResultStringSize(failure.callContextOriginating.contextMessage);
if (!m_spStrings.unique() || (m_spStrings.size() < cbNeed)) {
m_spStrings.reset();
m_spStrings.create(cbNeed);
}
size_t cbAlloc;
unsigned char* pBuffer = static_cast<unsigned char*>(m_spStrings.get(&cbAlloc));
unsigned char* pBufferEnd = (pBuffer != nullptr) ? pBuffer + cbAlloc : nullptr;
pBuffer = details::WriteResultString(pBuffer, pBufferEnd, failure.pszMessage, &m_failureInfo.pszMessage);
pBuffer = details::WriteResultString(pBuffer, pBufferEnd, failure.pszCode, &m_failureInfo.pszCode);
pBuffer = details::WriteResultString(pBuffer, pBufferEnd, failure.pszFunction, &m_failureInfo.pszFunction);
pBuffer = details::WriteResultString(pBuffer, pBufferEnd, failure.pszFile, &m_failureInfo.pszFile);
pBuffer = details::WriteResultString(pBuffer, pBufferEnd, failure.pszCallContext, &m_failureInfo.pszCallContext);
pBuffer = details::WriteResultString(pBuffer, pBufferEnd, failure.pszModule, &m_failureInfo.pszModule);
pBuffer = details::WriteResultString(pBuffer,
pBufferEnd,
failure.callContextCurrent.contextName,
&m_failureInfo.callContextCurrent.contextName);
pBuffer = details::WriteResultString(pBuffer,
pBufferEnd,
failure.callContextCurrent.contextMessage,
&m_failureInfo.callContextCurrent.contextMessage);
pBuffer = details::WriteResultString(pBuffer,
pBufferEnd,
failure.callContextOriginating.contextName,
&m_failureInfo.callContextOriginating.contextName);
details::WriteResultString(pBuffer,
pBufferEnd,
failure.callContextOriginating.contextMessage,
&m_failureInfo.callContextOriginating.contextMessage);
}
// Relies upon generated copy constructor and assignment operator
protected:
FailureInfo m_failureInfo;
details::shared_buffer m_spStrings;
};
// This is the default class thrown from all THROW_XXX macros. It stores all of the FailureInfo context that
// is available when the exception is thrown. It's also caught by exception guards for conversion to HRESULT.
class ResultException {
public:
ResultException(FailureInfo const& failure) WI_NOEXCEPT : m_failure(failure) {
}
// This constructor should be used only for custom exception types
ResultException(_Pre_satisfies_(hr < 0) HRESULT hr) WI_NOEXCEPT : m_failure(CustomExceptionFailureInfo(hr)) {
}
_Always_(_Post_satisfies_(return < 0)) HRESULT GetErrorCode() const WI_NOEXCEPT {
HRESULT const hr = m_failure.GetFailureInfo().hr;
__analysis_assume(hr < 0);
return hr;
}
FailureInfo const& GetFailureInfo() const WI_NOEXCEPT {
return m_failure.GetFailureInfo();
}
void SetFailureInfo(FailureInfo const& failure) WI_NOEXCEPT {
m_failure.SetFailureInfo(failure);
}
// Relies upon auto-generated copy constructor and assignment operator
protected:
StoredFailureInfo m_failure;
static FailureInfo CustomExceptionFailureInfo(HRESULT hr) WI_NOEXCEPT {
FailureInfo fi = {};
fi.type = FailureType::Exception;
fi.hr = hr;
return fi;
}
};
// This helper functions much like ScopeExit -- give it a lambda and get back a local object that can be used to
// catch all errors happening in your module through all WIL error handling mechanisms. The lambda will be called
// once for each error throw, error return, or error catch that is handled while the returned object is still in
// scope. Usage:
//
// auto monitor = wil::ThreadFailureCallback([](wil::FailureInfo const &failure)
// {
// // Write your code that logs or cares about failure details here...
// // It has access to HRESULT, filename, line number, etc through the failure param.
// });
//
// As long as the returned 'monitor' object remains in scope, the lambda will continue to receive callbacks for any
// failures that occur in this module on the calling thread. Note that this will guarantee that the lambda will run
// for any failure that is through any of the WIL macros (THROW_XXX, RETURN_XXX, LOG_XXX, etc).
template <typename TLambda>
inline wil::details::ThreadFailureCallbackFn<TLambda> ThreadFailureCallback(_Inout_ TLambda&& fnAtExit) WI_NOEXCEPT {
return wil::details::ThreadFailureCallbackFn<TLambda>(nullptr, wistd::forward<TLambda>(fnAtExit));
}
// Much like ThreadFailureCallback, this class will receive WIL failure notifications from the time it's instantiated
// until the time that it's destroyed. At any point during that time you can ask for the last failure that was seen
// by any of the WIL macros (RETURN_XXX, THROW_XXX, LOG_XXX, etc) on the current thread.
//
// This class is most useful when utilized as a member of an RAII class that's dedicated to providing logging or
// telemetry. In the destructor of that class, if the operation had not been completed successfully (it goes out of
// scope due to early return or exception unwind before success is acknowledged) then details about the last failure
// can be retrieved and appropriately logged.
//
// Usage:
//
// class MyLogger
// {
// public:
// MyLogger() : m_fComplete(false) {}
// ~MyLogger()
// {
// if (!m_fComplete)
// {
// FailureInfo *pFailure = m_cache.GetFailure();
// if (pFailure != nullptr)
// {
// // Log information about pFailure (pFileure->hr, pFailure->pszFile, pFailure->uLineNumber, etc)
// }
// else
// {
// // It's possible that you get stack unwind from an exception that did NOT come through WIL
// // like (std::bad_alloc from the STL). Use a reasonable default like: HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION).
// }
// }
// }
// void Complete() { m_fComplete = true; }
// private:
// bool m_fComplete;
// ThreadFailureCache m_cache;
// };
class ThreadFailureCache final : public details::IFailureCallback {
public:
ThreadFailureCache() : m_callbackHolder(this) {
}
ThreadFailureCache(ThreadFailureCache&& rhs) : m_failure(wistd::move(rhs.m_failure)), m_callbackHolder(this) {
}
ThreadFailureCache& operator=(ThreadFailureCache&& rhs) {
m_failure = wistd::move(rhs.m_failure);
return *this;
}
void WatchCurrentThread() {
m_callbackHolder.StartWatching();
}
void IgnoreCurrentThread() {
m_callbackHolder.StopWatching();
}
FailureInfo const* GetFailure() {
return (FAILED(m_failure.GetFailureInfo().hr) ? &(m_failure.GetFailureInfo()) : nullptr);
}
bool NotifyFailure(FailureInfo const& failure) WI_NOEXCEPT {
// When we "cache" a failure, we bias towards trying to find the origin of the last HRESULT
// generated, so we ignore subsequent failures on the same error code (assuming propagation).
if (failure.hr != m_failure.GetFailureInfo().hr) {
m_failure.SetFailureInfo(failure);
}
return false;
}
private:
StoredFailureInfo m_failure;
details::ThreadFailureCallbackHolder m_callbackHolder;
};
// The ScopeExit function accepts a lambda and returns an object meant to be captured in
// an auto variable. That lambda will be run when the object goes out of scope. For most
// begin/end pairings RAII techniques should be used instead, but occasionally there are
// uncommon cases where RAII techniques are impractical (ensuring a file is deleted after
// a test routine, etc). Usage involves:
//
// FunctionNeedingCleanup(); // start with a call to establish some state that requires cleanup
// auto fnCleanup = ScopeExit([&]
// {
// // write cleanup code here
// });
//
// When fnCleanup goes out of scope it will run its lambda. Optionally, if the cleanup is
// no long needed, it can be dismissed (so that it is not run):
//
// fnCleanup.Dismiss();
//
// If the cleanup is needed ahead of going out of scope it can be explicitly run:
//
// fnCleanup();
template <typename TLambda>
inline wil::details::ScopeExitFn<TLambda> ScopeExit(_Inout_ TLambda&& fnAtExit) WI_NOEXCEPT {
return wil::details::ScopeExitFn<TLambda>(wistd::forward<TLambda>(fnAtExit));
}
//*****************************************************************************
// Public Helpers that catch -- only enabled when exceptions are enabled
//*****************************************************************************
#ifdef WIL_ENABLE_EXCEPTIONS
// The ScopeExitXXX functions work identically to ScopeExit but add an exception guard for the lambda. The different
// variants control what happens if an exception were actually thrown from the cleanup lambda.
// The ScopeExitNoExcept version should eventually be removed in favor of the simpler ScopeExit() once noexcept is
// fully implemented to provide fail fast handling of exceptions from the regular scope exit class.
template <typename TLambda>
inline wil::details::ScopeExitFnGuard<TLambda> ScopeExitNoExcept(TLambda&& fnAtExit) WI_NOEXCEPT {
return wil::details::ScopeExitFnGuard<TLambda>(wil::details::GuardState::NeedsRunFailFast, wistd::forward<TLambda>(fnAtExit));
}
template <typename TLambda>
inline wil::details::ScopeExitFnGuard<TLambda> ScopeExitLog(TLambda&& fnAtExit) WI_NOEXCEPT {
return wil::details::ScopeExitFnGuard<TLambda>(wil::details::GuardState::NeedsRunLog, wistd::forward<TLambda>(fnAtExit));
}
template <typename TLambda>
inline wil::details::ScopeExitFnGuard<TLambda> ScopeExitIgnore(TLambda&& fnAtExit) WI_NOEXCEPT {
return wil::details::ScopeExitFnGuard<TLambda>(wil::details::GuardState::NeedsRunIgnore, wistd::forward<TLambda>(fnAtExit));
}
// ResultFromCaughtException is a function that is meant to be called from within a catch(...) block. Internally
// it re-throws and catches the exception to convert it to an HRESULT. If an exception is of an unrecognized type
// the function will fail fast.
//
// try
// {
// // Code
// }
// catch (...)
// {
// hr = wil::ResultFromCaughtException();
// }
_Always_(_Post_satisfies_(return < 0)) __declspec(noinline) inline HRESULT ResultFromCaughtException() WI_NOEXCEPT {
HRESULT hr;
if (g_resultFromUncaughtExceptionObjC && g_resultFromUncaughtExceptionObjC(&hr)) {
return hr;
}
try {
throw;
} catch (const ResultException& re) {
return re.GetErrorCode();
} catch (std::bad_alloc) {
return E_OUTOFMEMORY;
} catch (...) {
return details::ResultFromUnknownCaughtException();
}
}
// ResultFromException serves as an exception guard. Much like try/catch(...), this function accepts a lambda
// where all exceptions generated within will be caught and converted to their corresponding HRESULT. If an
// exception is of an unrecognized type, then the guard will fail fast.
//
// HRESULT ErrorCodeReturningFunction()
// {
// RETURN_HR(wil::ResultFromException([&])()
// {
// // Use of libraries or function calls that may throw
// // exceptions...
// }));
// }
template <typename Functor>
inline HRESULT ResultFromException(_Inout_ Functor&& functor) WI_NOEXCEPT {
try {
functor();
} catch (...) {
return ResultFromCaughtException();
}
return S_OK;
}
// NormalizeIfExceptionThrown serves as an exception guard built to normalize on one exception type. This allows
// a C++/CX void returning function to normalize all exceptions thrown within to Platform::Exception^, even if
// STL is used within (std::bad_alloc) or a custom ResultException has been thrown within. Thus when that C++/CX
// method is invoked by COM with a cross-apartment call, those exceptions will be caught and mapped correctly to
// an HRESULT. From within straight C++, this normalization works identically, only remapping all known exception
// types to ResultException, rather than Platform::Exception^
//
// void MyFunction()
// {
// wil::NormalizeIfExceptionThrown([&])()
// {
// // Use of libraries or function calls that may throw diverse
// // exception types...
// }));
// }
template <typename Functor>
inline void NormalizeIfExceptionThrown(_Inout_ Functor&& functor) {
try {
functor();
} catch (...) {
wil::details::RethrowNormalizedCaughtException(__R_INFO_ONLY(nullptr));
}
}
#endif // WIL_ENABLE_EXCEPTIONS
//! @cond
namespace details {
//*****************************************************************************
// Private helpers to catch and propagate exceptions
//*****************************************************************************
#ifdef WIL_ENABLE_EXCEPTIONS
_declspec(noreturn) inline void RethrowUnknownCaughtException(__R_FN_PARAMS_FULL, _In_opt_ PCWSTR message) {
if (g_pfnResultFromCaughtException != nullptr) {
const HRESULT hr = g_pfnResultFromCaughtException();
if (FAILED(hr)) {
ReportFailure(__R_FN_CALL_FULL, FailureType::Exception, hr, message);
}
}
#ifdef RESULT_PRERELEASE
if (g_fResultFailFastUnknownExceptions) {
// Caller bug: an unknown exception was thrown
ReportFailure(__R_FN_CALL_FULL, FailureType::FailFast, HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION), message);
}
#endif
ReportFailure(__R_FN_CALL_FULL, FailureType::Exception, HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION), message);
}
__declspec(noreturn) inline void RethrowNormalizedCaughtException_Helper(__R_FN_PARAMS_FULL, _In_opt_ PCWSTR message = nullptr) {
if (g_rethrowNormalizedCaughtExceptionObjC) {
g_rethrowNormalizedCaughtExceptionObjC(__R_FN_CALL_FULL, message);
}
try {
throw;
} catch (const ResultException& re) {
ReportFailure(__R_FN_CALL_FULL, FailureType::Exception, re.GetErrorCode(), message, ReportFailureOptions::SuppressAction);
// Outside of C++/CX, ResultException is our normalized exception. Because it's our class
// we can be confident that it has already been logged -- just re-throw it.
throw;
} catch (std::bad_alloc) {
ReportFailure(__R_FN_CALL_FULL, FailureType::Exception, E_OUTOFMEMORY, message);
} catch (...) {
RethrowUnknownCaughtException(__R_FN_CALL_FULL, message);
}
}
__declspec(noinline, noreturn) inline void RethrowNormalizedCaughtException(__R_FN_PARAMS_ONLY) {
__R_FN_LOCALS;
RethrowNormalizedCaughtException_Helper(__R_FN_CALL_FULL_RA);
}
__declspec(noinline, noreturn) inline void RethrowNormalizedCaughtExceptionMsg(__R_FN_PARAMS _In_ _Printf_format_string_ PCSTR formatString,
...) {
va_list argList;
va_start(argList, formatString);
wchar_t message[2048];
PrintLoggingMessage(message, ARRAYSIZE(message), formatString, argList);
__R_FN_LOCALS;
RethrowNormalizedCaughtException_Helper(__R_FN_CALL_FULL_RA, message);
}
_Always_(_Post_satisfies_(return < 0)) inline HRESULT ResultFromUnknownCaughtException() {
if (g_pfnResultFromCaughtException != nullptr) {
HRESULT hr = g_pfnResultFromCaughtException();
if (FAILED(hr)) {
return hr;
}
}
// Caller bug: an unknown exception was thrown
FAIL_FAST_HR_IF(HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION), g_fResultFailFastUnknownExceptions);
return HRESULT_FROM_WIN32(ERROR_UNHANDLED_EXCEPTION);
}
#endif // WIL_ENABLE_EXCEPTIONS
//*****************************************************************************
// Shared Reporting -- all reporting macros bubble up through this codepath
//*****************************************************************************
inline void LogFailure(__R_FN_PARAMS_FULL,
FailureType type,
HRESULT hr,
_In_opt_ PCWSTR message,
bool fWantDebugString,
_Out_writes_(debugStringSizeChars) _Post_z_ PWSTR debugString,
_Pre_satisfies_(debugStringSizeChars > 0) size_t debugStringSizeChars,
_Out_writes_(callContextStringSizeChars) _Post_z_ PSTR callContextString,
_Pre_satisfies_(callContextStringSizeChars > 0) size_t callContextStringSizeChars,
_Out_ FailureInfo* failure) WI_NOEXCEPT {
debugString[0] = L'\0';
callContextString[0] = L'\0';
static long volatile s_failureId = 0;
int failureCount = 0;
switch (type) {
case FailureType::Exception:
case FailureType::ObjCException:
failureCount = RecordException(hr);
break;
case FailureType::Return:
failureCount = RecordReturn(hr);
break;
case FailureType::ReturnPreRelease:
failureCount = RecordReturnPreRelease(hr);
break;
case FailureType::Log:
if (SUCCEEDED(hr)) {
// If you hit this assert (or are reviewing this failure telemetry), then most likely you are trying to log success
// using one of the WIL macros. Example:
// LOG_HR(S_OK);
// Instead, use one of the forms that conditionally logs based upon the error condition:
// LOG_IF_FAILED(hr);
WI_USAGE_ERROR_FORWARD("CALLER BUG: Macro usage error detected. Do not LOG_XXX success.");
hr = HRESULT_FROM_WIN32(ERROR_ASSERTION_FAILURE);
}
failureCount = RecordLog(hr);
break;
case FailureType::FailFast:
failureCount = RecordFailFast(hr);
break;
};
failure->type = type;
failure->hr = hr;
failure->failureId = ::InterlockedIncrementNoFence(&s_failureId);
failure->pszMessage = ((message != nullptr) && (message[0] != L'\0')) ? message : nullptr;
failure->threadId = ::GetCurrentThreadId();
failure->pszFile = fileName;
failure->uLineNumber = lineNumber;
failure->cFailureCount = failureCount;
failure->pszCode = code;
failure->pszFunction = functionName;
failure->returnAddress = returnAddress;
failure->callerReturnAddress = callerReturnAddress;
failure->pszCallContext = nullptr;
ClearContext(&failure->callContextCurrent);
ClearContext(&failure->callContextOriginating);
failure->pszModule = (g_pfnGetModuleName != nullptr) ? g_pfnGetModuleName() : nullptr;
// Completes filling out failure, notifies thread-based callbacks and the telemetry callback
GetContextAndNotifyFailure(failure, callContextString, callContextStringSizeChars);
// Allow a hook to inspect the failure before acting upon it
if (details::g_pfnLoggingCallback != nullptr) {
details::g_pfnLoggingCallback(*failure);
}
// Caller bug: Leaking a success code into a failure-only function
FAIL_FAST_IF(SUCCEEDED(failure->hr) && (type != FailureType::FailFast));
// We need to generate the logging message if:
// * The caller asked us to (generally for attaching to a C++/CX exception)
if (fWantDebugString) {
// Call the logging callback (if present) to allow them to generate the debug string that will be pushed to the console
// or the platform exception object if the caller desires it.
if (g_pfnResultLoggingCallback != nullptr) {
g_pfnResultLoggingCallback(failure, debugString, debugStringSizeChars);
}
// The callback only optionally needs to supply the debug string -- if the callback didn't populate it, yet we still want
// it for OutputDebugString or exception message, then generate the default string.
if (debugString[0] == L'\0') {
GetFailureLogString(debugString, debugStringSizeChars, *failure);
}
} else {
// [deprecated behavior]
// This callback was at one point *always* called for all failures, so we continue to call it for failures even when we don't
// need to generate the debug string information (when the callback was supplied directly). We can avoid this if the caller
// used the explicit function (through g_resultMessageCallbackSet)
if ((g_pfnResultLoggingCallback != nullptr) && !g_resultMessageCallbackSet) {
g_pfnResultLoggingCallback(failure, nullptr, 0);
}
}
}
inline __declspec(noinline) void ReportFailure(
__R_FN_PARAMS_FULL, FailureType type, HRESULT hr, _In_opt_ PCWSTR message, ReportFailureOptions options) {
FailureInfo failure;
wchar_t debugString[2048];
char callContextString[1024];
const bool forceObjCException = WI_IS_FLAG_SET(options, ReportFailureOptions::ForceObjCException);
LogFailure(__R_FN_CALL_FULL,
type,
hr,
message,
forceObjCException, // Performs extra logging if we're forcing a conversion to ObjCException
debugString,
ARRAYSIZE(debugString),
callContextString,
ARRAYSIZE(callContextString),
&failure);
if (WI_IS_FLAG_CLEAR(options, ReportFailureOptions::SuppressAction)) {
if (type == FailureType::FailFast) {
// This is an explicit fail fast - examine the callstack to determine the precise reason for this failure
RESULT_RAISE_FAST_FAIL_EXCEPTION;
} else if (type == FailureType::ObjCException || forceObjCException) {
if (!g_objcThrowFailureInfo) {
LogFailure(__R_FN_CALL_FULL,
type,
E_UNEXPECTED,
L"Throwing an Objective C exception requires having Objective C code",
false,
debugString,
ARRAYSIZE(debugString),
callContextString,
ARRAYSIZE(callContextString),
&failure);
RESULT_RAISE_FAST_FAIL_EXCEPTION;
}
g_objcThrowFailureInfo(failure);
} else if (type == FailureType::Exception) {
throw ResultException(failure);
}
}
}
inline void ReportFailure_Msg(
__R_FN_PARAMS_FULL, FailureType type, HRESULT hr, _Printf_format_string_ PCSTR formatString, va_list argList) {
wchar_t message[2048];
PrintLoggingMessage(message, ARRAYSIZE(message), formatString, argList);
ReportFailure(__R_FN_CALL_FULL, type, hr, message);
}
inline void ReportFailure_ReplaceMsg(__R_FN_PARAMS_FULL, FailureType type, HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) {
va_list argList;
va_start(argList, formatString);
ReportFailure_Msg(__R_FN_CALL_FULL, type, hr, formatString, argList);
}
__declspec(noinline) inline void ReportFailure_Hr(__R_FN_PARAMS_FULL, FailureType type, HRESULT hr) {
ReportFailure(__R_FN_CALL_FULL, type, hr);
}
__declspec(noinline) inline HRESULT ReportFailure_Win32(__R_FN_PARAMS_FULL, FailureType type, DWORD err) {
auto hr = HRESULT_FROM_WIN32(err);
ReportFailure(__R_FN_CALL_FULL, type, hr);
return hr;
}
__declspec(noinline) inline DWORD ReportFailure_GetLastError(__R_FN_PARAMS_FULL, FailureType type) {
auto err = GetLastErrorFail(__R_FN_CALL_FULL);
ReportFailure(__R_FN_CALL_FULL, type, HRESULT_FROM_WIN32(err));
return err;
}
__declspec(noinline) inline HRESULT ReportFailure_GetLastErrorHr(__R_FN_PARAMS_FULL, FailureType type) {
auto hr = GetLastErrorFailHr(__R_FN_CALL_FULL);
ReportFailure(__R_FN_CALL_FULL, type, hr);
return hr;
}
__declspec(noinline) inline HRESULT ReportFailure_NtStatus(__R_FN_PARAMS_FULL, FailureType type, NTSTATUS status) {
auto hr = wil::details::NtStatusToHr(status);
ReportFailure(__R_FN_CALL_FULL, type, hr);
return hr;
}
__declspec(noinline) inline void ReportFailure_HrMsg(
__R_FN_PARAMS_FULL, FailureType type, HRESULT hr, _Printf_format_string_ PCSTR formatString, va_list argList) {
ReportFailure_Msg(__R_FN_CALL_FULL, type, hr, formatString, argList);
}
__declspec(noinline) inline HRESULT
ReportFailure_Win32Msg(__R_FN_PARAMS_FULL, FailureType type, DWORD err, _Printf_format_string_ PCSTR formatString, va_list argList) {
auto hr = HRESULT_FROM_WIN32(err);
ReportFailure_Msg(__R_FN_CALL_FULL, type, HRESULT_FROM_WIN32(err), formatString, argList);
return hr;
}
__declspec(noinline) inline DWORD
ReportFailure_GetLastErrorMsg(__R_FN_PARAMS_FULL, FailureType type, _Printf_format_string_ PCSTR formatString, va_list argList) {
auto err = GetLastErrorFail(__R_FN_CALL_FULL);
ReportFailure_Msg(__R_FN_CALL_FULL, type, HRESULT_FROM_WIN32(err), formatString, argList);
return err;
}
__declspec(noinline) inline HRESULT
ReportFailure_GetLastErrorHrMsg(__R_FN_PARAMS_FULL, FailureType type, _Printf_format_string_ PCSTR formatString, va_list argList) {
auto hr = GetLastErrorFailHr(__R_FN_CALL_FULL);
ReportFailure_Msg(__R_FN_CALL_FULL, type, hr, formatString, argList);
return hr;
}
__declspec(noinline) inline HRESULT ReportFailure_NtStatusMsg(
__R_FN_PARAMS_FULL, FailureType type, NTSTATUS status, _Printf_format_string_ PCSTR formatString, va_list argList) {
auto hr = wil::details::NtStatusToHr(status);
ReportFailure_Msg(__R_FN_CALL_FULL, type, hr, formatString, argList);
return hr;
}
//*****************************************************************************
// Support for throwing custom exception types
//*****************************************************************************
inline HRESULT GetErrorCode(_In_ ResultException& exception) WI_NOEXCEPT {
return exception.GetErrorCode();
}
inline void SetFailureInfo(_In_ FailureInfo const& failure, _Inout_ ResultException& exception) WI_NOEXCEPT {
return exception.SetFailureInfo(failure);
}
#ifdef __cplusplus_winrt
inline HRESULT GetErrorCode(_In_ Platform::Exception ^ exception) WI_NOEXCEPT {
return exception->HResult;
}
inline void SetFailureInfo(_In_ FailureInfo const&, _Inout_ Platform::Exception ^ exception) WI_NOEXCEPT {
// no-op -- once a PlatformException^ is created, we can't modify the message, but this function must
// exist to distinguish this from ResultException
}
#endif
template <typename T>
__declspec(noreturn) inline void ReportFailure_CustomExceptionHelper(_Inout_ T& exception,
__R_FN_PARAMS_FULL,
_In_opt_ PCWSTR message = nullptr) {
// When seeing the error: "cannot convert parameter 1 from 'XXX' to 'wil::ResultException &'"
// Custom exceptions must be based upon either ResultException or Platform::Exception^ to be used with ResultException.h.
// This compilation error indicates an attempt to throw an incompatible exception type.
const HRESULT hr = GetErrorCode(exception);
FailureInfo failure;
wchar_t debugString[2048];
char callContextString[1024];
LogFailure(__R_FN_CALL_FULL,
FailureType::Exception,
hr,
message,
false, // false = does not need debug string
debugString,
ARRAYSIZE(debugString),
callContextString,
ARRAYSIZE(callContextString),
&failure);
// push the failure info context into the custom exception class
SetFailureInfo(failure, exception);
throw exception;
}
template <typename T>
__declspec(noreturn, noinline) inline void ReportFailure_CustomException(__R_FN_PARAMS _In_ T exception) {
__R_FN_LOCALS_RA;
ReportFailure_CustomExceptionHelper(exception, __R_FN_CALL_FULL);
}
template <typename T>
__declspec(noreturn, noinline) inline void ReportFailure_CustomExceptionMsg(__R_FN_PARAMS _In_ T exception,
_In_ _Printf_format_string_ PCSTR formatString,
...) {
va_list argList;
va_start(argList, formatString);
wchar_t message[2048];
PrintLoggingMessage(message, ARRAYSIZE(message), formatString, argList);
__R_FN_LOCALS_RA;
ReportFailure_CustomExceptionHelper(exception, __R_FN_CALL_FULL, message);
}
namespace __R_NS_NAME {
//*****************************************************************************
// Return Macros
//*****************************************************************************
__R_DIRECT_METHOD(void, Return_Hr)(__R_DIRECT_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_DIRECT_FN_CALL FailureType::Return, hr);
}
__R_DIRECT_METHOD(HRESULT, Return_Win32)(__R_DIRECT_FN_PARAMS DWORD err) WI_NOEXCEPT {
__R_FN_LOCALS;
return wil::details::ReportFailure_Win32(__R_DIRECT_FN_CALL FailureType::Return, err);
}
__R_DIRECT_METHOD(HRESULT, Return_GetLastError)(__R_DIRECT_FN_PARAMS_ONLY) WI_NOEXCEPT {
__R_FN_LOCALS;
return wil::details::ReportFailure_GetLastErrorHr(__R_DIRECT_FN_CALL FailureType::Return);
}
__R_DIRECT_METHOD(HRESULT, Return_NtStatus)(__R_DIRECT_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
__R_FN_LOCALS;
return wil::details::ReportFailure_NtStatus(__R_DIRECT_FN_CALL FailureType::Return, status);
}
__R_DIRECT_METHOD(void, Return_HrMsg)(__R_DIRECT_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_DIRECT_FN_CALL FailureType::Return, hr, formatString, argList);
}
__R_DIRECT_METHOD(HRESULT, Return_Win32Msg)(__R_DIRECT_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
return wil::details::ReportFailure_Win32Msg(__R_DIRECT_FN_CALL FailureType::Return, err, formatString, argList);
}
__R_DIRECT_METHOD(HRESULT, Return_GetLastErrorMsg)(__R_DIRECT_FN_PARAMS _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
return wil::details::ReportFailure_GetLastErrorHrMsg(__R_DIRECT_FN_CALL FailureType::Return, formatString, argList);
}
__R_DIRECT_METHOD(HRESULT, Return_NtStatusMsg)
(__R_DIRECT_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
return wil::details::ReportFailure_NtStatusMsg(__R_DIRECT_FN_CALL FailureType::Return, status, formatString, argList);
}
//*****************************************************************************
// Pre-release Return Macros
//*****************************************************************************
#ifdef RESULT_PRERELEASE
__R_DIRECT_METHOD(void, Return_HrPreRelease)(__R_DIRECT_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_DIRECT_FN_CALL FailureType::ReturnPreRelease, hr);
}
__R_DIRECT_METHOD(void, Return_NullPreRelease)(__R_DIRECT_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_DIRECT_FN_CALL FailureType::ReturnPreRelease, hr);
}
__R_DIRECT_METHOD(void, Return_NullWin32PreRelease)(__R_DIRECT_FN_PARAMS DWORD err) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Win32(__R_DIRECT_FN_CALL FailureType::ReturnPreRelease, err);
}
__R_DIRECT_METHOD(HRESULT, Return_Win32PreRelease)(__R_DIRECT_FN_PARAMS DWORD err) WI_NOEXCEPT {
__R_FN_LOCALS;
return wil::details::ReportFailure_Win32(__R_DIRECT_FN_CALL FailureType::ReturnPreRelease, err);
}
__R_DIRECT_METHOD(HRESULT, Return_GetLastErrorPreRelease)(__R_DIRECT_FN_PARAMS_ONLY) WI_NOEXCEPT {
__R_FN_LOCALS;
return wil::details::ReportFailure_GetLastErrorHr(__R_DIRECT_FN_CALL FailureType::ReturnPreRelease);
}
__R_DIRECT_METHOD(void, Return_NullGetLastErrorPreRelease)(__R_DIRECT_FN_PARAMS_ONLY) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_GetLastErrorHr(__R_DIRECT_FN_CALL FailureType::ReturnPreRelease);
}
__R_DIRECT_METHOD(HRESULT, Return_NtStatusPreRelease)(__R_DIRECT_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
__R_FN_LOCALS;
return wil::details::ReportFailure_NtStatus(__R_DIRECT_FN_CALL FailureType::ReturnPreRelease, status);
}
#endif
//*****************************************************************************
// Log Macros
//*****************************************************************************
__R_DIRECT_METHOD(HRESULT, Log_Hr)(__R_DIRECT_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_DIRECT_FN_CALL FailureType::Log, hr);
return hr;
}
__R_DIRECT_METHOD(DWORD, Log_Win32)(__R_DIRECT_FN_PARAMS DWORD err) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Win32(__R_DIRECT_FN_CALL FailureType::Log, err);
return err;
}
__R_DIRECT_METHOD(DWORD, Log_GetLastError)(__R_DIRECT_FN_PARAMS_ONLY) WI_NOEXCEPT {
__R_FN_LOCALS;
return wil::details::ReportFailure_GetLastError(__R_DIRECT_FN_CALL FailureType::Log);
}
__R_DIRECT_METHOD(NTSTATUS, Log_NtStatus)(__R_DIRECT_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatus(__R_DIRECT_FN_CALL FailureType::Log, status);
return status;
}
__R_INTERNAL_METHOD(_Log_Hr)(__R_INTERNAL_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_INTERNAL_FN_CALL FailureType::Log, hr);
}
__R_INTERNAL_METHOD(_Log_GetLastError)(__R_INTERNAL_FN_PARAMS_ONLY) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_GetLastError(__R_INTERNAL_FN_CALL FailureType::Log);
}
__R_INTERNAL_METHOD(_Log_Win32)(__R_INTERNAL_FN_PARAMS DWORD err) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Win32(__R_INTERNAL_FN_CALL FailureType::Log, err);
}
__R_INTERNAL_METHOD(_Log_NullAlloc)(__R_INTERNAL_FN_PARAMS_ONLY) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_INTERNAL_FN_CALL FailureType::Log, E_OUTOFMEMORY);
}
__R_INTERNAL_METHOD(_Log_NtStatus)(__R_INTERNAL_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatus(__R_INTERNAL_FN_CALL FailureType::Log, status);
}
__R_CONDITIONAL_METHOD(HRESULT, Log_IfFailed)(__R_CONDITIONAL_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
if (FAILED(hr)) {
__R_CALL_INTERNAL_METHOD(_Log_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return hr;
}
__R_CONDITIONAL_METHOD(BOOL, Log_IfWin32BoolFalse)(__R_CONDITIONAL_FN_PARAMS BOOL ret) WI_NOEXCEPT {
if (!ret) {
__R_CALL_INTERNAL_METHOD(_Log_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return ret;
}
__R_CONDITIONAL_METHOD(DWORD, Log_IfWin32Error)(__R_CONDITIONAL_FN_PARAMS DWORD err) WI_NOEXCEPT {
if (FAILED_WIN32(err)) {
__R_CALL_INTERNAL_METHOD(_Log_Win32)(__R_CONDITIONAL_FN_CALL err);
}
return err;
}
__R_CONDITIONAL_METHOD(HANDLE, Log_IfHandleInvalid)(__R_CONDITIONAL_FN_PARAMS HANDLE handle) WI_NOEXCEPT {
if (handle == INVALID_HANDLE_VALUE) {
__R_CALL_INTERNAL_METHOD(_Log_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return handle;
}
__R_CONDITIONAL_METHOD(HANDLE, Log_IfHandleNull)(__R_CONDITIONAL_FN_PARAMS HANDLE handle) WI_NOEXCEPT {
if (handle == nullptr) {
__R_CALL_INTERNAL_METHOD(_Log_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return handle;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(PointerT, Log_IfNullAlloc)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Log_NullAlloc)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(void, Log_IfNullAlloc)
(__R_CONDITIONAL_FN_PARAMS const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Log_NullAlloc)(__R_CONDITIONAL_FN_CALL_ONLY);
}
}
__R_CONDITIONAL_METHOD(bool, Log_HrIf)(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) WI_NOEXCEPT {
if (condition) {
__R_CALL_INTERNAL_METHOD(_Log_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return condition;
}
__R_CONDITIONAL_METHOD(bool, Log_HrIfFalse)(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) WI_NOEXCEPT {
if (!condition) {
__R_CALL_INTERNAL_METHOD(_Log_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(PointerT, Log_HrIfNull)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Log_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(void, Log_HrIfNull)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Log_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
}
__R_CONDITIONAL_METHOD(bool, Log_GetLastErrorIf)(__R_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT {
if (condition) {
__R_CALL_INTERNAL_METHOD(_Log_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
__R_CONDITIONAL_METHOD(bool, Log_GetLastErrorIfFalse)(__R_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT {
if (!condition) {
__R_CALL_INTERNAL_METHOD(_Log_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(PointerT, Log_GetLastErrorIfNull)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Log_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(void, Log_GetLastErrorIfNull)
(__R_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Log_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
}
__R_CONDITIONAL_METHOD(NTSTATUS, Log_IfNtStatusFailed)(__R_CONDITIONAL_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
if (FAILED_NTSTATUS(status)) {
__R_CALL_INTERNAL_METHOD(_Log_NtStatus)(__R_CONDITIONAL_FN_CALL status);
}
return status;
}
__R_DIRECT_METHOD(HRESULT, Log_HrMsg)(__R_DIRECT_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_DIRECT_FN_CALL FailureType::Log, hr, formatString, argList);
return hr;
}
__R_DIRECT_METHOD(DWORD, Log_Win32Msg)(__R_DIRECT_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_Win32Msg(__R_DIRECT_FN_CALL FailureType::Log, err, formatString, argList);
return err;
}
__R_DIRECT_METHOD(DWORD, Log_GetLastErrorMsg)(__R_DIRECT_FN_PARAMS _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
return wil::details::ReportFailure_GetLastErrorMsg(__R_DIRECT_FN_CALL FailureType::Log, formatString, argList);
}
__R_DIRECT_METHOD(NTSTATUS, Log_NtStatusMsg)
(__R_DIRECT_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatusMsg(__R_DIRECT_FN_CALL FailureType::Log, status, formatString, argList);
return status;
}
__R_INTERNAL_NOINLINE_METHOD(_Log_HrMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Log, hr, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_GetLastErrorMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Log, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Log_Win32Msg)
(__R_INTERNAL_NOINLINE_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_Win32Msg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Log, err, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Log_NullAllocMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Log, E_OUTOFMEMORY, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Log_NtStatusMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatusMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Log, status, formatString, argList);
}
__R_CONDITIONAL_NOINLINE_METHOD(HRESULT, Log_IfFailedMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (FAILED(hr)) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return hr;
}
__R_CONDITIONAL_NOINLINE_METHOD(BOOL, Log_IfWin32BoolFalseMsg)
(__R_CONDITIONAL_FN_PARAMS BOOL ret, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (!ret) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return ret;
}
__R_CONDITIONAL_NOINLINE_METHOD(DWORD, Log_IfWin32ErrorMsg)
(__R_CONDITIONAL_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (FAILED_WIN32(err)) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_Win32Msg)(__R_CONDITIONAL_NOINLINE_FN_CALL err, formatString, argList);
}
return err;
}
__R_CONDITIONAL_NOINLINE_METHOD(HANDLE, Log_IfHandleInvalidMsg)
(__R_CONDITIONAL_FN_PARAMS HANDLE handle, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (handle == INVALID_HANDLE_VALUE) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return handle;
}
__R_CONDITIONAL_NOINLINE_METHOD(HANDLE, Log_IfHandleNullMsg)
(__R_CONDITIONAL_FN_PARAMS HANDLE handle, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (handle == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return handle;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(PointerT, Log_IfNullAllocMsg)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_NullAllocMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL_ONLY, formatString, argList);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(void, Log_IfNullAllocMsg)
(__R_CONDITIONAL_FN_PARAMS const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_NullAllocMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL_ONLY, formatString, argList);
}
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Log_HrIfMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Log_HrIfFalseMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(PointerT, Log_HrIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(void, Log_HrIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Log_GetLastErrorIfMsg)
(__R_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Log_GetLastErrorIfFalseMsg)
(__R_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(PointerT, Log_GetLastErrorIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(void, Log_GetLastErrorIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
}
__R_CONDITIONAL_NOINLINE_METHOD(NTSTATUS, Log_IfNtStatusFailedMsg)
(__R_CONDITIONAL_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (FAILED_NTSTATUS(status)) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Log_NtStatusMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL status, formatString, argList);
}
return status;
}
} // namespace __R_NS_NAME
namespace __RFF_NS_NAME {
//*****************************************************************************
// FailFast Macros
//*****************************************************************************
__RFF_DIRECT_NORET_METHOD(void, FailFast_Hr)(__RFF_DIRECT_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Hr(__RFF_DIRECT_FN_CALL FailureType::FailFast, hr);
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_Win32)(__RFF_DIRECT_FN_PARAMS DWORD err) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Win32(__RFF_DIRECT_FN_CALL FailureType::FailFast, err);
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_GetLastError)(__RFF_DIRECT_FN_PARAMS_ONLY) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_GetLastError(__RFF_DIRECT_FN_CALL FailureType::FailFast);
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_NtStatus)(__RFF_DIRECT_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_NtStatus(__RFF_DIRECT_FN_CALL FailureType::FailFast, status);
}
__RFF_INTERNAL_NORET_METHOD(_FailFast_Hr)(__RFF_INTERNAL_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Hr(__RFF_INTERNAL_FN_CALL FailureType::FailFast, hr);
}
__RFF_INTERNAL_NORET_METHOD(_FailFast_GetLastError)(__RFF_INTERNAL_FN_PARAMS_ONLY) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_GetLastError(__RFF_INTERNAL_FN_CALL FailureType::FailFast);
}
__RFF_INTERNAL_NORET_METHOD(_FailFast_Win32)(__RFF_INTERNAL_FN_PARAMS DWORD err) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Win32(__RFF_INTERNAL_FN_CALL FailureType::FailFast, err);
}
__RFF_INTERNAL_NORET_METHOD(_FailFast_NullAlloc)(__RFF_INTERNAL_FN_PARAMS_ONLY) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Hr(__RFF_INTERNAL_FN_CALL FailureType::FailFast, E_OUTOFMEMORY);
}
__RFF_INTERNAL_NORET_METHOD(_FailFast_NtStatus)(__RFF_INTERNAL_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_NtStatus(__RFF_INTERNAL_FN_CALL FailureType::FailFast, status);
}
__RFF_CONDITIONAL_METHOD(HRESULT, FailFast_IfFailed)(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr) WI_NOEXCEPT {
if (FAILED(hr)) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Hr)(__RFF_CONDITIONAL_FN_CALL hr);
}
return hr;
}
__RFF_CONDITIONAL_METHOD(BOOL, FailFast_IfWin32BoolFalse)(__RFF_CONDITIONAL_FN_PARAMS BOOL ret) WI_NOEXCEPT {
if (!ret) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_GetLastError)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return ret;
}
__RFF_CONDITIONAL_METHOD(DWORD, FailFast_IfWin32Error)(__RFF_CONDITIONAL_FN_PARAMS DWORD err) WI_NOEXCEPT {
if (FAILED_WIN32(err)) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Win32)(__RFF_CONDITIONAL_FN_CALL err);
}
return err;
}
__RFF_CONDITIONAL_METHOD(HANDLE, FailFast_IfHandleInvalid)(__RFF_CONDITIONAL_FN_PARAMS HANDLE handle) WI_NOEXCEPT {
if (handle == INVALID_HANDLE_VALUE) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_GetLastError)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return handle;
}
__RFF_CONDITIONAL_METHOD(RESULT_NORETURN_NULL HANDLE, FailFast_IfHandleNull)(__RFF_CONDITIONAL_FN_PARAMS HANDLE handle) WI_NOEXCEPT {
if (handle == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_GetLastError)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return handle;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_IfNullAlloc)
(__RFF_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_NullAlloc)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_IfNullAlloc)
(__RFF_CONDITIONAL_FN_PARAMS const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_NullAlloc)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
}
__RFF_CONDITIONAL_METHOD(bool, FailFast_HrIf)(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) WI_NOEXCEPT {
if (condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Hr)(__RFF_CONDITIONAL_FN_CALL hr);
}
return condition;
}
__RFF_CONDITIONAL_METHOD(bool, FailFast_HrIfFalse)(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) WI_NOEXCEPT {
if (!condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Hr)(__RFF_CONDITIONAL_FN_CALL hr);
}
return condition;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_HrIfNull)
(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Hr)(__RFF_CONDITIONAL_FN_CALL hr);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_HrIfNull)
(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Hr)(__RFF_CONDITIONAL_FN_CALL hr);
}
}
__RFF_CONDITIONAL_METHOD(bool, FailFast_GetLastErrorIf)(__RFF_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT {
if (condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_GetLastError)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
__RFF_CONDITIONAL_METHOD(bool, FailFast_GetLastErrorIfFalse)(__RFF_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT {
if (!condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_GetLastError)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_GetLastErrorIfNull)
(__RFF_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_GetLastError)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_GetLastErrorIfNull)
(__RFF_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_GetLastError)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
}
__RFF_CONDITIONAL_METHOD(NTSTATUS, FailFast_IfNtStatusFailed)(__RFF_CONDITIONAL_FN_PARAMS NTSTATUS status) WI_NOEXCEPT {
if (FAILED_NTSTATUS(status)) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_NtStatus)(__RFF_CONDITIONAL_FN_CALL status);
}
return status;
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_HrMsg)
(__RFF_DIRECT_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__RFF_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__RFF_DIRECT_FN_CALL FailureType::FailFast, hr, formatString, argList);
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_Win32Msg)
(__RFF_DIRECT_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__RFF_FN_LOCALS;
wil::details::ReportFailure_Win32Msg(__RFF_DIRECT_FN_CALL FailureType::FailFast, err, formatString, argList);
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_GetLastErrorMsg)
(__RFF_DIRECT_FN_PARAMS _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__RFF_FN_LOCALS;
wil::details::ReportFailure_GetLastErrorMsg(__RFF_DIRECT_FN_CALL FailureType::FailFast, formatString, argList);
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_NtStatusMsg)
(__RFF_DIRECT_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__RFF_FN_LOCALS;
wil::details::ReportFailure_NtStatusMsg(__RFF_DIRECT_FN_CALL FailureType::FailFast, status, formatString, argList);
}
__RFF_INTERNAL_NOINLINE_NORET_METHOD(_FailFast_HrMsg)
(__RFF_INTERNAL_NOINLINE_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__RFF_INTERNAL_NOINLINE_FN_CALL FailureType::FailFast, hr, formatString, argList);
}
__RFF_INTERNAL_NOINLINE_NORET_METHOD(_FailFast_GetLastErrorMsg)
(__RFF_INTERNAL_NOINLINE_FN_PARAMS _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_GetLastErrorMsg(__RFF_INTERNAL_NOINLINE_FN_CALL FailureType::FailFast, formatString, argList);
}
__RFF_INTERNAL_NOINLINE_NORET_METHOD(_FailFast_Win32Msg)
(__RFF_INTERNAL_NOINLINE_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Win32Msg(__RFF_INTERNAL_NOINLINE_FN_CALL FailureType::FailFast, err, formatString, argList);
}
__RFF_INTERNAL_NOINLINE_NORET_METHOD(_FailFast_NullAllocMsg)
(__RFF_INTERNAL_NOINLINE_FN_PARAMS _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__RFF_INTERNAL_NOINLINE_FN_CALL FailureType::FailFast, E_OUTOFMEMORY, formatString, argList);
}
__RFF_INTERNAL_NOINLINE_NORET_METHOD(_FailFast_NtStatusMsg)
(__RFF_INTERNAL_NOINLINE_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_NtStatusMsg(__RFF_INTERNAL_NOINLINE_FN_CALL FailureType::FailFast, status, formatString, argList);
}
__RFF_CONDITIONAL_NOINLINE_METHOD(HRESULT, FailFast_IfFailedMsg)
(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (FAILED(hr)) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_HrMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return hr;
}
__RFF_CONDITIONAL_NOINLINE_METHOD(BOOL, FailFast_IfWin32BoolFalseMsg)
(__RFF_CONDITIONAL_FN_PARAMS BOOL ret, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (!ret) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_GetLastErrorMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return ret;
}
__RFF_CONDITIONAL_NOINLINE_METHOD(DWORD, FailFast_IfWin32ErrorMsg)
(__RFF_CONDITIONAL_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (FAILED_WIN32(err)) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_Win32Msg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL err, formatString, argList);
}
return err;
}
__RFF_CONDITIONAL_NOINLINE_METHOD(HANDLE, FailFast_IfHandleInvalidMsg)
(__RFF_CONDITIONAL_FN_PARAMS HANDLE handle, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (handle == INVALID_HANDLE_VALUE) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_GetLastErrorMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return handle;
}
__RFF_CONDITIONAL_NOINLINE_METHOD(RESULT_NORETURN_NULL HANDLE, FailFast_IfHandleNullMsg)
(__RFF_CONDITIONAL_FN_PARAMS HANDLE handle, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (handle == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_GetLastErrorMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return handle;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_IfNullAllocMsg)
(__RFF_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_NullAllocMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL_ONLY, formatString, argList);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_IfNullAllocMsg)
(__RFF_CONDITIONAL_FN_PARAMS const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_NullAllocMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL_ONLY, formatString, argList);
}
}
__RFF_CONDITIONAL_NOINLINE_METHOD(bool, FailFast_HrIfMsg)
(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (condition) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_HrMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
__RFF_CONDITIONAL_NOINLINE_METHOD(bool, FailFast_HrIfFalseMsg)
(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_HrMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_HrIfNullMsg)
(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_HrMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_HrIfNullMsg)
(__RFF_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_HrMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
}
__RFF_CONDITIONAL_NOINLINE_METHOD(bool, FailFast_GetLastErrorIfMsg)
(__RFF_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (condition) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_GetLastErrorMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
__RFF_CONDITIONAL_NOINLINE_METHOD(bool, FailFast_GetLastErrorIfFalseMsg)
(__RFF_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_GetLastErrorMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_GetLastErrorIfNullMsg)
(__RFF_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_GetLastErrorMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_GetLastErrorIfNullMsg)
(__RFF_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_GetLastErrorMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
}
__RFF_CONDITIONAL_NOINLINE_METHOD(NTSTATUS, FailFast_IfNtStatusFailedMsg)
(__RFF_CONDITIONAL_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (FAILED_NTSTATUS(status)) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_NtStatusMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL status, formatString, argList);
}
return status;
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_Unexpected)(__RFF_DIRECT_FN_PARAMS_ONLY) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Hr(__RFF_DIRECT_FN_CALL FailureType::FailFast, E_UNEXPECTED);
}
__RFF_INTERNAL_NORET_METHOD(_FailFast_Unexpected)(__RFF_INTERNAL_FN_PARAMS_ONLY) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_Hr(__RFF_INTERNAL_FN_CALL FailureType::FailFast, E_UNEXPECTED);
}
__RFF_CONDITIONAL_METHOD(bool, FailFast_If)(__RFF_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT {
if (condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Unexpected)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
__RFF_CONDITIONAL_METHOD(bool, FailFast_IfFalse)(__RFF_CONDITIONAL_FN_PARAMS bool condition) WI_NOEXCEPT {
if (!condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Unexpected)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_IfNull)
(__RFF_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Unexpected)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_IfNull)
(__RFF_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFast_Unexpected)(__RFF_CONDITIONAL_FN_CALL_ONLY);
}
}
__RFF_DIRECT_NORET_METHOD(void, FailFast_UnexpectedMsg)
(__RFF_DIRECT_FN_PARAMS _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
va_list argList;
va_start(argList, formatString);
__RFF_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__RFF_DIRECT_FN_CALL FailureType::FailFast, E_UNEXPECTED, formatString, argList);
}
__RFF_INTERNAL_NOINLINE_NORET_METHOD(_FailFast_UnexpectedMsg)
(__RFF_INTERNAL_NOINLINE_FN_PARAMS _Printf_format_string_ PCSTR formatString, va_list argList) WI_NOEXCEPT {
__RFF_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__RFF_INTERNAL_NOINLINE_FN_CALL FailureType::FailFast, E_UNEXPECTED, formatString, argList);
}
__RFF_CONDITIONAL_NOINLINE_METHOD(bool, FailFast_IfMsg)
(__RFF_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (condition) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_UnexpectedMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
__RFF_CONDITIONAL_NOINLINE_METHOD(bool, FailFast_IfFalseMsg)
(__RFF_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_UnexpectedMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFast_IfNullMsg)
(__RFF_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_UnexpectedMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFast_IfNullMsg)
(__RFF_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) WI_NOEXCEPT {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__RFF_CALL_INTERNAL_NOINLINE_METHOD(_FailFast_UnexpectedMsg)(__RFF_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
}
//*****************************************************************************
// FailFast Immediate Macros
//*****************************************************************************
__RFF_DIRECT_NORET_METHOD(void, FailFastImmediate_Unexpected)() WI_NOEXCEPT {
RESULT_RAISE_FAST_FAIL_EXCEPTION;
}
__RFF_INTERNAL_NORET_METHOD(_FailFastImmediate_Unexpected)() WI_NOEXCEPT {
RESULT_RAISE_FAST_FAIL_EXCEPTION;
}
__RFF_CONDITIONAL_METHOD(HRESULT, FailFastImmediate_IfFailed)(HRESULT hr) WI_NOEXCEPT {
if (FAILED(hr)) {
__RFF_CALL_INTERNAL_METHOD(_FailFastImmediate_Unexpected)();
}
return hr;
}
__RFF_CONDITIONAL_METHOD(bool, FailFastImmediate_If)(bool condition) WI_NOEXCEPT {
if (condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFastImmediate_Unexpected)();
}
return condition;
}
__RFF_CONDITIONAL_METHOD(bool, FailFastImmediate_IfFalse)(bool condition) WI_NOEXCEPT {
if (!condition) {
__RFF_CALL_INTERNAL_METHOD(_FailFastImmediate_Unexpected)();
}
return condition;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, FailFastImmediate_IfNull)
(_Pre_maybenull_ PointerT pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFastImmediate_Unexpected)();
}
return pointer;
}
template <__RFF_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__RFF_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, FailFastImmediate_IfNull)
(_In_opt_ const PointerT& pointer) WI_NOEXCEPT {
if (pointer == nullptr) {
__RFF_CALL_INTERNAL_METHOD(_FailFastImmediate_Unexpected)();
}
}
__RFF_CONDITIONAL_METHOD(NTSTATUS, FailFastImmediate_IfNtStatusFailed)(NTSTATUS status) WI_NOEXCEPT {
if (FAILED_NTSTATUS(status)) {
__RFF_CALL_INTERNAL_METHOD(_FailFastImmediate_Unexpected)();
}
return status;
}
} // namespace __RFF_NS_NAME
namespace __R_NS_NAME {
//*****************************************************************************
// Exception Macros
//*****************************************************************************
#ifdef WIL_ENABLE_EXCEPTIONS
__R_DIRECT_NORET_METHOD(void, Throw_Hr)(__R_DIRECT_FN_PARAMS HRESULT hr) {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_DIRECT_FN_CALL FailureType::Exception, hr);
}
__R_DIRECT_NORET_METHOD(void, Throw_Win32)(__R_DIRECT_FN_PARAMS DWORD err) {
__R_FN_LOCALS;
wil::details::ReportFailure_Win32(__R_DIRECT_FN_CALL FailureType::Exception, err);
}
__R_DIRECT_NORET_METHOD(void, Throw_GetLastError)(__R_DIRECT_FN_PARAMS_ONLY) {
__R_FN_LOCALS;
wil::details::ReportFailure_GetLastError(__R_DIRECT_FN_CALL FailureType::Exception);
}
__R_DIRECT_NORET_METHOD(void, Throw_NtStatus)(__R_DIRECT_FN_PARAMS NTSTATUS status) {
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatus(__R_DIRECT_FN_CALL FailureType::Exception, status);
}
__R_INTERNAL_NORET_METHOD(_Throw_Hr)(__R_INTERNAL_FN_PARAMS HRESULT hr) {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_INTERNAL_FN_CALL FailureType::Exception, hr);
}
__R_INTERNAL_NORET_METHOD(_Throw_GetLastError)(__R_INTERNAL_FN_PARAMS_ONLY) {
__R_FN_LOCALS;
wil::details::ReportFailure_GetLastError(__R_INTERNAL_FN_CALL FailureType::Exception);
}
__R_INTERNAL_NORET_METHOD(_Throw_Win32)(__R_INTERNAL_FN_PARAMS DWORD err) {
__R_FN_LOCALS;
wil::details::ReportFailure_Win32(__R_INTERNAL_FN_CALL FailureType::Exception, err);
}
__R_INTERNAL_NORET_METHOD(_Throw_NullAlloc)(__R_INTERNAL_FN_PARAMS_ONLY) {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_INTERNAL_FN_CALL FailureType::Exception, E_OUTOFMEMORY);
}
__R_INTERNAL_NORET_METHOD(_Throw_NtStatus)(__R_INTERNAL_FN_PARAMS NTSTATUS status) {
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatus(__R_INTERNAL_FN_CALL FailureType::Exception, status);
}
__R_CONDITIONAL_METHOD(HRESULT, Throw_IfFailed)(__R_CONDITIONAL_FN_PARAMS HRESULT hr) {
if (FAILED(hr)) {
__R_CALL_INTERNAL_METHOD(_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return hr;
}
__R_CONDITIONAL_METHOD(BOOL, Throw_IfWin32BoolFalse)(__R_CONDITIONAL_FN_PARAMS BOOL ret) {
if (!ret) {
__R_CALL_INTERNAL_METHOD(_Throw_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return ret;
}
__R_CONDITIONAL_METHOD(DWORD, Throw_IfWin32Error)(__R_CONDITIONAL_FN_PARAMS DWORD err) {
if (FAILED_WIN32(err)) {
__R_CALL_INTERNAL_METHOD(_Throw_Win32)(__R_CONDITIONAL_FN_CALL err);
}
return err;
}
__R_CONDITIONAL_METHOD(HANDLE, Throw_IfHandleInvalid)(__R_CONDITIONAL_FN_PARAMS HANDLE handle) {
if (handle == INVALID_HANDLE_VALUE) {
__R_CALL_INTERNAL_METHOD(_Throw_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return handle;
}
__R_CONDITIONAL_METHOD(RESULT_NORETURN_NULL HANDLE, Throw_IfHandleNull)(__R_CONDITIONAL_FN_PARAMS HANDLE handle) {
if (handle == nullptr) {
__R_CALL_INTERNAL_METHOD(_Throw_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return handle;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Throw_IfNullAlloc)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Throw_NullAlloc)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(void, Throw_IfNullAlloc)
(__R_CONDITIONAL_FN_PARAMS const PointerT& pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Throw_NullAlloc)(__R_CONDITIONAL_FN_CALL_ONLY);
}
}
__R_CONDITIONAL_METHOD(bool, Throw_HrIf)(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) {
if (condition) {
__R_CALL_INTERNAL_METHOD(_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return condition;
}
__R_CONDITIONAL_METHOD(bool, Throw_HrIfFalse)(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) {
if (!condition) {
__R_CALL_INTERNAL_METHOD(_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Throw_HrIfNull)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(void, Throw_HrIfNull)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
}
__R_CONDITIONAL_METHOD(bool, Throw_GetLastErrorIf)(__R_CONDITIONAL_FN_PARAMS bool condition) {
if (condition) {
__R_CALL_INTERNAL_METHOD(_Throw_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
__R_CONDITIONAL_METHOD(bool, Throw_GetLastErrorIfFalse)(__R_CONDITIONAL_FN_PARAMS bool condition) {
if (!condition) {
__R_CALL_INTERNAL_METHOD(_Throw_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Throw_GetLastErrorIfNull)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Throw_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, Throw_GetLastErrorIfNull)
(__R_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Throw_GetLastError)(__R_CONDITIONAL_FN_CALL_ONLY);
}
}
__R_CONDITIONAL_METHOD(NTSTATUS, Throw_IfNtStatusFailed)(__R_CONDITIONAL_FN_PARAMS NTSTATUS status) {
if (FAILED_NTSTATUS(status)) {
__R_CALL_INTERNAL_METHOD(_Throw_NtStatus)(__R_CONDITIONAL_FN_CALL status);
}
return status;
}
__R_DIRECT_METHOD(void, Throw_HrMsg)(__R_DIRECT_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_DIRECT_FN_CALL FailureType::Exception, hr, formatString, argList);
}
__R_DIRECT_METHOD(void, Throw_Win32Msg)(__R_DIRECT_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_Win32Msg(__R_DIRECT_FN_CALL FailureType::Exception, err, formatString, argList);
}
__R_DIRECT_METHOD(void, Throw_GetLastErrorMsg)(__R_DIRECT_FN_PARAMS _Printf_format_string_ PCSTR formatString, ...) {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_GetLastErrorMsg(__R_DIRECT_FN_CALL FailureType::Exception, formatString, argList);
}
__R_DIRECT_METHOD(void, Throw_NtStatusMsg)(__R_DIRECT_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, ...) {
va_list argList;
va_start(argList, formatString);
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatusMsg(__R_DIRECT_FN_CALL FailureType::Exception, status, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Throw_HrMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, va_list argList) {
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Exception, hr, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS _Printf_format_string_ PCSTR formatString, va_list argList) {
__R_FN_LOCALS;
wil::details::ReportFailure_GetLastErrorMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Exception, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Throw_Win32Msg)
(__R_INTERNAL_NOINLINE_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, va_list argList) {
__R_FN_LOCALS;
wil::details::ReportFailure_Win32Msg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Exception, err, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Throw_NullAllocMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS _Printf_format_string_ PCSTR formatString, va_list argList) {
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Exception, E_OUTOFMEMORY, formatString, argList);
}
__R_INTERNAL_NOINLINE_METHOD(_Throw_NtStatusMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, va_list argList) {
__R_FN_LOCALS;
wil::details::ReportFailure_NtStatusMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::Exception, status, formatString, argList);
}
__R_CONDITIONAL_NOINLINE_METHOD(HRESULT, Throw_IfFailedMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) {
if (FAILED(hr)) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return hr;
}
__R_CONDITIONAL_NOINLINE_METHOD(BOOL, Throw_IfWin32BoolFalseMsg)
(__R_CONDITIONAL_FN_PARAMS BOOL ret, _Printf_format_string_ PCSTR formatString, ...) {
if (!ret) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return ret;
}
__R_CONDITIONAL_NOINLINE_METHOD(DWORD, Throw_IfWin32ErrorMsg)
(__R_CONDITIONAL_FN_PARAMS DWORD err, _Printf_format_string_ PCSTR formatString, ...) {
if (FAILED_WIN32(err)) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_Win32Msg)(__R_CONDITIONAL_NOINLINE_FN_CALL err, formatString, argList);
}
return err;
}
__R_CONDITIONAL_NOINLINE_METHOD(HANDLE, Throw_IfHandleInvalidMsg)
(__R_CONDITIONAL_FN_PARAMS HANDLE handle, _Printf_format_string_ PCSTR formatString, ...) {
if (handle == INVALID_HANDLE_VALUE) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return handle;
}
__R_CONDITIONAL_NOINLINE_METHOD(RESULT_NORETURN_NULL HANDLE, Throw_IfHandleNullMsg)
(__R_CONDITIONAL_FN_PARAMS HANDLE handle, _Printf_format_string_ PCSTR formatString, ...) {
if (handle == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return handle;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Throw_IfNullAllocMsg)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_NullAllocMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL_ONLY, formatString, argList);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, Throw_IfNullAllocMsg)
(__R_CONDITIONAL_FN_PARAMS const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_NullAllocMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL_ONLY, formatString, argList);
}
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Throw_HrIfMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) {
if (condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Throw_HrIfFalseMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Throw_HrIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(void, Throw_HrIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Throw_GetLastErrorIfMsg)
(__R_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) {
if (condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Throw_GetLastErrorIfFalseMsg)
(__R_CONDITIONAL_FN_PARAMS bool condition, _Printf_format_string_ PCSTR formatString, ...) {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Throw_GetLastErrorIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL void, Throw_GetLastErrorIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_GetLastErrorMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL formatString, argList);
}
}
__R_CONDITIONAL_NOINLINE_METHOD(NTSTATUS, Throw_IfNtStatusFailedMsg)
(__R_CONDITIONAL_FN_PARAMS NTSTATUS status, _Printf_format_string_ PCSTR formatString, ...) {
if (FAILED_NTSTATUS(status)) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Throw_NtStatusMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL status, formatString, argList);
}
return status;
}
__R_DIRECT_NORET_METHOD(void, Objc_Throw_HrMsg)(__R_DIRECT_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) {
__R_FN_LOCALS;
va_list argList;
va_start(argList, formatString);
wil::details::ReportFailure_HrMsg(__R_DIRECT_FN_CALL FailureType::ObjCException, hr, formatString, argList);
}
__R_INTERNAL_NORET_METHOD(_Objc_Throw_Hr)(__R_INTERNAL_FN_PARAMS HRESULT hr) {
__R_FN_LOCALS;
wil::details::ReportFailure_Hr(__R_DIRECT_FN_CALL FailureType::ObjCException, hr);
}
__R_CONDITIONAL_METHOD(void, Objc_Throw_IfFailed)(__R_CONDITIONAL_FN_PARAMS HRESULT hr) {
if (FAILED(hr)) {
__R_CALL_INTERNAL_METHOD(_Objc_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
}
__R_INTERNAL_NOINLINE_METHOD(_Objc_Throw_HrMsg)
(__R_INTERNAL_NOINLINE_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, va_list argList) {
__R_FN_LOCALS;
wil::details::ReportFailure_HrMsg(__R_INTERNAL_NOINLINE_FN_CALL FailureType::ObjCException, hr, formatString, argList);
}
__R_CONDITIONAL_METHOD(void, Objc_Throw_IfFailedMsg)(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Printf_format_string_ PCSTR formatString, ...) {
if (FAILED(hr)) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Objc_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
}
__R_CONDITIONAL_METHOD(bool, Objc_Throw_HrIf)(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) {
if (condition) {
__R_CALL_INTERNAL_METHOD(_Objc_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return condition;
}
__R_CONDITIONAL_METHOD(bool, Objc_Throw_HrIfFalse)(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition) {
if (!condition) {
__R_CALL_INTERNAL_METHOD(_Objc_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return condition;
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Objc_Throw_HrIfMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) {
if (condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Objc_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
__R_CONDITIONAL_NOINLINE_METHOD(bool, Objc_Throw_HrIfFalseMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, bool condition, _Printf_format_string_ PCSTR formatString, ...) {
if (!condition) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Objc_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return condition;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Objc_Throw_HrIfNull)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Objc_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_TEMPLATE_METHOD(void, Objc_Throw_HrIfNull)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer) {
if (pointer == nullptr) {
__R_CALL_INTERNAL_METHOD(_Objc_Throw_Hr)(__R_CONDITIONAL_FN_CALL hr);
}
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_NOT_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(RESULT_NORETURN_NULL PointerT, Objc_Throw_HrIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _Pre_maybenull_ PointerT pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Objc_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
return pointer;
}
template <__R_CONDITIONAL_PARTIAL_TEMPLATE typename PointerT, __R_ENABLE_IF_IS_CLASS(PointerT)>
__R_CONDITIONAL_NOINLINE_TEMPLATE_METHOD(void, Objc_Throw_HrIfNullMsg)
(__R_CONDITIONAL_FN_PARAMS HRESULT hr, _In_opt_ const PointerT& pointer, _Printf_format_string_ PCSTR formatString, ...) {
if (pointer == nullptr) {
va_list argList;
va_start(argList, formatString);
__R_CALL_INTERNAL_NOINLINE_METHOD(_Objc_Throw_HrMsg)(__R_CONDITIONAL_NOINLINE_FN_CALL hr, formatString, argList);
}
}
#endif // WIL_ENABLE_EXCEPTIONS
} // __R_NS_NAME namespace
} // details namespace
//! @endcond
//*****************************************************************************
// Error Handling Policies to switch between error-handling style
//*****************************************************************************
// The following policies are used as template policies for components that can support exception, fail-fast, and
// error-code based modes.
// Use for classes which should return HRESULTs as their error-handling policy
struct err_returncode_policy {
typedef HRESULT result;
__forceinline static HRESULT Win32BOOL(BOOL fReturn) {
RETURN_IF_WIN32_BOOL_FALSE(fReturn);
return S_OK;
}
__forceinline static HRESULT Win32Handle(HANDLE h, _Out_ HANDLE* ph) {
*ph = h;
RETURN_IF_HANDLE_NULL(h);
return S_OK;
}
_Post_satisfies_(return == hr) __forceinline static HRESULT HResult(HRESULT hr) {
RETURN_HR(hr);
}
__forceinline static HRESULT LastError() {
RETURN_LAST_ERROR();
}
__forceinline static HRESULT LastErrorIfFalse(bool condition) {
if (!condition) {
RETURN_LAST_ERROR();
}
return S_OK;
}
_Post_satisfies_(return == S_OK) __forceinline static HRESULT OK() {
return S_OK;
}
};
// Use for classes which fail-fast on errors
struct err_failfast_policy {
typedef _Return_type_success_(true) void result;
__forceinline static result Win32BOOL(BOOL fReturn) {
FAIL_FAST_IF_WIN32_BOOL_FALSE(fReturn);
}
__forceinline static result Win32Handle(HANDLE h, _Out_ HANDLE* ph) {
*ph = h;
FAIL_FAST_IF_HANDLE_NULL(h);
}
_When_(FAILED(hr), _Analysis_noreturn_) __forceinline static result HResult(HRESULT hr) {
FAIL_FAST_IF_FAILED(hr);
}
__forceinline static result LastError() {
FAIL_FAST_LAST_ERROR();
}
__forceinline static result LastErrorIfFalse(bool condition) {
if (!condition) {
FAIL_FAST_LAST_ERROR();
}
}
__forceinline static result OK() {
}
};
#ifdef WIL_ENABLE_EXCEPTIONS
// Use for classes which should return through exceptions as their error-handling policy
struct err_exception_policy {
typedef _Return_type_success_(true) void result;
__forceinline static result Win32BOOL(BOOL fReturn) {
THROW_IF_WIN32_BOOL_FALSE(fReturn);
}
__forceinline static result Win32Handle(HANDLE h, _Out_ HANDLE* ph) {
*ph = h;
THROW_IF_HANDLE_NULL(h);
}
_When_(FAILED(hr), _Analysis_noreturn_) __forceinline static result HResult(HRESULT hr) {
THROW_IF_FAILED(hr);
}
__forceinline static result LastError() {
THROW_LAST_ERROR();
}
__forceinline static result LastErrorIfFalse(bool condition) {
if (!condition) {
THROW_LAST_ERROR();
}
}
__forceinline static result OK() {
}
};
#endif
} // namespace wil
#if defined(__OBJC__) && !defined(WIL_IGNORE_OBJC_EXCEPTIONS)
#import <Foundation/NSError.h>
#import <Foundation/NSNumber.h>
#import <Foundation/NSString.h>
#import <Foundation/NSException.h>
#import <Foundation/NSDictionary.h>
#import "FoundationErrorHandling.h"
namespace {
static NSString* const g_winobjcDomain = @"WinObjCErrorDomain";
static NSString* const g_hresultDomain = @"HRESULTErrorDomain";
static NSString* const g_NSHResultErrorDictKey = @"hresult";
NSString* _NSStringFromHResult(HRESULT hr) {
wchar_t errorText[256];
errorText[0] = L'\0';
auto strLen = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
errorText,
ARRAYSIZE(errorText),
nullptr);
return [NSString stringWithCharacters:reinterpret_cast<const unichar*>(errorText) length:strLen];
}
// Create the extra information we can communicate as part of the exception:
NSDictionary* _createFailureInfoDict(const wil::FailureInfo& fi) {
return @{
@"file" : [NSString stringWithUTF8String:fi.pszFile],
@"function" : [NSString stringWithUTF8String:fi.pszFunction],
@"line" : [NSNumber numberWithInt:fi.uLineNumber],
g_NSHResultErrorDictKey : [NSNumber numberWithInt:fi.hr],
NSLocalizedDescriptionKey : [NSString stringWithFormat:@"0x%x: %@", fi.hr, _NSStringFromHResult(fi.hr)],
};
}
// Construct an NSError for the out parameter representing a failure info from WRL:
NSError* _NSErrorFromFailureInfo(const wil::FailureInfo& fi) {
return [NSError errorWithDomain:g_hresultDomain code:fi.hr userInfo:_createFailureInfoDict(fi)];
}
// This is a helper to create NSExceptions from HRESULTs:
NSException* _NSExceptionFromFailureInfo(const wil::FailureInfo& fi) {
NSString* msg = [NSString string];
if (fi.pszMessage) {
msg = [NSString stringWithCharacters:reinterpret_cast<const unichar*>(fi.pszMessage) length:wcslen(fi.pszMessage)];
}
return [NSException _exceptionWithHRESULT:fi.hr reason:msg userInfo:_createFailureInfoDict(fi)];
}
bool _resultFromUncaughtExceptionObjC(HRESULT* out) {
try {
throw;
} catch (NSException* e) {
*out = [e _hresult];
return true;
}
return false;
}
void _rethrowAsNSException() {
try {
throw;
} catch (NSException*) {
// Already an NSException and we need to catch it so the catch (...) doesn't:
throw;
} catch (const wil::ResultException& re) {
@throw _NSExceptionFromFailureInfo(re.GetFailureInfo());
} catch (...) {
@throw [NSException _exceptionWithHRESULT:wil::ResultFromCaughtException()
reason:_NSStringFromHResult(wil::ResultFromCaughtException())
userInfo:nil];
}
}
void _objcThrowFailureInfo(const wil::FailureInfo& fi) {
@throw _NSExceptionFromFailureInfo(fi);
}
void __attribute__((unused)) _catchAndPopulateNSError(NSError** outError) {
NSError* error;
try {
throw;
} catch (NSException* e) {
unsigned errorCode = E_UNEXPECTED;
// If we have an hresult in our user dict, use that, otherwise this was unexpected:
NSNumber* hresultValue = e.userInfo[g_NSHResultErrorDictKey];
if (hresultValue) {
errorCode = [hresultValue unsignedIntValue];
}
error = [NSError errorWithDomain:g_winobjcDomain code:errorCode userInfo:e.userInfo];
} catch (const wil::ResultException& re) {
error = _NSErrorFromFailureInfo(re.GetFailureInfo());
} catch (...) {
error = [NSError errorWithDomain:g_hresultDomain code:wil::ResultFromCaughtException() userInfo:nil];
}
if (outError) {
*outError = error;
} else {
HRESULT code = error.code;
LOG_HR_MSG(code, "NSError occurred where caller is ignoring value: %hs", [[error description] UTF8String]);
}
}
void _rethrowNormalizedCaughtExceptionObjC(__R_FN_PARAMS_FULL, _In_opt_ PCWSTR message) {
try {
throw;
} catch (const wil::ResultException& re) {
// Report the exception
auto& failure = re.GetFailureInfo();
wil::details::ReportFailure(__R_FN_CALL_FULL,
wil::FailureType::Exception,
failure.hr,
message,
wil::details::ReportFailureOptions::SuppressAction);
// Convert to an NSException by re-throwing with the existing failure information to maintain as much context as we can.
wil::details::ReportFailure(failure.callerReturnAddress,
failure.uLineNumber,
failure.pszFile,
failure.pszFunction,
failure.pszCode,
failure.returnAddress,
wil::FailureType::Exception,
failure.hr,
failure.pszMessage,
wil::details::ReportFailureOptions::ForceObjCException);
} catch (NSException* e) {
wchar_t messageString[2048];
StringCchCopyW(messageString,
ARRAYSIZE(messageString),
reinterpret_cast<STRSAFE_LPCWSTR>([[e reason] cStringUsingEncoding:NSUnicodeStringEncoding]));
if (message) {
StringCchCatW(messageString, ARRAYSIZE(messageString), L" - ");
StringCchCatW(messageString, ARRAYSIZE(messageString), message);
}
// Report the exception
wil::details::ReportFailure(__R_FN_CALL_FULL,
wil::FailureType::Exception,
[e _hresult],
messageString,
wil::details::ReportFailureOptions::SuppressAction);
// In ObjC, NSException is our normalized exception...we can re-throw it.
throw;
} catch (std::bad_alloc const&) {
wil::details::ReportFailure(__R_FN_CALL_FULL, wil::FailureType::Exception, E_OUTOFMEMORY, message);
} catch (...) {
wil::details::RethrowUnknownCaughtException(__R_FN_CALL_FULL, message);
}
RESULT_RAISE_FAST_FAIL_EXCEPTION;
}
}
// Misspelling is intentional
WI_HEADER_INITITALIZATION_FUNCTION(InitializeObjCExceptions,
[] {
g_resultFromUncaughtExceptionObjC = _resultFromUncaughtExceptionObjC;
g_rethrowAsNSException = _rethrowAsNSException;
g_objcThrowFailureInfo = _objcThrowFailureInfo;
g_rethrowNormalizedCaughtExceptionObjC = _rethrowNormalizedCaughtExceptionObjC;
return 1;
});
#endif
#pragma warning(pop)
|
vkvenkat/WinObjC
|
Frameworks/include/wil/result.h
|
C
|
mit
| 238,327
|
'''
Copyright 2011 Jean-Baptiste B'edrune, Jean Sigwald
Using New BSD License:
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
#
# This code has since been edited to improve HFS parsing, add lzvn/lzfse support
# and is now a part of the mac_apt framework
#
import os
import mmap
import sys
import struct
import tempfile
import zlib
import pytsk3
import logging
from plugins.helpers.common import CommonFunctions
from plugins.helpers.btree import AttributesTree, CatalogTree, ExtentsOverflowTree
from plugins.helpers.structs import *
log = logging.getLogger('MAIN.HELPERS.HFS_ALT')
lzfse_capable = False
try:
import liblzfse
lzfse_capable = True
except ImportError:
print("liblzfse not found. Won't decompress lzfse/lzvn streams")
def write_file(filename,data):
f = open(filename, "wb")
f.write(data)
f.close()
def lzvn_decompress(compressed_stream, compressed_size, uncompressed_size): #TODO: Move to a class!
'''Adds Prefix and Postfix bytes as required by decompressor,
then decompresses and returns uncompressed bytes buffer
'''
header = b'bvxn' + struct.pack('<I', uncompressed_size) + struct.pack('<I', compressed_size)
footer = b'bvx$'
return liblzfse.decompress(header + compressed_stream + footer)
class HFSFile(object):
def __init__(self, volume, hfsplusfork, fileID, deleted=False):
self.volume = volume
self.blockSize = volume.blockSize
self.fileID = fileID
self.totalBlocks = hfsplusfork.totalBlocks
self.logicalSize = hfsplusfork.logicalSize
self.extents = []
self.deleted = deleted
b = 0
for extent in hfsplusfork.HFSPlusExtentDescriptor:
self.extents.append(extent)
b += extent.blockCount
while b != hfsplusfork.totalBlocks:
#log.debug("extents overflow {}".format(b))
k,v = volume.getExtentsOverflowForFile(fileID, b)
if not v:
log.debug("extents overflow missing, startblock={}".format(b))
break
for extent in v:
self.extents.append(extent)
b += extent.blockCount
def copyOutFile(self, outputfile, truncate=True):
f = open(outputfile, "wb")
for i in range(self.totalBlocks):
f.write(self.readBlock(i))
if truncate:
f.truncate(self.logicalSize)
f.close()
'''def readAllBuffer(self, truncate=True):
r = b""
for i in range(self.totalBlocks):
r += self.readBlock(i)
if truncate:
r = r[:self.logicalSize]
return r
'''
def readAllBuffer(self, truncate=True, output_file=None):
'''Write to output_file if valid, else return a buffer of data.
Warning: If file size > 200 MiB, b'' is returned, file data is only written to output_file.
'''
r = b""
bs = self.volume.blockSize
blocks_max = 52428800 // bs # 50MB
for extent in self.extents:
if extent.blockCount == 0: continue
#if not self.deleted and self.fileID != kHFSAllocationFileID and not self.volume.isBlockInUse(lba):
# log.debug("FAIL, block "0x{:x}" not marked as used".format(n))
if extent.blockCount > blocks_max:
counter = blocks_max
remaining_blocks = extent.blockCount
start_address = extent.startBlock * bs
while remaining_blocks > 0:
num_blocks_to_read = min(blocks_max, remaining_blocks)
size = num_blocks_to_read * bs
data = self.volume.read(start_address, size)
if output_file:
output_file.write(data)
elif self.logicalSize < 209715200: # 200MiB
r += data
remaining_blocks -= num_blocks_to_read
start_address += size
else:
data = self.volume.read(extent.startBlock * bs, bs * extent.blockCount)
if output_file:
output_file.write(data)
elif self.logicalSize < 209715200: # 200MiB
r += data
if truncate:
if output_file:
output_file.truncate(self.logicalSize)
elif self.logicalSize < 209715200: # 200MiB
r = r[:self.logicalSize]
return r
def processBlock(self, block, lba):
return block
def readBlock(self, n):
bs = self.volume.blockSize
if n*bs > self.logicalSize:
raise ValueError("BLOCK OUT OF BOUNDS")
bc = 0
for extent in self.extents:
bc += extent.blockCount
if n < bc:
lba = extent.startBlock+(n-(bc-extent.blockCount))
if not self.deleted and self.fileID != kHFSAllocationFileID and not self.volume.isBlockInUse(lba):
raise ValueError("FAIL, block %x not marked as used" % n)
return self.processBlock(self.volume.read(lba*bs, bs), lba)
return b""
class HFSCompressedResourceFork(HFSFile):
def __init__(self, volume, hfsplusfork, fileID, compression_type, uncompressed_size):
super(HFSCompressedResourceFork,self).__init__(volume, hfsplusfork, fileID)
block0 = self.readBlock(0)
self.compression_type = compression_type
self.uncompressed_size = uncompressed_size
if compression_type in [8, 12]: # 8 is lzvn, 12 is lzfse
#only tested for 8
self.header = HFSPlusCmpfLZVNRsrcHead.parse(block0)
#print(self.header)
else:
self.header = HFSPlusCmpfRsrcHead.parse(block0)
#print(self.header)
self.blocks = HFSPlusCmpfRsrcBlockHead.parse(block0[self.header.headerSize:])
log.debug("HFSCompressedResourceFork numBlocks:{}".format(self.blocks.numBlocks))
#HAX, readblock not implemented
def readAllBuffer(self, truncate=True, output_file=None):
'''Warning: If output size > 200 MiB, b'' is returned, file data is only written to output_file.'''
if self.compression_type in [7, 8, 11, 12] and not lzfse_capable:
raise ValueError('LZFSE/LZVN compression detected, no decompressor available!')
if self.logicalSize >= 209715200:
temp_file = tempfile.SpooledTemporaryFile(209715200)
super(HFSCompressedResourceFork, self).readAllBuffer(True, temp_file)
temp_file.seek(0)
buff = mmap.mmap(temp_file.fileno(), 0) # memory mapped file to access as buffer
else:
buff = super(HFSCompressedResourceFork, self).readAllBuffer()
r = b""
if self.compression_type in [7, 11]: # lzvn or lzfse # Does it ever go here????
raise ValueError("Did not expect type " + str(self.compression_type) + " in resource fork")
try:
# The following is only for lzvn, not encountered lzfse yet!
data_start = self.header.headerSize
compressed_stream = buff[data_start:self.header.totalSize]
decompressed = lzvn_decompress(compressed_stream, self.header.totalSize - self.header.headerSize, self.uncompressed_size)
if output_file: output_file.write(decompressed)
elif self.uncompressed_size < 209715200: r += decompressed
except liblzfse.error as ex:
raise ValueError("Exception from lzfse_lzvn decompressor")
elif self.compression_type in [8, 12]: # lzvn or lzfse in 64k chunks
try:
# The following is only for lzvn, not encountered lzfse yet!
full_uncomp = self.uncompressed_size
chunk_uncomp = 65536
i = 0
src_offset = self.header.headerSize
for offset in self.header.chunkOffsets:
compressed_size = offset - src_offset
data = buff[src_offset:offset] #input_file.read(compressed_size)
src_offset = offset
if full_uncomp <= 65536:
chunk_uncomp = full_uncomp
else:
chunk_uncomp = 65536
if len(self.header.chunkOffsets) == i + 1: # last chunk
chunk_uncomp = full_uncomp - (65536 * i)
if chunk_uncomp < compressed_size and data[0] == 0x06:
decompressed = data[1:]
else:
decompressed = lzvn_decompress(data, compressed_size, chunk_uncomp)
if output_file: output_file.write(decompressed)
elif self.uncompressed_size < 209715200: r += decompressed
i += 1
except liblzfse.error as ex:
raise ValueError("Exception from lzfse_lzvn decompressor")
else:
base = self.header.headerSize + 4
for b in self.blocks.HFSPlusCmpfRsrcBlockArray:
decompressed = zlib.decompress(buff[base+b.offset:base+b.offset+b.size])
if output_file: output_file.write(decompressed)
elif self.uncompressed_size < 209715200: r += decompressed
if self.logicalSize >= 209715200:
mmap.close()
temp_file.close()
return r
class HFSVolume(object):
def __init__(self, pytsk_image, offset=0):
self.img = pytsk_image
self.offset = offset
try:
data = self.read(0, 0x1000)
self.header = HFSPlusVolumeHeader.parse(data[0x400:0x800])
assert self.header.signature == 0x4858 or self.header.signature == 0x482B
except AssertionError:
raise ValueError("Not an HFS+ image")
#self.is_hfsx = self.header.signature == 0x4858
self.blockSize = self.header.blockSize
self.allocationFile = HFSFile(self, self.header.allocationFile, kHFSAllocationFileID)
self.allocationBitmap = self.allocationFile.readAllBuffer()
self.extentsFile = HFSFile(self, self.header.extentsFile, kHFSExtentsFileID)
self.extentsTree = ExtentsOverflowTree(self.extentsFile)
self.catalogFile = HFSFile(self, self.header.catalogFile, kHFSCatalogFileID)
self.xattrFile = HFSFile(self, self.header.attributesFile, kHFSAttributesFileID)
self.catalogTree = CatalogTree(self.catalogFile)
self.xattrTree = AttributesTree(self.xattrFile)
self.hasJournal = self.header.attributes & (1 << kHFSVolumeJournaledBit)
def read(self, offset, size):
return self.img.read(self.offset + offset, size)
def volumeID(self):
return struct.pack(">LL", self.header.finderInfo[6], self.header.finderInfo[7])
def isBlockInUse(self, block):
thisByte = self.allocationBitmap[block // 8]
return (thisByte & (1 << (7 - (block % 8)))) != 0
def unallocatedBlocks(self):
for i in range(self.header.totalBlocks):
if not self.isBlockInUse(i):
yield i, self.read(i*self.blockSize, self.blockSize)
def getExtentsOverflowForFile(self, fileID, startBlock, forkType=kForkTypeData):
return self.extentsTree.searchExtents(fileID, forkType, startBlock)
def getXattr(self, fileID, name):
return self.xattrTree.searchXattr(fileID, name)
def getFileByPath(self, path):
return self.catalogTree.getRecordFromPath(path)
def getFinderDateAdded(self, path):
k,v = self.catalogTree.getRecordFromPath(path)
if k and v.recordType == kHFSPlusFileRecord:
return v.data.ExtendedFileInfo.finderDateAdded
elif k and v.recordType == kHFSPlusFolderRecord:
return v.data.ExtendedFolderInfo.finderDateAdded
return 0
def listFolderContents(self, path):
k,v = self.catalogTree.getRecordFromPath(path)
if not k or v.recordType != kHFSPlusFolderRecord:
return
for k,v in self.catalogTree.getFolderContents(v.data.folderID):
if v.recordType == kHFSPlusFolderRecord:
print(v.data.folderID, getString(k) + "/")
elif v.recordType == kHFSPlusFileRecord:
print(v.data.fileID, getString(k))
def listFinderData(self, path):
'''Returns finder data'''
finder_data = {}
k,v = self.catalogTree.getRecordFromPath(path)
date_added = 0
if k and v.recordType == kHFSPlusFileRecord:
date_added = v.data.ExtendedFileInfo.finderDateAdded
if v.data.FileInfo.fileType: finder_data['fileType'] = v.data.FileInfo.fileType
if v.data.FileInfo.fileCreator: finder_data['fileCreator'] = v.data.FileInfo.fileCreator
if v.data.FileInfo.finderFlags: finder_data['finderFlags'] = v.data.FileInfo.finderFlags
if v.data.ExtendedFileInfo.extendedFinderFlags: finder_data['extendedFinderFlags'] = v.data.ExtendedFileInfo.extendedFinderFlags
elif k and v.recordType == kHFSPlusFolderRecord:
date_added = v.data.ExtendedFolderInfo.finderDateAdded
if v.data.FolderInfo.finderFlags: finder_data['FinderFlags'] = v.data.FolderInfo.finderFlags
if v.data.ExtendedFolderInfo.extendedFinderFlags: finder_data['extendedFinderFlags'] = v.data.ExtendedFolderInfo.extendedFinderFlags
if date_added: finder_data['DateAdded'] = date_added
return finder_data
def getCnidForPath(self, path):
k,v = self.catalogTree.getRecordFromPath(path)
if not v:
raise ValueError("Path not found")
if k and v.recordType == kHFSPlusFileRecord:
return v.data.fileID
elif k and v.recordType == kHFSPlusFolderThreadRecord:
return v.data.folderID
def getXattrsByPath(self, path):
file_id = self.getCnidForPath(path)
return self.xattrTree.getAllXattrs(file_id)
def getXattrByPath(self, path, name):
file_id = self.getCnidForPath(path)
return self.getXattr(file_id, name)
''' Compression type in Xattr as per apple:
Source: https://opensource.apple.com/source/copyfile/copyfile-138/copyfile.c.auto.html
case 3: /* zlib-compressed data in xattr */
case 4: /* 64k chunked zlib-compressed data in resource fork */
case 7: /* LZVN-compressed data in xattr */
case 8: /* 64k chunked LZVN-compressed data in resource fork */
case 9: /* uncompressed data in xattr (similar to but not identical to CMP_Type1) */
case 10: /* 64k chunked uncompressed data in resource fork */
case 11: /* LZFSE-compressed data in xattr */
case 12: /* 64k chunked LZFSE-compressed data in resource fork */
/* valid compression type, we want to copy. */
break;
case 5: /* specifies de-dup within the generation store. Don't copy decmpfs xattr. */
copyfile_debug(3, "compression_type <5> on attribute com.apple.decmpfs for src file %s is not copied.",
s->src ? s->src : "(null string)");
continue;
case 6: /* unused */
'''
def readFile(self, path, output_file=None):
'''Reads file specified by 'path' and copies it out into output_file if valid, else returns as string.
Warning: If file is too large, over 200 MiB, then it will return b'', and only write to output_file.
'''
k,v = self.catalogTree.getRecordFromPath(path)
if not v:
raise ValueError("File not found")
data = b''
assert v.recordType == kHFSPlusFileRecord
xattr = self.getXattr(v.data.fileID, "com.apple.decmpfs")
if xattr:
decmpfs = HFSPlusDecmpfs.parse(xattr)
log.debug("decmpfs.compression_type={}".format(str(decmpfs.compression_type)))
if decmpfs.compression_type == 1:
data = xattr[16:]
if output_file: output_file.write(data)
elif decmpfs.compression_type == 3:
if decmpfs.uncompressed_size == len(xattr) - 16:
data = xattr[16:]
else:
data = zlib.decompress(xattr[16:])
if output_file: output_file.write(data)
elif decmpfs.compression_type == 4:
f = HFSCompressedResourceFork(self, v.data.resourceFork, v.data.fileID, decmpfs.compression_type, decmpfs.uncompressed_size)
data = f.readAllBuffer(True, output_file)
elif decmpfs.compression_type in [7, 11]:
if xattr[16] == 0x06: # perhaps even 0xF?
data = xattr[17:] #tested OK
else: #tested OK
uncompressed_size = struct.unpack('<I', xattr[8:12])[0]
compressed_size = len(xattr) - 16
compressed_stream = xattr[16:]
data = lzvn_decompress(compressed_stream, compressed_size, uncompressed_size)
if output_file: output_file.write(data)
elif decmpfs.compression_type in [8, 12]:
# tested for type 8 , OK
f = HFSCompressedResourceFork(self, v.data.resourceFork, v.data.fileID, decmpfs.compression_type, decmpfs.uncompressed_size)
data = f.readAllBuffer(True, output_file)
if output_file: output_file.write(data)
else:
f = HFSFile(self, v.data.dataFork, v.data.fileID)
data = f.readAllBuffer(True, output_file)
return data
def readJournal(self):
jb = self.read(self.header.journalInfoBlock * self.blockSize, self.blockSize)
jib = JournalInfoBlock.parse(jb)
return self.read(jib.offset,jib.size)
def GetFileMACTimesFromFileRecord(self, v):
times = { 'c_time':None, 'm_time':None, 'cr_time':None, 'a_time':None }
catalog_file = v.data
times['c_time'] = CommonFunctions.ReadMacHFSTime(catalog_file.attributeModDate)
times['m_time'] = CommonFunctions.ReadMacHFSTime(catalog_file.contentModDate)
times['cr_time'] = CommonFunctions.ReadMacHFSTime(catalog_file.createDate)
times['a_time'] = CommonFunctions.ReadMacHFSTime(catalog_file.accessDate)
return times
def GetFileMACTimes(self, file_path):
'''
Returns dictionary {c_time, m_time, cr_time, a_time}
where cr_time = created time and c_time = Last time inode/mft modified
'''
k,v = self.catalogTree.getRecordFromPath(file_path)
if k and v.recordType in (kHFSPlusFileRecord, kHFSPlusFolderRecord):
return self.GetFileMACTimesFromFileRecord(v)
raise ValueError("Path not found or not file/folder!")
def IsValidFilePath(self, path):
'''Check if a file path is valid, does not check for folders!'''
k,v = self.catalogTree.getRecordFromPath(path)
if not v:
return False
return v.recordType == kHFSPlusFileRecord #TODO: Check for hard links , sym links?
def IsValidFolderPath(self, path):
'''Check if a folder path is valid'''
k,v = self.catalogTree.getRecordFromPath(path)
if not v:
return False
return v.recordType == kHFSPlusFolderRecord #TODO: Check for hard links , sym links?
def IsSymbolicLink(self, path):
'''Check if a path points to a file/folder or symbolic link'''
mode = self.GetFileMode(path)
if mode:
return (mode & S_IFLNK) == S_IFLNK
return False
def GetFileSizeFromFileRecord(self, v):
xattr = self.getXattr(v.data.fileID, "com.apple.decmpfs")
if xattr:
decmpfs = HFSPlusDecmpfs.parse(xattr)
return decmpfs.uncompressed_size #TODO verify for all cases!
else:
return v.data.dataFork.logicalSize
def GetFileSize(self, path):
'''For a given file path, gets logical file size'''
k,v = self.catalogTree.getRecordFromPath(path)
if k and v.recordType == kHFSPlusFileRecord:
return self.GetFileSizeFromFileRecord(v)
else:
raise ValueError("Path not found")
def GetUserAndGroupID(self, path):
k,v = self.catalogTree.getRecordFromPath(path)
if k and v.recordType in (kHFSPlusFileRecord, kHFSPlusFolderRecord):
return (v.data.HFSPlusBSDInfo.ownerID, v.data.HFSPlusBSDInfo.groupID)
else:
raise ValueError("Path not found")
def GetFileMode(self, path):
'''Returns the file or folder's fileMode '''
k,v = self.catalogTree.getRecordFromPath(path)
if k and v and v.recordType in (kHFSPlusFileRecord, kHFSPlusFolderRecord):
return v.data.HFSPlusBSDInfo.fileMode
else:
raise ValueError("Path not found or not a file/folder")
|
ydkhatri/mac_apt
|
plugins/helpers/hfs_alt.py
|
Python
|
mit
| 22,333
|
var assert = require("assert")
var RequestSet = require("../lib/request_set")
var node = {
request: function () {}
}
var unhealthy = {
request: function (options, callback) { callback({ message: 'no nodes'}) }
}
function succeeding_request(options, cb) {
return cb(null, {}, "foo")
}
function failing_request(options, cb) {
return cb({
message: "crap",
reason: "ihateyou"
})
}
function hangup_request(options, cb) {
return cb({
message: "hang up",
reason: "socket hang up"
})
}
function aborted_request(options, cb) {
return cb({
message: "aborted",
reason: "aborted"
})
}
var pool = {
options: { maxRetries: 5 },
get_node: function () {
return node
},
onRetry: function () {},
length: 3
}
describe("RequestSet", function () {
it("defaults attempt count to at least 2", function () {
var r = new RequestSet({length: 1, options: { maxRetries: 5 }}, {}, null)
assert.equal(r.attempts, 2)
})
it("defaults attempt count to at most maxRetries + 1", function () {
var r = new RequestSet({length: 9, options: { maxRetries: 4 }}, {}, null)
assert.equal(r.attempts, 5)
})
it("defaults attempt count to pool.length", function () {
var r = new RequestSet({length: 4, options: { maxRetries: 5 }}, {}, null)
assert.equal(r.attempts, 4)
})
describe("request()", function () {
it("calls the callback on success", function (done) {
node.request = succeeding_request
RequestSet.request(pool, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
it("calls the callback on error", function (done) {
node.request = failing_request
RequestSet.request(pool, {}, function (err, res, body) {
assert.equal(err.message, "crap")
done()
})
})
it("calls the callback with a 'no nodes' error when there's no nodes to service the request", function (done) {
var p = {
options: { maxRetries: 5 },
get_node: function () { return unhealthy },
length: 0,
onRetry: function () {}
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.message, "no nodes")
done()
})
})
it("retries hangups once", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 2,
nodes: [{ request: hangup_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
it("retries hangups once then fails", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 3,
nodes: [{ request: hangup_request }, { request: hangup_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.reason, "socket hang up")
done()
})
})
it("retries aborts once", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 2,
nodes: [{ request: aborted_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
it("retries aborts once then fails", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 3,
nodes: [{ request: aborted_request }, { request: aborted_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.reason, "aborted")
done()
})
})
it("retries up to this.attempts times", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 3,
nodes: [{ request: failing_request }, { request: failing_request }, { request: aborted_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.reason, "aborted")
done()
})
})
it("retries up to the first success", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 4,
nodes: [{ request: failing_request }, { request: failing_request }, { request: succeeding_request }, { request: failing_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
})
})
|
Voxer/poolee
|
test/requestset_test.js
|
JavaScript
|
mit
| 4,821
|
package leetcode;
/**
* https://leetcode.com/problems/largest-number-greater-than-twice-of-others/
*/
public class Problem747 {
public int dominantIndex(int[] nums) {
if (nums.length == 1) {
return 0;
}
int firstMax = -1;
int firstMaxIdx = -1;
int secondMax = -1;
for (int i = 0; i < nums.length; i++) {
if (firstMax < nums[i]) {
secondMax = firstMax;
firstMax = nums[i];
firstMaxIdx = i;
} else if (secondMax < nums[i]) {
secondMax = nums[i];
}
}
return firstMax >= secondMax * 2 ? firstMaxIdx : -1;
}
}
|
fredyw/leetcode
|
src/main/java/leetcode/Problem747.java
|
Java
|
mit
| 692
|
using System;
namespace HyperSlackers.AspNet.Identity.EntityFramework
{
/// <summary>
/// Tells the auditing engine to NOT audit this property.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class AuditIgnoreAttribute : Attribute
{
}
}
|
dmayhak/HyperSlackers.DbContext
|
DbContext/Attributes/AuditIgnoreAttribute.cs
|
C#
|
mit
| 385
|
package MIP::Recipes::Analysis::Sv_combinevariantcallsets;
use 5.026;
use Carp;
use charnames qw{ :full :short };
use English qw{ -no_match_vars };
use File::Basename qw{ dirname };
use File::Spec::Functions qw{ catfile splitpath };
use open qw{ :encoding(UTF-8) :std };
use Params::Check qw{ allow check last_error };
use utf8;
use warnings;
use warnings qw{ FATAL utf8 };
## CPANM
use autodie qw{ :all };
use List::MoreUtils qw { any };
use Readonly;
## MIPs lib/
use MIP::Constants qw{ $ASTERISK $COLON $DOT $EMPTY_STR $LOG_NAME $NEWLINE $UNDERSCORE };
BEGIN {
require Exporter;
use base qw{ Exporter };
# Functions and variables which can be optionally exported
our @EXPORT_OK = qw{ analysis_sv_combinevariantcallsets };
}
sub analysis_sv_combinevariantcallsets {
## Function : CombineVariants to combine all structural variants call from different callers
## Returns :
## Arguments: $active_parameter_href => Active parameters for this analysis hash {REF}
## : $case_id => Family id
## : $file_info_href => File info hash {REF}
## : $job_id_href => Job id hash {REF}
## : $parameter_href => Parameter hash {REF}
## : $profile_base_command => Submission profile base command
## : $recipe_name => Program name
## : $reference_dir => MIP reference directory
## : $sample_info_href => Info on samples and case hash {REF}
## : $temp_directory => Temporary directory {REF}
my ($arg_href) = @_;
## Flatten argument(s)
my $active_parameter_href;
my $file_info_href;
my $job_id_href;
my $parameter_href;
my $recipe_name;
my $sample_info_href;
## Default(s)
my $case_id;
my $profile_base_command;
my $reference_dir;
my $temp_directory;
my $tmpl = {
active_parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$active_parameter_href,
strict_type => 1,
},
case_id => {
default => $arg_href->{active_parameter_href}{case_id},
store => \$case_id,
strict_type => 1,
},
file_info_href => {
default => {},
defined => 1,
required => 1,
store => \$file_info_href,
strict_type => 1,
},
job_id_href => {
default => {},
defined => 1,
required => 1,
store => \$job_id_href,
strict_type => 1,
},
parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$parameter_href,
strict_type => 1,
},
profile_base_command => {
default => q{sbatch},
store => \$profile_base_command,
strict_type => 1,
},
recipe_name => {
defined => 1,
required => 1,
store => \$recipe_name,
strict_type => 1,
},
sample_info_href => {
default => {},
defined => 1,
required => 1,
store => \$sample_info_href,
strict_type => 1,
},
reference_dir => {
default => $arg_href->{active_parameter_href}{reference_dir},
store => \$reference_dir,
strict_type => 1,
},
temp_directory => {
default => $arg_href->{active_parameter_href}{temp_directory},
store => \$temp_directory,
strict_type => 1,
},
};
check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};
use MIP::File_info qw{ get_io_files parse_io_outfiles };
use MIP::Recipe qw{ parse_recipe_prerequisites };
use MIP::Program::Gnu::Coreutils qw{ gnu_mv };
use MIP::Processmanagement::Processes qw{ submit_recipe };
use MIP::Program::Bcftools
qw{ bcftools_merge bcftools_norm bcftools_view bcftools_view_and_index_vcf };
use MIP::Program::Svdb qw{ svdb_merge };
use MIP::Sample_info qw{ set_file_path_to_store
set_recipe_outfile_in_sample_info
set_recipe_metafile_in_sample_info };
use MIP::Script::Setup_script qw{ setup_script };
### PREPROCESSING:
## Stores the parallel chains that job ids should be inherited from
my @parallel_chains;
## Retrieve logger object
my $log = Log::Log4perl->get_logger($LOG_NAME);
## Unpack parameters
my @structural_variant_callers;
## Only process active callers
foreach
my $structural_variant_caller ( @{ $parameter_href->{cache}{structural_variant_callers} } )
{
if ( $active_parameter_href->{$structural_variant_caller} ) {
push @structural_variant_callers, $structural_variant_caller;
}
}
my %recipe = parse_recipe_prerequisites(
{
active_parameter_href => $active_parameter_href,
parameter_href => $parameter_href,
recipe_name => $recipe_name,
}
);
## Set and get the io files per chain, id and stream
my %io = parse_io_outfiles(
{
chain_id => $recipe{job_id_chain},
id => $case_id,
file_info_href => $file_info_href,
file_name_prefixes_ref => [$case_id],
outdata_dir => $active_parameter_href->{outdata_dir},
parameter_href => $parameter_href,
recipe_name => $recipe_name,
}
);
my $outdir_path_prefix = $io{out}{dir_path_prefix};
my $outfile_path = $io{out}{file_path};
my $outfile_path_prefix = $io{out}{file_path_prefix};
my $outfile_suffix = $io{out}{file_suffix};
## Filehandles
# Create anonymous filehandle
my $filehandle = IO::Handle->new();
## Creates recipe directories (info & data & script), recipe script filenames and writes sbatch header
my ( $recipe_file_path, $recipe_info_path ) = setup_script(
{
active_parameter_href => $active_parameter_href,
core_number => $recipe{core_number},
directory_id => $case_id,
filehandle => $filehandle,
job_id_href => $job_id_href,
memory_allocation => $recipe{memory},
process_time => $recipe{time},
recipe_directory => $recipe_name,
recipe_name => $recipe_name,
temp_directory => $temp_directory,
}
);
## Split to enable submission to &sample_info_qc later
my ( $volume, $directory, $stderr_file ) =
splitpath( $recipe_info_path . $DOT . q{stderr.txt} );
### SHELL:
## Collect infiles for all sample_ids for programs that do not do joint calling to enable migration to temporary directory
# Paths for structural variant callers to be merged
my %file_path;
_preprocess_single_callers_file(
{
active_parameter_href => $active_parameter_href,
filehandle => $filehandle,
file_info_href => $file_info_href,
file_path_href => \%file_path,
parallel_chains_ref => \@parallel_chains,
parameter_href => $parameter_href,
structural_variant_callers_ref => \@structural_variant_callers,
}
);
## Merged sample files to one case file (samples > 1) else reformat to standardise
_merge_or_reformat_single_callers_file(
{
active_parameter_href => $active_parameter_href,
filehandle => $filehandle,
file_path_href => \%file_path,
outdir_path_prefix => $outdir_path_prefix,
outfile_suffix => $outfile_suffix,
parameter_href => $parameter_href,
recipe_info_path => $recipe_info_path,
structural_variant_callers_ref => \@structural_variant_callers,
}
);
## Migrate joint calling per case callers like Manta and Delly
_preprocess_joint_callers_file(
{
active_parameter_href => $active_parameter_href,
filehandle => $filehandle,
file_info_href => $file_info_href,
file_path_href => \%file_path,
outdir_path_prefix => $outdir_path_prefix,
outfile_suffix => $outfile_suffix,
parallel_chains_ref => \@parallel_chains,
parameter_href => $parameter_href,
structural_variant_callers_ref => \@structural_variant_callers,
}
);
## Merge structural variant caller's case vcf files
say {$filehandle} q{## Merge structural variant caller's case vcf files};
## Get parameters
my @svdb_infile_paths;
STRUCTURAL_CALLER:
foreach my $structural_variant_caller (@structural_variant_callers) {
## Only use first part of name
my ($variant_caller_prio_tag) = split /_/sxm, $structural_variant_caller;
push @svdb_infile_paths,
catfile( $outdir_path_prefix,
$case_id
. $UNDERSCORE
. $structural_variant_caller
. $outfile_suffix
. $COLON
. $variant_caller_prio_tag );
}
svdb_merge(
{
filehandle => $filehandle,
infile_paths_ref => \@svdb_infile_paths,
priority => $active_parameter_href->{sv_svdb_merge_prioritize},
same_order => 1,
stdoutfile_path => $outfile_path,
}
);
say {$filehandle} $NEWLINE;
## Alternative file tag
my $alt_file_tag = $EMPTY_STR;
if ( $active_parameter_href->{sv_decompose} ) {
## Update file tag
$alt_file_tag = $UNDERSCORE . q{decompose};
## Split multiallelic variants
say {$filehandle} q{## Split multiallelic variants};
bcftools_norm(
{
filehandle => $filehandle,
infile_path => $outfile_path,
multiallelic => q{-},
outfile_path => $outfile_path_prefix . $alt_file_tag . $outfile_suffix,
}
);
say {$filehandle} $NEWLINE;
gnu_mv(
{
filehandle => $filehandle,
force => 1,
infile_path => $outfile_path_prefix . $alt_file_tag . $outfile_suffix,
outfile_path => $outfile_path,
}
);
say {$filehandle} $NEWLINE;
}
if ( $active_parameter_href->{sv_combinevariantcallsets_bcf_file} ) {
## Reformat variant calling file and index
bcftools_view_and_index_vcf(
{
filehandle => $filehandle,
infile_path => $outfile_path,
index_type => q{csi},
outfile_path_prefix => $outfile_path_prefix,
output_type => q{b},
}
);
}
close $filehandle or $log->logcroak(q{Could not close filehandle});
if ( $recipe{mode} == 1 ) {
set_recipe_outfile_in_sample_info(
{
path => $outfile_path,
recipe_name => $recipe_name,
sample_info_href => $sample_info_href,
}
);
$sample_info_href->{sv_vcf_file}{ready_vcf}{path} = $outfile_path;
if ( $active_parameter_href->{sv_combinevariantcallsets_bcf_file} ) {
my $sv_bcf_file_path = $outfile_path_prefix . $DOT . q{bcf};
set_recipe_metafile_in_sample_info(
{
metafile_tag => q{sv_bcf_file},
path => $sv_bcf_file_path,
recipe_name => $recipe_name,
sample_info_href => $sample_info_href,
}
);
set_file_path_to_store(
{
format => q{bcf},
id => $case_id,
path => $sv_bcf_file_path,
path_index => $sv_bcf_file_path . $DOT . q{csi},
recipe_name => $recipe_name,
sample_info_href => $sample_info_href,
}
);
}
submit_recipe(
{
base_command => $profile_base_command,
case_id => $case_id,
dependency_method => q{sample_to_case},
job_id_chain => $recipe{job_id_chain},
job_id_href => $job_id_href,
job_reservation_name => $active_parameter_href->{job_reservation_name},
log => $log,
max_parallel_processes_count_href =>
$file_info_href->{max_parallel_processes_count},
parallel_chains_ref => \@parallel_chains,
recipe_file_path => $recipe_file_path,
sample_ids_ref => \@{ $active_parameter_href->{sample_ids} },
submission_profile => $active_parameter_href->{submission_profile},
}
);
}
return 1;
}
sub _add_to_parallel_chain {
## Function : Add to parallel chain
## Returns :
## Arguments: $parallel_chains_ref => Store structural variant caller parallel chain
## : $structural_variant_caller_chain => Chain of structural variant caller
my ($arg_href) = @_;
## Flatten argument(s)
my $parallel_chains_ref;
my $structural_variant_caller_chain;
my $tmpl = {
parallel_chains_ref => {
default => [],
defined => 1,
required => 1,
store => \$parallel_chains_ref,
strict_type => 1,
},
structural_variant_caller_chain => {
defined => 1,
required => 1,
store => \$structural_variant_caller_chain,
strict_type => 1,
},
};
check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};
## If element is not part of array
if (
not any {
$_ eq $structural_variant_caller_chain
}
@{$parallel_chains_ref}
)
{
push @{$parallel_chains_ref}, $structural_variant_caller_chain;
}
return;
}
sub _preprocess_joint_callers_file {
## Function : Preprocess joint calling per case callers like Manta and Delly. And store merged outfile per caller
## Returns :
## Arguments: $active_parameter_href => Active parameters for this analysis hash {REF}
## : $case_id => Family id
## : $filehandle => Filehandle to write to
## : $file_info_href => File info hash {REF
## : $file_path_href => Store file path prefix {REF}
## : $outdir_path_prefix => Outdir path prefix
## : $outfile_suffix => Outfile suffix
## : $parallel_chains_ref => Store structural variant caller parallel chain
## : $parameter_href => Parameter hash {REF}
## : $structural_variant_callers_ref => Structural variant callers that do not use joint calling
my ($arg_href) = @_;
## Flatten argument(s)
my $active_parameter_href;
my $filehandle;
my $file_info_href;
my $file_path_href;
my $outdir_path_prefix;
my $outfile_suffix;
my $parallel_chains_ref;
my $parameter_href;
my $structural_variant_callers_ref;
## Default(s)
my $case_id;
my $tmpl = {
active_parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$active_parameter_href,
strict_type => 1,
},
case_id => {
default => $arg_href->{active_parameter_href}{case_id},
store => \$case_id,
strict_type => 1,
},
filehandle => { required => 1, store => \$filehandle, },
file_info_href => {
default => {},
defined => 1,
required => 1,
store => \$file_info_href,
strict_type => 1,
},
file_path_href => {
default => {},
defined => 1,
required => 1,
store => \$file_path_href,
strict_type => 1,
},
outdir_path_prefix => {
defined => 1,
required => 1,
store => \$outdir_path_prefix,
strict_type => 1,
},
outfile_suffix => {
defined => 1,
required => 1,
store => \$outfile_suffix,
strict_type => 1,
},
parallel_chains_ref => {
default => [],
defined => 1,
required => 1,
store => \$parallel_chains_ref,
strict_type => 1,
},
parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$parameter_href,
strict_type => 1,
},
structural_variant_callers_ref => {
default => [],
defined => 1,
required => 1,
store => \$structural_variant_callers_ref,
strict_type => 1,
},
};
check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};
use MIP::File_info qw{ get_io_files };
my $joint_caller = q{manta | delly_reformat | tiddit};
my $stream = q{out};
STRUCTURAL_CALLER:
foreach my $structural_variant_caller ( @{$structural_variant_callers_ref} ) {
next STRUCTURAL_CALLER
if ( $structural_variant_caller !~ / $joint_caller /xsm );
## Expect vcf. Special case: manta, delly, tiddit are processed by joint calling and per case
## Get the io infiles per chain and id
my %sample_io = get_io_files(
{
id => $case_id,
file_info_href => $file_info_href,
parameter_href => $parameter_href,
recipe_name => $structural_variant_caller,
stream => $stream,
}
);
my $infile_path_prefix = $sample_io{$stream}{file_path_prefix};
my $infile_suffix = $sample_io{$stream}{file_suffix};
my $infile_path = $infile_path_prefix . $infile_suffix;
_add_to_parallel_chain(
{
parallel_chains_ref => $parallel_chains_ref,
structural_variant_caller_chain =>
$parameter_href->{$structural_variant_caller}{chain},
}
);
my $decompose_outfile_path = catfile( $outdir_path_prefix,
$case_id . $UNDERSCORE . $structural_variant_caller . $outfile_suffix );
## Store merged outfile per caller
push @{ $file_path_href->{$structural_variant_caller} }, $decompose_outfile_path;
if ( $active_parameter_href->{sv_decompose} ) {
## Split multiallelic variants
say {$filehandle} q{## Split multiallelic variants};
bcftools_norm(
{
filehandle => $filehandle,
infile_path => $infile_path,
multiallelic => q{-},
outfile_path => $decompose_outfile_path,
}
);
say {$filehandle} $NEWLINE;
}
}
return;
}
sub _preprocess_single_callers_file {
## Function : Collect infiles for all sample_ids for programs that do not do joint calling. Add chain of structural variant caller to parallel chains
## Returns :
## Arguments: $active_parameter_href => Active parameters for this analysis hash {REF}
## : $filehandle => Filehandle to write to
## : $file_info_href => File info hash {REF
## : $file_path_href => Store file path prefix {REF}
## : $parallel_chains_ref => Store structural variant caller parallel chain
## : $parameter_href => Parameter hash {REF}
## : $structural_variant_callers_ref => Structural variant callers that do not use joint calling
## : $temp_directory => Temporary directory
my ($arg_href) = @_;
## Flatten argument(s)
my $active_parameter_href;
my $filehandle;
my $file_info_href;
my $file_path_href;
my $parallel_chains_ref;
my $parameter_href;
my $structural_variant_callers_ref;
## Default(s)
my $temp_directory;
my $tmpl = {
active_parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$active_parameter_href,
strict_type => 1,
},
filehandle => { required => 1, store => \$filehandle, },
file_info_href => {
default => {},
defined => 1,
required => 1,
store => \$file_info_href,
strict_type => 1,
},
file_path_href => {
default => {},
defined => 1,
required => 1,
store => \$file_path_href,
strict_type => 1,
},
parallel_chains_ref => {
default => [],
defined => 1,
required => 1,
store => \$parallel_chains_ref,
strict_type => 1,
},
parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$parameter_href,
strict_type => 1,
},
structural_variant_callers_ref => {
default => [],
defined => 1,
required => 1,
store => \$structural_variant_callers_ref,
strict_type => 1,
},
temp_directory => {
default => $arg_href->{active_parameter_href}{temp_directory},
store => \$temp_directory,
strict_type => 1,
},
};
check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};
use MIP::File_info qw{ get_io_files };
my $joint_caller = q{manta | delly_reformat | tiddit};
my $stream = q{out};
SAMPLE_ID:
foreach my $sample_id ( @{ $active_parameter_href->{sample_ids} } ) {
STRUCTURAL_CALLER:
foreach my $structural_variant_caller ( @{$structural_variant_callers_ref} ) {
next STRUCTURAL_CALLER
if ( $structural_variant_caller =~ / $joint_caller /xsm );
## Expect vcf. Special case: manta, delly and tiddit are processed by joint calling and per case
## Get the io infiles per chain and id
my %sample_io = get_io_files(
{
id => $sample_id,
file_info_href => $file_info_href,
parameter_href => $parameter_href,
recipe_name => $structural_variant_caller,
stream => $stream,
}
);
my $infile_path_prefix = $sample_io{$stream}{file_path_prefix};
my $infile_suffix = $sample_io{$stream}{file_suffix};
my $infile_path = $infile_path_prefix . $infile_suffix;
push @{ $file_path_href->{$structural_variant_caller} }, $infile_path . $DOT . q{gz};
_add_to_parallel_chain(
{
parallel_chains_ref => $parallel_chains_ref,
structural_variant_caller_chain =>
$parameter_href->{$structural_variant_caller}{chain},
}
);
## Reformat variant calling file and index
bcftools_view_and_index_vcf(
{
infile_path => $infile_path,
outfile_path_prefix => $infile_path_prefix,
output_type => q{z},
filehandle => $filehandle,
}
);
}
}
return;
}
sub _merge_or_reformat_single_callers_file {
## Function : Merged sample files to one case file (samples > 1) else reformat to standardise
## Returns :
## Arguments: $active_parameter_href => Active parameters for this analysis hash {REF}
## : $case_id => Family ID
## : $filehandle => Filehandle to write to
## : $file_path_href => Store file path prefix {REF}
## : $outdir_path_prefix => Outdir path prefix
## : $outfile_suffix => Outfile suffix
## : $parameter_href => Parameter hash {REF}
## : $recipe_info_path => Program info path
## : $structural_variant_callers_ref => Structural variant callers that do not use joint calling
my ($arg_href) = @_;
## Flatten argument(s)
my $active_parameter_href;
my $filehandle;
my $file_path_href;
my $outdir_path_prefix;
my $outfile_suffix;
my $parameter_href;
my $recipe_info_path;
my $structural_variant_callers_ref;
## Default(s)
my $case_id;
my $tmpl = {
active_parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$active_parameter_href,
strict_type => 1,
},
case_id => {
default => $arg_href->{active_parameter_href}{case_id},
store => \$case_id,
strict_type => 1,
},
filehandle => { required => 1, store => \$filehandle, },
file_path_href => {
default => {},
defined => 1,
required => 1,
store => \$file_path_href,
strict_type => 1,
},
outdir_path_prefix => {
defined => 1,
required => 1,
store => \$outdir_path_prefix,
strict_type => 1,
},
outfile_suffix => {
defined => 1,
required => 1,
store => \$outfile_suffix,
strict_type => 1,
},
parameter_href => {
default => {},
defined => 1,
required => 1,
store => \$parameter_href,
strict_type => 1,
},
recipe_info_path => {
defined => 1,
required => 1,
store => \$recipe_info_path,
strict_type => 1,
},
structural_variant_callers_ref => {
default => [],
defined => 1,
required => 1,
store => \$structural_variant_callers_ref,
strict_type => 1,
},
};
check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!};
my $joint_caller = q{manta | delly_reformat | tiddit};
STRUCTURAL_CALLER:
foreach my $structural_variant_caller ( @{$structural_variant_callers_ref} ) {
next STRUCTURAL_CALLER
if ( $structural_variant_caller =~ / $joint_caller /xsm );
## Expect vcf. Special case: joint calling and per case
## Assemble file paths by adding file ending
my @merge_infile_paths = @{ $file_path_href->{$structural_variant_caller} };
my $merge_outfile_path = catfile( $outdir_path_prefix,
$case_id . $UNDERSCORE . $structural_variant_caller . $outfile_suffix );
## Store merged outfile per caller
push @{ $file_path_href->{$structural_variant_caller} }, $merge_outfile_path;
if ( scalar @{ $active_parameter_href->{sample_ids} } > 1 ) {
## Merge all structural variant caller's vcf files per sample_id
say {$filehandle} q{## Merge all structural variant caller's vcf files per sample_id};
bcftools_merge(
{
filehandle => $filehandle,
infile_paths_ref => \@merge_infile_paths,
outfile_path => $merge_outfile_path,
output_type => q{v},
stderrfile_path => $recipe_info_path
. $UNDERSCORE
. $structural_variant_caller
. $UNDERSCORE
. q{merge.stderr.txt},
}
);
say {$filehandle} $NEWLINE;
}
else {
## Reformat all structural variant caller's vcf files per sample_id
say {$filehandle}
q{## Reformat all structural variant caller's vcf files per sample_id};
bcftools_view(
{
filehandle => $filehandle,
infile_path => $merge_infile_paths[0], # Can be only one
outfile_path => $merge_outfile_path,
output_type => q{v},
stderrfile_path => $recipe_info_path
. $UNDERSCORE
. $structural_variant_caller
. $UNDERSCORE
. q{merge.stderr.txt},
}
);
say {$filehandle} $NEWLINE;
}
}
return;
}
1;
|
henrikstranneheim/MIP
|
lib/MIP/Recipes/Analysis/Sv_combinevariantcallsets.pm
|
Perl
|
mit
| 30,538
|
<!DOCTYPE html>
<html class="theme-next pisces use-motion" lang="">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">
<link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">
<meta name="keywords" content="Hexo, NexT" />
<meta property="og:type" content="website">
<meta property="og:title" content="雁渡寒潭 风吹疏竹">
<meta property="og:url" content="http://slamke.github.io/archives/2016/11/index.html">
<meta property="og:site_name" content="雁渡寒潭 风吹疏竹">
<meta property="og:locale" content="default">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="雁渡寒潭 风吹疏竹">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Pisces',
version: '5.1.4',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: 'Author'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="http://slamke.github.io/archives/2016/11/"/>
<title>Archive | 雁渡寒潭 风吹疏竹</title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="default">
<div class="container sidebar-position-left page-archive">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">雁渡寒潭 风吹疏竹</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">教练,我想打篮球</p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
Home
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
Tags
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
Categories
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
Archives
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div class="post-block archive">
<div id="posts" class="posts-collapse">
<span class="archive-move-on"></span>
<span class="archive-page-counter">
Good! 104 posts in total. Keep on posting.
</span>
<div class="collection-title">
<h1 class="archive-year" id="archive-year-2016">2016</h1>
</div>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/11/29/Scala的类型和反射机制/" itemprop="url">
<span itemprop="name">Scala的类型和反射机制</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-11-29T16:43:45+08:00"
content="2016-11-29" >
11-29
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/11/29/JVM源码分析系列/" itemprop="url">
<span itemprop="name">JVM源码分析系列</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-11-29T16:43:45+08:00"
content="2016-11-29" >
11-29
</time>
</div>
</header>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<header class="post-header">
<h2 class="post-title">
<a class="post-title-link" href="/2016/11/27/SparkStreaming数据产生与导入相关的内存分析/" itemprop="url">
<span itemprop="name">SparkStreaming数据产生与导入相关的内存分析</span>
</a>
</h2>
<div class="post-meta">
<time class="post-time" itemprop="dateCreated"
datetime="2016-11-27T22:30:08+08:00"
content="2016-11-27" >
11-27
</time>
</div>
</header>
</article>
</div>
</div>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<section class="site-overview-wrap sidebar-panel sidebar-panel-active">
<div class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<p class="site-author-name" itemprop="name">Sun Ke</p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives/">
<span class="site-state-item-count">104</span>
<span class="site-state-item-name">posts</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories/index.html">
<span class="site-state-item-count">21</span>
<span class="site-state-item-name">categories</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags/index.html">
<span class="site-state-item-count">61</span>
<span class="site-state-item-name">tags</span>
</a>
</div>
</nav>
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright">© <span itemprop="copyrightYear">2018</span>
<span class="with-love">
<i class="fa fa-user"></i>
</span>
<span class="author" itemprop="copyrightHolder">Sun Ke</span>
</div>
<div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>
<span class="post-meta-divider">|</span>
<div class="theme-info">Theme — <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>
<script id="dsq-count-scr" src="https://Sunke.disqus.com/count.js" async></script>
</body>
</html>
|
slamke/slamke.github.io
|
archives/2016/11/index.html
|
HTML
|
mit
| 11,874
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_05_01
module Models
#
# Result of the request to list VpnSites. It contains a list of VpnSites
# and a URL nextLink to get the next set of results.
#
class ListVpnSitesResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<VpnSite>] List of VpnSites.
attr_accessor :value
# @return [String] URL to get the next set of operation list results if
# there are any.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<VpnSite>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [ListVpnSitesResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for ListVpnSitesResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ListVpnSitesResult',
type: {
name: 'Composite',
class_name: 'ListVpnSitesResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'VpnSiteElementType',
type: {
name: 'Composite',
class_name: 'VpnSite'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
Azure/azure-sdk-for-ruby
|
management/azure_mgmt_network/lib/2020-05-01/generated/azure_mgmt_network/models/list_vpn_sites_result.rb
|
Ruby
|
mit
| 2,834
|
#!/bin/bash
osvers_major=$(sw_vers -productVersion | awk -F. '{print $1}')
osvers_minor=$(sw_vers -productVersion | awk -F. '{print $2}')
ERROR=0
# Checks to see if the OS on the Mac is 10.x.x. If it is not, the
# following message is displayed without quotes:
#
# "Unknown Version Of macOS"
if [[ ${osvers_major} -ne 10 ]]; then
echo "<result>Unknown Version Of macOS</result>"
fi
# Checks to see if the OS on the Mac is 10.13 or higher.
# If it is not, the following message is displayed without quotes:
#
# "APFS Encryption Not Available For This Version Of macOS"
if [[ ${osvers_major} -eq 10 ]] && [[ ${osvers_minor} -lt 13 ]]; then
echo "<result>APFS Encryption Not Available For This Version Of macOS</result>"
fi
if [[ ${osvers_major} -eq 10 ]] && [[ ${osvers_minor} -ge 13 ]]; then
# If the OS on the Mac is 10.13 or higher, check to see if the
# boot drive is formatted with APFS or HFS+
boot_filesystem_check=$(/usr/sbin/diskutil info / | awk '/Type \(Bundle\)/ {print $3}')
# If the drive is formatted with APFS, the fdesetup tool will
# be available and is able to display the encryption status.
if [[ "$boot_filesystem_check" = "apfs" ]]; then
# If encrypted, the following message is
# displayed without quotes:
# "FileVault is On."
#
# If encrypting, the following message is
# displayed without quotes:
# "Encryption in progress:"
# How much has been encrypted of of the total
# amount of space is also displayed.
#
# If decrypting, the following message is
# displayed without quotes:
# "Decryption in progress:"
# How much has been decrypted of of the total
# amount of space is also displayed
#
# If not encrypted, the following message is
# displayed without quotes:
# "FileVault is Off."
ENCRYPTSTATUS=$(fdesetup status | xargs)
if [[ -z $(echo "$ENCRYPTSTATUS" | awk '/Encryption | Decryption/') ]]; then
ENCRYPTSTATUS=$(fdesetup status | head -1)
echo "<result>$ENCRYPTSTATUS</result>"
else
ENCRYPTSTATUS=$(fdesetup status | tail -1)
echo "<result>$ENCRYPTSTATUS</result>"
fi
else
echo "<result>Unable to display encryption status for filesystems other than APFS.</result>"
fi
fi
exit $ERROR
|
kevinstrick/rtrouton_scripts
|
rtrouton_scripts/Casper_Extension_Attributes/check_apfs_encryption/check_apfs_encryption_extension_attribute.sh
|
Shell
|
mit
| 2,281
|
---
layout: post
title: News
---
https://www.raleighnc.gov/
WRAL.com
The News and Observer.com
|
RaleighCapital/raleighcapital.github.io
|
_posts/2010-1-1-news.md
|
Markdown
|
mit
| 97
|
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\JsonResponse;
use \BackendBundle\Entity\User;
use BackendBundle\Entity\Video;
class VideoController extends Controller {
public function newAction(Request $request) {
$jwt_auth = $this->get("app.jwt_auth");
$hash = $request->get('authorization', null);
$check = $jwt_auth->checkToken($hash);
if ($check == true) {
$identity = $jwt_auth->checkToken($hash, true);
$json = $request->request->get("json", null);
if ($json != null) {
$params = json_decode($json);
$createdAt = new \DateTime('now');
$updatedAt = new \DateTime('now');
$imagen = null;
$video_path = null;
$user_id = ($identity->sub != null ? $identity->sub : null);
$title = (isset($params->title)) ? $params->title : null;
$description = (isset($params->description)) ? $params->description : null;
$status = (isset($params->status)) ? $params->status : null;
if ($user_id != null && $title != null) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository("BackendBundle:User")->findOneBy(
array(
"id" => $user_id
));
$video = new Video();
$video->setUser($user);
$video->setCreatedAt($createdAt);
$video->setUpdatedAt($updatedAt);
$video->setTitle($title);
$video->getDescription($description);
$video->setStatus($status);
//$video->setImage($image);
$em->persist($video);
$em->flush();
$video = $em->getRepository("BackendBundle:Video")->findOneBy(
array(
"user" => $user,
"title" => $title,
"status" => $status,
"createdAt" => $createdAt
));
$data = array(
"status" => "success",
"code" => 200,
"data" => $video
);
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Video not created"
);
}
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Video not created, params failed"
);
}
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Authorization not valid"
);
}
return $this->json($data);
}
public function editAction(Request $request, $id = null) {
$jwt_auth = $this->get("app.jwt_auth");
$hash = $request->get('authorization', null);
$check = $jwt_auth->checkToken($hash);
if ($check == true) {
$identity = $jwt_auth->checkToken($hash, true);
$json = $request->request->get("json", null);
if ($json != null) {
$params = json_decode($json);
$video_id = $id;
$createdAt = new \DateTime('now');
$updatedAt = new \DateTime('now');
$imagen = null;
$video_path = null;
$user_id = ($identity->sub != null ? $identity->sub : null);
$title = (isset($params->title)) ? $params->title : null;
$description = (isset($params->description)) ? $params->description : null;
$status = (isset($params->status)) ? $params->status : null;
if ($user_id != null && $title != null) {
$em = $this->getDoctrine()->getManager();
$video = $em->getRepository("BackendBundle:Video")->findOneBy(
array(
"id" => $video_id,
));
if (isset($identity->sub) && $identity->sub == $video->getUser()->getId()) {
$video->setUpdatedAt($updatedAt);
$video->setTitle($title);
$video->getDescription($description);
$video->setStatus($status);
//$video->setImage($image);
$em->persist($video);
$em->flush();
$data = array(
"status" => "success",
"code" => 200,
"msg" => "video updated success"
);
} else {
$data = array(
"status" => "success",
"code" => 400,
"msg" => "video updated error, you not owner"
);
}
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Video not updated"
);
}
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Video not updated, params failed"
);
}
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Authorization not valid"
);
}
return $this->json($data);
}
public function uploadAction(Request $request, $id) {
$jwt_auth = $this->get("app.jwt_auth");
$hash = $request->get('authorization', null);
$check = $jwt_auth->checkToken($hash);
if ($check == true) {
$identity = $jwt_auth->checkToken($hash, true);
$video_id = $id;
$em = $this->getDoctrine()->getManager();
$video = $em->getRepository("BackendBundle:Video")->findOneBy(
array(
"id" => $video_id,
));
if ($video_id != null && isset($identity->sub) && $identity->sub == $video->getUser()->getId()) {
$file = $request->files->get('image', null);
$file_video = $request->files->get('video', null);
if ($file != null && !empty($file)) {
$ext = $file->guessExtension();
if ($ext == "jpeg" || $ext == "jpg" || $ext == "png" || $ext == "gif") {
$file_name = time() . "." . $ext;
$path_of_file = "uploads/video_images/video_" . $video_id;
$file->move($path_of_file, $file_name);
$video->setImage($file_name);
$em->persist($video);
$em->flush();
$data = array(
"status" => "success",
"code" => 200,
"msg" => "Image file for video uploaded"
);
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Video image file extension error"
);
}
} else {
if ($file_video != null && !empty($file_video)) {
$ext = $file_video->guessExtension();
if ($ext == "mp4" || $ext == "avi") {
$file_name = time() . "." . $ext;
$path_of_file = "uploads/video_files/video_" . $video_id;
$file_video->move($path_of_file, $file_name);
$video->setVideoPath($file_name);
$em->persist($video);
$em->flush();
$data = array(
"status" => "success",
"code" => 200,
"msg" => "Video file uploaded"
);
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Video file extension error"
);
}
}
}
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Video uploaded error, not owner"
);
}
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "Authorization not valid"
);
}
return $this->json($data);
}
public function videosAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$dql = "SELECT v FROM BackendBundle:Video v ORDER BY v.id DESC";
$query = $em->createQuery($dql);
$page = $request->query->getInt("page", 1);
$paginator = $this->get("knp_paginator");
$items_per_page = 6;
$pagination = $paginator->paginate($query, $page, $items_per_page);
$total_items_count = $pagination->getTotalItemCount();
$data = array(
"status" => "success",
"total_items_count" => $total_items_count,
"page_actual" => $page,
"items_per_page" => $items_per_page,
"total_pages" => ceil($total_items_count / $items_per_page),
"data" => $pagination
);
return $this->json($data);
}
public function lastsVideosAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$dql = "SELECT v FROM BackendBundle:Video v ORDER BY v.createdAt DESC";
$query = $em->createQuery($dql)->setMaxResults(5);
$videos = $query->getResult();
$data = array(
"status" => "success",
"data" => $videos
);
return $this->json($data);
}
public function videoAction(Request $request, $id = null) {
$em = $this->getDoctrine()->getManager();
$video = $em->getRepository("BackendBundle:Video")->findOneBy(
array(
"id" => $id,
));
if ($video) {
$data = array();
$data["status"] = 'success';
$data["code"] = 200;
$data["data"] = $video;
} else {
$data = array(
"status" => "error",
"code" => 400,
"msg" => "video doesnt exist"
);
}
return $this->json($data);
}
public function searchAction(Request $request, $search = null) {
$em = $this->getDoctrine()->getManager();
if ($search != null) {
$dql = "SELECT v FROM BackendBundle:Video v "
. "WHERE v.title LIKE :search OR "
. "v.description LIKE :search ORDER BY v.id DESC";
$query = $em->createQuery($dql)
->setParameter("search", "%$search%");
} else {
$dql = "SELECT v FROM BackendBundle:Video v ORDER BY v.id DESC";
$query = $em->createQuery($dql);
}
$page = $request->query->getInt("page", 1);
$paginator = $this->get("knp_paginator");
$items_per_page = 6;
$pagination = $paginator->paginate($query, $page, $items_per_page);
$total_items_count = $pagination->getTotalItemCount();
$data = array(
"status" => "success",
"total_items_count" => $total_items_count,
"page_actual" => $page,
"items_per_page" => $items_per_page,
"total_pages" => ceil($total_items_count / $items_per_page),
"data" => $pagination
);
return $this->json($data);
}
public function pruebasAction() {
echo "Hola controlador video";
die();
}
}
|
JoseGCheca/curso-fullstack
|
src/AppBundle/Controller/VideoController.php
|
PHP
|
mit
| 13,288
|
/**
* Created by sakura on 16/3/28.
*/
// $(function () {
// $('#myTab a:last').tab("show");
// })
document.getElementById("btn-normal").disabled = '';
|
abcghy/GraduateDesign
|
dist/js/test.js
|
JavaScript
|
mit
| 159
|
<?php
namespace App\Controller\Order;
use App\Controller\Infrastructure\BaseController;
use App\Entity\Cart;
use App\Entity\CartProductVariant;
use App\Form\CartSummaryType;
use App\Repository\CartRepository;
use App\Repository\ProductRepository;
use App\Repository\ProductVariantRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class CartController extends BaseController
{
private $cartRepository;
private $productRepository;
private $productVariantRepository;
public function __construct(
CartRepository $cartRepository,
ProductRepository $productRepository,
ProductVariantRepository $productVariantRepository
) {
$this->cartRepository = $cartRepository;
$this->productRepository = $productRepository;
$this->productVariantRepository = $productVariantRepository;
}
/**
* @Route("/cart", name="cart_home")
*/
public function home(Request $request)
{
$cartProductVariants = $this->cartRepository->findOneBy([
'sessionId' => $request->getSession()->getId()
]);
return $this->render('Order/cart.html.twig', [
'cartProductVariants' => $cartProductVariants ? $cartProductVariants->getCartProductVariants() : [],
]);
}
/**
* @Route("/cart_summary", name="cart_summary")
*
* @IsGranted("ROLE_USER")
*/
public function summary(Request $request)
{
$cartSummaryForm = $this->createForm(CartSummaryType::class, null, [
'user' => $this->getUser(),
'paymentChargeRoute' => $this->generateUrl('payment_charge'),
]);
return $this->render('Order/cart_summary.html.twig', [
'cartSummaryForm' => $cartSummaryForm->createView(),
'stripe_public_key' => $this->getParameter('stripe_public_key'),
]);
}
/**
* @Route("/remove_from_cart/{identifier}", name="remove_from_cart")
*/
public function removeProduct(string $identifier, Request $request)
{
// TODO: correct to new approach
$productVariant = $this->productVariantRepository
->readOneEntityBy([
'identifier' => $identifier
])->getResult();
if (!$productVariant) {
// TODO: redirect to /cart with error
return $this->redirectToRoute('cart_home');
}
$cart = $request->getSession()->get('cart');
if (array_key_exists($productVariant->getIdentifier(), $cart)) {
unset($cart[$productVariant->getIdentifier()]);
$request->getSession()->set('cart', $cart);
}
return $this->redirectToRoute('cart_home');
}
/**
* @Route("/add_to_cart", name="add_product_to_cart",
* methods={"POST"},
* options={"expose"=true},
* condition="request.isXmlHttpRequest()"
* )
*/
public function addProduct(Request $request)
{
// TODO: check if product not from user's store
$addToCartData = $request->request->get('add_to_cart');
$productVariantIdentifier = $addToCartData['productVariant'] ?? null;
$quantity = $addToCartData['quantity'];
if ($productVariantIdentifier) {
if ($this->isCsrfTokenValid('add_to_cart', $request->request->get('_csrf_token'))) {
$productVariant = $this->productVariantRepository->findOneBy([
'identifier' => $productVariantIdentifier
]);
if (!$productVariant) {
return $this->json('Product variant does not exist', 404);
}
if ($productVariant->getAvailability() < $addToCartData['quantity']) {
return $this->json('Not enough products available!', 409);
}
$session = $request->getSession();
$sessionId = $session->getId();
$cart = $this->cartRepository
->findOneBy(['sessionId' => $sessionId]);
if (!$cart) {
$cart = new Cart();
$cart->setSessionId($sessionId);
$cart->setUser($this->getUser());
$this->entityManager->persist($cart);
$this->entityManager->flush();
}
$cartProductVariant = $this->getDoctrine()
->getRepository(CartProductVariant::class)
->findOneBy([
'cart' => $cart,
'productVariant' => $productVariant
]);
if (!$cartProductVariant) {
$cartProductVariant = new CartProductVariant();
$cartProductVariant->setCart($cart);
$cartProductVariant->setProductVariant($productVariant);
$cartProductVariant->setQuantity($quantity);
} else {
$cartProductVariant->setQuantity(
$cartProductVariant->getQuantity() + $quantity
);
}
$this->entityManager->persist($cartProductVariant);
$this->entityManager->flush();
return new Response(
$this->cartRepository->getTotalSessionQuantity($sessionId),
200
);
} else {
// TODO: return error
}
} else {
// TODO: return error
}
}
}
|
LaVestima/hanna-agency
|
src/Controller/Order/CartController.php
|
PHP
|
mit
| 5,711
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.7-5-b-84
description: >
Object.defineProperties - 'descObj' is the global object which
implements its own [[Get]] method to get 'configurable' property
(8.10.5 step 4.a)
includes:
- runTestCase.js
- fnGlobalObject.js
---*/
function testcase() {
var obj = {};
try {
fnGlobalObject().configurable = true;
Object.defineProperties(obj, {
prop: fnGlobalObject()
});
var result1 = obj.hasOwnProperty("prop");
delete obj.prop;
var result2 = obj.hasOwnProperty("prop");
return result1 === true && result2 === false;
} finally {
delete fnGlobalObject().configurable;
}
}
runTestCase(testcase);
|
PiotrDabkowski/Js2Py
|
tests/test_cases/built-ins/Object/defineProperties/15.2.3.7-5-b-84.js
|
JavaScript
|
mit
| 1,147
|
module Wesi
VERSION = "0.0.4"
end
|
labra/wesi
|
lib/wesi/version.rb
|
Ruby
|
mit
| 36
|
## 1.12.0 (2011-02-03)
* Added pidfile writing from `rake resque:work`
* Added Worker#pid method
* Bugfix: Errors in failure backend are rescue'd
* Bugfix: Non-working workers no longer counted in "working" count
* Bugfix: Don't think resque-web is a worker
## 1.11.0 (2010-08-23)
* Web UI: Group /workers page by hostnames
## 1.10.0 (2010-08-23)
* Support redis:// string format in `Resque.redis=`
* Using new cross-platform JSON gem.
* Added `after_enqueue` plugin hook.
* Added `shutdown?` method which can be overridden.
* Added support for the "leftright" gem when running tests.
* Grammarfix: In the README
## 1.9.10 (2010-08-06)
* Bugfix: before_fork should get passed the job
## 1.9.9 (2010-07-26)
* Depend on redis-namespace 0.8.0
* Depend on json_pure instead of json (for JRuby compat)
* Bugfix: rails_env display in stats view
## 1.9.8 (2010-07-20)
* Bugfix: Worker.all should never return nil
* monit example: Fixed Syntax Error and adding environment to the rake task
* redis rake task: Fixed typo in copy command
## 1.9.7 (2010-07-09)
* Improved memory usage in Job.destroy
* redis-namespace 0.7.0 now required
* Bugfix: Reverted $0 changes
* Web Bugfix: Payload-less failures in the web ui work
## 1.9.6 (2010-06-22)
* Bugfix: Rakefile logging works the same as all the other logging
## 1.9.5 (2010-06-16)
* Web Bugfix: Display the configured namespace on the stats page
* Revert Bugfix: Make ps -o more cross platform friendly
## 1.9.4 (2010-06-14)
* Bugfix: Multiple failure backend gets exception information when created
## 1.9.3 (2010-06-14)
* Bugfix: Resque#queues always returns an array
## 1.9.2 (2010-06-13)
* Bugfix: Worker.all returning nil fix
* Bugfix: Make ps -o more cross platform friendly
## 1.9.1 (2010-06-04)
* Less strict JSON dependency
* Included HISTORY.md in gem
## 1.9.0 (2010-06-04)
* Redis 2 support
* Depend on redis-namespace 0.5.0
* Added Resque::VERSION constant (alias of Resque::Version)
* Bugfix: Specify JSON dependency
* Bugfix: Hoptoad plugin now works on 1.9
## 1.8.5 (2010-05-18)
* Bugfix: Be more liberal in which Redis clients we accept.
## 1.8.4 (2010-05-18)
* Try to resolve redis-namespace dependency issue
## 1.8.3 (2010-05-17)
* Depend on redis-rb ~> 1.0.7
## 1.8.2 (2010-05-03)
* Bugfix: Include "tasks/" dir in RubyGem
## 1.8.1 (2010-04-29)
* Bugfix: Multiple failure backend did not support requeue-ing failed jobs
* Bugfix: Fix /failed when error has no backtrace
* Bugfix: Add `Redis::DistRedis` as a valid client
## 1.8.0 (2010-04-07)
* Jobs that never complete due to killed worker are now failed.
* Worker "working" state is now maintained by the parent, not the child.
* Stopped using deprecated redis.rb methods
* `Worker.working` race condition fixed
* `Worker#process` has been deprecated.
* Monit example fixed
* Redis::Client and Redis::Namespace can be passed to `Resque.redis=`
## 1.7.1 (2010-04-02)
* Bugfix: Make job hook execution order consistent
* Bugfix: stdout buffering in child process
## 1.7.0 (2010-03-31)
* Job hooks API. See docs/HOOKS.md.
* web: Hovering over dates shows a timestamp
* web: AJAXify retry action for failed jobs
* web bugfix: Fix pagination bug
## 1.6.1 (2010-03-25)
* Bugfix: Workers may not be clearing their state correctly on
shutdown
* Added example monit config.
* Exception class is now recorded when an error is raised in a
worker.
* web: Unit tests
* web: Show namespace in header and footer
* web: Remove a queue
* web: Retry failed jobs
## 1.6.0 (2010-03-09)
* Added `before_first_fork`, `before_fork`, and `after_fork` hooks.
* Hoptoad: Added server_environment config setting
* Hoptoad bugfix: Don't depend on RAILS_ROOT
* 1.8.6 compat fixes
## 1.5.2 (2010-03-03)
* Bugfix: JSON check was crazy.
## 1.5.1 (2010-03-03)
* `Job.destroy` and `Resque.dequeue` return the # of destroyed jobs.
* Hoptoad notifier improvements
* Specify the namespace with `resque-web` by passing `-N namespace`
* Bugfix: Don't crash when trying to parse invalid JSON.
* Bugfix: Non-standard namespace support
* Web: Red backgound for queue "failed" only shown if there are failed jobs.
* Web bugfix: Tabs highlight properly now
* Web bugfix: ZSET partial support in stats
* Web bugfix: Deleting failed jobs works again
* Web bugfix: Sets (or zsets, lists, etc) now paginate.
## 1.5.0 (2010-02-17)
* Version now included in procline, e.g. `resque-1.5.0: Message`
* Web bugfix: Ignore idle works in the "working" page
* Added `Resque::Job.destroy(queue, klass, *args)`
* Added `Resque.dequeue(klass, *args)`
## 1.4.0 (2010-02-11)
* Fallback when unable to bind QUIT and USR1 for Windows and JRuby.
* Fallback when no `Kernel.fork` is provided (for IronRuby).
* Web: Rounded corners in Firefox
* Cut down system calls in `Worker#prune_dead_workers`
* Enable switching DB in a Redis server from config
* Support USR2 and CONT to stop and start job processing.
* Web: Add example failing job
* Bugfix: `Worker#unregister_worker` shouldn't call `done_working`
* Bugfix: Example god config now restarts Resque properly.
* Multiple failure backends now permitted.
* Hoptoad failure backend updated to new API
## 1.3.1 (2010-01-11)
* Vegas bugfix: Don't error without a config
## 1.3.0 (2010-01-11)
* Use Vegas for resque-web
* Web Bugfix: Show proper date/time value for failed_at on Failures
* Web Bugfix: Make the / route more flexible
* Add Resque::Server.tabs array (so plugins can add their own tabs)
* Start using [Semantic Versioning](http://semver.org/)
## 1.2.4 (2009-12-15)
* Web Bugfix: fix key links on stat page
## 1.2.3 (2009-12-15)
* Bugfix: Fixed `rand` seeding in child processes.
* Bugfix: Better JSON encoding/decoding without Yajl.
* Bugfix: Avoid `ps` flag error on Linux
* Add `PREFIX` observance to `rake` install tasks.
## 1.2.2 (2009-12-08)
* Bugfix: Job equality was not properly implemented.
## 1.2.1 (2009-12-07)
* Added `rake resque:workers` task for starting multiple workers.
* 1.9.x compatibility
* Bugfix: Yajl decoder doesn't care about valid UTF-8
* config.ru loads RESQUECONFIG if the ENV variable is set.
* `resque-web` now sets RESQUECONFIG
* Job objects know if they are equal.
* Jobs can be re-queued using `Job#recreate`
## 1.2.0 (2009-11-25)
* If USR1 is sent and no child is found, shutdown.
* Raise when a job class does not respond to `perform`.
* Added `Resque.remove_queue` for deleting a queue
## 1.1.0 (2009-11-04)
* Bugfix: Broken ERB tag in failure UI
* Bugfix: Save the worker's ID, not the worker itself, in the failure module
* Redesigned the sinatra web interface
* Added option to clear failed jobs
## 1.0.0 (2009-11-03)
* First release.
|
iGoDigital-LLC/resque-mongo
|
HISTORY.md
|
Markdown
|
mit
| 6,660
|
# ResizableItem
This component allows to resize and drag itself.
Layout properties, such as minimumHeight, may be used to control resizing,
but height or width, user can set through resizing, can not be below 10.
Internal MouseArea accessible through _ma_ property.
Also there are helper properties _draggable_ and _dragCursor_ for controlling _ma_ drag behavior.
|
gossen/qml-components
|
README.md
|
Markdown
|
mit
| 369
|
<HTML><HEAD>
<TITLE>Review for Rush Hour (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0120812">Rush Hour (1998)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?David+Sunga">David Sunga</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>RUSH HOUR (1998)</PRE>
<PRE>Rating: 2.5 stars (out of 4.0)
********************************
Key to rating system:
2.0 stars - Debatable
2.5 stars - Some people may like it
3.0 stars - I liked it
3.5 stars - I am biased in favor of the movie
4.0 stars - I felt the movie's impact personally or it stood out
*********************************
A Movie Review by David Sunga</PRE>
<P>Directed by: Brett Ratner
Written by: Ross LaManna (story) and Jim Kouf (screenplay) .</P>
<P>Ingredients: Reckless cop teamed with Hong Kong detective, comedy,
pratfalls, kidnapped kid</P>
<P>Starring: Chris Tucker, Jackie Chan, Julia Hsu, </P>
<P>Synopsis:
RUSH HOUR is a standard cop buddy plot uplifted by the presence of its
two stars: martial arts funny man Jackie Chan and comedian Chris Tucker.
Tucker plays main character James Carter, an outlandish and narcissistic
Los Angeles cop who is irritating to his superiors. As a result of their
displeasure, Carter is assigned to baby-sit a visiting Hong Kong
detective named Lee (Jackie Chan) whom the authorities want to keep out
of the way as they investigate the kidnapping of Soo Yung (Julia Hsu in
her acting debut), the young child of Lee's friend Chinese Consul Han
(Tzi Ma). But Carter and his new acquaintance Detective Lee don't stay
out of the investigation. They bicker over ethnic misunderstandings and
botch things up, but finally work as a team to solve the case. </P>
<P>Opinion:
I were a teacher giving grades, Tucker would get a B. He's good and
funny, but his loquacious screeching is sometimes a bit much.</P>
<P>On the other hand, RUSH HOUR is proof positive that America is finally
catching on to the world's appreciation international megastar Jackie
Chan. Longtime Chan fans should be forewarned RUSH HOUR isn't a Jackie
Chan or Hong Kong picture; it's a Hollywood buddy formula where Chan is
merely the co-star. But despite not being the main character, Chan still
gets plenty of chances to amuse us by hanging from dangerous ledges,
climbing, leaping, kicking, or consoling a little girl. Chan gets an A,
and if there's a sequel, I hope he gets more air time.</P>
<P>RUSH HOUR is lively, entertaining, and will appeal to people of all ages
and ethnicities. The bad guys aren't impressive, and the plot is
routine, but Tucker and Chan provide sufficient charisma, comic lines,
timing, and acrobatics to give the formula enough enjoyable moments. I
took my parents to see it, and they loved it. </P>
<PRE>Reviewed by David Sunga
September 25, 1998
<A HREF="http://www.criticzoo.com">http://www.criticzoo.com</A></PRE>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
|
xianjunzhengbackup/code
|
data science/machine_learning_for_the_web/chapter_4/movie/14554.html
|
HTML
|
mit
| 3,794
|
<?php
namespace josegonzalez\Queuesadilla\Engine;
use DateInterval;
use DateTime;
use josegonzalez\Queuesadilla\Engine\SynchronousEngine;
use josegonzalez\Queuesadilla\FixtureData;
use josegonzalez\Queuesadilla\TestCase;
use josegonzalez\Queuesadilla\Worker\SequentialWorker;
use josegonzalez\Queuesadilla\Worker\TestWorker;
use Psr\Log\NullLogger;
class SynchronousEngineTest extends TestCase
{
public function setUp() : void
{
$this->url = getenv('SYNCHRONOUS_URL');
$this->config = ['url' => $this->url];
$this->Logger = new NullLogger;
$this->engineClass = 'josegonzalez\Queuesadilla\Engine\SynchronousEngine';
$this->Engine = $this->mockEngine(['getWorker']);
$this->Engine->expects($this->any())
->method('getWorker')
->will($this->returnValue(new TestWorker($this->Engine)));
$this->Fixtures = new FixtureData;
}
public function tearDown() : void
{
unset($this->Engine);
}
/**
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::__construct
*/
public function testConstruct()
{
$Engine = new SynchronousEngine($this->Logger, []);
$this->assertNotNull($Engine->connection());
$Engine = new SynchronousEngine($this->Logger, $this->url);
$this->assertNotNull($Engine->connection());
$Engine = new SynchronousEngine($this->Logger, $this->config);
$this->assertNotNull($Engine->connection());
}
/**
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::connect
*/
public function testConnect()
{
$this->assertTrue($this->Engine->connect());
}
/**
* @covers josegonzalez\Queuesadilla\Engine\Base::getJobClass
*/
public function testGetJobClass()
{
$this->assertEquals('\\josegonzalez\\Queuesadilla\\Job\\Base', $this->Engine->getJobClass());
}
/**
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::acknowledge
*/
public function testAcknowledge()
{
$Engine = $this->mockEngine();
$this->assertFalse($Engine->acknowledge(null));
$this->assertFalse($Engine->acknowledge(false));
$this->assertFalse($Engine->acknowledge(1));
$this->assertFalse($Engine->acknowledge('string'));
$this->assertFalse($Engine->acknowledge(['key' => 'value']));
$this->assertFalse($Engine->acknowledge($this->Fixtures->default['first']));
$this->assertTrue($Engine->push($this->Fixtures->default['first']));
$this->assertTrue($Engine->push($this->Fixtures->other['third']));
$this->assertFalse($Engine->acknowledge($this->Fixtures->default['first']));
}
/**
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::reject
*/
public function testReject()
{
$Engine = $this->mockEngine();
$this->assertFalse($Engine->reject(null));
$this->assertFalse($Engine->reject(false));
$this->assertFalse($Engine->reject(1));
$this->assertFalse($Engine->reject('string'));
$this->assertFalse($Engine->reject(['key' => 'value']));
$this->assertFalse($Engine->reject($this->Fixtures->default['first']));
$this->assertTrue($Engine->push($this->Fixtures->default['first']));
$this->assertTrue($Engine->push($this->Fixtures->other['third']));
$this->assertFalse($Engine->reject($this->Fixtures->default['first']));
}
/**
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::push
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::pop
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::shouldDelay
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::shouldExpire
*/
public function testPush()
{
$Engine = $this->mockEngine();
$this->assertTrue($Engine->push($this->Fixtures->default['first'], 'default'));
$this->assertTrue($Engine->push($this->Fixtures->default['second'], [
'delay' => 30,
]));
$this->assertTrue($Engine->push($this->Fixtures->other['third'], [
'expires_in' => 1,
]));
$this->assertTrue($Engine->push($this->Fixtures->default['fourth'], 'default'));
sleep(2);
$pop1 = $this->Engine->pop();
$pop2 = $this->Engine->pop();
$pop3 = $this->Engine->pop();
$pop4 = $this->Engine->pop();
$this->assertNull($pop1);
$this->assertNull($pop2);
$this->assertNull($pop3);
$this->assertNull($pop4);
}
/**
* @covers josegonzalez\Queuesadilla\Engine\SynchronousEngine::getWorker
*/
public function testGetWorker()
{
$Engine = new SynchronousEngine;
$this->assertInstanceOf(
'\josegonzalez\Queuesadilla\Worker\SequentialWorker',
$this->protectedMethodCall($Engine, 'getWorker')
);
}
protected function mockEngine($methods = null, $config = null)
{
if ($config === null) {
$config = $this->config;
}
return $this->getMockBuilder($this->engineClass)
->setMethods($methods)
->setConstructorArgs([$this->Logger, $config])
->getMock();
}
}
|
josegonzalez/php-queuesadilla
|
tests/josegonzalez/Queuesadilla/Engine/SynchronousEngineTest.php
|
PHP
|
mit
| 5,313
|
<?php
/**
* GenderInterface.php
*
* @author Bolbo
*/
namespace Bolbo\Component\Person\Model;
/**
* Interface GenderInterface
* @package Bolbo\Component\Person\Model
*/
interface GenderInterface
{
/**
* @return mixed
*/
public function getLabel();
/**
* @param $genderId
* @return mixed
*/
public function setGenderId($genderId);
}
|
bolbo/store
|
src/Bolbo/Component/Person/Model/GenderInterface.php
|
PHP
|
mit
| 384
|
<?php
use Mockery as m;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class DatabaseEloquentMorphTest extends PHPUnit_Framework_TestCase {
public function tearDown()
{
m::close();
}
public function testMorphOneSetsProperConstraints()
{
$relation = $this->getOneRelation();
}
public function testMorphOneEagerConstraintsAreProperlyAdded()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('whereIn')->once()->with('table.morph_id', array(1, 2));
$relation->getQuery()->shouldReceive('where')->once()->with('table.morph_type', get_class($relation->getParent()));
$model1 = new EloquentMorphResetModelStub;
$model1->id = 1;
$model2 = new EloquentMorphResetModelStub;
$model2->id = 2;
$relation->addEagerConstraints(array($model1, $model2));
}
/**
* Note that the tests are the exact same for morph many because the classes share this code...
* Will still test to be safe.
*/
public function testMorphManySetsProperConstraints()
{
$relation = $this->getManyRelation();
}
public function testMorphManyEagerConstraintsAreProperlyAdded()
{
$relation = $this->getManyRelation();
$relation->getQuery()->shouldReceive('whereIn')->once()->with('table.morph_id', array(1, 2));
$relation->getQuery()->shouldReceive('where')->once()->with('table.morph_type', get_class($relation->getParent()));
$model1 = new EloquentMorphResetModelStub;
$model1->id = 1;
$model2 = new EloquentMorphResetModelStub;
$model2->id = 2;
$relation->addEagerConstraints(array($model1, $model2));
}
public function testCreateFunctionOnMorph()
{
// Doesn't matter which relation type we use since they share the code...
$relation = $this->getOneRelation();
$created = m::mock('Illuminate\Database\Eloquent\Model');
$created->shouldReceive('setAttribute')->once()->with('morph_id', 1);
$created->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
$relation->getRelated()->shouldReceive('newInstance')->once()->with(array('name' => 'taylor'))->andReturn($created);
$created->shouldReceive('save')->once()->andReturn(true);
$this->assertEquals($created, $relation->create(array('name' => 'taylor')));
}
public function testFindOrNewMethodFindsModel()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('find')->once()->with('foo', array('*'))->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$relation->getRelated()->shouldReceive('newInstance')->never();
$model->shouldReceive('setAttribute')->never();
$model->shouldReceive('save')->never();
$this->assertTrue($relation->findOrNew('foo') instanceof Model);
}
public function testFindOrNewMethodReturnsNewModelWithMorphKeysSet()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('find')->once()->with('foo', array('*'))->andReturn(null);
$relation->getRelated()->shouldReceive('newInstance')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$model->shouldReceive('setAttribute')->once()->with('morph_id', 1);
$model->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
$model->shouldReceive('save')->never();
$this->assertTrue($relation->findOrNew('foo') instanceof Model);
}
public function testFirstOrNewMethodFindsFirstModel()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
$relation->getQuery()->shouldReceive('first')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$relation->getRelated()->shouldReceive('newInstance')->never();
$model->shouldReceive('setAttribute')->never();
$model->shouldReceive('save')->never();
$this->assertTrue($relation->firstOrNew(array('foo')) instanceof Model);
}
public function testFirstOrNewMethodReturnsNewModelWithMorphKeysSet()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
$relation->getQuery()->shouldReceive('first')->once()->with()->andReturn(null);
$relation->getRelated()->shouldReceive('newInstance')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$model->shouldReceive('setAttribute')->once()->with('morph_id', 1);
$model->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
$model->shouldReceive('save')->never();
$this->assertTrue($relation->firstOrNew(array('foo')) instanceof Model);
}
public function testFirstOrCreateMethodFindsFirstModel()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
$relation->getQuery()->shouldReceive('first')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$relation->getRelated()->shouldReceive('newInstance')->never();
$model->shouldReceive('setAttribute')->never();
$model->shouldReceive('save')->never();
$this->assertTrue($relation->firstOrCreate(array('foo')) instanceof Model);
}
public function testFirstOrCreateMethodCreatesNewMorphModel()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
$relation->getQuery()->shouldReceive('first')->once()->with()->andReturn(null);
$relation->getRelated()->shouldReceive('newInstance')->once()->with(array('foo'))->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$model->shouldReceive('setAttribute')->once()->with('morph_id', 1);
$model->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
$model->shouldReceive('save')->once()->andReturn(true);
$this->assertTrue($relation->firstOrCreate(array('foo')) instanceof Model);
}
public function testUpdateOrCreateMethodFindsFirstModelAndUpdates()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
$relation->getQuery()->shouldReceive('first')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$relation->getRelated()->shouldReceive('newInstance')->never();
$model->shouldReceive('setAttribute')->never();
$model->shouldReceive('fill')->once()->with(array('bar'));
$model->shouldReceive('save')->once();
$this->assertTrue($relation->updateOrCreate(array('foo'),array('bar')) instanceof Model);
}
public function testUpdateOrCreateMethodCreatesNewMorphModel()
{
$relation = $this->getOneRelation();
$relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
$relation->getQuery()->shouldReceive('first')->once()->with()->andReturn(null);
$relation->getRelated()->shouldReceive('newInstance')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
$model->shouldReceive('setAttribute')->once()->with('morph_id', 1);
$model->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
$model->shouldReceive('save')->once()->andReturn(true);
$model->shouldReceive('fill')->once()->with(array('bar'));
$this->assertTrue($relation->updateOrCreate(array('foo'),array('bar')) instanceof Model);
}
protected function getOneRelation()
{
$builder = m::mock('Illuminate\Database\Eloquent\Builder');
$builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');
$builder->shouldReceive('where')->once()->with('table.morph_id', '=', 1);
$related = m::mock('Illuminate\Database\Eloquent\Model');
$builder->shouldReceive('getModel')->andReturn($related);
$parent = m::mock('Illuminate\Database\Eloquent\Model');
$parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
$parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));
$builder->shouldReceive('where')->once()->with('table.morph_type', get_class($parent));
return new MorphOne($builder, $parent, 'table.morph_type', 'table.morph_id', 'id');
}
protected function getManyRelation()
{
$builder = m::mock('Illuminate\Database\Eloquent\Builder');
$builder->shouldReceive('whereNotNull')->once()->with('table.morph_id');
$builder->shouldReceive('where')->once()->with('table.morph_id', '=', 1);
$related = m::mock('Illuminate\Database\Eloquent\Model');
$builder->shouldReceive('getModel')->andReturn($related);
$parent = m::mock('Illuminate\Database\Eloquent\Model');
$parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
$parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));
$builder->shouldReceive('where')->once()->with('table.morph_type', get_class($parent));
return new MorphMany($builder, $parent, 'table.morph_type', 'table.morph_id', 'id');
}
}
class EloquentMorphResetModelStub extends Illuminate\Database\Eloquent\Model {}
class EloquentMorphQueryStub extends Illuminate\Database\Query\Builder {
public function __construct() {}
}
|
lukasgeiter/laravel-framework
|
tests/Database/DatabaseEloquentMorphTest.php
|
PHP
|
mit
| 9,306
|
<?php
/*
* This file is part of the Symfony2-Boilerplate repository.
*
* (c) Diego Caponera <http://moonwave99.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace MWLabs\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class HomeController extends Controller
{
/**
* @Route("/")
*/
public function indexAction()
{
return $this -> render('FrontendBundle::index.html.twig', array(
'section' => 'home'
));
}
/**
* @Route("/search")
*/
public function searchAction()
{
return new Response;
}
}
|
moonwave99/symfony2-boilerplate
|
src/MWLabs/FrontendBundle/Controller/HomeController.php
|
PHP
|
mit
| 875
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
<style>
.left,
.right {
width: 300px;
height: 120px;
}
.left div,
.right div {
width: 100px;
height: 90px;
padding: 5px;
margin: 5px;
float: left;
border: 1px solid #ccc;
}
.left div {
background: #bbffaa;
}
.right div {
background: yellow;
}
</style>
</head>
<body>
<h2>通过prepend与prependTo添加元素</h2>
<div class="left">
<div class="aaron">点击通过jQuery的prepend添加元素</div>
<div class="aaron">点击通过jQuery的prependTo添加元素</div>
</div>
<div class="right">
<div class="aaron"><p>测试prepend</p></div>
<div class="aaron"><p>测试prependTo</p></div>
</div>
<script type="text/javascript">
$(".left .aaron:first").on('click', function() {
//找到class="right"下的第一个div
//然后通过prepend在内部的首位置添加一个新的p节点
$('.right .aaron:first').prepend('<p style="color:red">prepend增加的p元素</p>')
})
</script>
<script type="text/javascript">
$(".left .aaron:last").on('click', function() {
//找到class="right"下的第二个div
//然后通过prependTo内部的首位置添加一个新的p节点
$('<p style="color:red">prependTo增加的p元素</p>').prependTo($('.right .aaron:last'))
})
</script>
</body>
</html>
|
flyromance/jQuery
|
_Aaron/jQuery入门教程/jQuery的节点操作/内部插入prepend()与prependTo().html
|
HTML
|
mit
| 1,693
|
/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+markdown&plugins=line-numbers */
/**
* prism.js default theme for JavaScript, CSS and HTML
* Based on dabblet (http://dabblet.com)
* @author Lea Verou
*/
code[class*="language-"],
pre[class*="language-"] {
color: black;
background: none;
text-shadow: 0 1px white;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,
code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {
text-shadow: none;
background: #b3d4fc;
}
pre[class*="language-"]::selection, pre[class*="language-"] ::selection,
code[class*="language-"]::selection, code[class*="language-"] ::selection {
text-shadow: none;
background: #b3d4fc;
}
@media print {
code[class*="language-"],
pre[class*="language-"] {
text-shadow: none;
}
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
background: #f5f2f0;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #999;
}
.namespace {
opacity: .7;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
color: #905;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #690;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
color: #a67f59;
background: hsla(0, 0%, 100%, .5);
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: #07a;
}
.token.function {
color: #DD4A68;
}
.token.regex,
.token.important,
.token.variable {
color: #e90;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
pre.line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre.line-numbers > code {
position: relative;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: 0;
font-size: 100%;
left: -3.8em;
width: 3em; /* works for line-numbers below 1000 lines */
letter-spacing: -1px;
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows > span {
pointer-events: none;
display: block;
counter-increment: linenumber;
}
.line-numbers-rows > span:before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: 0.8em;
text-align: right;
}
|
sydjs/sydjs_zero
|
tutorial/vendor/prismjs/prism.css
|
CSS
|
mit
| 3,086
|
require_relative "test_helper"
class FeedDownloaderTest < Minitest::Test
def setup
flush
end
def test_should_schedule_feed_parser
url = "http://example.com/atom.xml"
stub_request_file("atom.xml", url)
assert_equal 0, FeedParser.jobs.size
FeedDownloader.new.perform(1, url, 10)
assert_equal 1, FeedParser.jobs.size
FeedDownloader.new.perform(1, url, 10)
assert_equal 1, FeedParser.jobs.size, "Should not parse again because checksum matches"
end
def test_should_schedule_critical_feed_parser
url = "http://example.com/atom.xml"
stub_request_file("atom.xml", url)
assert_equal 0, FeedParserCritical.jobs.size
FeedDownloaderCritical.new.perform(1, url, 10)
assert_equal 1, FeedParserCritical.jobs.size
end
def test_should_send_user_agent
url = "http://example.com/atom.xml"
stub_request_file("atom.xml", url).with(headers: {"User-Agent" => "Feedbin feed-id:1 - 10 subscribers"})
FeedDownloader.new.perform(1, url, 10)
end
def test_should_send_authorization
username = "username"
password = "password"
url = "http://#{username}:#{password}@example.com/atom.xml"
stub_request(:get, "http://example.com/atom.xml").with(headers: {"Authorization" => "Basic #{Base64.strict_encode64("#{username}:#{password}")}"})
FeedDownloader.new.perform(1, url, 10)
end
def test_should_use_saved_redirect
feed_id = 1
url_one = "http://example.com/one"
url_two = "http://example.com/two"
redirect_cache = RedirectCache.new(feed_id)
Cache.write(redirect_cache.stable_key, {to: url_two})
stub_request(:get, url_two)
FeedDownloader.new.perform(feed_id, url_one, 10)
end
def test_should_use_saved_redirect_with_basic_auth
feed_id = 1
username = "username"
password = "password"
url_one = "http://#{username}:#{password}@example.com/one"
url_two = "http://example.com/two"
redirect_cache = RedirectCache.new(feed_id)
Cache.write(redirect_cache.stable_key, {to: url_two})
stub_request(:get, url_two).with(headers: {"Authorization" => "Basic #{Base64.strict_encode64("#{username}:#{password}")}"})
FeedDownloader.new.perform(feed_id, url_one, 10)
end
def test_should_do_nothing_if_not_modified
feed_id = 1
etag = "etag"
last_modified = "last_modified"
Cache.write("refresher_http_#{feed_id}", {
etag: etag,
last_modified: last_modified,
checksum: nil
})
url = "http://example.com/atom.xml"
stub_request(:get, url).with(headers: {"If-None-Match" => etag, "If-Modified-Since" => last_modified}).to_return(status: 304)
FeedDownloader.new.perform(feed_id, url, 10)
assert_equal 0, FeedParser.jobs.size
end
def test_should_not_be_ok_after_error
feed_id = 1
url = "http://example.com/atom.xml"
stub_request(:get, url).to_return(status: 429)
FeedDownloader.new.perform(feed_id, url, 10)
refute FeedStatus.new(feed_id).ok?, "Should not be ok?"
end
def test_should_follow_redirects
first_url = "http://www.example.com"
last_url = "#{first_url}/final"
response = {
status: 301,
headers: {
"Location" => "/final"
}
}
stub_request(:get, first_url).to_return(response)
stub_request(:get, last_url)
FeedDownloader.new.perform(1, first_url, 10)
end
end
|
feedbin/refresher
|
test/feed_downloader_test.rb
|
Ruby
|
mit
| 3,347
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Thu Oct 24 12:32:07 EEST 2013 -->
<title>org.tandembrowsing.io.db Class Hierarchy</title>
<meta name="date" content="2013-10-24">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.tandembrowsing.io.db Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/tandembrowsing/io/ajax/package-tree.html">Prev</a></li>
<li><a href="../../../../org/tandembrowsing/io/soap/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/tandembrowsing/io/db/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.tandembrowsing.io.db</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">org.tandembrowsing.io.db.<a href="../../../../org/tandembrowsing/io/db/DBUtil.html" title="class in org.tandembrowsing.io.db"><span class="strong">DBUtil</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/tandembrowsing/io/ajax/package-tree.html">Prev</a></li>
<li><a href="../../../../org/tandembrowsing/io/soap/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/tandembrowsing/io/db/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
tomhai/tandembrowsing
|
javadoc/org/tandembrowsing/io/db/package-tree.html
|
HTML
|
mit
| 4,381
|
import { Enum } from '../utility/enum'
Enum.register(FontWeight, "FontWeight", { jsStringPrefix: 'ms-fontWeight-' });
export enum FontWeight {
unspecified,
light,
semilight,
regular,
semiBold
}
|
kennedylabs/lab-blocks
|
app/fabric/fabric.fontweight.enum.ts
|
TypeScript
|
mit
| 206
|
<?php
namespace Bundle\Manager;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class BundleManagerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $sm)
{
return new BundleManager(
$sm->get('Bundle\Table\BundleTable'),
$sm->get('Bundle\Table\BundleMetaTable'));
}
}
|
tkrebs/ep3-hs
|
module/Bundle/src/Bundle/Manager/BundleManagerFactory.php
|
PHP
|
mit
| 417
|
var Helper = require("@kaoscript/runtime").Helper;
module.exports = function() {
function min() {
return ["female", 24];
}
let foo = Helper.namespace(function() {
const [gender, age] = min();
return {
gender: gender,
age: age
};
});
console.log(foo.age);
console.log(Helper.toString(foo.gender));
};
|
kaoscript/kaoscript
|
test/fixtures/compile/namespace/namespace.var.const.destruct.array.js
|
JavaScript
|
mit
| 319
|
<?php
namespace Chiave\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
// ->add('citizenId')
->add('email')
->add('submit',
'submit',
array(
'label' => 'Wyślij'
)
)
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Chiave\UserBundle\Entity\User'
));
}
/**
* @return string
*/
public function getName()
{
return 'chiave_userbundle_users';
}
}
|
chiave/bluerose
|
src/Chiave/UserBundle/Form/UserType.php
|
PHP
|
mit
| 1,072
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template result</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Boost.Xpressive">
<link rel="up" href="../at.html#idp69068512" title="Description">
<link rel="prev" href="../at.html" title="Struct at">
<link rel="next" href="result_This_Co_idp12683440.html" title="Struct template result<This(Cont &, Idx)>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../at.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../at.html#idp69068512"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="result_This_Co_idp12683440.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.xpressive.op.at.result"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template result</span></h2>
<p>boost::xpressive::op::at::result</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../../header/boost/xpressive/regex_actions_hpp.html" title="Header <boost/xpressive/regex_actions.hpp>">boost/xpressive/regex_actions.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Sig<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="result.html" title="Struct template result">result</a> <span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../at.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../at.html#idp69068512"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="result_This_Co_idp12683440.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
calvinfarias/IC2015-2
|
BOOST/boost_1_61_0/libs/xpressive/doc/html/boost/xpressive/op/at/result.html
|
HTML
|
mit
| 3,866
|
#include "PageMap.h"
#include "Kernel.h"
PageMap::PageMap() {
for(uint32_t i = 0; i < page_bitmap_size; i++) {
page_bitmap[i] = 0;
}
present = false;
}
int PageMap::first_free_page() const {
// Iterate through the bitmap and find the first free page
for (uint32_t idx = 0; idx < page_bitmap_size; idx++) {
uint32_t bitmapEntry = page_bitmap[idx];
if (bitmapEntry != 0xFFFFFFFF) {
for (int32_t bit = 0; bit < 32; bit++) {
uint32_t pageStatus = (bitmapEntry >> bit) & 0x1;
if (pageStatus == 0) {
uint32_t pageIndex = (idx * 32) + bit;
return pageIndex;
}
}
}
}
return -1;
}
void PageMap::set_page_taken(uint32_t idx) {
if (idx > 1024) {
kpanic(
"PageMap::set_page_taken called with an index greater than 1024: "
"%d",
idx);
}
uint32_t bitmapIndex = idx / 32;
uint32_t bitIndex = (idx & 0x1F);
uint32_t old = page_bitmap[bitmapIndex];
page_bitmap[bitmapIndex] |= (0x1 << bitIndex);
uint32_t new_b = page_bitmap[bitmapIndex];
}
void PageMap::set_page_free(uint32_t idx) {
if (idx > 1024) {
kpanic(
"PageMap::set_page_free called with an index greater than 1024: %d",
idx);
}
uint32_t bitmapIndex = idx / 32;
uint32_t bitIndex = (idx & 0x1F);
uint32_t bitMask = ~(1 << bitIndex);
page_bitmap[bitmapIndex] &= bitMask;
}
void PageMap::clear() {
for(uint32_t i = 0; i < page_bitmap_size; i++) {
page_bitmap[i] = 0;
}
}
|
andybest/mustard
|
src/kernel/arch/x86/mm/PageMap.cpp
|
C++
|
mit
| 1,654
|
namespace SwissAcademic.Addons.MacroManagerAddon
{
partial class DirectoryForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnFolderBrowserDialog = new System.Windows.Forms.Button();
this.txtPath = new System.Windows.Forms.TextBox();
this.btnEnvironmentVariables = new System.Windows.Forms.Button();
this.ccEnvironment = new System.Windows.Forms.ContextMenuStrip(this.components);
this.lblEnvironmentFullPath = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnOk
//
this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOk.Location = new System.Drawing.Point(265, 62);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(95, 23);
this.btnOk.TabIndex = 0;
this.btnOk.Text = "Ok";
this.btnOk.UseVisualStyleBackColor = true;
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(366, 62);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(95, 23);
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// btnFolderBrowserDialog
//
this.btnFolderBrowserDialog.Location = new System.Drawing.Point(426, 25);
this.btnFolderBrowserDialog.Name = "btnFolderBrowserDialog";
this.btnFolderBrowserDialog.Size = new System.Drawing.Size(35, 20);
this.btnFolderBrowserDialog.TabIndex = 3;
this.btnFolderBrowserDialog.Text = "...";
this.btnFolderBrowserDialog.UseVisualStyleBackColor = true;
this.btnFolderBrowserDialog.Click += new System.EventHandler(this.BtnFolderBrowserDialog_Click);
//
// txtPath
//
this.txtPath.Location = new System.Drawing.Point(15, 25);
this.txtPath.Name = "txtPath";
this.txtPath.Size = new System.Drawing.Size(364, 23);
this.txtPath.TabIndex = 4;
this.txtPath.TextChanged += new System.EventHandler(this.TxtPath_TextChanged);
//
// btnEnvironmentVariables
//
this.btnEnvironmentVariables.Location = new System.Drawing.Point(385, 25);
this.btnEnvironmentVariables.Name = "btnEnvironmentVariables";
this.btnEnvironmentVariables.Size = new System.Drawing.Size(35, 21);
this.btnEnvironmentVariables.TabIndex = 5;
this.btnEnvironmentVariables.Text = "%";
this.btnEnvironmentVariables.UseVisualStyleBackColor = true;
this.btnEnvironmentVariables.Click += new System.EventHandler(this.BtnEnvironmentVariables_Click);
//
// ccEnvironment
//
this.ccEnvironment.Name = "ccEnvironment";
this.ccEnvironment.Size = new System.Drawing.Size(61, 4);
//
// lblEnvironmentFullPath
//
this.lblEnvironmentFullPath.AutoSize = true;
this.lblEnvironmentFullPath.Location = new System.Drawing.Point(12, 48);
this.lblEnvironmentFullPath.Name = "lblEnvironmentFullPath";
this.lblEnvironmentFullPath.Size = new System.Drawing.Size(0, 15);
this.lblEnvironmentFullPath.TabIndex = 6;
//
// DirectoryDialog
//
this.AcceptButton = this.btnOk;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(473, 97);
this.Controls.Add(this.lblEnvironmentFullPath);
this.Controls.Add(this.btnEnvironmentVariables);
this.Controls.Add(this.txtPath);
this.Controls.Add(this.btnFolderBrowserDialog);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOk);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DirectoryDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "DirectoryDialog";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnFolderBrowserDialog;
private System.Windows.Forms.TextBox txtPath;
private System.Windows.Forms.Button btnEnvironmentVariables;
private System.Windows.Forms.ContextMenuStrip ccEnvironment;
private System.Windows.Forms.Label lblEnvironmentFullPath;
}
}
|
Citavi/C6-Add-Ons-and-Online-Sources
|
src/MacroManager/Forms/DirectoryForm.Designer.cs
|
C#
|
mit
| 6,412
|
/**
* 版权所有 (c) 2018,中金支付有限公司
*/
package com.radish.master.entity.wechat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.cnpc.framework.annotation.Header;
import com.cnpc.framework.base.entity.BaseEntity;
/**
* 类说明
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* dongyan 2018年7月5日 Create this file
* </pre>
*
*/
@Entity
@Table(name = "tbl_wen")
public class Wen extends BaseEntity {
private static final long serialVersionUID = -1272754979289656394L;
@Header(name = "病理号")
@Column(name = "bingli")
private String bingli;
@Header(name = "病案号")
@Column(name = "bingan")
private String bingan;
@Header(name = "性别")
@Column(name = "sex")
private String sex;
@Header(name = "年龄")
@Column(name = "age")
private String age;
@Header(name = "送检日期")
@Column(name = "getdate")
private String getdate;
@Header(name = "诊断日期")
@Column(name = "zhenduan")
private String zhenduan;
@Header(name = "诊断结论")
@Column(name = "jielun")
private String jielun;
@Header(name = "标本类型")
@Column(name = "biaoben")
private String biaoben;
@Header(name = "报告类型")
@Column(name = "baogao")
private String baogao;
@Header(name = "肿瘤大小数据")
@Column(name = "shuju")
private String shuju;
@Header(name = "最大值")
@Column(name = "zuida")
private String zuida;
public String getBingli() {
return bingli;
}
public void setBingli(String bingli) {
this.bingli = bingli;
}
public String getBingan() {
return bingan;
}
public void setBingan(String bingan) {
this.bingan = bingan;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGetdate() {
return getdate;
}
public void setGetdate(String getdate) {
this.getdate = getdate;
}
public String getZhenduan() {
return zhenduan;
}
public void setZhenduan(String zhenduan) {
this.zhenduan = zhenduan;
}
public String getJielun() {
return jielun;
}
public void setJielun(String jielun) {
this.jielun = jielun;
}
public String getBiaoben() {
return biaoben;
}
public void setBiaoben(String biaoben) {
this.biaoben = biaoben;
}
public String getBaogao() {
return baogao;
}
public void setBaogao(String baogao) {
this.baogao = baogao;
}
public String getShuju() {
return shuju;
}
public void setShuju(String shuju) {
this.shuju = shuju;
}
public String getZuida() {
return zuida;
}
public void setZuida(String zuida) {
this.zuida = zuida;
}
}
|
Squama/Master
|
AdminEAP-web/src/main/java/com/radish/master/entity/wechat/Wen.java
|
Java
|
mit
| 3,193
|
module.exports = {
SearchClient: require("./ddg/search-client")
}
|
VarioLabs/ddg-api.js
|
lib/ddg-api.js
|
JavaScript
|
mit
| 67
|
require 'fog/rackspace/core'
module Fog
module Rackspace
class BlockStorage < Fog::Service
include Fog::Rackspace::Errors
class IdentifierTaken < Fog::Errors::Error; end
class ServiceError < Fog::Rackspace::Errors::ServiceError; end
class InternalServerError < Fog::Rackspace::Errors::InternalServerError; end
class BadRequest < Fog::Rackspace::Errors::BadRequest; end
DFW_ENDPOINT = 'https://dfw.blockstorage.api.rackspacecloud.com/v1'
LON_ENDPOINT = 'https://lon.blockstorage.api.rackspacecloud.com/v1'
ORD_ENDPOINT = 'https://ord.blockstorage.api.rackspacecloud.com/v1'
requires :rackspace_api_key, :rackspace_username
recognizes :rackspace_auth_url
recognizes :rackspace_endpoint
recognizes :rackspace_region
recognizes :rackspace_block_storage_url
model_path 'fog/rackspace/models/block_storage'
model :volume
collection :volumes
model :volume_type
collection :volume_types
model :snapshot
collection :snapshots
request_path 'fog/rackspace/requests/block_storage'
request :create_volume
request :delete_volume
request :get_volume
request :list_volumes
request :get_volume_type
request :list_volume_types
request :create_snapshot
request :delete_snapshot
request :get_snapshot
request :list_snapshots
class Mock < Fog::Rackspace::Service
include Fog::Rackspace::MockData
def initialize(options = {})
@rackspace_api_key = options[:rackspace_api_key]
end
def request(params)
Fog::Mock.not_implemented
end
def response(params={})
body = params[:body] || {}
status = params[:status] || 200
headers = params[:headers] || {}
response = Excon::Response.new(:body => body, :headers => headers, :status => status)
if params.has_key?(:expects) && ![*params[:expects]].include?(response.status)
raise(Excon::Errors.status_error(params, response))
else response
end
end
end
class Real < Fog::Rackspace::Service
def initialize(options = {})
@rackspace_api_key = options[:rackspace_api_key]
@rackspace_username = options[:rackspace_username]
@rackspace_auth_url = options[:rackspace_auth_url]
@rackspace_must_reauthenticate = false
@connection_options = options[:connection_options] || {}
setup_custom_endpoint(options)
authenticate
deprecation_warnings(options)
@persistent = options[:persistent] || false
@connection = Fog::XML::Connection.new(endpoint_uri.to_s, @persistent, @connection_options)
end
def request(params, parse_json = true)
super
rescue Excon::Errors::NotFound => error
raise NotFound.slurp(error, self)
rescue Excon::Errors::BadRequest => error
raise BadRequest.slurp(error, self)
rescue Excon::Errors::InternalServerError => error
raise InternalServerError.slurp(error, self)
rescue Excon::Errors::HTTPStatusError => error
raise ServiceError.slurp(error, self)
end
def authenticate(options={})
super({
:rackspace_api_key => @rackspace_api_key,
:rackspace_username => @rackspace_username,
:rackspace_auth_url => @rackspace_auth_url,
:connection_options => @connection_options
})
end
def service_name
:cloudBlockStorage
end
def region
@rackspace_region
end
def request_id_header
"X-Compute-Request-Id"
end
def endpoint_uri(service_endpoint_url=nil)
@uri = super(@rackspace_endpoint || service_endpoint_url, :rackspace_block_storage_url)
end
private
def setup_custom_endpoint(options)
@rackspace_endpoint = Fog::Rackspace.normalize_url(options[:rackspace_block_storage_url] || options[:rackspace_endpoint])
if v2_authentication?
case @rackspace_endpoint
when DFW_ENDPOINT
@rackspace_endpoint = nil
@rackspace_region = :dfw
when ORD_ENDPOINT
@rackspace_endpoint = nil
@rackspace_region = :ord
when LON_ENDPOINT
@rackspace_endpoint = nil
@rackspace_region = :lon
else
@rackspace_region = options[:rackspace_region] || :dfw
end
else
#if we are using auth1 and the endpoint is not set, default to DFW_ENDPOINT for historical reasons
@rackspace_endpoint ||= DFW_ENDPOINT
end
end
def deprecation_warnings(options)
Fog::Logger.deprecation("The :rackspace_endpoint option is deprecated. Please use :rackspace_block_storage_url for custom endpoints") if options[:rackspace_endpoint]
if [DFW_ENDPOINT, ORD_ENDPOINT, LON_ENDPOINT].include?(@rackspace_endpoint) && v2_authentication?
regions = @identity_service.service_catalog.display_service_regions(service_name)
Fog::Logger.deprecation("Please specify region using :rackspace_region rather than :rackspace_endpoint. Valid region for :rackspace_region are #{regions}.")
end
unless options[:rackspace_region]
Fog::Logger.deprecation("Default region support will be removed in an upcoming release. Please switch to manually setting your endpoint. This requires settng the :rackspace_region option")
end
end
def append_tenant_v1(credentials)
account_id = credentials['X-Server-Management-Url'].match(/.*\/([\d]+)$/)[1]
endpoint = @rackspace_endpoint || credentials['X-Server-Management-Url'] || DFW_ENDPOINT
@uri = URI.parse(endpoint)
@uri.path = "#{@uri.path}/#{account_id}"
end
def authenticate_v1(options)
credentials = Fog::Rackspace.authenticate(options, @connection_options)
append_tenant_v1 credentials
@auth_token = credentials['X-Auth-Token']
end
end
end
end
end
|
suhongrui/gitlab
|
vendor/bundle/ruby/2.1.0/gems/fog-1.21.0/lib/fog/rackspace/block_storage.rb
|
Ruby
|
mit
| 6,301
|
// Copyright (c) 2011-2018 The Bitsend Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/bantablemodel.h>
#include <qt/clientmodel.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <interfaces/node.h>
#include <sync.h>
#include <utiltime.h>
#include <QDebug>
#include <QList>
bool BannedNodeLessThan::operator()(const CCombinedBan& left, const CCombinedBan& right) const
{
const CCombinedBan* pLeft = &left;
const CCombinedBan* pRight = &right;
if (order == Qt::DescendingOrder)
std::swap(pLeft, pRight);
switch(column)
{
case BanTableModel::Address:
return pLeft->subnet.ToString().compare(pRight->subnet.ToString()) < 0;
case BanTableModel::Bantime:
return pLeft->banEntry.nBanUntil < pRight->banEntry.nBanUntil;
}
return false;
}
// private implementation
class BanTablePriv
{
public:
/** Local cache of peer information */
QList<CCombinedBan> cachedBanlist;
/** Column to sort nodes by */
int sortColumn;
/** Order (ascending or descending) to sort nodes by */
Qt::SortOrder sortOrder;
/** Pull a full list of banned nodes from CNode into our cache */
void refreshBanlist(interfaces::Node& node)
{
banmap_t banMap;
node.getBanned(banMap);
cachedBanlist.clear();
cachedBanlist.reserve(banMap.size());
for (const auto& entry : banMap)
{
CCombinedBan banEntry;
banEntry.subnet = entry.first;
banEntry.banEntry = entry.second;
cachedBanlist.append(banEntry);
}
if (sortColumn >= 0)
// sort cachedBanlist (use stable sort to prevent rows jumping around unnecessarily)
qStableSort(cachedBanlist.begin(), cachedBanlist.end(), BannedNodeLessThan(sortColumn, sortOrder));
}
int size() const
{
return cachedBanlist.size();
}
CCombinedBan *index(int idx)
{
if (idx >= 0 && idx < cachedBanlist.size())
return &cachedBanlist[idx];
return 0;
}
};
BanTableModel::BanTableModel(interfaces::Node& node, ClientModel *parent) :
QAbstractTableModel(parent),
m_node(node),
clientModel(parent)
{
columns << tr("IP/Netmask") << tr("Banned Until");
priv.reset(new BanTablePriv());
// default to unsorted
priv->sortColumn = -1;
// load initial data
refresh();
}
BanTableModel::~BanTableModel()
{
// Intentionally left empty
}
int BanTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int BanTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant BanTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
CCombinedBan *rec = static_cast<CCombinedBan*>(index.internalPointer());
if (role == Qt::DisplayRole) {
switch(index.column())
{
case Address:
return QString::fromStdString(rec->subnet.ToString());
case Bantime:
QDateTime date = QDateTime::fromMSecsSinceEpoch(0);
date = date.addSecs(rec->banEntry.nBanUntil);
return date.toString(Qt::SystemLocaleLongDate);
}
}
return QVariant();
}
QVariant BanTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags BanTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex BanTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
CCombinedBan *data = priv->index(row);
if (data)
return createIndex(row, column, data);
return QModelIndex();
}
void BanTableModel::refresh()
{
Q_EMIT layoutAboutToBeChanged();
priv->refreshBanlist(m_node);
Q_EMIT layoutChanged();
}
void BanTableModel::sort(int column, Qt::SortOrder order)
{
priv->sortColumn = column;
priv->sortOrder = order;
refresh();
}
bool BanTableModel::shouldShow()
{
return priv->size() > 0;
}
|
LIMXTEC/BitSend
|
src/qt/bantablemodel.cpp
|
C++
|
mit
| 4,521
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _mongoose = require('mongoose');
var _mongoose2 = _interopRequireDefault(_mongoose);
var _validator = require('validator');
var _findOrCreatePlugin = require('./find-or-create-plugin');
var _findOrCreatePlugin2 = _interopRequireDefault(_findOrCreatePlugin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Schema = _mongoose2.default.Schema;
var userSchema = new Schema({
id: {
type: String,
required: true,
match: /\d+/
},
displayName: { type: String, required: true, match: /^([A-Za-z]+((\s[A-Za-z]+)+)?)$/ },
emails: [{ value: {
type: String,
required: true,
unique: true,
validate: [{ validator: function validator(value) {
return (0, _validator.isEmail)(value);
}, message: 'Invalid email.' }]
} }],
photos: [{ value: { type: String, validate: { validator: _validator.isURL } } }]
});
userSchema.plugin(_findOrCreatePlugin2.default);
var User = _mongoose2.default.model('User', userSchema);
exports.default = User;
|
iykyvic/fcc-voting
|
dist/server/models/Users.js
|
JavaScript
|
mit
| 1,132
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Comp3766Component } from './comp-3766.component';
describe('Comp3766Component', () => {
let component: Comp3766Component;
let fixture: ComponentFixture<Comp3766Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Comp3766Component ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Comp3766Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
angular/angular-cli-stress-test
|
src/app/components/comp-3766/comp-3766.component.spec.ts
|
TypeScript
|
mit
| 847
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>ftconv</title>
<link rel="stylesheet" type="text/css" href="csound.css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
<link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
<link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
<link rel="prev" href="ftchnls.html" title="ftchnls" />
<link rel="next" href="ftcps.html" title="ftcps" />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">ftconv</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="ftchnls.html">Prev</a> </td>
<th width="60%" align="center">Orchestra Opcodes and Operators</th>
<td width="20%" align="right"> <a accesskey="n" href="ftcps.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="refentry">
<a id="ftconv"></a>
<div class="titlepage"></div>
<a id="IndexFtconv" class="indexterm"></a>
<div class="refnamediv">
<h2>
<span class="refentrytitle">ftconv</span>
</h2>
<p>ftconv —
Low latency multichannel convolution, using a function table as impulse
response source.
</p>
</div>
<div class="refsect1">
<a id="idm47161628464000"></a>
<h2>Description</h2>
<p>
Low latency multichannel convolution, using a function table as impulse
response source. The algorithm is to split the impulse response to
partitions of length determined by the <span class="emphasis"><em>iplen</em></span> parameter, and delay and
mix partitions so that the original, full length impulse response is
reconstructed without gaps. The output delay (latency) is <span class="emphasis"><em>iplen</em></span> samples,
and does not depend on the control rate, unlike in the case of other
convolve opcodes.
</p>
</div>
<div class="refsect1">
<a id="idm47161628461600"></a>
<h2>Syntax</h2>
<pre class="synopsis">a1[, a2[, a3[, ... a8]]] <span class="command"><strong>ftconv</strong></span> ain, ift, iplen[, iskipsamples \
[, iirlen[, iskipinit]]]</pre>
</div>
<div class="refsect1">
<a id="idm47161628459504"></a>
<h2>Initialization</h2>
<p>
<span class="emphasis"><em>ift</em></span>
-- source ftable number. The table is expected to contain interleaved
multichannel audio data, with the number of channels equal to the number
of output variables (a1, a2, etc.). An interleaved table can be created
from a set of mono tables with <a class="link" href="GEN52.html" title="GEN52"><em class="citetitle">GEN52</em></a>.
</p>
<p>
<span class="emphasis"><em>iplen</em></span>
-- length of impulse response partitions, in sample frames; must be an
integer power of two. Lower settings allow for shorter output delay, but
will increase CPU usage.
</p>
<p>
<span class="emphasis"><em>iskipsamples</em></span>
(optional, defaults to zero) -- number of sample frames to skip
at the beginning of the table.
Useful for reverb responses that have some amount of initial delay.
If this delay is not less than <span class="emphasis"><em>iplen</em></span> samples, then setting
<span class="emphasis"><em>iskipsamples</em></span> to the same value as <span class="emphasis"><em>iplen</em></span>
will eliminate any additional latency by <span class="emphasis"><em>ftconv</em></span>.
</p>
<p>
<span class="emphasis"><em>iirlen</em></span>
(optional) -- total length of impulse response, in sample frames.
The default is to use all table data (not including the guard point).
</p>
<p>
<span class="emphasis"><em>iskipinit</em></span>
(optional, defaults to zero) -- if set to any non-zero value, skip
initialization whenever possible without causing an error.
</p>
</div>
<div class="refsect1">
<a id="idm47161628450784"></a>
<h2>Performance</h2>
<p>
<span class="emphasis"><em>ain</em></span>
-- input signal.
</p>
<p>
<span class="emphasis"><em>a1 ... a8</em></span>
-- output signal(s).
</p>
</div>
<div class="refsect1">
<a id="idm47161628448320"></a>
<h2>Example</h2>
<p>
Here is an example of the ftconv opcode. It uses the file <a class="ulink" href="examples/ftconv.csd" target="_top"><em class="citetitle">ftconv.csd</em></a>.
</p>
<div class="example">
<a id="idm47161628446464"></a>
<p class="title">
<strong>Example 345. Example of the ftconv opcode.</strong>
</p>
<div class="example-contents">
<p>See the sections <a class="link" href="UsingRealTime.html" title="Real-Time Audio"><em class="citetitle">Real-time Audio</em></a> and <a class="link" href="CommandFlags.html" title="Csound command line"><em class="citetitle">Command Line Flags</em></a> for more information on using command line flags.</p>
<div class="refsect1">
<a id="idm47161483958512"></a>
<pre class="programlisting">
<span class="csdtag"><CsoundSynthesizer></span>
<span class="csdtag"><CsOptions></span>
<span class="comment">; Select audio/midi flags here according to platform</span>
<span class="comment">; Audio out Audio in</span>
-odac -iadc <span class="comment">;;;RT audio I/O</span>
<span class="comment">; For Non-realtime ouput leave only the line below:</span>
<span class="comment">; -o ftconv.wav -W ;;; for file output any platform</span>
<span class="csdtag"></CsOptions></span>
<span class="csdtag"><CsInstruments></span>
<span class="ohdr">sr</span> <span class="op">=</span> 48000
<span class="ohdr">ksmps</span> <span class="op">=</span> 32
<span class="ohdr">nchnls</span> <span class="op">=</span> 2
<span class="ohdr">0dbfs</span> <span class="op">=</span> 1
garvb <span class="opc">init</span> 0
gaW <span class="opc">init</span> 0
gaX <span class="opc">init</span> 0
gaY <span class="opc">init</span> 0
itmp <span class="ohdr">ftgen</span> 1, 0, 64, <span class="op">-</span>2, 2, 40, <span class="op">-</span>1, <span class="op">-</span>1, <span class="op">-</span>1, 123, \
1, 13.000, 0.05, 0.85, 20000.0, 0.0, 0.50, 2, \
1, 2.000, 0.05, 0.85, 20000.0, 0.0, 0.25, 2, \
1, 16.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2, \
1, 9.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2, \
1, 12.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2, \
1, 8.000, 0.05, 0.85, 20000.0, 0.0, 0.35, 2
itmp <span class="ohdr">ftgen</span> 2, 0, 262144, <span class="op">-</span>2, 0
<span class="opc">spat3dt</span> 2, <span class="op">-</span>0.2, 1, 0, 1, 1, 2, 0.005
itmp <span class="ohdr">ftgen</span> 3, 0, 262144, <span class="op">-</span>52, 3, 2, 0, 4, 2, 1, 4, 2, 2, 4
<span class="oblock">instr</span> 1
a1 <span class="opc">vco2</span> 1, 440, 10
kfrq <span class="opc">port</span> 100, 0.008, 20000
a1 <span class="opc">butterlp</span> a1, kfrq
a2 <span class="opc">linseg</span> 0, 0.003, 1, 0.01, 0.7, 0.005, 0, 1, 0
a1 <span class="op">=</span> a1 <span class="op">*</span> a2 <span class="op">*</span> 2
<span class="opc">denorm</span> a1
<span class="opc">vincr</span> garvb, a1
aw, ax, ay, az <span class="opc">spat3di</span> a1, p4, p5, p6, 1, 1, 2
<span class="opc">vincr</span> gaW, aw
<span class="opc">vincr</span> gaX, ax
<span class="opc">vincr</span> gaY, ay
<span class="oblock">endin</span>
<span class="oblock">instr</span> 2
<span class="opc">denorm</span> garvb
<span class="comment">; skip as many samples as possible without truncating the IR</span>
arW, arX, arY <span class="opc">ftconv</span> garvb, 3, 2048, 2048, (65536 <span class="op">-</span> 2048)
aW <span class="op">=</span> gaW <span class="op">+</span> arW
aX <span class="op">=</span> gaX <span class="op">+</span> arX
aY <span class="op">=</span> gaY <span class="op">+</span> arY
garvb <span class="op">=</span> 0
gaW <span class="op">=</span> 0
gaX <span class="op">=</span> 0
gaY <span class="op">=</span> 0
aWre, aWim <span class="opc">hilbert</span> aW
aXre, aXim <span class="opc">hilbert</span> aX
aYre, aYim <span class="opc">hilbert</span> aY
aWXr <span class="op">=</span> 0.0928<span class="op">*</span>aXre <span class="op">+</span> 0.4699<span class="op">*</span>aWre
aWXiYr <span class="op">=</span> 0.2550<span class="op">*</span>aXim <span class="op">-</span> 0.1710<span class="op">*</span>aWim <span class="op">+</span> 0.3277<span class="op">*</span>aYre
aL <span class="op">=</span> aWXr <span class="op">+</span> aWXiYr
aR <span class="op">=</span> aWXr <span class="op">-</span> aWXiYr
<span class="opc">outs</span> aL, aR
<span class="oblock">endin</span>
<span class="csdtag"></CsInstruments></span>
<span class="csdtag"><CsScore></span>
<span class="stamnt">i</span> 1 0 0.5 0.0 2.0 -0.8
<span class="stamnt">i</span> 1 1 0.5 1.4 1.4 -0.6
<span class="stamnt">i</span> 1 2 0.5 2.0 0.0 -0.4
<span class="stamnt">i</span> 1 3 0.5 1.4 -1.4 -0.2
<span class="stamnt">i</span> 1 4 0.5 0.0 -2.0 0.0
<span class="stamnt">i</span> 1 5 0.5 -1.4 -1.4 0.2
<span class="stamnt">i</span> 1 6 0.5 -2.0 0.0 0.4
<span class="stamnt">i</span> 1 7 0.5 -1.4 1.4 0.6
<span class="stamnt">i</span> 1 8 0.5 0.0 2.0 0.8
<span class="stamnt">i</span> 2 0 10
<span class="stamnt">e</span>
<span class="csdtag"></CsScore></span>
<span class="csdtag"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
</p>
</div>
<div class="refsect1">
<a id="idm47161628442176"></a>
<h2>See also</h2>
<p>
<a class="link" href="pconvolve.html" title="pconvolve"><em class="citetitle">pconvolve</em></a>,
<a class="link" href="convolve.html" title="convolve"><em class="citetitle">convolve</em></a>,
<a class="link" href="dconv.html" title="dconv"><em class="citetitle">dconv</em></a>.
</p>
</div>
<div class="refsect1">
<a id="idm47161628438176"></a>
<h2>Credits</h2>
<p>
</p>
<table border="0" summary="Simple list" class="simplelist">
<tr>
<td>Author: Istvan Varga</td>
</tr>
<tr>
<td>2005</td>
</tr>
</table>
<p>
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="ftchnls.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="OpcodesTop.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="ftcps.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">ftchnls </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> ftcps</td>
</tr>
</table>
</div>
</body>
</html>
|
ketchupok/csound.github.io
|
docs/manual/ftconv.html
|
HTML
|
mit
| 11,912
|
# -*- encoding: utf-8 -*-
from mock import Mock, patch
from psutil import AccessDenied, TimeoutExpired
from thefuck.output_readers import rerun
class TestRerun(object):
def setup_method(self, test_method):
self.patcher = patch('thefuck.output_readers.rerun.Process')
process_mock = self.patcher.start()
self.proc_mock = process_mock.return_value = Mock()
def teardown_method(self, test_method):
self.patcher.stop()
@patch('thefuck.output_readers.rerun._wait_output', return_value=False)
@patch('thefuck.output_readers.rerun.Popen')
def test_get_output(self, popen_mock, wait_output_mock):
popen_mock.return_value.stdout.read.return_value = b'output'
assert rerun.get_output('', '') is None
wait_output_mock.assert_called_once()
@patch('thefuck.output_readers.rerun.Popen')
def test_get_output_invalid_continuation_byte(self, popen_mock):
output = b'ls: illegal option -- \xc3\nusage: ls [-@ABC...] [file ...]\n'
expected = u'ls: illegal option -- \ufffd\nusage: ls [-@ABC...] [file ...]\n'
popen_mock.return_value.stdout.read.return_value = output
actual = rerun.get_output('', '')
assert actual == expected
@patch('thefuck.output_readers.rerun._wait_output')
def test_get_output_unicode_misspell(self, wait_output_mock):
rerun.get_output(u'pácman', u'pácman')
wait_output_mock.assert_called_once()
def test_wait_output_is_slow(self, settings):
assert rerun._wait_output(Mock(), True)
self.proc_mock.wait.assert_called_once_with(settings.wait_slow_command)
def test_wait_output_is_not_slow(self, settings):
assert rerun._wait_output(Mock(), False)
self.proc_mock.wait.assert_called_once_with(settings.wait_command)
@patch('thefuck.output_readers.rerun._kill_process')
def test_wait_output_timeout(self, kill_process_mock):
self.proc_mock.wait.side_effect = TimeoutExpired(3)
self.proc_mock.children.return_value = []
assert not rerun._wait_output(Mock(), False)
kill_process_mock.assert_called_once_with(self.proc_mock)
@patch('thefuck.output_readers.rerun._kill_process')
def test_wait_output_timeout_children(self, kill_process_mock):
self.proc_mock.wait.side_effect = TimeoutExpired(3)
self.proc_mock.children.return_value = [Mock()] * 2
assert not rerun._wait_output(Mock(), False)
assert kill_process_mock.call_count == 3
def test_kill_process(self):
proc = Mock()
rerun._kill_process(proc)
proc.kill.assert_called_once_with()
@patch('thefuck.output_readers.rerun.logs')
def test_kill_process_access_denied(self, logs_mock):
proc = Mock()
proc.kill.side_effect = AccessDenied()
rerun._kill_process(proc)
proc.kill.assert_called_once_with()
logs_mock.debug.assert_called_once()
|
nvbn/thefuck
|
tests/output_readers/test_rerun.py
|
Python
|
mit
| 2,942
|
<?php
namespace Artax;
class ResourceBody implements \Iterator, \Countable {
private $resource;
private $lengthCache;
private $currentIterCache;
private $streamGranularity = 32768;
function __construct($resource) {
if (is_resource($resource)) {
$this->validateSeekability($resource);
$this->resource = $resource;
} else {
throw new \InvalidArgumentException(
'Invalid stream resource'
);
}
}
private function validateSeekability($resource) {
if (!stream_get_meta_data($resource)['seekable']) {
throw new \InvalidArgumentException(
'Invalid stream resource: must be seekable'
);
}
}
function count() {
if (isset($this->lengthCache)) {
$length = $this->lengthCache;
} else {
$currentPosition = $this->getResourcePosition($this->resource);
$length = $this->lengthCache = $this->getResourceLength($this->resource);
$this->seekResource($this->resource, $currentPosition);
}
return $length;
}
private function getResourceLength($resource) {
if (fseek($resource, 0, SEEK_END)) {
throw new \RuntimeException(
'Failed seeking on stream'
);
}
$length = $this->getResourcePosition($resource);
$this->seekResource($resource, 0);
return $length;
}
private function getResourcePosition($resource) {
$position = @ftell($resource);
if ($position !== FALSE) {
return $position;
} else {
throw new \RuntimeException(
'Failed to determine stream position'
);
}
}
private function seekResource($resource, $pos, $whence = SEEK_SET) {
if (@fseek($resource, $pos, $whence)) {
throw new \RuntimeException(
'Failed seeking on stream'
);
}
}
private function isEof($resource) {
$resourceReportsEof = @feof($resource);
if ($resourceReportsEof && is_resource($resource)) {
$isEof = TRUE;
} elseif ($resourceReportsEof) {
throw new \RuntimeException(
'Resource went away unexpectedly'
);
} else {
$isEof = FALSE;
}
return $isEof;
}
function current() {
if (isset($this->currentIterCache)) {
$current = $this->currentIterCache;
} else {
$current = $this->currentIterCache = $this->getResourceChunk($this->resource);
}
return $current;
}
private function getResourceChunk($resource) {
$chunk = @fread($resource, $this->streamGranularity);
if ($chunk === FALSE) {
throw new \RuntimeException(
'Failed reading from stream'
);
}
return $chunk;
}
function key() {
return $this->getResourcePosition($this->resource);
}
function next() {
$this->currentIterCache = NULL;
}
function valid() {
return !$this->isEof($this->resource);
}
function rewind() {
$this->seekResource($this->resource, 0);
}
function setStreamGranularity($bytes) {
$this->streamGranularity = filter_var($bytes, FILTER_VALIDATE_INT, ['options' => [
'min_range' => 1,
'default' => 32768
]]);
}
}
|
Ocramius/Artax
|
src/Artax/ResourceBody.php
|
PHP
|
mit
| 3,658
|
{% extends "../layout.html" %}
{% block content %}
<main id="content" role="main">
<div class="phase-banner-alpha">
<p>
<strong class="phase-tag">BETA</strong>
<span>This is an BETA prototype, details may be missing whilst we build the service. Your feedback will help us improve this service.</span>
</p>
</div>
{% from "custom_inc/waterdata-severn.html" import permits %}
{% for pNumber, pData in permits %}
{% if pNumber==chosenPermitID %}
<div class="big-space">
<!-- breadcrumbs -->
<nav id="navigate">
<div class="breadcrumbs" id="breadcrumbs">
<ol role="breadcrumbs">
<li><a href="/v15/pages/licences">Your licences</a></li>
<li><a href="">Licence number: {{ pData.LicenceSerialNo }}</a></li>
</ol>
</div>
<!-- manage controls -->
<div class="manage" id="manage">
<div class="right">
<a href="/v12_2/change_password/new_password.html" class="change-password">Change password</a>
<a href="/v12_2/pages/signin" class="sign-out">Sign out</a>
</div>
</div>
</nav>
</div>
<!-- page title -->
{% if pData.LicenceName %}
<h1 class="heading-large">{{ pData.LicenceName }}</h1>
{% else %}
<h1 class="heading-large">Licence number {{ pData.LicenceSerialNo }}</h1>
{% endif %}
<!-- rename licence form -->
<div class="form--well ">
<label for="name" class="">
<span class="form-label-bold">Licence name</span>
</label>
<input minlength="2" maxlength="32" style="background: #fff" type="text" class="form-control " id="name" name="name" value="">
<p></p>
<a class="button" href="/v15/pages/online_licence?wid={{ query.wid }}" role="button" style="margin-bottom:20px;">
Save
</a>
<p class="form-cancel">
<a href="#" onclick="history.go(-1)">
Cancel
</a>
</p>
</div>
<div class="datatable datahead">
<label>Start date</label>
<div class="licenceAnswerv7">
{{ pData.EffectiveDateStart }}
</div>
</div>
<div class="datatable">
<label>End date</label>
<div class="licenceAnswerv7">
{{ pData.EffectiveDateEnd }}
</div>
</div>
<div class="datatable">
<label>Licence name</label>
<div class="licenceAnswerv7">
{% if pData.LicenceName %}
{{ pData.LicenceName }}</br>
<a href="/v15/pages/online_licence_rename?wid=1">Rename this licence</a>
{% else %}
<!-- <span>No name chosen</span></br> -->
<a href="/v12_2/online_licence/rename/online_licence_rename?wid=1">Name this licence</a>
{% endif %}
</div>
</div>
<div class="datatable">
<label>Licence holder</label>
<div class="licenceAnswerv7">
{{ pData.FirstName }} {{ pData.Surname }}</br>
<a href="/v12_2/pages/contact_details?wid={{ pNumber }}">View licence contact details</a></div>
</div>
<div class="datatable">
<label>Source of supply</label>
<div class="licenceAnswerv7">{{ pData.Source}}</div>
</div>
<div class="datatable">
<label>Period of abstraction</label>
<div class="licenceAnswerv7">{{ pData.PeriodofAbstraction }}</div>
</div>
<div class="datatable">
<label>Point of abstraction</label>
<div class="licenceAnswerv7">
{{ pData.Pointofabstraction }}
</div>
</div>
<div class="datatable">
<label>Purpose of abstraction</label>
<div class="licenceAnswerv7">
{{ pData.purpose1 }}</br>
{% if pData.purpose2 %}
{{ pData.purpose2 }}</br>
{% endif %}
{% if pData.purpose3 %}
{{ pData.purpose3 }}</br>
{% endif %}
{% if pData.purpose4 %}
{{ pData.purpose4 }}</br>
{% endif %}
{% if pData.purpose5 %}
{{ pData.purpose5 }}</br>
{% endif %}
<a href="/v15/pages/points_purposes/tabbed_points?wid=1">View details of abstraction purposes</a>
</div>
<div class="datatable">
<label>Abstraction conditions</label>
<div class="licenceAnswerv7">
{{ pData.condition1 }}</br>
{% if pData.condition2 %}
{{ pData.condition2 }}</br>
{% endif %}
{% if pData.condition3 %}
{{ pData.condition3 }}</br>
{% endif %}
{% if pData.condition4 %}
{{ pData.condition4 }}</br>
{% endif %}
{% if pData.condition5 %}
{{ pData.condition5 }}</br>
{% endif %}
<a href="/v15/conditions?wid=1">View details of abstraction conditions</a>
</div>
</div>
<div class="datatable">
<label>Abstraction amounts</label>
<div class="licenceAnswerv7">
{{ pData.amount1 }}</br>
{% if pData.amount2 %}
{{ pData.amount2 }}</br>
{% endif %}
{% if pData.amount3 %}
{{ pData.amount3 }}</br>
{% endif %}
{% if pData.amount4 %}
{{ pData.amount4 }}</br>
{% endif %}
{% if pData.amount5 %}
{{ pData.amount5 }}</br>
{% endif %}
<a href="/v15/pages/points_purposes/tabbed_points?wid=1">View details of amounts</a>
</div>
<br>
<br>
{% endif %}
{% endfor %}
</main>
{% endblock %}
|
christinagyles-ea/water
|
app/v6/views/v15/pages/online_licence_rename.html
|
HTML
|
mit
| 5,248
|
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports BMNGOneImageLayer
* @version $Id: BMNGOneImageLayer.js 2942 2015-03-30 21:16:36Z tgaskins $
*/
define([
'../layer/RenderableLayer',
'../geom/Sector',
'../shapes/SurfaceImage',
'../util/WWUtil'
],
function (RenderableLayer,
Sector,
SurfaceImage,
WWUtil) {
"use strict";
/**
* Constructs a Blue Marble image layer that spans the entire globe.
* @alias BMNGOneImageLayer
* @constructor
* @augments RenderableLayer
* @classdesc Displays a Blue Marble image layer that spans the entire globe with a single image.
*/
var BMNGOneImageLayer = function () {
RenderableLayer.call(this, "Blue Marble Image");
var surfaceImage = new SurfaceImage(Sector.FULL_SPHERE,
WorldWind.configuration.baseUrl + "images/BMNG_world.topo.bathy.200405.3.2048x1024.jpg");
this.addRenderable(surfaceImage);
this.pickEnabled = false;
this.minActiveAltitude = 3e6;
};
BMNGOneImageLayer.prototype = Object.create(RenderableLayer.prototype);
return BMNGOneImageLayer;
});
|
NASAWorldWindResearch/AgroSphere
|
src/layer/BMNGOneImageLayer.js
|
JavaScript
|
mit
| 1,436
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Action'
db.create_table('gratitude_action', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('gratitude', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['gratitude.Gratitude'], null=True)),
('action', self.gf('django.db.models.fields.CharField')(max_length=500)),
('created', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, blank=True)),
('modified', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, blank=True)),
))
db.send_create_signal('gratitude', ['Action'])
def backwards(self, orm):
# Deleting model 'Action'
db.delete_table('gratitude_action')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'gratitude.action': {
'Meta': {'object_name': 'Action'},
'action': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'gratitude': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gratitude.Gratitude']", 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'gratitude.gratitude': {
'Meta': {'object_name': 'Gratitude'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'stash_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}),
'stashed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'text': ('django.db.models.fields.CharField', [], {'max_length': '5000'}),
'user_id': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'gratitude.setting': {
'Meta': {'object_name': 'Setting'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
'gratitude.userdetail': {
'Meta': {'object_name': 'UserDetail'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'no_messages': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
}
}
complete_apps = ['gratitude']
|
adamfeuer/ArtOfGratitude_app
|
gratitude/migrations/0005_auto__add_action.py
|
Python
|
mit
| 7,091
|
package org.luyue.commons.logging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Slf4jExample {
public static void main(String[] args) {
// if using slf4j simple implementation, set logger level to TRACE
// System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
// if using slf4j Java logging implementation, specify path to the config file
// System.setProperty("java.util.logging.config.file", "<Path_to_logging.properties>");
Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
final String message = "Hello logging!";
logger.trace(message);
logger.debug(message);
logger.info(message);
logger.warn(message);
logger.error(message);
}
}
|
yuelu/logging
|
src/main/java/org/luyue/commons/logging/Slf4jExample.java
|
Java
|
mit
| 800
|
var SimpleSuperclass = Hotcake.define(SimpleSuperclass,
{
ctor: function ()
{
this.value = 100;
},
incrementReturn: function ()
{
this.value += 100;
return this.value;
}
});
var SimpleSubclass = Hotcake.define(SimpleSubclass,
{
returnValue: function ()
{
return -11;
}
}, SimpleSuperclass);
var SimpleSubclass2 = Hotcake.define(SimpleSubclass,
{
returnNothing: function ()
{
return -1999;
}
}, SimpleSubclass2);
|
Knetic/hotcake
|
tests/acceptanceTest_3_2.js
|
JavaScript
|
mit
| 504
|
#pragma once
#include <string>
namespace bim
{
enum class MessageType
{
INFO,
WARNING,
ERROR
};
typedef void (*MessageCallback)(MessageType _type, const std::string& _message);
// Replace the internal message callback with a custom one.
// The default callback will output to std::cerr.
void setMessageCallback(MessageCallback _callback);
namespace details
{
extern MessageCallback g_theCallback;
inline void buildMessageString(std::string&) {}
template<typename T, typename... TArgs>
void buildMessageString(std::string& _message, T _first, TArgs... _args)
{
_message += std::to_string(_first);
buildMessageString(_message, _args...);
}
template<typename... TArgs>
void buildMessageString(std::string& _message, const char* _first, TArgs... _args)
{
_message += _first;
buildMessageString(_message, _args...);
}
template<typename... TArgs>
void buildMessageString(std::string& _message, const std::string& _first, TArgs... _args)
{
_message += _first;
buildMessageString(_message, _args...);
}
}
template<typename... TArgs>
void sendMessage(MessageType _type, TArgs... _args)
{
std::string msg;
details::buildMessageString(msg, _args...);
details::g_theCallback(_type, msg);
}
}
|
Jojendersie/Bim
|
include/bim/log.hpp
|
C++
|
mit
| 1,259
|
// Template Source: BaseEntityCollectionRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.Team;
import com.microsoft.graph.models.TeamVisibilityType;
import com.microsoft.graph.models.ClonableTeamParts;
import java.util.EnumSet;
import com.microsoft.graph.models.TeamworkActivityTopic;
import com.microsoft.graph.models.ItemBody;
import com.microsoft.graph.models.KeyValuePair;
import com.microsoft.graph.models.TeamworkNotificationRecipient;
import com.microsoft.graph.models.ChatMessage;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.options.QueryOption;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseEntityCollectionRequest;
import com.microsoft.graph.requests.TeamCollectionResponse;
import com.microsoft.graph.requests.TeamCollectionRequestBuilder;
import com.microsoft.graph.requests.TeamCollectionRequest;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Team Collection Request.
*/
public class TeamCollectionRequest extends BaseEntityCollectionRequest<Team, TeamCollectionResponse, TeamCollectionPage> {
/**
* The request builder for this collection of Team
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public TeamCollectionRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, TeamCollectionResponse.class, TeamCollectionPage.class, TeamCollectionRequestBuilder.class);
}
/**
* Creates a new Team
* @param newTeam the Team to create
* @return a future with the created object
*/
@Nonnull
public java.util.concurrent.CompletableFuture<Team> postAsync(@Nonnull final Team newTeam) {
final String requestUrl = getBaseRequest().getRequestUrl().toString();
return new TeamRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
.buildRequest(getBaseRequest().getHeaders())
.postAsync(newTeam);
}
/**
* Creates a new Team
* @param newTeam the Team to create
* @return the newly created object
*/
@Nonnull
public Team post(@Nonnull final Team newTeam) throws ClientException {
final String requestUrl = getBaseRequest().getRequestUrl().toString();
return new TeamRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
.buildRequest(getBaseRequest().getHeaders())
.post(newTeam);
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
/**
* Sets the filter clause for the request
*
* @param value the filter clause
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest filter(@Nonnull final String value) {
addFilterOption(value);
return this;
}
/**
* Sets the order by clause for the request
*
* @param value the order by clause
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest orderBy(@Nonnull final String value) {
addOrderByOption(value);
return this;
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the top value for the request
*
* @param value the max number of items to return
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest top(final int value) {
addTopOption(value);
return this;
}
/**
* Sets the count value for the request
*
* @param value whether or not to return the count of objects with the request
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest count(final boolean value) {
addCountOption(value);
return this;
}
/**
* Sets the count value to true for the request
*
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest count() {
addCountOption(true);
return this;
}
/**
* Sets the skip value for the request
*
* @param value of the number of items to skip
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest skip(final int value) {
addSkipOption(value);
return this;
}
/**
* Add Skip token for pagination
* @param skipToken - Token for pagination
* @return the updated request
*/
@Nonnull
public TeamCollectionRequest skipToken(@Nonnull final String skipToken) {
addSkipTokenOption(skipToken);
return this;
}
}
|
microsoftgraph/msgraph-sdk-java
|
src/main/java/com/microsoft/graph/requests/TeamCollectionRequest.java
|
Java
|
mit
| 5,788
|
/* THIS FILE IS GENERATED. DO NOT EDIT */
package seph.lang.structure;
import seph.lang.*;
import seph.lang.persistent.*;
public class SephObject_n_6 extends SephObjectStructure {
public final IPersistentVector parents;
public final String selector0;
public final SephObject cell0;
public final String selector1;
public final SephObject cell1;
public final String selector2;
public final SephObject cell2;
public final String selector3;
public final SephObject cell3;
public final String selector4;
public final SephObject cell4;
public final String selector5;
public final SephObject cell5;
public SephObject_n_6(IPersistentMap meta, IPersistentVector parents, String selector0, SephObject cell0, String selector1, SephObject cell1, String selector2, SephObject cell2, String selector3, SephObject cell3, String selector4, SephObject cell4, String selector5, SephObject cell5) {
super(meta);
this.parents = parents;
this.selector0 = selector0.intern();
this.cell0 = cell0;
this.selector1 = selector1.intern();
this.cell1 = cell1;
this.selector2 = selector2.intern();
this.cell2 = cell2;
this.selector3 = selector3.intern();
this.cell3 = cell3;
this.selector4 = selector4.intern();
this.cell4 = cell4;
this.selector5 = selector5.intern();
this.cell5 = cell5;
}
public final SephObject get(String name) {
name = name.intern();
if(name == this.selector0) return this.cell0;
if(name == this.selector1) return this.cell1;
if(name == this.selector2) return this.cell2;
if(name == this.selector3) return this.cell3;
if(name == this.selector4) return this.cell4;
if(name == this.selector5) return this.cell5;
SephObject result;
for(ISeq s = this.parents.seq(); s != null; s = s.next()) {
result = ((SephObject)s.first()).get(name);
if(result != null) return result;
}
return null;
}
}
|
seph-lang/seph
|
src/main/seph/lang/structure/SephObject_n_6.java
|
Java
|
mit
| 2,077
|
require 'test/assert'
require 'test/colorize'
require 'test/spec/stats'
module Moon
module Test
class SpecSuite
include Colorize
include Moon::Test::Assert
attr_accessor :name
attr_accessor :logger
attr_accessor :debug_logger
attr_accessor :tests
def initialize(name = nil)
init_assertions
# spec log
@logger = Logger.new
# debug debug_logger
@debug_logger = NullIO::OUT
@name = name || "#{self.class}"
@tests = []
@test_stack = [@tests]
end
def describe(obj)
@debug_logger.puts "#{name}.DESCRIBE: #{obj}"
@test_stack << []
yield self
stack = @test_stack.pop
stack.map! do |a|
str, b = *a
[obj.to_s + " " + str, b]
end
@test_stack[-1].concat(stack)
end
alias :context :describe
def describe_top(&block)
describe(name, &block)
end
def it(str, &block)
@debug_logger.puts "#{name}.IT: #{str}"
@test_stack[-1] << [str, block]
end
def given(str, &block)
it("given #{str}", &block)
end
def spec(str = '', &block)
it(str, &block)
end
def spec_bm(*args, &block)
spec do
bench(*args, &block)
end
end
def run_specs(options = {})
with_assertions = options.fetch(:assertions, true)
realtime = options.fetch(:realtime_result, true)
quiet = options.fetch(:quiet, false)
time_then = Time.now
passed = 0
stats = Stats.new
stats.logger = @logger
@tests.each do |a|
test_name, block = *a
@debug_logger.print test_name
if (n = 120 - test_name.size - 7) > 0
@debug_logger.print '.' * n
end
failure = false
catch_assertion_errors do |err|
failure = true
stats.add_failure [test_name, err]
end
begin
instance_exec(&block)
if failure
@debug_logger.print colorize('FAILED', :light_red)
else
@debug_logger.print colorize('PASSED', :light_green)
stats.add_pass
end
rescue AssertError
# just ignore it
rescue Exception => ex
stats.add_failure [test_name, ex]
@debug_logger.puts colorize('KO!', :light_red)
@debug_logger.puts ex.inspect
@debug_logger.puts ex.backtrace.join("\n")
end
@debug_logger.puts
end
time_now = Time.now
stats.time_diff = (time_now - time_then)
stats.test_count = @tests.size
stats.assertions = @assertions
stats.assertion_errors = @assertion_errors
stats.display unless quiet
stats
end
end
# Basic Spec Framework
module Spec
attr_accessor :spec_suite
def init_test_suite
@spec_suite = SpecSuite.new
end
def describe(*a, &b)
@spec_suite.describe(*a, &b)
end
def context(*a, &b)
@spec_suite.context(*a, &b)
end
def it(*a, &b)
@spec_suite.it(*a, &b)
end
def spec(*a, &b)
@spec_suite.spec(*a, &b)
end
def spec_bm(*a, &b)
@spec_suite.spec_bm(*a, &b)
end
def run_specs(*a, &b)
@spec_suite.run_specs(*a, &b)
end
end
include Spec
end
end
|
polyfox/moon-packages
|
lib/moon/packages/test/spec.rb
|
Ruby
|
mit
| 3,502
|
# JSONP
**Content-Type: "text/javascript"**
## What is JSONP, and why was it created?
Say you're on domain `example.com`, and you want to make a request to domain `example.net`. To do so, you need to cross domain boundaries, a no-no in most of browserland.
The one item that bypasses this limitation is `<script>` tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really do anything with the results, the script just gets evaluated.
Enter **JSONP**. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.
For example, say the server expects a parameter called callback to enable its JSONP capabilities. Then your request would look like:
```
http://www.example.net/sample?callback=mycallback
```
Without JSONP, this might return some basic JavaScript object, like so:
```json
{ "foo": "bar" }
```
However, with `JSONP`, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:
```js
mycallback({ "foo": "bar" });
```
As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:
```js
mycallback = function(data){
alert(data.foo);
};
```
And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!
It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequest is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.
**However**, CORS[*](https://github.com/kataras/iris/tree/master/_examples/auth/cors) is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.
> https://stackoverflow.com/a/2067584 _(source)_
## Send JSONP with Iris
The `Context.JSONP(v, ...opts)` is the method which sends JSONP responses to the client. It accepts the value and optional settings for rendering. The `JSONP` options structure looks like this:
```go
type JSONP struct {
Indent string
Callback string
}
```
> If `Indent` field is empty and the application runs without optimizations, the `Indent` field will be automatically set to `4 spaces`.
So, if we want to write a JSONP with indentation of two spaces and a callback extracted from URL Query Parameter of `?callback=mycallback`, we write something like that:
```go
func handler(ctx iris.Context) {
callback := ctx.URLParamDefault("callback", "defaultCallback")
response := map[string]interface{}{"foo": "bar"}
options := iris.JSONP{Indent: " ", Callback:true}
ctx.JSONP(response, options)
}
```
If we want to render a Go struct as JSONP's callback data, the struct's fields we want to render should be **[exported](https://tour.golang.org/basics/3)**, and optionally tagged with the `json` struct tag. Look the exaple below:
```go
type Item struct {
Name string `json:"name"`
}
func handler(ctx iris.Context) {
response := Item{
Name: "gopher",
}
ctx.JSONP(response, iris.JSONP{Callback: "addToCard"})
}
```
<!-- slide:break-100 -->
|
kataras/build-a-better-web-together
|
responses/jsonp.md
|
Markdown
|
mit
| 3,599
|
module Fog
module Brightbox
class Compute
class Real
def get_server_type(identifier, options = {})
return nil if identifier.nil? || identifier == ""
request(
:expects => [200],
:method => 'GET',
:path => "/1.0/server_types/#{identifier}",
:headers => {"Content-Type" => "application/json"},
:body => options.to_json
)
end
end
end
end
end
|
jbenjore/JPs-love-project
|
annotate-models/ruby/1.9.1/gems/fog-0.8.1/lib/fog/compute/requests/brightbox/get_server_type.rb
|
Ruby
|
mit
| 481
|
<DIV NAME="detail" ID="detail" xmlns="http://www.w3.org/TR/REC-html40"><H3><A NAME='detail_CaptureObjectDataToFile'></A>TestComplete GenericMasterFunctions::<BIG>CaptureObjectDataToFile</BIG>
</H3> <TABLE><TR>
<TD class="borderStyle"><SPAN CLASS='Support' TITLE='SmartBear Test Complete'>TC</SPAN></TD>
</TR></TABLE>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Copy the current contents of an object's data to a file.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"><detailed_desc xmlns="">
Only an object that Robot can perform an ObjectData VP
on can use this command. By default, the files will be
stored in the active "Test" directory. If you specify a
relative path, the path will be relative to the project
directory. The directory for a full or relative path
must already exist.
</detailed_desc><BR/>
</DIV>
<BR/>
<DIV NAME="list" ID="other">
<p><B>Fields: </B><SMALL>[ ]=Optional with Default Value</SMALL></p>
<code class="safs">
<OL start="5" ><LI>
<B>File</B>
<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
The name of the file used to store the object data.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"><detailed_desc xmlns="">
The name of the file used to store the object data.
By default, the files will be
stored in the active "Test" directory. If you specify a
relative path, the path will be relative to the project
directory. The directory for a full or relative path
must already exist.
</detailed_desc><BR/>
</DIV>
</LI>
<LI>[ <B>FileEncoding</B> = ]<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Specify a character encoding to be used when saving data to a file.
If it is not specified, the system default file encoding will be used.
The encoding should be a valid string supported by Java; if it is not valid,
the system default file encoding will be used instead.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>[ <B>FilterMode</B> = ]<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
(Future) Specify a file filter to use to process the text before comparison.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>[ <B>FilterOptions</B> = ]<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
(Future) Specify filter options to use with the file filter.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI></OL ></code>
<br/>
<p><B>Examples:</B></p>
<code class="safs"><UL>
<LI>
<B><usage xmlns="">T, Browser, HTMLTable, CaptureObjectDataToFile, aFilename.ext, , "", ""</usage></B>
<BR/><DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Capture the HTMLTable object data contents to a file.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"><detailed_desc xmlns="">
Capture the HTMLTable object data contents to the
Datapool\Test\aFilename.ext file.<br>
Note the unused reserved fields for FileFilter and FilterOptions.
</detailed_desc><BR/>
</DIV>
</LI>
<LI>
<B><usage xmlns="">T, Browser, HTMLTable, CaptureObjectDataToFile, myDirectory\aFilename.ext, , "", ""</usage></B>
<BR/><DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Capture the HTMLTable object data contents to a file.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"><detailed_desc xmlns="">
Capture the HTMLTable object data contents to the
[project]\myDirectory\aFilename.ext file.<br>
Note the unused reserved fields for FileFilter and FilterOptions.
</detailed_desc><BR/>
</DIV>
</LI>
<LI>
<B><usage xmlns="">T, Browser, HTMLTable, CaptureObjectDataToFile, tableContent.ext</usage></B>
<BR/><DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Capture the HTMLTable object data contents to a file.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"><detailed_desc xmlns="">
Capture the HTMLTable object data contents,
save it to file tableContent.ext by the system default file encoding.
</detailed_desc><BR/>
</DIV>
</LI>
<LI>
<B><usage xmlns="">T, Browser, HTMLTable, CaptureObjectDataToFile, tableContent.ext, "UTF-8"</usage></B>
<BR/><DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Capture the HTMLTable object data contents to a file.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"><detailed_desc xmlns="">
Capture the HTMLTable object data contents,
save it to file tableContent.ext by UTF-8 encoding.
</detailed_desc><BR/>
</DIV>
</LI>
</UL>
</code>
<br/>
<A href="SAFSReferenceKey.htm" alt="Reference Legend or Key">
<SMALL><B>[How To Read This Reference]</B></SMALL>
</A>
<HR/>
</DIV>
</DIV>
|
kid551/safsdev.test.github.io
|
keyref/TestCompleteGenericMasterFunctionsCaptureObjectDataToFile.html
|
HTML
|
mit
| 5,255
|
/*
* QCELP decoder
* Copyright (c) 2007 Reynaldo H. Verdejo Pinochet
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* QCELP decoder
* @author Reynaldo H. Verdejo Pinochet
* @remark FFmpeg merging spearheaded by Kenan Gillet
* @remark Development mentored by Benjamin Larson
*/
#include "internal.h"
#include "get_bits.h"
#include "qcelpdata.h"
#include "celp_math.h"
#include "celp_filters.h"
#include "acelp_filters.h"
#include "acelp_vectors.h"
#include "lsp.h"
typedef enum {
I_F_Q = -1, /**< insufficient frame quality */
SILENCE,
RATE_OCTAVE,
RATE_QUARTER,
RATE_HALF,
RATE_FULL
} qcelp_packet_rate;
typedef struct {
AVFrame avframe;
GetBitContext gb;
qcelp_packet_rate bitrate;
QCELPFrame frame; /**< unpacked data frame */
uint8_t erasure_count;
uint8_t octave_count; /**< count the consecutive RATE_OCTAVE frames */
float prev_lspf[10];
float predictor_lspf[10];/**< LSP predictor for RATE_OCTAVE and I_F_Q */
float pitch_synthesis_filter_mem[303];
float pitch_pre_filter_mem[303];
float rnd_fir_filter_mem[180];
float formant_mem[170];
float last_codebook_gain;
int prev_g1[2];
int prev_bitrate;
float pitch_gain[4];
uint8_t pitch_lag[4];
uint16_t first16bits;
uint8_t warned_buf_mismatch_bitrate;
/* postfilter */
float postfilter_synth_mem[10];
float postfilter_agc_mem;
float postfilter_tilt_mem;
} QCELPContext;
/**
* Initialize the speech codec according to the specification.
*
* TIA/EIA/IS-733 2.4.9
*/
static av_cold int qcelp_decode_init(AVCodecContext *avctx)
{
QCELPContext *q = (QCELPContext *)avctx->priv_data;
int i;
avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
for (i = 0; i < 10; i++)
q->prev_lspf[i] = (i + 1) / 11.;
avcodec_get_frame_defaults(&q->avframe);
avctx->coded_frame = &q->avframe;
return 0;
}
/**
* Decode the 10 quantized LSP frequencies from the LSPV/LSP
* transmission codes of any bitrate and check for badly received packets.
*
* @param q the context
* @param lspf line spectral pair frequencies
*
* @return 0 on success, -1 if the packet is badly received
*
* TIA/EIA/IS-733 2.4.3.2.6.2-2, 2.4.8.7.3
*/
static int decode_lspf(QCELPContext *q, float *lspf)
{
int i;
float tmp_lspf, smooth, erasure_coeff;
const float *predictors;
if (q->bitrate == RATE_OCTAVE || q->bitrate == I_F_Q) {
predictors = q->prev_bitrate != RATE_OCTAVE &&
q->prev_bitrate != I_F_Q ? q->prev_lspf
: q->predictor_lspf;
if (q->bitrate == RATE_OCTAVE) {
q->octave_count++;
for (i = 0; i < 10; i++) {
q->predictor_lspf[i] =
lspf[i] = (q->frame.lspv[i] ? QCELP_LSP_SPREAD_FACTOR
: -QCELP_LSP_SPREAD_FACTOR) +
predictors[i] * QCELP_LSP_OCTAVE_PREDICTOR +
(i + 1) * ((1 - QCELP_LSP_OCTAVE_PREDICTOR) / 11);
}
smooth = q->octave_count < 10 ? .875 : 0.1;
} else {
erasure_coeff = QCELP_LSP_OCTAVE_PREDICTOR;
assert(q->bitrate == I_F_Q);
if (q->erasure_count > 1)
erasure_coeff *= q->erasure_count < 4 ? 0.9 : 0.7;
for (i = 0; i < 10; i++) {
q->predictor_lspf[i] =
lspf[i] = (i + 1) * (1 - erasure_coeff) / 11 +
erasure_coeff * predictors[i];
}
smooth = 0.125;
}
// Check the stability of the LSP frequencies.
lspf[0] = FFMAX(lspf[0], QCELP_LSP_SPREAD_FACTOR);
for (i = 1; i < 10; i++)
lspf[i] = FFMAX(lspf[i], lspf[i - 1] + QCELP_LSP_SPREAD_FACTOR);
lspf[9] = FFMIN(lspf[9], 1.0 - QCELP_LSP_SPREAD_FACTOR);
for (i = 9; i > 0; i--)
lspf[i - 1] = FFMIN(lspf[i - 1], lspf[i] - QCELP_LSP_SPREAD_FACTOR);
// Low-pass filter the LSP frequencies.
ff_weighted_vector_sumf(lspf, lspf, q->prev_lspf, smooth, 1.0 - smooth, 10);
} else {
q->octave_count = 0;
tmp_lspf = 0.;
for (i = 0; i < 5; i++) {
lspf[2 * i + 0] = tmp_lspf += qcelp_lspvq[i][q->frame.lspv[i]][0] * 0.0001;
lspf[2 * i + 1] = tmp_lspf += qcelp_lspvq[i][q->frame.lspv[i]][1] * 0.0001;
}
// Check for badly received packets.
if (q->bitrate == RATE_QUARTER) {
if (lspf[9] <= .70 || lspf[9] >= .97)
return -1;
for (i = 3; i < 10; i++)
if (fabs(lspf[i] - lspf[i - 2]) < .08)
return -1;
} else {
if (lspf[9] <= .66 || lspf[9] >= .985)
return -1;
for (i = 4; i < 10; i++)
if (fabs(lspf[i] - lspf[i - 4]) < .0931)
return -1;
}
}
return 0;
}
/**
* Convert codebook transmission codes to GAIN and INDEX.
*
* @param q the context
* @param gain array holding the decoded gain
*
* TIA/EIA/IS-733 2.4.6.2
*/
static void decode_gain_and_index(QCELPContext *q, float *gain)
{
int i, subframes_count, g1[16];
float slope;
if (q->bitrate >= RATE_QUARTER) {
switch (q->bitrate) {
case RATE_FULL: subframes_count = 16; break;
case RATE_HALF: subframes_count = 4; break;
default: subframes_count = 5;
}
for (i = 0; i < subframes_count; i++) {
g1[i] = 4 * q->frame.cbgain[i];
if (q->bitrate == RATE_FULL && !((i + 1) & 3)) {
g1[i] += av_clip((g1[i - 1] + g1[i - 2] + g1[i - 3]) / 3 - 6, 0, 32);
}
gain[i] = qcelp_g12ga[g1[i]];
if (q->frame.cbsign[i]) {
gain[i] = -gain[i];
q->frame.cindex[i] = (q->frame.cindex[i] - 89) & 127;
}
}
q->prev_g1[0] = g1[i - 2];
q->prev_g1[1] = g1[i - 1];
q->last_codebook_gain = qcelp_g12ga[g1[i - 1]];
if (q->bitrate == RATE_QUARTER) {
// Provide smoothing of the unvoiced excitation energy.
gain[7] = gain[4];
gain[6] = 0.4 * gain[3] + 0.6 * gain[4];
gain[5] = gain[3];
gain[4] = 0.8 * gain[2] + 0.2 * gain[3];
gain[3] = 0.2 * gain[1] + 0.8 * gain[2];
gain[2] = gain[1];
gain[1] = 0.6 * gain[0] + 0.4 * gain[1];
}
} else if (q->bitrate != SILENCE) {
if (q->bitrate == RATE_OCTAVE) {
g1[0] = 2 * q->frame.cbgain[0] +
av_clip((q->prev_g1[0] + q->prev_g1[1]) / 2 - 5, 0, 54);
subframes_count = 8;
} else {
assert(q->bitrate == I_F_Q);
g1[0] = q->prev_g1[1];
switch (q->erasure_count) {
case 1 : break;
case 2 : g1[0] -= 1; break;
case 3 : g1[0] -= 2; break;
default: g1[0] -= 6;
}
if (g1[0] < 0)
g1[0] = 0;
subframes_count = 4;
}
// This interpolation is done to produce smoother background noise.
slope = 0.5 * (qcelp_g12ga[g1[0]] - q->last_codebook_gain) / subframes_count;
for (i = 1; i <= subframes_count; i++)
gain[i - 1] = q->last_codebook_gain + slope * i;
q->last_codebook_gain = gain[i - 2];
q->prev_g1[0] = q->prev_g1[1];
q->prev_g1[1] = g1[0];
}
}
/**
* If the received packet is Rate 1/4 a further sanity check is made of the
* codebook gain.
*
* @param cbgain the unpacked cbgain array
* @return -1 if the sanity check fails, 0 otherwise
*
* TIA/EIA/IS-733 2.4.8.7.3
*/
static int codebook_sanity_check_for_rate_quarter(const uint8_t *cbgain)
{
int i, diff, prev_diff = 0;
for (i = 1; i < 5; i++) {
diff = cbgain[i] - cbgain[i-1];
if (FFABS(diff) > 10)
return -1;
else if (FFABS(diff - prev_diff) > 12)
return -1;
prev_diff = diff;
}
return 0;
}
/**
* Compute the scaled codebook vector Cdn From INDEX and GAIN
* for all rates.
*
* The specification lacks some information here.
*
* TIA/EIA/IS-733 has an omission on the codebook index determination
* formula for RATE_FULL and RATE_HALF frames at section 2.4.8.1.1. It says
* you have to subtract the decoded index parameter from the given scaled
* codebook vector index 'n' to get the desired circular codebook index, but
* it does not mention that you have to clamp 'n' to [0-9] in order to get
* RI-compliant results.
*
* The reason for this mistake seems to be the fact they forgot to mention you
* have to do these calculations per codebook subframe and adjust given
* equation values accordingly.
*
* @param q the context
* @param gain array holding the 4 pitch subframe gain values
* @param cdn_vector array for the generated scaled codebook vector
*/
static void compute_svector(QCELPContext *q, const float *gain,
float *cdn_vector)
{
int i, j, k;
uint16_t cbseed, cindex;
float *rnd, tmp_gain, fir_filter_value;
switch (q->bitrate) {
case RATE_FULL:
for (i = 0; i < 16; i++) {
tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
cindex = -q->frame.cindex[i];
for (j = 0; j < 10; j++)
*cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cindex++ & 127];
}
break;
case RATE_HALF:
for (i = 0; i < 4; i++) {
tmp_gain = gain[i] * QCELP_RATE_HALF_CODEBOOK_RATIO;
cindex = -q->frame.cindex[i];
for (j = 0; j < 40; j++)
*cdn_vector++ = tmp_gain * qcelp_rate_half_codebook[cindex++ & 127];
}
break;
case RATE_QUARTER:
cbseed = (0x0003 & q->frame.lspv[4]) << 14 |
(0x003F & q->frame.lspv[3]) << 8 |
(0x0060 & q->frame.lspv[2]) << 1 |
(0x0007 & q->frame.lspv[1]) << 3 |
(0x0038 & q->frame.lspv[0]) >> 3;
rnd = q->rnd_fir_filter_mem + 20;
for (i = 0; i < 8; i++) {
tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
for (k = 0; k < 20; k++) {
cbseed = 521 * cbseed + 259;
*rnd = (int16_t) cbseed;
// FIR filter
fir_filter_value = 0.0;
for (j = 0; j < 10; j++)
fir_filter_value += qcelp_rnd_fir_coefs[j] *
(rnd[-j] + rnd[-20+j]);
fir_filter_value += qcelp_rnd_fir_coefs[10] * rnd[-10];
*cdn_vector++ = tmp_gain * fir_filter_value;
rnd++;
}
}
memcpy(q->rnd_fir_filter_mem, q->rnd_fir_filter_mem + 160,
20 * sizeof(float));
break;
case RATE_OCTAVE:
cbseed = q->first16bits;
for (i = 0; i < 8; i++) {
tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
for (j = 0; j < 20; j++) {
cbseed = 521 * cbseed + 259;
*cdn_vector++ = tmp_gain * (int16_t) cbseed;
}
}
break;
case I_F_Q:
cbseed = -44; // random codebook index
for (i = 0; i < 4; i++) {
tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
for (j = 0; j < 40; j++)
*cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cbseed++ & 127];
}
break;
case SILENCE:
memset(cdn_vector, 0, 160 * sizeof(float));
break;
}
}
/**
* Apply generic gain control.
*
* @param v_out output vector
* @param v_in gain-controlled vector
* @param v_ref vector to control gain of
*
* TIA/EIA/IS-733 2.4.8.3, 2.4.8.6
*/
static void apply_gain_ctrl(float *v_out, const float *v_ref, const float *v_in)
{
int i;
for (i = 0; i < 160; i += 40)
ff_scale_vector_to_given_sum_of_squares(v_out + i, v_in + i,
ff_dot_productf(v_ref + i,
v_ref + i, 40),
40);
}
/**
* Apply filter in pitch-subframe steps.
*
* @param memory buffer for the previous state of the filter
* - must be able to contain 303 elements
* - the 143 first elements are from the previous state
* - the next 160 are for output
* @param v_in input filter vector
* @param gain per-subframe gain array, each element is between 0.0 and 2.0
* @param lag per-subframe lag array, each element is
* - between 16 and 143 if its corresponding pfrac is 0,
* - between 16 and 139 otherwise
* @param pfrac per-subframe boolean array, 1 if the lag is fractional, 0
* otherwise
*
* @return filter output vector
*/
static const float *do_pitchfilter(float memory[303], const float v_in[160],
const float gain[4], const uint8_t *lag,
const uint8_t pfrac[4])
{
int i, j;
float *v_lag, *v_out;
const float *v_len;
v_out = memory + 143; // Output vector starts at memory[143].
for (i = 0; i < 4; i++) {
if (gain[i]) {
v_lag = memory + 143 + 40 * i - lag[i];
for (v_len = v_in + 40; v_in < v_len; v_in++) {
if (pfrac[i]) { // If it is a fractional lag...
for (j = 0, *v_out = 0.; j < 4; j++)
*v_out += qcelp_hammsinc_table[j] * (v_lag[j - 4] + v_lag[3 - j]);
} else
*v_out = *v_lag;
*v_out = *v_in + gain[i] * *v_out;
v_lag++;
v_out++;
}
} else {
memcpy(v_out, v_in, 40 * sizeof(float));
v_in += 40;
v_out += 40;
}
}
memmove(memory, memory + 160, 143 * sizeof(float));
return memory + 143;
}
/**
* Apply pitch synthesis filter and pitch prefilter to the scaled codebook vector.
* TIA/EIA/IS-733 2.4.5.2, 2.4.8.7.2
*
* @param q the context
* @param cdn_vector the scaled codebook vector
*/
static void apply_pitch_filters(QCELPContext *q, float *cdn_vector)
{
int i;
const float *v_synthesis_filtered, *v_pre_filtered;
if (q->bitrate >= RATE_HALF || q->bitrate == SILENCE ||
(q->bitrate == I_F_Q && (q->prev_bitrate >= RATE_HALF))) {
if (q->bitrate >= RATE_HALF) {
// Compute gain & lag for the whole frame.
for (i = 0; i < 4; i++) {
q->pitch_gain[i] = q->frame.plag[i] ? (q->frame.pgain[i] + 1) * 0.25 : 0.0;
q->pitch_lag[i] = q->frame.plag[i] + 16;
}
} else {
float max_pitch_gain;
if (q->bitrate == I_F_Q) {
if (q->erasure_count < 3)
max_pitch_gain = 0.9 - 0.3 * (q->erasure_count - 1);
else
max_pitch_gain = 0.0;
} else {
assert(q->bitrate == SILENCE);
max_pitch_gain = 1.0;
}
for (i = 0; i < 4; i++)
q->pitch_gain[i] = FFMIN(q->pitch_gain[i], max_pitch_gain);
memset(q->frame.pfrac, 0, sizeof(q->frame.pfrac));
}
// pitch synthesis filter
v_synthesis_filtered = do_pitchfilter(q->pitch_synthesis_filter_mem,
cdn_vector, q->pitch_gain,
q->pitch_lag, q->frame.pfrac);
// pitch prefilter update
for (i = 0; i < 4; i++)
q->pitch_gain[i] = 0.5 * FFMIN(q->pitch_gain[i], 1.0);
v_pre_filtered = do_pitchfilter(q->pitch_pre_filter_mem,
v_synthesis_filtered,
q->pitch_gain, q->pitch_lag,
q->frame.pfrac);
apply_gain_ctrl(cdn_vector, v_synthesis_filtered, v_pre_filtered);
} else {
memcpy(q->pitch_synthesis_filter_mem, cdn_vector + 17, 143 * sizeof(float));
memcpy(q->pitch_pre_filter_mem, cdn_vector + 17, 143 * sizeof(float));
memset(q->pitch_gain, 0, sizeof(q->pitch_gain));
memset(q->pitch_lag, 0, sizeof(q->pitch_lag));
}
}
/**
* Reconstruct LPC coefficients from the line spectral pair frequencies
* and perform bandwidth expansion.
*
* @param lspf line spectral pair frequencies
* @param lpc linear predictive coding coefficients
*
* @note: bandwidth_expansion_coeff could be precalculated into a table
* but it seems to be slower on x86
*
* TIA/EIA/IS-733 2.4.3.3.5
*/
static void lspf2lpc(const float *lspf, float *lpc)
{
double lsp[10];
double bandwidth_expansion_coeff = QCELP_BANDWIDTH_EXPANSION_COEFF;
int i;
for (i = 0; i < 10; i++)
lsp[i] = cos(M_PI * lspf[i]);
ff_acelp_lspd2lpc(lsp, lpc, 5);
for (i = 0; i < 10; i++) {
lpc[i] *= bandwidth_expansion_coeff;
bandwidth_expansion_coeff *= QCELP_BANDWIDTH_EXPANSION_COEFF;
}
}
/**
* Interpolate LSP frequencies and compute LPC coefficients
* for a given bitrate & pitch subframe.
*
* TIA/EIA/IS-733 2.4.3.3.4, 2.4.8.7.2
*
* @param q the context
* @param curr_lspf LSP frequencies vector of the current frame
* @param lpc float vector for the resulting LPC
* @param subframe_num frame number in decoded stream
*/
static void interpolate_lpc(QCELPContext *q, const float *curr_lspf,
float *lpc, const int subframe_num)
{
float interpolated_lspf[10];
float weight;
if (q->bitrate >= RATE_QUARTER)
weight = 0.25 * (subframe_num + 1);
else if (q->bitrate == RATE_OCTAVE && !subframe_num)
weight = 0.625;
else
weight = 1.0;
if (weight != 1.0) {
ff_weighted_vector_sumf(interpolated_lspf, curr_lspf, q->prev_lspf,
weight, 1.0 - weight, 10);
lspf2lpc(interpolated_lspf, lpc);
} else if (q->bitrate >= RATE_QUARTER ||
(q->bitrate == I_F_Q && !subframe_num))
lspf2lpc(curr_lspf, lpc);
else if (q->bitrate == SILENCE && !subframe_num)
lspf2lpc(q->prev_lspf, lpc);
}
static qcelp_packet_rate buf_size2bitrate(const int buf_size)
{
switch (buf_size) {
case 35: return RATE_FULL;
case 17: return RATE_HALF;
case 8: return RATE_QUARTER;
case 4: return RATE_OCTAVE;
case 1: return SILENCE;
}
return I_F_Q;
}
/**
* Determine the bitrate from the frame size and/or the first byte of the frame.
*
* @param avctx the AV codec context
* @param buf_size length of the buffer
* @param buf the bufffer
*
* @return the bitrate on success,
* I_F_Q if the bitrate cannot be satisfactorily determined
*
* TIA/EIA/IS-733 2.4.8.7.1
*/
static qcelp_packet_rate determine_bitrate(AVCodecContext *avctx,
const int buf_size,
const uint8_t **buf)
{
qcelp_packet_rate bitrate;
if ((bitrate = buf_size2bitrate(buf_size)) >= 0) {
if (bitrate > **buf) {
QCELPContext *q = (QCELPContext *)avctx->priv_data;
if (!q->warned_buf_mismatch_bitrate) {
av_log(avctx, AV_LOG_WARNING,
"Claimed bitrate and buffer size mismatch.\n");
q->warned_buf_mismatch_bitrate = 1;
}
bitrate = (qcelp_packet_rate)(**buf);
} else if (bitrate < **buf) {
av_log(avctx, AV_LOG_ERROR,
"Buffer is too small for the claimed bitrate.\n");
return I_F_Q;
}
(*buf)++;
} else if ((bitrate = buf_size2bitrate(buf_size + 1)) >= 0) {
av_log(avctx, AV_LOG_WARNING,
"Bitrate byte is missing, guessing the bitrate from packet size.\n");
} else
return I_F_Q;
if (bitrate == SILENCE) {
//FIXME: Remove experimental warning when tested with samples.
av_log_ask_for_sample(avctx, "'Blank frame handling is experimental.");
}
return bitrate;
}
static void warn_insufficient_frame_quality(AVCodecContext *avctx,
const char *message)
{
av_log(avctx, AV_LOG_WARNING, "Frame #%d, IFQ: %s\n",
avctx->frame_number, message);
}
static void postfilter(QCELPContext *q, float *samples, float *lpc)
{
static const float pow_0_775[10] = {
0.775000f, 0.600625f, 0.465484f, 0.360750f, 0.279582f,
0.216676f, 0.167924f, 0.130141f, 0.100859f, 0.078166f
}, pow_0_625[10] = {
0.625000f, 0.390625f, 0.244141f, 0.152588f, 0.095367f,
0.059605f, 0.037253f, 0.023283f, 0.014552f, 0.009095f
};
float lpc_s[10], lpc_p[10], pole_out[170], zero_out[160];
int n;
for (n = 0; n < 10; n++) {
lpc_s[n] = lpc[n] * pow_0_625[n];
lpc_p[n] = lpc[n] * pow_0_775[n];
}
ff_celp_lp_zero_synthesis_filterf(zero_out, lpc_s,
q->formant_mem + 10, 160, 10);
memcpy(pole_out, q->postfilter_synth_mem, sizeof(float) * 10);
ff_celp_lp_synthesis_filterf(pole_out + 10, lpc_p, zero_out, 160, 10);
memcpy(q->postfilter_synth_mem, pole_out + 160, sizeof(float) * 10);
ff_tilt_compensation(&q->postfilter_tilt_mem, 0.3f, pole_out + 10, 160);
ff_adaptive_gain_control(samples, pole_out + 10,
ff_dot_productf(q->formant_mem + 10,
q->formant_mem + 10, 160),
160, 0.9375, &q->postfilter_agc_mem);
}
static int qcelp_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
QCELPContext *q = (QCELPContext *)avctx->priv_data;
float *outbuffer;
int i, ret;
float quantized_lspf[10], lpc[10];
float gain[16];
float *formant_mem;
/* get output buffer */
q->avframe.nb_samples = 160;
if ((ret = avctx->get_buffer(avctx, &q->avframe)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
outbuffer = (float *)q->avframe.data[0];
if ((q->bitrate = determine_bitrate(avctx, buf_size, &buf)) == I_F_Q) {
warn_insufficient_frame_quality(avctx, "bitrate cannot be determined.");
goto erasure;
}
if (q->bitrate == RATE_OCTAVE &&
(q->first16bits = AV_RB16(buf)) == 0xFFFF) {
warn_insufficient_frame_quality(avctx, "Bitrate is 1/8 and first 16 bits are on.");
goto erasure;
}
if (q->bitrate > SILENCE) {
const QCELPBitmap *bitmaps = qcelp_unpacking_bitmaps_per_rate[q->bitrate];
const QCELPBitmap *bitmaps_end = qcelp_unpacking_bitmaps_per_rate[q->bitrate] +
qcelp_unpacking_bitmaps_lengths[q->bitrate];
uint8_t *unpacked_data = (uint8_t *)&q->frame;
init_get_bits(&q->gb, buf, 8 * buf_size);
memset(&q->frame, 0, sizeof(QCELPFrame));
for (; bitmaps < bitmaps_end; bitmaps++)
unpacked_data[bitmaps->index] |= get_bits(&q->gb, bitmaps->bitlen) << bitmaps->bitpos;
// Check for erasures/blanks on rates 1, 1/4 and 1/8.
if (q->frame.reserved) {
warn_insufficient_frame_quality(avctx, "Wrong data in reserved frame area.");
goto erasure;
}
if (q->bitrate == RATE_QUARTER &&
codebook_sanity_check_for_rate_quarter(q->frame.cbgain)) {
warn_insufficient_frame_quality(avctx, "Codebook gain sanity check failed.");
goto erasure;
}
if (q->bitrate >= RATE_HALF) {
for (i = 0; i < 4; i++) {
if (q->frame.pfrac[i] && q->frame.plag[i] >= 124) {
warn_insufficient_frame_quality(avctx, "Cannot initialize pitch filter.");
goto erasure;
}
}
}
}
decode_gain_and_index(q, gain);
compute_svector(q, gain, outbuffer);
if (decode_lspf(q, quantized_lspf) < 0) {
warn_insufficient_frame_quality(avctx, "Badly received packets in frame.");
goto erasure;
}
apply_pitch_filters(q, outbuffer);
if (q->bitrate == I_F_Q) {
erasure:
q->bitrate = I_F_Q;
q->erasure_count++;
decode_gain_and_index(q, gain);
compute_svector(q, gain, outbuffer);
decode_lspf(q, quantized_lspf);
apply_pitch_filters(q, outbuffer);
} else
q->erasure_count = 0;
formant_mem = q->formant_mem + 10;
for (i = 0; i < 4; i++) {
interpolate_lpc(q, quantized_lspf, lpc, i);
ff_celp_lp_synthesis_filterf(formant_mem, lpc, outbuffer + i * 40, 40, 10);
formant_mem += 40;
}
// postfilter, as per TIA/EIA/IS-733 2.4.8.6
postfilter(q, outbuffer, lpc);
memcpy(q->formant_mem, q->formant_mem + 160, 10 * sizeof(float));
memcpy(q->prev_lspf, quantized_lspf, sizeof(q->prev_lspf));
q->prev_bitrate = q->bitrate;
*got_frame_ptr = 1;
*(AVFrame *)data = q->avframe;
return buf_size;
}
AVCodec ff_qcelp_decoder = {
/*.name = */ "qcelp",
/*.type = */ AVMEDIA_TYPE_AUDIO,
/*.id = */ CODEC_ID_QCELP,
/*.priv_data_size = */ sizeof(QCELPContext),
/*.init = */ qcelp_decode_init,
/*.encode = */ 0,
/*.close = */ 0,
/*.decode = */ qcelp_decode_frame,
/*.capabilities = */ CODEC_CAP_DR1,
/*.next = */ 0,
/*.flush = */ 0,
/*.supported_framerates = */ 0,
/*.pix_fmts = */ 0,
/*.long_name = */ NULL_IF_CONFIG_SMALL("QCELP / PureVoice"),
};
|
mcodegeeks/OpenKODE-Framework
|
01_Develop/libXMFFmpeg/Source/libavcodec/qcelpdec.cpp
|
C++
|
mit
| 26,887
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Página login
*/
class Login extends CI_Controller {
/**
* Login constructor.
*/
public function __construct()
{
parent::__construct();
/** Carregamento de bibliotecas */
$this->load->library('form_validation');
$this->load->library('encrypt');
$this->load->helper('user');
/** Carregamento de models */
$this->load->model('UsuarioM', 'usuario');
$this->load->model('LocalizacaoM', 'localizacao');
}
/**
* Página index do login
*/
public function index(){
/** Regras de validação do formulario */
$this->form_validation->set_rules('login', 'Login', 'required|trim|callback_check');
$this->form_validation->set_rules('senha', 'Senha', 'required|trim');
/** Se foi executado o formulario e esteve OK*/
if ($this->form_validation->run() == true) {
/** @var string $login Valor do campo login do formulario*/
$login = $this->input->post('login');
$user = $this->usuario->getByLogin($login)->result_array()[0];
$session['usuario'] = $user;
/** Cria uma session com todos os dados do usuario e sua localização caso tiver */
setSesUsuario($user);
$session['login'] = true;
$this->session->set_userdata($session);
redirect(site_url('dashboard'));
}else{
/** Carrega a View login */
$this->load->view('geral/login');
}
}
/**
* Regra de formulário setado no campo login
*
* @param string $login
* @return bool
*/
public function check($login)
{
$senha = $this->input->post('senha');
$user = $this->usuario->getByLogin($login)->result_array();
/** Verifica se encontrou no banco */
if (count($user) == 1) {
$user = $user[0];
/** Verifica se a senha informada é igual a cadastrada */
if ($this->encrypt->decode($user['Senha']) == $senha) {
return true;
}
}
/** Retorna mensagem caso o usuario ou senha esteja errado */
$this->form_validation->set_message('check', ' Usuário e/ou senha não existe ou incorreto.');
return false;
}
public function sair(){
$this->session->unset_userdata('login');
$this->session->unset_userdata('usuario');
$this->session->unset_userdata('permissao');
redirect(site_url('login'));
}
}
|
leobelini/guiapet
|
application/controllers/geral/Login.php
|
PHP
|
mit
| 2,623
|
class FixedExpensesController < BaseExpensesController
private
def expenses_title
"Fixed expenses"
end
def expenses_path
event_fixed_expenses_path(@event)
end
def expenses
@event.fixed_expenses
end
def expense_path(expense=@expense)
event_fixed_expense_path(@event.id, expense.id)
end
def edit_expense_path(expense)
edit_event_fixed_expense_path(@event.id, expense.id)
end
def expense_class
FixedExpense
end
end
|
CultivateHQ/ballpark
|
app/controllers/fixed_expenses_controller.rb
|
Ruby
|
mit
| 466
|
<html>
<head>
<title>David Napley's panel show appearances</title>
<script type="text/javascript" src="../common.js"></script>
<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>
<script type="text/javascript" src="../people.js"></script>
<!--#include virtual="head.txt" -->
</head>
<body>
<!--#include virtual="nav.txt" -->
<div class="page">
<h1>David Napley's panel show appearances</h1>
<p>David Napley (born 1915-07-25<sup><a href="https://en.wikipedia.org/wiki/David_Napley">[ref]</a></sup>) has appeared in <span class="total">1</span> episodes between 1981-1981. <a href="https://en.wikipedia.org/wiki/David_Napley">David Napley on Wikipedia</a>.</p>
<div class="performerholder">
<table class="performer">
<tr style="vertical-align:bottom;">
<td><div style="height:100px;" class="performances male" title="1"></div><span class="year">1981</span></td>
</tr>
</table>
</div>
<ol class="episodes">
<li><strong>1981-02-05</strong> / <a href="../shows/question-time.html">Question Time</a></li>
</ol>
</div>
</body>
</html>
|
slowe/panelshows
|
people/5h2h0uj0.html
|
HTML
|
mit
| 1,075
|
body {
background: url(../images/refugee_pic.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
div.white_overlay {
width: 60%;
height: 75%;
align: "middle";
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
opacity:0.7;
background-color: white;
z-index:-5;
}
button {
height: 50px;
width: 600px;
border-radius: 4px;
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
cursor: pointer;
background-color: white;
color: black;
border: 2px solid #F78F1E;
}
button:hover {
background-color: #F78F1E;
color: white;
}
/**/
#menu_heading {
position: absolute;
top: 19%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
font-size:48px;
}
#button_review {
position: absolute;
top: 25%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
}
#button_saved {
position: absolute;
top: 35%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
}
#button_change {
position: absolute;
top: 45%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
}
#button_progress {
position: absolute;
top: 55%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
}
#button_review {
position: absolute;
top: 65%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
}
#button_logout {
position: absolute;
top: 75%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
}
#index_logo {
position: absolute;
top: 93%;
left: 93%;
transform: translateX(-50%) translateY(-50%);
color: #000;
z-index:1;
}
|
AlexanderJones/HackJustice-Website
|
english/menu.css
|
CSS
|
mit
| 2,263
|
# frozen_string_literal: true
RSpec.describe Bitaculous::Animatify::Paths do
subject(:animatify) { Bitaculous::Animatify }
let(:trail) { File.expand_path '../../../../../', __FILE__ }
let(:assets_path) { File.expand_path 'assets', trail }
let(:fonts_path) { File.expand_path 'fonts', assets_path }
let(:images_path) { File.expand_path 'images', assets_path }
let(:javascripts_path) { File.expand_path 'javascripts', assets_path }
let(:stylesheets_path) { File.expand_path 'stylesheets', assets_path }
let(:vendor_path) { File.expand_path 'vendor', trail }
let(:vendor_assets_path) { File.expand_path 'assets', vendor_path }
let(:vendor_fonts_path) { File.expand_path 'fonts', vendor_assets_path }
let(:vendor_images_path) { File.expand_path 'images', vendor_assets_path }
let(:vendor_javascripts_path) { File.expand_path 'javascripts', vendor_assets_path }
let(:vendor_stylesheets_path) { File.expand_path 'stylesheets', vendor_assets_path }
it 'returns the assets path' do
expect(animatify.assets_path).to eql assets_path
end
it 'returns the fonts path' do
expect(animatify.fonts_path).to eql fonts_path
end
it 'returns the images path' do
expect(animatify.images_path).to eql images_path
end
it 'returns the javascripts path' do
expect(animatify.javascripts_path).to eql javascripts_path
end
it 'returns the stylesheets path' do
expect(animatify.stylesheets_path).to eql stylesheets_path
end
it 'returns the vendor path' do
expect(animatify.vendor_path).to eql vendor_path
end
it 'returns the vendor assets path' do
expect(animatify.vendor_assets_path).to eql vendor_assets_path
end
it 'returns the vendor fonts path' do
expect(animatify.vendor_fonts_path).to eql vendor_fonts_path
end
it 'returns the vendor images path' do
expect(animatify.vendor_images_path).to eql vendor_images_path
end
it 'returns the vendor javascripts path' do
expect(animatify.vendor_javascripts_path).to eql vendor_javascripts_path
end
it 'returns vendor stylesheets path' do
expect(animatify.vendor_stylesheets_path).to eql vendor_stylesheets_path
end
end
|
bitaculous/animatify
|
spec/unit/bitaculous/animatify/paths_spec.rb
|
Ruby
|
mit
| 2,260
|
ktarbet.github.io
=================
Karl Tarbet ktarbet at gmail.com
Karl is the primary author of <a href="https://github.com/usbr/Pisces">Pisces</a>. Pisces is a desktop application that graphs and analyzes time series data. Pisces is designed to organize, graph, and analyze natural resource data that varies with time: gauge height, river flow, water temperature, etc.
Gradually varied flow (<a href="http://ktarbet.github.io/circular_gvf/index.html"> GVF</a>) in circular pipe. HTML5 and JavaScript
<a href="http://ktarbet.github.io"> ktarbet.github.io </a>
|
ktarbet/ktarbet.github.io
|
README.md
|
Markdown
|
mit
| 573
|
---
layout: main
---
<div class="project">
<div class="project-meta">
<div class="project-date">{{ page.date | date: "%B %d, %Y" }}</div>
<h3 class="project-title">{{ page.title }}</h3>
</div>
{{ content }}
</div>
|
spieswl/spieswl.github.io
|
_layouts/project.html
|
HTML
|
mit
| 257
|
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015 Axel Mendoza <aekroft@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
|
aek/solt_sftp
|
src/solt_sftp/__init__.py
|
Python
|
mit
| 1,132
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>SLF4J 1.7.26 Reference Package org.slf4j.event</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="style" />
</head>
<body>
<div class="overview">
<ul>
<li>
<a href="../../../overview-summary.html">Overview</a>
</li>
<li class="selected">Package</li>
</ul>
</div>
<div class="framenoframe">
<ul>
<li>
<a href="../../../index.html" target="_top">FRAMES</a>
</li>
<li>
<a href="package-summary.html" target="_top">NO FRAMES</a>
</li>
</ul>
</div>
<h2>Package org.slf4j.event</h2>
<table class="summary">
<thead>
<tr>
<th>Class Summary</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="EventConstants.html" target="classFrame">EventConstants</a>
</td>
</tr>
<tr>
<td>
<a href="EventRecodingLogger.html" target="classFrame">EventRecodingLogger</a>
</td>
</tr>
<tr>
<td>
<a href="Level.html" target="classFrame">Level</a>
</td>
</tr>
<tr>
<td>
<a href="LoggingEvent.html" target="classFrame">LoggingEvent</a>
</td>
</tr>
<tr>
<td>
<a href="SubstituteLoggingEvent.html" target="classFrame">SubstituteLoggingEvent</a>
</td>
</tr>
</tbody>
</table>
<div class="overview">
<ul>
<li>
<a href="../../../overview-summary.html">Overview</a>
</li>
<li class="selected">Package</li>
</ul>
</div>
<div class="framenoframe">
<ul>
<li>
<a href="../../../index.html" target="_top">FRAMES</a>
</li>
<li>
<a href="package-summary.html" target="_top">NO FRAMES</a>
</li>
</ul>
</div>
<hr />
Copyright © 2005-2019 QOS.ch. All Rights Reserved.
</body>
</html>
|
JPAT-ROSEMARY/SCUBA
|
org.jpat.scuba.external.slf4j/slf4j-1.7.26/site/xref/org/slf4j/event/package-summary.html
|
HTML
|
mit
| 2,589
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Build.Shared;
namespace Microsoft.Build.Framework
{
/// <summary>
/// Arguments for task finished events
/// </summary>
// WARNING: marking a type [Serializable] without implementing
// ISerializable imposes a serialization contract -- it is a
// promise to never change the type's fields i.e. the type is
// immutable; adding new fields in the next version of the type
// without following certain special FX guidelines, can break both
// forward and backward compatibility
[Serializable]
public class TaskFinishedEventArgs : BuildStatusEventArgs
{
/// <summary>
/// Default constructor
/// </summary>
protected TaskFinishedEventArgs()
: base()
{
// do nothing
}
/// <summary>
/// This constructor allows event data to be initialized.
/// Sender is assumed to be "MSBuild".
/// </summary>
/// <param name="message">text message</param>
/// <param name="helpKeyword">help keyword </param>
/// <param name="projectFile">project file</param>
/// <param name="taskFile">file in which the task is defined</param>
/// <param name="taskName">task name</param>
/// <param name="succeeded">true indicates task succeed</param>
public TaskFinishedEventArgs
(
string message,
string helpKeyword,
string projectFile,
string taskFile,
string taskName,
bool succeeded
)
: this(message, helpKeyword, projectFile, taskFile, taskName, succeeded, DateTime.UtcNow)
{
}
/// <summary>
/// This constructor allows event data to be initialized and the timestamp to be set
/// Sender is assumed to be "MSBuild".
/// </summary>
/// <param name="message">text message</param>
/// <param name="helpKeyword">help keyword </param>
/// <param name="projectFile">project file</param>
/// <param name="taskFile">file in which the task is defined</param>
/// <param name="taskName">task name</param>
/// <param name="succeeded">true indicates task succeed</param>
/// <param name="eventTimestamp">Timestamp when event was created</param>
public TaskFinishedEventArgs
(
string message,
string helpKeyword,
string projectFile,
string taskFile,
string taskName,
bool succeeded,
DateTime eventTimestamp
)
: base(message, helpKeyword, "MSBuild", eventTimestamp)
{
this.taskName = taskName;
this.taskFile = taskFile;
this.succeeded = succeeded;
this.projectFile = projectFile;
}
private string taskName;
private string projectFile;
private string taskFile;
private bool succeeded;
#region CustomSerializationToStream
/// <summary>
/// Serializes to a stream through a binary writer
/// </summary>
/// <param name="writer">Binary writer which is attached to the stream the event will be serialized into</param>
internal override void WriteToStream(BinaryWriter writer)
{
base.WriteToStream(writer);
writer.WriteOptionalString(taskName);
writer.WriteOptionalString(projectFile);
writer.WriteOptionalString(taskFile);
writer.Write(succeeded);
}
/// <summary>
/// Deserializes the Errorevent from a stream through a binary reader
/// </summary>
/// <param name="reader">Binary reader which is attached to the stream the event will be deserialized from</param>
/// <param name="version">The version of the runtime the message packet was created from</param>
internal override void CreateFromStream(BinaryReader reader, int version)
{
base.CreateFromStream(reader, version);
taskName = reader.ReadByte() == 0 ? null : reader.ReadString();
projectFile = reader.ReadByte() == 0 ? null : reader.ReadString();
taskFile = reader.ReadByte() == 0 ? null : reader.ReadString();
succeeded = reader.ReadBoolean();
}
#endregion
/// <summary>
/// Task Name
/// </summary>
public string TaskName => taskName;
/// <summary>
/// True if target built successfully, false otherwise
/// </summary>
public bool Succeeded => succeeded;
/// <summary>
/// Project file associated with event.
/// </summary>
public string ProjectFile => projectFile;
/// <summary>
/// MSBuild file where this task was defined.
/// </summary>
public string TaskFile => taskFile;
}
}
|
AndyGerlicher/msbuild
|
src/Framework/TaskFinishedEventArgs.cs
|
C#
|
mit
| 5,137
|
<?php
namespace App\Controllers;
use \Flight;
use \GUMP;
use App\Models;
/*
*To handle all the user operations
*
*/
class UserController
{
protected $user;
/**
* Function name
*
* what the function does
*
* @param (type) (name) about this param
* @return (type) (name)
*/
public function __construct($user)
{
$this->user=$user;
}
/**
* getAssignedDevices
*
* what the function does
*
* @param (type) (name) about this param
* @return (type) (name)
*/
public function getAssignedDevices()
{
$deviceInformationArray=array();
$deviceDetails=json_decode(Flight::request()->getBody(),true);
//$response=$this->admin->getDeviceInfoFromIMEI();
$is_valid = GUMP::is_valid($deviceDetails, array(
'employee_id' => 'required'
));
if($is_valid === true)
{
$deviceInformationArray[]=$deviceDetails["employee_id"];
$deviceInformationArray[]="Assigned";
$response=$this->user->getAssignedDeviceList($deviceInformationArray);
Flight::json($response);
}
else
{
echo Flight::json(array(API_RESPONSE_STATUS_CODE=>400,API_RESPONSE_STATUS_ERROR_MESSAGE=>"Bad Request",API_RESPONSE=>$is_valid));
}
}
/**
* changePin
*
* change user pin
*
* @param (type) (name) about this param
* @return (type) (name)
*/
public function changePin()
{
$userInformationArray=array();
$userDetails=json_decode(Flight::request()->getBody(),true);
//$response=$this->admin->getDeviceInfoFromIMEI();
$is_valid = GUMP::is_valid($userDetails, array(
'employee_id' => 'required',
'new_pin'=>'required',
'old_pin'=>'required'
));
if($is_valid === true)
{
$userInformationArray[]=$userDetails["employee_id"];
$userInformationArray[]=$userDetails["old_pin"];
$userInformationArray[]=$userDetails["new_pin"];
$response=$this->user->changeUserPin($userInformationArray);
Flight::json($response);
}
else
{
echo Flight::json(array(API_RESPONSE_STATUS_CODE=>400,API_RESPONSE_STATUS_ERROR_MESSAGE=>"Bad Request",API_RESPONSE=>$is_valid));
}
}
/**
* resetPin
*
* reset user pin
*
* @param (type) (name) about this param
* @return (type) (name)
*/
public function resetPin()
{
$userInformationArray=array();
$userDetails=json_decode(Flight::request()->getBody(),true);
//$response=$this->admin->getDeviceInfoFromIMEI();
$is_valid = GUMP::is_valid($userDetails, array(
'employee_id' => 'required',
'pin'=>'required',
));
if($is_valid === true)
{
$userInformationArray[]=$userDetails["pin"];
$userInformationArray[]=$userDetails["employee_id"];
$response=$this->user->resetUserPin($userInformationArray);
Flight::json($response);
}
else
{
echo Flight::json(array(API_RESPONSE_STATUS_CODE=>400,API_RESPONSE_STATUS_ERROR_MESSAGE=>"Bad Request",API_RESPONSE=>$is_valid));
}
}
/**
* userRole
*
* Find the user role
*
* @param (type) (name) about this param
* @return (type) (name)
*/
public function userRole()
{
$userInformationArray=array();
$userDetails=json_decode(Flight::request()->getBody(),true);
//$response=$this->admin->getDeviceInfoFromIMEI();
$is_valid = GUMP::is_valid($userDetails, array(
'employee_id' => 'required'
));
if($is_valid === true)
{
$userInformationArray[]=$userDetails["employee_id"];
$response=$this->user->checkUserRole($userInformationArray);
Flight::json($response);
}
else
{
echo Flight::json(array(API_RESPONSE_STATUS_CODE=>400,API_RESPONSE_STATUS_ERROR_MESSAGE=>"Bad Request",API_RESPONSE=>$is_valid));
}
}
/**
* userRole
*
* Find the user role
*
* @param (type) (name) about this param
* @return (type) (name)
*/
public function addUser()
{
$userInformationArray=array();
$userDetails=json_decode(Flight::request()->getBody(),true);
//$response=$this->admin->getDeviceInfoFromIMEI();
$is_valid = GUMP::is_valid($userDetails, array(
'first_name' => 'required',
'last_name' => 'required',
'employee_id' => 'required',
'pin' => 'required'
));
if($is_valid === true)
{
$userInformationArray[]=$userDetails["first_name"];
$userInformationArray[]=$userDetails["last_name"];
$userInformationArray[]=$userDetails["employee_id"];
$userInformationArray[]=$userDetails["pin"];
error_log(print_r($userInformationArray));
$response=$this->user->addNewUser($userInformationArray);
Flight::json($response);
}
else
{
echo Flight::json(array(API_RESPONSE_STATUS_CODE=>400,API_RESPONSE_STATUS_ERROR_MESSAGE=>"Bad Request",API_RESPONSE=>$is_valid));
}
}
}
|
TarentoIndia/TarentoDeviceManagement
|
views-code-php/device-management/app/controllers/UserController.php
|
PHP
|
mit
| 5,706
|
# 致谢
本博客外观基于 [码志](http://mazhuang.org) 修改,感谢!
|
zhangqinning/zhangqinning.github.io
|
README.md
|
Markdown
|
mit
| 86
|
<?php
declare(strict_types=1);
namespace Tests\SitemapPlugin\Controller;
final class SitemapProductControllerApiImagesTest extends XmlApiTestCase
{
public function testShowActionResponse()
{
$this->loadFixturesFromFiles(['channel.yaml', 'product_images.yaml']);
$this->generateSitemaps();
$response = $this->getBufferedResponse('/sitemap/products.xml');
$this->assertResponse($response, 'show_sitemap_products_image');
$this->deleteSitemaps();
}
}
|
stefandoorn/sitemap-plugin
|
tests/Controller/SitemapProductControllerApiImagesTest.php
|
PHP
|
mit
| 504
|
/*
The default style.
*/
body {
cursor: default !important;
padding-top: 20px !important;
font-size: 12px !important;
font-family: 'DejaVu Sans', 'Verdana', sans-serif !important;
background: url('/static/img/background.png') no-repeat top center #272B30;
background-attachment: fixed;
}
a {
font-weight: bold;
text-decoration: none !important;
}
a:hover {
text-decoration: underline !important;
}
.logo {
margin-bottom: 15px;
text-align: center;
}
.right {
text-align: right;
}
.middle {
text-align: center;
}
.emblem {
max-width: 128px;
max-height: 128px;
}
.outfit {
top: -16px;
text-align: right;
position: relative;
z-index: 100;
}
.outfit2 {
top: -16px;
left: -16px;
text-align: right;
margin-top: 16px;
position: relative;
z-index: 100;
}
.progress-bar-custom {
background-color: #5E58AF;
}
.tab-content {
margin-top: 25px;
}
/*
Progress bars with centered text
http://stackoverflow.com/questions/12937470/twitter-bootstrap-center-text-on-progress-bar
*/
.progress {
position: relative;
}
.progress span {
position: absolute;
display: block;
width: 100%;
}
/*
Defined button sizes to allow an alternative to inline css.
*/
.btn-custom-tiny {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 45px;
}
.btn-custom-xsmall {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 55px;
}
.btn-custom-small {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 65px;
}
.btn-custom-medium {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 75px;
}
.btn-custom-large {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 85px;
}
.btn-custom-xlarge {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 95px;
}
.btn-custom-huge {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
width: 105px;
}
/*
Change the max width of a popover so it doesn't wrap.
*/
.popover {
max-width: 100%;
}
|
diath/pyfsw
|
pyfsw/static/css/style.css
|
CSS
|
mit
| 2,081
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Emanuele</title>
<meta name="description" content="Emanuele">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='http://fonts.googleapis.com/css?family=Roboto:100' rel='stylesheet' type='text/css'>
<link href="normalize.css" rel="stylesheet">
<link href="main.css" rel="stylesheet">
</head>
<body>
<a href="mailto:emanuele@lostcrew.it">Emanuele</a>
</body>
</html>
|
LostCrew/emanuele
|
index.html
|
HTML
|
mit
| 505
|
# PXFrostedImageView
[](http://cocoapods.org/pods/PXFrostedImageView)
[](http://cocoapods.org/pods/PXFrostedImageView)
[](http://cocoapods.org/pods/PXFrostedImageView)
## Usage
Use it like an image view. Makes a great background for other views.
To run the example project, clone the repo, and run `pod install` from the Example directory first.
## Installation
PXFrostedImageView is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod "PXFrostedImageView"
```
## Author
Daniel Blakemore, DanBlakemore@gmail.com
## License
PXFrostedImageView is available under the MIT license. See the LICENSE file for more info.
|
pixio/PXFrostedImageView
|
README.md
|
Markdown
|
mit
| 942
|
from snowball.utils import SnowMachine
from snowball.climate import WeatherProbe
# Note: multiline import limits line length
from snowball.water.phases import (
WaterVapor, IceCrystal, SnowFlake
)
def let_it_snow():
"""
Makes it snow, using a SnowMachine when weather doesn't allow it.
Returns a list of SnowFlakes.
Example::
>>> let_it_snow()
The snow machine is broken. No snow today. :/
[]
>>> let_it_snow()
[<snowball.water.phases.SnowFlake object at 0x101dbc210>,
<snowball.water.phases.SnowFlake object at 0x101dbc350>,
<snowball.water.phases.SnowFlake object at 0x101dbc1d0>,
<snowball.water.phases.SnowFlake object at 0x101dbc190>,
<snowball.water.phases.SnowFlake object at 0x101dbc3d0>,
<snowball.water.phases.SnowFlake object at 0x101dbc410>,
<snowball.water.phases.SnowFlake object at 0x101dbc450>,
<snowball.water.phases.SnowFlake object at 0x101dbc390>,
<snowball.water.phases.SnowFlake object at 0x101dbc310>]
"""
# Create a WeatherProbe
weather_probe = WeatherProbe()
if weather_probe.temperature < 0 and weather_probe.clouds:
# There's clouds and it's cold enough
# Create necessary components
vapor = WaterVapor()
ice = IceCrystal()
# Start with empty list of flakes
snow_flakes = []
# Now create 10 snowflakes
for counter in xrange(1, 10):
flake = SnowFlake(vapor, ice)
# Add flake to list
snow_flakes.append(flake)
return snow_flakes
else:
# The weather's not right, use the SnowMachine
snow_machine = SnowMachine()
snow_flakes = snow_machine.let_it_snow()
return snow_flakes
|
dokterbob/slf-programming-workshops
|
examples/snowball/main.py
|
Python
|
mit
| 1,795
|
package com.percolate.coffee.util.api.request;
import android.content.res.Resources;
import com.octo.android.robospice.request.springandroid.SpringAndroidSpiceRequest;
import com.percolate.coffee.R;
import com.percolate.coffee.model.CoffeeTypeDetailed;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
/**
* Show Request; gets a single {@link com.percolate.coffee.model.CoffeeType} given a {@link com.percolate.coffee.model.CoffeeType} CoffeeTypeId
*/
public class CoffeeTypeShowRequest extends SpringAndroidSpiceRequest<CoffeeTypeDetailed> {
Resources mResources;
String mId;
/**
*Constructor
* @param coffeeTypeId {@link com.percolate.coffee.model.CoffeeType} mCoffeeTypeId
* @param resources applications resources
*/
public CoffeeTypeShowRequest(String coffeeTypeId, Resources resources) {
super(CoffeeTypeDetailed.class);
mResources = resources;
mId = coffeeTypeId;
if (coffeeTypeId == null) {
throw new NullPointerException("THE ID CANNOT BE NULL");
}
}
@Override
public CoffeeTypeDetailed loadDataFromNetwork() throws Exception {
String url = mResources.getString(R.string.percolate_coffee_base_url) + mId + "/";
HttpHeaders headers = new HttpHeaders() {
{
set("Authorization", mResources.getString(R.string.percolate_coffee_api_key));
}
};
headers.add("Content-Type", "application/json");
headers.add("Accept", "application/json");
CoffeeTypeDetailed coffeeType = getRestTemplate().exchange(url.toLowerCase(), HttpMethod.GET, new HttpEntity<Object>(headers), CoffeeTypeDetailed.class).getBody();
return coffeeType;
}
/**
* @param resources
* @return a String which can be used as a standard key for caching the results of this request
*/
public String getCacheKey(Resources resources) {
return resources.getString(R.string.percolate_coffee_coffee_type_show_cache_key);
}
}
|
aaemman/Coffee
|
java/com/percolate/coffee/util/api/request/CoffeeTypeShowRequest.java
|
Java
|
mit
| 1,947
|
enyo.kind({
name: "bootstrap.Breadcrumb",
tag: "ul",
classes: "breadcrumb",
defaultKind: "bootstrap.MenuItem",
});
|
pangea/bootstrap-enyo
|
source/Breadcrumbs.js
|
JavaScript
|
mit
| 119
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>class Test::Unit::Data::ClassMethods::Loader - test-unit-3.3.0 Documentation</title>
<script type="text/javascript">
var rdoc_rel_prefix = "../../../../";
</script>
<script src="../../../../js/jquery.js"></script>
<script src="../../../../js/darkfish.js"></script>
<link href="../../../../css/fonts.css" rel="stylesheet">
<link href="../../../../css/rdoc.css" rel="stylesheet">
<body id="top" role="document" class="class">
<nav role="navigation">
<div id="project-navigation">
<div id="home-section" role="region" title="Quick navigation" class="nav-section">
<h2>
<a href="../../../../index.html" rel="home">Home</a>
</h2>
<div id="table-of-contents-navigation">
<a href="../../../../table_of_contents.html#pages">Pages</a>
<a href="../../../../table_of_contents.html#classes">Classes</a>
<a href="../../../../table_of_contents.html#methods">Methods</a>
</div>
</div>
<div id="search-section" role="search" class="project-section initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<div id="search-field-wrapper">
<input id="search-field" role="combobox" aria-label="Search"
aria-autocomplete="list" aria-controls="search-results"
type="text" name="search" placeholder="Search" spellcheck="false"
title="Type to search, Up and Down to navigate, Enter to load">
</div>
<ul id="search-results" aria-label="Search Results"
aria-busy="false" aria-expanded="false"
aria-atomic="false" class="initially-hidden"></ul>
</form>
</div>
</div>
<div id="class-metadata">
<div id="parent-class-section" class="nav-section">
<h3>Parent</h3>
<p class="link"><a href="../../../../Object.html">Object</a>
</div>
<!-- Method Quickref -->
<div id="method-list-section" class="nav-section">
<h3>Methods</h3>
<ul class="link-list" role="directory">
<li ><a href="#method-c-new">::new</a>
<li ><a href="#method-i-load">#load</a>
<li ><a href="#method-i-load_csv">#load_csv</a>
<li ><a href="#method-i-load_tsv">#load_tsv</a>
<li ><a href="#method-i-normalize_value">#normalize_value</a>
<li ><a href="#method-i-set_test_data">#set_test_data</a>
</ul>
</div>
</div>
</nav>
<main role="main" aria-labelledby="class-Test::Unit::Data::ClassMethods::Loader">
<h1 id="class-Test::Unit::Data::ClassMethods::Loader" class="class">
class Test::Unit::Data::ClassMethods::Loader
</h1>
<section class="description">
</section>
<section id="5Buntitled-5D" class="documentation-section">
<section id="public-class-5Buntitled-5D-method-details" class="method-section">
<header>
<h3>Public Class Methods</h3>
</header>
<div id="method-c-new" class="method-detail ">
<div class="method-heading">
<span class="method-name">new</span><span
class="method-args">(test_case)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>@api private</p>
<div class="method-source-code" id="new-source">
<pre><span class="ruby-comment"># File lib/test/unit/data.rb, line 206</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">initialize</span>(<span class="ruby-identifier">test_case</span>)
<span class="ruby-ivar">@test_case</span> = <span class="ruby-identifier">test_case</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</section>
<section id="public-instance-5Buntitled-5D-method-details" class="method-section">
<header>
<h3>Public Instance Methods</h3>
</header>
<div id="method-i-load" class="method-detail ">
<div class="method-heading">
<span class="method-name">load</span><span
class="method-args">(file_name)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Load data from file.</p>
<p>@param [String] file_name full path to test data file.</p>
<pre>File format is automatically detected from filename extension.</pre>
<p>@raise [ArgumentError] if <code>file_name</code> is not supported file
format. @see <a href="Loader.html#method-i-load_csv">load_csv</a> @see <a
href="Loader.html#method-i-load_tsv">load_tsv</a> @api private</p>
<div class="method-source-code" id="load-source">
<pre><span class="ruby-comment"># File lib/test/unit/data.rb, line 218</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">load</span>(<span class="ruby-identifier">file_name</span>)
<span class="ruby-keyword">case</span> <span class="ruby-constant">File</span>.<span class="ruby-identifier">extname</span>(<span class="ruby-identifier">file_name</span>).<span class="ruby-identifier">downcase</span>
<span class="ruby-keyword">when</span> <span class="ruby-string">".csv"</span>
<span class="ruby-identifier">load_csv</span>(<span class="ruby-identifier">file_name</span>)
<span class="ruby-keyword">when</span> <span class="ruby-string">".tsv"</span>
<span class="ruby-identifier">load_tsv</span>(<span class="ruby-identifier">file_name</span>)
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">raise</span> <span class="ruby-constant">ArgumentError</span>, <span class="ruby-node">"unsupported file format: <#{file_name}>"</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div id="method-i-load_csv" class="method-detail ">
<div class="method-heading">
<span class="method-name">load_csv</span><span
class="method-args">(file_name)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Load data from CSV file.</p>
<p>There are 2 types of CSV file as following examples. First, there is a
header on first row and it's first column is “label”. Another, there is
no header in the file.</p>
<p>@example Load data from CSV file with header</p>
<pre class="ruby"><span class="ruby-comment"># test-data.csv:</span>
<span class="ruby-comment"># label,expected,target</span>
<span class="ruby-comment"># empty string,true,""</span>
<span class="ruby-comment"># plain string,false,hello</span>
<span class="ruby-comment">#</span>
<span class="ruby-identifier">load_data</span>(<span class="ruby-string">"/path/to/test-data.csv"</span>)
<span class="ruby-keyword">def</span> <span class="ruby-identifier">test_empty?</span>(<span class="ruby-identifier">data</span>)
<span class="ruby-identifier">assert_equal</span>(<span class="ruby-identifier">data</span>[<span class="ruby-string">"expected"</span>], <span class="ruby-identifier">data</span>[<span class="ruby-string">"target"</span>].<span class="ruby-identifier">empty?</span>)
<span class="ruby-keyword">end</span>
</pre>
<p>@example Load data from CSV file without header</p>
<pre class="ruby"><span class="ruby-comment"># test-data-without-header.csv:</span>
<span class="ruby-comment"># empty string,true,""</span>
<span class="ruby-comment"># plain string,false,hello</span>
<span class="ruby-comment">#</span>
<span class="ruby-identifier">load_data</span>(<span class="ruby-string">"/path/to/test-data-without-header.csv"</span>)
<span class="ruby-keyword">def</span> <span class="ruby-identifier">test_empty?</span>(<span class="ruby-identifier">data</span>)
<span class="ruby-identifier">expected</span>, <span class="ruby-identifier">target</span> = <span class="ruby-identifier">data</span>
<span class="ruby-identifier">assert_equal</span>(<span class="ruby-identifier">expected</span>, <span class="ruby-identifier">target</span>.<span class="ruby-identifier">empty?</span>)
<span class="ruby-keyword">end</span>
</pre>
<p>@api private</p>
<div class="method-source-code" id="load_csv-source">
<pre><span class="ruby-comment"># File lib/test/unit/data.rb, line 258</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">load_csv</span>(<span class="ruby-identifier">file_name</span>)
<span class="ruby-identifier">require</span> <span class="ruby-string">'csv'</span>
<span class="ruby-identifier">first_row</span> = <span class="ruby-keyword">true</span>
<span class="ruby-identifier">header</span> = <span class="ruby-keyword">nil</span>
<span class="ruby-constant">CSV</span>.<span class="ruby-identifier">foreach</span>(<span class="ruby-identifier">file_name</span>) <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">row</span><span class="ruby-operator">|</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">first_row</span>
<span class="ruby-identifier">first_row</span> = <span class="ruby-keyword">false</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">row</span>.<span class="ruby-identifier">first</span> <span class="ruby-operator">==</span> <span class="ruby-string">"label"</span>
<span class="ruby-identifier">header</span> = <span class="ruby-identifier">row</span>[<span class="ruby-value">1</span><span class="ruby-operator">..</span><span class="ruby-value">-1</span>]
<span class="ruby-keyword">next</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">set_test_data</span>(<span class="ruby-identifier">header</span>, <span class="ruby-identifier">row</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div id="method-i-load_tsv" class="method-detail ">
<div class="method-heading">
<span class="method-name">load_tsv</span><span
class="method-args">(file_name)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Load data from TSV file.</p>
<p>There are 2 types of TSV file as following examples. First, there is a
header on first row and it's first column is “label”. Another, there is
no header in the file.</p>
<p>@example Load data from TSV file with header</p>
<pre class="ruby"><span class="ruby-comment"># test-data.tsv:</span>
<span class="ruby-comment"># label expected target</span>
<span class="ruby-comment"># empty string true ""</span>
<span class="ruby-comment"># plain string false hello</span>
<span class="ruby-comment">#</span>
<span class="ruby-identifier">load_data</span>(<span class="ruby-string">"/path/to/test-data.tsv"</span>)
<span class="ruby-keyword">def</span> <span class="ruby-identifier">test_empty?</span>(<span class="ruby-identifier">data</span>)
<span class="ruby-identifier">assert_equal</span>(<span class="ruby-identifier">data</span>[<span class="ruby-string">"expected"</span>], <span class="ruby-identifier">data</span>[<span class="ruby-string">"target"</span>].<span class="ruby-identifier">empty?</span>)
<span class="ruby-keyword">end</span>
</pre>
<p>@example Load data from TSV file without header</p>
<pre class="ruby"><span class="ruby-comment"># test-data-without-header.tsv:</span>
<span class="ruby-comment"># empty string true ""</span>
<span class="ruby-comment"># plain string false hello</span>
<span class="ruby-comment">#</span>
<span class="ruby-identifier">load_data</span>(<span class="ruby-string">"/path/to/test-data-without-header.tsv"</span>)
<span class="ruby-keyword">def</span> <span class="ruby-identifier">test_empty?</span>(<span class="ruby-identifier">data</span>)
<span class="ruby-identifier">expected</span>, <span class="ruby-identifier">target</span> = <span class="ruby-identifier">data</span>
<span class="ruby-identifier">assert_equal</span>(<span class="ruby-identifier">expected</span>, <span class="ruby-identifier">target</span>.<span class="ruby-identifier">empty?</span>)
<span class="ruby-keyword">end</span>
</pre>
<p>@api private</p>
<div class="method-source-code" id="load_tsv-source">
<pre><span class="ruby-comment"># File lib/test/unit/data.rb, line 304</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">load_tsv</span>(<span class="ruby-identifier">file_name</span>)
<span class="ruby-identifier">require</span> <span class="ruby-string">"csv"</span>
<span class="ruby-keyword">if</span> <span class="ruby-constant">CSV</span>.<span class="ruby-identifier">const_defined?</span>(<span class="ruby-value">:VERSION</span>)
<span class="ruby-identifier">first_row</span> = <span class="ruby-keyword">true</span>
<span class="ruby-identifier">header</span> = <span class="ruby-keyword">nil</span>
<span class="ruby-constant">CSV</span>.<span class="ruby-identifier">foreach</span>(<span class="ruby-identifier">file_name</span>, <span class="ruby-value">:col_sep</span> =<span class="ruby-operator">></span> <span class="ruby-string">"\t"</span>) <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">row</span><span class="ruby-operator">|</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">first_row</span>
<span class="ruby-identifier">first_row</span> = <span class="ruby-keyword">false</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">row</span>.<span class="ruby-identifier">first</span> <span class="ruby-operator">==</span> <span class="ruby-string">"label"</span>
<span class="ruby-identifier">header</span> = <span class="ruby-identifier">row</span>[<span class="ruby-value">1</span><span class="ruby-operator">..</span><span class="ruby-value">-1</span>]
<span class="ruby-keyword">next</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">set_test_data</span>(<span class="ruby-identifier">header</span>, <span class="ruby-identifier">row</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">else</span>
<span class="ruby-comment"># for old CSV library</span>
<span class="ruby-identifier">first_row</span> = <span class="ruby-keyword">true</span>
<span class="ruby-identifier">header</span> = <span class="ruby-keyword">nil</span>
<span class="ruby-constant">CSV</span>.<span class="ruby-identifier">open</span>(<span class="ruby-identifier">file_name</span>, <span class="ruby-string">"r"</span>, <span class="ruby-string">"\t"</span>) <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">row</span><span class="ruby-operator">|</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">first_row</span>
<span class="ruby-identifier">first_row</span> = <span class="ruby-keyword">false</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">row</span>.<span class="ruby-identifier">first</span> <span class="ruby-operator">==</span> <span class="ruby-string">"label"</span>
<span class="ruby-identifier">header</span> = <span class="ruby-identifier">row</span>[<span class="ruby-value">1</span><span class="ruby-operator">..</span><span class="ruby-value">-1</span>]
<span class="ruby-keyword">next</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">set_test_data</span>(<span class="ruby-identifier">header</span>, <span class="ruby-identifier">row</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</section>
<section id="private-instance-5Buntitled-5D-method-details" class="method-section">
<header>
<h3>Private Instance Methods</h3>
</header>
<div id="method-i-normalize_value" class="method-detail ">
<div class="method-heading">
<span class="method-name">normalize_value</span><span
class="method-args">(value)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<div class="method-source-code" id="normalize_value-source">
<pre><span class="ruby-comment"># File lib/test/unit/data.rb, line 339</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">normalize_value</span>(<span class="ruby-identifier">value</span>)
<span class="ruby-keyword">return</span> <span class="ruby-keyword">true</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span> <span class="ruby-operator">==</span> <span class="ruby-string">"true"</span>
<span class="ruby-keyword">return</span> <span class="ruby-keyword">false</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span> <span class="ruby-operator">==</span> <span class="ruby-string">"false"</span>
<span class="ruby-keyword">begin</span>
<span class="ruby-constant">Integer</span>(<span class="ruby-identifier">value</span>)
<span class="ruby-keyword">rescue</span> <span class="ruby-constant">ArgumentError</span>
<span class="ruby-keyword">begin</span>
<span class="ruby-constant">Float</span>(<span class="ruby-identifier">value</span>)
<span class="ruby-keyword">rescue</span> <span class="ruby-constant">ArgumentError</span>
<span class="ruby-identifier">value</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div id="method-i-set_test_data" class="method-detail ">
<div class="method-heading">
<span class="method-name">set_test_data</span><span
class="method-args">(header, row)</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<div class="method-source-code" id="set_test_data-source">
<pre><span class="ruby-comment"># File lib/test/unit/data.rb, line 353</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">set_test_data</span>(<span class="ruby-identifier">header</span>, <span class="ruby-identifier">row</span>)
<span class="ruby-identifier">label</span> = <span class="ruby-identifier">row</span>.<span class="ruby-identifier">shift</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">header</span>
<span class="ruby-identifier">data</span> = {}
<span class="ruby-identifier">header</span>.<span class="ruby-identifier">each_with_index</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">key</span>, <span class="ruby-identifier">i</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">data</span>[<span class="ruby-identifier">key</span>] = <span class="ruby-identifier">normalize_value</span>(<span class="ruby-identifier">row</span>[<span class="ruby-identifier">i</span>])
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">data</span> = <span class="ruby-identifier">row</span>.<span class="ruby-identifier">collect</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">cell</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">normalize_value</span>(<span class="ruby-identifier">cell</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-ivar">@test_case</span>.<span class="ruby-identifier">data</span>(<span class="ruby-identifier">label</span>, <span class="ruby-identifier">data</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</section>
</section>
</main>
<footer id="validator-badges" role="contentinfo">
<p><a href="http://validator.w3.org/check/referer">Validate</a>
<p>Generated by <a href="http://docs.seattlerb.org/rdoc/">RDoc</a> 4.2.1.
<p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>.
</footer>
|
Celyagd/celyagd.github.io
|
stakes-jekyll/doc/test-unit-3.3.0/rdoc/Test/Unit/Data/ClassMethods/Loader.html
|
HTML
|
mit
| 21,841
|
'use strict';
module.exports = {
"plugins": [],
"recurseDepth": 10,
"source": {
"includePattern": ".+\\.js(doc|x)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"sourceType": "module",
"tags": {
"allowUnknownTags": true,
"dictionaries": ["jsdoc","closure"]
},
"templates": {
"cleverLinks": false,
"monospaceLinks": false,
"default": {
"outputSourceFiles": false,
"includeDate": false,
"useLongnameInNav": false
}
},
"opts": {
"template": "templates/default", // same as -t templates/default
//"template": "node_modules/tui-jsdoc-template",
//"template": "node_modules/docdash",
//"template": "node_modules/minami",
//"template": "node_modules/postman-jsdoc-theme",
//"template": "node_modules/jaguarjs-jsdoc",
"encoding": "utf8", // same as -e utf8
"destination": "./docs/", // same as -d ./out/
"recurse": true, // same as -r
"debug": true, // same as --debug
"readme": "./README.md"
//"package": "./package.json", // same as --package
//"tutorials": "./tutorials/" // same as -u path/to/tutorials
}
};
|
Wildix/IntegrationService
|
.jsdoc.js
|
JavaScript
|
mit
| 1,316
|
<!DOCTYPE html>
<html ng-app="jcs-demo">
<head lang="en">
<meta charset="UTF-8">
<title>Angular Auto Validate Test Page</title>
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="row" ng-controller="demoCtrl">
<div class="col-sm-8 col-sm-offset-1">
<p>
<button type="button" class="btn btn-primary" ng-click="toggleBS3Icons();">Toggle Validation State Icons</button>
</p>
<form role="form" name="testFrm" novalidate="novalidate"
ng-submit="submit(testFrm);"
validate-non-visible-controls="false"
validate-on-form-submit="true"
disable-dynamic-validatio_n>
<button type="button" class="btn btn-primary" ng-click="setExternalError(testFrm);">Set External Error On Firstname</button>
<div class="form-group">
<label class="control-label">Name</label>
<input type="text" name="firstname" style="display: block;" class="form-control" placeholder="Enter Your Name"
ng-model="user.name" required="required" ng-required-err-type="nameRequired"/>
</div>
<div class="form-group">
<label class="control-label">Name</label>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-envelope"></i>
</span>
<input type="email" name="email" class="form-control"
ng-model="user.email"
placeholder="Enter email address"
ng-required="true"/>
</div>
</div>
<div class="form-group">
<label class="control-label">Email address - <small>Element with a custom element modifier (see source code)</small></label>
<input type="email" class="form-control" placeholder="Enter email" ng-model="user.email" required="required" element-modifier="myCustomModifierKey"/>
</div>
<div class="form-group">
<label class="control-label">Password - <small>Element with validation happening on blur rather than change</small></label>
<input type="password" class="form-control" ng-model="user.password" placeholder="Password" required="required" ng-minlength="6" ng-model-options="{updateOn: 'blur'}"/>
</div>
<div class="form-group">
<label class="control-label">Robot Test: Please spell Angular. - <small>Custom validation</small></label>
<input type="text" class="form-control" placeholder="Enter The Word Angular" ng-model="user.iq" mustcontainword="angular"/>
</div>
<div class="form-group">
<label class="control-label">Regex Pattern Only Letters</label>
<input type="text" class="form-control" placeholder="Enter Only Letters..." ng-model="user.letters" ng-pattern="/[a-zA-Z]/"/>
</div>
<div class="form-group">
<label class="control-label">Is User Active?
<input type="checkbox" class="form-control" ng-model="user.isActive" /></label>
</div>
<div class="form-group">
<label class="control-label">Input with no validation</label>
<input type="text" class="form-control" placeholder="Enter The Word Angular" ng-model="user.noValidation" />
</div>
<div class="form-group">
<label class="control-label">Valid Styling disabled</label>
<input type="text" class="form-control" required ng-model="user.someProperty" disable-invalid-styling="true" />
</div>
<ng-form name="childForm">
<div class="form-group">
<label class="control-label">Nickname</label>
<input type="text" class="form-control" name="Nickname" placeholder="Enter Nickname" ng-model="user.Nickname" required="required" ng-minlength="4">
</div>
</ng-form>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
<button type="button" class="btn btn-default" ng-click="resetFormViaEvent()">Reset Via Event</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<h1>Not Required</h1>
<form name="signupFrm" novalidate="novalidate" class="form-horizontal" ng-submit="signin()">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Username:</label>
<div class="col-sm-10">
<input id="inputName" class="form-control" name="username"
ng-model="model.username"
ng-model-options="{updateOn: 'blur'}"
ng-minlength="3"
ng-maxlength="10"
/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input class="form-control" name="password"
type="password"
ng-model="model.password"
ng-model-options="{updateOn: 'blur'}"
ng-minlength="3"
ng-maxlength="10"
required/>
</div>
</div>
<div class="row">
<div class="col-md-9">
<p class="input-group">
<input type="text" class="form-control" ng-model="startTime" required ng-minlength="2" disable-valid-styling="true"/>
<!--<ul style="display: none;">-->
<!--<li></li>-->
<!--</ul>-->
<span class="input-group-btn">
<button class="btn btn-default"><i class="glyphicon glyphicon-facetime-video"></i></button>
</span>
</p>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
<span>Result :</span>{{result}}
</div>
</div>
<script type="text/javascript" src="../bower_components/angular/angular.js"></script>
<!--<script type="text/javascript" src="../dist/jcs-auto-validate.min.js"></script>-->
<script type="text/javascript" src="../src/jcs-auto-validate.js"></script>
<script type="text/javascript" src="../src/providers/validator.js"></script>
<script type="text/javascript" src="../src/services/bootstrap3ElementModifier.js"></script>
<script type="text/javascript" src="../src/services/debounce.js"></script>
<script type="text/javascript" src="../src/services/defaultErrorMessageResolver.js"></script>
<script type="text/javascript" src="../src/services/foundation5ElementModifier.js"></script>
<script type="text/javascript" src="../src/services/foundation6ElementModifier.js"></script>
<script type="text/javascript" src="../src/services/validationManager.js"></script>
<script type="text/javascript" src="../src/config/ngSubmitDecorator.js"></script>
<script type="text/javascript" src="../src/config/ngModelDecorator.js"></script>
<script type="text/javascript" src="../src/directives/formReset.js"></script>
<script type="text/javascript" src="../src/directives/autoValidateFormOptions.js"></script>
<script type="text/javascript" src="../src/directives/registerCustomFormControl.js"></script>
<script type="text/javascript" src="../src/jcs-auto-validate-run.js"></script>
<script type="text/javascript">
(function (angular) {
var app = angular.module('jcs-demo', ['jcs-autoValidate']);
app.controller('demoCtrl', [
'$http',
'$scope',
'bootstrap3ElementModifier',
function ($http, $scope, bootstrap3ElementModifier) {
$scope.user = {};
$scope.bs3Icons = false;
$scope.toggleBS3Icons = function () {
$scope.bs3Icons = !$scope.bs3Icons;
bootstrap3ElementModifier.enableValidationStateIcons($scope.bs3Icons);
};
$scope.resetFormViaEvent = function() {
$scope.$broadcast('form:testFrm:reset');
};
$scope.submit = function (frmCtrl) {
//frmCtrl.autoValidateFormOptions.resetForm();
alert('submitted');
$http.post('https://api.app.com/users', $scope.user).then(function (response) {
if (response.data.validationErrors) {
angular.forEach(response.data.validationErrors, function (error) {
frmCtrl.setExternalValidation(error.key, error.messageKey, error.message);
})
}
});
};
$scope.setExternalError = function (frm) {
frm.setExternalValidation('firstname', "customError", 'hello joe', true);
};
$scope.toggleBS3Icons();
}
]);
app.directive('mustcontainword', [
function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var validateFn = function (viewValue) {
if (ctrl.$isEmpty(viewValue) || viewValue.toLowerCase().indexOf(attrs.mustcontainword.toLowerCase()) === -1) {
ctrl.$setValidity('mustcontainword', false);
return undefined;
} else {
ctrl.$setValidity('mustcontainword', true);
return viewValue;
}
};
ctrl.$parsers.push(validateFn);
ctrl.$formatters.push(validateFn);
}
}
}]);
app.directive('uniqueIdChecker', [
'$http',
function($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var validateFn = function (viewValue) {
$http.get('https://myapp.com/validator-checks/unique-id/' + viewValue).then(function () {
ctrl.$setValidity('nonUniqueId', true);
}, function () {
ctrl.$setValidity('nonUniqueId', false);
});
return viewValue;
};
ctrl.$parsers.push(validateFn);
ctrl.$formatters.push(validateFn);
}
}
}]);
app.run([
'defaultErrorMessageResolver',
function (defaultErrorMessageResolver) {
defaultErrorMessageResolver.getErrorMessages().then(function (errorMessages) {
errorMessages['nonUniqueId'] = 'This id is already taken plus choose another';
});
}
]);
app.factory('myCustomElementModifier', [
function () {
var /**
* @ngdoc function
* @name myCustomElementModifier#makeValid
* @methodOf myCustomElementModifier
*
* @description
* Makes an element appear valid by apply custom styles and child elements.
*
* @param {Element} el - The input control element that is the target of the validation.
*/
makeValid = function (el) {
el.removeClass('bg-red');
el.addClass('bg-green');
},
/**
* @ngdoc function
* @name myCustomElementModifier#makeInvalid
* @methodOf myCustomElementModifier
*
* @description
* Makes an element appear invalid by apply custom styles and child elements.
*
* @param {Element} el - The input control element that is the target of the validation.
* @param {String} errorMsg - The validation error message to display to the user.
*/
makeInvalid = function (el, errorMsg) {
el.removeClass('bg-green');
el.addClass('bg-red');
};
return {
makeValid: makeValid,
makeInvalid: makeInvalid,
key: 'myCustomModifierKey'
};
}
]);
// now register the custom element modifier with the auto-validate module and set it as the default one for all elements
app.run([
'validator',
'myCustomElementModifier',
'defaultErrorMessageResolver',
function (validator, myCustomElementModifier, defaultErrorMessageResolver) {
validator.registerDomModifier(myCustomElementModifier.key, myCustomElementModifier);
defaultErrorMessageResolver.setI18nFileRootPath('../src/lang/');
defaultErrorMessageResolver.setCulture('en-gb');
defaultErrorMessageResolver.getErrorMessages().then(function (errorMessages) {
errorMessages['pattern'] = 'Custom Error Message {0}';
errorMessages['mustcontainword'] = 'Please enter the word "{0}"';
errorMessages['nameRequired'] = 'Please enter your name';
});
}
]);
}(angular));
</script>
</body>
</html>
|
jonsamwell/angular-auto-validate
|
tests/testPage.html
|
HTML
|
mit
| 15,492
|
import * as actions from './actions';
import mutations from './mutations';
import getters from './getters';
const state = {
transactions: [],
businesses: []
};
export default {
state,
actions,
mutations,
getters
};
|
jdm8736/simple-budget-app
|
src/app/transactions/vuex/index.js
|
JavaScript
|
mit
| 229
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "BackEnd.h"
int const TySize[] = {
#define IRTYPE(ucname, baseType, size, bitSize, enRegOk, dname) size,
#include "IRTypeList.h"
#undef IRTYPE
};
enum IRBaseTypes : BYTE {
IRBaseType_Illegal,
IRBaseType_Int,
IRBaseType_Uint,
IRBaseType_Float,
IRBaseType_Simd,
IRBaseType_Var,
IRBaseType_Condcode,
IRBaseType_Misc
};
int const TyBaseType[] = {
#define IRTYPE(ucname, baseType, size, bitSize, enRegOk, dname) IRBaseType_ ## baseType,
#include "IRTypeList.h"
#undef IRTYPE
};
wchar_t * const TyDumpName[] = {
#define IRTYPE(ucname, baseType, size, bitSize, enRegOk, dname) L# dname,
#include "IRTypeList.h"
#undef IRTYPE
};
bool IRType_IsSignedInt(IRType type) { return TyBaseType[type] == IRBaseType_Int; }
bool IRType_IsUnsignedInt(IRType type) { return TyBaseType[type] == IRBaseType_Uint; }
bool IRType_IsFloat(IRType type) { return TyBaseType[type] == IRBaseType_Float; }
bool IRType_IsNative(IRType type)
{
return TyBaseType[type] > IRBaseType_Illegal && TyBaseType[type] < IRBaseType_Var;
}
bool IRType_IsNativeInt(IRType type)
{
return TyBaseType[type] > IRBaseType_Illegal && TyBaseType[type] < IRBaseType_Float;
}
bool IRType_IsSimd(IRType type)
{
return TyBaseType[type] == IRBaseType_Simd;
}
bool IRType_IsSimd128(IRType type)
{
return type == TySimd128F4 || type == TySimd128I4 || type == TySimd128D2;
}
#if DBG_DUMP || defined(ENABLE_IR_VIEWER)
void IRType_Dump(IRType type)
{
Output::Print(TyDumpName[type]);
}
#endif
|
arunetm/ChakraCore_0114
|
lib/Backend/IRType.cpp
|
C++
|
mit
| 1,866
|
# Laravel Facebook Posts
This is a simple package I created for my own use to post to facebook. This is not yet ready for general use. I plan to add a lot of other features.
## Install
Via Composer
```
$ composer require developernaren/facebook
```
## Usage
I have made the facebook class into a singleton class because I need only a single instance at a time.
Because I have made this into a singleton, this is how it can currently be used ( I might change this in the future, But this is how I need it for now)
`$fb = app()->make('FB');`
`$fb->addStatus( "First line of the status )`
`->addStatus( "Second Line Here" )`
`->addlink( "http://linktomywebsite.com" )`
`->asPage( "<pageID>" )`
` ->post();`
## Contributing
Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.
## Security
If you discover any security related issues, please email :author_email instead of using the issue tracker.
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
|
developernaren/facebook
|
README.md
|
Markdown
|
mit
| 1,091
|
// c9.h ¶ÔÁ½¸öÊýÖµÐ͹ؼü×ֵıȽÏÔ¼¶¨ÎªÈçϵĺ궨Òå
#define EQ(a,b) ((a)==(b))
#define LT(a,b) ((a)<(b))
#define LQ(a,b) ((a)<=(b))
|
guyuexing/DataStruct
|
DataStructDemo/数据结构/ch9/C9.H
|
C++
|
mit
| 139
|
#include "BoundarySimulator.h"
#include "SPlisHSPlasH/TimeManager.h"
#include "SPlisHSPlasH/Simulation.h"
#include "SPlisHSPlasH/BoundaryModel.h"
using namespace SPH;
void BoundarySimulator::updateBoundaryForces()
{
Real h = TimeManager::getCurrent()->getTimeStepSize();
Simulation *sim = Simulation::getCurrent();
const unsigned int nObjects = sim->numberOfBoundaryModels();
for (unsigned int i = 0; i < nObjects; i++)
{
BoundaryModel *bm = sim->getBoundaryModel(i);
RigidBodyObject *rbo = bm->getRigidBodyObject();
if (rbo->isDynamic())
{
Vector3r force, torque;
bm->getForceAndTorque(force, torque);
rbo->addForce(force);
rbo->addTorque(torque);
bm->clearForceAndTorque();
}
}
}
|
InteractiveComputerGraphics/SPlisHSPlasH
|
Simulator/BoundarySimulator.cpp
|
C++
|
mit
| 715
|
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, .1, 1000 );
var renderer = new THREE.WebGLRenderer();
var container = document.getElementById('container');
container.appendChild(renderer.domElement);
renderer.setSize(window.innerWidth, window.innerHeight);
var loader = new THREE.STLLoader();
loader.load('../data/MonkeyBrain.stl', function(geometry) {
console.log(geometry)
var material = new THREE.MeshNormalMaterial({visible: true, transparent: true, opacity: 0.5});
// var material = new THREE.MeshBasicMaterial({visible: true, wireframe:true});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer.render(scene, camera);
});
|
RobIsaTeam/courses
|
_course_3_threejs/code/lesson-03.js
|
JavaScript
|
mit
| 734
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace APHIS.Account
{
public partial class Register
{
/// <summary>
/// RegisterUser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CreateUserWizard RegisterUser;
/// <summary>
/// RegisterUserWizardStep control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CreateUserWizardStep RegisterUserWizardStep;
}
}
|
Code4HR/pet-check
|
Account/Register.aspx.designer.cs
|
C#
|
mit
| 1,116
|
# reload zsh config
alias reload!='source ~/.zshrc'
# Detect which `ls` flavor is in use
if ls --color > /dev/null 2>&1; then # GNU `ls`
colorflag="--color"
else # OS X `ls`
colorflag="-G"
fi
alias v="nvim"
alias c="code-insiders"
# Filesystem aliases
alias ..='cd ..'
alias ...='cd ../..'
alias ....="cd ../../.."
alias .....="cd ../../../.."
alias lc="colorls -lA --sf --gs"
alias l="ls -lah ${colorflag}"
alias la="ls -AF ${colorflag}"
alias ll="ls -lFh ${colorflag}"
alias lld="ls -l | grep ^d"
alias rmf="rm -rf"
# Helpers
alias grep='grep --color=auto'
alias df='df -h' # disk free, in Gigabytes, not bytes
alias du='du -h -c' # calculate disk usage for a folder
# Applications
alias ios='open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app'
# cd to last opened finder location
alias cdf='cd `osascript -e "tell application \"Finder\" to if window 1 exists then if target of window 1 as string is not \":\" then get POSIX path of (target of window 1 as alias)"`'
# IP addresses
alias ip="dig +short myip.opendns.com @resolver1.opendns.com"
alias localip="ipconfig getifaddr en1"
alias ips="ifconfig -a | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1'"
# Flush Directory Service cache
alias flush="dscacheutil -flushcache"
# View HTTP traffic
alias sniff="sudo ngrep -d 'en1' -t '^(GET|POST) ' 'tcp and port 80'"
alias httpdump="sudo tcpdump -i en1 -n -s 0 -w - | grep -a -o -E \"Host\: .*|GET \/.*\""
# HTTPS default for HTTPie https://httpie.org/doc#custom-default-scheme
alias https="http --default-scheme=https"
# Trim new lines and copy to clipboard
alias trimcopy="tr -d '\n' | pbcopy"
# Recursively delete `.DS_Store` files
alias cleanup="find . -name '*.DS_Store' -type f -ls -delete"
# Re-source cron/crontab after edits are made
alias newcron="crontab $HOME/.dotfiles/cron/crontab && crontab -l"
# File size
alias fs="stat -f \"%z bytes\""
# Directory size
alias ds="du -hcs"
alias dsu="du -hcs ./*"
# ROT13-encode text. Works for decoding, too! ;)
alias rot13='tr a-zA-Z n-za-mN-ZA-M'
# Empty the Trash on all mounted volumes and the main HDD
alias emptytrash="sudo rm -rfv /Volumes/*/.Trashes; rm -rfv ~/.Trash"
# Hide/show all desktop icons (useful when presenting)
alias hidedesktop="defaults write com.apple.finder CreateDesktop -bool false && killall Finder"
alias showdesktop="defaults write com.apple.finder CreateDesktop -bool true && killall Finder"
# One of @janmoesen’s ProTip™s
for method in GET HEAD POST PUT DELETE TRACE OPTIONS; do
alias "$method"="lwp-request -m '$method'"
done
# Stuff I never really use but cannot delete either because of http://xkcd.com/530/
alias stcu="osascript -e 'set volume output muted true'"
alias pumpitup="osascript -e 'set volume 10'"
# Start a simple web server
alias webserv="python -m http.server"
# Kill all the tabs in Chrome to free up memory
# [C] explained: http://www.commandlinefu.com/commands/view/402/exclude-grep-from-your-grepped-output-of-ps-alias-included-in-description
alias chromekill="ps ux | grep '[C]hrome Helper --type=renderer' | grep -v extension-process | tr -s ' ' | cut -d ' ' -f2 | xargs kill"
alias colortest="~/.color-scripts/color-scripts/colortest"
alias dnd="osascript ~/.dotfiles/applescripts/dnd.applescript"
alias down="pmset sleepnow"
alias keepup="/bin/bash -c 'sleep 15 && while true; do ~/dev/scripts/mousemove.sh ; sleep 280; done'"
|
paulhirschi/dotfiles
|
zsh/aliases.zsh
|
Shell
|
mit
| 3,400
|
function registerListeners() {
window.addEventListener("keydown", function(event) {
switch (event.keyCode) {
case 87: // w
keyStatus[0] = true;
break;
case 65: // a
keyStatus[1] = true;
break;
case 83: // s
keyStatus[2] = true;
break;
case 68: // d
keyStatus[3] = true;
break;
}
}, false);
window.addEventListener("keyup", function(event) {
switch (event.keyCode) {
case 87: // w
keyStatus[0] = false;
break;
case 65: // a
keyStatus[1] = false;
break;
case 83: // s
keyStatus[2] = false;
break;
case 68: // d
keyStatus[3] = false;
break;
}
}, false);
}
|
eott/into-hyperspace
|
input.js
|
JavaScript
|
mit
| 682
|
export class Validation {
constructor() {
this.errors = [];
}
get validationArray() {
return [];
}
get valid() {
let self = this;
return this.validationArray.reduce((isValid, isPartValid) => {
if(!isPartValid) return isValid;
if (typeof isPartValid.valid === 'boolean' && !isPartValid.valid) {
self.errors.push(isPartValid);
}
return isValid && isPartValid.valid;
}, true);
}
addErrors(newErrors) {
let self = this;
newErrors.forEach((errorObj) => {
self.errors.push(errorObj)
})
}
};
|
influencetech/ivx-js
|
src/modules/validation/ivx-js-validation/validation.js
|
JavaScript
|
mit
| 693
|
module UnitQuaternions
import Base: +, -, ^, ==, ×, angle, inv, log, mean, show, getindex
export UnitQuaternion, ⊕, ⊞, ⊟, axis, covariance, rotatevector, rotateframe, rotationmatrix, slerp, vector
const EPS = 1e-9
####################################################################################################
# Type Definition
####################################################################################################
immutable UnitQuaternion
ϵ::Vector{Float64}
η::Float64
function UnitQuaternion(ϵ, η)
length(ϵ) == 3 || error("Must be a 3-vector.")
η = abs(η) < EPS ? zero(η) : η # small scalars are exactly zero
# normalization algorithm taken from http://stackoverflow.com/a/12934750/1053656
squared_mag = η * η + sum(abs2(ϵ))
if abs(one(squared_mag) - squared_mag) < 2.107342e-08
scale = 2.0 / (1.0 + squared_mag)
else
scale = 1.0 / sqrt(squared_mag)
end
η >= zero(η) ? new(ϵ * scale, η * scale) : new(-ϵ * scale, -η * scale)
end
end
####################################################################################################
# Constructors
####################################################################################################
"""
`UnitQuaternion()`
Constructs the identity unit quaternion.
"""
UnitQuaternion() = UnitQuaternion([0, 0, 0], 1)
"""
`UnitQuaternion(ϵ1, ϵ2, ϵ3, η)`
Constructs a unit quaternion where the vector part is `[ϵ1, ϵ2, ϵ3]` and the scalar part `η`.
"""
UnitQuaternion(ϵ1::Real, ϵ2::Real, ϵ3::Real, η::Real) = UnitQuaternion([ϵ1, ϵ2, ϵ3], η)
"""
`UnitQuaternion(v)`
Constructs a unit quaternion from the vector `v`. If `v` is a 4-vector, its first three elements are
taken as the vector part and its fourth element is taken as the scalar part. If `v` is a 3-vector, it
is assumed to be a rotation vector and the rotation is converted to a unit quaternion.
"""
function UnitQuaternion(v::AbstractVector)
if length(v) == 3
θ = norm(v)
return θ > EPS ? UnitQuaternion(sin(θ/2.0) * v / θ, cos(θ/2.0)) : UnitQuaternion()
elseif length(v) == 4
return UnitQuaternion([v[1], v[2], v[3]], v[4])
else
error("Must be a 3-vector (rotation vector) or a 4-vector (quaternion).")
end
end
####################################################################################################
# Operators
####################################################################################################
"""
`+(q)`
Applies the left-hand compound operator to the unit quaternion `q`, which returns a 4x4 matrix.
"""
+(q::UnitQuaternion) = [q.η * eye(3) - ×(q.ϵ) q.ϵ; -q.ϵ' q.η]
"""
`+(p, q)`
Calculates the quaternion product `p + q` using the left-hand compound operator.
"""
+(p::UnitQuaternion, q::UnitQuaternion) = UnitQuaternion(+(p) * vector(q))
"""
`^(q, n)`
Raises the unit quaternion `q` to the power of `n`.
"""
^(q::UnitQuaternion, n::Integer) = UnitQuaternion(2n * log(q))
^(q::UnitQuaternion, n::Real) = UnitQuaternion(2n * log(q))
"""
`⊕(q)`
Applies the right-hand compound operator to the unit quaternion `q`, which returns a 4x4 matrix.
"""
⊕(q::UnitQuaternion) = [q.η * eye(3) + ×(q.ϵ) q.ϵ; -q.ϵ' q.η]
"""
`⊕(p, q)`
Calculates the quaternion product `q + p` using the right-hand compound operator (i.e., `p ⊕ q`).
"""
⊕(p::UnitQuaternion, q::UnitQuaternion) = UnitQuaternion(⊕(p) * vector(q))
"""
`⊟(p, q)`
Calculates the rotation from unit quaternion `p` to unit quaternion `q` (i.e., their difference)
and converts the result to a rotation vector.
"""
⊟(p::UnitQuaternion, q::UnitQuaternion) = 2.0 * log(inv(q) + p)
"""
`⊞(q, rotationvector)`
Perturbs the unit quaternion `q` by the rotation vector `rotationvector`. Equivalent to
`q + UnitQuaternion(rotationvector)`.
"""
function ⊞(q::UnitQuaternion, rotationvector::AbstractVector)
length(rotationvector) == 3 || error("Must be 3-vector.")
q + UnitQuaternion(rotationvector)
end
"""
`==(p, q)`
Checks if unit quaterions `p` and `q` are equal.
"""
==(p::UnitQuaternion, q::UnitQuaternion) = abs(p.η - q.η) < EPS && all(i->(abs(i) < EPS), p.ϵ - q.ϵ)
"""
`getindex(q, i)`
Returns the `i`-th element of the unit quaternion `q`, where `i` = 1:3 form the vector part of `q`
and `i` = 4 is the scalar part of `q`.
"""
getindex(q::UnitQuaternion, i::Integer) = i == 4 ? q.η : q.ϵ[i]
####################################################################################################
# Methods
####################################################################################################
"""
`angle(q)`
Returns the angle of rotation of the unit quaternion `q`.
"""
angle(q::UnitQuaternion) = 2.0 * atan2(norm(q.ϵ), q.η)
"""
`axis(q)`
Returns the axis of rotation of the unit quaternion `q`.
"""
axis(q::UnitQuaternion) = norm(q.ϵ) > EPS ? q.ϵ / norm(q.ϵ) : [0.0, 0.0, 1.0]
"""
`covariance(qs, qmean, weights)`
Returns the 3x3 covariance matrix of a vector of unit quaternions `qs` given the unit quaternion
mean `qmean`. The optional argument `weights` is a vector of weights used to calculate a weighted
covariance of the `qs`. If no weights are given, all unit quaternions are weighted equally.
"""
function covariance{T<:Real}(v::AbstractVector{UnitQuaternion}, qmean::UnitQuaternion,
weights::Vector{T} = ones(length(v)))
normweights = map(w -> w/sum(weights), weights)
cov = zeros(3, 3)
for i = 1:length(v)
diff = v[i] ⊟ qmean
cov += normweights[i] * diff * diff'
end
return cov
end
"""
`covariance(qs, weights)`
Returns the 3x3 covariance matrix of a vector of unit quaternions `qs`. The optional argument `weights` is
a vector of weights used to calculate a weighted covariance of the `qs`. If no weights are given, all unit
quaternions are weighted equally.
"""
function covariance{T<:Real}(qs::AbstractVector{UnitQuaternion}, weights::Vector{T} = ones(length(qs)))
qmean = mean(qs, weights)
return covariance(qs, qmean, weights)
end
"""
`inv(q)`
Calculates the inverse of the unit quaternion `q`.
"""
inv(q::UnitQuaternion) = UnitQuaternion(-q.ϵ, q.η)
"""
`mean(qs, weights)`
Returns the quaternion mean of a vector of unit quaternions `qs`. The optional argument `weights` is
a vector of weights used to calculate a weighted mean of the `qs`. If no weights are given, all unit
quaternions are weighted equally.
"""
function mean{T<:Real}(qs::AbstractVector{UnitQuaternion}, weights::Vector{T} = ones(length(qs)))
normweights = map(w -> w/sum(weights), weights)
M = sum([w * vector(q) * vector(q)' for (w, q) in zip(normweights, qs)])
evals, evecs = eig(M)
largestevalindex = sortperm(evals)[end]
return UnitQuaternion(evecs[:,largestevalindex])
end
"""
`rotatevector(q, v)`
Given a unit quaternion `q` and a 3-vector `v`, performs a vector rotation and
returns the rotated vector `v`.
"""
function rotatevector(q::UnitQuaternion, v::AbstractVector)
length(v) == 3 || error("Must be a 3-vector.")
(2.0 * q.η^2 - 1.0) * v + (2.0 * q.η * ×(q.ϵ)) * v + (2.0 * q.ϵ * q.ϵ') * v
end
"""
`rotateframe(q, v)`
Given a unit quaternion `q` and a 3-vector `v`, performs a coordinate frame rotation and
returns `v` expressed in the rotated coordinate frame.
"""
function rotateframe(q::UnitQuaternion, v::AbstractVector)
length(v) == 3 || error("Must be a 3-vector.")
(2.0 * q.η^2 - 1.0) * v - (2.0 * q.η * ×(q.ϵ)) * v + (2.0 * q.ϵ * q.ϵ') * v
end
"""
`rotationmatrix(q)`
Creates a rotation matrix (direction cosine matrix) of the rotation parameterized by the unit quaternion `q`.
"""
function rotationmatrix(q::UnitQuaternion)
# Note, the "natural order" is used here (see Trawny or Shuster), which is different
# from the textbook by Kuipers, who uses the "historical" (Hamiltonian) order.
# Returned rotation matrix implements rotateframe (i.e., rotateframe(q, r) = rotationmatrix(q) * r)
return (+(q) * ⊕(inv(q)))[1:3, 1:3]
end
"""
`log(q)`
Takes the log of the unit quaternion `q`.
"""
function log(q::UnitQuaternion)
if q == UnitQuaternion()
return [0.0, 0.0, 0.0]
elseif abs(q.η) < EPS
return π/2 * axis(q)
else
return angle(q)/2.0 * axis(q)
end
end
"""
`show(io, q)`
Prints the unit quaternion `q` to the stream `io`.
"""
function show(io::IO, q::UnitQuaternion)
out = @sprintf("ϵ = [%.3f, %.3f, %.3f], η = %.3f", q.ϵ[1], q.ϵ[2], q.ϵ[3], q.η)
print(io, out)
end
"""
`slerp(p, q, t)`
Performs spherical linear interpolation from unit quaternion `p` to unit quaternion `q`. The
interpolation parameter `t` specifies the fraction of arc to traverse. The returned unit
quaternion parameterizes a rotation from `p` to the end point specified by `t`.
"""
slerp(p::UnitQuaternion, q::UnitQuaternion, t::Real) = (q + inv(p))^t + p
"""
`vector(q)`
Returns the elements of the unit quaternion `q` as a 4-vector.
"""
vector(q::UnitQuaternion) = [q.ϵ[1], q.ϵ[2], q.ϵ[3], q.η]
####################################################################################################
# Utility Functions
####################################################################################################
"""
`×(a)`
Returns the skew-symmetric cross product matrix of the 3-vector `a`.
"""
function ×(a::AbstractVector)
length(a) == 3 || error("Must be a 3-vector.")
return [0.0 -a[3] a[2]; a[3] 0.0 -a[1]; -a[2] a[1] 0.0]
end
end # module
|
kam3k/UnitQuaternions.jl
|
src/UnitQuaternions.jl
|
Julia
|
mit
| 9,578
|
var helper = require('../support/spec_helper');
var ORM = require('../../');
describe("Model keys option", function () {
var db = null;
before(function () {
db = helper.connect();
});
after(function () {
return db.closeSync();
});
describe("if model id is a property", function () {
var Person = null;
before(function () {
Person = db.define("person", {
uid: String,
name: String,
surname: String
}, {
id: "uid"
});
return helper.dropSync(Person);
});
it("should not auto increment IDs", function () {
var JohnDoe = Person.createSync({
uid: "john-doe",
name: "John",
surname: "Doe"
});
assert.equal(JohnDoe.uid, "john-doe");
assert.notProperty(JohnDoe, "id");
});
});
describe("if model defines several keys", function () {
var DoorAccessHistory = null;
before(function () {
DoorAccessHistory = db.define("door_access_history", {
year: {
type: 'integer'
},
month: {
type: 'integer'
},
day: {
type: 'integer'
},
user: String,
action: ["in", "out"]
}, {
id: ["year", "month", "day"]
});
return helper.dropSync(DoorAccessHistory, function () {
DoorAccessHistory.createSync([{
year: 2013,
month: 7,
day: 11,
user: "dresende",
action: "in"
},
{
year: 2013,
month: 7,
day: 12,
user: "dresende",
action: "out"
}
]);
});
});
it("should make possible to get instances based on all keys", function () {
var HistoryItem = DoorAccessHistory.getSync(2013, 7, 11);
assert.equal(HistoryItem.year, 2013);
assert.equal(HistoryItem.month, 7);
assert.equal(HistoryItem.day, 11);
assert.equal(HistoryItem.user, "dresende");
assert.equal(HistoryItem.action, "in");
});
it("should make possible to remove instances based on all keys", function () {
var HistoryItem = DoorAccessHistory.getSync(2013, 7, 12);
HistoryItem.removeSync();
var exists = DoorAccessHistory.existsSync(2013, 7, 12);
assert.isFalse(exists);
});
});
});
|
xicilion/fib-orm
|
test/integration/model-keys.js
|
JavaScript
|
mit
| 2,890
|
package eu.goodlike.hls.download.m3u.data.builder;
import com.google.inject.assistedinject.AssistedInject;
import eu.goodlike.hls.download.m3u.data.MediaPlaylistData;
import okhttp3.HttpUrl;
/**
* Factory for {@link MediaPlaylistBuilder}; implementation provided by Guice {@link AssistedInject}
*/
public interface MediaPlaylistBuilderFactory {
/**
* @param source url of the source of playlist data
* @return new {@link MediaPlaylistBuilder}
* @throws NullPointerException if source is null
*/
HlsBuilder<MediaPlaylistData> createMediaPlaylistBuilder(HttpUrl source);
}
|
TheGoodlike13/hls-downloader
|
src/main/java/eu/goodlike/hls/download/m3u/data/builder/MediaPlaylistBuilderFactory.java
|
Java
|
mit
| 605
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.