hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98 values | lang stringclasses 21 values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4172c4c88fc46e6eefb1b5f49f4660832e73ab80 | 3,810 | h | C | backend/drogon/trantor/trantor/utils/MsgBuffer.h | attikas/dr_website | c2d519ed06bc211f854ca2b7ad44e756eda567f2 | [
"MIT"
] | null | null | null | backend/drogon/trantor/trantor/utils/MsgBuffer.h | attikas/dr_website | c2d519ed06bc211f854ca2b7ad44e756eda567f2 | [
"MIT"
] | null | null | null | backend/drogon/trantor/trantor/utils/MsgBuffer.h | attikas/dr_website | c2d519ed06bc211f854ca2b7ad44e756eda567f2 | [
"MIT"
] | null | null | null | /**
*
* MsgBuffer.h
* An Tao
*
* Public header file in trantor lib.
*
* Copyright 2018, An Tao. All rights reserved.
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
*
*/
#pragma once
#include <trantor/utils/NonCopyable.h>
#include <vector>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#ifdef _WIN32
using ssize_t = std::intptr_t;
#endif
namespace trantor
{
static constexpr size_t kBufferDefaultLength{2048};
static constexpr char CRLF[]{"\r\n"};
class MsgBuffer
{
public:
MsgBuffer(size_t len = kBufferDefaultLength);
// peek
const char *peek() const
{
return begin() + head_;
}
const char *beginWrite() const
{
return begin() + tail_;
}
char *beginWrite()
{
return begin() + tail_;
}
uint8_t peekInt8() const
{
assert(readableBytes() >= 1);
return *(static_cast<const uint8_t *>((void *)peek()));
}
uint16_t peekInt16() const;
uint32_t peekInt32() const;
uint64_t peekInt64() const;
// read
std::string read(size_t len);
uint8_t readInt8();
uint16_t readInt16();
uint32_t readInt32();
uint64_t readInt64();
void swap(MsgBuffer &buf) noexcept;
size_t readableBytes() const
{
return tail_ - head_;
}
size_t writableBytes() const
{
return buffer_.size() - tail_;
}
// append
void append(const MsgBuffer &buf);
template <int N>
void append(const char (&buf)[N])
{
assert(strnlen(buf, N) == N - 1);
append(buf, N - 1);
}
void append(const char *buf, size_t len);
void append(const std::string &buf)
{
append(buf.c_str(), buf.length());
}
void appendInt8(const uint8_t b)
{
append(static_cast<const char *>((void *)&b), 1);
}
void appendInt16(const uint16_t s);
void appendInt32(const uint32_t i);
void appendInt64(const uint64_t l);
// add in front
void addInFront(const char *buf, size_t len);
void addInFrontInt8(const int8_t b)
{
addInFront(static_cast<const char *>((void *)&b), 1);
}
void addInFrontInt16(const int16_t s);
void addInFrontInt32(const int32_t i);
void addInFrontInt64(const int64_t l);
void retrieveAll();
void retrieve(size_t len);
ssize_t readFd(int fd, int *retErrno);
void retrieveUntil(const char *end)
{
assert(peek() <= end);
assert(end <= beginWrite());
retrieve(end - peek());
}
// find
const char *findCRLF() const
{
const char *crlf = std::search(peek(), beginWrite(), CRLF, CRLF + 2);
return crlf == beginWrite() ? NULL : crlf;
}
void ensureWritableBytes(size_t len);
void hasWritten(size_t len)
{
assert(len <= writableBytes());
tail_ += len;
}
// cancel
void unwrite(size_t offset)
{
assert(readableBytes() >= offset);
tail_ -= offset;
}
const char &operator[](size_t offset) const
{
assert(readableBytes() >= offset);
return peek()[offset];
}
char &operator[](size_t offset)
{
assert(readableBytes() >= offset);
return begin()[head_ + offset];
}
private:
size_t head_;
size_t initCap_;
std::vector<char> buffer_;
size_t tail_;
const char *begin() const
{
return &buffer_[0];
}
char *begin()
{
return &buffer_[0];
}
};
inline void swap(MsgBuffer &one, MsgBuffer &two) noexcept
{
one.swap(two);
}
} // namespace trantor
namespace std
{
template <>
inline void swap(trantor::MsgBuffer &one, trantor::MsgBuffer &two) noexcept
{
one.swap(two);
}
} // namespace std
| 22.411765 | 77 | 0.598425 |
270d9f4adf15d619134996e965e7570932375e64 | 1,451 | h | C | MTHawkeyeDemo/MTHawkeyeDemo/GraphicsDemo/GLESTool.h | JonyFang/MTHawkeye | b90d15aaa72bf6b74d80c0b62ce7a105cbcb5db1 | [
"MIT"
] | 1,357 | 2019-04-17T10:43:30.000Z | 2022-03-24T08:00:07.000Z | MTHawkeyeDemo/MTHawkeyeDemo/GraphicsDemo/GLESTool.h | JonyFang/MTHawkeye | b90d15aaa72bf6b74d80c0b62ce7a105cbcb5db1 | [
"MIT"
] | 52 | 2019-04-19T01:59:20.000Z | 2021-09-13T15:11:21.000Z | MTHawkeyeDemo/MTHawkeyeDemo/GraphicsDemo/GLESTool.h | JonyFang/MTHawkeye | b90d15aaa72bf6b74d80c0b62ce7a105cbcb5db1 | [
"MIT"
] | 173 | 2019-04-17T10:52:08.000Z | 2022-03-30T06:11:44.000Z | //
// GLESTool.h
// MTHawkeyeDemo
//
// Created by David.Dai on 2019/3/20.
// Copyright © 2019 Meitu. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>
NS_ASSUME_NONNULL_BEGIN
#define GLES_LONG_STRING(x) #x
#define GLES_SHADER_STRING(name) @GLES_LONG_STRING(name)
extern NSString *const kTexutreVertexShaderString;
extern NSString *const kTextureFragmentShaderString;
typedef struct {
GLuint program;
GLuint vertexShader;
GLuint fragmentShader;
} GLESProgram;
typedef struct {
GLint positionAttribute;
GLint inputTextureCoorAttribute;
GLint textureUniform;
} GLESTextureProgramAttribute;
typedef struct {
GLuint texutreId;
float width;
float height;
} GLESTextureInfo;
@interface GLESTool : NSObject
+ (GLESProgram)programWithVertexShader:(NSString *)vertexShaderStr fragmentShader:(NSString *)fragmentShaderStr;
+ (void)releaseProgram:(GLESProgram)program;
+ (GLESTextureProgramAttribute)attchTextureAttributeToProgram:(GLESProgram)program;
+ (GLint)attributeIndex:(NSString *)attributeName program:(GLuint)program;
+ (GLint)uniformIndex:(NSString *)uniformName program:(GLuint)program;
+ (GLESTextureInfo)texture:(UIImage *)image;
+ (void)releaseTexture:(GLESTextureInfo)textureInfo;
+ (unsigned char *)pixelRGBABytesFromImageRef:(CGImageRef)imageRef;
+ (GLfloat *)textureVertexForViewSize:(CGSize)viewSize textureSize:(CGSize)textureSize;
@end
NS_ASSUME_NONNULL_END
| 27.903846 | 112 | 0.787733 |
1cadc2dcfa0dda815f089a06baad67dbaf53c6ed | 1,228 | css | CSS | web/rainmaker/dev-packages/egov-bpa-dev/src/ui-config/screens/specs/utils/index.css | venkatesan-egov/frontend | 53b0d9b904a96f45cd8db8233cbbcce57599e295 | [
"MIT"
] | null | null | null | web/rainmaker/dev-packages/egov-bpa-dev/src/ui-config/screens/specs/utils/index.css | venkatesan-egov/frontend | 53b0d9b904a96f45cd8db8233cbbcce57599e295 | [
"MIT"
] | null | null | null | web/rainmaker/dev-packages/egov-bpa-dev/src/ui-config/screens/specs/utils/index.css | venkatesan-egov/frontend | 53b0d9b904a96f45cd8db8233cbbcce57599e295 | [
"MIT"
] | null | null | null | .radio-button-group {
padding: 0;
}
.checkbox-root {
width: 16px;
margin-right: 11px;
}
.fontSize12 {
font-size: 12px;
}
.city-picker-dialog-style {
min-height: 180px;
min-width: 365px;
}
@media only screen and (max-width: 768px) {
.city-picker-dialog-style {
min-width: 250px;
}
}
.tl-trade-type div {
color: rgba(0, 0, 0, 0.87) !important;
}
div[class^="MuiPaper-root"] svg text, .stepper-container svg text {
font-size: 15px !important }
.bpacheckbox-label {
letter-spacing: 0.58px;
margin-bottom: 0 !important;
color: rgba(0, 0, 0, 0.87);
}
#material-ui-rightContainerH div{
font-size: 24px !important;
padding-top: 10px !important;
color: #262627 !important;
}
#material-ui-rightContainer {
margin-top: 5px !important;
}
#material-ui-applicantContainer {
background: rgb(242, 242, 242) !important;
padding: 10px !important;
}
#material-ui-applicantContainer div:nth-child(3),
#material-ui-blocksContainer div:nth-child(3) {
width: 100% !important;
}
#material-ui-fieldinspectionSummary {
width: 100% !important;
}
#material-ui-buildingheaderDetails:nth-child(1) {
padding: 14px 0 0 10px;
}
#custom-containers-proposedLabel {
color: black;
font-size: 16px;
}
| 18.058824 | 67 | 0.685668 |
9c3529d0263cf22d3b746f71a7165b33c52e65bd | 1,782 | js | JavaScript | 40/canvas/scripts/script.js | kredep/IT2 | bdf9150f570a8b7e9c47beaac386615794559a86 | [
"MIT"
] | null | null | null | 40/canvas/scripts/script.js | kredep/IT2 | bdf9150f570a8b7e9c47beaac386615794559a86 | [
"MIT"
] | null | null | null | 40/canvas/scripts/script.js | kredep/IT2 | bdf9150f570a8b7e9c47beaac386615794559a86 | [
"MIT"
] | null | null | null | window.onload = startUp;
function startUp() {
draw1();
draw2();
draw3();
}
function draw1() {
var canvas = document.getElementById("oppg1");
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.rect(20,200,660,230);
ctx.fillStyle = 'rgb(200,0,0)';
ctx.fillRect(20,200,660,230);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(20,200);
ctx.lineTo(350,20);
ctx.lineTo(680,200);
ctx.fillStyle = 'rgb(20,200,150)';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.rect(80,250,140,140);
ctx.fillStyle = 'rgb(255,255,255)';
ctx.fillRect(80,250,140,140);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(150,250);
ctx.lineTo(150,390);
ctx.moveTo(80,320);
ctx.lineTo(220,320);
ctx.stroke();
ctx.rect(450,250,100,180);
ctx.fillStyle = 'rgb(255,255,255)';
ctx.fillRect(450,250,100,180);
ctx.stroke();
}
function draw2() {
var canvas = document.getElementById("oppg2");
var ctx = canvas.getContext("2d");
ctx.lineWidth = 3;
for (let i=1;i<6;i++) {
ctx.beginPath();
ctx.arc(250, 250, i*20, 0, 2 * Math.PI);
ctx.stroke();
}
}
function draw3() {
var canvas = document.getElementById("oppg3");
var ctx = canvas.getContext("2d");
ctx.fillStyle = 'rgb(218, 224, 179)';
ctx.fillRect(0,0,600,600);
ctx.lineWidth = 4;
for (let i=1;i<15;i++) {
var grd = (15-i) / 14;
if (i%2!=0) {
var rgba = 'rgba(0,255,0,' + grd + ')';
} else {
var rgba = 'rgba(255,0,0,' + grd + ')';
}
console.log(rgba);
ctx.beginPath();
ctx.strokeStyle = rgba;
ctx.arc(300, 300, i*17, 0, 2 * Math.PI);
ctx.closePath();
ctx.stroke();
}
}
| 24.75 | 51 | 0.541526 |
fe2dff4f1b46ac0720634d12233c24b6f0ddeade | 3,072 | c | C | src/psv-strip.c | psvsdk/psvsdk | 389e7d33dd1133e36fdf2fce8eb0b2608646f117 | [
"MIT"
] | 11 | 2019-03-08T15:59:01.000Z | 2021-10-05T04:23:43.000Z | src/psv-strip.c | psvsdk/psvsdk | 389e7d33dd1133e36fdf2fce8eb0b2608646f117 | [
"MIT"
] | 3 | 2019-03-03T20:16:19.000Z | 2020-02-09T12:00:05.000Z | src/psv-strip.c | psvsdk/psvsdk | 389e7d33dd1133e36fdf2fce8eb0b2608646f117 | [
"MIT"
] | 53 | 2020-01-06T11:25:26.000Z | 2022-03-20T15:40:41.000Z | /**
# NAME
psv-strip - strip a Vita ELF
# SYNOPSIS
psv-strip in.velf out.velf
# NOTES
does not seems to work on every case
# CREDIT
- github.com/Princess-of-Sleeping
# SEE ALSO
- velf(5)
*/
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "elf.h"
#define EXPECT(EXPR, FMT, ...) \
if (!(EXPR)) \
return fprintf(stderr, FMT "\n", ##__VA_ARGS__), -1;
#ifndef USAGE
#define USAGE "See man psv-pack\n"
#endif
int pack_velf(FILE* fd_src, FILE* fd_dst) {
char buf[0x100];
EXPECT(fread(buf, sizeof(buf), 1, fd_src) == 1, "Bad ELF header size");
/*
* Remove section entrys
*/
Elf32_Ehdr* elf_header = (Elf32_Ehdr*)buf;
elf_header->e_shoff = 0;
elf_header->e_shentsize = 0;
elf_header->e_shnum = 0;
elf_header->e_shstrndx = 0;
Elf32_Phdr* pPhdr = (Elf32_Phdr*)(buf + elf_header->e_phoff);
/*
* Packed ehdr and phdr
*/
if (elf_header->e_phoff != elf_header->e_ehsize) {
Elf32_Phdr* pPhdrTmp = malloc(elf_header->e_phentsize * elf_header->e_phnum);
memcpy(pPhdrTmp, pPhdr, elf_header->e_phentsize * elf_header->e_phnum);
memset(buf + elf_header->e_ehsize, 0, sizeof(buf) - elf_header->e_ehsize);
memcpy(buf + elf_header->e_ehsize, pPhdrTmp, elf_header->e_phentsize * elf_header->e_phnum);
free(pPhdrTmp);
elf_header->e_phoff = elf_header->e_ehsize;
pPhdr = (Elf32_Phdr*)(buf + elf_header->e_phoff);
}
long seg_offset = elf_header->e_ehsize + (elf_header->e_phentsize * elf_header->e_phnum);
/*
* Write packed elf header
*/
fseek(fd_dst, 0, SEEK_SET);
EXPECT(fwrite(buf, seg_offset, 1, fd_dst) == 1, "Unable to write packed elf header");
/*
* Write elf segments
*/
for (int i = 0; i < elf_header->e_phnum; i++) {
/*
* vita only accepts 0x10 to 0x1000 alignments
*/
if (pPhdr[i].p_align > 0x1000) {
pPhdr[i].p_align = 0x10; // vita elf default align
}
seg_offset = (seg_offset + (pPhdr[i].p_align - 1)) & ~(pPhdr[i].p_align - 1);
if (pPhdr[i].p_filesz != 0) {
void* seg_tmp = malloc(pPhdr[i].p_filesz);
fseek(fd_dst, seg_offset, SEEK_SET);
fseek(fd_src, pPhdr[i].p_offset, SEEK_SET);
EXPECT(fread(seg_tmp, pPhdr[i].p_filesz, 1, fd_src) == 1, "Unable to read pHdr[%i]", i);
EXPECT(fwrite(seg_tmp, pPhdr[i].p_filesz, 1, fd_dst) == 1, "Unable to read pHdr[%i]", i);
free(seg_tmp);
seg_tmp = NULL;
}
pPhdr[i].p_offset = seg_offset;
seg_offset += pPhdr[i].p_filesz;
}
seg_offset = elf_header->e_ehsize + (elf_header->e_phentsize * elf_header->e_phnum);
/*
* Write updated elf header
*/
fseek(fd_dst, 0, SEEK_SET);
EXPECT(fwrite(&buf, seg_offset, 1, fd_dst) == 1, "Unable to write final ELF");
return 0;
}
int main(int argc, char** argv) {
EXPECT(argc > 2, "%s", USAGE);
FILE* fd_src = fopen(argv[1], "rb");
EXPECT(fd_src, "Unable to open input file");
FILE* fd_dst = fopen(argv[2], "wb");
EXPECT(fd_dst, "Unable to open output file"); // cppcheck-suppress resourceLeak
pack_velf(fd_src, fd_dst);
fclose(fd_dst);
fclose(fd_src);
return 0;
}
| 23.097744 | 94 | 0.655924 |
1fca81150897cbfe4ea4ff6677d795b2328bf5a6 | 628 | html | HTML | ES6/promise/ajax_json/one.html | ZhengGuoDeveloper/javascript-master | 0cf071ad5a9e84720c31c7a2bc263d4613761e58 | [
"MIT"
] | null | null | null | ES6/promise/ajax_json/one.html | ZhengGuoDeveloper/javascript-master | 0cf071ad5a9e84720c31c7a2bc263d4613761e58 | [
"MIT"
] | null | null | null | ES6/promise/ajax_json/one.html | ZhengGuoDeveloper/javascript-master | 0cf071ad5a9e84720c31c7a2bc263d4613761e58 | [
"MIT"
] | null | null | null | <script>
new Promise(function (resolve, reject) {
// setTimeout(function () {
var a=100;
resolve(a);
// }, 1000);
}).then(function (res) {
console.log(res);
return new Promise(function (resolve, reject) {
// setTimeout(function () {
var b=200;
resolve(b);
// }, 1000);
// })
}).then(function (res) {
console.log(res);
return new Promise(function (resolve, reject) {
setTimeout(function () {
var c=300
resolve(c);
}, 1000);
})
}).then(function (res) {
console.log(res);
}
)
</script> | 23.259259 | 51 | 0.496815 |
0ff36619b455c8047fc6c927952fb87ee2f17577 | 8,868 | swift | Swift | Sources/MessagePack/ConvenienceProperties.swift | Aranatha/MessagePackSwift | a507b8e69a3b6ca1418f36818454959fce058cda | [
"MIT"
] | null | null | null | Sources/MessagePack/ConvenienceProperties.swift | Aranatha/MessagePackSwift | a507b8e69a3b6ca1418f36818454959fce058cda | [
"MIT"
] | null | null | null | Sources/MessagePack/ConvenienceProperties.swift | Aranatha/MessagePackSwift | a507b8e69a3b6ca1418f36818454959fce058cda | [
"MIT"
] | null | null | null | import Foundation
extension MessagePackValue {
/// The number of elements in the `.Array` or `.Map`, `nil` otherwise.
public func count() throws -> Int {
switch self {
case .array(let array):
return array.count
case .map(let dict):
return dict.count
default:
throw MessagePackError.unsupportedType
}
}
/// The element at subscript `i` in the `.Array`, `nil` otherwise.
public subscript (i: Int) -> MessagePackValue? {
switch self {
case .array(let array):
return i < array.count ? array[i] : Optional.none
default:
return nil
}
}
/// The element at keyed subscript `key`, `nil` otherwise.
public subscript (key: MessagePackValue) -> MessagePackValue? {
switch self {
case .map(let dict):
return dict[key]
default:
return nil
}
}
/// True if `.Nil`, false otherwise.
public var isNil: Bool {
switch self {
case .nil:
return true
default:
return false
}
}
// MARK: Signed integer values
/// The signed platform-dependent width integer value if `.int` or an
/// appropriately valued `.uint`, `nil` otherwise.
public func intValue() throws -> Int {
switch self {
case .int(let value):
return try Int(msgpk_exactly: value)
case .uint(let value):
return try Int(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The signed 8-bit integer value if `.int` or an appropriately valued
/// `.uint`, `nil` otherwise.
public func int8Value() throws -> Int8 {
switch self {
case .int(let value):
return try Int8(msgpk_exactly: value)
case .uint(let value):
return try Int8(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The signed 16-bit integer value if `.int` or an appropriately valued
/// `.uint`, `nil` otherwise.
public func int16Value() throws -> Int16 {
switch self {
case .int(let value):
return try Int16(msgpk_exactly: value)
case .uint(let value):
return try Int16(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The signed 32-bit integer value if `.int` or an appropriately valued
/// `.uint`, `nil` otherwise.
public func int32Value() throws -> Int32 {
switch self {
case .int(let value):
return try Int32(msgpk_exactly: value)
case .uint(let value):
return try Int32(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The signed 64-bit integer value if `.int` or an appropriately valued
/// `.uint`, `nil` otherwise.
public func int64Value() throws -> Int64 {
switch self {
case .int(let value):
return value
case .uint(let value):
return try Int64(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
// MARK: Unsigned integer values
/// The unsigned platform-dependent width integer value if `.uint` or an
/// appropriately valued `.int`, `nil` otherwise.
public func uintValue() throws -> UInt {
switch self {
case .int(let value):
return try UInt(msgpk_exactly: value)
case .uint(let value):
return try UInt(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The unsigned 8-bit integer value if `.uint` or an appropriately valued
/// `.int`, `nil` otherwise.
public func uint8Value() throws -> UInt8 {
switch self {
case .int(let value):
return try UInt8(msgpk_exactly: value)
case .uint(let value):
return try UInt8(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The unsigned 16-bit integer value if `.uint` or an appropriately valued
/// `.int`, `nil` otherwise.
public func uint16Value() throws -> UInt16 {
switch self {
case .int(let value):
return try UInt16(msgpk_exactly: value)
case .uint(let value):
return try UInt16(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The unsigned 32-bit integer value if `.uint` or an appropriately valued
/// `.int`, `nil` otherwise.
public func uint32Value() throws -> UInt32 {
switch self {
case .int(let value):
return try UInt32(msgpk_exactly: value)
case .uint(let value):
return try UInt32(msgpk_exactly: value)
default:
throw MessagePackError.unsupportedType
}
}
/// The unsigned 64-bit integer value if `.uint` or an appropriately valued
/// `.int`, `nil` otherwise.
public func uint64Value() throws -> UInt64 {
switch self {
case .int(let value):
return try UInt64(msgpk_exactly: value)
case .uint(let value):
return value
default:
throw MessagePackError.unsupportedType
}
}
/// The contained array if `.Array`, `nil` otherwise.
public func arrayValue() throws -> [MessagePackValue] {
switch self {
case .array(let array):
return array
default:
throw MessagePackError.unsupportedType
}
}
/// The contained boolean value if `.Bool`, `nil` otherwise.
public func boolValue() throws -> Bool {
switch self {
case .bool(let value):
return value
default:
throw MessagePackError.unsupportedType
}
}
/// The contained floating point value if `.Float` or `.Double`, `nil` otherwise.
public func floatValue() throws -> Float {
switch self {
case .float(let value):
return value
case .double(let value):
guard let float = Float(exactly: value) else {
throw MessagePackError.inexact
}
return float
default:
throw MessagePackError.unsupportedType
}
}
/// The contained double-precision floating point value if `.Float` or `.Double`, `nil` otherwise.
public func doubleValue() throws -> Double {
switch self {
case .float(let value):
guard let double = Double(exactly: value) else {
throw MessagePackError.inexact
}
return double
case .double(let value):
return value
default:
throw MessagePackError.unsupportedType
}
}
/// The contained string if `.String`, `nil` otherwise.
public func stringValue() throws -> String {
switch self {
case .binary(let data):
guard let string = String(data: data, encoding: .utf8) else {
throw MessagePackError.invalidData
}
return string
case .string(let string):
return string
default:
throw MessagePackError.unsupportedType
}
}
/// The contained data if `.Binary` or `.Extended`, `nil` otherwise.
public func dataValue() throws -> Data {
switch self {
case .binary(let bytes):
return bytes
case .extended(_, let data):
return data
default:
throw MessagePackError.unsupportedType
}
}
/// The contained timestamp as Date
public var timestampValue: Date? {
switch self {
case let .timestamp(date):
return date
default:
return nil
}
}
/// The contained type and data if Extended, `nil` otherwise.
public func extendedValue() throws -> (Int8, Data) {
guard case let .extended(type, data) = self else {
throw MessagePackError.unsupportedType
}
return (type, data)
}
/// The contained type if `.Extended`, `nil` otherwise.
public func extendedType() throws -> Int8 {
guard case let .extended(type, _) = self else {
throw MessagePackError.unsupportedType
}
return type
}
/// The contained dictionary if `.Map`, `nil` otherwise.
public func dictionaryValue() throws -> [MessagePackValue: MessagePackValue] {
guard case let .map(dict) = self else {
throw MessagePackError.unsupportedType
}
return dict
}
}
| 30.474227 | 102 | 0.568899 |
33270a402f92d2ec94e2db647e7c5d239b6f78fe | 3,733 | py | Python | temboo/core/Library/LittleSis/Relationship/GetOneRelationship.py | jordanemedlock/psychtruths | 52e09033ade9608bd5143129f8a1bfac22d634dd | [
"Apache-2.0"
] | 7 | 2016-03-07T02:07:21.000Z | 2022-01-21T02:22:41.000Z | temboo/core/Library/LittleSis/Relationship/GetOneRelationship.py | jordanemedlock/psychtruths | 52e09033ade9608bd5143129f8a1bfac22d634dd | [
"Apache-2.0"
] | null | null | null | temboo/core/Library/LittleSis/Relationship/GetOneRelationship.py | jordanemedlock/psychtruths | 52e09033ade9608bd5143129f8a1bfac22d634dd | [
"Apache-2.0"
] | 8 | 2016-06-14T06:01:11.000Z | 2020-04-22T09:21:44.000Z | # -*- coding: utf-8 -*-
###############################################################################
#
# GetOneRelationship
# Retrieves information about any known relationship between two entities in LittleSis according their IDs.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetOneRelationship(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the GetOneRelationship Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(GetOneRelationship, self).__init__(temboo_session, '/Library/LittleSis/Relationship/GetOneRelationship')
def new_input_set(self):
return GetOneRelationshipInputSet()
def _make_result_set(self, result, path):
return GetOneRelationshipResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return GetOneRelationshipChoreographyExecution(session, exec_id, path)
class GetOneRelationshipInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the GetOneRelationship
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_APIKey(self, value):
"""
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from LittleSis.org.)
"""
super(GetOneRelationshipInputSet, self)._set_input('APIKey', value)
def set_EntityIDs(self, value):
"""
Set the value of the EntityIDs input for this Choreo. ((required, string) The IDs of the entities between which you want to find relationships. Format is a semicolon delimited string (e.g. 1026;1))
"""
super(GetOneRelationshipInputSet, self)._set_input('EntityIDs', value)
def set_ResponseFormat(self, value):
"""
Set the value of the ResponseFormat input for this Choreo. ((optional, string) Format of the response returned by LittleSis.org. Acceptable inputs: xml or json. Defaults to xml)
"""
super(GetOneRelationshipInputSet, self)._set_input('ResponseFormat', value)
class GetOneRelationshipResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the GetOneRelationship Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from LittleSis.org.)
"""
return self._output.get('Response', None)
class GetOneRelationshipChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return GetOneRelationshipResultSet(response, path)
| 40.139785 | 205 | 0.699437 |
41365f271a2363e69f094ef8d5a9c3365ab4616e | 1,095 | kt | Kotlin | src/main/kotlin/solace/sponge/service/user/UserStorageService.kt | TheFrontier/Solace | 874c63d715195c51336742741cf27a4b0a7a1c37 | [
"MIT"
] | 2 | 2019-01-10T10:18:45.000Z | 2019-01-10T12:35:53.000Z | src/main/kotlin/solace/sponge/service/user/UserStorageService.kt | xDotDash/Solace | 3f842f87e34cd58df4ac24401cc7150ff7e27a5f | [
"MIT"
] | null | null | null | src/main/kotlin/solace/sponge/service/user/UserStorageService.kt | xDotDash/Solace | 3f842f87e34cd58df4ac24401cc7150ff7e27a5f | [
"MIT"
] | null | null | null | @file:Suppress("NOTHING_TO_INLINE")
package solace.sponge.service.user
import org.spongepowered.api.entity.living.player.User
import org.spongepowered.api.profile.GameProfile
import org.spongepowered.api.service.user.UserStorageService
import solace.java.util.unwrapped
import solace.sponge.service.uncheckedService
import java.util.*
inline val UserStorageService: UserStorageService
get() = org.spongepowered.api.service.user.UserStorageService::class.java.uncheckedService
inline val UUID.user: User?
get() = UserStorageService.get(this).unwrapped
inline val String.user: User?
get() = UserStorageService.get(this).unwrapped
inline val GameProfile.user: User?
get() = UserStorageService.get(this).unwrapped
inline fun GameProfile.getOrCreateUser(): User =
UserStorageService.getOrCreate(this)
inline fun GameProfile.deleteUser(): Boolean =
UserStorageService.delete(this)
inline fun User.delete(): Boolean =
UserStorageService.delete(this)
inline fun String.matchGameProfile(): Collection<GameProfile> =
UserStorageService.match(this) | 32.205882 | 94 | 0.786301 |
33145b0e261a1ea5fd7c8dd0a24951e1dbcfbc1a | 279 | kt | Kotlin | app/src/main/java/lt/getpet/getpet/constants/ActivityConstants.kt | Hack4Vilnius/getpet-android | f1603cc232dd76a406c76231b229e2150f9ae70a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/lt/getpet/getpet/constants/ActivityConstants.kt | Hack4Vilnius/getpet-android | f1603cc232dd76a406c76231b229e2150f9ae70a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/lt/getpet/getpet/constants/ActivityConstants.kt | Hack4Vilnius/getpet-android | f1603cc232dd76a406c76231b229e2150f9ae70a | [
"Apache-2.0"
] | null | null | null | package lt.getpet.getpet.constants
class ActivityConstants {
companion object {
const val PET_FAVORITE = 1001
const val RC_SIGN_IN = 10007
const val EXTRA_PET = "pet"
const val EXTRA_SHOW_GET_PET_BUTTON = "EXTRA_SHOW_GET_PET_BUTTON"
}
} | 23.25 | 73 | 0.688172 |
5f85b844a0c276c5b6fb242334554619432dec26 | 8,352 | sql | SQL | tabmes.sql | rezaiqbal10/projekmagang | 04b1f3f4a25ab0595bc6d9180aa654286f2b3845 | [
"MIT"
] | null | null | null | tabmes.sql | rezaiqbal10/projekmagang | 04b1f3f4a25ab0595bc6d9180aa654286f2b3845 | [
"MIT"
] | null | null | null | tabmes.sql | rezaiqbal10/projekmagang | 04b1f3f4a25ab0595bc6d9180aa654286f2b3845 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 09, 2020 at 07:10 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `tabmes`
--
-- --------------------------------------------------------
--
-- Table structure for table `kontruksi`
--
CREATE TABLE `kontruksi` (
`id` int(11) NOT NULL,
`paket_pekerjaan` varchar(200) NOT NULL,
`lokasi` varchar(200) NOT NULL,
`output` varchar(200) NOT NULL,
`outcome` varchar(200) NOT NULL,
`penyedia_jasa` varchar(200) NOT NULL,
`tahun_anggaran` int(5) DEFAULT NULL,
`biaya` varchar(200) DEFAULT NULL,
`created_date` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `kontruksi`
--
INSERT INTO `kontruksi` (`id`, `paket_pekerjaan`, `lokasi`, `output`, `outcome`, `penyedia_jasa`, `tahun_anggaran`, `biaya`, `created_date`) VALUES
(1, 'combo extra', 'jakarta', '2', '3', 'jne', 2019, '6', NULL),
(3, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', 'JAMBI', '1', '2', 'g', 2019, '12', NULL),
(4, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', 'Kab. Boyolali', '1', '2', 'Km', 2012, '12', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `sda`
--
CREATE TABLE `sda` (
`id` int(11) NOT NULL,
`paket_pekerjaan` varchar(200) NOT NULL,
`penyedia_jasa` varchar(200) NOT NULL,
`tahun_anggaran` int(5) DEFAULT NULL,
`created_date` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `sda`
--
INSERT INTO `sda` (`id`, `paket_pekerjaan`, `penyedia_jasa`, `tahun_anggaran`, `created_date`) VALUES
(4, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi irigasi dan rawa', 'Dokumen', 2020, NULL),
(8, 'Bendung irigasi kewenangan Daerah yang dibangun', 'Bendung', 2020, NULL),
(9, 'Jaringan irigasi rawa yang dibangun', 'km', 2020, NULL),
(10, 'Jaringan irigasi tambak yang dibangun', 'km', 2020, NULL),
(11, 'Jaringan irigasi permukaan kewenangan Pusat yang direhabilitasi/ditingkatkan', 'km', 2020, NULL),
(12, 'Bendung irigasi kewenangan Pusat yang direhabilitasi/ditingkatkan', 'Bendung', 2020, NULL),
(13, 'Jaringan irigasi permukaan kewenangan Daerah yang direhabilitasi/ditingkatkan', 'Km', 2020, NULL),
(14, 'Bendung irigasi kewenangan Daerah yang direhabilitasi/ditingkatkan', 'Bendung', 2020, NULL),
(15, 'Jaringan irigasi rawa yang direhabilitasi/ditingkatkan', 'Km', 2020, NULL),
(16, 'Jaringan irigasi tambak yang direhabilitasi/ditingkatkan', 'Km', 2020, NULL),
(17, 'Kawasan rawa yang dikonservasi', 'Km', 2020, NULL),
(18, 'Layanan Sarana dan Prasarana Internal', 'Layanan', 2020, NULL),
(19, 'Layanan Dukungan Manajemen Satker', 'Layanan', 2020, NULL),
(20, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi pengendali banjir, lahar, drainase utama perkotaan, dan pengaman pantai', 'Dokumen', 2020, NULL),
(21, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', 'Dokumen', 2020, NULL),
(22, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi air tanah dan air baku', 'Dokumen', 2020, NULL),
(23, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi irigasi dan rawa', '200.0003 Dokumen', 2015, NULL),
(24, 'Jaringan irigasi permukaan kewenangan Pusat yang dibangun', '436.7611 Km', 2015, NULL),
(25, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi pengendali banjir, lahar, drainase utama perkotaan, dan pengaman pantai', '61.0001 Dokumen', 2015, NULL),
(26, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', '132.0002 Dokumen', 2015, NULL),
(27, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi air tanah dan air baku', '68.0005 Dokumen', 2017, NULL),
(28, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi irigasi dan rawa', '200.0003 Dokumen', 2016, NULL),
(29, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi pengendali banjir, lahar, drainase utama perkotaan, dan pengaman pantai', '61.0001 Dokumen', 2016, NULL),
(30, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', '132.0002 Dokumen', 2016, NULL),
(31, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi air tanah dan air baku', '68.0005 Dokumen', 2016, NULL),
(32, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi irigasi dan rawa', '200.0003 Dokumen', 2017, NULL),
(33, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi pengendali banjir, lahar, drainase utama perkotaan, dan pengaman pantai', '61.0001 Dokumen', 2017, NULL),
(34, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', '132.0002 Dokumen', 2017, NULL),
(35, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi air tanah dan air baku', '68.0005 Dokumen', 2017, NULL),
(36, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi irigasi dan rawa', '200.0003 Dokumen', 2018, NULL),
(37, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi pengendali banjir, lahar, drainase utama perkotaan, dan pengaman pantai', '61.0001 Dokumen', 2018, NULL),
(38, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', '132.0002 Dokumen', 2018, NULL),
(39, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi air tanah dan air baku', '68.0005 Dokumen', 2018, NULL),
(40, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi irigasi dan rawa', '200.0003 Dokumen', 2019, NULL),
(41, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi pengendali banjir, lahar, drainase utama perkotaan, dan pengaman pantai', '61.0001 Dokumen', 2019, NULL),
(42, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi bendungan dan bangunan penampung air lainnya', '132.0002 Dokumen', 2019, NULL),
(43, 'Rencana teknis dan dokumen lingkungan hidup untuk konstruksi air tanah dan air baku', '68.0005 Dokumen', 2019, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`id_user` int(11) NOT NULL,
`nama` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`no_telp` varchar(15) NOT NULL,
`role` enum('gudang','admin','manager') NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` int(11) NOT NULL,
`foto` text NOT NULL,
`is_active` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id_user`, `nama`, `username`, `email`, `no_telp`, `role`, `password`, `created_at`, `foto`, `is_active`) VALUES
(1, 'Adminisitrator', 'admin', 'admin@admin.com', '025123456789', 'admin', '$2y$10$wMgi9s3FEDEPEU6dEmbp8eAAEBUXIXUy3np3ND2Oih.MOY.q/Kpoy', 1568689561, '2a2d3270fafa1034a8a81d0d0072fcdc.png', 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `kontruksi`
--
ALTER TABLE `kontruksi`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `sda`
--
ALTER TABLE `sda`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id_user`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `kontruksi`
--
ALTER TABLE `kontruksi`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `sda`
--
ALTER TABLE `sda`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=44;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 45.639344 | 194 | 0.71875 |
1804c2477718baa3ceecb9eff1329d670d33379d | 10,940 | rs | Rust | src/main.rs | s3mon/s3mon | e0ba08efa118555a0f71185fd0c8301efcff1420 | [
"BSD-3-Clause"
] | 3 | 2019-10-18T02:59:42.000Z | 2019-10-20T09:59:16.000Z | src/main.rs | s3mon/s3mon | e0ba08efa118555a0f71185fd0c8301efcff1420 | [
"BSD-3-Clause"
] | 8 | 2019-10-03T21:02:03.000Z | 2019-10-17T21:01:44.000Z | src/main.rs | s3mon/s3mon | e0ba08efa118555a0f71185fd0c8301efcff1420 | [
"BSD-3-Clause"
] | 3 | 2019-10-10T17:14:11.000Z | 2021-01-11T05:36:24.000Z | use clap::{App, Arg};
use env_logger;
use serde_yaml;
use std::sync::Arc;
use std::{process, thread};
mod auth;
mod config;
mod s3;
fn main() {
// RUST_LOG=debug
let _ = env_logger::try_init();
// cli options
let matches = App::new("s3mon")
.version(env!("CARGO_PKG_VERSION"))
.arg(
Arg::with_name("config")
.help("config.yml")
.long("config")
.short("c")
.required(false)
.value_name("FILE")
.takes_value(true)
.validator(is_file),
)
.get_matches();
// Gets a value for config if supplied by user, or defaults to "default.conf"
let config = matches.value_of("config").unwrap_or_else(|| {
eprintln!("Unable to open configuration file, use (\"-h for help\")");
process::exit(1);
});
// parse config file
let file = std::fs::File::open(&config).expect("Unable to open file");
let yml: config::Config = match serde_yaml::from_reader(file) {
Err(e) => {
eprintln!("Error parsing configuration file: {}", e);
process::exit(1);
}
Ok(yml) => yml,
};
// create an S3 Client
let s3 = match s3::Monitor::new(&yml) {
Ok(s3) => Arc::new(s3),
Err(e) => {
eprintln!("Error: {}", e);
process::exit(1);
}
};
// store all threads
let mut children = vec![];
for bucket in yml.s3mon.buckets {
let bucket_name = bucket.0.to_string();
for file in bucket.1 {
let thread_s3 = Arc::clone(&s3);
let bucket = bucket_name.clone();
children.push(thread::spawn(|| {
println!("{}", check(thread_s3, bucket, file));
}));
}
}
// Wait for all the threads to finish
for child in children {
let _ = child.join();
}
}
fn check(s3: Arc<s3::Monitor>, bucket: String, file: config::Object) -> String {
// create InfluxDB line protocol
// https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/
let mut output: Vec<String> = Vec::new();
output.push(format!("s3mon,bucket={},prefix={}", bucket, file.prefix));
let mut exist = false;
let mut size_mismatch = false;
let mut bucket_error = false;
// query the bucket
match s3.objects(bucket, file.prefix, file.age) {
Ok(objects) => {
if !objects.is_empty() {
exist = true;
}
for o in objects {
if file.size > 0 {
if let Some(size) = o.size {
if size < file.size {
size_mismatch = true;
}
}
}
}
}
Err(e) => {
eprintln!("Error: {}", e);
bucket_error = true;
}
}
output.push(format!(
"error={}i,exist={}i,size_mismatch={}i",
bucket_error as i32, exist as i32, size_mismatch as i32,
));
output.join(" ")
}
fn is_file(s: String) -> Result<(), String> {
let metadata = match std::fs::metadata(&s) {
Err(err) => return Err(err.to_string()),
Ok(metadata) => metadata,
};
if !metadata.is_file() {
return Err(format!("cannot read file: {}", s));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_config() -> Result<(), serde_yaml::Error> {
let yml = r#"
---
s3mon:
endpoint: endpoint
region: region
access_key: ACCESS_KEY_ID
secret_key: SECRET_ACCESS_KEY
buckets:
bucket_A:
- prefix: foo
age: 43200
- prefix: bar
- prefix: baz
size: 1024
"#;
let mut buckets = std::collections::BTreeMap::new();
buckets.insert(
"bucket_A".to_string(),
vec![
config::Object {
prefix: "foo".to_string(),
age: 43200,
size: 0,
},
config::Object {
prefix: "bar".to_string(),
age: 86400,
size: 0,
},
config::Object {
prefix: "baz".to_string(),
age: 86400,
size: 1024,
},
],
);
let cfg = config::Config {
s3mon: config::Data {
endpoint: "endpoint".to_string(),
region: "region".to_string(),
access_key: "ACCESS_KEY_ID".to_string(),
secret_key: "SECRET_ACCESS_KEY".to_string(),
buckets,
},
};
let y: config::Config = serde_yaml::from_str(yml)?;
assert_eq!(cfg, y);
Ok(())
}
#[test]
fn check_object() {
use chrono::prelude::{SecondsFormat, Utc};
use rusoto_core::Region;
use rusoto_mock::{MockCredentialsProvider, MockRequestDispatcher};
use rusoto_s3::S3Client;
let last_modified = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
let mock = MockRequestDispatcher::with_status(200).with_body(
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Name>cubeta</Name>
<Prefix>E</Prefix>
<StartAfter>ExampleGuide.pdf</StartAfter>
<KeyCount>1</KeyCount>
<MaxKeys>3</MaxKeys>
<IsTruncated>false</IsTruncated>
<Contents>
<Key>ExampleObject.txt</Key>
<LastModified>{}</LastModified>
<ETag>"599bab3ed2c697f1d26842727561fd94"</ETag>
<Size>857</Size>
<StorageClass>REDUCED_REDUNDANCY</StorageClass>
</Contents>
</ListBucketResult>
"#,
last_modified
)
.as_str(),
);
let client = Arc::new(s3::Monitor {
s3: S3Client::new_with(mock, MockCredentialsProvider, Region::UsEast1),
});
// test finding file & prefix
let file = config::Object {
prefix: "E".to_string(),
age: 30,
size: 0,
};
assert_eq!(
check(client, "cubeta".to_string(), file),
"s3mon,bucket=cubeta,prefix=E error=0i,exist=1i,size_mismatch=0i",
);
}
#[test]
fn check_object_size_mismatch() {
use chrono::prelude::{SecondsFormat, Utc};
use rusoto_core::Region;
use rusoto_mock::{MockCredentialsProvider, MockRequestDispatcher};
use rusoto_s3::S3Client;
let last_modified = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
let mock = MockRequestDispatcher::with_status(200).with_body(
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Name>cubeta</Name>
<Prefix>E</Prefix>
<StartAfter>ExampleGuide.pdf</StartAfter>
<KeyCount>1</KeyCount>
<MaxKeys>3</MaxKeys>
<IsTruncated>false</IsTruncated>
<Contents>
<Key>ExampleObject.txt</Key>
<LastModified>{}</LastModified>
<ETag>"599bab3ed2c697f1d26842727561fd94"</ETag>
<Size>857</Size>
<StorageClass>REDUCED_REDUNDANCY</StorageClass>
</Contents>
</ListBucketResult>
"#,
last_modified
)
.as_str(),
);
let client = Arc::new(s3::Monitor {
s3: S3Client::new_with(mock, MockCredentialsProvider, Region::UsEast1),
});
// test finding file & prefix
let file = config::Object {
prefix: "E".to_string(),
age: 30,
size: 1024,
};
assert_eq!(
check(client, "cubeta".to_string(), file),
"s3mon,bucket=cubeta,prefix=E error=0i,exist=1i,size_mismatch=1i",
);
}
#[test]
fn check_object_age_expired() {
use rusoto_core::Region;
use rusoto_mock::{MockCredentialsProvider, MockRequestDispatcher};
use rusoto_s3::S3Client;
let mock = MockRequestDispatcher::with_status(200).with_body(
r#"<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Name>cubeta</Name>
<Prefix>E</Prefix>
<StartAfter>ExampleGuide.pdf</StartAfter>
<KeyCount>1</KeyCount>
<MaxKeys>3</MaxKeys>
<IsTruncated>false</IsTruncated>
<Contents>
<Key>ExampleObject.txt</Key>
<LastModified>2019-10-14T08:52:23.231Z</LastModified>
<ETag>"599bab3ed2c697f1d26842727561fd94"</ETag>
<Size>857</Size>
<StorageClass>REDUCED_REDUNDANCY</StorageClass>
</Contents>
</ListBucketResult>
"#,
);
let client = Arc::new(s3::Monitor {
s3: S3Client::new_with(mock, MockCredentialsProvider, Region::UsEast1),
});
// test finding file & prefix
let file = config::Object {
prefix: "E".to_string(),
age: 30,
size: 1024,
};
assert_eq!(
check(client, "cubeta".to_string(), file),
"s3mon,bucket=cubeta,prefix=E error=0i,exist=0i,size_mismatch=0i",
);
}
#[test]
fn check_object_no_bucket() {
use rusoto_core::Region;
use rusoto_mock::{MockCredentialsProvider, MockRequestDispatcher};
use rusoto_s3::S3Client;
let mock = MockRequestDispatcher::with_status(404).with_body(
r#"<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>NoSuchBucket</Code>
<Message>The specified bucket does not exist</Message>
<RequestId>4442587FB7D0A2F9</RequestId>
</Error>"#,
);
let client = Arc::new(s3::Monitor {
s3: S3Client::new_with(mock, MockCredentialsProvider, Region::UsEast1),
});
// test finding file & prefix
let file = config::Object {
prefix: "E".to_string(),
age: 30,
size: 512,
};
assert_eq!(
check(client, "cubeta".to_string(), file),
"s3mon,bucket=cubeta,prefix=E error=1i,exist=0i,size_mismatch=0i",
);
}
}
| 31.618497 | 88 | 0.503382 |
74c5190bfcb80e6dd566f8fe9af27947df9880fa | 586 | js | JavaScript | lodash/chain.js | kitakitabauer/node-samples | fe587bdc3946d0515e2dfc111b7d59ba2282b44f | [
"MIT"
] | null | null | null | lodash/chain.js | kitakitabauer/node-samples | fe587bdc3946d0515e2dfc111b7d59ba2282b44f | [
"MIT"
] | null | null | null | lodash/chain.js | kitakitabauer/node-samples | fe587bdc3946d0515e2dfc111b7d59ba2282b44f | [
"MIT"
] | null | null | null | 'use strict';
console.log('--- chain ---');
const _ = require('lodash');
let users = [
{name: 'fred', age: 20, gender: 'male'},
{name: 'barney', age: 30, gender: 'female'},
{name: 'john', age: 40, gender: 'male'}
];
let ret1 = _.chain(users)
.filter(user => user.gender === 'male')
.map(user => user.name + ' is ' + user.age)
.take(2)
.value();
console.log(ret1);
// → [ 'fred is 20', 'john is 40' ]
let objects = {
b: {n: 1},
a: {n: 2},
c: {n: 3}
};
let ret2 = _.chain(objects)
.keys()
.sortBy()
.value();
console.log(ret2);
// → [ 'a', 'b', 'c' ]
| 17.235294 | 46 | 0.513652 |
85a0428ed36a9c08b697287c604b9fb77acfdaaa | 2,498 | js | JavaScript | src/sedan.js | CIS580/frogger-lbreck93 | 11c547360973dd6de78ae1faef06cfd9d9f86786 | [
"CC-BY-2.0"
] | null | null | null | src/sedan.js | CIS580/frogger-lbreck93 | 11c547360973dd6de78ae1faef06cfd9d9f86786 | [
"CC-BY-2.0"
] | null | null | null | src/sedan.js | CIS580/frogger-lbreck93 | 11c547360973dd6de78ae1faef06cfd9d9f86786 | [
"CC-BY-2.0"
] | null | null | null | "use strict";
const MS_PER_FRAME = 1000 / 8;
/**
* @module exports the Player class
*/
module.exports = exports = Sedan;
/**
* @constructor Player
* Creates a new player object
* @param {Postition} position object specifying an x and y
*/
function Sedan(position) {
this.state = "drive";
this.type = 'hostile';
this.row = position.row;
this.direction = Math.round(Math.random() * (1));
this.width = 64;
this.height = 64;
this.spritesheet = new Image();
this.ground = new Image();
this.ground.src = encodeURI('assets/tex_road.jpg');
this.x = 64*this.row;
if (this.direction == 0){
this.spritesheet.src = encodeURI('assets/TRBRYcars [Converted] sedan.png');
this.y = position.cavasHeight + 25;
this.resty = position.cavasHeight + 25;
}
else{
this.y = -50;
this.resty = -50;
this.spritesheet.src = encodeURI('assets/TRBRYcars [Converted] sedan-Reversed.png');
}
this.timer = 0;
this.frame = 0;
this.speed = Math.round(Math.random() * (2 - 1) + 1);
var self = this;
}
/**
* @function updates the player object
* {DOMHighResTimeStamp} time the elapsed time since the last frame
*/
Sedan.prototype.update = function (time, canvas) {
// console.log(this.row, this.x, this.y);
switch (this.direction) {
case 0:
if (this.y < 430)
{
this.y+=this.speed;
}
else{
this.y = -20;
}
break;
case 1:
if ((-25 - this.height) < this.y)
{
this.y-=this.speed;
}
else{
this.y = canvas.height + 25;
}
break;
}
};
/**
* @function renders the player into the provided context
* {DOMHighResTimeStamp} time the elapsed time since the last frame
* {CanvasRenderingContext2D} ctx the context to render into
*/
Sedan.prototype.render = function(time, ctx, canvas) {
//rendering too much i think.
ctx.strokeStyle = 'red';
ctx.strokeRect(this.x, this.y, this.width, this.height);
ctx.drawImage(this.ground,
this.row*64, 0, this.width, canvas.height);
ctx.drawImage(
// image
this.spritesheet,
// source rectangle
0, 0, this.spritesheet.width, this.spritesheet.height,
this.x, this.y, this.width, this.height
);
};
Sedan.prototype.reset = function(){
this.y = this.resety;
}; | 26.574468 | 96 | 0.573259 |
6603baf5b8b978adc0a8e2e869a837269faaf70e | 1,143 | css | CSS | style/input-text.css | raihan71/adabuku-onlineBookStore | 04a451c39bc5805974e8dbdada05edd03bad7b5f | [
"MIT"
] | 2 | 2017-09-29T09:21:12.000Z | 2018-01-23T14:37:57.000Z | style/input-text.css | raihan71/adabuku-onlineBookStore | 04a451c39bc5805974e8dbdada05edd03bad7b5f | [
"MIT"
] | null | null | null | style/input-text.css | raihan71/adabuku-onlineBookStore | 04a451c39bc5805974e8dbdada05edd03bad7b5f | [
"MIT"
] | null | null | null | .style-1 input[type="text"] {
width: 500px;
margin-bottom: 10px;
padding: 5px;
border: solid 1px gainsboro;
-webkit-transition: box-shadow 0.3s, border 0.3s;
-moz-transition: box-shadow 0.3s, border 0.3s;
-o-transition: box-shadow 0.3s, border 0.3s;
transition: box-shadow 0.3s, border 0.3s;
}
.style-1 input[type="text"]:focus, .style-1 input[type="text"].focus {
border: solid 1px #707070;
-webkit-box-shadow: 0 0 5px 1px #969696;
-moz-box-shadow: 0 0 5px 1px #969696;
box-shadow: 0 0 5px 1px #969696;
}
.input-list {
list-style: none;
display: inline;
width: auto;
position: relative;
margin-left: 5px;
}
.input {
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
box-sizing:border-box;
width:100%;
margin:0 0 .9rem;
padding:.6rem;
background:#fff;
border:1px solid #bbb;
box-shadow:inset 0 1px 3px rgba(0,0,0,.05);
border-radius:0;
outline:none;
resize:vertical;
transition:border-color .3s ease;
}
.input[disabled] {
border-color:#c8c8c8;
background-color:#f2f2f2;
box-shadow:none;
cursor:not-allowed
}
.input:focus {
border-color:#0c69d6
} | 20.781818 | 70 | 0.671916 |
827cad1caf9cfb53c91fb3b2f5a262a02193a039 | 230 | sql | SQL | kenny2automate/sql/v3.sql | T-taku/kenny2automate | 4f0e8895cbcd91a8179e1d7bd1c6908e0df52051 | [
"MIT"
] | 12 | 2018-03-06T15:31:50.000Z | 2020-08-25T05:27:26.000Z | kenny2automate/sql/v3.sql | T-taku/kenny2automate | 4f0e8895cbcd91a8179e1d7bd1c6908e0df52051 | [
"MIT"
] | 9 | 2018-03-07T08:20:43.000Z | 2019-05-06T06:37:57.000Z | kenny2automate/sql/v3.sql | T-taku/kenny2automate | 4f0e8895cbcd91a8179e1d7bd1c6908e0df52051 | [
"MIT"
] | 7 | 2018-04-03T04:33:38.000Z | 2020-08-11T15:31:36.000Z | CREATE TABLE IF NOT EXISTS guilds (
-- guild ID
guild_id integer PRIMARY KEY NOT NULL,
-- bad words
words_censor text,
-- disabled commands
guild_disabled_commands text,
-- disabled cogs
guild_disabled_cogs text
)
| 20.909091 | 40 | 0.734783 |
e7338a058afd54aa901e833ef5d39a01c56f3378 | 287 | js | JavaScript | tests/auto-observe-no-cache/script.js | army8735/pixiu | 22422044d8d9172018a8e2f5048e4201d68f17a0 | [
"MIT"
] | 1 | 2019-04-08T06:16:31.000Z | 2019-04-08T06:16:31.000Z | tests/auto-observe-no-cache/script.js | army8735/pixiu | 22422044d8d9172018a8e2f5048e4201d68f17a0 | [
"MIT"
] | 3 | 2019-03-22T01:26:14.000Z | 2019-04-22T08:35:44.000Z | tests/auto-observe-no-cache/script.js | army8735/pixiu | 22422044d8d9172018a8e2f5048e4201d68f17a0 | [
"MIT"
] | null | null | null | 'use strict';
let sels = ['#a', '#b'];
let index = 0;
pixiu.auto.observe(0, function(list, str) {
document.querySelector(sels[index++]).value = str;
});
document.querySelector('div').innerText = 0.2;
setTimeout(function() {
document.querySelector('div').innerText = 0.3;
}, 100);
| 20.5 | 52 | 0.655052 |
11e58204ddeed60779026f15576ebe1f384c0c78 | 1,052 | html | HTML | manuscript/page-249/body.html | marvindanig/the-kama-sutra-of-vatsyayana | 5356880ede1323494cf2ae5f87b24a9eb1f7dc8b | [
"CECILL-B"
] | 1 | 2019-03-27T16:54:31.000Z | 2019-03-27T16:54:31.000Z | manuscript/page-249/body.html | marvindanig/the-kama-sutra-of-vatsyayana | 5356880ede1323494cf2ae5f87b24a9eb1f7dc8b | [
"CECILL-B"
] | null | null | null | manuscript/page-249/body.html | marvindanig/the-kama-sutra-of-vatsyayana | 5356880ede1323494cf2ae5f87b24a9eb1f7dc8b | [
"CECILL-B"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p class="no-indent ">certain things with the values of which she may be unacquainted, and if she begins to dispute with him about the things or their value, he should not contradict her, but point out that he agrees with her in every way.</p><p>Thus ends the ways of making the acquaintance of the woman desired.</p><p class=" stretch-last-line">Now after a girl has become acquainted with the man as above described, and has manifested her love to him by the various outward signs; and by the motions of her body, the man should make every effort to gain her over. But as girls are not acquainted with sexual union, they should be treated with the greatest delicacy, and the man should proceed with considerable caution, though in the case of other women, accustomed to sexual intercourse, this is not necessary. When the intentions of the girl are known, and her bashfulness put aside, the man should begin to make use of her money, and an interchange of clothes, rings, and flowers</p></div> </div> | 1,052 | 1,052 | 0.779468 |
5f0b894da7f3a622d1743402f0b4794586fdab50 | 2,076 | ts | TypeScript | web/src/app/entry/job/job-info.component.ts | AKhodus/adcm | 98dbf22af3f1c6afa94505e9acaff0ac4088a602 | [
"Apache-2.0"
] | 16 | 2019-11-28T18:05:21.000Z | 2021-12-08T18:09:18.000Z | web/src/app/entry/job/job-info.component.ts | AKhodus/adcm | 98dbf22af3f1c6afa94505e9acaff0ac4088a602 | [
"Apache-2.0"
] | 1,127 | 2019-11-29T08:57:25.000Z | 2022-03-31T20:21:32.000Z | web/src/app/entry/job/job-info.component.ts | AKhodus/adcm | 98dbf22af3f1c6afa94505e9acaff0ac4088a602 | [
"Apache-2.0"
] | 10 | 2019-11-28T18:05:06.000Z | 2022-01-13T06:16:40.000Z | // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Component, Input } from '@angular/core';
import { JobStatus } from '@app/core/types';
import { ITimeInfo } from './log/log.component';
@Component({
selector: 'app-job-info',
styles: [
`
:host {
position: fixed;
right: 40px;
top: 120px;
}
.time-info,
.time-info div {
display: flex;
align-items: center;
}
.time-info div mat-icon {
margin-right: 6px;
}
.time-info div span {
margin-right: 30px;
}
.start_flag {
transform: rotate(30deg);
font-size: 20px;
margin-top: 8px;
}
.finish_flag {
transform: rotate(150deg);
font-size: 20px;
}
`,
],
template: `
<div class="time-info">
<div>
<mat-icon color="primary" class="start_flag">outlined_flag</mat-icon>
<span>{{ timeInfo?.start }}</span>
</div>
<div>
<mat-icon *ngIf="isRun" class="icon-locked running">autorenew</mat-icon>
<mat-icon *ngIf="!isRun" [class]="status">{{ Icon(status) }}</mat-icon>
<span>{{ timeInfo?.time }}</span>
</div>
<div *ngIf="timeInfo?.end">
<mat-icon color="primary" class="finish_flag">outlined_flag</mat-icon>
<span>{{ timeInfo?.end }}</span>
</div>
</div>
`,
})
export class JobInfoComponent {
@Input() timeInfo: ITimeInfo;
@Input() status: JobStatus;
Icon = (status: string): string => (status === 'aborted' ? 'block' : 'done_all');
get isRun(): boolean {
return this.status === 'running';
}
}
| 28.438356 | 83 | 0.589114 |
47864b2742619f12f0bbc587a53cf742345d3951 | 2,810 | html | HTML | templates/instrucciones.html | Francisco-Galindo/psychic-octo-lamp | 0a9cd476e2167285201990d7227dec6ba4057264 | [
"MIT"
] | null | null | null | templates/instrucciones.html | Francisco-Galindo/psychic-octo-lamp | 0a9cd476e2167285201990d7227dec6ba4057264 | [
"MIT"
] | null | null | null | templates/instrucciones.html | Francisco-Galindo/psychic-octo-lamp | 0a9cd476e2167285201990d7227dec6ba4057264 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="../statics/styles/instrucciones.css">
<link rel="shortcut icon" href="../statics/img/pulpito_p2.png" type="image/x-icon">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="justify-content-center mt-3">
<h1>Instrucciones</h1>
<h2>Antes de empezar</h2>
<p>Antes de emepzar la partida, se va a solicitar que elijas la cantidad
de personajes y el tipo del tablero en el que se va a jugar.</p>
<div style="text-align: center;">
<img src="../statics/img/pulpito1.jpg" width="30%" alt="">
<img src="../statics/img/vistaTablero.jpg" width="30%" alt="">
</div>
<h2>Dentro del juego</h2>
<p>Una vez dentro del juego van a haber hasta 4 pulpos más el pulpo
ignorancia dentro del tablero. El objetivo es responder la mayor
cantidad de preguntas correctas antes que los demás para poder llegar
al final del tablero.
El turno de cada jugador se inicia tirando el dado para que le salga una
pregunta de los seis temas que trae el juego:
<ol>
<li>Informatica</li>
<li>Geografia</li>
<li>Derecho</li>
<li>Historia</li>
<li>Literatura Iberoamericana</li>
<li>Biologia</li>
</ol>
<p>Tras esto van a salir las opciones de las respuestas de cada pregunta
para que el jugador elija la correcta. En caso de elegir la respuesta
equivocada sera la ignorancia la que avance. En caso de que la ignorancia
llegue al final antes que los demas, todos los jugadores pierden.</p>
<div style="text-align: center; margin-right: 20%;">
<img src="../statics/img/pulpito_ignorancia.png" style="padding: 20px; margin-left: 20%" alt="">
<p style="margin-left: 20.5%"><small>Imagen 1. Ignorancia</small></p>
</div>
<div class="mb-3" style="text-align: left;">
<a href="../index.html">
<button tabindex="1">
Regresar
</button>
</a>
</div>
</div>
</div>
</body>
</html> | 45.322581 | 214 | 0.567972 |
7e45cf5251f8ea19f7f24f16a2e592bb772bd797 | 1,552 | swift | Swift | LeetCode.swift/Solution/098_ValidateBinarySearchTree.swift | yeziahehe/LeetCode.swift | f8db7799fbbba0b7930881d1cdaa3c78a0f9cd92 | [
"MIT"
] | 11 | 2017-10-09T10:00:50.000Z | 2021-12-01T01:55:33.000Z | LeetCode.swift/Solution/098_ValidateBinarySearchTree.swift | JustJooney/LeetCode.swift | f8db7799fbbba0b7930881d1cdaa3c78a0f9cd92 | [
"MIT"
] | null | null | null | LeetCode.swift/Solution/098_ValidateBinarySearchTree.swift | JustJooney/LeetCode.swift | f8db7799fbbba0b7930881d1cdaa3c78a0f9cd92 | [
"MIT"
] | 4 | 2019-03-04T11:17:01.000Z | 2022-01-04T19:55:10.000Z | //
// 098_ValidateBinarySearchTree.swift
// LeetCode.swift
//
// Created by 叶帆 on 2020/8/25.
// Copyright © 2020 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
/**
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
import Foundation
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class Solution {
func isValidBST(_ root: TreeNode?) -> Bool {
return isValidBST(root, nil, nil)
}
/* 限定以 root 为根的子树节点必须满足 max.val > root.val > min.val */
func isValidBST(_ root: TreeNode?, _ min: TreeNode?, _ max: TreeNode?) -> Bool {
// base case
if root == nil {
return true
}
// 若 root.val 不符合 max 和 min 的限制,说明不是合法 BST
if min != nil && root!.val <= min!.val {
return false
}
if max != nil && root!.val >= max!.val {
return false
}
// 限定左子树的最大值是 root.val,右子树的最小值是 root.val
return isValidBST(root?.left, min, root) && isValidBST(root?.right, root, max)
}
}
| 20.693333 | 91 | 0.583119 |
350435931ee29ee2b61c4923720a4d7356eef2f1 | 238 | kt | Kotlin | app/src/main/java/com/zachtib/barcodewallet/ui/model/Resource.kt | zachtib/BarcodeWallet | 5fd5af7275df6c17fef4a38ab328dd1a4ffa4ddf | [
"MIT"
] | null | null | null | app/src/main/java/com/zachtib/barcodewallet/ui/model/Resource.kt | zachtib/BarcodeWallet | 5fd5af7275df6c17fef4a38ab328dd1a4ffa4ddf | [
"MIT"
] | null | null | null | app/src/main/java/com/zachtib/barcodewallet/ui/model/Resource.kt | zachtib/BarcodeWallet | 5fd5af7275df6c17fef4a38ab328dd1a4ffa4ddf | [
"MIT"
] | null | null | null | package com.zachtib.barcodewallet.ui.model
sealed class Resource<out T> {
object Loading : Resource<Nothing>()
data class Content<T>(val data: T) : Resource<T>()
data class Error<T>(val throwable: Throwable) : Resource<T>()
} | 34 | 65 | 0.701681 |
f19221b610b7b13308e193c60285036a8578fc02 | 298 | rb | Ruby | test/controllers/dataset_items_controller_test.rb | unipept/unipept | f8f7fc62fcf2f17dcbeabfe992de989eacaaec35 | [
"MIT"
] | 15 | 2015-10-27T19:45:01.000Z | 2021-05-03T08:52:21.000Z | test/controllers/dataset_items_controller_test.rb | unipept/unipept | f8f7fc62fcf2f17dcbeabfe992de989eacaaec35 | [
"MIT"
] | 1,106 | 2017-02-22T16:53:39.000Z | 2022-03-30T21:56:46.000Z | test/controllers/dataset_items_controller_test.rb | unipept/unipept | f8f7fc62fcf2f17dcbeabfe992de989eacaaec35 | [
"MIT"
] | 3 | 2018-11-29T01:11:26.000Z | 2020-08-14T01:24:15.000Z | require 'test_helper'
class DatasetItemsControllerTest < ActionController::TestCase
test 'should show datasetitem' do
datasetitem1 = dataset_items(:datasetitem1)
get :show, params: { 'id' => '1' }
assert_response :success
assert_equal datasetitem1.data, @response.body
end
end
| 27.090909 | 61 | 0.741611 |
e72f5fb36f232ad7f10dd2a694c78236b9fa7770 | 3,211 | js | JavaScript | src/stories/components/data-display/avatar/example.stories.js | qasir-id/qiui | d2abfe69c904e7218f26311b066affd73bb6539c | [
"MIT"
] | null | null | null | src/stories/components/data-display/avatar/example.stories.js | qasir-id/qiui | d2abfe69c904e7218f26311b066affd73bb6539c | [
"MIT"
] | null | null | null | src/stories/components/data-display/avatar/example.stories.js | qasir-id/qiui | d2abfe69c904e7218f26311b066affd73bb6539c | [
"MIT"
] | null | null | null | // Vendors
import React from 'react';
// Material UI
import { makeStyles } from '@material-ui/core/styles';
// Components
import AvatarImage from './avatar-image';
import AvatarImageDocs from './avatar-image/docs.mdx';
import AvatarLetter from './avatar-letter';
import AvatarLetterDocs from './avatar-letter/docs.mdx';
import AvatarSize from './avatar-size';
import AvatarSizeDocs from './avatar-size/docs.mdx';
import AvatarIcon from './avatar-icon';
import AvatarIconDocs from './avatar-icon/docs.mdx';
import AvatarVariants from './avatar-variants';
import AvatarVariantsDocs from './avatar-variants/docs.mdx';
import AvatarFallbacks from './avatar-fallbacks';
import AvatarFallbacksDocs from './avatar-fallbacks/docs.mdx';
import AvatarGrouped from './avatar-grouped';
import AvatarGroupedDocs from './avatar-grouped/docs.mdx';
import AvatarWithBadge from './avatar-with-badge';
import AvatarWithBadgeDocs from './avatar-with-badge/docs.mdx';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
margin: theme.spacing(1),
},
},
}));
const Wrapper = ({ children }) => {
const classes = useStyles();
return <div className={classes.root}>{children}</div>;
};
export default {
title: 'Components/Data Display/Avatar/Example',
parameters: {
design: { disabled: true },
options: { showPanel: false },
},
};
export const image = () => (
<Wrapper>
<AvatarImage />
</Wrapper>
);
image.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarImageDocs,
},
},
};
export const letter = () => (
<Wrapper>
<AvatarLetter />
</Wrapper>
);
letter.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarLetterDocs,
},
},
};
export const size = () => (
<Wrapper>
<AvatarSize />
</Wrapper>
);
size.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarSizeDocs,
},
},
};
export const icon = () => (
<Wrapper>
<AvatarIcon />
</Wrapper>
);
icon.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarIconDocs,
},
},
};
export const variants = () => (
<Wrapper>
<AvatarVariants />
</Wrapper>
);
variants.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarVariantsDocs,
},
},
};
export const fallbacks = () => (
<Wrapper>
<AvatarFallbacks />
</Wrapper>
);
fallbacks.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarFallbacksDocs,
},
},
};
export const grouped = () => (
<Wrapper>
<AvatarGrouped />
</Wrapper>
);
grouped.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarGroupedDocs,
},
},
};
export const withBadge = () => (
<Wrapper>
<AvatarWithBadge />
</Wrapper>
);
withBadge.story = {
parameters: {
status: 'Stable', // Stable | Development | Deprecated
docs: {
page: AvatarWithBadgeDocs,
},
},
};
| 19.579268 | 63 | 0.62317 |
b11d38aa50fe6994622b91f5a98c5944d0af9204 | 3,904 | css | CSS | Public/Home/css/cstfont/iconfont.css | qq372915965/sjshop | 139245362c969af29201b028e762f1f6cad6073a | [
"BSD-2-Clause"
] | null | null | null | Public/Home/css/cstfont/iconfont.css | qq372915965/sjshop | 139245362c969af29201b028e762f1f6cad6073a | [
"BSD-2-Clause"
] | null | null | null | Public/Home/css/cstfont/iconfont.css | qq372915965/sjshop | 139245362c969af29201b028e762f1f6cad6073a | [
"BSD-2-Clause"
] | null | null | null |
@font-face {font-family: "iconfont";
src: url('iconfont.eot?t=1526267822022'); /* IE9*/
src: url('iconfont.eot?t=1526267822022#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('data:application/x-font-woff;charset=utf-8;base64,d09GRgABAAAAAAhwAAsAAAAADOAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAADMAAABCsP6z7U9TLzIAAAE8AAAARAAAAFZW7kqnY21hcAAAAYAAAACpAAACLnVKPnFnbHlmAAACLAAAA/kAAAWYs0pUo2hlYWQAAAYoAAAALwAAADYRXYUYaGhlYQAABlgAAAAcAAAAJAfeA4xobXR4AAAGdAAAABQAAAAsK+kAAGxvY2EAAAaIAAAAGAAAABgH1AkSbWF4cAAABqAAAAAfAAAAIAEaAGNuYW1lAAAGwAAAAUUAAAJtPlT+fXBvc3QAAAgIAAAAZgAAAI3Rily1eJxjYGRgYOBikGPQYWB0cfMJYeBgYGGAAJAMY05meiJQDMoDyrGAaQ4gZoOIAgCKIwNPAHicY2Bk/sc4gYGVgYOpk+kMAwNDP4RmfM1gxMjBwMDEwMrMgBUEpLmmMDgwVLzYztzwv4EhhrmBoQEozAiSAwAzCw0reJzFksENwjAMRb9JUwLiQCXEFGxUqV2CQ0dgDE6s0I3sblF+4l6COIOjF8k/ih19B0AEEMiNNIC8IMjxpCpFDzgWvcGd+QVnKg0mDRo1aWdivY3LvK48rdVhUz9DWKVe16IGHNBiz347dohIFNsv938U8r/WdZzK/tgyTgPTBp+owclT1OjQR2hy6Ci0c+gtTJxcx3qHfsMGJ/8CG538O5bZQXoDelUwWAAAAHicdVNLTNxWFH33vWd7frZn7PFnPNjzgzHJFNOOh3GUBqO2kwRQ0lDSb1bpKggpLLLJJhIjQaRKFJHSZUsXqFKRWEeoKqM2m6ossmk2ZJOqgk1Vqd11Qfj0zUwhdMHT8/H19fW9553riziEjn4nm8REKupHb6AGmkAI+AoUJWxDwa15uAJagdOMtETcklsQSkWPDINR5NN6tV4rG7zAyyCBA36hWnc97MJQLcRvQlW3ATJZ66bS16OQRxAzXefh4TheBS1X6pHDgcOx10bS1bwauZ9QlIyifB7hOS6CMZUluGvoUS4a4w+/5WRL28ydwzlIZFzr2idiPqt8+lltxu4zogDNJqjZvPTdSMpKsf3A0lUlIyTFiGmJpd403N+Nm2rCLu8gtgg76xPyIxlBcWSgEjunBIIDRgiBB8QDlxnsUQJyyo9Ra5/j9ltdXN2mdHu1i41bGN9qdJCEJxGt/f2tk5DVbWwdxzBkHCjj8DP5gXEYQm+h6+hDxsKDIhNR8IW0HoQwFBKHCIyBBExXbDCvX2f+EQipWy+TMzi7EnQbgufN4fcamcEYQFyOJzktd+H1ekEigh+TVUGJWRgAixaAqSciuYrCA0grrT2O22ttvqT05eb6LqW76+s7lO58L6uqo6p4wjB1rXKDyjrQEnZ8WwSzUJWNMKbYET1RMSmVJMiCl1PiuWq+qOaqQE8Stvb2N+jO+nHeZVBtlW2EO02p4PVOP1DfmR2YXaN0bbaLM8uELM908IMT5+waPn/sZdjt9ancpbOzq8w+fnVmpWF8e2zsNu7gmVWP0HEIw3b57vmWSBKZ6BxjUHZZoXKN9TKoVw1GQE+3+8wTNmtpB1dDzKYNJ98dbUw7bE03Rr96ZV4fn5uq16fmvuzeUuDY05evfn318rTtnDLxH+zl8vydILgzv8xCT3jgp3gF6W2dQfC1kta+SkOlIb99ub4R+Pjp3L2FxUV/cWHh3sOLsw8u4pUX5dCdm3PD8ovnzzt5jpoU4SazoghxhRQIbmAEBjC5D//ymt7kr16ToIO7A03v/Wdeuyx0NPiFRJCGkGro9QBCYGcX2OwNsj+fifHNY9FJwN+434zQ5MFvUCv/SUQj2gcbX0QhBls4LfP5zMEWly//gz0twr3K+xN+gq6wvHpHzS7ofrWtcHtg6gETtDNJbLyC/7ZrlP+3PdIeNP7tmJbIKqqV7NUSoqaXiuGUN/loXFUhrmaymdi1pYkBX+o9n7R6FNNU00oqKUkpMW4rgp3Aqt6T0QWBwtKlC84ly9EljaeYRpUbA5OPP9bTPaKlJCAW+2jj5mA/+4aPU9JeAs/H41JK6veS74yKukgjciKlIPQvOOIROgAAAHicY2BkYGAAYsdYxq3x/DZfGbhZGEDgurzCOgT9v4GFgdkeyOVgYAKJAgDvzghcAHicY2BkYGBu+N/AEMPCAAJAkpEBFXADAEcRAnR4nGNhYGBgfsnAwMJAGAMAJ6MBFQAAAAAAdgC4AT4BbAGuAfICFgIwAlwCzHicY2BkYGDgZghnYGUAASYg5gJCBob/YD4DABJlAX4AeJxlj01OwzAQhV/6B6QSqqhgh+QFYgEo/RGrblhUavdddN+mTpsqiSPHrdQDcB6OwAk4AtyAO/BIJ5s2lsffvHljTwDc4Acejt8t95E9XDI7cg0XuBeuU38QbpBfhJto41W4Rf1N2MczpsJtdGF5g9e4YvaEd2EPHXwI13CNT+E69S/hBvlbuIk7/Aq30PHqwj7mXle4jUcv9sdWL5xeqeVBxaHJIpM5v4KZXu+Sha3S6pxrW8QmU4OgX0lTnWlb3VPs10PnIhVZk6oJqzpJjMqt2erQBRvn8lGvF4kehCblWGP+tsYCjnEFhSUOjDFCGGSIyujoO1Vm9K+xQ8Jee1Y9zed0WxTU/3OFAQL0z1xTurLSeTpPgT1fG1J1dCtuy56UNJFezUkSskJe1rZUQuoBNmVXjhF6XNGJPyhnSP8ACVpuyAAAAHicbYrLDkAwFAXvQRW18SEWPulWPSqhiaiUrye1NYvJ5ORQQh8V/aOQIEUGgRwSBUpUUKgJodjZWKddkJq36Z69iIOK5v6w5/BdzDBm+6q75nI+WF4su+ktz5sw/FYe3RI9L6IeVwAA') format('woff'),
url('iconfont.ttf?t=1526267822022') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/
url('iconfont.svg?t=1526267822022#iconfont') format('svg'); /* iOS 4.1- */
}
.iconfont {
font-family:"iconfont" !important;
font-size:16px;
font-style:normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-radiobox:before { content: "\e75b"; }
.icon-bangzhu:before { content: "\e603"; }
.icon-radio:before { content: "\e75e"; }
.icon-radioactive:before { content: "\e75f"; }
.icon-radiodef:before { content: "\e608"; }
.icon-rmb1:before { content: "\e611"; }
.icon-youxiajiaogouxuan:before { content: "\e8b7"; }
.icon-dagou:before { content: "\e605"; }
.icon-dagou-:before { content: "\e701"; }
| 108.444444 | 2,955 | 0.892674 |
df84944a377bbc3f605c43ea7cd0a26ba93682d7 | 510 | ts | TypeScript | packages/hm-utils/lib/requestFactory.d.ts | Foreinyel/hemyn-common | 688201aaa667c25ac81a7a8dbdcff7ba9756173b | [
"MIT"
] | null | null | null | packages/hm-utils/lib/requestFactory.d.ts | Foreinyel/hemyn-common | 688201aaa667c25ac81a7a8dbdcff7ba9756173b | [
"MIT"
] | null | null | null | packages/hm-utils/lib/requestFactory.d.ts | Foreinyel/hemyn-common | 688201aaa667c25ac81a7a8dbdcff7ba9756173b | [
"MIT"
] | null | null | null | export interface RequestOptions {
requestInterceptors?: (config: any) => void;
timeout?: number;
isOk?: (res: any) => boolean;
getErr?: (res: any) => string;
getData?: (res: any) => any;
on401?: () => void;
statusCodeKey?: string;
}
declare const _default: (options: RequestOptions) => {
rPost: <T, U>(path: string, data: T) => Promise<U>;
rGet: <U_1>(path: string) => Promise<U_1>;
rPut: <T_1, U_2>(path: string, data: T_1) => Promise<U_2>;
};
export default _default;
| 31.875 | 62 | 0.605882 |
8567633d8fb4308a9d3d449ca176462c40a15304 | 304 | js | JavaScript | react-complete-guide/practice-one/src/UserOutput/UserOutput.js | tawillia/React_projects | 7ced1556708c0aa9cc53225ed9abe954b0db5748 | [
"MIT"
] | null | null | null | react-complete-guide/practice-one/src/UserOutput/UserOutput.js | tawillia/React_projects | 7ced1556708c0aa9cc53225ed9abe954b0db5748 | [
"MIT"
] | null | null | null | react-complete-guide/practice-one/src/UserOutput/UserOutput.js | tawillia/React_projects | 7ced1556708c0aa9cc53225ed9abe954b0db5748 | [
"MIT"
] | null | null | null | import React from 'react';
import './UserOutput.css';
const userOutput = props => {
return (
<div className='UserOutput'>
<p className='UserName'>Username: {props.userName}</p>
<p>Input a new usename in the input box to change current username!</p>
</div>
);
};
export default userOutput;
| 20.266667 | 74 | 0.680921 |
124d988c723f03660a4b5c632487851c14bf20e6 | 24,011 | h | C | include/oHpi.h | openhpi2/openhpi_apr25 | 720d4043124ac44d17715db4ffb735c623c08e38 | [
"BSD-3-Clause"
] | 5 | 2018-12-18T01:32:53.000Z | 2021-11-15T10:41:48.000Z | include/oHpi.h | openhpi2/openhpi_apr25 | 720d4043124ac44d17715db4ffb735c623c08e38 | [
"BSD-3-Clause"
] | 34 | 2018-05-11T21:31:33.000Z | 2021-01-12T07:13:46.000Z | include/oHpi.h | openhpi2/openhpi_apr25 | 720d4043124ac44d17715db4ffb735c623c08e38 | [
"BSD-3-Clause"
] | 8 | 2018-08-27T22:48:44.000Z | 2022-03-15T03:49:55.000Z | /* -*- linux-c -*-
*
* (C) Copright IBM Corp 2004-2006
* (C) Copyright Pigeon Point Systems. 2010-2011
* (C) Copyright Nokia Siemens Networks 2010
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This
* file and program are licensed under a BSD style license. See
* the Copying file included with the OpenHPI distribution for
* full licensing terms.
*
* Authors:
* Renier Morales <renier@openhpi.org>
* Anton Pak <anton.pak@pigeonpoint.com>
* Ulrich Kleber <ulikleber@users.sourceforge.net>
* Michael Thompson <michael.thompson@pentair.com>
*/
#ifndef __OHPI_H
#define __OHPI_H
#include <stdlib.h>
#include <SaHpi.h>
#include <glib.h>
#define OH_DEFAULT_DOMAIN_ID 0
#define OPENHPI_DEFAULT_DAEMON_PORT 4743
#define MAX_PLUGIN_NAME_LENGTH 32
#define OH_SAHPI_INTERFACE_VERSION_MIN_SUPPORTED (SaHpiVersionT)0x020101 /* B.01.01 */
#define OH_SAHPI_INTERFACE_VERSION_MAX_SUPPORTED SAHPI_INTERFACE_VERSION
#define OH_PATH_PARAM_MAX_LENGTH 2048
#ifdef __cplusplus
extern "C" {
#endif
typedef SaHpiUint32T oHpiHandlerIdT;
typedef struct {
oHpiHandlerIdT id;
SaHpiUint8T plugin_name[MAX_PLUGIN_NAME_LENGTH];
SaHpiEntityPathT entity_root;
SaHpiInt32T load_failed;
} oHpiHandlerInfoT;
typedef struct {
SaHpiDomainIdT id;
SaHpiTextBufferT host;
SaHpiUint16T port;
SaHpiEntityPathT entity_root;
} oHpiDomainEntryT;
typedef enum {
OHPI_ON_EP = 1, // Not used now
OHPI_LOG_ON_SEV,
OHPI_EVT_QUEUE_LIMIT,
OHPI_DEL_SIZE_LIMIT,
OHPI_DEL_SAVE,
OHPI_DAT_SIZE_LIMIT,
OHPI_DAT_USER_LIMIT,
OHPI_DAT_SAVE,
//OHPI_DEBUG,
//OHPI_DEBUG_TRACE,
//OHPI_DEBUG_LOCK,
OHPI_PATH,
OHPI_VARPATH,
OHPI_CONF
} oHpiGlobalParamTypeT;
typedef union {
SaHpiEntityPathT OnEP; /* Not used now */
/* Log events of severity equal to ore more critical than this */
SaHpiSeverityT LogOnSev;
SaHpiUint32T EvtQueueLimit; /* Max events # allowed in session queue */
SaHpiUint32T DelSizeLimit; /* Maximum size of domain event log */
SaHpiBoolT DelSave; /* True if domain event log is to be saved to disk */
SaHpiUint32T DatSizeLimit; /* Max alarms allowed in alarm table */
SaHpiUint32T DatUserLimit; /* Max number of user alarms allowed */
SaHpiBoolT DatSave; /* True if domain alarm table is to be saved to disk */
//unsigned char Debug; /* 1 = YES, 0 = NO */
//unsigned char DebugTrace; /* !0 = YES, 0 = NO */
//unsigned char DebugLock; /* !0 = YES, 0 = NO */
SaHpiUint8T Path[OH_PATH_PARAM_MAX_LENGTH]; /* Dir path to openhpi plugins */
SaHpiUint8T VarPath[OH_PATH_PARAM_MAX_LENGTH]; /* Dir path for openhpi data */
SaHpiUint8T Conf[OH_PATH_PARAM_MAX_LENGTH]; /* File path of openhpi configuration */
} oHpiGlobalParamUnionT;
typedef struct {
oHpiGlobalParamTypeT Type;
oHpiGlobalParamUnionT u;
} oHpiGlobalParamT;
/***************************************************************************
**
** Name: oHpiVersionGet()
**
** Description:
** This function returns the version of the Base Library.
**
** Remarks:
** This is a Base Library level function.
** The SaHpiUint64T version consists of 3 16-bit blocks: MAJOR, MINOR, and PATCH.
** MAJOR occupies bytes[7:6].
** MINOR occupies bytes[5:4].
** PATCH occupies bytes[3:2].
** Bytes[1:0] are zeroed.
** For example version 2.17.0 is returned as 0x0002001100000000.
**
***************************************************************************/
SaHpiUint64T SAHPI_API oHpiVersionGet(void);
/***************************************************************************
**
** Name: oHpiHandlerCreate()
**
** Description:
** This function creates a new handler (instance of a plugin) on the
** OpenHPI daemon side.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** config - [in] Hash table. Holds configuration information used by the handler.
** The table key is a configuration parameter name (as a string).
** The table item is the configuration parameter value (as a string).
** id - [out] Unique (for the targeted OpenHPI daemon) id associated
** with the created handler.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_PARAMS is returned when the:
** * config is is passed in as NULL.
** * id is is passed in as NULL.
** SA_ERR_HPI_INTERNAL_ERROR is returned if a handler is created,
** but failed to open.
** SA_ERR_HPI_ERROR is returned:
** * when config doesn't have "plugin" parameter
** * in other error cases.
**
** Remarks:
** This is a Daemon level function.
** The config table must have an entry for "plugin" in order to know for which
** plugin the handler is being created.
** If the handler failed to open the oHpiHandlerRetry can be used to retry
** opening the handler.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiHandlerCreate (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN GHashTable *config,
SAHPI_OUT oHpiHandlerIdT *id );
/***************************************************************************
**
** Name: oHpiHandlerDestroy()
**
** Description:
** This function destroys the specified handler on the OpenHPI daemon side.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** id - [in] Unique (for the targeted OpenHPI daemon) id associated
** with the handler. Reserved id values:
** * SAHPI_FIRST_ENTRY Get first handler.
** * SAHPI_LAST_ENTRY Reserved as delimiter for end of list. Not a valid
** handler identifier.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_ERROR is returned:
** * when the daemon failed to destroy the handler.
** * in other error cases.
**
** Remarks:
** This is Daemon level function.
** TODO: Improve the current set of error codes for the function.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiHandlerDestroy (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN oHpiHandlerIdT id );
/***************************************************************************
**
** Name: oHpiHandlerInfo()
**
** Description:
** This function is used for requesting information about specified handler.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** id - [in] Unique (for the targeted OpenHPI daemon) id associated
** with the handler. Reserved id values:
** * SAHPI_FIRST_ENTRY Get first handler.
** * SAHPI_LAST_ENTRY Reserved as delimiter for end of list. Not a valid
** handler identifier.
** info - [out] Pointer to struct to hold the handler information.
** conf_params - [out] Pointer to to pre-allocated hash-table to hold
** the handler's configuration parameters.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_PARAMS is returned when the:
** * info is passed in as NULL
** * conf_params is passed in as NULL
** * id is passed in as SAHPI_FIRST_ENTRY
** SA_ERR_HPI_NOT_PRESENT is returned when the specified the targeted
** OpenHPI daemon has no handler with the specified id.
**
** Remarks:
** This is Daemon level function.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiHandlerInfo (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN oHpiHandlerIdT id,
SAHPI_OUT oHpiHandlerInfoT *info,
SAHPI_INOUT GHashTable *conf_params );
/***************************************************************************
**
** Name: oHpiHandlerGetNext()
**
** Description:
** This function is used for iterating through all loaded handlers on the
** targeted OpenHPI daemon.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** id - [in] Unique (for the targeted OpenHPI daemon) id associated
** with the handler. Reserved id values:
** * SAHPI_FIRST_ENTRY Get first handler.
** * SAHPI_LAST_ENTRY Reserved as delimiter for end of list. Not a valid
** handler identifier.
** next_id - [out] Pointer to the location to store the id of the next handler.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_NOT_PRESENT is returned when the:
** * handler identified by id is not present.
* * there is no next handler after the specified one.
** * id is SAHPI_FIRST_ENTRY and there are no loaded handlers in the targeted
** OpenHPI daemon.
** SA_ERR_HPI_INVALID_PARAMS is returned if the:
** * next_id pointer is passed in as NULL.
** * id is an invalid reserved value such as SAHPI_LAST_ENTRY.
**
** Remarks:
** This is a Daemon level function.
** If the id parameter is set to SAHPI_FIRST_ENTRY, the function sets
** the next_id parameter to the id of the first handler for the targeted
** OpenHPI daemon. To retrieve an entire list of ids for the targeted
** OpenHPI daemon call this function first with an id of SAHPI_FIRST_ENTRY,
** and then use the returned next_id the next call.
** Proceed until the next_id returned is SAHPI_LAST_ENTRY or
** the call returned SA_ERR_HPI_NOT_PRESENT.
** TODO: Implement a check that the id is and invalid reserved value.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiHandlerGetNext (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN oHpiHandlerIdT id,
SAHPI_OUT oHpiHandlerIdT *next_id );
/***************************************************************************
**
** Name: oHpiHandlerFind()
**
** Description:
** This function is used for requesting a handler id that manages the specified
** resource.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** rid - [in] Resource id.
** id - [out] Pointer to the location to store the handler id.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_RESOURCE is returned if resource id does not match
** any resource in the targeted OpenHPI daemon.
**
** Remarks:
** This is Daemon level function.
** Every resource that the OpenHPI daemon exposes is created and managed by
** some handler. This function allows to know the id of the handler
** responsible for the specified resource.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiHandlerFind (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN SaHpiResourceIdT rid,
SAHPI_OUT oHpiHandlerIdT *id );
/***************************************************************************
**
** Name: oHpiHandlerRetry()
**
** Description:
** This function is used for retrying initialization of the failed handler.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** id - [in] Unique (for the targeted OpenHPI daemon) id associated
** with the handler. Reserved id values:
** * SAHPI_FIRST_ENTRY Get first handler.
** * SAHPI_LAST_ENTRY Reserved as delimiter for end of list. Not a valid
** handler identifier.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_OK is returned if the handler was already successfully initialized.
** SA_ERR_HPI_NOT_PRESENT is returned when the targeted OpenHPI daemon
** has no handler with the specified id.
**
** Remarks:
** This is Daemon level function.
** It is possible that the handler has failed to initialize.
** For example because of a connection failure to the managed entity.
** This function allows an HPI User to retry the handler initialization process.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiHandlerRetry (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN oHpiHandlerIdT id );
/***************************************************************************
**
** Name: oHpiGlobalParamGet()
**
** Description:
** This function is used for requesting global configuration parameters
** from the targeted OpenHPI daemon.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** param - [in/out] Pointer to a Parameter data structure into which the
** requested parameter is placed. The requested parameter type is
** passed in via param->Type.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_PARAMS is returned if param is passed in as NULL.
** SA_ERR_HPI_UNKNOWN is returned if param->Type is unknown to the
** targeted OpenHPI daemon.
**
** Remarks:
** This is Daemon level function.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiGlobalParamGet (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_INOUT oHpiGlobalParamT *param );
/***************************************************************************
**
** Name: oHpiGlobalParamSet()
**
** Description:
** This function is used for setting the value of the specified global
** configuration parameters for the targeted OpenHPI daemon.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** param - [in] Pointer to a Parameter data structure holding the
** data to be set. The requested parameter type is passed in via
** param->Type.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_PARAMS is returned if param is passed in as NULL.
** SA_ERR_HPI_ERROR is returned:
** * when the param->Type is unknown to the targeted OpenHPI daemon.
** * in other error cases
**
** Remarks:
** This is Daemon level function.
** TODO: Improve the current set of error codes for the function.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiGlobalParamSet (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN oHpiGlobalParamT *param );
/***************************************************************************
**
** Name: oHpiInjectEvent()
**
** Description:
** This function is used to inject an HPI event into the targeted handler as if
** it originated from the handler.
** This call will set the event.Source, rpte.ResourceId, rpte.ResourceEntity
** so that the caller knows what the final assigned values were.
** For rpte.ResourceEntity, the entity_root configuration parameter for the plugin
** is used to complete it. In addition, for each rdr in rdr, a Num, RecordId,
** and Entity will be assigned. This will also be reflected in the passed rdr
** list so that the caller can know what the assigned values were.
**
** Parameters:
** sid - [in] Identifier for a session context previously obtained using
** saHpiSessionOpen().
** id - [in] Unique (for the targeted OpenHPI daemon) id associated
** with the handler for which the event will be injected.
** event - [in] pointer to the event to be injected.
** rpte - [in] pointer to the resource to be injected.
** rdr - [in] pointer to the list of RDRs to be injected along with rpte
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_SESSION is returned if sid is null.
** SA_ERR_HPI_INVALID_PARAMS is returned if
** id is null.
** event, rpte, or rdr pointer are passed in as NULL
**
** Remarks:
** This is Daemon level function.
** Currently only the simulator plug-in supports this function.
** id and event are required parameters. rpte is only required if the event
** is of RESOURCE type or HOTSWAP type. rdr is an optional argument in all
** cases and can be NULL. If @rdrs is passed, it will be copied. It is the
** responsibility of the caller to clean up the RDRs list once it is used here.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiInjectEvent (
SAHPI_IN SaHpiSessionIdT sid,
SAHPI_IN oHpiHandlerIdT id,
SAHPI_IN SaHpiEventT *event,
SAHPI_IN SaHpiRptEntryT *rpte,
SAHPI_IN SaHpiRdrT *rdr);
/***************************************************************************
**
** Name: oHpiDomainAdd()
**
** Description:
** This function informs the Base Library about the existence of an HPI domain
** and returns a Unique Domain Id that Base Library associates with the domain.
** In other words the function adds a new entry in Base Library known domain
** table.
**
** Parameters:
** host - [in] The hostname of the domain host.
** port - [in] The port number on the domain host.
** entity_root - [in] This entity_root will be added to all entity paths
** exposed in the domain.
** domain_id - [out] Unique Domain Id associated with the new domain
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_PARAMS is returned if the host, port, or entity_root
** is passed in as NULL.
** SA_ERR_HPI_INVALID_DATA is returned if the host is not
** SAHPI_TL_TYPE_BCDPLUS, SAHPI_TL_TYPE_ASCII6, or SAHPI_TL_TYPE_TEXT.
** SA_ERR_HPI_OUT_OF_SPACE is returned if the domain cannot be added.
**
** Remarks:
** This is Base Library level function.
** It only informs Base Library about existence of HPI service with the
** specified connectivity parameters.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiDomainAdd (
SAHPI_IN const SaHpiTextBufferT *host,
SAHPI_IN SaHpiUint16T port,
SAHPI_IN const SaHpiEntityPathT *entity_root,
SAHPI_OUT SaHpiDomainIdT *domain_id );
/***************************************************************************
**
** Name: oHpiDomainAddById()
**
** Description:
** This function informs the Base Library about the existence of an HPI domain.
** The function allows an HPI User to specify a Unique Domain Id that Base Library
** associates with the domain.
** In other words the function adds new entry in the Base Library known domain
** table.
**
** Parameters:
** host - [in] The hostname of the domain host.
** port - [in] The port number on the domain host.
** entity_root - [in] This entity_root will be added to all entity paths
** exposed in the domain.
** domain_id - [in] Unique Domain Id that User wants to be associated with
** the new domain.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_INVALID_PARAMS is returned if the host, port, or entity_root
** is passed in as NULL.
** SA_ERR_HPI_INVALID_DATA is returned if the host is not
** SAHPI_TL_TYPE_BCDPLUS, SAHPI_TL_TYPE_ASCII6, or SAHPI_TL_TYPE_TEXT.
** SA_ERR_HPI_DUPLICATE is returned if the specified domain_id is already
** in use.
** SA_ERR_HPI_OUT_OF_SPACE is returned if the domain cannot be added.
**
** Remarks:
** This is Base Library level function.
** It only informs Base Library about existence of HPI service with the
** specified connectivity parameters.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiDomainAddById (
SAHPI_IN SaHpiDomainIdT domain_id,
SAHPI_IN const SaHpiTextBufferT *host,
SAHPI_IN SaHpiUint16T port,
SAHPI_IN const SaHpiEntityPathT *entity_root );
/***************************************************************************
**
** Name: oHpiDomainEntryGet()
**
** Description:
** This function retrieves resource information for the specified entry of the
** Base Library known domain table. This function allows an HPI User to read
** the table entry-by-entry.
**
** Parameters:
** EntryId - [in] Identifier of the domain entry to retrieve. Reserved EntryId
** values:
** * SAHPI_FIRST_ENTRY Get first entry.
** * SAHPI_LAST_ENTRY Reserved as delimiter for end of list. Not a valid
** entry identifier.
** NextEntryId - [out] Pointer to the location to store the EntryId of next
** domain entry.
** DomainEntry - [out] Pointer to the structure to hold the returned domain
** entry.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_NOT_PRESENT is returned when the:
** * Entry identified by EntryId is not present.
** * EntryId is SAHPI_FIRST_ENTRY and the Base Library domain table is empty.
** SA_ERR_HPI_INVALID_PARAMS is returned if the:
** * DomainEntry pointer is passed in as NULL.
** * NextEntryId pointer is passed in as NULL.
** * EntryId is an invalid reserved value such as SAHPI_LAST_ENTRY.
**
** Remarks:
** This is Base Library level function.
** If the EntryId parameter is set to SAHPI_FIRST_ENTRY, the first entry in
** the Base Library domain table is returned. When an entry is successfully
** retrieved, NextEntryId is set to the identifier of the next valid entry;
** however, when the last entry has been retrieved, NextEntryId is set to
** SAHPI_LAST_ENTRY. To retrieve an entire list of entries, call this function
** first with an EntryId of SAHPI_FIRST_ENTRY, and then use the returned
** NextEntryId in the next call. Proceed until the NextEntryId returned is
** SAHPI_LAST_ENTRY.
***************************************************************************/
SaErrorT SAHPI_API oHpiDomainEntryGet (
SAHPI_IN SaHpiEntryIdT EntryId,
SAHPI_OUT SaHpiEntryIdT *NextEntryId,
SAHPI_OUT oHpiDomainEntryT *DomainEntry );
/*******************************************************************************
**
** Name: oHpiDomainEntryGetByDomainId()
**
** Description:
** This function retrieves resource information from the Base Library known
** domain table for the specified domain using its DomainId.
**
** Parameters:
** DomainId - [in] Domain identified for this operation.
** DomainEntry - [out] Pointer to the structure to hold the returned domain
** entry.
**
** Return Value:
** SA_OK is returned on successful completion; otherwise, an error code is
** returned.
** SA_ERR_HPI_NOT_PRESENT is returned when the specified DomainId is unknown
** to the Base Library.
** SA_ERR_HPI_INVALID_PARAMS is returned if the DomainEntry pointer is passed in
** as NULL.
**
** Remarks:
** This is Base Library level function.
**
***************************************************************************/
SaErrorT SAHPI_API oHpiDomainEntryGetByDomainId (
SAHPI_IN SaHpiDomainIdT DomainId,
SAHPI_OUT oHpiDomainEntryT *DomainEntry );
#define OHPI_VERSION_GET(v, VER) \
{ \
char version[] = VER; \
char *start = version; \
char *end = version; \
v += (strtoull(start, &end, 10) << 48); \
end++; \
start = end; \
v += (strtoull(start, &end, 10) << 32); \
end++; \
start = end; \
v += (strtoull(start, &end, 10) << 16); \
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*__OHPI_H*/
| 37.693878 | 88 | 0.645121 |
39d89a6965253c30a2e6d52d7996699588313d64 | 388 | js | JavaScript | api/dbcon.js | sarahwalter/myplanner | 85c30238cba31cb3c0aef783e2646503561b1150 | [
"MIT"
] | null | null | null | api/dbcon.js | sarahwalter/myplanner | 85c30238cba31cb3c0aef783e2646503561b1150 | [
"MIT"
] | 6 | 2018-07-19T03:06:11.000Z | 2018-08-17T03:32:11.000Z | api/dbcon.js | sarahwalter/myplanner | 85c30238cba31cb3c0aef783e2646503561b1150 | [
"MIT"
] | 3 | 2018-07-14T15:17:20.000Z | 2018-07-14T22:42:50.000Z | const mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: 'us-cdbr-iron-east-04.cleardb.net',
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: 'heroku_17a4cf0a865e81c'
// host: 'localhost',
// user: 'root',
// password: '',
// database: 'myplanner-test'
});
module.exports.pool = pool; | 27.714286 | 45 | 0.654639 |
1640eb875d4ee8ad37e5d999856d99d2db2ad219 | 1,336 | h | C | linux-2.6.0/include/linux/efs_fs.h | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | 1 | 2020-11-10T12:47:02.000Z | 2020-11-10T12:47:02.000Z | linux-2.6.0/include/linux/efs_fs.h | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | null | null | null | linux-2.6.0/include/linux/efs_fs.h | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | null | null | null | /*
* efs_fs.h
*
* Copyright (c) 1999 Al Smith
*
* Portions derived from work (c) 1995,1996 Christian Vogelgsang.
*/
#ifndef __EFS_FS_H__
#define __EFS_FS_H__
#define EFS_VERSION "1.0a"
static const char cprt[] = "EFS: "EFS_VERSION" - (c) 1999 Al Smith <Al.Smith@aeschi.ch.eu.org>";
#include <asm/uaccess.h>
/* 1 block is 512 bytes */
#define EFS_BLOCKSIZE_BITS 9
#define EFS_BLOCKSIZE (1 << EFS_BLOCKSIZE_BITS)
#include <linux/fs.h>
#include <linux/efs_fs_i.h>
#include <linux/efs_fs_sb.h>
#include <linux/efs_dir.h>
static inline struct efs_inode_info *INODE_INFO(struct inode *inode)
{
return container_of(inode, struct efs_inode_info, vfs_inode);
}
static inline struct efs_sb_info *SUPER_INFO(struct super_block *sb)
{
return sb->s_fs_info;
}
struct statfs;
extern struct inode_operations efs_dir_inode_operations;
extern struct file_operations efs_dir_operations;
extern struct address_space_operations efs_symlink_aops;
extern int efs_fill_super(struct super_block *, void *, int);
extern int efs_statfs(struct super_block *, struct kstatfs *);
extern void efs_read_inode(struct inode *);
extern efs_block_t efs_map_block(struct inode *, efs_block_t);
extern struct dentry *efs_lookup(struct inode *, struct dentry *, struct nameidata *);
extern int efs_bmap(struct inode *, int);
#endif /* __EFS_FS_H__ */
| 25.207547 | 96 | 0.761976 |
b72caf03d02d42e125203a689c7fc9dc4afd73b9 | 1,826 | asm | Assembly | programs/oeis/052/A052515.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/052/A052515.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/052/A052515.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A052515: Number of ordered pairs of complementary subsets of an n-set with both subsets of cardinality at least 2.
; 0,0,0,0,6,20,50,112,238,492,1002,2024,4070,8164,16354,32736,65502,131036,262106,524248,1048534,2097108,4194258,8388560,16777166,33554380,67108810,134217672,268435398,536870852,1073741762,2147483584,4294967230,8589934524,17179869114,34359738296,68719476662,137438953396,274877906866,549755813808,1099511627694,2199023255468,4398046511018,8796093022120,17592186044326,35184372088740,70368744177570,140737488355232,281474976710558,562949953421212,1125899906842522,2251799813685144,4503599627370390,9007199254740884,18014398509481874,36028797018963856,72057594037927822,144115188075855756,288230376151711626,576460752303423368,1152921504606846854,2305843009213693828,4611686018427387778,9223372036854775680,18446744073709551486,36893488147419103100,73786976294838206330,147573952589676412792,295147905179352825718,590295810358705651572,1180591620717411303282,2361183241434822606704,4722366482869645213550,9444732965739290427244,18889465931478580854634,37778931862957161709416,75557863725914323418982,151115727451828646838116,302231454903657293676386,604462909807314587352928,1208925819614629174706014,2417851639229258349412188,4835703278458516698824538,9671406556917033397649240,19342813113834066795298646,38685626227668133590597460,77371252455336267181195090,154742504910672534362390352,309485009821345068724780878,618970019642690137449561932,1237940039285380274899124042,2475880078570760549798248264,4951760157141521099596496710,9903520314283042199192993604,19807040628566084398385987394,39614081257132168796771974976,79228162514264337593543950142,158456325028528675187087900476,316912650057057350374175801146,633825300114114700748351602488
mov $2,$0
mul $0,2
mov $1,2
pow $1,$2
sub $1,2
trn $1,$0
mov $0,$1
| 166 | 1,640 | 0.912924 |
9962ee4feb34497663c925ce2d3315b1612774c4 | 7,592 | c | C | lib/trusty/syscall.c | Rashed97/trusty_lk_trusty | 6316ab7d8285a9738ac0b63552b7a60c074cb3de | [
"MIT"
] | 7 | 2020-03-26T01:52:25.000Z | 2021-11-29T07:00:24.000Z | lib/trusty/syscall.c | Rashed97/trusty_lk_trusty | 6316ab7d8285a9738ac0b63552b7a60c074cb3de | [
"MIT"
] | 2 | 2020-03-28T22:53:56.000Z | 2021-12-03T15:33:32.000Z | lib/trusty/syscall.c | Rashed97/trusty_lk_trusty | 6316ab7d8285a9738ac0b63552b7a60c074cb3de | [
"MIT"
] | 2 | 2020-03-26T02:20:24.000Z | 2021-01-31T22:46:57.000Z | /*
* Copyright (c) 2013, Google, Inc. All rights reserved
* Copyright (c) 2013-2018, NVIDIA CORPORATION. All rights reserved
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <assert.h>
#include <debug.h>
#include <err.h>
#include <kernel/thread.h>
#include <kernel/mutex.h>
#include <mm.h>
#include <stdlib.h>
#include <string.h>
#include <trace.h>
#include <uthread.h>
#include <lib/trusty/sys_fd.h>
#include <lib/trusty/trusty_app.h>
#include <trusty_std.h>
#define LOCAL_TRACE 0
static int32_t sys_std_write(uint32_t fd, user_addr_t user_ptr, uint32_t size);
uint32_t uctx_get_current_guest(void);
int32_t sys_std_platform_ioctl(uint32_t fd, uint32_t cmd, user_addr_t user_ptr);
static mutex_t fd_lock = MUTEX_INITIAL_VALUE(fd_lock);
static const struct sys_fd_ops sys_std_fd_op = {
.write = sys_std_write,
.ioctl = sys_std_platform_ioctl,
};
static struct sys_fd_ops const *sys_fds[MAX_SYS_FD_HADLERS] = {
[1] = &sys_std_fd_op, /* stdout */
[2] = &sys_std_fd_op, /* stderr */
[3] = &sys_std_fd_op, /* std_ioctol */
};
status_t install_sys_fd_handler(uint32_t fd, const struct sys_fd_ops *ops)
{
status_t ret;
if (fd >= countof(sys_fds)) {
return ERR_INVALID_ARGS;
}
mutex_acquire(&fd_lock);
if (!sys_fds[fd]) {
sys_fds[fd] = ops;
ret = NO_ERROR;
} else {
ret = ERR_ALREADY_EXISTS;
}
mutex_release(&fd_lock);
return ret;
}
static const struct sys_fd_ops *get_sys_fd_handler(uint32_t fd)
{
if (fd >= countof(sys_fds)) {
return NULL;
}
return sys_fds[fd];
}
static bool valid_address(vaddr_t addr, size_t size)
{
return uthread_is_valid_range(uthread_get_current(), addr, size);
}
/* handle stdout/stderr */
static int32_t sys_std_write(uint32_t fd, user_addr_t user_ptr, uint32_t size)
{
/* check buffer is in task's address space */
if (!valid_address((vaddr_t)user_ptr, size)) {
return ERR_INVALID_ARGS;
}
/* always send out error logs */
dwrite((fd == 2) ? ALWAYS : INFO, (const void *)(uintptr_t)user_ptr, size);
return size;
}
long sys_write(uint32_t fd, user_addr_t user_ptr, uint32_t size)
{
const struct sys_fd_ops *ops = get_sys_fd_handler(fd);
if (ops && ops->write) {
return ops->write(fd, user_ptr, size);
}
return ERR_NOT_SUPPORTED;
}
long sys_brk(u_int brk)
{
trusty_app_t *trusty_app = uthread_get_current()->private_data;
/* update brk, if within range */
if ((brk >= trusty_app->start_brk) && (brk <= trusty_app->end_brk)) {
trusty_app->cur_brk = brk;
}
return (long) trusty_app->cur_brk;
}
long sys_exit_group(void)
{
thread_t *current = get_current_thread();
dprintf(CRITICAL, "exit called, thread %p, name %s\n",
current, current->name);
uthread_exit(0);
return 0L;
}
long sys_read(uint32_t fd, user_addr_t user_ptr, uint32_t size)
{
const struct sys_fd_ops *ops = get_sys_fd_handler(fd);
if (ops && ops->read) {
return ops->read(fd, user_ptr, size);
}
return ERR_NOT_SUPPORTED;
}
long sys_ioctl(uint32_t fd, uint32_t req, user_addr_t user_ptr)
{
const struct sys_fd_ops *ops = get_sys_fd_handler(fd);
if (ops && ops->ioctl) {
return ops->ioctl(fd, req, user_ptr);
}
return ERR_NOT_SUPPORTED;
}
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
long sys_nanosleep(uint32_t clock_id, uint32_t flags,
uint32_t sleep_time_l, uint32_t sleep_time_h)
{
uint64_t sleep_time = sleep_time_l + ((uint64_t)sleep_time_h << 32);
thread_sleep((lk_time_t)(DIV_ROUND_UP(sleep_time, 1000 * 1000)));
return NO_ERROR;
}
long sys_gettime(uint32_t clock_id, uint32_t flags, user_addr_t time)
{
// return time in nanoseconds
lk_bigtime_t t = current_time_hires() * 1000;
return copy_to_user(time, &t, sizeof(uint64_t));
}
long sys_mmap(user_addr_t uaddr, uint32_t size, uint32_t flags, uint32_t handle)
{
trusty_app_t *trusty_app = uthread_get_current()->private_data;
vaddr_t vaddr;
long ret;
/*
* Allocate and map memory with Device attributes
*/
if (flags & MMAP_FLAG_DEVICE_MEM) {
ret = uthread_pmm_alloc_and_map(trusty_app->ut, &vaddr, size,
flags, 1);
if (ret)
return ret;
return vaddr;
}
/*
* Only allows mapping on IO region specified by handle (id) and uaddr
* must be 0 for now.
* TBD: Add support in uthread_map to use uaddr as a hint.
*/
if (flags != MMAP_FLAG_IO_HANDLE || uaddr != 0) {
return ERR_INVALID_ARGS;
}
ret = trusty_app_setup_mmio(trusty_app, handle, &vaddr, size);
if (ret != NO_ERROR) {
return ret;
}
return vaddr;
}
long sys_munmap(user_addr_t uaddr, uint32_t size)
{
trusty_app_t *trusty_app = uthread_get_current()->private_data;
/*
* uthread_unmap always unmaps whole region.
* TBD: Add support to unmap partial region when there's use case.
*/
return uthread_unmap(trusty_app->ut, uaddr, size);
}
#if UTHREAD_WITH_MEMORY_MAPPING_SUPPORT
long sys_prepare_dma(user_addr_t uaddr, uint32_t size, uint32_t flags,
user_addr_t pmem)
{
uthread_t *current = uthread_get_current();
struct dma_pmem kpmem;
uint32_t mapped_size = 0;
uint32_t entries = 0;
long ret;
LTRACEF("uaddr 0x%x, size 0x%x, flags 0x%x, pmem 0x%x\n",
uaddr, size, flags, pmem);
if (size == 0 || !valid_address((vaddr_t)uaddr, size)) {
return ERR_INVALID_ARGS;
}
do {
ret = uthread_virt_to_phys(current,
(vaddr_t)uaddr + mapped_size, (paddr_t *)&kpmem.paddr);
if (ret != NO_ERROR) {
return ret;
}
kpmem.size = MIN(size - mapped_size,
PAGE_SIZE - (kpmem.paddr & (PAGE_SIZE - 1)));
ret = copy_to_user(pmem, &kpmem, sizeof(struct dma_pmem));
if (ret != NO_ERROR) {
return ret;
}
pmem += sizeof(struct dma_pmem);
mapped_size += kpmem.size;
entries++;
} while (mapped_size < size && (flags & DMA_FLAG_MULTI_PMEM));
if (flags & DMA_FLAG_FROM_DEVICE) {
arch_clean_invalidate_cache_range(uaddr, mapped_size);
} else {
arch_clean_cache_range(uaddr, mapped_size);
}
if (!(flags & DMA_FLAG_ALLOW_PARTIAL) && mapped_size != size) {
return ERR_BAD_LEN;
}
return entries;
}
long sys_finish_dma(user_addr_t uaddr, uint32_t size, uint32_t flags)
{
LTRACEF("uaddr 0x%x, size 0x%x, flags 0x%x\n", uaddr, size, flags);
/* check buffer is in task's address space */
if (!valid_address((vaddr_t)uaddr, size)) {
return ERR_INVALID_ARGS;
}
if (flags & DMA_FLAG_FROM_DEVICE) {
arch_clean_invalidate_cache_range(uaddr, size);
}
return NO_ERROR;
}
#else /* !UTHREAD_WITH_MEMORY_MAPPING_SUPPORT */
long sys_prepare_dma(user_addr_t uaddr, uint32_t size, uint32_t flags,
user_addr_t pmem)
{
return ERR_NOT_SUPPORTED;
}
long sys_finish_dma(user_addr_t uaddr, uint32_t size, uint32_t flags)
{
return ERR_NOT_SUPPORTED;
}
#endif
| 26.089347 | 80 | 0.723393 |
8787915fc1b1c73d855c3281eeb3af3f02ba091c | 1,969 | kt | Kotlin | app/src/main/java/com/anurag/newsfeedapp/data/network/NetworkDataSource.kt | droid-it/News-Feed-App | 5b285f252a3f53179a3b27a99618489722588242 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/anurag/newsfeedapp/data/network/NetworkDataSource.kt | droid-it/News-Feed-App | 5b285f252a3f53179a3b27a99618489722588242 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/anurag/newsfeedapp/data/network/NetworkDataSource.kt | droid-it/News-Feed-App | 5b285f252a3f53179a3b27a99618489722588242 | [
"Apache-2.0"
] | null | null | null | package com.anurag.newsfeedapp.data.network
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.anurag.newsfeedapp.data.News
import com.anurag.newsfeedapp.data.finalTime
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.suspendCoroutine
@Singleton
class NetworkDataSource @Inject constructor(
private val networkClient: NetworkClient
) {
suspend fun getNewsFeed(): List<News> {
return fetchNews()
}
private suspend fun fetchNews(): List<News> = suspendCoroutine {
val request = JsonObjectRequest(
Request.Method.GET, URL, null,
{ response ->
val news = parseResponse(response)
it.resumeWith(Result.success(news))
},
{ error ->
it.resumeWith(Result.failure(error))
})
networkClient.addToRequestQueue(request)
}
private fun parseResponse(response: JSONObject): List<News> {
val jsonArray = response.getJSONArray("articles")
val newsArray = ArrayList<News>()
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val publishedAt =
jsonObject.getString("publishedAt") //fetching publishedAt from the JSON file
newsArray += News(
title = jsonObject.getString("title"),
url = jsonObject.getString("url"),
imageUrl = jsonObject.getString("urlToImage"),
description = jsonObject.getString("description"),
source = jsonObject.getJSONObject("source")
.getString("name"),
time = finalTime(publishedAt)
)
}
return newsArray
}
companion object {
const val URL = "https://saurav.tech/NewsAPI/top-headlines/category/general/in.json"
}
} | 30.765625 | 98 | 0.624175 |
e2675d948123541dabe4ab70a85fa2239804e839 | 206 | sql | SQL | sql/_13_issues/_10_1h/cases/CUBRIDSUS-2941.sql | Zhaojia2019/cubrid-testcases | 475a828e4d7cf74aaf2611fcf791a6028ddd107d | [
"BSD-3-Clause"
] | 9 | 2016-03-24T09:51:52.000Z | 2022-03-23T10:49:47.000Z | sql/_13_issues/_10_1h/cases/CUBRIDSUS-2941.sql | Zhaojia2019/cubrid-testcases | 475a828e4d7cf74aaf2611fcf791a6028ddd107d | [
"BSD-3-Clause"
] | 173 | 2016-04-13T01:16:54.000Z | 2022-03-16T07:50:58.000Z | sql/_13_issues/_10_1h/cases/CUBRIDSUS-2941.sql | Zhaojia2019/cubrid-testcases | 475a828e4d7cf74aaf2611fcf791a6028ddd107d | [
"BSD-3-Clause"
] | 38 | 2016-03-24T17:10:31.000Z | 2021-10-30T22:55:45.000Z | SELECT STR_TO_DATE('abc','abc');
SELECT STR_TO_DATE('','vvvvvv');
SELECT STR_TO_DATE('000%%','000%%');
SELECT STR_TO_DATE('abc 4','cde %s');
SELECT STR_TO_DATE('abc 11:33:44 am 19 23:59:59','cde %r %d %T'); | 41.2 | 65 | 0.660194 |
e700a2a12b453bc1cfb73ec2fd13af1fdcd9f820 | 4,065 | swift | Swift | Sources/LSFoundation/String+LSFoundation.swift | hisaac/LSFoundation | 483447cc6ebf189e963c738671913e5a649e0856 | [
"MIT"
] | null | null | null | Sources/LSFoundation/String+LSFoundation.swift | hisaac/LSFoundation | 483447cc6ebf189e963c738671913e5a649e0856 | [
"MIT"
] | null | null | null | Sources/LSFoundation/String+LSFoundation.swift | hisaac/LSFoundation | 483447cc6ebf189e963c738671913e5a649e0856 | [
"MIT"
] | null | null | null | //
// String+LSFoundation.swift
// LSFoundation
//
import Foundation
public extension String {
/// Convenience accessor for `NSString`'s `lastPathComponent` property
var lastPathComponent: String {
return NSString(string: self).lastPathComponent
}
/// Checks if a string does not contain another string
/// - Parameter other: The other element to check for
/// - Returns: True if the string is not contained within the other string
func doesNotContain<T>(_ other: T) -> Bool where T: StringProtocol {
return self.contains(other).toggled
}
/// Checks if the current string contains any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if any of the given strings are contained within the current string
func containsAny<T>(of other: T...) -> Bool where T: StringProtocol {
return containsAny(of: other)
}
/// Checks if the current string contains any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if any of the given strings are contained within the current string
func containsAny<T>(of other: [T]) -> Bool where T: StringProtocol {
for element in other {
if self.contains(element) {
return true
}
}
return false
}
/// Checks if the current string contains all of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if all of the given strings are contained within the current string
func containsAll<T>(of other: T...) -> Bool where T: StringProtocol {
return containsAll(of: other)
}
/// Checks if the current string contains all of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if all of the given strings are contained within the current string
func containsAll<T>(of other: [T]) -> Bool where T: StringProtocol {
for element in other {
if self.doesNotContain(element) {
return false
}
}
return true
}
/// Checks if the current string does not contain any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if none of the given strings are contained within the current string
func containsNone<T>(of other: T...) -> Bool where T: StringProtocol {
return containsNone(of: other)
}
/// Checks if the current string does not contain any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if none of the given strings are contained within the current string
func containsNone<T>(of other: [T]) -> Bool where T: StringProtocol {
for element in other {
if self.contains(element) {
return false
}
}
return true
}
/// Checks if the current string ends with any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if the current string ends with any of the given strings
func endsWithAny<T>(of other: T...) -> Bool where T: StringProtocol {
return endsWithAny(of: other)
}
/// Checks if the current string ends with any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if the current string ends with any of the given strings
func endsWithAny<T>(of other: [T]) -> Bool where T: StringProtocol {
for element in other {
if self.hasSuffix(element) {
return true
}
}
return false
}
/// Checks if the current string starts with any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if the current string starts with any of the given strings
func startsWithAny<T>(of other: T...) -> Bool where T: StringProtocol {
return endsWithAny(of: other)
}
/// Checks if the current string starts with any of the given strings
/// - Parameter other: The other strings to check for
/// - Returns: True if the current string starts with any of the given strings
func startsWithAny<T>(of other: [T]) -> Bool where T: StringProtocol {
for element in other {
if self.hasPrefix(element) {
return true
}
}
return false
}
}
| 34.74359 | 89 | 0.709471 |
3dcda4624610ac0ea0868998394b531847969493 | 635 | rs | Rust | src/test/kani/Enum/discriminant.rs | celinval/rmc-dev | d7a574d0d2364010c86851cf57000b2da439d873 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 61 | 2021-05-04T06:33:26.000Z | 2022-01-20T22:47:12.000Z | src/test/kani/Enum/discriminant.rs | celinval/rmc-dev | d7a574d0d2364010c86851cf57000b2da439d873 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 494 | 2021-04-26T15:13:24.000Z | 2022-01-22T01:24:55.000Z | src/test/kani/Enum/discriminant.rs | celinval/rmc-dev | d7a574d0d2364010c86851cf57000b2da439d873 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 17 | 2021-04-30T11:01:35.000Z | 2022-01-11T23:05:39.000Z | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Testcase for https://github.com/model-checking/rmc/issues/558.
// See https://rust-lang.github.io/unsafe-code-guidelines/layout/enums.html for information on the
// layout.
pub enum MyEnum {
Val1,
Val2,
}
fn foo(x: u32) -> Option<MyEnum> {
// The math does overflow. Val1 == 0, Val2 == 1, None == 2.
// The discriminant logic is val - max == 0 ? <> : <>; where max is 2
if x > 10 { Some(MyEnum::Val2) } else { None }
}
pub fn main() {
let x = foo(15);
assert!(x.is_some(), "assert");
}
| 30.238095 | 98 | 0.633071 |
59927239bd241ce0d56271947d3da33ac27c193b | 5,017 | kt | Kotlin | src/test/kotlin/no/nav/tjenestepensjon/simulering/v1/OpptjeningsperiodeCallableTest.kt | navikt/tjenestepensjon-simulering | b0d117c47a8a045e96ffb86570c8271bf35d67b1 | [
"MIT"
] | null | null | null | src/test/kotlin/no/nav/tjenestepensjon/simulering/v1/OpptjeningsperiodeCallableTest.kt | navikt/tjenestepensjon-simulering | b0d117c47a8a045e96ffb86570c8271bf35d67b1 | [
"MIT"
] | 1 | 2019-05-28T16:40:24.000Z | 2019-05-29T05:38:31.000Z | src/test/kotlin/no/nav/tjenestepensjon/simulering/v1/OpptjeningsperiodeCallableTest.kt | navikt/tjenestepensjon-simulering | b0d117c47a8a045e96ffb86570c8271bf35d67b1 | [
"MIT"
] | null | null | null | package no.nav.tjenestepensjon.simulering.v1
import no.nav.tjenestepensjon.simulering.model.domain.FNR
import no.nav.tjenestepensjon.simulering.model.domain.TPOrdning
import no.nav.tjenestepensjon.simulering.model.domain.TpLeverandor
import no.nav.tjenestepensjon.simulering.model.domain.TpLeverandor.EndpointImpl.REST
import no.nav.tjenestepensjon.simulering.model.domain.TpLeverandor.EndpointImpl.SOAP
import no.nav.tjenestepensjon.simulering.testHelper.anyNonNull
import no.nav.tjenestepensjon.simulering.v1.exceptions.StillingsprosentCallableException
import no.nav.tjenestepensjon.simulering.v1.models.domain.Stillingsprosent
import no.nav.tjenestepensjon.simulering.v1.soap.SoapClient
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.ws.client.WebServiceIOException
import java.time.LocalDate
@ExtendWith(MockitoExtension::class)
internal class OpptjeningsperiodeCallableTest {
@Mock
private lateinit var soapClient: SoapClient
@Test
@Throws(Exception::class)
fun `Call shall return stillingsprosenter with soap`() {
val stillingsprosenter: List<Stillingsprosent> = prepareStillingsprosenter()
Mockito.`when`(soapClient.getStillingsprosenter(anyNonNull(), anyNonNull(), anyNonNull())).thenReturn(stillingsprosenter)
val result: List<Stillingsprosent> = StillingsprosentCallable(fnr, tpOrdning, soapTpLeverandor, soapClient)()
assertStillingsprosenter(stillingsprosenter, result)
}
@Test
@Throws(Exception::class)
fun `Call shall return stillingsprosenter with rest`() {
val stillingsprosenter: List<Stillingsprosent> = prepareStillingsprosenter()
Mockito.`when`(soapClient.getStillingsprosenter(anyNonNull(), anyNonNull(), anyNonNull())).thenReturn(stillingsprosenter)
val result: List<Stillingsprosent> = StillingsprosentCallable(fnr, tpOrdning, restTpLeverandor, soapClient)()
assertStillingsprosenter(stillingsprosenter, result)
}
@Test
@Throws(Exception::class)
fun `Exception shall be rethrown as StillingsprosentCallableException with soap`() {
Mockito.`when`(soapClient.getStillingsprosenter(anyNonNull(), anyNonNull(), anyNonNull())).thenThrow(WebServiceIOException("msg from cause"))
val exception = assertThrows<StillingsprosentCallableException> { StillingsprosentCallable(fnr, tpOrdning, soapTpLeverandor, soapClient)() }
assertEquals("Call to getStillingsprosenter failed with exception: org.springframework.ws.client.WebServiceIOException: msg from cause", exception.message)
assertEquals(tpOrdning, exception.tpOrdning)
}
@Test
@Throws(Exception::class)
fun `Exception shall be rethrown as StillingsprosentCallableException with rest`() {
Mockito.`when`(soapClient.getStillingsprosenter(anyNonNull(), anyNonNull(), anyNonNull())).thenThrow(WebServiceIOException("msg from cause"))
val exception = assertThrows<StillingsprosentCallableException> { StillingsprosentCallable(fnr, tpOrdning, restTpLeverandor, soapClient)() }
assertEquals("Call to getStillingsprosenter failed with exception: org.springframework.ws.client.WebServiceIOException: msg from cause", exception.message)
assertEquals(tpOrdning, exception.tpOrdning)
}
private companion object {
val fnr = FNR("01011234567")
val tpOrdning = TPOrdning("tss1", "tp1")
val soapTpLeverandor = TpLeverandor("lev", SOAP, "sim", "stilling")
val restTpLeverandor = TpLeverandor("lev", REST, "sim", "stilling")
fun prepareStillingsprosenter() = listOf(
Stillingsprosent(
stillingsprosent = 100.0,
aldersgrense = 70,
datoFom = LocalDate.of(2018, 1, 2),
datoTom = LocalDate.of(2029, 12, 31),
faktiskHovedlonn = "hovedlønn1",
stillingsuavhengigTilleggslonn = "tilleggslønn1",
utvidelse = null
),
Stillingsprosent(
stillingsprosent = 12.5,
aldersgrense = 67,
datoFom = LocalDate.of(2019, 2, 3),
datoTom = LocalDate.of(2035, 11, 30),
faktiskHovedlonn = "hovedlønn2",
stillingsuavhengigTilleggslonn = "tilleggslønn2",
utvidelse = null
)
)
fun assertStillingsprosenter(expected: List<Stillingsprosent>, actual: List<Stillingsprosent>) {
assertEquals(expected.size, actual.size)
for (index in expected.indices) {
assertEquals(expected[index], actual[index])
}
}
}
} | 51.193878 | 163 | 0.70281 |
856157398be0d5b103a29e11dade52d50b23b806 | 692 | js | JavaScript | src/rocks/timeline-pusher/index.js | animachine/animachine | ee4cf607901a2cde5ffd20783f7ac4fc6765a5d2 | [
"MIT"
] | 447 | 2015-02-24T10:44:00.000Z | 2022-02-11T22:01:34.000Z | src/rocks/timeline-pusher/index.js | Ni-c0de-mus/animachine | 5be456f187f4f65769039e42e3496d494b2f3957 | [
"MIT"
] | 8 | 2015-02-25T19:31:06.000Z | 2018-10-05T15:53:31.000Z | src/rocks/timeline-pusher/index.js | Ni-c0de-mus/animachine | 5be456f187f4f65769039e42e3496d494b2f3957 | [
"MIT"
] | 45 | 2015-01-15T14:43:16.000Z | 2022-01-04T11:55:03.000Z | import {createComputedValue} from 'afflatus'
BETON.define({
id: 'timeline-pusher',
dependencies: ['project-manager'],
init
})
function init({projectManager}) {
const {state, actions, getters} = projectManager
let lastTime = performance.now()
function push() {
const time = performance.now()
const timeline = state.currentTimeline
if (
timeline
&& timeline.isPlaying
&& timeline.lastKeyTime > 0
) {
let nextTime = timeline.currentTime + time - lastTime
nextTime %= timeline.lastKeyTime
timeline.currentTime = nextTime
}
lastTime = time
window.requestAnimationFrame(push)
}
window.requestAnimationFrame(push)
}
| 23.066667 | 59 | 0.676301 |
2fbdae89e50b93552ec0023514e0eeb7ac7d9c7f | 35 | sql | SQL | packages/auth/sql/20000/auth.schema.sql | davidsparkles/fullstack-one | 21507851cdadc3e544db204f24d110a0f5e15034 | [
"MIT"
] | 32 | 2017-11-28T00:35:53.000Z | 2020-04-07T03:14:02.000Z | packages/auth/sql/20000/auth.schema.sql | davidsparkles/fullstack-one | 21507851cdadc3e544db204f24d110a0f5e15034 | [
"MIT"
] | 67 | 2018-01-13T10:31:47.000Z | 2019-12-02T15:49:47.000Z | _v1/packages/auth/sql/20000/auth.schema.sql | fullstack-build/soniq | c18a280ba2601e4c020d9461bf500adaeb6058d0 | [
"MIT"
] | 5 | 2018-08-16T22:55:26.000Z | 2019-11-27T20:52:49.000Z | CREATE SCHEMA IF NOT EXISTS _auth;
| 17.5 | 34 | 0.8 |
f170f4fbfb831b2d9760325149e68b1815e94a45 | 718 | rb | Ruby | sinatra-secure-password-lab-v-000/spec/spec_helper.rb | josephhyatt/learn_co | a627a15eb71a0e0aa5ef3e518b8fa52050d772f3 | [
"MIT"
] | null | null | null | sinatra-secure-password-lab-v-000/spec/spec_helper.rb | josephhyatt/learn_co | a627a15eb71a0e0aa5ef3e518b8fa52050d772f3 | [
"MIT"
] | 15 | 2020-02-25T22:30:45.000Z | 2022-02-26T08:32:24.000Z | spec/spec_helper.rb | mcdonaldcarolyn/tank-census | 0364a3e4881a3fa474bbf76bc7b62bacd05c33d9 | [
"MIT"
] | 1 | 2020-08-14T21:30:15.000Z | 2020-08-14T21:30:15.000Z | require_relative '../config/environment.rb'
require 'rack/test'
ENV["SINATRA_ENV"] = "test"
require_relative '../config/environment'
require 'capybara/rspec'
require 'capybara/dsl'
require 'rack_session_access/capybara'
if ActiveRecord::Migrator.needs_migration?
raise 'Migrations are pending. Run `rake db:migrate SINATRA_ENV=test` to resolve the issue.'
end
ApplicationController.configure do |app|
app.use RackSessionAccess::Middleware
end
RSpec.configure do |config|
config.include Rack::Test::Methods
config.include Capybara::DSL
config.order = 'default'
end
def app
Rack::Builder.parse_file('config.ru').first
end
Capybara.app = app
# def session
# last_request.env['rack.session']
# end | 19.944444 | 94 | 0.763231 |
a5ff047e3accf9953346f2db94e3153698888030 | 232 | swift | Swift | eTrips/MVC/Models/StaticData/Grant/Grant.swift | unicef/etools-etrips-ios | b03cf1e1fefa1f6e8dc88ccc74e18e25eaeaa5fc | [
"Apache-2.0"
] | 2 | 2017-04-27T05:08:20.000Z | 2017-10-02T17:54:16.000Z | eTrips/MVC/Models/StaticData/Grant/Grant.swift | unicef/etools-etrips-ios | b03cf1e1fefa1f6e8dc88ccc74e18e25eaeaa5fc | [
"Apache-2.0"
] | null | null | null | eTrips/MVC/Models/StaticData/Grant/Grant.swift | unicef/etools-etrips-ios | b03cf1e1fefa1f6e8dc88ccc74e18e25eaeaa5fc | [
"Apache-2.0"
] | null | null | null | import Foundation
import ObjectMapper
public class Grant: Mappable {
var grantID: Int?
var name: String?
public required init?(map: Map) {
}
public func mapping(map: Map) {
grantID <- map["id"]
name <- map["name"]
}
}
| 13.647059 | 34 | 0.663793 |
7a2079e71eeac4bd3ff4009d46b408a684a97198 | 6,254 | rs | Rust | Rust/rust_gtk/src/bin/button_counter/mod.rs | sreeise/Programming-Reference | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | 2 | 2019-04-28T00:56:22.000Z | 2019-08-03T17:41:19.000Z | Rust/rust_gtk/src/bin/button_counter/mod.rs | sreeise/ProgrammingSnippets | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | 1 | 2018-07-10T22:33:12.000Z | 2018-07-16T22:30:35.000Z | Rust/rust_gtk/src/bin/button_counter/mod.rs | sreeise/ProgrammingSnippets | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | null | null | null | use gtk::*;
use std::process;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
/// Predefined messages that will be used by the UI upon certain conditions.
const MESSAGES: [&str; 3] = ["Ouch! You hit me!", "...", "Thanks!"];
#[repr(u8)]
// An enum, represented as a u8, that is used as an index into the `MESSAGES` array.
enum Message { Hit, Dead, Heal }
pub struct App {
pub window: Window,
pub header: Header,
pub content: Content,
}
pub struct Header {
pub container: HeaderBar,
pub hit: Button,
pub heal: Button,
}
pub struct Content {
pub container: Box,
pub health: Label,
pub message: Label,
}
pub struct HealthComponent(AtomicUsize);
impl HealthComponent {
fn new(initial: usize) -> HealthComponent { HealthComponent(AtomicUsize::new(initial)) }
fn get_health(&self) -> usize { self.0.load(Ordering::SeqCst) }
fn subtract(&self, value: usize) -> usize {
let current = self.0.load(Ordering::SeqCst);
let new = if current < value { 0 } else { current - value };
self.0.store(new, Ordering::SeqCst);
new
}
fn heal(&self, value: usize) -> usize {
let original = self.0.fetch_add(value, Ordering::SeqCst);
original + value
}
}
impl App {
fn new(health: &HealthComponent) -> App {
// Create a new top level window.
let window = Window::new(WindowType::Toplevel);
// Create a the headerbar and it's associated content.
let header = Header::new();
// Contains the content within the window.
let content = Content::new(health);
// Set the headerbar as the title bar widget.
window.set_titlebar(&header.container);
// Set the title of the window.
window.set_title("App Name");
// Set the window manager class.
window.set_wmclass("app-name", "App name");
// The icon the app will display.
Window::set_default_icon_name("iconname");
// Add the content box into the window.
window.add(&content.container);
// Programs what to do when the exit button is used.
window.connect_delete_event(move |_, _| {
main_quit();
Inhibit(false)
});
// Return our main application state
App { window, header, content }
}
}
impl Header {
fn new() -> Header {
// Creates the main header bar container widget.
let container = HeaderBar::new();
// Sets the text to display in the title section of the header bar.
container.set_title("App Name");
// Enable the window controls within this headerbar.
container.set_show_close_button(true);
// Create the hit and heal buttons.
let hit = Button::new_with_label("Hit");
let heal = Button::new_with_label("Heal");
// Add the corresponding style classes to those buttons.
hit.get_style_context().map(|c| c.add_class("destructive-action"));
heal.get_style_context().map(|c| c.add_class("suggested-action"));
// THen add them to the header bar.
container.pack_start(&hit);
container.pack_end(&heal);
// Returns the header and all of it's state
Header { container, hit, heal }
}
}
impl Content {
fn new(health: &HealthComponent) -> Content {
// Create a vertical box to store all of it's inner children vertically.
let container = Box::new(Orientation::Vertical, 0);
// The health info will be contained within a horizontal box within the vertical box.
let health_info = Box::new(Orientation::Horizontal, 0);
let health_label = Label::new("Current Health:");
let health = Label::new(health.get_health().to_string().as_str());
// Set the horizontal alignments of each of our objects.
health_info.set_halign(Align::Center);
health_label.set_halign(Align::Start);
health.set_halign(Align::Start);
// Add the health info box's children
health_info.pack_start(&health_label, false, false, 5);
health_info.pack_start(&health, true, true, 5);
// Create a message label that will later be modified by the application, upon
// performing a hit or heal action.
let message = Label::new("Hello");
// Add everything to our vertical box
container.pack_start(&health_info, true, false, 0);
container.pack_start(&Separator::new(Orientation::Horizontal), false, false, 0);
container.pack_start(&message, true, false, 0);
Content { container, health, message }
}
}
pub fn run_button_counter() {
// Initialize GTK before proceeding.
if gtk::init().is_err() {
eprintln!("failed to initialize GTK Application");
process::exit(1);
}
// Set the initial state of our health component. We use an `Arc` so that we can share
// this value across multiple programmable closures.
let health = Arc::new(HealthComponent::new(10));
// Initialize the UI's initial state.
let app = App::new(&health);
{
// Program the Hit button to subtract health.
let health = health.clone();
let message = app.content.message.clone();
let info = app.content.health.clone();
app.header.hit.clone().connect_clicked(move |_| {
let new_health = health.subtract(1);
let action = if new_health == 0 { Message::Dead } else { Message::Hit };
message.set_label(MESSAGES[action as usize]);
info.set_label(new_health.to_string().as_str());
});
}
{
// Program the Heal button to restore health.
let health = health.clone();
let message = app.content.message.clone();
let info = app.content.health.clone();
app.header.heal.clone().connect_clicked(move |_| {
let new_health = health.heal(5);
message.set_label(MESSAGES[Message::Heal as usize]);
info.set_label(new_health.to_string().as_str());
});
}
// Make all the widgets within the UI visible.
app.window.show_all();
// Start the GTK main event loop
gtk::main();
}
| 32.915789 | 93 | 0.620563 |
dfa7d97cb5d24befbef3fc635d0792030cdb15cc | 102 | ts | TypeScript | composition-api/src/plugins/myapp-scss/index.ts | michaldolensky/large-scale-apps-my-vue3-project | 854db3e9eb05bc41624aee43861c00aa48cbef8c | [
"MIT"
] | 119 | 2020-08-18T03:37:06.000Z | 2022-03-27T21:49:22.000Z | composition-api/src/plugins/myapp-scss/index.ts | bravohex/large-scale-apps-my-vue3-project | 84b4be34619ff5776c0353c1b3fed879d07fffbb | [
"MIT"
] | 8 | 2020-09-07T03:29:44.000Z | 2022-01-24T15:24:07.000Z | composition-api/src/plugins/myapp-scss/index.ts | bravohex/large-scale-apps-my-vue3-project | 84b4be34619ff5776c0353c1b3fed879d07fffbb | [
"MIT"
] | 30 | 2020-09-14T21:47:56.000Z | 2022-03-28T14:49:28.000Z | export const MyAppScss = {
install() {
require('../../assets/scss/myapp-scss/index.scss')
}
}
| 17 | 54 | 0.607843 |
0bb56b74527c4ab3380dff7d3851c648cd78de0c | 347 | py | Python | src/workflows/__init__.py | stufisher/python-workflows | f1f67bb56a0f8a6820762f68e2e59ade2da60a95 | [
"BSD-3-Clause"
] | null | null | null | src/workflows/__init__.py | stufisher/python-workflows | f1f67bb56a0f8a6820762f68e2e59ade2da60a95 | [
"BSD-3-Clause"
] | null | null | null | src/workflows/__init__.py | stufisher/python-workflows | f1f67bb56a0f8a6820762f68e2e59ade2da60a95 | [
"BSD-3-Clause"
] | null | null | null | __version__ = "2.18"
def version():
"""Returns the version number of the installed workflows package."""
return __version__
class Error(Exception):
"""Common class for exceptions deliberately raised by workflows package."""
class Disconnected(Error):
"""Indicates the connection could not be established or has been lost."""
| 23.133333 | 79 | 0.723343 |
975625d3cc1cce999aa425f569ce2a6d691f6ee7 | 4,014 | swift | Swift | Sources/v1/Common/APIs/TFA/TFAModels.swift | iSevenDays/ios-sdk | ae56611c15a510f958d9b80b2e52f605ed3bea56 | [
"Apache-2.0"
] | null | null | null | Sources/v1/Common/APIs/TFA/TFAModels.swift | iSevenDays/ios-sdk | ae56611c15a510f958d9b80b2e52f605ed3bea56 | [
"Apache-2.0"
] | null | null | null | Sources/v1/Common/APIs/TFA/TFAModels.swift | iSevenDays/ios-sdk | ae56611c15a510f958d9b80b2e52f605ed3bea56 | [
"Apache-2.0"
] | null | null | null | import Foundation
public enum TFAFactorType: String {
case password
case totp
case email
}
public struct TFAMetaResponse: Codable, CustomDebugStringConvertible {
public let factorId: Int
public let factorType: String
public let keychainData: String?
public let salt: String?
public let token: String
public let walletId: String
public enum FactorTypeBase {
case codeBased(TFACodeMetaModel)
case passwordBased(TFAPasswordMetaModel)
}
public enum CodeBasedType {
case totp
case email
case other(String)
}
// MARK: - Public
static func getFactorTypeBase(_ meta: TFAMetaResponse) -> FactorTypeBase {
switch meta.factorType {
case "password":
if let passwordMetaModel = TFAPasswordMetaModel.fromTFAMetaResponse(meta) {
return .passwordBased(passwordMetaModel)
} else {
return .codeBased(TFACodeMetaModel.fromTFAMetaResponse(meta))
}
default:
return .codeBased(TFACodeMetaModel.fromTFAMetaResponse(meta))
}
}
public var factorTypeBase: FactorTypeBase {
return TFAMetaResponse.getFactorTypeBase(self)
}
public var codeBasedType: CodeBasedType {
switch self.factorType {
case "totp":
return .totp
case "email":
return .email
default:
return .other(self.factorType)
}
}
// MARK: - CustomDebugStringConvertible
public var debugDescription: String {
var fields: [String] = []
fields.append("factorId: \(self.factorId)")
fields.append("factorType: \(self.factorType)")
if let keychainData = self.keychainData {
fields.append("keychainData: \(keychainData)")
}
if let salt = self.salt {
fields.append("salt: \(salt)")
}
fields.append("token: \(self.token)")
fields.append("walletId: \(self.walletId)")
let description = DebugFormattedDescription(fields)
return description
}
}
public struct TFAFactor: Decodable {
public let type: String
public let id: Int
public let attributes: Attributes
public struct Attributes: Decodable {
public let priority: Int
}
}
/// TFA-related extensions to the list of `TFAFactor`
extension Array where Element == TFAFactor {
/// Method returns totp factors
public func getTOTPFactors() -> [TFAFactor] {
return self.filter({ (factor) -> Bool in
switch factor.type {
case TFAFactorType.totp.rawValue:
return true
default:
return false
}
})
}
/// Methods reports whether totp is enabled
public func isTOTPEnabled() -> Bool {
let totpPriority = self.getHighestPriority(factorType: TFAFactorType.totp.rawValue)
for factor in self {
switch factor.type {
case TFAFactorType.totp.rawValue:
continue
default:
if factor.attributes.priority > totpPriority {
return false
}
}
}
return totpPriority > 0
}
/// Method returns the highest priority of factorType
/// - Parameters:
/// - factorType: Factor type for which priority should be returned
public func getHighestPriority(factorType: String?) -> Int {
var filtered = self
if let factorType = factorType {
filtered = self.filter({ $0.type == factorType })
}
let priority: Int = filtered.reduce(0, { (result, factor) -> Int in
return Swift.max(result, factor.attributes.priority)
})
return priority
}
}
| 27.306122 | 91 | 0.571749 |
6b920da1399613346df31fed0dab46df866b7721 | 14,651 | h | C | engine/src/base/objsystem/primitives.h | Oghma/speect | f618e8d651cb9ec4c90cc244af3e7aa993599f6d | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 5 | 2016-01-29T14:39:46.000Z | 2019-04-24T14:45:55.000Z | engine/src/base/objsystem/primitives.h | Oghma/speect | f618e8d651cb9ec4c90cc244af3e7aa993599f6d | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | engine/src/base/objsystem/primitives.h | Oghma/speect | f618e8d651cb9ec4c90cc244af3e7aa993599f6d | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 7 | 2015-09-17T14:45:05.000Z | 2020-03-30T13:19:29.000Z | /************************************************************************************/
/* Copyright (c) 2008-2011 The Department of Arts and Culture, */
/* The Government of the Republic of South Africa. */
/* */
/* Contributors: Meraka Institute, CSIR, South Africa. */
/* */
/* 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. */
/* */
/************************************************************************************/
/* */
/* AUTHOR : Aby Louw */
/* DATE : 1 November 2008 */
/* */
/************************************************************************************/
/* */
/* SObject functions for four primitive data types: ints, floats, strings and void* */
/* */
/* Loosely based on cst_val of Flite, http://cmuflite.org (1.3) */
/* Note that this is a derived work with no verbatim source code from above */
/* mentioned project. */
/* */
/************************************************************************************/
#ifndef _SPCT_PRIMITIVES_H__
#define _SPCT_PRIMITIVES_H__
/************************************************************************************/
/* Flite license, cst_val */
/* */
/* Language Technologies Institute */
/* Carnegie Mellon University */
/* Copyright (c) 1999 */
/* All Rights Reserved. */
/* */
/* Permission is hereby granted, free of charge, to use and distribute */
/* this software and its documentation without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of this work, and to */
/* permit persons to whom this work is furnished to do so, subject to */
/* the following conditions: */
/* 1. The code must retain the above copyright notice, this list of */
/* conditions and the following disclaimer. */
/* 2. Any modifications must be clearly marked as such. */
/* 3. Original authors' names are not deleted. */
/* 4. The authors' names are not used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK */
/* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */
/* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */
/* SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE */
/* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES */
/* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN */
/* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, */
/* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF */
/* THIS SOFTWARE. */
/* */
/* Author: Alan W Black */
/* */
/************************************************************************************/
/**
* @file primitives.h
* SObjects for four primitive data types: ints, floats, strings and void*.
*/
/**
* @ingroup SObjSystem
* @defgroup SPrimitiveObjects Primitive Data Types Objects
* SObject functions for four primitive data types: ints, floats,
* strings, void*. Internally four new classes and* object types are
* created and inherit from #SObjectClass and #SObject.
*
* The classes and objects are:
* <ul>
* <li> @c SInt and SIntClass, </li>
* <li> @c SFloat and SFloatClass, </li>
* <li> @c SString and SStringClass, and </li>
* <li> @c SVoid and SVoidClass. </li>
* </ul>
*
* Although these classes exists and can be used in function
* calls, it is easier to use them as #SObject objects.
*
* SVoid and it's associated functions (#SObjectSetVoid,
* #SObjectResetVoid, #SObjectGetVoid) are used to
* encapsulate data structures so that they can be simply used as #SObject
* types. This enables the use/implementation of more complicated
* types (or even external object types that Speect does not need to
* know of).
* @{
*/
/************************************************************************************/
/* */
/* Modules used */
/* */
/************************************************************************************/
#include "include/common.h"
#include "base/utils/types.h"
#include "base/errdbg/errdbg.h"
#include "base/objsystem/object_def.h"
/************************************************************************************/
/* */
/* Begin external c declaration */
/* */
/************************************************************************************/
S_BEGIN_C_DECLS
/************************************************************************************/
/* */
/* Typedefs */
/* */
/************************************************************************************/
/**
* The SVoid SObject type free function typedef.
* A pointer to a function that frees the data of the SVoid type
* SObject void pointer.
*
* @param ptr The void type pointer data to free.
* @param error Error code.
*/
typedef void (*s_svoid_free_fp)(void *ptr, s_erc *error);
/************************************************************************************/
/* */
/* Function prototypes */
/* */
/************************************************************************************/
/**
* @name Integer
* @{
*/
/**
* Create a new SObject from a signed integer.
* @public @memberof SObject
*
* @param i The signed integer value.
* @param error Error code.
*
* @return Pointer to the newly created SObject (of type @c SInt).
*/
S_API SObject *SObjectSetInt(sint32 i, s_erc *error);
/**
* Change the data value (singed integer) of an SObject that has been
* previously created by #SObjectSetInt.
* @public @memberof SObject
*
* @param self The @c SInt type SObject.
* @param i The @a new signed integer value.
* @param error Error code.
*/
S_API void SObjectResetInt(SObject *self, sint32 i, s_erc *error);
/**
* Get the signed integer of the SObject object.
* @public @memberof SObject
*
* @param self The SObject (of type @c SInt).
* @param error Error code.
*
* @return The signed integer value.
*/
S_API sint32 SObjectGetInt(const SObject *self, s_erc *error);
/**
* @}
*/
/**
* @name Float
* @{
*/
/**
* Create a new SObject from a float.
* @public @memberof SObject
*
* @param f The float value.
* @param error Error code.
*
* @return Pointer to the newly created SObject (of type @c SFloat).
*/
S_API SObject *SObjectSetFloat(float f, s_erc *error);
/**
* Change the data value (float) of an SObject that has been
* previously created by #SObjectSetFloat.
* @public @memberof SObject
*
* @param self The @c SFloat type SObject.
* @param f The @a new float value.
* @param error Error code.
*/
S_API void SObjectResetFloat(SObject *self, float f, s_erc *error);
/**
* Get the float of the SObject object.
* @public @memberof SObject
*
* @param self The SObject (of type @c SFloat).
* @param error Error code.
*
* @return The float value.
*/
S_API float SObjectGetFloat(const SObject *self, s_erc *error);
/**
* @}
*/
/**
* @name String
* @{
*/
/**
* Create a new SObject from a character string.
* @public @memberof SObject
*
* @param s Pointer to the string.
* @param error Error code.
*
* @return Pointer to the newly created SObject (of type @c SString).
*
* @note The string is copied and not referenced.
*/
S_API SObject *SObjectSetString(const char *s, s_erc *error);
/**
* Change the data value (string) of an SObject that has been
* previously created by #SObjectSetString.
* @public @memberof SObject
*
* @param self The @c SString type SObject.
* @param s Pointer to the @a new string.
* @param error Error code.
*/
S_API void SObjectResetString(SObject *self, const char *s, s_erc *error);
/**
* Get the string of the SObject object.
* @public @memberof SObject
*
* @param self The SObject (of type @c SString).
* @param error Error code.
*
* @return Pointer to the string.
*/
S_API const char *SObjectGetString(const SObject *self, s_erc *error);
/**
* @}
*/
/**
* @name Void
* @{
*/
/**
* Create a new SObject from a void pointer.
* @public @memberof SObject
*
* @param ptr Pointer to the object.
* @param type_name An identifier for this void object type. Used for
* safety checks.
* @param free_func A callback function used to free the object.
* @param error Error code.
*
* @return Pointer to the newly created SObject.
*
* @note The @c type_name is copied and not referenced.
*/
S_API SObject *SObjectSetVoid(void *ptr, const char *type_name,
s_svoid_free_fp free_func,
s_erc *error);
/**
* Change the pointer of an SObject that has been
* previously created by #SObjectSetVoid.
* @public @memberof SObject
*
* @param self The SObject.
* @param ptr Pointer to the @a new object.
* @param type_name An identifier for this void object type. Used for
* safety checks.
* @param free_func A callback function used to free the
* object.
* @param error Error code.
*
* @note The @c type_name is copied and not referenced.
*/
S_API void SObjectResetVoid(SObject *self, void *ptr,
const char *type_name,
s_svoid_free_fp free_func,
s_erc *error);
/**
* Get the void pointer of the SObject object.
* @public @memberof SObject
*
* @param self The SObject.
* @param type_name An identifier for this void object type. Used for
* safety checks.
* @param error Error code.
*
* @return Void pointer.
*/
S_API const void *SObjectGetVoid(const SObject *self,
const char *type_name,
s_erc *error);
/**
* @}
*/
/**
* Add the SInt, SFloat, SString and SVoid classes to the object system.
* @private @memberof SObject
*
* @param error Error code.
*/
S_LOCAL void _s_primitive_class_add(s_erc *error);
/************************************************************************************/
/* */
/* End external c declaration */
/* */
/************************************************************************************/
S_END_C_DECLS
/**
* @}
* end documentation
*/
#endif /* _SPCT_PRIMITIVES_H__ */
| 37.566667 | 86 | 0.4513 |
0f935d32404e8afe9671fc34953fadefbe695543 | 415 | asm | Assembly | oeis/145/A145543.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/145/A145543.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/145/A145543.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A145543: Denominators in continued fraction expansion of sqrt(3/5).
; Submitted by Christian Krause
; 1,4,9,31,71,244,559,1921,4401,15124,34649,119071,272791,937444,2147679,7380481,16908641,58106404,133121449,457470751,1048062951,3601659604,8251382159,28355806081,64962994321,223244789044,511452572409,1757602506271,4026657584951
seq $0,41022 ; Numerators of continued fraction convergents to sqrt(15).
dif $0,3
| 59.285714 | 229 | 0.824096 |
1f92ef2000145cbb183aa016ee627031b2ae556c | 15,216 | html | HTML | v16.10.0/html/classwx_ex_statistics.html | antonvw/wxExtension-help | af3e72b4d33f6a61cd67e67054effb78e5daf318 | [
"MIT"
] | null | null | null | v16.10.0/html/classwx_ex_statistics.html | antonvw/wxExtension-help | af3e72b4d33f6a61cd67e67054effb78e5daf318 | [
"MIT"
] | null | null | null | v16.10.0/html/classwx_ex_statistics.html | antonvw/wxExtension-help | af3e72b4d33f6a61cd67e67054effb78e5daf318 | [
"MIT"
] | null | null | null | <!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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>wxExtension: wxExStatistics< T > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">wxExtension
 <span id="projectnumber">v16.10.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="classwx_ex_statistics-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">wxExStatistics< T > Class Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Offers base statistics.
<a href="classwx_ex_statistics.html#details">More...</a></p>
<p><code>#include <wx/extension/statistics.h></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:aaecfd57a4562097fad1cf65764bb05f7"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aaecfd57a4562097fad1cf65764bb05f7"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#aaecfd57a4562097fad1cf65764bb05f7">wxExStatistics</a> ()</td></tr>
<tr class="memdesc:aaecfd57a4562097fad1cf65764bb05f7"><td class="mdescLeft"> </td><td class="mdescRight">Default constructor. <br /></td></tr>
<tr class="separator:aaecfd57a4562097fad1cf65764bb05f7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2ef625a382ecd017b306c4904c7c2068"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2ef625a382ecd017b306c4904c7c2068"></a>
<a class="el" href="classwx_ex_statistics.html">wxExStatistics</a> & </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#a2ef625a382ecd017b306c4904c7c2068">operator+=</a> (const <a class="el" href="classwx_ex_statistics.html">wxExStatistics</a> &s)</td></tr>
<tr class="memdesc:a2ef625a382ecd017b306c4904c7c2068"><td class="mdescLeft"> </td><td class="mdescRight">Adds other statistics. <br /></td></tr>
<tr class="separator:a2ef625a382ecd017b306c4904c7c2068"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0e2a9f76ab2684ead3bfc603f1ea992a"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#a0e2a9f76ab2684ead3bfc603f1ea992a">Clear</a> ()</td></tr>
<tr class="memdesc:a0e2a9f76ab2684ead3bfc603f1ea992a"><td class="mdescLeft"> </td><td class="mdescRight">Clears the items. <a href="#a0e2a9f76ab2684ead3bfc603f1ea992a">More...</a><br /></td></tr>
<tr class="separator:a0e2a9f76ab2684ead3bfc603f1ea992a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0b2f9e717eebb56395d3f4f83f2c4b27"><td class="memItemLeft" align="right" valign="top">const wxString </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#a0b2f9e717eebb56395d3f4f83f2c4b27">Get</a> () const </td></tr>
<tr class="memdesc:a0b2f9e717eebb56395d3f4f83f2c4b27"><td class="mdescLeft"> </td><td class="mdescRight">Returns all items as a string. <a href="#a0b2f9e717eebb56395d3f4f83f2c4b27">More...</a><br /></td></tr>
<tr class="separator:a0b2f9e717eebb56395d3f4f83f2c4b27"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abb097fbf87da88002d03ebd3a6d74572"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abb097fbf87da88002d03ebd3a6d74572"></a>
const auto & </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#abb097fbf87da88002d03ebd3a6d74572">GetItems</a> () const </td></tr>
<tr class="memdesc:abb097fbf87da88002d03ebd3a6d74572"><td class="mdescLeft"> </td><td class="mdescRight">Returns the items. <br /></td></tr>
<tr class="separator:abb097fbf87da88002d03ebd3a6d74572"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6e3646a890a82cdf9103a7eb91fa33a1"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a6e3646a890a82cdf9103a7eb91fa33a1"></a>
const T </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#a6e3646a890a82cdf9103a7eb91fa33a1">Get</a> (const wxString &key) const </td></tr>
<tr class="memdesc:a6e3646a890a82cdf9103a7eb91fa33a1"><td class="mdescLeft"> </td><td class="mdescRight">Returns value for specified key. <br /></td></tr>
<tr class="separator:a6e3646a890a82cdf9103a7eb91fa33a1"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af007bf5968bf6b2d4ff2754a8f2cb76b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af007bf5968bf6b2d4ff2754a8f2cb76b"></a>
const T </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#af007bf5968bf6b2d4ff2754a8f2cb76b">Dec</a> (const wxString &key, T dec_value=1)</td></tr>
<tr class="memdesc:af007bf5968bf6b2d4ff2754a8f2cb76b"><td class="mdescLeft"> </td><td class="mdescRight">Decrements key with value. <br /></td></tr>
<tr class="separator:af007bf5968bf6b2d4ff2754a8f2cb76b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a93468d7e4a43ca9f7ad2f5a2539bceac"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a93468d7e4a43ca9f7ad2f5a2539bceac"></a>
const T </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#a93468d7e4a43ca9f7ad2f5a2539bceac">Inc</a> (const wxString &key, T inc_value=1)</td></tr>
<tr class="memdesc:a93468d7e4a43ca9f7ad2f5a2539bceac"><td class="mdescLeft"> </td><td class="mdescRight">Increments key with value. <br /></td></tr>
<tr class="separator:a93468d7e4a43ca9f7ad2f5a2539bceac"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab11330e3d4878f045433ebdc4afa0f65"><td class="memItemLeft" align="right" valign="top">const T </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#ab11330e3d4878f045433ebdc4afa0f65">Set</a> (const wxString &key, T value)</td></tr>
<tr class="memdesc:ab11330e3d4878f045433ebdc4afa0f65"><td class="mdescLeft"> </td><td class="mdescRight">Sets key to value. <a href="#ab11330e3d4878f045433ebdc4afa0f65">More...</a><br /></td></tr>
<tr class="separator:ab11330e3d4878f045433ebdc4afa0f65"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a228c75ba3fbb006c7315f5a26808c7ab"><td class="memItemLeft" align="right" valign="top"><a class="el" href="classwx_ex_grid.html">wxExGrid</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#a228c75ba3fbb006c7315f5a26808c7ab">Show</a> (wxWindow *parent, bool hide_row_labels=true, bool hide_col_labels=true, wxWindowID id=wxID_ANY)</td></tr>
<tr class="memdesc:a228c75ba3fbb006c7315f5a26808c7ab"><td class="mdescLeft"> </td><td class="mdescRight">Shows the statistics as a grid window on the parent, and specify whether to show row labels and col labels. <a href="#a228c75ba3fbb006c7315f5a26808c7ab">More...</a><br /></td></tr>
<tr class="separator:a228c75ba3fbb006c7315f5a26808c7ab"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a270d04e5ca522dfa0191574b8c0c3144"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a270d04e5ca522dfa0191574b8c0c3144"></a>
const <a class="el" href="classwx_ex_grid.html">wxExGrid</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classwx_ex_statistics.html#a270d04e5ca522dfa0191574b8c0c3144">GetGrid</a> () const </td></tr>
<tr class="memdesc:a270d04e5ca522dfa0191574b8c0c3144"><td class="mdescLeft"> </td><td class="mdescRight">Access to the grid, returns nullptr if the grid has not been shown yet. <br /></td></tr>
<tr class="separator:a270d04e5ca522dfa0191574b8c0c3144"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><h3>template<class T><br />
class wxExStatistics< T ></h3>
<p>Offers base statistics. </p>
<p>All statistics involve a key value pair, where the key is a wxString, and the value a template. The statistics can be shown on a grid, that is automatically updated whenever statistics change. </p>
</div><h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="a0e2a9f76ab2684ead3bfc603f1ea992a"></a>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<class T> </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">void <a class="el" href="classwx_ex_statistics.html">wxExStatistics</a>< T >::Clear </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Clears the items. </p>
<p>If you have Shown the statistics the window is updated as well. </p>
</div>
</div>
<a class="anchor" id="a0b2f9e717eebb56395d3f4f83f2c4b27"></a>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<class T> </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">const wxString <a class="el" href="classwx_ex_statistics.html">wxExStatistics</a>< T >::Get </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Returns all items as a string. </p>
<p>All items are returned as a string, with comma's separating items, and a : separating key and value. </p>
</div>
</div>
<a class="anchor" id="ab11330e3d4878f045433ebdc4afa0f65"></a>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<class T> </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">const T <a class="el" href="classwx_ex_statistics.html">wxExStatistics</a>< T >::Set </td>
<td>(</td>
<td class="paramtype">const wxString & </td>
<td class="paramname"><em>key</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">T </td>
<td class="paramname"><em>value</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Sets key to value. </p>
<p>If you have Shown the statistics the window is updated as well. </p>
</div>
</div>
<a class="anchor" id="a228c75ba3fbb006c7315f5a26808c7ab"></a>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<class T> </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classwx_ex_grid.html">wxExGrid</a>* <a class="el" href="classwx_ex_statistics.html">wxExStatistics</a>< T >::Show </td>
<td>(</td>
<td class="paramtype">wxWindow * </td>
<td class="paramname"><em>parent</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>hide_row_labels</em> = <code>true</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>hide_col_labels</em> = <code>true</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">wxWindowID </td>
<td class="paramname"><em>id</em> = <code>wxID_ANY</code> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Shows the statistics as a grid window on the parent, and specify whether to show row labels and col labels. </p>
<p>Returns the window that is created, or is activated, if it already was created. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">parent</td><td>the parent for the grid </td></tr>
<tr><td class="paramname">hide_row_labels</td><td>show row labels (i.e. row numbers) </td></tr>
<tr><td class="paramname">hide_col_labels</td><td>show col labels (Item, Value) </td></tr>
<tr><td class="paramname">id</td><td>the id of the grid component </td></tr>
</table>
</dd>
</dl>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| 55.532847 | 410 | 0.675605 |
7f7c79c522ffe2d476329ad8f0727a6896d62344 | 70 | rs | Rust | src/transfer/mod.rs | vyomkeshj/hyperqueue | 24d367c9f6b9d690a25ec01e59a4db053e3d533a | [
"MIT"
] | null | null | null | src/transfer/mod.rs | vyomkeshj/hyperqueue | 24d367c9f6b9d690a25ec01e59a4db053e3d533a | [
"MIT"
] | null | null | null | src/transfer/mod.rs | vyomkeshj/hyperqueue | 24d367c9f6b9d690a25ec01e59a4db053e3d533a | [
"MIT"
] | null | null | null | pub mod auth;
pub mod connection;
pub mod messages;
pub mod protocol;
| 14 | 19 | 0.771429 |
5fdfc30f203612eb8e922c2fe8f4f676dd612461 | 1,912 | h | C | 1.28.0/gnustep-base-1.28.0/Headers/Foundation/NSErrorRecoveryAttempting.h | mlcldh/GNUstepBase | 21ec741298079662afead20514069daf3b5a6c41 | [
"MIT"
] | 5 | 2022-01-08T08:05:58.000Z | 2022-01-11T03:29:09.000Z | notification/libs-base-master/Headers/Foundation/NSErrorRecoveryAttempting.h | barry-source/tips | 29374cfdf8e713bd03aecffc5f48fd8d1652433d | [
"MIT"
] | null | null | null | notification/libs-base-master/Headers/Foundation/NSErrorRecoveryAttempting.h | barry-source/tips | 29374cfdf8e713bd03aecffc5f48fd8d1652433d | [
"MIT"
] | 1 | 2022-03-20T01:15:17.000Z | 2022-03-20T01:15:17.000Z | /** Interface for NSErrorRecoveryAttempting for GNUStep
Copyright (C) 2007 Free Software Foundation, Inc.
Written by: Fred Kiefer <fredkiefer@gmx.de>
Date: July 2007
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
*/
#ifndef __NSErrorRecoveryAttempting_h_GNUSTEP_BASE_INCLUDE
#define __NSErrorRecoveryAttempting_h_GNUSTEP_BASE_INCLUDE
#import <GNUstepBase/GSVersionMacros.h>
#if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST)
#import <Foundation/NSObject.h>
#if defined(__cplusplus)
extern "C" {
#endif
/**
* These methods define the informal error recovery protocol
*/
@interface NSObject (NSErrorRecoveryAttempting)
- (BOOL) attemptRecoveryFromError: (NSError*)error
optionIndex: (unsigned int)recoveryOptionIndex;
- (void) attemptRecoveryFromError: (NSError*)error
optionIndex: (unsigned int)recoveryOptionIndex
delegate: (id)delegate
didRecoverSelector: (SEL)didRecoverSelector
contextInfo: (void*)contextInfo;
@end
#if defined(__cplusplus)
}
#endif
#endif
#endif /* __NSErrorRecoveryAttempting_h_GNUSTEP_BASE_INCLUDE*/
| 31.866667 | 69 | 0.733787 |
5885a8ba4e3275ce40998514b7f907534e6ae8e4 | 881 | swift | Swift | SinaProject/SinaProject/Classes/Other/Category/UIButton-Button.swift | fcgIsPioneer/SinaProject_swift3 | 5d43628776f73797073eb8b1b57ab86f837c1fc5 | [
"Apache-2.0"
] | null | null | null | SinaProject/SinaProject/Classes/Other/Category/UIButton-Button.swift | fcgIsPioneer/SinaProject_swift3 | 5d43628776f73797073eb8b1b57ab86f837c1fc5 | [
"Apache-2.0"
] | null | null | null | SinaProject/SinaProject/Classes/Other/Category/UIButton-Button.swift | fcgIsPioneer/SinaProject_swift3 | 5d43628776f73797073eb8b1b57ab86f837c1fc5 | [
"Apache-2.0"
] | null | null | null | //
// UIButton-Button.swift
// SinaProject
//
// Created by FCG on 2017/1/18.
// Copyright © 2017年 FCG. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(imageName : String, bgImageName : String) {
self.init()
setImage(UIImage(named: imageName), for: .normal)
setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted)
setBackgroundImage(UIImage(named: bgImageName), for: .normal)
setBackgroundImage(UIImage(named: bgImageName + "_highlighted"), for: .highlighted)
sizeToFit()
}
convenience init(btnTitle : String, bgColor : UIColor, fontSize : CGFloat) {
self.init()
setTitle(btnTitle, for: .normal)
titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
backgroundColor = bgColor
}
}
| 25.911765 | 91 | 0.61748 |
cb4e4e724f8318bcb542a341b3d7786fa6366b53 | 431 | h | C | include/icarus_rover_rc/Mapping_Node.h | dgitz/icarus_rover_rc | 2ec789d7757715d71fc6ec4ce90e15fdc8053f3e | [
"MIT"
] | null | null | null | include/icarus_rover_rc/Mapping_Node.h | dgitz/icarus_rover_rc | 2ec789d7757715d71fc6ec4ce90e15fdc8053f3e | [
"MIT"
] | null | null | null | include/icarus_rover_rc/Mapping_Node.h | dgitz/icarus_rover_rc | 2ec789d7757715d71fc6ec4ce90e15fdc8053f3e | [
"MIT"
] | null | null | null | #ifndef __MAPPINGNODE_INCLUDED__
#define __MAPPINGNODE_INCLUDED__
struct grid_cell{
int index;
int x; //Grid coordinates
int y; //Grid coordinates
double X; //Real-world coordinates, Meters
double Y; //Real-world coordinates, Meters
int status; //1 if it is updated, 0 if not.
};
int get_index_from_cell(int x, int y);
grid_cell find_cell(grid_cell mycell, grid_cell map_origin,double X, double Y, int value);
#endif | 30.785714 | 90 | 0.75406 |
716b0ad9da32f810bf72706bf05c0651a080642c | 727 | tsx | TypeScript | packages/web/src/Components/IconButton/IconButton.tsx | tomkiel/natds-js | d376db863477cdda34cb93391c17fc36ae7ec449 | [
"ISC"
] | 34 | 2020-01-09T16:48:59.000Z | 2022-02-08T13:49:06.000Z | packages/web/src/Components/IconButton/IconButton.tsx | tomkiel/natds-js | d376db863477cdda34cb93391c17fc36ae7ec449 | [
"ISC"
] | 1,116 | 2019-12-06T19:47:54.000Z | 2022-03-25T20:23:49.000Z | packages/web/src/Components/IconButton/IconButton.tsx | tomkiel/natds-js | d376db863477cdda34cb93391c17fc36ae7ec449 | [
"ISC"
] | 11 | 2020-05-13T20:13:28.000Z | 2022-01-31T17:58:17.000Z | import * as React from 'react'
import MaterialIconButton from '@material-ui/core/IconButton'
import { IIconButtonProps } from './IconButton.props'
export { IIconButtonProps } from './IconButton.props'
/**
* For advanced usages, check [Material UI IconButton docs](https://material-ui.com/components/buttons/#icon-buttons)
*
* ## Importing
*
* ```jsx
* import { IconButton } from '@naturacosmeticos/natds-web';
* ```
*
* @see https://material-ui.com/components/buttons/#icon-buttons
*/
export const IconButton = React.forwardRef<HTMLButtonElement, IIconButtonProps>(
(props: IIconButtonProps, ref) => <MaterialIconButton {...props} ref={ref} />
)
IconButton.displayName = 'IconButton'
export default IconButton
| 27.961538 | 117 | 0.727648 |
915d7622ca8e6d3bf03950c92178823ee3b6a1aa | 206 | lua | Lua | xdg/neovim/lua/plugins/movement/init.lua | chaoticmurder/dotfiles | a3ff0d918885c525301ff296246018643be004f8 | [
"MIT"
] | null | null | null | xdg/neovim/lua/plugins/movement/init.lua | chaoticmurder/dotfiles | a3ff0d918885c525301ff296246018643be004f8 | [
"MIT"
] | null | null | null | xdg/neovim/lua/plugins/movement/init.lua | chaoticmurder/dotfiles | a3ff0d918885c525301ff296246018643be004f8 | [
"MIT"
] | null | null | null | return {'ggandor/lightspeed.nvim', opt = true,
keys = {
's',
'S',
'f',
'F',
't',
'T',
},
config = function ()
require('plugins.movement.config')
end
}
| 13.733333 | 46 | 0.432039 |
6be97d669e119ebbfe79ef75996bf0c88f26bf9e | 582 | asm | Assembly | oeis/002/A002279.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/002/A002279.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/002/A002279.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A002279: a(n) = 5*(10^n - 1)/9.
; 0,5,55,555,5555,55555,555555,5555555,55555555,555555555,5555555555,55555555555,555555555555,5555555555555,55555555555555,555555555555555,5555555555555555,55555555555555555,555555555555555555,5555555555555555555,55555555555555555555,555555555555555555555,5555555555555555555555,55555555555555555555555,555555555555555555555555,5555555555555555555555555,55555555555555555555555555,555555555555555555555555555,5555555555555555555555555555,55555555555555555555555555555,555555555555555555555555555555
mov $1,10
pow $1,$0
div $1,9
mul $1,5
mov $0,$1
| 64.666667 | 498 | 0.871134 |
a119c054223f5094fe046e90686c8c9efede0abe | 2,581 | go | Go | webInterface.go | igiant/control | 6d0e04fe6f34b1603482fd5c100f38659cc1b113 | [
"MIT"
] | null | null | null | webInterface.go | igiant/control | 6d0e04fe6f34b1603482fd5c100f38659cc1b113 | [
"MIT"
] | null | null | null | webInterface.go | igiant/control | 6d0e04fe6f34b1603482fd5c100f38659cc1b113 | [
"MIT"
] | null | null | null | package control
import "encoding/json"
// Certificates (Secured Web Interface and SSL-VPN) will be handled by CertificateManager
// SslVpnConfig - not applicable on Linux
type SslVpnConfig struct {
Enabled bool `json:"enabled"`
Port int `json:"port"`
Certificate IdReference `json:"certificate"`
}
type CustomizedBrand struct {
Enabled bool `json:"enabled"`
PageTitle string `json:"pageTitle"`
}
type WebInterfaceConfig struct {
UseSsl bool `json:"useSsl"`
SslConfig SslVpnConfig `json:"sslConfig"`
Hostname OptionalString `json:"hostname"`
DetectedHostname string `json:"detectedHostname"`
AdminPath string `json:"adminPath"`
Port int `json:"port"`
SslPort int `json:"sslPort"`
Certificate IdReference `json:"certificate"`
CustomizedBrand CustomizedBrand `json:"customizedBrand"`
}
// WebInterfaceGet - Returns actual values for Web Interface and Kerio Clientless SSL-VPN configuration in WebAdmin
func (s *ServerConnection) WebInterfaceGet() (*WebInterfaceConfig, error) {
data, err := s.CallRaw("WebInterface.get", nil)
if err != nil {
return nil, err
}
config := struct {
Result struct {
Config WebInterfaceConfig `json:"config"`
} `json:"result"`
}{}
err = json.Unmarshal(data, &config)
return &config.Result.Config, err
}
// WebInterfaceSet - Stores configuration
// config - structure with settings for webinterface module
// revertTimeout - If client doesn't confirm config to this timeout, configuration is reverted (0 - revert disabled)
func (s *ServerConnection) WebInterfaceSet(config WebInterfaceConfig, revertTimeout int) error {
params := struct {
Config WebInterfaceConfig `json:"config"`
RevertTimeout int `json:"revertTimeout"`
}{config, revertTimeout}
_, err := s.CallRaw("WebInterface.set", params)
return err
}
// WebInterfaceUploadImage - Uploaded image which will need to be apply/reset
// fileId - according to spec 390.
// isFavicon - true = the image is favicon, false = the image is product logo
func (s *ServerConnection) WebInterfaceUploadImage(fileId string, isFavicon bool) error {
params := struct {
FileId string `json:"fileId"`
IsFavicon bool `json:"isFavicon"`
}{fileId, isFavicon}
_, err := s.CallRaw("WebInterface.uploadImage", params)
return err
}
// WebInterfaceReset - Discard uploaded images
func (s *ServerConnection) WebInterfaceReset() error {
_, err := s.CallRaw("WebInterface.reset", nil)
return err
}
| 34.878378 | 116 | 0.698566 |
e9c500766a485901c6b3ea40101c027387344626 | 5,305 | lua | Lua | lua/weapons/gmod_tool/stools/commandbox.lua | Lexicality/Lexical-Tools | fbc0677f48f82b8423a8300202261496640ea91c | [
"Apache-2.0"
] | 5 | 2015-10-31T12:06:31.000Z | 2022-01-10T17:55:34.000Z | lua/weapons/gmod_tool/stools/commandbox.lua | Lexicality/Lexical-Tools | fbc0677f48f82b8423a8300202261496640ea91c | [
"Apache-2.0"
] | 21 | 2015-09-19T20:37:20.000Z | 2022-03-11T15:51:12.000Z | lua/weapons/gmod_tool/stools/commandbox.lua | Lexicality/Lexical-Tools | fbc0677f48f82b8423a8300202261496640ea91c | [
"Apache-2.0"
] | 8 | 2015-11-01T17:31:41.000Z | 2020-12-24T16:03:43.000Z | --[[
Lexical Tools - lua\weapons\gmod_tool\stools\commandbox.lua
Copyright 2010-2013 Lex Robinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]] --
TOOL.Category = "Lexical Tools"
TOOL.Name = "#Command Box"
-- Bits of commands that aren't allowed to be sent
local disallowed = {
"bind",
"quit",
"quti",
"exit",
"ent_fire",
"rcon",
"cl_",
"net_",
"mat_",
"r_",
"g_",
"disconnect",
"alias",
"name",
}
TOOL.ClientConVar["model"] = "models/props_lab/reciever01a.mdl"
TOOL.ClientConVar["command"] = ""
TOOL.ClientConVar["key"] = "5"
cleanup.Register("commandboxes")
function TOOL:UpdateGhost(ent, ply) -- ( ent, player )
if (not IsValid(ent)) then
return
end
local tr = ply:GetEyeTrace()
if (not tr.Hit or (IsValid(tr.Entity) and
(tr.Entity:IsPlayer() or tr.Entity:GetClass() == "gmod_commandbox"))) then
ent:SetNoDraw(true)
return
end
local angles = tr.HitNormal:Angle()
angles.pitch = angles.pitch + 90
ent:SetAngles(angles)
ent:SetPos(tr.HitPos - tr.HitNormal * ent:OBBMins().z)
ent:SetNoDraw(false)
end
function TOOL:Think()
if (SERVER and not game.SinglePlayer()) then
return
end
if (CLIENT and game.SinglePlayer()) then
return
end
local ent = self.GhostEntity
local model = string.lower(self:GetClientInfo("model"))
if (not (IsValid(ent) and ent:GetModel() == model)) then
self:MakeGhostEntity(model, vector_origin, Angle())
end
self:UpdateGhost(self.GhostEntity, self:GetOwner())
end
list.Set("CommandboxModels", "models/props_lab/reciever01a.mdl", {})
list.Set("CommandboxModels", "models/props_lab/monitor02.mdl", {})
local function canTool(tr)
return tr.Hit and tr.HitWorld or
(IsValid(tr.Entity) and not tr.Entity:IsPlayer())
end
if (CLIENT) then
local messages = {
"Commands cannot include the word '",
"Updated Command Box",
"Created Command Box",
}
usermessage.Hook("CommandBoxMessage", function(um)
local message = um:ReadShort()
if (message == 1) then
local word = um:ReadShort()
message = messages[message] .. disallowed[word] .. "'!"
else
message = messages[message]
end
GAMEMODE:AddNotify(message, NOTIFY_GENERIC, 10)
surface.PlaySound("ambient/water/drip" .. math.random(1, 4) .. ".wav")
end)
language.Add("Tool_commandbox_name", "Command Box Tool")
language.Add("Tool_commandbox_desc",
"Allows you to assign concommands to numpad keys.")
language.Add("Tool_commandbox_0", "Left click to spawn a Command Box")
-- Other
language.Add("Undone_commandbox", "Undone Command Box")
language.Add("SBoxLimit_commandboxes", "You've hit the Command Boxes limit!")
language.Add("Cleanup_commandboxes", "Command Boxes")
language.Add("Cleaned_commandboxes", "Cleaned up all Command Boxes")
TOOL.LeftClick = canTool
function TOOL.BuildCPanel(cp)
cp:AddControl("Header", {
Text = "#Tool_commandbox_name",
Description = "#Tool_commandbox_desc",
})
cp:AddControl("PropSelect", {
Label = "Model:",
ConVar = "commandbox_model",
Category = "Models",
Models = list.Get("CommandboxModels"),
})
cp:AddControl("Numpad",
{Label = "Key:", Command = "commandbox_key", ButtonSize = 22})
cp:AddControl("TextBox", {
Label = "Command",
MaxLength = "255",
Command = "commandbox_command",
})
end
return
end
umsg.PoolString("CommandBoxMessage")
CreateConVar("sbox_maxcommandboxes", 10, FCVAR_NOTIFY)
local function msg(ply, num, num2)
umsg.Start("CommandBoxMessage", ply)
umsg.Short(num)
if (num2) then
umsg.Short(num2)
end
umsg.End()
end
function TOOL:LeftClick(tr)
if (not canTool(tr)) then
return false
end
local ply = self:GetOwner()
local model, command, key
key = self:GetClientNumber("key")
model = self:GetClientInfo("model")
command = self:GetClientInfo("command")
local search = string.lower(command)
for i, words in pairs(disallowed) do
if (string.find(search, words)) then
msg(ply, 1, i)
return false
end
end
local ent = tr.Entity
if (IsValid(ent) and ent:GetClass() == "gmod_commandbox" and ent:GetPlayer() ==
ply) then
ent:SetCommand(command)
ent:SetKey(key)
msg(ply, 2)
return true
end
local angles = tr.HitNormal:Angle()
angles.pitch = angles.pitch + 90
local box = MakeCommandBox(ply, tr.HitPos, angles, model, key, command)
if (not box) then
return false
end
box:SetPos(tr.HitPos - tr.HitNormal * box:OBBMins().z)
local weld
if (IsValid(ent) and not ent:IsWorld()) then
weld = constraint.Weld(box, ent, 0, tr.PhysicsBone, 0)
ent:DeleteOnRemove(box)
else
local phys = box:GetPhysicsObject()
if (IsValid(phys)) then
phys:EnableMotion(false)
end
end
undo.Create("commandbox")
undo.AddEntity(box)
undo.AddEntity(weld)
undo.SetPlayer(ply)
undo.Finish()
ply:AddCleanup("commandboxes", box)
ply:AddCleanup("commandboxes", weld)
msg(ply, 3)
return true
end
| 25.628019 | 80 | 0.707257 |
a40ae1c4103f01ac16e72de5e0b7e1da76d974a3 | 3,280 | kt | Kotlin | app/src/test/java/com/cliffracertech/bootycrate/BottomNavigationDrawerTests.kt | NicholasHochstetler/StuffCrate | 5b429d0528c902b852f47bc8759d3cd75c2d29f7 | [
"Apache-2.0"
] | 15 | 2021-09-12T14:48:25.000Z | 2022-01-29T17:37:13.000Z | app/src/test/java/com/cliffracertech/bootycrate/BottomNavigationDrawerTests.kt | NicholasHochstetler/BootyCrate | 5b429d0528c902b852f47bc8759d3cd75c2d29f7 | [
"Apache-2.0"
] | null | null | null | app/src/test/java/com/cliffracertech/bootycrate/BottomNavigationDrawerTests.kt | NicholasHochstetler/BootyCrate | 5b429d0528c902b852f47bc8759d3cd75c2d29f7 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 Nicholas Hochstetler
* You may not use this file except in compliance with the Apache License
* Version 2.0, obtainable at http://www.apache.org/licenses/LICENSE-2.0
* or in the file LICENSE in the project's root directory. */
package com.cliffracertech.bootycrate
import android.content.Context
import android.graphics.Rect
import androidx.core.view.doOnNextLayout
import androidx.fragment.app.FragmentActivity
import androidx.test.core.app.ApplicationProvider
import com.cliffracertech.bootycrate.utils.dpToPixels
import com.cliffracertech.bootycrate.view.BottomNavigationDrawer
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class BottomNavigationDrawerTests {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val rect = Rect()
//private lateinit var instance: BottomNavigationDrawer
//private fun waitForAnimationsToFinish() = Shadows.shadowOf(Looper.getMainLooper()).idle()
private fun instance(vararg attrs: Pair<Int, String>): BottomNavigationDrawer {
val activity = Robolectric.buildActivity(FragmentActivity::class.java).create().get()
val attrSet = Robolectric.buildAttributeSet()
for (attr in attrs)
attrSet.addAttribute(attr.first, attr.second)
return BottomNavigationDrawer(activity, attrSet.build())
}
@Test fun initialPeekHeight() {
instance(Pair(R.attr.behavior_peekHeight, "50dp")).doOnNextLayout {
it.getHitRect(rect)
assertThat(rect.height()).isEqualTo(context.resources.dpToPixels(50f))
}
}
@Test fun expandedHeight() {
instance().doOnNextLayout {
(it as BottomNavigationDrawer).expand()
it.getHitRect(rect)
assertThat(rect.height()).isEqualTo(it.height)
}
}
@Test fun isHideableXMLvalues() {
var instance = instance()
assertThat(instance.isHideable).isEqualTo(BottomNavigationDrawer.IsHideable.Yes)
for (value in BottomNavigationDrawer.IsHideable.values()) {
instance = instance(Pair(R.attr.isHideable, value.ordinal.toString()))
assertThat(instance.isHideable).isEqualTo(value)
}
}
@Test fun expandCollapseHideShow() {
val instance = instance()
assertThat(instance.isCollapsed).isTrue()
instance.expand()
assertThat(instance.isExpanded).isTrue()
instance.collapse()
assertThat(instance.isCollapsed).isTrue()
instance.hide()
assertThat(instance.isHidden).isTrue()
instance.show()
assertThat(instance.isHidden).isFalse()
assertThat(instance.isCollapsed).isTrue()
}
@Test fun isHideableValues() {
var instance = instance(Pair(R.attr.isHideable, BottomNavigationDrawer.IsHideable.No.ordinal.toString()))
instance.hide()
assertThat(instance.isHidden).isFalse()
instance = instance(Pair(R.attr.isHideable, BottomNavigationDrawer.IsHideable.OnlyByApp.ordinal.toString()))
instance.hide()
assertThat(instance.isHidden).isTrue()
}
} | 37.701149 | 116 | 0.7125 |
e7287ff349655a82ba3d12ca8219a3e017c28a95 | 17,031 | js | JavaScript | scripts/jquery.seven20.grid.js | unhosted/seven20 | 7d9ebb100f805b3bcbcc43276048dd4092df6a84 | [
"Unlicense"
] | null | null | null | scripts/jquery.seven20.grid.js | unhosted/seven20 | 7d9ebb100f805b3bcbcc43276048dd4092df6a84 | [
"Unlicense"
] | 1 | 2017-07-04T14:55:31.000Z | 2017-07-04T14:55:31.000Z | scripts/jquery.seven20.grid.js | unhosted/seven20 | 7d9ebb100f805b3bcbcc43276048dd4092df6a84 | [
"Unlicense"
] | null | null | null | (function ($) {
$.fn.seven20Grid = function (options) {
var defaultOptions =
{
"contentType": '',
'dataPath': '',
'dataName': '',
'gridSelector': '#gridUI',
'outerContainerSelector': '#grid-inner-container',
'innerContainerSelector': '#grid-inner-container .grid-items-list',
'gridItemSelector': '.grid-items-list',
'buildViewer': true,
'timer': '',
'filter': '',
'downKey': 40,
'upKey': 38,
'selectKey': 32,
'deleteKey': 46,
'completeKey': 35,
'editButtons': null,
'globalButtonNames': ["refresh", "add"],
'globalButtonIcons': ["refresh", "plus"],
'editButtonNames': ["share", "edit", "publish", "archive", "delete"],
'editButtonIcons': ["share", "edit", "globe", "inbox", "trash"],
'viewerTemplate': '<div id="viewer" class="well grid-height span3"><div class="slide-left-button"><i class="icon-chevron-right"></i></div><h2><span class="view-path"></span></h2></spab><div id="view-items-list" class=""></div></div>',
'gridTemplate': '<div id="grid" class="well grid-width span3"><div id="grid-inner-container" class="grid-width"><div class="grid-control-bar grid-width"><div class="control-group grid-width"><div class="left-padding"></div><div class="input-prepend input-append" style="display: inline-block;"><input type="checkbox" class="selectall"><input type="text" rows="30" id="filterText" class="input-medium"><a class="btn filter-button" href="#" data-original-title="Filter"><i class="icon-filter"></i></a></div><div class="global-buttons"></div><div class="edit-buttons"></div></div></div><div class="error-message"></div><table class="grid-items-list grid-width"></table></div></div>',
'barButtonHtml': '<a class="btn ##name##-button" href="#" data-original-title="##tip##"><i class="icon-##icon##"></i></a>',
'grid_item_html': '<tr class="grid-item grid-item-bar" ##data##><td class="left-padding"></td><td class="checkbox"><input type="checkbox" class="checkbox" /></td><td class="grid-item-content-area">##item-html##</td></tr>',
'grid_item_data_html': '<td class="grid-item-left-tag-area"><td class="id-tag">##id##</td></td><td class="grid-item-title-area">##display##</td><td class="grid-item-date-area">##@type##</td>',
'viewTemplate1': '<div class="view-row"><div class="view-name">',
'viewTemplate2': '</div><div class="view-value">',
'viewTemplate3': '</div></div>',
'arrowHTML': '<div class="selected-item"></div>'
};
var o = $.extend(defaultOptions, options);
return this.each(function () {
var $t = $(this);
function init() {
buildGrid();
if(o.buildViewer)
buildViewer();
if(o.dataPath !== '')
LoadData();
var editButtonSelector = configureButtons();
o.editButtons = $t.find(editButtonSelector);
o.editButtons.hide();
configureButtonEvents();
configureCheckboxes($t);
configureGridItemClick();
}
function showLoadingAnimation() {
$(o.innerContainerSelector).html('<div class="loading-results">Loading Results</div>');
}
$.fn.seven20Grid.insert = function(data, id) {
insertRow(data, id);
}
$.fn.seven20Grid.clear = function(data, id) {
$(o.innerContainerSelector).html('');
}
$.fn.seven20Grid.getSelectedItems = function() {
return getSelectedItems();
}
$.fn.seven20Grid.setDataPath = function(dataPath) {
o.dataPath = dataPath;
$('#viewer').find('span.view-path').html(o.dataPath);
$('#viewer').find('#view-items-list').html('');
}
function insertRow(item, id) {
var item_html = o.grid_item_data_html;
var data_html = '';
var complete_html = o.grid_item_html;
var count = 0;
for (var key in item) {
item_html = item_html.replace('##' + key + '##', item[key]);
data_html += ' data-' + key + '="' + item[key] + '"';
}
item_html = item_html.replace('##id##', id);
complete_html = complete_html.replace('##item-html##',item_html).replace('##data##', data_html);
$(o.innerContainerSelector).append(complete_html);
}
function LoadData() {
$('#viewer').find('span.view-path').html(o.dataPath);
var data = remoteStorage.root.getListing(o.dataPath);
if(data.length == 0)
$(o.innerContainerSelector).html('<div class="no-data">No Data To Show</div>');
else
$(o.innerContainerSelector).html('');
for(i = 0; i < data.length; ++i){
if(data[i].substr(-1) != '/')
insertRow(remoteStorage.root.getObject(o.dataPath + data[i]),o.dataPath + data[i]);
}
}
function buildViewer() {
$(o.gridSelector).append(o.viewerTemplate);
$t.find('.slide-left-button').bind('click', function () {
$(this).parent().slideRight();
});
}
function buildGrid() {
$(o.gridSelector).append(o.gridTemplate);
}
function addCreatorItem() {
addEditorItem();
}
function getRowID(row){
var dataHolder = $(row).parent().parent();
var itemID = dataHolder.find('.id-tag').html();
return itemID;
}
function editItems(selectedItems) {
$.each(selectedItems, function (i, item) {
var itemID = getRowID(item);
addEditorItem(itemID, $(item).parent().parent().data());
});
}
function publishItems(selectedItems) {
$.each(selectedItems, function (i, item) {
var itemID = getRowID(item);
var message = remoteStorage.root.publishObject(itemID);
showMessage(message, 'Publish successful');
});
}
function archiveItems(selectedItems) {
$.each(selectedItems, function (i, item) {
var itemID = getRowID(item);
var message = remoteStorage.root.archiveObject(itemID);
showMessage('Archived record at _id=' + itemID, 'Archive Successful');
});
}
function deleteItems(selectedItems) {
$.each(selectedItems, function (i, item) {
var itemID = getRowID(item);
remoteStorage.root.removeObject(itemID);
showMessage('Deleted record at _id=' + itemID,'Delete Successful');
});
}
function addEditorItem(id, data) {
$('#viewer').seven20Editor({contentId:id, data:data, target:'#viewer', contentName:o.dataPath});
}
function configureCheckboxes() {
$t.find('.selectall').bind('click', function () {
if ($(this).is(':checked')) {
$(o.gridItemSelector).find(':checkbox:not(:checked)').attr('checked', 'checked').change();
//enableGridButtons();
} else {
$(o.gridItemSelector).find(':checkbox:checked').removeAttr('checked').change();
//disableGridButtons();
}
});
// Turn item bar yellow on checkbox click
$(o.gridItemSelector).delegate(':checkbox', 'change', function () {
if ($(this).is(':checked')) {
$(this).parents('.grid-item').addClass('checked-grid-item-bar');
enableGridButtons();
} else {
$(this).parents('.grid-item').removeClass('checked-grid-item-bar');
if ($(o.gridItemSelector).find(":checked").length === 0) {
// Make complete and delete item buttons look disabled
disableGridButtons();
}
}
});
}
function configureButtons() {
var editButtonSelector = "";
var globalButtonSelector = "";
// Create the global buttons
for (var i in o.globalButtonNames) {
globalButtonSelector += ", ." + o.globalButtonNames[i] + "-button";
var globalButtonHtml = o.barButtonHtml;
var camelName = o.globalButtonNames[i][0] = o.globalButtonNames[i][0].toUpperCase();
if (o.globalButtonNames[i].length > 1)
camelName += o.globalButtonNames[i].substr(1, o.globalButtonNames[i].length);
globalButtonHtml = globalButtonHtml.replace(/##name##/, o.globalButtonNames[i]);
globalButtonHtml = globalButtonHtml.replace(/##icon##/, o.globalButtonIcons[i]);
globalButtonHtml = globalButtonHtml.replace(/##tip##/, camelName);
$t.find('.global-buttons').append(globalButtonHtml);
}
globalButtonSelector = globalButtonSelector.replace(",", "");
// Create the edit buttons
for (var i in o.editButtonNames) {
editButtonSelector += ", ." + o.editButtonNames[i] + "-button";
var editButtonHtml = o.barButtonHtml;
var camelName = o.editButtonNames[i][0] = o.editButtonNames[i][0].toUpperCase();
if (o.editButtonNames[i].length > 1)
camelName += o.editButtonNames[i].substr(1, o.editButtonNames[i].length);
editButtonHtml = editButtonHtml.replace(/##name##/, o.editButtonNames[i]);
editButtonHtml = editButtonHtml.replace(/##icon##/, o.editButtonIcons[i]);;
editButtonHtml = editButtonHtml.replace(/##tip##/, camelName);
$t.find('.edit-buttons').append(editButtonHtml);
}
editButtonSelector = editButtonSelector.replace(",", "");
$(editButtonSelector).tooltip({ placement: 'bottom' });
$(globalButtonSelector).tooltip({ placement: 'bottom' });
$('.filter-button').tooltip({ placement: 'bottom' });
return editButtonSelector;
}
function configureButtonEvents() {
// Refresh the grid results
$t.find('.refresh-button').bind('click', function () {
$(this).parent().parent().find('#filterText').val('');
LoadData();
});
$("#filterText").keyup(function (event) {
if (event.keyCode == 13) {
$("div.filter-button").click();
}
});
// Add an item
$t.find('.add-button').bind('click', function () {
addCreatorItem();
});
// Edit the selected items
$t.find('.edit-button').bind('click', function () {
var selectedItems = getSelectedItems();
editItems(selectedItems);
removeItems(selectedItems);
disableGridButtons();
});
// Delete the selected items
$t.find('.delete-button').bind('click', function () {
deleteItems(getSelectedItems());
clearCheckedItems(' items moved to trash', false);
disableGridButtons();
});
// Complete the selected item
$t.find('.archive-button').bind('click', function () {
var selectedItems = getSelectedItems();
archiveItems(selectedItems);
clearCheckedItems(' items archived', true);
disableGridButtons();
});
// Complete the selected item
$t.find('.publish-button').bind('click', function () {
var selectedItems = getSelectedItems();
publishItems(selectedItems);
clearCheckedItems(' items published', true);
disableGridButtons();
});
$t.find('.filter-button').bind('click', function () {
var filter = $(this).parent().find('#filterText').val();
if (filter == o.filter) {
return;
}
if (filter === "") {
$(o.gridItemSelector).find('.grid-item').show();
return;
}
o.filter = filter;
filterItems(o.filter);
});
}
function configureGridItemClick() {
// Add click event to the grid item content area for viewing the item
$(o.gridItemSelector).delegate('.grid-item.grid-item-bar', 'click', function () {
// Show loading animation
$('#view-items-list').empty();
$(o.gridItemSelector).find('.selected-grid-item-bar').removeClass('selected-grid-item-bar');
$(this).addClass('selected-grid-item-bar');
showDataInViewer([$(this).data()]);
});
}
function showDataInViewer(data, target, unused) {
var view_html = "";
for (var key in data[0]) {
view_html = o.viewTemplate1 + key + o.viewTemplate2 + data[0][key] + o.viewTemplate3;
$('#view-items-list').append(view_html);
}
}
function filterItems(term) {
var results = $(o.gridItemSelector).find('.grid-item:contains(' + term + ')');
if (results.length === 0) {
$(o.gridItemSelector).find('.grid-item').fadeOut();
return;
}
var excess = $(o.gridItemSelector).find('.grid-item:not(:contains(' + term + '))');
excess.fadeOut();
results.show();
}
function getSelectedItems() {
return $(o.gridItemSelector).find(":checked");
}
function clearCheckedItems(message, fade) {
var selectedItems = getSelectedItems();
// Prevent the arrow from being prepended if nothing's checked
if (selectedItems.length === 0) {
// Alert the user that nothing's checked with a yellow alert message
showMessage('N/A', 'No items selected');
return;// false;
}
// Alert the user what's been removed
removeItems(selectedItems, selectedItems.length + message, fade)
}
function removeItems(removeList, message, fadeout) {
if (fadeout === true) {
removeList.parents('.grid-item').fadeOut('slow', function () {
$(this).remove();
});
}
else {
removeList.parents('.grid-item').remove();
}
if (message !== undefined)
showMessage(message, 'Success');
}
function disableGridButtons() {
o.editButtons.fadeOut();
}
function enableGridButtons() {
if (o.editButtons.is(':visible') != true) {
o.editButtons.fadeIn();
}
}
init();
});
}
})(jQuery); | 45.295213 | 693 | 0.471141 |
ec3b054dfae4fd0f6daaba1babc52c3ef596197a | 3,376 | swift | Swift | CleanArchitecture/Scene/Login/LoginViewModel.swift | anhnc55/CleanArchitecture | 74b4cc2927009f79492c835e6c3b030d66563c09 | [
"MIT"
] | 94 | 2020-09-04T02:49:05.000Z | 2022-03-30T20:23:49.000Z | CleanArchitecture/Scene/Login/LoginViewModel.swift | anhnc55/CleanArchitecture | 74b4cc2927009f79492c835e6c3b030d66563c09 | [
"MIT"
] | 1 | 2021-01-13T02:48:39.000Z | 2021-01-15T03:48:22.000Z | CleanArchitecture/Scene/Login/LoginViewModel.swift | anhnc55/CleanArchitecture | 74b4cc2927009f79492c835e6c3b030d66563c09 | [
"MIT"
] | 24 | 2020-08-11T04:26:49.000Z | 2022-02-20T01:57:57.000Z | //
// LoginViewModel.swift
// CleanArchitecture
//
// Created by Tuan Truong on 7/14/20.
// Copyright © 2020 Tuan Truong. All rights reserved.
//
import Combine
import SwiftUI
import ValidatedPropertyKit
import CombineExt
struct LoginViewModel {
let navigator: LoginNavigatorType
let useCase: LoginUseCaseType
}
// MARK: - ViewModelType
extension LoginViewModel: ViewModel {
final class Input: ObservableObject {
@Published var username = ""
@Published var password = ""
let loginTrigger: Driver<Void>
init(loginTrigger: Driver<Void>) {
self.loginTrigger = loginTrigger
}
}
final class Output: ObservableObject {
@Published var isLoginEnabled = true
@Published var isLoading = false
@Published var alert = AlertMessage()
@Published var usernameValidationMessage = ""
@Published var passwordValidationMessage = ""
}
func transform(_ input: Input, cancelBag: CancelBag) -> Output {
let errorTracker = ErrorTracker()
let activityTracker = ActivityTracker(false)
let output = Output()
let usernameValidation = Publishers
.CombineLatest(input.$username, input.loginTrigger)
.map { $0.0 }
.map(LoginDto.validateUserName(_:))
usernameValidation
.asDriver()
.map { $0.message }
.assign(to: \.usernameValidationMessage, on: output)
.store(in: cancelBag)
let passwordValidation = Publishers
.CombineLatest(input.$password, input.loginTrigger)
.map { $0.0 }
.map(LoginDto.validatePassword(_:))
passwordValidation
.asDriver()
.map { $0.message }
.assign(to: \.passwordValidationMessage, on: output)
.store(in: cancelBag)
Publishers
.CombineLatest(usernameValidation, passwordValidation)
.map { $0.0.isValid && $0.1.isValid }
.assign(to: \.isLoginEnabled, on: output)
.store(in: cancelBag)
input.loginTrigger
.delay(for: 0.1, scheduler: RunLoop.main) // waiting for username/password validation
.filter { output.isLoginEnabled }
.map { _ in
self.useCase.login(dto: LoginDto(username: input.username, password: input.password))
.trackError(errorTracker)
.trackActivity(activityTracker)
.asDriver()
}
.switchToLatest()
.sink(receiveValue: {
let message = AlertMessage(title: "Login successful",
message: "Hello \(input.username). Welcome to the app!",
isShowing: true)
output.alert = message
})
.store(in: cancelBag)
errorTracker
.receive(on: RunLoop.main)
.map { AlertMessage(error: $0) }
.assign(to: \.alert, on: output)
.store(in: cancelBag)
activityTracker
.receive(on: RunLoop.main)
.assign(to: \.isLoading, on: output)
.store(in: cancelBag)
return output
}
}
| 32.461538 | 101 | 0.554206 |
9934d3c41d4e453c4b3b19a0395ef21f85549f01 | 917 | h | C | dawg/iconv.h | selavy/studies | e17b91ffab193e46fec00cf2b8070dbf1f2c39e3 | [
"MIT"
] | null | null | null | dawg/iconv.h | selavy/studies | e17b91ffab193e46fec00cf2b8070dbf1f2c39e3 | [
"MIT"
] | null | null | null | dawg/iconv.h | selavy/studies | e17b91ffab193e46fec00cf2b8070dbf1f2c39e3 | [
"MIT"
] | null | null | null | #pragma once
#include <cassert>
// Generated by mkiconv.py. Do not edit by hand.
constexpr int iconv_table[128] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
};
constexpr int iconv(char c) noexcept {
#ifndef NDEBUG
assert(('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));
return iconv_table[static_cast<unsigned char>(c & 0x7Fu)];
#else
return iconv_table[static_cast<unsigned char>(c)];
#endif
}
| 33.962963 | 67 | 0.432933 |
e7371534dd59d4cb0d342823a81a5497c35bfa6d | 13,093 | js | JavaScript | modules/searchbar/model.js | starkarabil/masterportaldeployment | b3c8786bab023abb29530a3a9300a15871bcf27c | [
"MIT"
] | null | null | null | modules/searchbar/model.js | starkarabil/masterportaldeployment | b3c8786bab023abb29530a3a9300a15871bcf27c | [
"MIT"
] | null | null | null | modules/searchbar/model.js | starkarabil/masterportaldeployment | b3c8786bab023abb29530a3a9300a15871bcf27c | [
"MIT"
] | null | null | null | const SearchbarModel = Backbone.Model.extend(/** @lends SearchbarModel.prototype */{
defaults: {
placeholder: "Suche",
recommendedList: "",
recommendedListLength: 5,
quickHelp: false,
searchString: "",
hitList: [],
minChars: "",
isInitialSearch: true,
isInitialRecommendedListCreated: false,
knownInitialSearchTasks: ["gazetteer", "specialWFS", "bkg", "tree", "osm"],
activeInitialSearchTasks: []
},
/**
* @class SearchbarModel
* @description todo
* @extends Backbone.Model
* @memberof Searchbar
* @constructs
* @property {String} placeholder="" todo
* @property {String} recommendedList="" todo
* @property {Number} recommendedListLength=5 todo
* @property {Boolean} quickHelp=false todo
* @property {String} searchString="" the current string in the search mask
* @property {Array} hitList=[] todo
* @property {String} minChars="" todo
* @property {Boolean} isInitialSearch=true Flag that is set to false at the end of the initial search (ParametricURL).
* @property {Boolean} isInitialRecommendedListCreated=false Has the recommended list already been generated after the initial search?
* @property {String[]} knownInitialSearchTasks=["gazetteer", "specialWFS", "bkg", "tree", "osm"] Search algorithms for which an initial search is possible
* @property {Array} activeInitialSearchTasks=[] Search algorithms for which an initial search is activated
* @listens Searchbar#RadioTriggerSearchbarCreateRecommendedList
* @listens Searchbar#RadioTriggerSearchbarPushHits
* @listens Searchbar#RadioTriggerSearchbarRemoveHits
* @listens Searchbar#RadioTriggerSearchbarCheckInitialSearch
* @listens Searchbar#RadioTriggerSearchbarAbortSearch
* @fires ParametricURL#RadioRequestParametricURLGetInitString
* @fires Searchbar#RadioTriggerSearchbarSetPastedHouseNumber
* @fires Searchbar#RadioTriggerSearchbarSearch
* @fires ViewZoom#RadioTriggerViewZoomHitSelected
* @fires Searchbar#RadioTriggerSearchbarCheckInitialSearch
* @returns {void}
*/
initialize: function () {
this.listenTo(Radio.channel("Searchbar"), {
"createRecommendedList": this.createRecommendedList,
"pushHits": this.pushHits,
"removeHits": this.removeHits,
"checkInitialSearch": this.checkInitialSearch,
"abortSearch": this.abortSearch
});
if (_.isUndefined(Radio.request("ParametricURL", "getInitString")) === false) {
// Speichere den Such-Parameter für die initiale Suche zur späteren Verwendung in der View
this.setInitSearchString(Radio.request("ParametricURL", "getInitString"));
}
else {
// Es wird keine initiale Suche durchgeführt
this.set("isInitialSearch", false);
this.set("isInitialRecommendedListCreated", true);
}
},
/**
* If a search algorithm terminates the search, it is no longer necessary to wait for a result for this algorithm.
* Therefore, this search algorithm is marked as done.
* @param {String} triggeredBy Name of the calling search algorithm
* @returns {void} result
*/
abortSearch: function (triggeredBy) {
if (this.get("isInitialSearch")) {
// Markiere Algorithmus als abgearbeitet
this.set("initialSearch_" + triggeredBy, true);
// Prüfe, ob es noch ausstehende Ergebnisse gibt
this.checkInitialSearch();
}
},
/**
* Checks whether all search algorithms of the initial search have been processed.
* @returns {void}
*/
checkInitialSearch: function () {
var allDone = true;
// Ist mindestens ein Suchalgorithmus noch als ausstehend markiert?
_.forEach(this.get("activeInitialSearchTasks"), function (taskName) {
var status = this.get("initialSearch_" + taskName);
if (!status) {
allDone = false;
}
}, this);
if (allDone) {
// Sobald alle Ergebnisse vorliegen, wird der Modus "Initiale Suche"
// beendet und die Ergebnisliste erstmalig erzeugt.
this.set("isInitialSearch", false);
this.createRecommendedList("initialSearchFinished");
this.set("isInitialRecommendedListCreated", true);
}
},
/**
* Check by configuration which search algorithms are activated for initial search
* @param {Object} config Configuration
* @returns {void}
*/
setInitialSearchTasks: function (config) {
var searchTasks = this.get("knownInitialSearchTasks"),
activeSearchTasks = [];
// Prüfe für jeden bekannten Suchalgorithmus ob er aktiviert ist. Wenn ja markiere ihn als
// "Ergebnis ausstehend" und füge ihn der Liste aktiver Suchalgorithmen hinzu.
_.forEach(searchTasks, function (taskName) {
if (_.has(config, taskName) === true) {
if (taskName === "gazetteer") {
// Der Suchalgorithmus "gazetteer" ist ein Sonderfall, da er mehrere Suchen durchführen kann
this.set("initialSearch_gazetteer_streetsOrHouseNumbers", false);
activeSearchTasks.push("gazetteer_streetsOrHouseNumbers");
this.set("initialSearch_gazetteer_streetKeys", false);
activeSearchTasks.push("gazetteer_streetKeys");
}
else {
this.set("initialSearch_" + taskName, false);
activeSearchTasks.push(taskName);
}
}
}, this);
this.set("activeInitialSearchTasks", activeSearchTasks);
},
setInitSearchString: function (value) {
this.set("initSearchString", value);
},
/**
* called from view
* @param {string} value - value from event
* @param {string} eventType - type of the event
* @fires Searchbar#RadioTriggerSearchbarSetPastedHouseNumber
* @fires Searchbar#RadioTriggerSearchbarSearch
* @returns {void}
*/
setSearchString: function (value, eventType) {
var splitAdress = value.split(" "),
houseNumber,
streetName;
// für Copy/Paste bei Adressen
if (splitAdress.length > 1 && splitAdress[splitAdress.length - 1].match(/\d/) && eventType === "paste") {
houseNumber = splitAdress[splitAdress.length - 1];
streetName = value.substr(0, value.length - houseNumber.length - 1);
this.setEventType(eventType);
this.set("searchString", streetName);
Radio.trigger("Searchbar", "setPastedHouseNumber", houseNumber);
}
else {
this.set("searchString", value);
}
this.set("hitList", []);
Radio.trigger("Searchbar", "search", this.get("searchString"));
$(".dropdown-menu-search").show();
},
/**
* Help method to set an attribute of type Array.
* @param {String} attribute - todo
* @param {String} value - todo
* @param {event} evtType - todo
* @fires ViewZoom#RadioTriggerViewZoomHitSelected
* @return {void}
*/
pushHits: function (attribute, value, evtType) {
var tempArray = _.clone(this.get(attribute)),
valueWithNumbers;
tempArray.push(value);
// removes addresses without house number, if more than one exists
if (evtType === "paste" && !_.isUndefined(tempArray) && tempArray.length > 1) {
valueWithNumbers = tempArray.filter(function (val) {
var valueArray = val.name.split(",")[0].split(" ");
return !_.isNaN(parseInt(valueArray[valueArray.length - 1], 10));
});
tempArray = _.isUndefined(valueWithNumbers) ? tempArray : valueWithNumbers;
}
this.set(attribute, _.flatten(tempArray));
if (!_.isUndefined(valueWithNumbers) && this.get("eventType") === "paste") {
Radio.trigger("ViewZoom", "hitSelected");
}
},
/**
* Removes all hits with the given filter
* @param {string} attribute object to be filtered
* @param {object[]} filter filter parameters
* @return {Void} Nothing
*/
removeHits: function (attribute, filter) {
var toRemove, i,
tempArray = _.clone(this.get(attribute));
if (_.isObject(filter)) {
toRemove = _.where(tempArray, filter);
_.each(toRemove, function (item) {
tempArray.splice(tempArray.indexOf(item), 1);
});
}
else {
for (i = tempArray.length - 1; i >= 0; i--) {
if (tempArray[i] === filter) {
tempArray.splice(i, 1);
}
}
}
this.set(attribute, _.flatten(tempArray));
},
/**
* changes the filename extension of given filepath
* @param {String} src source string
* @param {String} ext file extension
* @return {String} file extension
*/
changeFileExtension: function (src, ext) {
if (_.isUndefined(src)) {
return src;
}
if (src.substring(src.lastIndexOf("."), src.length) !== ext) {
return src.substring(0, src.lastIndexOf(".")) + ext;
}
return src;
},
/**
* crops names of hits to length zeichen
* @param {String} s todo
* @param {number} length todo
* @returns {string} s todo
*/
shortenString: function (s, length) {
if (_.isUndefined(s)) {
return s;
}
if (s.length > length && length > 0) {
return s.substring(0, length).trim() + "..";
}
return s;
},
/**
* Generate a list with hits of the individual search algorithms.
* @param {String} triggeredBy Calling search algorithm
* @fires Searchbar#RadioTriggerSearchbarCheckInitialSearch
* @returns {void}
*/
createRecommendedList: function (triggeredBy) {
var max = this.get("recommendedListLength"),
recommendedList = [],
hitList = this.get("hitList"),
foundTypes = [],
singleTypes,
usedNumbers = [],
randomNumber;
// Die Funktion "createRecommendedList" wird vielfach (von jedem Suchalgorithmus) aufgerufen.
// Im Rahmen der initialen Suche muss sichergestellt werden, dass die Ergebnisse der einzelnen
// Algorithmen erst verarbeitet werden, wenn alle Ergebnisse vorliegen.
if (this.get("isInitialSearch")) {
// Markiere den aufgrufenden Suchalgorithmus als erledigt
this.set("initialSearch_" + triggeredBy, true);
// Stoße eine Prüfung, ob alle Suchen abgeschlossen sind, an. Hinweis: Wenn dies der Fall ist,
// so wird "isInitialSearch" auf false gesetzt und die aktuelle Funktion erneut aufgerufen.
Radio.trigger("Searchbar", "checkInitialSearch");
return;
}
if (hitList.length > max) {
singleTypes = _.reject(hitList, function (hit) {
var res;
if (_.contains(foundTypes, hit.type) === true || foundTypes.length === max) {
res = true;
}
else {
foundTypes.push(hit.type);
}
return res;
});
while (singleTypes.length < max) {
randomNumber = _.random(0, hitList.length - 1);
if (_.contains(usedNumbers, randomNumber) === false) {
singleTypes.push(hitList[randomNumber]);
usedNumbers.push(randomNumber);
singleTypes = _.uniq(singleTypes);
}
}
recommendedList = singleTypes;
}
else {
recommendedList = this.get("hitList");
}
this.set("recommendedList", _.sortBy(recommendedList, "name"));
this.trigger("renderRecommendedList");
},
/**
* Setter for "tempCounter"
* @param {String} value tempCounter
* @returns {void}
*/
setTempCounter: function (value) {
this.set("tempCounter", value);
},
/**
* Setter for "eventType"
* @param {String} value eventType
* @returns {void}
*/
setEventType: function (value) {
this.set("eventType", value);
},
/**
* Setter for "searchFieldisSelected"
* @param {String} value searchFieldisSelected
* @returns {void}
*/
setSearchFieldisSelected: function (value) {
this.set("searchFieldisSelected", value);
},
/**
* Setter for "quickHelp"
* @param {String} value quickHelp
* @returns {void}
*/
setQuickHelp: function (value) {
this.set("quickHelp", value);
}
});
export default SearchbarModel;
| 36.77809 | 159 | 0.594974 |
c5ffa9200be0bbc998b19cf728747984b0f5f92b | 2,128 | asm | Assembly | programs/oeis/017/A017812.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/017/A017812.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/017/A017812.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A017812: Binomial coefficients C(96,n).
; 1,96,4560,142880,3321960,61124064,927048304,11919192480,132601016340,1296543270880,11279926456656,88188515933856,624668654531480,4036320536972640,23929614612052080,130815226545884704,662252084388541314,3116480397122547360,13677886187371180080,56151322242892212960,216182590635135019896,782375089917631500576,2667187806537380115600,8581386855815918632800,26101718353106752508100,75172948856947447223328,205279975724741105879088,532207344471551015242080,1311510956019179287560840,3075267069286351432901280,6868096454739518200146192,14622398903638974232569312,29701747773016666409906415,57603389620395959098000320,106735692531910159505118240,189074655342240853980495168,320376499329908113689172368,519529458372823968144603840,806637843263068792645569120,1199615254083538204447256640,1709451737069041941337340712,2334860909167471919875392192,3057555952481213228408251680,3839721428697337542652223040,4625118993658156585467450480,5344581948227203165429053888,5925514768686681770366994528,6303739115624129542943611200,6435067013866298908421603100,6303739115624129542943611200,5925514768686681770366994528,5344581948227203165429053888,4625118993658156585467450480,3839721428697337542652223040,3057555952481213228408251680,2334860909167471919875392192,1709451737069041941337340712,1199615254083538204447256640,806637843263068792645569120,519529458372823968144603840,320376499329908113689172368,189074655342240853980495168,106735692531910159505118240,57603389620395959098000320,29701747773016666409906415,14622398903638974232569312,6868096454739518200146192,3075267069286351432901280,1311510956019179287560840,532207344471551015242080,205279975724741105879088,75172948856947447223328,26101718353106752508100,8581386855815918632800,2667187806537380115600,782375089917631500576,216182590635135019896,56151322242892212960,13677886187371180080,3116480397122547360,662252084388541314,130815226545884704,23929614612052080,4036320536972640,624668654531480,88188515933856,11279926456656,1296543270880,132601016340,11919192480,927048304,61124064,3321960,142880,4560,96,1
mov $1,96
bin $1,$0
mov $0,$1
| 304 | 2,054 | 0.941259 |
b2f00fc324ac567aafda05e99a1cb8336f8b4e7a | 7,116 | py | Python | test_cases/apache_avro_adapter.py | QratorLabs/ritfest2016 | cddaaa9e827f5315d2e426c083029124649d6f50 | [
"MIT"
] | null | null | null | test_cases/apache_avro_adapter.py | QratorLabs/ritfest2016 | cddaaa9e827f5315d2e426c083029124649d6f50 | [
"MIT"
] | null | null | null | test_cases/apache_avro_adapter.py | QratorLabs/ritfest2016 | cddaaa9e827f5315d2e426c083029124649d6f50 | [
"MIT"
] | null | null | null | import io
import avro.io
try:
from avro.schema import parse
except ImportError:
from avro.schema import Parse as parse
class ApacheAvroAdapter(object):
NAME = 'avro'
def __init__(self):
with open('specs/str.avsc', 'r') as f:
schema = parse(f.read())
self.str_reader = avro.io.DatumReader(schema)
self.str_writer = avro.io.DatumWriter(schema)
with open('specs/bin.avsc', 'r') as f:
schema = parse(f.read())
self.bin_reader = avro.io.DatumReader(schema)
self.bin_writer = avro.io.DatumWriter(schema)
with open('specs/int.avsc', 'r') as f:
schema = parse(f.read())
self.int_reader = avro.io.DatumReader(schema)
self.int_writer = avro.io.DatumWriter(schema)
with open('specs/float.avsc', 'r') as f:
schema = parse(f.read())
self.float_reader = avro.io.DatumReader(schema)
self.float_writer = avro.io.DatumWriter(schema)
with open('specs/null.avsc', 'r') as f:
schema = parse(f.read())
self.null_reader = avro.io.DatumReader(schema)
self.null_writer = avro.io.DatumWriter(schema)
with open('specs/bool.avsc', 'r') as f:
schema = parse(f.read())
self.bool_reader = avro.io.DatumReader(schema)
self.bool_writer = avro.io.DatumWriter(schema)
with open('specs/array.avsc', 'r') as f:
schema = parse(f.read())
self.array_reader = avro.io.DatumReader(schema)
self.array_writer = avro.io.DatumWriter(schema)
with open('specs/map.avsc', 'r') as f:
schema = parse(f.read())
self.map_reader = avro.io.DatumReader(schema)
self.map_writer = avro.io.DatumWriter(schema)
with open('specs/struct10.avsc', 'r') as f:
schema = parse(f.read())
self.struct10_reader = avro.io.DatumReader(schema)
self.struct10_writer = avro.io.DatumWriter(schema)
with open('specs/struct_map.avsc', 'r') as f:
schema = parse(f.read())
self.struct_map_reader = avro.io.DatumReader(schema)
self.struct_map_writer = avro.io.DatumWriter(schema)
with open('specs/simple_list.avsc', 'r') as f:
schema = parse(f.read())
self.simple_list_reader = avro.io.DatumReader(schema)
self.simple_list_writer = avro.io.DatumWriter(schema)
with open('specs/points_list.avsc', 'r') as f:
schema = parse(f.read())
self.points_list_reader = avro.io.DatumReader(schema)
self.points_list_writer = avro.io.DatumWriter(schema)
def encoder_string(self, data):
io_stream = io.BytesIO()
self.str_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_string(self, data):
io_stream = io.BytesIO(data)
return self.str_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_bytes(self, data):
io_stream = io.BytesIO()
self.bin_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_bytes(self, data):
io_stream = io.BytesIO(data)
return self.bin_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_integer(self, data):
io_stream = io.BytesIO()
self.int_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_integer(self, data):
io_stream = io.BytesIO(data)
return self.int_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_float(self, data):
io_stream = io.BytesIO()
self.float_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_float(self, data):
io_stream = io.BytesIO(data)
return self.float_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_null(self, data):
io_stream = io.BytesIO()
self.null_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_null(self, data):
io_stream = io.BytesIO(data)
return self.null_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_boolean(self, data):
io_stream = io.BytesIO()
self.bool_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_boolean(self, data):
io_stream = io.BytesIO(data)
return self.bool_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_array(self, data):
io_stream = io.BytesIO()
self.array_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_array(self, data):
io_stream = io.BytesIO(data)
return self.array_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_map(self, data):
io_stream = io.BytesIO()
self.map_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_map(self, data):
io_stream = io.BytesIO(data)
return self.map_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_struct_10(self, data):
io_stream = io.BytesIO()
self.struct10_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_struct_10(self, data):
io_stream = io.BytesIO(data)
return self.struct10_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_struct_map(self, data):
io_stream = io.BytesIO()
self.struct_map_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_struct_map(self, data):
io_stream = io.BytesIO(data)
return self.struct_map_reader.read(avro.io.BinaryDecoder(io_stream))
def encoder_simple_list(self, data):
io_stream = io.BytesIO()
self.simple_list_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_simple_list(self, data):
io_stream = io.BytesIO(data)
return self.simple_list_reader.read(
avro.io.BinaryDecoder(io_stream),
)
def encoder_points_list(self, data):
io_stream = io.BytesIO()
self.points_list_writer.write(
data,
avro.io.BinaryEncoder(io_stream),
)
return io_stream.getvalue()
def decoder_points_list(self, data):
io_stream = io.BytesIO(data)
return self.points_list_reader.read(
avro.io.BinaryDecoder(io_stream),
)
| 32.054054 | 76 | 0.604272 |
f0238d97d920682e53df77bf6d0427a081fe7819 | 7,980 | py | Python | untiler/__init__.py | waissbluth/untiler | 866b3096196ac340597f77fbf5f2ce899e58238e | [
"MIT"
] | 37 | 2015-10-06T16:41:18.000Z | 2022-03-22T14:52:13.000Z | untiler/__init__.py | waissbluth/untiler | 866b3096196ac340597f77fbf5f2ce899e58238e | [
"MIT"
] | 18 | 2015-09-02T21:13:44.000Z | 2021-01-04T15:46:04.000Z | untiler/__init__.py | waissbluth/untiler | 866b3096196ac340597f77fbf5f2ce899e58238e | [
"MIT"
] | 8 | 2017-04-12T01:22:36.000Z | 2021-08-17T04:10:46.000Z | #!/usr/bin/env python
from __future__ import with_statement
from __future__ import print_function
from __future__ import division
import os
from multiprocessing import Pool
import click
import mercantile as merc
import numpy as np
import rasterio
from rasterio import Affine
from rasterio.warp import reproject
try:
from rasterio.warp import RESAMPLING as Resampling # pre-1.0
except ImportError:
from rasterio.warp import Resampling
import untiler.scripts.tile_utils as tile_utils
def make_affine(height, width, ul, lr):
"""
Create an affine for a tile of a given size
"""
xCell = (ul[0] - lr[0]) / width
yCell = (ul[1] - lr[1]) / height
return Affine(-xCell, 0.0, ul[0],
0.0, -yCell, ul[1])
def affaux(up):
return Affine(1, 0, 0, 0, -1, 0), Affine(up, 0, 0, 0, -up, 0)
def upsample(rgb, up, fr, to):
up_rgb = np.empty((rgb.shape[0], rgb.shape[1] * up, rgb.shape[2] * up), dtype=rgb.dtype)
reproject(
rgb, up_rgb,
src_transform=fr,
dst_transform=to,
src_crs="EPSG:3857",
dst_crs="EPSG:3857",
resampling=Resampling.bilinear)
return up_rgb
def make_src_meta(bounds, size, creation_opts={}):
"""
Create metadata for output tiles
"""
ul = merc.xy(bounds.west, bounds.north)
lr = merc.xy(bounds.east, bounds.south)
aff = make_affine(size, size, ul, lr)
## default values
src_meta = {
'driver': 'GTiff',
'height': size,
'width': size,
'count': 4,
'dtype': np.uint8,
'affine': aff,
"crs": 'EPSG:3857',
'compress': 'JPEG',
'tiled': True,
'blockxsize': 256,
'blockysize': 256
}
for c in creation_opts.keys():
src_meta[c] = creation_opts[c]
return src_meta
def make_window(x, y, xmin, ymin, windowsize):
"""
Create a window for writing a child tile to a parent output tif
"""
if x < xmin or y < ymin:
raise ValueError("Indices can't be smaller than origin")
row = (y - ymin) * windowsize
col = (x - xmin) * windowsize
return (
(row, row + windowsize),
(col, col + windowsize)
)
globalArgs = None
def make_image_array(imdata, outputSize):
try:
depth, width, height = imdata.shape
if depth == 4:
alpha = imdata[3]
else:
alpha = np.zeros((outputSize, outputSize), dtype=np.uint8) + 255
return np.array([
imdata[0 % depth, :, :],
imdata[1 % depth, :, :],
imdata[2 % depth, :, :],
alpha
])
except Exception as e:
raise e
def load_image_data(imdata, outputSize):
imsize, depth = imdata.shape
if int(np.sqrt(imsize)) != outputSize:
raise ValueError("Output size of %s ** 2 does not equal %s" % (outputSize, imsize))
return imdata.reshape(outputSize, outputSize, depth).astype(np.uint8), imsize, depth
def global_setup(inputDir, args):
global globalArgs
globalArgs = args
def logwriter(openLogFile, writeObj):
if openLogFile:
print(writeObj, file=openLogFile)
return
def streaming_tile_worker(data):
size = 2 ** (data['zMax'] - globalArgs['compositezoom']) * globalArgs['tileResolution']
out_meta = make_src_meta(merc.bounds(data['x'], data['y'], data['z']), size, globalArgs['creation_opts'])
z, x, y = [int(i) for i in (data['z'], data['x'], data['y'])]
filename = globalArgs['sceneTemplate'] % (z, x, y)
subtiler = tile_utils.TileUtils()
log = 'FILE: %s\n' % filename
try:
with rasterio.open(filename, 'w', **out_meta) as dst:
if data['zMaxCov']:
superTiles = subtiler.get_super_tiles(data['zMaxTiles'], data['zMaxCov'])
fillbaseX, fillbaseY = subtiler.get_sub_base_zoom(data['x'], data['y'], data['z'], data['zMaxCov'])
## fill thresh == the number of sub tiles that would need to occur in a fill tile to not fill (eg completely covered)
fThresh = 4 ** (data['zMax'] - data['zMaxCov'])
fDiff = 2 ** (data['zMax'] - data['zMaxCov'])
toFaux, frFaux = affaux(fDiff)
if not globalArgs['no_fill']:
print('filling')
## Read and write the fill tiles first
for t in subtiler.get_fill_super_tiles(superTiles, data['maxCovTiles'], fThresh):
z, x, y = [int(i) for i in t]
path = globalArgs['readTemplate'] % (z, x, y)
log += '%s %s %s\n' % (z, x, y)
with rasterio.open(path) as src:
imdata = src.read()
imdata = make_image_array(imdata, globalArgs['tileResolution'])
imdata = upsample(imdata, fDiff, frFaux, toFaux)
window = make_window(x, y, fillbaseX, fillbaseY, globalArgs['tileResolution'] * fDiff)
dst.write(imdata, window=window)
baseX, baseY = subtiler.get_sub_base_zoom(data['x'], data['y'], data['z'], data['zMax'])
for t in data['zMaxTiles']:
z, x, y = [int(i) for i in t]
path = globalArgs['readTemplate'] % (z, x, y)
log += '%s %s %s\n' % (z, x, y)
with rasterio.open(path) as src:
imdata = src.read()
imdata = make_image_array(imdata, globalArgs['tileResolution'])
window = make_window(x, y, baseX, baseY, globalArgs['tileResolution'])
dst.write(imdata, window=window)
if globalArgs['logdir']:
with open(os.path.join(globalArgs['logdir'], '%s.log' % os.path.basename(filename)), 'w') as logger:
logwriter(logger, log)
return filename
except Exception as e:
click.echo("%s errored" % (path), err=True)
raise e
def inspect_dir(inputDir, zoom, read_template):
tiler = tile_utils.TileUtils()
allFiles = tiler.search_dir(inputDir)
template, readTemplate, separator = tile_utils.parse_template("%s/%s" % (inputDir, read_template))
allTiles = np.array([i for i in tiler.get_tiles(allFiles, template, separator)])
allTiles, _, _, _, _ = tiler.select_tiles(allTiles, zoom)
for t in allTiles:
z, x, y = t
click.echo([x, y, z])
def stream_dir(inputDir, outputDir, compositezoom, maxzoom, logdir, read_template, scene_template, workers, creation_opts, no_fill, tile_resolution=256):
tiler = tile_utils.TileUtils()
allFiles = tiler.search_dir(inputDir)
template, readTemplate, separator = tile_utils.parse_template("%s/%s" % (inputDir, read_template))
allTiles = np.array([i for i in tiler.get_tiles(allFiles, template, separator)])
if allTiles.shape[0] == 0 or allTiles.shape[1] != 3:
raise ValueError("No tiles were found for that template")
if maxzoom:
allTiles = tiler.filter_tiles(allTiles, maxzoom)
if allTiles.shape[0] == 0:
raise ValueError("No tiles were found below that maxzoom")
_, sceneTemplate, _ = tile_utils.parse_template("%s/%s" % (outputDir, scene_template))
pool = Pool(workers, global_setup, (inputDir, {
'maxzoom': maxzoom,
'readTemplate': readTemplate,
'outputDir': outputDir,
'tileResolution': tile_resolution,
'compositezoom': compositezoom,
'fileTemplate': '%s/%s_%s_%s_%s.tif',
'sceneTemplate': sceneTemplate,
'logdir': logdir,
'creation_opts': creation_opts,
'no_fill': no_fill
}))
superTiles = tiler.get_super_tiles(allTiles, compositezoom)
for p in pool.imap_unordered(streaming_tile_worker, tiler.get_sub_tiles(allTiles, superTiles)):
click.echo(p)
pool.close()
pool.join()
if __name__ == "__main__":
stream_dir()
inspect_dir()
| 30.113208 | 153 | 0.590977 |
143ae46beccdba6d953d2e530994caf756e45f19 | 885 | css | CSS | version0/styles/main.css | Adalab/promo-p-modulo-1-pair-18-spotify2 | 0804c1caf4447e8e85285de49aa9c12b38d2593e | [
"MIT"
] | null | null | null | version0/styles/main.css | Adalab/promo-p-modulo-1-pair-18-spotify2 | 0804c1caf4447e8e85285de49aa9c12b38d2593e | [
"MIT"
] | null | null | null | version0/styles/main.css | Adalab/promo-p-modulo-1-pair-18-spotify2 | 0804c1caf4447e8e85285de49aa9c12b38d2593e | [
"MIT"
] | null | null | null | /* :root {
--brand-color: white;
} */
body {
font-family: 'Roboto', 'Open Sans';
/* color: ; */
}
.container {
padding: 20px 20px;
}
.nav {
background-color: black;
/* color: var(--brand-color); */
display: flex;
justify-content: space-between;
align-items: center;
/* box-sizing: content; */
}
.img_logo {
width: 20%;
max-width: 400px;
}
.nav_header {
position: sticky;
top: 0;
font-size: 20px;
color: white;
}
.nav_footer {
font-size: 5px;
color: white;
}
.burguer_menu {
width: 30px;
}
.li_menu {
display: none;
font-size: 15px;
}
.link_item {
padding: 15px;
}
.banner {
background-color: lightskyblue;
}
/* TABLET DESIGN */
@media all and (min-width: 1000px) {
.li_menu {
list-style: none;
display: flex;
}
.burguer_menu {
display: none;
}
}
| 13.615385 | 38 | 0.553672 |
763b18700e9cfad92b2a3f0d7b9330062dbe85cc | 861 | asm | Assembly | oeis/198/A198638.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/198/A198638.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/198/A198638.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A198638: Number of 2n X 2 0..2 arrays with values 0..2 introduced in row major order and each element equal to an even number of horizontal and vertical neighbors.
; Submitted by Christian Krause
; 4,36,376,3936,41216,431616,4519936,47333376,495681536,5190844416,54359228416,569257230336,5961339109376,62427953627136,653754017775616,6846200955273216,71694347178868736,750792950862053376,7862405855482740736,82336183052000034816,862235702936276566016,9029449506403318235136,94557622829859393765376,990220281855859633422336,10369721416992565300822016,108593132494217029475106816,1137202047258723308888129536,11908934447197207235055845376,124711980610226913878460071936
add $0,1
mul $0,2
seq $0,81057 ; E.g.f.: Sum_{n>=0} a(n)*x^n/n! = {Sum_{n>=0} F(n+1)*x^n/n!}^2, where F(n) is the n-th Fibonacci number.
div $0,2
sub $0,2
mul $0,5
div $0,8
mul $0,2
add $0,4
| 61.5 | 470 | 0.81417 |
d5d06690b17a2898cafbac353ac1cb5b5023d848 | 220 | h | C | strvect.h | PatrizioC/strvect | 5d12047caa919a1ef0cff60148afb7e55f5f3ede | [
"MIT"
] | null | null | null | strvect.h | PatrizioC/strvect | 5d12047caa919a1ef0cff60148afb7e55f5f3ede | [
"MIT"
] | null | null | null | strvect.h | PatrizioC/strvect | 5d12047caa919a1ef0cff60148afb7e55f5f3ede | [
"MIT"
] | null | null | null | #ifndef __STRVECT_H__
#define __STRVECT_H__
void print_strvect(char **vector, int n);
char** file_row_list(FILE *f, char **vettore, int *n);
void free_strvect(char** vector, int n);
char** strvect(int n, ...);
#endif
| 20 | 54 | 0.709091 |
0cae04c95140cd33bca1362795247caf69458f47 | 9,770 | py | Python | fugue/column/functions.py | kvnkho/fugue | 5f3fe8f1fb72632e5b5987d720c1d1ef546e4682 | [
"Apache-2.0"
] | 547 | 2020-09-22T08:30:14.000Z | 2022-03-30T23:11:05.000Z | fugue/column/functions.py | kvnkho/fugue | 5f3fe8f1fb72632e5b5987d720c1d1ef546e4682 | [
"Apache-2.0"
] | 196 | 2020-09-22T23:08:26.000Z | 2022-03-26T21:22:48.000Z | fugue/column/functions.py | kvnkho/fugue | 5f3fe8f1fb72632e5b5987d720c1d1ef546e4682 | [
"Apache-2.0"
] | 37 | 2020-09-23T17:05:00.000Z | 2022-03-29T18:26:52.000Z | from typing import Any, Optional
import pyarrow as pa
from fugue.column.expressions import (
ColumnExpr,
_FuncExpr,
_to_col,
function,
)
from triad import Schema
def coalesce(*args: Any) -> ColumnExpr:
"""SQL ``COALESCE`` function
:param args: If a value is not :class:`~fugue.column.expressions.ColumnExpr`
then it's converted to a literal column by
:func:`~fugue.column.expressions.col`
.. note::
this function can infer neither type nor alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
f.coalesce(col("a"), col("b")+col("c"), 1)
"""
return function("COALESCE", *[_to_col(x) for x in args])
def min(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin
"""SQL ``MIN`` function (aggregation)
:param col: the column to find min
.. note::
* this function can infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
# assume col a has type double
f.min(col("a")) # CAST(MIN(a) AS double) AS a
f.min(-col("a")) # CAST(MIN(-a) AS double) AS a
# neither type nor alias can be inferred in the following cases
f.min(col("a")+1)
f.min(col("a")+col("b"))
# you can specify explicitly
# CAST(MIN(a+b) AS int) AS x
f.min(col("a")+col("b")).cast(int).alias("x")
"""
assert isinstance(col, ColumnExpr)
return _SameTypeUnaryAggFuncExpr("MIN", col)
def max(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin
"""SQL ``MAX`` function (aggregation)
:param col: the column to find max
.. note::
* this function can infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
# assume col a has type double
f.max(col("a")) # CAST(MAX(a) AS double) AS a
f.max(-col("a")) # CAST(MAX(-a) AS double) AS a
# neither type nor alias can be inferred in the following cases
f.max(col("a")+1)
f.max(col("a")+col("b"))
# you can specify explicitly
# CAST(MAX(a+b) AS int) AS x
f.max(col("a")+col("b")).cast(int).alias("x")
"""
assert isinstance(col, ColumnExpr)
return _SameTypeUnaryAggFuncExpr("MAX", col)
def count(col: ColumnExpr) -> ColumnExpr:
"""SQL ``COUNT`` function (aggregation)
:param col: the column to find count
.. note::
* this function cannot infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
f.count(col("*")) # COUNT(*)
f.count(col("a")) # COUNT(a) AS a
# you can specify explicitly
# CAST(COUNT(a) AS double) AS a
f.count(col("a")).cast(float)
"""
assert isinstance(col, ColumnExpr)
return _UnaryAggFuncExpr("COUNT", col)
def count_distinct(col: ColumnExpr) -> ColumnExpr:
"""SQL ``COUNT DISTINCT`` function (aggregation)
:param col: the column to find distinct element count
.. note::
* this function cannot infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
f.count_distinct(col("*")) # COUNT(DISTINCT *)
f.count_distinct(col("a")) # COUNT(DISTINCT a) AS a
# you can specify explicitly
# CAST(COUNT(DISTINCT a) AS double) AS a
f.count_distinct(col("a")).cast(float)
"""
assert isinstance(col, ColumnExpr)
return _UnaryAggFuncExpr("COUNT", col, arg_distinct=True)
def avg(col: ColumnExpr) -> ColumnExpr:
"""SQL ``AVG`` function (aggregation)
:param col: the column to find average
.. note::
* this function cannot infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
f.avg(col("a")) # AVG(a) AS a
# you can specify explicitly
# CAST(AVG(a) AS double) AS a
f.avg(col("a")).cast(float)
"""
assert isinstance(col, ColumnExpr)
return _UnaryAggFuncExpr("AVG", col)
def sum(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin
"""SQL ``SUM`` function (aggregation)
:param col: the column to find sum
.. note::
* this function cannot infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
f.sum(col("a")) # SUM(a) AS a
# you can specify explicitly
# CAST(SUM(a) AS double) AS a
f.sum(col("a")).cast(float)
"""
assert isinstance(col, ColumnExpr)
return _UnaryAggFuncExpr("SUM", col)
def first(col: ColumnExpr) -> ColumnExpr:
"""SQL ``FIRST`` function (aggregation)
:param col: the column to find first
.. note::
* this function can infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
# assume col a has type double
f.first(col("a")) # CAST(FIRST(a) AS double) AS a
f.first(-col("a")) # CAST(FIRST(-a) AS double) AS a
# neither type nor alias can be inferred in the following cases
f.first(col("a")+1)
f.first(col("a")+col("b"))
# you can specify explicitly
# CAST(FIRST(a+b) AS int) AS x
f.first(col("a")+col("b")).cast(int).alias("x")
"""
assert isinstance(col, ColumnExpr)
return _SameTypeUnaryAggFuncExpr("FIRST", col)
def last(col: ColumnExpr) -> ColumnExpr:
"""SQL ``LAST`` function (aggregation)
:param col: the column to find last
.. note::
* this function can infer type from ``col`` type
* this function can infer alias from ``col``'s inferred alias
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
# assume col a has type double
f.last(col("a")) # CAST(LAST(a) AS double) AS a
f.last(-col("a")) # CAST(LAST(-a) AS double) AS a
# neither type nor alias can be inferred in the following cases
f.last(col("a")+1)
f.last(col("a")+col("b"))
# you can specify explicitly
# CAST(LAST(a+b) AS int) AS x
f.last(col("a")+col("b")).cast(int).alias("x")
"""
assert isinstance(col, ColumnExpr)
return _SameTypeUnaryAggFuncExpr("LAST", col)
def is_agg(column: Any) -> bool:
"""Check if a column contains aggregation operation
:param col: the column to check
:return: whether the column is :class:`~fugue.column.expressions.ColumnExpr`
and contains aggregation operations
.. admonition:: New Since
:class: hint
**0.6.0**
.. admonition:: Examples
.. code-block:: python
import fugue.column.functions as f
assert not f.is_agg(1)
assert not f.is_agg(col("a"))
assert not f.is_agg(col("a")+lit(1))
assert f.is_agg(f.max(col("a")))
assert f.is_agg(-f.max(col("a")))
assert f.is_agg(f.max(col("a")+1))
assert f.is_agg(f.max(col("a"))+f.min(col("a"))))
"""
if isinstance(column, _UnaryAggFuncExpr):
return True
if isinstance(column, _FuncExpr):
return any(is_agg(x) for x in column.args) or any(
is_agg(x) for x in column.kwargs.values()
)
return False
class _UnaryAggFuncExpr(_FuncExpr):
def __init__(self, func: str, col: ColumnExpr, arg_distinct: bool = False):
super().__init__(func, col, arg_distinct=arg_distinct)
def infer_alias(self) -> ColumnExpr:
return (
self
if self.output_name != ""
else self.alias(self.args[0].infer_alias().output_name)
)
def _copy(self) -> _FuncExpr:
return _UnaryAggFuncExpr(self.func, *self.args, **self.kwargs)
class _SameTypeUnaryAggFuncExpr(_UnaryAggFuncExpr):
def _copy(self) -> _FuncExpr:
return _SameTypeUnaryAggFuncExpr(self.func, *self.args, **self.kwargs)
def infer_type(self, schema: Schema) -> Optional[pa.DataType]:
return self.as_type or self.args[0].infer_type(schema)
| 26.334232 | 80 | 0.572467 |
4a47e7b87b89412cfeed3d282f21751964597afd | 4,177 | js | JavaScript | build/static/js/52.dcfa5e02.chunk.js | atulbhatt-system32/atlastNew | fda36fc944b5398e79e441c687a7f25bd17bed81 | [
"MTLL"
] | null | null | null | build/static/js/52.dcfa5e02.chunk.js | atulbhatt-system32/atlastNew | fda36fc944b5398e79e441c687a7f25bd17bed81 | [
"MTLL"
] | null | null | null | build/static/js/52.dcfa5e02.chunk.js | atulbhatt-system32/atlastNew | fda36fc944b5398e79e441c687a7f25bd17bed81 | [
"MTLL"
] | null | null | null | (this["webpackJsonp@coreui/coreui-pro-react-admin-template"]=this["webpackJsonp@coreui/coreui-pro-react-admin-template"]||[]).push([[52],{1444:function(e,r,o){"use strict";o.r(r);o(1);var t=o(632),a=o(784),n=o(634),c=o(17);r.default=function(){return Object(c.jsxs)(t.m,{columns:!0,className:"cols-2",children:[Object(c.jsxs)(t.j,{children:[Object(c.jsxs)(t.n,{children:["Bar Chart",Object(c.jsx)(n.a,{href:"http://www.chartjs.org"})]}),Object(c.jsx)(t.k,{children:Object(c.jsx)(a.a,{datasets:[{label:"GitHub Commits",backgroundColor:"#f87979",data:[40,20,12,39,10,40,39,80,40,20,12,11]}],labels:"months",options:{tooltips:{enabled:!0}}})})]}),Object(c.jsxs)(t.j,{children:[Object(c.jsx)(t.n,{children:"Doughnut Chart"}),Object(c.jsx)(t.k,{children:Object(c.jsx)(a.b,{datasets:[{backgroundColor:["#41B883","#E46651","#00D8FF","#DD1B16"],data:[40,20,80,10]}],labels:["VueJs","EmberJs","ReactJs","AngularJs"],options:{tooltips:{enabled:!0}}})})]}),Object(c.jsxs)(t.j,{children:[Object(c.jsx)(t.n,{children:"Line Chart"}),Object(c.jsx)(t.k,{children:Object(c.jsx)(a.c,{datasets:[{label:"Data One",backgroundColor:"rgb(228,102,81,0.9)",data:[30,39,10,50,30,70,35]},{label:"Data Two",backgroundColor:"rgb(0,216,255,0.9)",data:[39,80,40,35,40,20,45]}],options:{tooltips:{enabled:!0}},labels:"months"})})]}),Object(c.jsxs)(t.j,{children:[Object(c.jsx)(t.n,{children:"Pie Chart"}),Object(c.jsx)(t.k,{children:Object(c.jsx)(a.d,{datasets:[{backgroundColor:["#41B883","#E46651","#00D8FF","#DD1B16"],data:[40,20,80,10]}],labels:["VueJs","EmberJs","ReactJs","AngularJs"],options:{tooltips:{enabled:!0}}})})]}),Object(c.jsxs)(t.j,{children:[Object(c.jsx)(t.n,{children:"Polar Area Chart"}),Object(c.jsx)(t.k,{children:Object(c.jsx)(a.e,{datasets:[{label:"My First dataset",backgroundColor:"rgba(179,181,198,0.2)",pointBackgroundColor:"rgba(179,181,198,1)",pointBorderColor:"#fff",pointHoverBackgroundColor:"rgba(179,181,198,1)",pointHoverBorderColor:"rgba(179,181,198,1)",data:[65,59,90,81,56,55,40]},{label:"My Second dataset",backgroundColor:"rgba(255,99,132,0.2)",pointBackgroundColor:"rgba(255,99,132,1)",pointBorderColor:"#fff",pointHoverBackgroundColor:"rgba(255,99,132,1)",pointHoverBorderColor:"rgba(255,99,132,1)",data:[28,48,40,19,96,27,100]}],options:{aspectRatio:1.5,tooltips:{enabled:!0}},labels:["Eating","Drinking","Sleeping","Designing","Coding","Cycling","Running"]})})]}),Object(c.jsxs)(t.j,{children:[Object(c.jsx)(t.n,{children:"Radar Chart"}),Object(c.jsx)(t.k,{children:Object(c.jsx)(a.f,{datasets:[{label:"2019",backgroundColor:"rgba(179,181,198,0.2)",borderColor:"rgba(179,181,198,1)",pointBackgroundColor:"rgba(179,181,198,1)",pointBorderColor:"#fff",pointHoverBackgroundColor:"#fff",pointHoverBorderColor:"rgba(179,181,198,1)",tooltipLabelColor:"rgba(179,181,198,1)",data:[65,59,90,81,56,55,40]},{label:"2020",backgroundColor:"rgba(255,99,132,0.2)",borderColor:"rgba(255,99,132,1)",pointBackgroundColor:"rgba(255,99,132,1)",pointBorderColor:"#fff",pointHoverBackgroundColor:"#fff",pointHoverBorderColor:"rgba(255,99,132,1)",tooltipLabelColor:"rgba(255,99,132,1)",data:[28,48,40,19,96,27,100]}],options:{aspectRatio:1.5,tooltips:{enabled:!0}},labels:["Eating","Drinking","Sleeping","Designing","Coding","Cycling","Running"]})})]})]})}},634:function(e,r,o){"use strict";o.d(r,"a",(function(){return d})),o.d(r,"b",(function(){return p}));var t=o(40),a=o(159),n=o(1),c=o.n(n),l=o(632),s=o(17),i=["name","text"],b=function(e){var r=e.name,o=e.text,n=Object(a.a)(e,i),c=r?"https://coreui.io/react/docs/components/".concat(r):e.href;return Object(s.jsx)("div",{className:"card-header-actions",children:Object(s.jsx)(l.db,Object(t.a)(Object(t.a)({},n),{},{href:c,rel:"noreferrer noopener",target:"_blank",className:"card-header-action",children:Object(s.jsx)("small",{className:"text-muted",children:o||"docs"})}))})},d=c.a.memo(b),j=["children"],g=function(e){var r=Object(t.a)({},e),o=r.children,n=Object(a.a)(r,j);return Object(s.jsx)(l.b,Object(t.a)(Object(t.a)({href:"https://coreui.io/pro/react/",color:"danger",target:"_blank",rel:"noreferrer noopener"},n),{},{children:o||"CoreUI Pro Component"}))},p=c.a.memo(g)}}]);
//# sourceMappingURL=52.dcfa5e02.chunk.js.map | 2,088.5 | 4,131 | 0.697151 |
650ec3bb5d3381c505f9bd3240d3f221d5e35e00 | 660 | py | Python | open_data/dataset/migrations/0005_keyword_squashed_0006_remove_keyword_relevancy.py | balfroim/OpenData | f0334dae16c2806e81f7d2d53adeabc72403ecce | [
"MIT"
] | null | null | null | open_data/dataset/migrations/0005_keyword_squashed_0006_remove_keyword_relevancy.py | balfroim/OpenData | f0334dae16c2806e81f7d2d53adeabc72403ecce | [
"MIT"
] | null | null | null | open_data/dataset/migrations/0005_keyword_squashed_0006_remove_keyword_relevancy.py | balfroim/OpenData | f0334dae16c2806e81f7d2d53adeabc72403ecce | [
"MIT"
] | null | null | null | # Generated by Django 3.2 on 2021-04-21 13:01
from django.db import migrations, models
class Migration(migrations.Migration):
replaces = [('dataset', '0005_keyword'), ('dataset', '0006_remove_keyword_relevancy')]
dependencies = [
('dataset', '0004_alter_theme_id'),
]
operations = [
migrations.CreateModel(
name='Keyword',
fields=[
('word', models.CharField(max_length=64, primary_key=True, serialize=False)),
('datasets', models.ManyToManyField(blank=True, related_name='keywords', to='dataset.ProxyDataset')),
],
),
]
| 28.695652 | 118 | 0.587879 |
c6b78b90e031795606d57f8f612f7c4f912f3dc9 | 151 | rb | Ruby | lib/insane_hook/errors.rb | Trevoke/insane-hook | be3e1229cc6ddeb71999c44cc7adfce36fc53f41 | [
"MIT"
] | 2 | 2018-05-23T05:13:59.000Z | 2018-05-30T17:41:25.000Z | lib/insane_hook/errors.rb | Trevoke/insane-hook | be3e1229cc6ddeb71999c44cc7adfce36fc53f41 | [
"MIT"
] | null | null | null | lib/insane_hook/errors.rb | Trevoke/insane-hook | be3e1229cc6ddeb71999c44cc7adfce36fc53f41 | [
"MIT"
] | null | null | null | class InsaneHook
module Errors
class CommandNotRunError < StandardError
end
class MissingArgumentError < StandardError
end
end
end
| 16.777778 | 46 | 0.748344 |
dced414b0f92324f6cd2097fe126da4fedd33695 | 850 | lua | Lua | Resources/Scripts/Steam_Handler_onPostInit.lua | broozar/SteamShiva | bbcae01abed8656bcb4712ca46094e5fcabe317e | [
"MIT"
] | null | null | null | Resources/Scripts/Steam_Handler_onPostInit.lua | broozar/SteamShiva | bbcae01abed8656bcb4712ca46094e5fcabe317e | [
"MIT"
] | null | null | null | Resources/Scripts/Steam_Handler_onPostInit.lua | broozar/SteamShiva | bbcae01abed8656bcb4712ca46094e5fcabe317e | [
"MIT"
] | 2 | 2017-07-09T09:28:46.000Z | 2019-06-05T13:18:32.000Z | --------------------------------------------------------------------------------
-- Handler.......... : onPostInit
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Steam.onPostInit ( )
--------------------------------------------------------------------------------
this.achievementsInit ( )
this.statsInit ( )
local bSuccess = Steamworks.Init ( "Steam" )
if bSuccess then
if this.bDebug ( ) then
this.Debug ( )
else
this.Running ( )
end
end
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
| 32.692308 | 80 | 0.217647 |
085914e79be9fb9cff388c4de0e64916d11bf756 | 1,619 | swift | Swift | WhoIsTheVillain/AppLabel.swift | choi88andys/WhoIsTheVillain | 2e5212edaa5af02d4c804ddbc4941c71c085e1a1 | [
"MIT"
] | null | null | null | WhoIsTheVillain/AppLabel.swift | choi88andys/WhoIsTheVillain | 2e5212edaa5af02d4c804ddbc4941c71c085e1a1 | [
"MIT"
] | null | null | null | WhoIsTheVillain/AppLabel.swift | choi88andys/WhoIsTheVillain | 2e5212edaa5af02d4c804ddbc4941c71c085e1a1 | [
"MIT"
] | null | null | null |
import SwiftUI
struct AppLabel: View {
private var labelWidth: CGFloat {
if SettingConstants.isPhone {
return UIScreen.main.bounds.width * 0.9
} else {
return UIScreen.main.bounds.width * 0.8
}
}
private var labelHeight: CGFloat {
if SettingConstants.isPhone {
return 50
} else {
return 100
}
}
var body: some View {
return VStack {
RoundedRectangle(cornerRadius: SettingConstants.fontSize*1.5)
.fill(Color.gray)
.overlay(Text(Strings.appLabel)
.font(.system(size: SettingConstants.fontSize*1.9, weight: Font.Weight.light, design: Font.Design.serif))
.padding(.top, SettingConstants.fontSize*0.8)
.foregroundColor(.white)
.multilineTextAlignment(.center))
.frame(maxWidth: labelWidth, maxHeight: labelHeight)
.padding(.top, SettingConstants.fontSize*0.5)
.navigationBarTitleDisplayMode(NavigationBarItem.TitleDisplayMode.inline)
Divider()
}
.padding(.bottom, SettingConstants.fontSize*0.5)
}
}
struct AppLabel_Previews: PreviewProvider {
static var previews: some View {
AppLabel()
.previewDevice(PreviewDevice(rawValue: "iPhone 8"))
.previewDisplayName("8")
AppLabel()
.previewDevice(PreviewDevice(rawValue: "iPad (9th generation)"))
.previewDisplayName("pad 9 gen")
}
}
| 29.436364 | 125 | 0.566399 |
419ed3ca352891cf8b6e70980cc20a4c7838a529 | 26,815 | h | C | Box2D/Common/OpenCL/b2CLCompactionFuncitons.h | wolfviking0/webcl-box2d | a4a7954f279f5d9dda18c042e60cf228b252d266 | [
"Zlib"
] | 8 | 2015-07-28T09:12:23.000Z | 2022-01-03T00:35:21.000Z | Box2D/Common/OpenCL/b2CLCompactionFuncitons.h | deidaraho/webcl-box2d | a4a7954f279f5d9dda18c042e60cf228b252d266 | [
"Zlib"
] | null | null | null | Box2D/Common/OpenCL/b2CLCompactionFuncitons.h | deidaraho/webcl-box2d | a4a7954f279f5d9dda18c042e60cf228b252d266 | [
"Zlib"
] | 3 | 2016-04-07T12:32:21.000Z | 2019-08-22T00:10:50.000Z | /*
*
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.
*/
/* Copyright (c) 2014, Samsung Electronics Co. Ltd.*/
#ifndef simple_BVH_compaction_funcitons_h
#define simple_BVH_compaction_funcitons_h
#include <Box2D/Common/OpenCL/b2CLDevice.h>
#include <sys/stat.h>
#include <algorithm>
#include <math.h>
#if defined linux
#include <string.h>
#endif
#include <fcntl.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
#define DEBUG_INFO (0)
#define NUM_BANKS (16)
#define MAX_ERROR (1e-7)
#define SEPARATOR ("----------------------------------------------------------------------\n")
//#define min(A,B) ((A) < (B) ? (A) : (B))
#if defined (_WIN32)
#define fmax(A,B) ((A) > (B) ? (A) : (B))
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
enum CompactionKernelMethods
{
PRESCAN_FIRST_LEVEL = 0,
PRESCAN = 1,
PRESCAN_STORE_SUM_FIRST_LEVEL = 2,
PRESCAN_STORE_SUM = 3,
PRESCAN_STORE_SUM_NON_POWER_OF_TWO_FIRST_LEVEL = 4,
PRESCAN_STORE_SUM_NON_POWER_OF_TWO = 5,
PRESCAN_NON_POWER_OF_TWO_FIRST_LEVEL= 6,
PRESCAN_NON_POWER_OF_TWO = 7,
UNIFORM_ADD = 8,
PARALLEL_COMPACT = 9,
PARALLEL_COMPACT_FINAL = 10
};
static const char* CompactionKernelNames[] =
{
"PreScanKernelFirstLevel",
"PreScanKernel",
"PreScanStoreSumFirstLevelKernel",
"PreScanStoreSumKernel",
"PreScanStoreSumNonPowerOfTwoFirstLevelKernel",
"PreScanStoreSumNonPowerOfTwoKernel",
"PreScanNonPowerOfTwoKernelFirstLevel",
"PreScanNonPowerOfTwoKernel",
"UniformAddKernel",
"ParallelCompact",
"ParallelCompactFinal"
};
static const unsigned int CompactionKernelCount = sizeof(CompactionKernelNames) / sizeof(char *);
class b2CLCompactionFunctions
{
cl_mem* ScanPartialSums;
unsigned int ElementsAllocated;
unsigned int LevelsAllocated;
cl_program compactionProgram;
cl_kernel compactionKernels[CompactionKernelCount];
public:
size_t maxWorkGroupSize;
b2CLCompactionFunctions()
:ScanPartialSums(0),ElementsAllocated(0),LevelsAllocated(0),maxWorkGroupSize(0)
{
#if defined(BROADPHASE_OPENCL)
printf("Initializing b2CLCompactionFunctions...\n");
int err;
//load opencl programs from files
char* scanKernelSource=0;
size_t scanKernelSourceLen=0;
shrLog("...loading b2CLScanKernel.cl\n");
#ifdef linux
scanKernelSource = b2clLoadProgSource(shrFindFilePath("/opt/apps/com.samsung.browser/include/Box2D/Common/OpenCL/b2CLScanKernel.cl", NULL), "// My comment\n", &scanKernelSourceLen);
#elif defined (_WIN32)
scanKernelSource = b2clLoadProgSource(shrFindFilePath("../../Box2D/Common/OpenCL/b2CLScanKernel.cl", NULL), "// My comment\n", &scanKernelSourceLen);
#elif defined (__EMSCRIPTEN__)
scanKernelSource = b2clLoadProgSource(shrFindFilePath("./Common/OpenCL/b2CLScanKernel.cl", NULL), "// My comment\n", &scanKernelSourceLen);
#else
scanKernelSource = b2clLoadProgSource(shrFindFilePath("../../../Box2D/Common/OpenCL/b2CLScanKernel.cl", NULL), "// My comment\n", &scanKernelSourceLen);
#endif
if(scanKernelSource == NULL)
{
b2Log("Could not load program source, is path 'b2CLScanKernel.cl' correct?");
}
//create the compute program from source kernel code
compactionProgram=clCreateProgramWithSource(b2CLDevice::instance().GetContext(), 1, (const char**)&scanKernelSource, NULL, &err);
if (!compactionProgram)
{
printf("Error: Failed to create compute program!\n");
exit(1);
}
//build the program
err=clBuildProgram(compactionProgram,0,NULL,NULL,NULL,NULL);
if (err != CL_SUCCESS)
{
size_t len;
char buffer[2048];
printf("Error: Failed to build program executable!\n");
clGetProgramBuildInfo(compactionProgram,b2CLDevice::instance().GetCurrentDevice(), CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);
printf("%s\n", buffer);
exit(1);
}
//create the compute kernel
for(int i = 0; i < static_cast<int>(CompactionKernelCount); i++)
{
// Create each kernel from within the compactionProgram
compactionKernels[i] = clCreateKernel(compactionProgram, CompactionKernelNames[i], &err);
if (!compactionKernels[i] || err != CL_SUCCESS)
{
printf("Error: Failed to create compute kernel!\n");
exit(1);
}
size_t maxWorkGroupSizeTmp;
b2CLDevice::instance().getMaximumKernelWorkGroupSize(compactionKernels[i], maxWorkGroupSizeTmp);
if(!maxWorkGroupSize || maxWorkGroupSizeTmp<maxWorkGroupSize) maxWorkGroupSize=maxWorkGroupSizeTmp;
}
#endif
}
bool IsPowerOfTwo(int n)
{
return ((n&(n-1))==0) ;
}
int floorPow2(int n)
{
int exp;
frexp((float)n, &exp);
return 1 << (exp - 1);
}
int
CreatePartialSumBuffers(unsigned int count)
{
ElementsAllocated = count;
unsigned int group_size = maxWorkGroupSize;
unsigned int element_count = count;
int level = 0;
do
{
unsigned int group_count = (int)fmax(1, (int)ceil((float)element_count / (2.0f * group_size)));
if (group_count > 1)
{
level++;
}
element_count = group_count;
} while (element_count > 1);
ScanPartialSums = (cl_mem*) malloc(level * sizeof(cl_mem));
LevelsAllocated = level;
memset(ScanPartialSums, 0, sizeof(cl_mem) * level);
element_count = count;
level = 0;
do
{
unsigned int group_count = (int)fmax(1, (int)ceil((float)element_count / (2.0f * group_size)));
if (group_count > 1)
{
size_t buffer_size = group_count * sizeof(float);
ScanPartialSums[level++] = b2CLDevice::instance().allocateArray(buffer_size);
}
element_count = group_count;
} while (element_count > 1);
return CL_SUCCESS;
}
void
ReleasePartialSums(void)
{
unsigned int i;
for (i = 0; i < LevelsAllocated; i++)
{
b2CLDevice::instance().freeArray(ScanPartialSums[i]);
}
free(ScanPartialSums);
ScanPartialSums = 0;
ElementsAllocated = 0;
LevelsAllocated = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
ParallelCompactBuffer(
cl_mem CompactIn_data,
cl_mem CompactOut_data,
cl_mem numUsefulNodes,
cl_mem ScanResult_data,
cl_mem LevelLength_data,
int max_level_length,
int num_move,
bool final=false)
{
unsigned int k = final?PARALLEL_COMPACT_FINAL:PARALLEL_COMPACT;
unsigned int a = 0;
int err = CL_SUCCESS;
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &CompactIn_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &CompactOut_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &numUsefulNodes);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &ScanResult_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &LevelLength_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &max_level_length);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to set kernel arguments!\n", CompactionKernelNames[k]);
return;
}
size_t global[] = { static_cast<size_t>(max_level_length), static_cast<size_t>(num_move) };
err = CL_SUCCESS;
err |= clEnqueueNDRangeKernel(b2CLDevice::instance().GetCommandQueue(), compactionKernels[k], 2, NULL, global, NULL, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to execute kernel!\n", CompactionKernelNames[k]);
return;
}
return;
}
int
PreScan(
size_t *global,
size_t *local,
size_t shared,
cl_mem output_data,
cl_mem input_data,
unsigned int n,
int group_index,
int base_index,
int level,
int addr_offset)
{
if(shared==0) return CL_SUCCESS;
#if DEBUG_INFO
printf("PreScan: Global[%4d] Local[%4d] Shared[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n",
(int)global[0], (int)local[0], (int)shared, group_index, base_index, n);
#endif
unsigned int k;
k = level==0 ? PRESCAN_FIRST_LEVEL : PRESCAN;
unsigned int a = 0;
int err = CL_SUCCESS;
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &output_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &input_data);
err |= clSetKernelArg(compactionKernels[k], a++, shared, 0);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &group_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &base_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &n);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &addr_offset);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to set kernel arguments!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
err = CL_SUCCESS;
err |= clEnqueueNDRangeKernel(b2CLDevice::instance().GetCommandQueue(), compactionKernels[k], 1, NULL, global, local, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to execute kernel!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
return CL_SUCCESS;
}
int
PreScanStoreSum(
size_t *global,
size_t *local,
size_t shared,
cl_mem output_data,
cl_mem input_data,
cl_mem partial_sums,
unsigned int n,
int group_index,
int base_index,
int level,
int addr_offset)
{
if(shared==0) return CL_SUCCESS;
#if DEBUG_INFO
printf("PreScan: Global[%4d] Local[%4d] Shared[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n",
(int)global[0], (int)local[0], (int)shared, group_index, base_index, n);
#endif
unsigned int k;
k = level==0 ? PRESCAN_STORE_SUM_FIRST_LEVEL : PRESCAN_STORE_SUM;
unsigned int a = 0;
int err = CL_SUCCESS;
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &output_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &input_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &partial_sums);
err |= clSetKernelArg(compactionKernels[k], a++, shared, 0);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &group_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &base_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &n);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &addr_offset);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to set kernel arguments!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
err = CL_SUCCESS;
err |= clEnqueueNDRangeKernel(b2CLDevice::instance().GetCommandQueue(), compactionKernels[k], 1, NULL, global, local, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to execute kernel!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
return CL_SUCCESS;
}
int
PreScanStoreSumNonPowerOfTwo(
size_t *global,
size_t *local,
size_t shared,
cl_mem output_data,
cl_mem input_data,
cl_mem partial_sums,
unsigned int n,
int group_index,
int base_index,
int level,
int addr_offset)
{
if(shared==0) return CL_SUCCESS;
#if DEBUG_INFO
printf("PreScanStoreSumNonPowerOfTwo: Global[%4d] Local[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n",
(int)global[0], (int)local[0], group_index, base_index, n);
#endif
unsigned int k;
k = level==0 ? PRESCAN_STORE_SUM_NON_POWER_OF_TWO_FIRST_LEVEL : PRESCAN_STORE_SUM_NON_POWER_OF_TWO;
unsigned int a = 0;
int err = CL_SUCCESS;
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &output_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &input_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &partial_sums);
err |= clSetKernelArg(compactionKernels[k], a++, shared, 0);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &group_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &base_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &n);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &addr_offset);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to set kernel arguments!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
err = CL_SUCCESS;
err |= clEnqueueNDRangeKernel(b2CLDevice::instance().GetCommandQueue(), compactionKernels[k], 1, NULL, global, local, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to execute kernel!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
return CL_SUCCESS;
}
int
PreScanNonPowerOfTwo(
size_t *global,
size_t *local,
size_t shared,
cl_mem output_data,
cl_mem input_data,
unsigned int n,
int group_index,
int base_index,
int level,
int addr_offset)
{
if(shared==0) return CL_SUCCESS;
#if DEBUG_INFO
printf("PreScanNonPowerOfTwo: Global[%4d] Local[%4d] BlockIndex[%4d] BaseIndex[%4d] Entries[%d]\n",
(int)global[0], (int)local[0], group_index, base_index, n);
#endif
unsigned int k;
k = level==0 ? PRESCAN_NON_POWER_OF_TWO_FIRST_LEVEL : PRESCAN_NON_POWER_OF_TWO;
unsigned int a = 0;
int err = CL_SUCCESS;
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &output_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &input_data);
err |= clSetKernelArg(compactionKernels[k], a++, shared, 0);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &group_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &base_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &n);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &addr_offset);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to set kernel arguments!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
err = CL_SUCCESS;
err |= clEnqueueNDRangeKernel(b2CLDevice::instance().GetCommandQueue(), compactionKernels[k], 1, NULL, global, local, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to execute kernel!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
return CL_SUCCESS;
}
int
UniformAdd(
size_t *global,
size_t *local,
cl_mem output_data,
cl_mem partial_sums,
unsigned int n,
unsigned int group_offset,
unsigned int base_index,
unsigned int addr_offset)
{
#if DEBUG_INFO
printf("UniformAdd: Global[%4d] Local[%4d] BlockOffset[%4d] BaseIndex[%4d] Entries[%d]\n",
(int)global[0], (int)local[0], group_offset, base_index, n);
#endif
unsigned int k = UNIFORM_ADD;
unsigned int a = 0;
int err = CL_SUCCESS;
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &output_data);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_mem), &partial_sums);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(float), 0);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &group_offset);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &base_index);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &n);
err |= clSetKernelArg(compactionKernels[k], a++, sizeof(cl_int), &addr_offset);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to set kernel arguments!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
err = CL_SUCCESS;
err |= clEnqueueNDRangeKernel(b2CLDevice::instance().GetCommandQueue(), compactionKernels[k], 1, NULL, global, local, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
printf("Error: %s: Failed to execute kernel!\n", CompactionKernelNames[k]);
return EXIT_FAILURE;
}
return CL_SUCCESS;
}
int
PreScanBufferRecursive(
cl_mem output_data,
cl_mem input_data,
unsigned int max_group_size,
unsigned int max_work_item_count,
unsigned int element_count,
unsigned int addr_offset,
int level)
{
unsigned int group_size = max_group_size;
unsigned int group_count = (int)fmax(1.0f, (int)ceil((float)element_count / (2.0f * group_size)));
unsigned int work_item_count = 0;
if (group_count > 1)
work_item_count = group_size;
else if (IsPowerOfTwo(element_count))
work_item_count = element_count / 2;
else
work_item_count = floorPow2(element_count);
work_item_count = (work_item_count > max_work_item_count) ? max_work_item_count : work_item_count;
unsigned int element_count_per_group = work_item_count * 2;
unsigned int last_group_element_count = element_count - (group_count-1) * element_count_per_group;
unsigned int remaining_work_item_count = (int)fmax(1.0f, last_group_element_count / 2);
remaining_work_item_count = (remaining_work_item_count > max_work_item_count) ? max_work_item_count : remaining_work_item_count;
unsigned int remainder = 0;
size_t last_shared = 0;
if (last_group_element_count != element_count_per_group)
{
remainder = 1;
if(!IsPowerOfTwo(last_group_element_count))
remaining_work_item_count = floorPow2(last_group_element_count);
remaining_work_item_count = (remaining_work_item_count > max_work_item_count) ? max_work_item_count : remaining_work_item_count;
unsigned int padding = (2 * remaining_work_item_count) / NUM_BANKS;
last_shared = sizeof(float) * (2 * remaining_work_item_count + padding);
}
remaining_work_item_count = (remaining_work_item_count > max_work_item_count) ? max_work_item_count : remaining_work_item_count;
size_t global[] = { (int)fmax(1, group_count - remainder) * work_item_count, 1 };
size_t local[] = { work_item_count, 1 };
unsigned int padding = element_count_per_group / NUM_BANKS;
size_t shared = sizeof(float) * (element_count_per_group + padding);
cl_mem partial_sums = ScanPartialSums[level];
int err = CL_SUCCESS;
if (group_count > 1)
{
err = PreScanStoreSum(global, local, shared, output_data, input_data, partial_sums, work_item_count * 2, 0, 0,level,addr_offset);
if(err != CL_SUCCESS)
return err;
if (remainder)
{
size_t last_global[] = { 1 * remaining_work_item_count, 1 };
size_t last_local[] = { remaining_work_item_count, 1 };
err = PreScanStoreSumNonPowerOfTwo(
last_global, last_local, last_shared,
output_data, input_data, partial_sums,
last_group_element_count,
group_count - 1,
element_count - last_group_element_count,level,addr_offset);
if(err != CL_SUCCESS)
return err;
}
err = PreScanBufferRecursive(partial_sums, partial_sums, max_group_size, max_work_item_count, group_count, 0, level + 1);
if(err != CL_SUCCESS)
return err;
err = UniformAdd(global, local, output_data, partial_sums, element_count - last_group_element_count, 0, 0, addr_offset);
if(err != CL_SUCCESS)
return err;
if (remainder)
{
size_t last_global[] = { 1 * remaining_work_item_count, 1 };
size_t last_local[] = { remaining_work_item_count, 1 };
err = UniformAdd(
last_global, last_local,
output_data, partial_sums,
last_group_element_count,
group_count - 1,
element_count - last_group_element_count, addr_offset);
if(err != CL_SUCCESS)
return err;
}
}
else if (IsPowerOfTwo(element_count))
{
err = PreScan(global, local, shared, output_data, input_data, work_item_count * 2, 0, 0, level, addr_offset);
if(err != CL_SUCCESS)
return err;
}
else
{
err = PreScanNonPowerOfTwo(global, local, shared, output_data, input_data, element_count, 0, 0, level, addr_offset);
if(err != CL_SUCCESS)
return err;
}
return CL_SUCCESS;
}
void
PreScanBuffer(
cl_mem CompactIn_data,
cl_mem CompactOut_data,
cl_mem clNumUsefulNodesOutput,
cl_mem ScanResult_data,
cl_mem clNumUsefulNodesInput,
int max_group_size,
int max_work_item_count,
int *clNumUsefulNodes,
int clMaxNumUsefulNodes,
int num_move,
bool final=false)
{
// Scan for each row. Should be able to use segmented scan to scan all rows together!
for (int i=0; i<num_move; i++)
PreScanBufferRecursive(ScanResult_data, CompactIn_data, max_group_size, max_work_item_count, clNumUsefulNodes[i], clMaxNumUsefulNodes*i, 0);
clFinish(b2CLDevice::instance().GetCommandQueue());
ParallelCompactBuffer(CompactIn_data, CompactOut_data, clNumUsefulNodesOutput, ScanResult_data, clNumUsefulNodesInput, clMaxNumUsefulNodes, num_move, final);
}
};
#endif
| 41.638199 | 755 | 0.568152 |
58c064908fd0bb312bc0ff2cae6d378a645c87d8 | 132 | rs | Rust | company-management/src/management/employee.rs | Den4200/simple-rust-projects | f5863de03b86014447001154df70aac3aae07dfd | [
"MIT"
] | null | null | null | company-management/src/management/employee.rs | Den4200/simple-rust-projects | f5863de03b86014447001154df70aac3aae07dfd | [
"MIT"
] | null | null | null | company-management/src/management/employee.rs | Den4200/simple-rust-projects | f5863de03b86014447001154df70aac3aae07dfd | [
"MIT"
] | null | null | null | #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Employee {
pub full_name: String,
pub department_name: String
}
| 22 | 48 | 0.712121 |
cd7c4ca57a0a6ee4859ef07b837938afef89f75d | 609 | swift | Swift | Flicks/Define.swift | tiennth/coderschool-flicks | a5bd8ec1f668dd788d6b033a28cee20a8733910e | [
"Apache-2.0"
] | null | null | null | Flicks/Define.swift | tiennth/coderschool-flicks | a5bd8ec1f668dd788d6b033a28cee20a8733910e | [
"Apache-2.0"
] | 1 | 2016-03-13T03:56:40.000Z | 2016-03-17T16:43:12.000Z | Flicks/Define.swift | tiennth/coderschool-flicks | a5bd8ec1f668dd788d6b033a28cee20a8733910e | [
"Apache-2.0"
] | null | null | null | //
// Define.swift
// Flicks
//
// Created by Tien on 3/9/16.
// Copyright © 2016 Tien. All rights reserved.
//
import Foundation
import UIKit
let kFlicksErrorDomain = "FlickError"
let kSomethingWentWrongErrorCode = 100
// Appearance
let oddRowColor = 0xF6F6F5
let evenRowColor = 0xFBFBFB
extension UIColor {
class func colorFromRGB(rgbValue:Int) -> UIColor {
return UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0))
}
}
| 21 | 73 | 0.648604 |
abb17848a555fba18a51ef580238749d4287a090 | 976 | rb | Ruby | test/unit/lock_file_test.rb | jsgarvin/admit_one | 42eee744ee8744d5f41fd6059bac69d4202077f9 | [
"MIT"
] | 1 | 2016-11-04T23:28:07.000Z | 2016-11-04T23:28:07.000Z | test/unit/lock_file_test.rb | jsgarvin/admit_one | 42eee744ee8744d5f41fd6059bac69d4202077f9 | [
"MIT"
] | null | null | null | test/unit/lock_file_test.rb | jsgarvin/admit_one | 42eee744ee8744d5f41fd6059bac69d4202077f9 | [
"MIT"
] | null | null | null | require File.expand_path('../../../lib/admit_one', __FILE__)
require 'test/unit'
class LockFileTest < Test::Unit::TestCase
def setup
File.delete(lock_file_path) if File.exist?(lock_file_path)
end
def test_should_create_and_remove_lockfile
block_executed = false
AdmitOne::LockFile.new(:admit_one_lock_file_unit_test) do
block_executed = true
assert(File.exist?(lock_file_path))
end
assert(block_executed)
assert(!File.exist?(lock_file_path))
end
def test_should_not_clobber_another_lock_file
File.open(lock_file_path, "a") { |file| file.write("1\n") }
assert_raise(AdmitOne::LockFailure) do
AdmitOne::LockFile.new(:admit_one_lock_file_unit_test) do
assert false #should never run
end
end
assert(File.exist?(lock_file_path))
File.delete(lock_file_path)
end
#######
private
#######
def lock_file_path
"#{Dir.tmpdir}/admit_one_lock_file_unit_test.lock"
end
end | 25.684211 | 63 | 0.702869 |
1f87bba57b8990bf26a5d70fe766a8197065dc5d | 5,312 | html | HTML | graphic_design.html | TehBunni/brianthai.github.io | fc80397cfd2f04b79580f746fd3b49638efcdf77 | [
"CC-BY-3.0"
] | null | null | null | graphic_design.html | TehBunni/brianthai.github.io | fc80397cfd2f04b79580f746fd3b49638efcdf77 | [
"CC-BY-3.0"
] | null | null | null | graphic_design.html | TehBunni/brianthai.github.io | fc80397cfd2f04b79580f746fd3b49638efcdf77 | [
"CC-BY-3.0"
] | null | null | null | <!DOCTYPE HTML>
<!--
Massively by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Graphic Design - Brian Thai</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.html" class="logo">Graphic Design</a>
</header>
<!-- Nav -->
<nav id="nav">
<ul class="links">
<li><a href="index.html">Programming</a></li>
<li><a href="video_editing.html">Video Editing</a></li>
<li class="active"><a href="graphic_design.html">Graphic Design</a></li>
<!-- <li><a href="hobbies.html">Hobbies</a></li> -->
</ul>
<ul class="icons">
<li><a href="https://twitter.com/TehBunno" class="icon brands fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="https://www.facebook.com/tehbrianthai/" class="icon brands fa-facebook-f"><span class="label">Facebook</span></a></li>
<li><a href="https://www.instagram.com/tehbunni/" class="icon brands fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="https://www.linkedin.com/in/tehbrianthai/" class="icon brands fa-linkedin"><span class="label">LinkedIn</span></a></li>
<li><a href="https://github.com/TehBunni" class="icon brands fa-github"><span class="label">GitHub</span></a></li>
</ul>
</nav>
<!-- Main -->
<div id="main">
<!-- Featured Post -->
<article class="post featured">
<header class="major">
<h1>An Animated World</h1>
<p>As I dove deeper and deeper into video editing and game development, I found that<br />
expanding my skills in graphic design will allow for more creative freedom.<br />
Most of these artworks are NOT drawn by me. I simply animate them.<br />
Currently, I am learning Blender in order to expand my reach into the 3D world.</p>
</header>
</article>
<!-- Posts -->
<section class="posts">
<article>
<header>
<h2>Zagreus (Gif Version)</h2>
</header>
<a class="image fit"><img src="images/graphic_design/Zagreus.gif" alt="" /></a>
<p>Learned how to animate dripping liquids, falling leaves, and smoke + embers.</p>
<ul class="actions special">
<li><a href="https://sjursen.artstation.com/" class="button">Original Artist @AstriLohne</a></li>
</ul>
</article>
<article>
<header>
<h2>Sinon (Gif Version)</h2>
</header>
<a class="image fit"><img src="images/graphic_design/Sinon.gif" alt="" /></a>
<p>My first deep dive into learning the puppet tool in Adobe After Effects.</p>
<ul class="actions special">
<li><a href="https://www.pixiv.net/en/users/4253496" class="button">Original Artist @NkmR8</a></li>
</ul>
</article>
</section>
<!-- Post -->
<section class="post">
<article>
<header>
<h2>Other Projects</h2>
</header>
<ul>
<li>Blueguys VTuber Model</li>
<li>Ryan Higa Animated Twitch Intro + Stinger Transitions</li>
<li>Blender Donut</li>
</ul>
</article>
</section>
</div>
<!-- Footer -->
<footer id="footer">
<section class="split contact">
<section>
<h3>Email</h3>
<p>brian.thai024@gmail.com</p>
</section>
<section>
<h3>Social</h3>
<ul class="icons alt">
<li><a href="https://twitter.com/TehBunno" class="icon brands fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="https://www.facebook.com/tehbrianthai/" class="icon brands fa-facebook-f"><span class="label">Facebook</span></a></li>
<li><a href="https://www.instagram.com/tehbunni/" class="icon brands fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="https://www.linkedin.com/in/tehbrianthai/" class="icon brands fa-linkedin"><span class="label">LinkedIn</span></a></li>
<li><a href="https://github.com/TehBunni" class="icon brands fa-github"><span class="label">GitHub</span></a></li>
</ul>
</section>
</section>
</footer>
<!-- Copyright -->
<div id="copyright">
<ul><li>© Untitled</li><li>Design: <a href="https://html5up.net">HTML5 UP</a></li></ul>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html> | 39.93985 | 141 | 0.57323 |
41d3cfc2c345e8e63504dab95ec701432d39e01b | 4,721 | h | C | GCYProjectDemo/CommonViewController/GCYAlertController/GSAlertView.h | Tony0822/GCYProjectDemo | 23f37959595cdd64a385136513b01240858420b2 | [
"Apache-2.0"
] | null | null | null | GCYProjectDemo/CommonViewController/GCYAlertController/GSAlertView.h | Tony0822/GCYProjectDemo | 23f37959595cdd64a385136513b01240858420b2 | [
"Apache-2.0"
] | null | null | null | GCYProjectDemo/CommonViewController/GCYAlertController/GSAlertView.h | Tony0822/GCYProjectDemo | 23f37959595cdd64a385136513b01240858420b2 | [
"Apache-2.0"
] | null | null | null | ////
//// GSAlertView.h
//// GCYProjectDemo
////
//// Created by TonyYang on 2017/10/29.
//// Copyright © 2017年 TonyYang. All rights reserved.
////
//
//#import <UIKit/UIKit.h>
//
//#define gs_dispatch_main_async_safe(block)\
// if ([NSThread isMainThread]) {\
// block();\
// } else {\
// dispatch_async(dispatch_get_main_queue(), block);\
// }
///**
// 回调主线程(显示alert必须在主线程执行)
//
// @param block 执行块
// */
//static inline void gs_getSafeMainQueue( dispatch_block_t block)
//{
// gs_dispatch_main_async_safe(block);
//}
///**
// alert 按钮执行回调
//
// @param buttonIndex 选中的index
// */
//typedef void (^gsAlertClickBlock)(NSInteger buttonIndex);
//
//void gsShowAlertTwoButton(NSString *title, NSString *message, NSString *cancelButtonTitle, gsAlertClickBlock cancelBolck, NSString * otherButtonTitle, gsAlertClickBlock otherBlock);
//void gsShowAlertOneButton(NSString *title, NSString *message, NSString *cancelButtonTitle, gsAlertClickBlock cancelBlock);
//void gsShowAlertTitle(NSString *title);
//void gsShowAlertMessage(NSString *message);
//void gsShowAlertTitleMessage(NSString *title, NSString *message);
//
//void gsShowToastTitleMessageDismiss(NSString *title, NSString *message, NSTimeInterval duration, gsAlertClickBlock dismissCompletion);
//void gsShowToastTitleDismiss(NSString *title, NSTimeInterval duration, gsAlertClickBlock dismissCompletion);
//void gsShowToastMessageDismiss(NSString *message, NSTimeInterval duration, gsAlertClickBlock dismissCompletion);
//void gsShowToastTitle(NSString *title, NSTimeInterval duration);
//void gsShowToastMessage(NSString *message, NSTimeInterval duration);
//
////void gsShowTextHUDTitleMessage(NSString *title, NSString *message);
////void gsShowTextHUDTitle(NSString *title);
////void gsShowTextHUDMessage(NSString *message);
////
////void gsShowLoadingHUDTitleMessage(NSString *title, NSString *message);
////void gsShowLoadingHUDTitlt(NSString *title);
////void gsShowLoadingHUDMessage(NSString *message);
////
////void gsShowProgressHUDTitleMessage(NSString *title, NSString *message);
////void gsShowProgressHUDTitle(NSString *title);
////void gsShowProgressHUDMessage(NSString *message);
////void gsShowHUDProgress(float progress);
////
////void gsShowHUDSuccessTitleMessage(NSString *title, NSString *message);
////void gsShowHUDSuccessTitle(NSString *title);
////void gsShowHUDSuccessMessage(NSString *message);
////
////void gsShowHUDFailTitleMessage(NSString *title, NSString *message);
////void gsShowHUDFailTitle(NSString *title);
////void gsShowHUDFailMessage(NSString *message);
////void gsDismissHUD();
//
//@interface GSAlertView : UIAlertView
//
///**
// 最多支持两个button
// */
//+ (void)showAlertViewWithTitle:(NSString *)title
// message:(NSString *)message
// cancelButtonTitle:(NSString *)cancelButtonTitle
// otherButtonTitle:(NSString *)otherButtonTitle
// cancelButtonBlock:(gsAlertClickBlock)cancleBlock
// otherButtonBlock:(gsAlertClickBlock)otherBlock;
//
///**
// 不定数量的Alert
// @param otherButtonTitle 其他按钮标题的列表
// */
//+ (void)showAlertViewWithTitle:(NSString *)title
// message:(NSString *)message
// cancelButtonTitle:(NSString *)cancelButtonTitle
// buttonIndexBlock:(gsAlertClickBlock)buttonIndexBlock
// otherButtonTitle:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
//
///**
// 不带按钮自动消失的Toast
// @param duration 显示时间
// @param dismissComoletion 关闭后回调
// */
//+ (void)showToastViewWithTitle:(NSString *)title
// message:(NSString *)message
// duration:(NSTimeInterval)duration
// dismissCompletion:(gsAlertClickBlock)dismissComoletion;
//
/////**
//// 文字HUD
//// */
////+ (void)showTextHUDWithTitle:(NSString *)title
//// message:(NSString *)message;
////
/////**
//// 显示loading
////
//// */
////+ (void)showLoadingHUDWithTitle:(NSString *)title
//// message:(NSString *)message;
////
/////**
//// progressHUD
////
//// */
////+ (void)showProgressHUDWithTitle:(NSString *)title
//// message:(NSString *)message;
//
///**
// progressHUD,进度条进度值
//
// @param progress 进度值
// */
////+ (void)setHUDProgress:(float)progress;
////
/////**
//// HUD共有方法,设置成功状态
////
//// */
////+ (void)setHUDSuccessStateWithTitle:(NSString *)title
//// message:(NSString *)message;
////
/////**
//// HUD共有方法,设置失败状态
////
//// */
////+ (void)setHUDFailStateWithTitle:(NSString *)title
//// message:(NSString *)message;
////
/////**
//// HUD共有方法,关闭HUD
//// */
////+ (void)dismissHUD;
////
//
//
//
//@end
//
| 31.473333 | 183 | 0.670197 |
1f87f57bffb8fea5395cb018f141fb531976ece3 | 270 | html | HTML | src/components/wb-barebone/wb-barebone.html | duboisp/wet-boew-experimental | 677ff45fa7bc8b62c46e84e0bb9be573444d2bff | [
"MIT"
] | 7 | 2016-02-29T11:50:31.000Z | 2021-04-01T04:19:28.000Z | src/components/wb-barebone/wb-barebone.html | duboisp/wet-boew-experimental | 677ff45fa7bc8b62c46e84e0bb9be573444d2bff | [
"MIT"
] | 5 | 2017-01-21T13:41:24.000Z | 2021-12-02T05:18:03.000Z | src/components/wb-barebone/wb-barebone.html | duboisp/wet-boew-experimental | 677ff45fa7bc8b62c46e84e0bb9be573444d2bff | [
"MIT"
] | 21 | 2016-02-07T04:06:08.000Z | 2022-03-30T00:58:02.000Z | ---
title: wb-barebone
layout: default-other
---
<h1><code><wb-barebone></code> - Web Experience Toolkit - version 5 (Wet5)</h1>
<p>To test if the barebone plugin work, in the console you should see an entry</p>
<wb-barebone v="5">
</wb-barebone>
| 27 | 89 | 0.648148 |
2c06a69b32fa5e8f271d5ed33c6c6102a3481901 | 1,935 | swift | Swift | Sources/MusicXML/Complex Types/SystemLayout.swift | himanshusingh/MusicXML | 91412126ad1b5ef7cb79ad88ec39667b28e75f9f | [
"MIT"
] | null | null | null | Sources/MusicXML/Complex Types/SystemLayout.swift | himanshusingh/MusicXML | 91412126ad1b5ef7cb79ad88ec39667b28e75f9f | [
"MIT"
] | null | null | null | Sources/MusicXML/Complex Types/SystemLayout.swift | himanshusingh/MusicXML | 91412126ad1b5ef7cb79ad88ec39667b28e75f9f | [
"MIT"
] | null | null | null | //
// SystemLayout.swift
// MusicXML
//
// Created by James Bean on 5/15/19.
//
/// A system is a group of staves that are read and played simultaneously. System layout includes
/// left and right margins and the vertical distance from the previous system. The system distance
/// is measured from the bottom line of the previous system to the top line of the current system.
/// It is ignored for the first system on a page. The top system distance is measured from the
/// page's top margin to the top line of the first system. It is ignored for all but the first
/// system on a page. Sometimes the sum of measure widths in a system may not equal the system width
/// specified by the layout elements due to roundoff or other errors. The behavior when reading
/// MusicXML files in these cases is application-dependent. For instance, applications may find that
/// the system layout data is more reliable than the sum of the measure widths, and adjust the
/// measure widths accordingly.
public struct SystemLayout {
// MARK: - Instance Properties
// MARK: Elements
public let margins: SystemMargins?
public let distance: Tenths?
public let topSystemDistance: Tenths?
public let dividers: SystemDividers?
// MARK: - Initializers
public init(
margins: SystemMargins? = nil,
distance: Tenths? = nil,
topSystemDistance: Tenths? = nil,
dividers: SystemDividers? = nil
) {
self.margins = margins
self.distance = distance
self.topSystemDistance = topSystemDistance
self.dividers = dividers
}
}
extension SystemLayout: Equatable {}
extension SystemLayout: Codable {
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case margins = "system-margins"
case distance = "system-distance"
case topSystemDistance = "top-system-distance"
case dividers = "system-dividers"
}
}
| 35.833333 | 100 | 0.702842 |
9c5d927ce5d64acf76cacb44a0e336b2fce45d3d | 27,681 | js | JavaScript | apps/wordpress/htdocs/wp-content/plugins/all-in-one-seo-pack/dist/Lite/assets/js/link-format-block.js | adib26/wordpress | b84f48b1f41567dbfdaab656501d8bebef8f07af | [
"Apache-2.0"
] | null | null | null | apps/wordpress/htdocs/wp-content/plugins/all-in-one-seo-pack/dist/Lite/assets/js/link-format-block.js | adib26/wordpress | b84f48b1f41567dbfdaab656501d8bebef8f07af | [
"Apache-2.0"
] | 252 | 2020-03-26T00:09:13.000Z | 2022-03-16T14:42:33.000Z | apps/wordpress/htdocs/wp-content/plugins/all-in-one-seo-pack/dist/Lite/assets/js/link-format-block.js | adib26/wordpress | b84f48b1f41567dbfdaab656501d8bebef8f07af | [
"Apache-2.0"
] | 1 | 2021-05-18T15:20:55.000Z | 2021-05-18T15:20:55.000Z | !function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=36)}([function(e,t){!function(){e.exports=this.wp.element}()},function(e,t){!function(){e.exports=this.wp.i18n}()},function(e,t){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}},function(e,t){!function(){e.exports=this.wp.url}()},function(e,t){!function(){e.exports=this.wp.components}()},function(e,t){!function(){e.exports=this.lodash}()},function(e,t,n){var r;
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var c=typeof r;if("string"===c||"number"===c)e.push(r);else if(Array.isArray(r)&&r.length){var i=o.apply(null,r);i&&e.push(i)}else if("object"===c)for(var l in r)n.call(r,l)&&r[l]&&e.push(l)}}return e.join(" ")}e.exports?(o.default=o,e.exports=o):void 0===(r=function(){return o}.apply(t,[]))||(e.exports=r)}()},function(e,t){function n(t){return e.exports=n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},n(t)}e.exports=n},function(e,t){!function(){e.exports=this.wp.richText}()},function(e,t){function n(){return e.exports=n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(this,arguments)}e.exports=n},function(e,t){!function(){e.exports=this.wp.primitives}()},function(e,t,n){var r=n(21);e.exports=function(e,t){if(null==e)return{};var n,o,c=r(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(c[n]=e[n])}return c}},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t){function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}e.exports=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e}},function(e,t,n){var r=n(22);e.exports=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&r(e,t)}},function(e,t,n){var r=n(23),o=n(2);e.exports=function(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?o(e):t}},function(e,t){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){var r=n(30),o=n(31),c=n(32),i=n(34);e.exports=function(e,t){return r(e)||o(e,t)||c(e,t)||i()}},function(e,t){!function(){e.exports=this.regeneratorRuntime}()},function(e,t){!function(){e.exports=this.wp.blockEditor}()},function(e,t){function n(e,t,n,r,o,c,i){try{var l=e[c](i),a=l.value}catch(e){return void n(e)}l.done?t(a):Promise.resolve(a).then(r,o)}e.exports=function(e){return function(){var t=this,r=arguments;return new Promise((function(o,c){var i=e.apply(t,r);function l(e){n(i,o,c,l,a,"next",e)}function a(e){n(i,o,c,l,a,"throw",e)}l(void 0)}))}}},function(e,t){e.exports=function(e,t){if(null==e)return{};var n,r,o={},c=Object.keys(e);for(r=0;r<c.length;r++)n=c[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}},function(e,t){function n(t,r){return e.exports=n=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},n(t,r)}e.exports=n},function(e,t){function n(t){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?e.exports=n=function(e){return typeof e}:e.exports=n=function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(t)}e.exports=n},,function(e,t){!function(){e.exports=this.wp.htmlEntities}()},function(e,t){!function(){e.exports=this.wp.compose}()},function(e,t){!function(){e.exports=this.wp.data}()},function(e,t){!function(){e.exports=this.wp.dom}()},function(e,t){!function(){e.exports=this.wp.editor}()},function(e,t){e.exports=function(e){if(Array.isArray(e))return e}},function(e,t){e.exports=function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var n=[],r=!0,o=!1,c=void 0;try{for(var i,l=e[Symbol.iterator]();!(r=(i=l.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(e){o=!0,c=e}finally{try{r||null==l.return||l.return()}finally{if(o)throw c}}return n}}},function(e,t,n){var r=n(33);e.exports=function(e,t){if(e){if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}},function(e,t){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}},function(e,t){e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}},,function(e,t,n){"use strict";n.r(t);var r=n(11),o=n.n(r),c=n(12),i=n.n(c),l=n(13),a=n.n(l),s=n(2),u=n.n(s),p=n(14),f=n.n(p),b=n(15),d=n.n(b),m=n(7),O=n.n(m),h=n(0),g=n(1),v=n(4),j=n(8),y=n(3),k=n(19),_=n(25),w=n(10),E=Object(h.createElement)(w.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},Object(h.createElement)(w.Path,{d:"M15.6 7.3h-.7l1.6-3.5-.9-.4-3.9 8.5H9v1.5h2l-1.3 2.8H8.4c-2 0-3.7-1.7-3.7-3.7s1.7-3.7 3.7-3.7H10V7.3H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H9l-1.4 3.2.9.4 5.7-12.5h1.4c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.9 0 5.2-2.3 5.2-5.2 0-2.9-2.4-5.2-5.2-5.2z"})),x=Object(h.createElement)(w.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},Object(h.createElement)(w.Path,{d:"M15.6 7.2H14v1.5h1.6c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.8 0 5.2-2.3 5.2-5.2 0-2.9-2.3-5.2-5.2-5.2zM4.7 12.4c0-2 1.7-3.7 3.7-3.7H10V7.2H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H10v-1.5H8.4c-2 0-3.7-1.7-3.7-3.7zm4.6.9h5.3v-1.5H9.3v1.5z"})),S=n(16),P=n.n(S),C=n(17),T=n.n(C),N=n(5),L=n(9),R=n.n(L),A=n(18),H=n.n(A),I=n(20),F=n.n(I),z=n(6),D=n.n(z),M=n(26),V=n(27),U=n(28);function B(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function W(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?B(Object(n),!0).forEach((function(t){P()(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):B(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var G=[{id:"opensInNewTab",title:Object(g.__)("Open in new tab"),type:"ToggleControl"},{id:"nofollow",title:Object(g.__)('Add "nofollow" to link',"all-in-one-seo-pack"),type:"ToggleControl"},{id:"sponsored",title:Object(g.__)('Add "sponsored" to link',"all-in-one-seo-pack"),type:"ToggleControl"},{id:"ugc",title:Object(g.__)('Add "ugc" to link',"all-in-one-seo-pack"),type:"ToggleControl"},{id:"title",title:Object(g.__)("Add title attribute to link","all-in-one-seo-pack"),type:"TextControl"}],Q=function(e){var t=e.value,n=e.onChange,r=void 0===n?N.noop:n,o=e.settings,c=void 0===o?G:o;if(!c||!c.length)return null;var i=function(e){return function(n){r(W(W({},t),{},P()({},e.id,n)))}},l=c.map((function(e){if("TextControl"===e.type){var n=Object(h.useState)(),o=T()(n,2),c=o[0],l=o[1];return Object(h.createElement)(v.TextControl,{"data-aioseop":"true",className:"block-editor-link-control__setting",key:e.id,label:e.title,onChange:function(e){l(e)},onBlur:function(n){r(W(W({},t),{},P()({},e.id,n.target.value)))},value:c||t[e.id]})}if("ToggleControl"===e.type)return Object(h.createElement)(v.ToggleControl,{className:"block-editor-link-control__setting",key:e.id,label:e.title,onChange:i(e),checked:!!t&&!!t[e.id]})}));return Object(h.createElement)("fieldset",{className:"block-editor-link-control__settings"},Object(h.createElement)(v.VisuallyHidden,{as:"legend"},Object(g.__)("Currently selected link settings")),l)};function q(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},c=Object.keys(e);for(r=0;r<c.length;r++)n=c[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(r=0;r<c.length;r++)n=c[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function J(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}var K=function(e){var t=e.icon,n=e.size,r=void 0===n?24:n,o=$(e,["icon","size"]);return Object(h.cloneElement)(t,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?J(Object(n),!0).forEach((function(t){q(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):J(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({width:r,height:r},o))},X=Object(h.createElement)(w.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"-2 -2 24 24"},Object(h.createElement)(w.Path,{d:"M9 0C4.03 0 0 4.03 0 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zM1.11 9.68h2.51c.04.91.167 1.814.38 2.7H1.84c-.403-.85-.65-1.764-.73-2.7zm8.57-5.4V1.19c.964.366 1.756 1.08 2.22 2 .205.347.386.708.54 1.08l-2.76.01zm3.22 1.35c.232.883.37 1.788.41 2.7H9.68v-2.7h3.22zM8.32 1.19v3.09H5.56c.154-.372.335-.733.54-1.08.462-.924 1.255-1.64 2.22-2.01zm0 4.44v2.7H4.7c.04-.912.178-1.817.41-2.7h3.21zm-4.7 2.69H1.11c.08-.936.327-1.85.73-2.7H4c-.213.886-.34 1.79-.38 2.7zM4.7 9.68h3.62v2.7H5.11c-.232-.883-.37-1.788-.41-2.7zm3.63 4v3.09c-.964-.366-1.756-1.08-2.22-2-.205-.347-.386-.708-.54-1.08l2.76-.01zm1.35 3.09v-3.04h2.76c-.154.372-.335.733-.54 1.08-.464.92-1.256 1.634-2.22 2v-.04zm0-4.44v-2.7h3.62c-.04.912-.178 1.817-.41 2.7H9.68zm4.71-2.7h2.51c-.08.936-.327 1.85-.73 2.7H14c.21-.87.337-1.757.38-2.65l.01-.05zm0-1.35c-.046-.894-.176-1.78-.39-2.65h2.16c.403.85.65 1.764.73 2.7l-2.5-.05zm1-4H13.6c-.324-.91-.793-1.76-1.39-2.52 1.244.56 2.325 1.426 3.14 2.52h.04zm-9.6-2.52c-.597.76-1.066 1.61-1.39 2.52H2.65c.815-1.094 1.896-1.96 3.14-2.52zm-3.15 12H4.4c.324.91.793 1.76 1.39 2.52-1.248-.567-2.33-1.445-3.14-2.55l-.01.03zm9.56 2.52c.597-.76 1.066-1.61 1.39-2.52h1.76c-.82 1.08-1.9 1.933-3.14 2.48l-.01.04z"})),Y=function(e){var t=e.itemProps,n=e.suggestion,r=e.isSelected,o=void 0!==r&&r,c=e.onClick,i=e.isURL,l=void 0!==i&&i,a=e.searchTerm,s=void 0===a?"":a;return Object(h.createElement)(v.Button,R()({},t,{onClick:c,className:D()("block-editor-link-control__search-item",{"is-selected":o,"is-url":l,"is-entity":!l})}),l&&Object(h.createElement)(K,{className:"block-editor-link-control__search-item-icon",icon:X}),Object(h.createElement)("span",{className:"block-editor-link-control__search-item-header"},Object(h.createElement)("span",{className:"block-editor-link-control__search-item-title"},Object(h.createElement)(v.TextHighlight,{text:n.title,highlight:s})),Object(h.createElement)("span",{"aria-hidden":!l,className:"block-editor-link-control__search-item-info"},!l&&(Object(y.safeDecodeURI)(n.url)||""),l&&Object(g.__)("Press ENTER to add this link"))),n.type&&Object(h.createElement)("span",{className:"block-editor-link-control__search-item-type"},n.type))},Z=Object(h.createElement)(w.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"-2 -2 24 24"},Object(h.createElement)(w.Path,{d:"M16 4h2v9H7v3l-5-4 5-4v3h9V4z"})),ee=n(29),te=function(e){var t=e.value,n=e.onChange,r=e.onSelect,o=e.renderSuggestions,c=e.fetchSuggestions,i=e.showInitialSuggestions,l=e.errorMessage,a=Object(h.useState)(),s=T()(a,2),u=s[0],p=s[1];return Object(h.createElement)("form",{onSubmit:function(e){e.preventDefault(),r(u||{url:t})}},Object(h.createElement)("div",{className:"block-editor-link-control__search-input-wrapper"},Object(h.createElement)(ee.URLInput,{className:"block-editor-link-control__search-input",value:t,onChange:function(e,t){n(e),p(t)},placeholder:Object(g.__)("Search or type url"),__experimentalRenderSuggestions:o,__experimentalFetchLinkSuggestions:c,__experimentalHandleURLSuggestions:!0,__experimentalShowInitialSuggestions:i}),Object(h.createElement)("div",{className:"block-editor-link-control__search-actions"},Object(h.createElement)(v.Button,{type:"submit",label:Object(g.__)("Submit"),icon:Z,className:"block-editor-link-control__search-submit"}))),l&&Object(h.createElement)(v.Notice,{className:"block-editor-link-control__search-error",status:"error",isDismissible:!1},l))},ne=function(e){var t=e.searchTerm,n=e.onClick,r=e.itemProps,o=e.isSelected;return t?Object(h.createElement)(v.Button,R()({},r,{className:D()("block-editor-link-control__search-create block-editor-link-control__search-item",{"is-selected":o}),onClick:n}),Object(h.createElement)(v.Icon,{className:"block-editor-link-control__search-item-icon",icon:"insert"}),Object(h.createElement)("span",{className:"block-editor-link-control__search-item-header"},Object(h.createElement)("span",{className:"block-editor-link-control__search-item-title"},Object(h.createInterpolateElement)(Object(g.sprintf)(Object(g.__)("New page: <mark>%s</mark>"),t),{mark:Object(h.createElement)("mark",null)})))):null};function re(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function oe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?re(Object(n),!0).forEach((function(t){P()(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):re(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var ce=Object(v.createSlotFill)("BlockEditorLinkControlViewer"),ie=ce.Slot,le=ce.Fill,ae=function(e){var t=!1;return{promise:new Promise((function(n,r){e.then((function(e){return t?r({isCanceled:!0}):n(e)}),(function(e){return r(t?{isCanceled:!0}:e)}))})),cancel:function(){t=!0}}};function se(e){var t=e.value,n=e.settings,r=e.onChange,o=void 0===r?N.noop:r,c=e.showSuggestions,i=void 0===c||c,l=e.showInitialSuggestions,a=e.forceIsEditingLink,s=e.createSuggestion,u=Object(h.useRef)(),p=Object(h.useRef)(),f=Object(h.useRef)(),b=Object(M.useInstanceId)(se),d=Object(h.useState)(t&&t.url||""),m=T()(d,2),O=m[0],j=m[1],k=Object(h.useState)(void 0!==a?a:!t||!t.url),_=T()(k,2),w=_[0],E=_[1],x=Object(h.useState)(!1),S=T()(x,2),P=S[0],C=S[1],L=Object(h.useState)(null),A=T()(L,2),I=A[0],z=A[1],B=Object(h.useRef)(!1),W=Object(V.useSelect)((function(e){return{fetchSearchSuggestions:(0,e("core/block-editor").getSettings)().__experimentalFetchLinkSuggestions}}),[]).fetchSearchSuggestions,G=t&&Object(y.filterURLForDisplay)(Object(y.safeDecodeURI)(t.url))||"";Object(h.useEffect)((function(){void 0!==a&&a!==w&&E(a)}),[a]),Object(h.useEffect)((function(){B.current&&f.current&&!f.current.contains(document.activeElement)&&(U.focus.focusable.find(f.current)[0]||f.current).focus();B.current=!1}),[w]),Object(h.useEffect)((function(){return function(){u.current&&u.current.cancel(),p.current&&p.current.cancel()}}),[]);var q=function(e){var t="URL",n=Object(y.getProtocol)(e)||"";return n.includes("mailto")&&(t="mailto"),n.includes("tel")&&(t="tel"),Object(N.startsWith)(e,"#")&&(t="internal"),Promise.resolve([{id:e,title:e,url:"URL"===t?Object(y.prependHTTP)(e):e,type:t}])},$=function(){var e=F()(H.a.mark((function e(t,n){var r,o;return H.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Promise.all([W(t,oe({},n.isInitialSuggestions?{perPage:3}:{})),q(t)]);case 2:return r=e.sent,o=!t.includes(" "),r=o&&!n.isInitialSuggestions?r[0].concat(r[1]):r[0],e.abrupt("return",K(t)?r:r.concat({title:t,url:t,type:"__CREATE__"}));case 6:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}();function J(){B.current=!!f.current&&f.current.contains(document.activeElement),E(!1)}function K(e){var t=Object(N.startsWith)(e,"#");return Object(y.isURL)(e)||e&&e.includes("www.")||t}var X=Object(h.useCallback)((function(e,t){return i?K(e)?q(e):$(e,t):Promise.resolve([])}),[q,W]),Z=function(){var e=F()(H.a.mark((function e(t){var n;return H.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return C(!0),z(null),e.prev=2,p.current=ae(Promise.resolve(s(t))),e.next=6,p.current.promise;case 6:n=e.sent,C(!1),n?(o(n),J()):E(!0),e.next=18;break;case 11:if(e.prev=11,e.t0=e.catch(2),!e.t0||!e.t0.isCanceled){e.next=15;break}return e.abrupt("return");case 15:z(e.t0.message||Object(g.__)("An unknown error occurred during creation. Please try again.")),C(!1),E(!0);case 18:case"end":return e.stop()}}),e,null,[[2,11]])})));return function(t){return e.apply(this,arguments)}}(),ee=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E(!1),o(oe(oe({},t),e))},re=Object(h.useMemo)((function(){return{url:t&&t.url}}),[t&&t.url]);return Object(h.createElement)("div",{tabIndex:-1,ref:f,className:"block-editor-link-control"},P&&Object(h.createElement)("div",{className:"block-editor-link-control__loading"},Object(h.createElement)(v.Spinner,null)," ",Object(g.__)("Creating"),"…"),(w||!t)&&!P&&Object(h.createElement)(te,{value:O,onChange:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";j(e)},onSelect:function(){var e=F()(H.a.mark((function e(n){return H.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("__CREATE__"!==n.type){e.next=5;break}return e.next=3,Z(O);case 3:e.next=7;break;case 5:ee(n,t),J();case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),renderSuggestions:i?function(e){var n=e.suggestionsListProps,r=e.buildSuggestionItemProps,c=e.suggestions,i=e.selectedSuggestion,l=e.isLoading,a=e.isInitialSuggestions,u=D()("block-editor-link-control__search-results",{"is-loading":l}),p=["url","mailto","tel","internal"],f=1===c.length&&p.includes(c[0].type.toLowerCase()),d=s&&!f&&!a,m="block-editor-link-control-search-results-label-".concat(b),j=a?Object(g.__)("Recently updated"):Object(g.sprintf)(Object(g.__)('Search results for "%s"'),O),y=Object(h.createElement)(a?h.Fragment:v.VisuallyHidden,{},Object(h.createElement)("span",{className:"block-editor-link-control__search-results-label",id:m},j));return Object(h.createElement)("div",{className:"block-editor-link-control__search-results-wrapper"},y,Object(h.createElement)("div",R()({},n,{className:u,"aria-labelledby":m}),c.map((function(e,n){return d&&"__CREATE__"===e.type?Object(h.createElement)(ne,{searchTerm:O,onClick:F()(H.a.mark((function t(){return H.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Z(e.title);case 2:case"end":return t.stop()}}),t)}))),key:e.type,itemProps:r(e,n),isSelected:n===i}):"__CREATE__"===e.type?null:Object(h.createElement)(Y,{key:"".concat(e.id,"-").concat(e.type),itemProps:r(e,n),suggestion:e,index:n,onClick:function(){J(),o(oe(oe({},t),e))},isSelected:n===i,isURL:p.includes(e.type.toLowerCase()),searchTerm:O})}))))}:null,fetchSuggestions:X,showInitialSuggestions:l,errorMessage:I}),t&&!w&&!P&&Object(h.createElement)(h.Fragment,null,Object(h.createElement)("div",{"aria-label":Object(g.__)("Currently selected"),"aria-selected":"true",className:D()("block-editor-link-control__search-item",{"is-current":!0})},Object(h.createElement)("span",{className:"block-editor-link-control__search-item-header"},Object(h.createElement)(v.ExternalLink,{className:"block-editor-link-control__search-item-title",href:t.url},t&&t.title||G),t&&t.title&&Object(h.createElement)("span",{className:"block-editor-link-control__search-item-info"},G)),Object(h.createElement)(v.Button,{isSecondary:!0,onClick:function(){return E(!0)},className:"block-editor-link-control__search-item-action"},Object(g.__)("Edit")),Object(h.createElement)(ie,{fillProps:re}))),Object(h.createElement)(Q,{key:"aioseop-settings-drawer",value:t,settings:n,onChange:o}))}se.ViewerFill=le;var ue=se;function pe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function fe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pe(Object(n),!0).forEach((function(t){P()(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var be=Object(v.withSpokenMessages)((function(e){var t=e.isActive,n=e.activeAttributes,r=e.addingLink,o=e.value,c=e.onChange,i=e.speak,l=e.stopAddingLink,a=Object(h.useMemo)(N.uniqueId,[r]),s=Object(h.useState)(),u=T()(s,2),p=u[0],f=u[1],b=Object(h.useMemo)((function(){var e=window.getSelection();if(e.rangeCount){var n=e.getRangeAt(0);if(r&&!t)return n;var o=n.startContainer;for(o=o.nextElementSibling||o;o.nodeType!==window.Node.ELEMENT_NODE;)o=o.parentNode;return o.closest("a")}}),[r,o.start,o.end]);n.rel&&n.rel.includes("nofollow"),n.rel&&n.rel.includes("sponsored"),n.rel&&n.rel.includes("ugc");var d=fe({url:n.url,opensInNewTab:"_blank"===n.target,nofollow:!!n.rel&&n.rel.includes("nofollow"),sponsored:!!n.rel&&n.rel.includes("sponsored"),ugc:!!n.rel&&n.rel.includes("ugc"),title:n.title},p);return Object(h.createElement)(v.Popover,{key:a,anchorRef:b,focusOnMount:!!r&&"firstElement",onClose:l,position:"bottom center"},Object(h.createElement)(ue,{value:d,onChange:function(e){e=fe(fe({},p),e);var n=(d.opensInNewTab!==e.opensInNewTab||d.sponsored!==e.sponsored||d.nofollow!==e.nofollow||d.ugc!==e.ugc)&&d.url===e.url,r=n&&void 0===e.url;if(f(r?e:void 0),!r){var a=Object(y.prependHTTP)(e.url),s=function(e){var t=e.url,n=e.opensInNewWindow,r=e.nofollow,o=e.sponsored,c=e.ugc,i=e.title,l={type:"core/link",attributes:{url:t}},a=[];return n&&(l.attributes.target="_blank",a.push("noreferrer noopener")),r&&a.push("nofollow"),o&&a.push("sponsored"),c&&a.push("ugc"),a.length>0&&(l.attributes.rel=a.join(" ")),i&&(l.attributes.title=i),l}({url:a,opensInNewWindow:e.opensInNewTab,nofollow:e.nofollow,sponsored:e.sponsored,ugc:e.ugc,title:e.title});if(Object(j.isCollapsed)(o)&&!t){var u=e.title||a,b=Object(j.applyFormat)(Object(j.create)({text:u}),s,0,u.length);c(Object(j.insert)(o,b))}else c(Object(j.applyFormat)(o,s));n||l(),!function(e){if(!e)return!1;var t=e.trim();if(!t)return!1;if(/^\S+:/.test(t)){var n=Object(y.getProtocol)(t);if(!Object(y.isValidProtocol)(n))return!1;if(Object(N.startsWith)(n,"http")&&!/^https?:\/\/[^\/\s]/i.test(t))return!1;var r=Object(y.getAuthority)(t);if(!Object(y.isValidAuthority)(r))return!1;var o=Object(y.getPath)(t);if(o&&!Object(y.isValidPath)(o))return!1;var c=Object(y.getQueryString)(t);if(c&&!Object(y.isValidQueryString)(c))return!1;var i=Object(y.getFragment)(t);if(i&&!Object(y.isValidFragment)(i))return!1}return!(Object(N.startsWith)(t,"#")&&!Object(y.isValidFragment)(t))}(a)?i(Object(g.__)("Warning: the link has been inserted but may have errors. Please test it.","all-in-one-seo-pack"),"assertive"):i(t?Object(g.__)("Link edited.","all-in-one-seo-pack"):Object(g.__)("Link inserted.","all-in-one-seo-pack"),"assertive")}},forceIsEditingLink:r}))}));function de(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=O()(e);if(t){var o=O()(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return d()(this,n)}}var me=Object(g.__)("Link","all-in-one-seo-pack"),Oe={name:"core/link",title:me,tagName:"a",className:null,attributes:{url:"href",target:"target",rel:"rel",title:"title"},__unstablePasteRule:function(e,t){var n=t.html,r=t.plainText;if(Object(j.isCollapsed)(e))return e;var o=(n||r).replace(/<[^>]+>/g,"").trim();return Object(y.isURL)(o)?(window.console.log("Created link:\n\n",o),Object(j.applyFormat)(e,{type:"core/link",attributes:{url:Object(_.decodeEntities)(o)}})):e},edit:Object(v.withSpokenMessages)(function(e){f()(n,e);var t=de(n);function n(){var e;return i()(this,n),(e=t.apply(this,arguments)).addLink=e.addLink.bind(u()(e)),e.stopAddingLink=e.stopAddingLink.bind(u()(e)),e.onRemoveFormat=e.onRemoveFormat.bind(u()(e)),e.state={addingLink:!1},e}return a()(n,[{key:"addLink",value:function(){var e=this.props,t=e.value,n=e.onChange,r=Object(j.getTextContent)(Object(j.slice)(t));r&&Object(y.isURL)(r)?n(Object(j.applyFormat)(t,{type:"core/link",attributes:{url:r}})):r&&Object(y.isEmail)(r)?n(Object(j.applyFormat)(t,{type:"core/link",attributes:{url:"mailto:".concat(r)}})):this.setState({addingLink:!0})}},{key:"stopAddingLink",value:function(){this.setState({addingLink:!1}),this.props.onFocus()}},{key:"onRemoveFormat",value:function(){var e=this.props,t=e.value,n=e.onChange,r=e.speak;n(Object(j.removeFormat)(t,"core/link")),r(Object(g.__)("Link removed.","all-in-one-seo-pack"),"assertive")}},{key:"render",value:function(){var e=this.props,t=e.isActive,n=e.activeAttributes,r=e.value,o=e.onChange;return Object(h.createElement)(h.Fragment,null,Object(h.createElement)(k.RichTextShortcut,{type:"primary",character:"k",onUse:this.addLink}),Object(h.createElement)(k.RichTextShortcut,{type:"primaryShift",character:"k",onUse:this.onRemoveFormat}),t&&Object(h.createElement)(k.RichTextToolbarButton,{name:"link",icon:E,title:Object(g.__)("Unlink","all-in-one-seo-pack"),onClick:this.onRemoveFormat,isActive:t,shortcutType:"primaryShift",shortcutCharacter:"k"}),!t&&Object(h.createElement)(k.RichTextToolbarButton,{name:"link",icon:x,title:me,onClick:this.addLink,isActive:t,shortcutType:"primary",shortcutCharacter:"k"}),(this.state.addingLink||t)&&Object(h.createElement)(be,{key:"aioseop-inline-link-ui",addingLink:this.state.addingLink,stopAddingLink:this.stopAddingLink,isActive:t,activeAttributes:n,value:r,onChange:o}))}}]),n}(h.Component))},he=wp.richText,ge=he.registerFormatType,ve=he.unregisterFormatType;[Oe].forEach((function(e){var t=e.name,n=o()(e,["name"]);t&&(ve("core/link"),ge(t,n))}))}]); | 4,613.5 | 26,205 | 0.705538 |
bda286b30d43786f0ae304783e7a7c424c0cb6a0 | 488 | swift | Swift | PulsarKit/PulsarKitTests/Models/User.swift | maxoly/PulsarKit | ce5e013cd37460ce0124203f5ebe925a5a26be58 | [
"MIT"
] | 14 | 2015-11-25T11:38:51.000Z | 2021-12-15T11:16:43.000Z | PulsarKit/PulsarKitTests/Models/User.swift | maxoly/PulsarKit | ce5e013cd37460ce0124203f5ebe925a5a26be58 | [
"MIT"
] | 3 | 2020-04-28T13:32:27.000Z | 2021-08-18T07:24:53.000Z | PulsarKit/PulsarKitTests/Models/User.swift | maxoly/PulsarKit | ce5e013cd37460ce0124203f5ebe925a5a26be58 | [
"MIT"
] | 3 | 2015-12-17T14:33:13.000Z | 2020-05-27T19:35:54.000Z | //
// User.swift
// PulsarKitTests
//
// Created by Massimo Oliviero on 14/08/2018.
// Copyright © 2019 Nacoon. All rights reserved.
//
import Foundation
struct User: Hashable {
let id: Int
let name: String
init(id: Int, name: String = "") {
self.id = id
self.name = name
}
static func == (lhs: User, rhs: User) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
| 17.428571 | 51 | 0.55123 |
0c960c32123fe98899d1aea36a071118d99135d2 | 5,654 | py | Python | nemo/collections/nlp/utils/evaluation_utils.py | ParikhKadam/NeMo | ee11f7c4666d410d91f9da33c61f4819ea625013 | [
"Apache-2.0"
] | 1 | 2020-08-04T08:29:41.000Z | 2020-08-04T08:29:41.000Z | nemo/collections/nlp/utils/evaluation_utils.py | ParikhKadam/NeMo | ee11f7c4666d410d91f9da33c61f4819ea625013 | [
"Apache-2.0"
] | 1 | 2020-06-11T00:54:42.000Z | 2020-06-11T00:54:42.000Z | nemo/collections/nlp/utils/evaluation_utils.py | ParikhKadam/NeMo | ee11f7c4666d410d91f9da33c61f4819ea625013 | [
"Apache-2.0"
] | 3 | 2020-03-10T05:10:07.000Z | 2020-12-08T01:33:35.000Z | # =============================================================================
# Copyright 2020 NVIDIA. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import numpy as np
from nemo import logging
def analyze_confusion_matrix(cm, dict, max_pairs=10):
"""
Sort all confusions in the confusion matrix by value and display results.
Print results in a format: (name -> name, value)
Args:
cm: Confusion matrix
dict: Dictionary with key as a name and index as a value (Intents or Slots)
max_pairs: Max number of confusions to print
"""
threshold = 5 # just arbitrary value to take confusion with at least this number
confused_pairs = {}
size = cm.shape[0]
for i in range(size):
res = cm[i].argsort()
for j in range(size):
pos = res[size - j - 1]
# no confusion - same row and column
if pos == i:
continue
elif cm[i][pos] >= threshold:
str = f'{dict[i]} -> {dict[pos]}'
confused_pairs[str] = cm[i][pos]
else:
break
# sort by max confusions and print first max_pairs
sorted_confused_pairs = sorted(confused_pairs.items(), key=lambda x: x[1], reverse=True)
for i, pair_str in enumerate(sorted_confused_pairs):
if i >= max_pairs:
break
logging.info(pair_str)
def errors_per_class(cm, dict):
"""
Summarize confusions per each class in the confusion matrix.
It can be useful both for Intents and Slots.
It counts each confusion twice in both directions.
Args:
cm: Confusion matrix
dict: Dictionary with key as a name and index as a value (Intents or Slots)
"""
size = cm.shape[0]
confused_per_class = {}
total_errors = 0
for class_num in range(size):
sum = 0
for i in range(size):
if i != class_num:
sum += cm[class_num][i]
sum += cm[i][class_num]
confused_per_class[dict[class_num]] = sum
total_errors += sum
# logging.info(f'{dict[class_num]} - {sum}')
logging.info(f'Total errors (multiplied by 2): {total_errors}')
sorted_confused_per_class = sorted(confused_per_class.items(), key=lambda x: x[1], reverse=True)
for conf_str in sorted_confused_per_class:
logging.info(conf_str)
def log_misclassified_queries(intent_labels, intent_preds, queries, intent_dict, limit=50):
"""
Display examples of Intent mistakes.
In a format: Query, predicted and labeled intent names.
"""
logging.info(f'*** Misclassified intent queries (limit {limit}) ***')
cnt = 0
for i in range(len(intent_preds)):
if intent_labels[i] != intent_preds[i]:
query = queries[i].split('\t')[0]
logging.info(
f'{query} (predicted: {intent_dict[intent_preds[i]]} - labeled: {intent_dict[intent_labels[i]]})'
)
cnt = cnt + 1
if cnt >= limit:
break
def log_misclassified_slots(
intent_labels, intent_preds, slot_labels, slot_preds, subtokens_mask, queries, intent_dict, slot_dict, limit=50
):
"""
Display examples of Slot mistakes.
In a format: Query, predicted and labeled intent names and list of predicted and labeled slot numbers.
also prints dictionary of the slots at the start for easier reading.
"""
logging.info('')
logging.info(f'*** Misclassified slots queries (limit {limit}) ***')
# print slot dictionary
logging.info(f'Slot dictionary:')
str = ''
for i, slot in enumerate(slot_dict):
str += f'{i} - {slot}, '
if i % 5 == 4 or i == len(slot_dict) - 1:
logging.info(str)
str = ''
logging.info('----------------')
cnt = 0
for i in range(len(intent_preds)):
cur_slot_pred = slot_preds[i][subtokens_mask[i]]
cur_slot_label = slot_labels[i][subtokens_mask[i]]
if not np.all(cur_slot_pred == cur_slot_label):
query = queries[i].split('\t')[0]
logging.info(
f'{query} (predicted: {intent_dict[intent_preds[i]]} - labeled: {intent_dict[intent_labels[i]]})'
)
logging.info(f'p: {cur_slot_pred}')
logging.info(f'l: {cur_slot_label}')
cnt = cnt + 1
if cnt >= limit:
break
def check_problematic_slots(slot_preds_list, slot_dict):
""" Check non compliance of B- and I- slots for datasets that use such slot encoding. """
cnt = 0
# for sentence in slot_preds:
# slots = sentence.split(" ")
sentence = slot_preds_list
for i in range(len(sentence)):
slot_name = slot_dict[int(sentence[i])]
if slot_name.startswith("I-"):
prev_slot_name = slot_dict[int(sentence[i - 1])]
if slot_name[2:] != prev_slot_name[2:]:
print("Problem: " + slot_name + " - " + prev_slot_name)
cnt += 1
print("Total problematic slots: " + str(cnt))
| 37.197368 | 115 | 0.598161 |
9bb00f82b0f4c522c32d4e9bb8e89bbfc95bec72 | 490 | js | JavaScript | src/store/cache.js | poketo/poketo-reader | a9864da660b7ea41f55aef9166bc7bb2bbf62817 | [
"MIT"
] | 30 | 2018-09-21T06:33:58.000Z | 2022-02-06T14:06:34.000Z | src/store/cache.js | poketo/poketo-reader | a9864da660b7ea41f55aef9166bc7bb2bbf62817 | [
"MIT"
] | 49 | 2018-09-01T17:36:34.000Z | 2022-03-03T10:06:20.000Z | src/store/cache.js | poketo/site | a9864da660b7ea41f55aef9166bc7bb2bbf62817 | [
"MIT"
] | 6 | 2019-06-02T16:36:00.000Z | 2022-02-17T13:32:58.000Z | // @flow
import { getConfiguredCache } from 'money-clip';
// NOTE: this cache version should be bumped any time the schema of the store
// changes shape, or the API responses change. It'll invalidate cached data and
// force a re-fetch.
const apiVersion = 'pqrtebuhhk';
const storeVersion = '1536114047316';
const version = `${apiVersion}-${storeVersion}`;
const maxAge = 432000000; // 5 days in milliseconds
const cache = getConfiguredCache({ version, maxAge });
export default cache;
| 30.625 | 79 | 0.740816 |
5f6a3bf9455b6e90791c2298234889f4babe6606 | 53 | ts | TypeScript | examples/webpack/dll/dll-entry-only/index.ts | turing-fe/weekly | b42bb6cf40acc242741c703f24c068f25dee162f | [
"MIT"
] | 1 | 2022-02-08T09:52:54.000Z | 2022-02-08T09:52:54.000Z | examples/webpack/dll/dll-entry-only/index.ts | turing-fe/weekly | b42bb6cf40acc242741c703f24c068f25dee162f | [
"MIT"
] | null | null | null | examples/webpack/dll/dll-entry-only/index.ts | turing-fe/weekly | b42bb6cf40acc242741c703f24c068f25dee162f | [
"MIT"
] | null | null | null | export { a, b } from './a'
export { c } from './cjs'
| 17.666667 | 26 | 0.509434 |
70a64c5392a59fdd3d1a5328f1ed206ed96a2dda | 217 | lua | Lua | MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/disappearances_psycho_boss.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/disappearances_psycho_boss.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/disappearances_psycho_boss.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | object_mobile_disappearances_psycho_boss = object_mobile_shared_disappearances_psycho_boss:new {
}
ObjectTemplates:addTemplate(object_mobile_disappearances_psycho_boss, "object/mobile/disappearances_psycho_boss.iff")
| 54.25 | 117 | 0.907834 |
b1842b038fb42c087f5d1465c58b74a0d9fd1762 | 984 | h | C | include/Customer.h | Poler2000/MarketSimulation | 0ffbda1c68315da98e6def963a9ad9ac93cdaaa6 | [
"MIT"
] | null | null | null | include/Customer.h | Poler2000/MarketSimulation | 0ffbda1c68315da98e6def963a9ad9ac93cdaaa6 | [
"MIT"
] | null | null | null | include/Customer.h | Poler2000/MarketSimulation | 0ffbda1c68315da98e6def963a9ad9ac93cdaaa6 | [
"MIT"
] | null | null | null | #ifndef MARKETSIMULATION_CUSTOMER_H
#define MARKETSIMULATION_CUSTOMER_H
#include <string>
#include <vector>
#include <map>
#include <memory>
#include "Need.h"
#include "Market.h"
namespace poler::market {
class Customer {
public:
Customer(std::string name, std::uint32_t income,
std::shared_ptr<Market> market, std::vector<std::shared_ptr<Product>>& products);
void run();
void exit();
private:
const uint32_t id_;
const std::string name_;
double income_;
bool isRunning_;
std::shared_ptr<Market> market_;
std::map<std::shared_ptr<Product>, int> needs_;
//std::vector<Need> needs_;
std::vector<std::shared_ptr<Product>> createWishlist();
void goShopping(std::vector<std::shared_ptr<Product>>& wishlist);
static std::uint32_t getId();
static void goToSleep();
void updateNeeds();
};
}
#endif //MARKETSIMULATION_CUSTOMER_H
| 24 | 98 | 0.636179 |
bb2fe580ff5d73a9a3009fb13b626bce40eba2d1 | 911 | html | HTML | manuscript/page-26/body.html | marvindanig/me-smith | 0f070f8e04b37665b301317339d92f19205fdb9e | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | manuscript/page-26/body.html | marvindanig/me-smith | 0f070f8e04b37665b301317339d92f19205fdb9e | [
"BlueOak-1.0.0",
"MIT"
] | 2 | 2020-09-06T09:59:06.000Z | 2021-05-08T00:02:51.000Z | manuscript/page-26/body.html | marvindanig/me-smith | 0f070f8e04b37665b301317339d92f19205fdb9e | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p class="no-indent ">devil. Wait till you see him lay down on the rope. That yap up there at the top of the hill could have done this for you long ago. Here, Windy”—addressing Tubbs—“tie this rope to the X, and make a knot that will hold.”</p><p>“SHE’S A GAME KID, ALL RIGHT,” SAID SMITH TO HIMSELF AT THE TOP OF THE HILL.</p><p>The girl’s words and manner inspired confidence. Interest and relief were in the face of the little man standing at the side of the road.</p><p>“Now, Windy, hand me the rope. I’ll take three turns around my saddle-horn, and when I say ’go’ you see that your team get down in their collars.”</p><p>“She’s a game kid, all right,” said Smith to himself at the top of the hill.</p><p class=" stretch-last-line">When the sorrel pony at the head of the team felt the rope grow taut on the saddle-horn, it lay down to its</p></div> </div> | 911 | 911 | 0.726674 |
c4905a85beee8f0278a6c58b2cbba250a7bbfb51 | 8,629 | c | C | embedded/common/hostinterface/BlockMemory.c | vermar/open-sensor-platform | 18d41770c3fd2ccd57fc37e52922960a5865a843 | [
"Apache-2.0"
] | 50 | 2015-02-20T22:46:14.000Z | 2022-03-12T01:09:48.000Z | embedded/common/hostinterface/BlockMemory.c | vermar/open-sensor-platform | 18d41770c3fd2ccd57fc37e52922960a5865a843 | [
"Apache-2.0"
] | 7 | 2015-06-22T09:03:08.000Z | 2015-12-18T23:49:06.000Z | embedded/common/hostinterface/BlockMemory.c | sensorplatforms/open-sensor-platform | e120c4f236ee30c49ae9d83021f663d290f3d4a7 | [
"Apache-2.0"
] | 24 | 2015-01-10T14:18:21.000Z | 2021-11-29T09:42:09.000Z | /* Open Sensor Platform Project
* https://github.com/sensorplatforms/open-sensor-platform
*
* Copyright (C) 2015 Audience Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*-------------------------------------------------------------------------------------------------*\
| I N C L U D E F I L E S
\*-------------------------------------------------------------------------------------------------*/
#include "BlockMemory.h"
#include "osp-types.h"
/*-------------------------------------------------------------------------------------------------*\
| E X T E R N A L V A R I A B L E S & F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------*\
| P R I V A T E C O N S T A N T S & M A C R O S
\*-------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------*\
| P R I V A T E T Y P E D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/
typedef struct _BlkMem {
void *pFree; /* Pointer to first free memory block */
void *pEnd; /* Pointer to memory block end */
uint32_t BlkSz; /* Memory block size */
uint32_t TotalCnt; /* Total memory blocks in the pool */
uint32_t UsedCnt; /* Total allocated block count */
} BlkMem_t;
/*-------------------------------------------------------------------------------------------------*\
| S T A T I C V A R I A B L E S D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------*\
| F O R W A R D F U N C T I O N D E C L A R A T I O N S
\*-------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------*\
| P U B L I C V A R I A B L E S D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------*\
| P R I V A T E F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------*\
| P U B L I C F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/
/****************************************************************************************************
* @fn InitBlockPool
* Initialize the memory pool with the given block sizes. Memory pool can be a static array
* or one time allocation from a bigger pool/heap. Pool pointer must be 32-bit aligned.
* Memory pool must be initialized using this call after a DECLARE_BLOCK_POOL
*
* @param [IN]pPool - Pointer (32-bit aligned) to the memory pool that needs to be initialized
* @param [IN]poolSize - Total size of the memory pool in bytes that will be divided into blocks
* @param [IN]blkSize - Individual memory block sizes that will be allocated from the pool
*
* @return OSP_STATUS_OK if initialization successful, OSP_STATUS_INVALID_PARAMETER otherwise
*
***************************************************************************************************/
int16_t InitBlockPool( void *pPool, uint32_t poolSize, uint32_t blkSize )
{
/* Initialize memory block system */
BlkMem_t *pBlkPool = (BlkMem_t*)pPool;
void *pEnd;
void *pBlk;
void *pNext;
/* Adjust block size to 32-bit boundary */
blkSize = (blkSize + 3) & ~3;
if (blkSize == 0)
{
return (OSP_STATUS_INVALID_PARAMETER);
}
if ((blkSize + sizeof(BlkMem_t)) > poolSize)
{
return (OSP_STATUS_INVALID_PARAMETER);
}
/* Initialize the block pool structure. */
pBlk = ((uint8_t*)pPool) + sizeof(BlkMem_t);
pBlkPool->pFree = pBlk;
pEnd = ((uint8_t*)pPool) + poolSize;
pBlkPool->pEnd = pEnd;
pBlkPool->BlkSz = blkSize;
pBlkPool->TotalCnt = 0;
pBlkPool->UsedCnt = 0;
/* Link all free blocks using offsets. */
pEnd = ((uint8_t*)pEnd) - blkSize;
while (1)
{
pNext = ((uint8_t*)pBlk) + blkSize;
pBlkPool->TotalCnt++;
if (pNext > pEnd)
break;
*((void **)pBlk) = pNext;
pBlk = pNext;
}
/* End marker */
*((void **)pBlk) = 0;
return OSP_STATUS_OK;
}
/****************************************************************************************************
* @fn AllocBlock
* Allocate a memory block from the given memory pool
*
* @param [IN]pPool - Pointer to the memory pool from which fixed size memory block is requested
*
* @return Pointer to the allocated memory block
*
***************************************************************************************************/
void *AllocBlock( void *pPool )
{
/* Allocate a memory block and return start address. */
void **free;
SETUP_CRITICAL_SECTION();
ENTER_CRITICAL_SECTION();
free = ((BlkMem_t*)pPool)->pFree;
if (free)
{
((BlkMem_t*)pPool)->pFree = *free;
((BlkMem_t*)pPool)->UsedCnt++;
}
EXIT_CRITICAL_SECTION();
return (free);
}
/****************************************************************************************************
* @fn FreeBlock
* Return to the memory pool a block of memory that was previously allocated from it.
*
* @param [IN]pPool - Pointer to the memory pool to which the previously allocated memory block is
* being returned
* @param [IN]pBlock - Pointer to the memory block that is being returned to the pool
*
* @return OSP_STATUS_OK if successful, OSP_STATUS_INVALID_PARAMETER otherwise
*
***************************************************************************************************/
int16_t FreeBlock( void *pPool, void *pBlock )
{
SETUP_CRITICAL_SECTION();
/* Check if the block belongs to pool before trying to free it */
if ((pBlock < pPool) || (pBlock >= ((BlkMem_t*)pPool)->pEnd))
{
return (OSP_STATUS_INVALID_PARAMETER);
}
ENTER_CRITICAL_SECTION();
*((void **)pBlock) = ((BlkMem_t*)pPool)->pFree;
((BlkMem_t*)pPool)->pFree = pBlock;
((BlkMem_t*)pPool)->UsedCnt--;
EXIT_CRITICAL_SECTION();
return OSP_STATUS_OK;
}
/****************************************************************************************************
* @fn GetPoolStats
* Returns the total block count and used blocks count from the given pool
*
* @param [IN]pPool - Pointer to the memory pool that has been initialized
* @param [OUT]pTotalCount - return the total number of blocks in the given pool
* @param [OUT]pUsedCount - return the current used block count
*
* @return none
*
***************************************************************************************************/
void GetPoolStats( void *pPool, uint32_t *pTotalCount, uint32_t *pUsedCount )
{
SETUP_CRITICAL_SECTION();
ENTER_CRITICAL_SECTION();
if (pTotalCount)
{
*pTotalCount = ((BlkMem_t*)pPool)->TotalCnt;
}
if (pUsedCount)
{
*pUsedCount = ((BlkMem_t*)pPool)->UsedCnt;
}
EXIT_CRITICAL_SECTION();
}
/*-------------------------------------------------------------------------------------------------*\
| E N D O F F I L E
\*-------------------------------------------------------------------------------------------------*/
| 41.287081 | 101 | 0.412446 |
9a4263c9580444834aa8df0ce2d10a2f7cd94f6d | 100 | css | CSS | modules/scholorships/client/css/scholorships.css | cNille/stipendify | 7fdd986b54097df983ba819129c22cd6b57a143c | [
"Apache-2.0",
"MIT"
] | 1 | 2016-09-14T13:02:02.000Z | 2016-09-14T13:02:02.000Z | modules/scholorships/client/css/scholorships.css | cNille/stipendify | 7fdd986b54097df983ba819129c22cd6b57a143c | [
"Apache-2.0",
"MIT"
] | 13 | 2016-06-23T17:25:47.000Z | 2017-05-11T23:29:33.000Z | modules/scholorships/client/css/scholorships.css | cNille/stipendify | 7fdd986b54097df983ba819129c22cd6b57a143c | [
"Apache-2.0",
"MIT"
] | null | null | null |
input.ng-invalid {
background-color:#ffdee4;
}
input.ng-valid {
background-color: white;
}
| 12.5 | 29 | 0.67 |
0a6ba4f18a26f53372dfc8e94a0c8335caaa8abd | 1,292 | sql | SQL | recipes/tables/rainfall.sql | svetasmirnova/mysqlcookbook | 8cb370b9b91ef35f4654b774bac019e2b636ac67 | [
"CC0-1.0"
] | 1 | 2022-03-01T16:45:38.000Z | 2022-03-01T16:45:38.000Z | recipes/tables/rainfall.sql | svetasmirnova/mysqlcookbook | 8cb370b9b91ef35f4654b774bac019e2b636ac67 | [
"CC0-1.0"
] | null | null | null | recipes/tables/rainfall.sql | svetasmirnova/mysqlcookbook | 8cb370b9b91ef35f4654b774bac019e2b636ac67 | [
"CC0-1.0"
] | null | null | null | # rainfall.sql
# rainfall table: each record indicates date of measurement and amount
# of precipitation on that day.
# This file sets up the table and runs a self join to calculate
# running totals and averages for amount of precipitation each
# day, assuming no missing days. rainfall2.sql shows the calculations
# if missing days are permitted.
DROP TABLE IF EXISTS rainfall;
#@ _CREATE_TABLE_
CREATE TABLE rainfall
(
date DATE NOT NULL,
precip FLOAT(10,2) NOT NULL,
PRIMARY KEY(date)
);
#@ _CREATE_TABLE_
INSERT INTO rainfall (date, precip)
VALUES
('2014-06-01', 1.5),
('2014-06-02', 0),
('2014-06-03', 0.5),
('2014-06-04', 0),
('2014-06-05', 1.0)
;
SELECT * FROM rainfall;
# calculate cumulative precipation per day, assuming no missing days
SELECT t1.date, t1.precip AS 'daily precip',
SUM(t2.precip) AS 'cum. precip'
FROM rainfall AS t1, rainfall AS t2
WHERE t1.date >= t2.date
GROUP BY t1.date, t1.precip;
# Add columns to show elapsed days and running average of amount of
# precipitation, assuming no missing days
SELECT t1.date, t1.precip AS 'daily precip',
SUM(t2.precip) AS 'cum. precip',
COUNT(t2.precip) AS days,
AVG(t2.precip) AS 'avg. precip'
FROM rainfall AS t1, rainfall AS t2
WHERE t1.date >= t2.date
GROUP BY t1.date, t1.precip;
| 25.84 | 70 | 0.715944 |
a8dd2e6e5ef2e20118ff3dc41463f0cc6e002bdf | 189 | rs | Rust | src/lib.rs | ssssota/svg2png-wasm | 6091103ec6a7c09a948e489bf7af66606f682ec7 | [
"MIT"
] | 50 | 2021-10-13T05:18:25.000Z | 2022-03-02T17:39:18.000Z | src/lib.rs | OpenGG/svg2png-wasm | 38bab828d54a4341a583d35e6ee9d92b0295de31 | [
"MIT"
] | 16 | 2021-09-14T09:19:15.000Z | 2022-01-05T02:01:15.000Z | src/lib.rs | OpenGG/svg2png-wasm | 38bab828d54a4341a583d35e6ee9d92b0295de31 | [
"MIT"
] | 4 | 2021-09-26T15:09:13.000Z | 2022-03-20T16:23:46.000Z | pub mod converter;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn initialize() {
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
| 18.9 | 48 | 0.714286 |
4a5bf3811a5e09878f36f82589fdad1748412ebe | 846 | js | JavaScript | Array/BestTimeToButAndSellStock.js | DorAm/algorithms | 4126e3cdd87d8f6b13c7ebd63da5bdafdc192f74 | [
"MIT"
] | 1 | 2021-04-03T15:50:11.000Z | 2021-04-03T15:50:11.000Z | Array/BestTimeToButAndSellStock.js | DorAm/algorithms | 4126e3cdd87d8f6b13c7ebd63da5bdafdc192f74 | [
"MIT"
] | null | null | null | Array/BestTimeToButAndSellStock.js | DorAm/algorithms | 4126e3cdd87d8f6b13c7ebd63da5bdafdc192f74 | [
"MIT"
] | null | null | null | /**
* Best Time to Buy and Sell Stock:
*
* You are given an array prices where prices[i] is the price of a given stock on the ith day.
* You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the
* future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve
* any profit, return 0.
*
* Time: O(n)
* Space: O(1)
**/
function bestTimeToBuyAndSellStock(prices) {
let maxProfit = 0;
let minPrice = Number.MAX_VALUE;
for (let i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
}
return maxProfit;
}
let prices = [7, 1, 5, 3, 6, 4];
bestTimeToBuyAndSellStock(prices);
| 30.214286 | 116 | 0.641844 |
b9250b479c28c2e043aa743f58bde029d93ae043 | 2,439 | h | C | gcc/libjava/include/jrate/sys/Timer.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | 1 | 2021-06-15T05:43:22.000Z | 2021-06-15T05:43:22.000Z | src/native/src/jrate/sys/Timer.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | src/native/src/jrate/sys/Timer.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | // ************************************************************************
// $Id: Timer.h 429 2004-09-15 20:32:02Z corsaro $
// ************************************************************************
//
// jRate
//
// Copyright (C) 2001-2004 by Angelo Corsaro.
// <corsaro@cse.wustl.edu>
// All Rights Reserved.
//
// Permission to use, copy, modify, and distribute this software and
// its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. I don't make any representations
// about the suitability of this software for any purpose. It is
// provided "as is" without express or implied warranty.
//
//
// *************************************************************************
//
// *************************************************************************
#ifndef _JRATE_SYS_TIMER_H_
#define _JRATE_SYS_TIMER_H_
#include <sys/time.h>
#include "jrate/sys/TimeValue.h"
#include "jrate/sys/TimerManager.h"
#include "jrate/sys/Command.h"
namespace jrate { namespace sys {
class Timer {
public:
typedef enum {SCHEDULED, FIRED, CANCELLED, IDLE} TimerStatus;
public:
Timer(jrate::sys::Command* command,
const jrate::sys::TimeValue& delay,
const jrate::sys::TimeValue& interval
= jrate::sys::TimeValue::zero);
~Timer();
public:
void cancel();
void schedule();
void reschedule();
public:
const TimeValue& appointment() const;
inline TimerStatus status() {
return status_;
}
protected:
inline void status(TimerStatus s) {
status_ = s;
}
void computeAppointment();
public:
bool operator>(const Timer& rhs) const;
public:
//
// TODO: Implement these methods
//
void addHandler(jrate::sys::Command* handler);
void removeHandler(jrate::sys::Command* handler);
void setHandler(jrate::sys::Command* handler);
private:
friend class TimerManager;
void fire();
private:
jrate::sys::Command* handler_;
jrate::sys::TimeValue delay_;
jrate::sys::TimeValue appointment_;
jrate::sys::TimeValue interval_;
TimerStatus status_;
};
}/* jrate */ } /* sys */
#endif /* _JRATE_SYS_TIMER_H_ */
| 26.51087 | 76 | 0.562526 |
fa0f26fb017dbb035a5815ddf48eb74464b5649e | 371 | kt | Kotlin | app/src/main/java/com/kangaroo/wtcoin/data/model/responses/AlitimeResponse.kt | easemob/Creative-Challenge-WTCoin | 372f1ca6d26ba2e9e24295e63280dd888ae51b64 | [
"MIT"
] | null | null | null | app/src/main/java/com/kangaroo/wtcoin/data/model/responses/AlitimeResponse.kt | easemob/Creative-Challenge-WTCoin | 372f1ca6d26ba2e9e24295e63280dd888ae51b64 | [
"MIT"
] | null | null | null | app/src/main/java/com/kangaroo/wtcoin/data/model/responses/AlitimeResponse.kt | easemob/Creative-Challenge-WTCoin | 372f1ca6d26ba2e9e24295e63280dd888ae51b64 | [
"MIT"
] | 1 | 2021-09-16T07:58:37.000Z | 2021-09-16T07:58:37.000Z | package com.kangaroo.miaosha.data.model.responses
import com.squareup.moshi.JsonClass
/**
* 自动生成:by WaTaNaBe on 2021-06-10 15:14.
* alitime
*/
@JsonClass(generateAdapter = true)
data class AlitimeResponse(
val api: String,
val `data`: Data,
val ret: List<String>,
val v: String
)
@JsonClass(generateAdapter = true)
data class Data(
val t: Long
) | 18.55 | 49 | 0.698113 |
009ebf12e3ed16b2ccba539b8c1cf1e2c4737e47 | 262 | sql | SQL | src/Database/Migrations/Create.sql | JKorf/MediaPi | 4b21bb9cfa692534d0098ad947dd99beb7b0c1ed | [
"MIT"
] | 2 | 2018-02-26T15:57:04.000Z | 2019-03-11T15:21:38.000Z | src/Database/Migrations/Create.sql | JKorf/MediaPi | 4b21bb9cfa692534d0098ad947dd99beb7b0c1ed | [
"MIT"
] | 1 | 2018-07-25T16:36:11.000Z | 2018-07-25T16:36:11.000Z | src/Database/Migrations/Create.sql | JKorf/MediaPi | 4b21bb9cfa692534d0098ad947dd99beb7b0c1ed | [
"MIT"
] | null | null | null | CREATE TABLE Instances (Id INTEGER PRIMARY KEY, Name TEXT);
CREATE TABLE Favorites (Id INTEGER);
CREATE TABLE WatchedEpisodes (ShowId INTEGER, EpisodeSeason INTEGER, EpisodeNumber INTEGER, WatchedAt INTEGER);
CREATE TABLE WatchedFiles (URL TEXT, WatchedAt TEXT); | 65.5 | 111 | 0.816794 |
8aaf99c650dcd7cffe3eb25b6f51156c9846d8ff | 391 | rs | Rust | crate/character_selection_model/src/lib.rs | Lighty0410/autexousious | 99d142d8fdbf2076f3fd929f61b8140d47cf6b86 | [
"Apache-2.0",
"MIT"
] | 41 | 2020-03-13T04:45:03.000Z | 2022-01-17T18:13:09.000Z | crate/character_selection_model/src/lib.rs | Lighty0410/autexousious | 99d142d8fdbf2076f3fd929f61b8140d47cf6b86 | [
"Apache-2.0",
"MIT"
] | 61 | 2016-06-19T01:28:12.000Z | 2021-07-17T08:21:44.000Z | crate/character_selection_model/src/lib.rs | Lighty0410/autexousious | 99d142d8fdbf2076f3fd929f61b8140d47cf6b86 | [
"Apache-2.0",
"MIT"
] | 3 | 2020-03-21T21:53:36.000Z | 2021-01-30T01:10:55.000Z | #![deny(missing_debug_implementations, missing_docs)] // kcov-ignore
//! Types used during character selection.
pub use crate::{
character_selection_entity::CharacterSelectionEntity,
character_selections::CharacterSelections,
character_selections_status::CharacterSelectionsStatus,
};
mod character_selection_entity;
mod character_selections;
mod character_selections_status;
| 27.928571 | 68 | 0.823529 |
b8df63cfdd132b12ca93a04ea06ab5b3a4c71713 | 2,298 | swift | Swift | TestKitchen/TestKitchen/classes/Ingredient/recommend/main/view/INgreHeaderView.swift | TJ-93/TestKitchen | f91f3f2f98163d9229fbb48fdf2d3c544e344b87 | [
"MIT"
] | null | null | null | TestKitchen/TestKitchen/classes/Ingredient/recommend/main/view/INgreHeaderView.swift | TJ-93/TestKitchen | f91f3f2f98163d9229fbb48fdf2d3c544e344b87 | [
"MIT"
] | null | null | null | TestKitchen/TestKitchen/classes/Ingredient/recommend/main/view/INgreHeaderView.swift | TJ-93/TestKitchen | f91f3f2f98163d9229fbb48fdf2d3c544e344b87 | [
"MIT"
] | null | null | null | //
// INgreHeaderView.swift
// TestKitchen
//
// Created by qianfeng on 2016/10/27.
// Copyright © 2016年 陶杰. All rights reserved.
//
import UIKit
class INgreHeaderView: UIView {
//点击事件
var jumpClosure:IngreJumpClosure?
var listModel:IngreRecommendWidgetList?{
didSet{
configText((listModel?.title)!)
}
}
//文字
private var titleLabel:UILabel?
//图片
private var imageView:UIImageView?
//左右间距
private var space:CGFloat=40
//文字和图片的间距
private var margin:CGFloat=20
//图片的宽度
private var iconW:CGFloat=32
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor=UIColor(white: 0.8, alpha: 1.0)
let bgView=UIView.createView()
bgView.backgroundColor=UIColor.whiteColor()
bgView.frame=CGRectMake(0, 10, bounds.size.width, 44)
addSubview(bgView)
titleLabel=UILabel.createLabel(nil, textAlignment: .Left, font: UIFont.systemFontOfSize(18))
bgView.addSubview(titleLabel!)
imageView=UIImageView(image: UIImage(named: "more_icon"))
bgView.addSubview(imageView!)
//点击事件
let g=UITapGestureRecognizer(target: self, action: #selector(tapAction))
bgView.addGestureRecognizer(g)
}
@objc private func tapAction(){
if jumpClosure != nil && listModel?.title_link != nil{
jumpClosure!((listModel?.title_link)!)
}
}
private func configText(text:String){
let str=NSString(string: text)
/*
参1:文字的最大范围
参2:文字的显示规范
参3:文字的属性
参4:上下文
*/
let maxW=bounds.size.width-space*2-iconW-margin
let attr=[NSFontAttributeName:UIFont.systemFontOfSize(18)]
let w=str.boundingRectWithSize(CGSize(width: maxW, height: 44), options: .UsesLineFragmentOrigin, attributes: attr, context: nil).size.width
let labelSpaceX=(maxW-w)/2
titleLabel?.text=text
//修改label位置
titleLabel!.frame=CGRectMake(space+labelSpaceX, 0, w, 44)
imageView?.frame=CGRectMake(titleLabel!.frame.origin.x+w+margin, 0, iconW, iconW)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 29.844156 | 148 | 0.629243 |