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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
796f87d53d9c60daea0adfc6758c35cacba2d8ab | 1,830 | swift | Swift | MEGameTracker/Views/Common/Spinnerable/SpinnerNib.swift | mleiv/MEGameTracker | cef2c76b62fffe9ac662b9a820a6ebd54962ef5f | [
"MIT"
] | 2 | 2020-03-08T20:15:21.000Z | 2021-07-19T21:43:05.000Z | MEGameTracker/Views/Common/Spinnerable/SpinnerNib.swift | mleiv/MEGameTracker | cef2c76b62fffe9ac662b9a820a6ebd54962ef5f | [
"MIT"
] | 1 | 2021-12-25T05:38:14.000Z | 2021-12-25T15:23:48.000Z | MEGameTracker/Views/Common/Spinnerable/SpinnerNib.swift | mleiv/MEGameTracker | cef2c76b62fffe9ac662b9a820a6ebd54962ef5f | [
"MIT"
] | 1 | 2021-06-02T20:45:22.000Z | 2021-06-02T20:45:22.000Z | //
// SpinnerNib.swift
// MEGameTracker
//
// Created by Emily Ivie on 5/14/2016.
// Copyright © 2016 urdnot. All rights reserved.
//
import UIKit
final public class SpinnerNib: UIView {
@IBOutlet weak var spinner: UIActivityIndicatorView?
@IBOutlet weak var spinnerLabel: MarkupLabel?
@IBOutlet weak var spacerView: UIView?
@IBOutlet public weak var progressView: UIProgressView?
var title: String? {
didSet {
if oldValue != title {
setupTitle()
}
}
}
var isShowProgress: Bool = false {
didSet {
if oldValue != isShowProgress {
setupProgress()
}
}
}
public func setup() {
setupTitle()
setupProgress()
}
public func setupTitle() {
spinnerLabel?.text = title
spinnerLabel?.isHidden = !(title?.isEmpty == false)
layoutIfNeeded()
}
public func setupProgress() {
spacerView?.isHidden = !isShowProgress
progressView?.isHidden = !isShowProgress
layoutIfNeeded()
}
public func start() {
setupProgress()
progressView?.progress = 0.0
spinner?.startAnimating()
isHidden = false
}
public func startSpinning() {
spinner?.startAnimating()
progressView?.progress = 0.0
}
public func stop() {
spinner?.stopAnimating()
isHidden = true
}
public func updateProgress(percentCompleted: Int) {
let decimalCompleted = Float(percentCompleted) / 100.0
progressView?.setProgress(decimalCompleted, animated: true)
}
public func changeMessage(_ title: String) {
spinnerLabel?.text = title
}
public class func loadNib(title: String? = nil) -> SpinnerNib? {
let bundle = Bundle(for: SpinnerNib.self)
if let view = bundle.loadNibNamed("SpinnerNib", owner: self, options: nil)?.first as? SpinnerNib {
// view.spinner?.color = Styles.colors.tint // Styles.colors.tint
view.title = title
return view
}
return nil
}
}
| 21.27907 | 100 | 0.69071 |
d03a88b7728e86d272d6bb5102124e7fec41ee7e | 940 | dart | Dart | test/iteration/utils.dart | duytruong27/rrule | 9589ec06818b383b97819f57602845e4ac01f8af | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-03-26T21:57:19.000Z | 2021-03-26T21:57:19.000Z | test/iteration/utils.dart | duytruong27/rrule | 9589ec06818b383b97819f57602845e4ac01f8af | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | test/iteration/utils.dart | duytruong27/rrule | 9589ec06818b383b97819f57602845e4ac01f8af | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | import 'package:meta/meta.dart';
import 'package:rrule/rrule.dart';
import 'package:test/test.dart';
import 'package:time_machine/time_machine.dart';
@isTest
void testRecurring(
String description, {
@required RecurrenceRule rrule,
@required LocalDateTime start,
Iterable<LocalDate> expectedDates,
Iterable<LocalDateTime> expectedDateTimes,
bool isInfinite = false,
}) {
assert((expectedDates == null) != (expectedDateTimes == null));
test(description, () {
final expected =
expectedDateTimes ?? expectedDates.map((d) => d.at(LocalTime(9, 0, 0)));
if (isInfinite) {
final actual = rrule.getInstances(start: start).take(expected.length * 2);
expect(
actual.length,
expected.length * 2,
reason: 'Is actually \'infinite\'',
);
expect(actual.take(expected.length), expected);
} else {
expect(rrule.getInstances(start: start), expected);
}
});
}
| 27.647059 | 80 | 0.668085 |
39c0272cdee86e89d1226991dd16cbe2c23b93d9 | 747 | js | JavaScript | lib/utils/requestLogger.js | mwergles/node-api-skeleton | 8a45bfd80439ea1c31bbaeee4c387b7998594067 | [
"MIT"
] | 1 | 2018-06-28T16:39:04.000Z | 2018-06-28T16:39:04.000Z | lib/utils/requestLogger.js | mwergles/node-api-skeleton | 8a45bfd80439ea1c31bbaeee4c387b7998594067 | [
"MIT"
] | null | null | null | lib/utils/requestLogger.js | mwergles/node-api-skeleton | 8a45bfd80439ea1c31bbaeee4c387b7998594067 | [
"MIT"
] | null | null | null | const winston = require('winston')
const format = winston.format.combine(
winston.format.colorize(),
winston.format.timestamp(),
winston.format.align(),
winston.format.printf((info) => {
const {timestamp, level, message} = info
const ts = timestamp.replace(/(.*?)T(.*?)\..*/, '$1 $2')
return `${ts} [${level}]: ${message}`
})
)
const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console({
format: format
})
]
})
module.exports = {
write: function (message) {
const status = message.replace(/\w+\s.*?\s(\d+).*/, '$1')
message = message.replace('\n', '')
if (status >= 400) {
return logger.error(message)
}
logger.info(message)
}
}
| 20.75 | 61 | 0.5917 |
9c5107422190198f3aa7499ba1fcff51b38253a8 | 4,138 | js | JavaScript | Masteradvanced/src/commands/globalwork.js | LadJay/ohinljn | 8da5177fd6e5b7be917805924ef92b31eed31470 | [
"MIT"
] | null | null | null | Masteradvanced/src/commands/globalwork.js | LadJay/ohinljn | 8da5177fd6e5b7be917805924ef92b31eed31470 | [
"MIT"
] | null | null | null | Masteradvanced/src/commands/globalwork.js | LadJay/ohinljn | 8da5177fd6e5b7be917805924ef92b31eed31470 | [
"MIT"
] | null | null | null |
exports.run = (client, message) => {
var cookies = require('cookiesdb')
const moment = require('moment')
require('moment-duration-format')
var lolrandom = Math.floor(Math.random() * 90);
const { RichEmbed } = require('discord.js')
const fs = require("fs")
let upgrade = JSON.parse(fs.readFileSync("./upgrade.json", "utf8"));
let userUp = message.mentions.users.first();
if (!userUp) {
userUp = message.author;
}
if(!upgrade[userUp.id]) upgrade[userUp.id] = {
upgrade: 0
};
fs.writeFile("./upgrade.json", JSON.stringify(upgrade), (err) => {
if (err) console.log(err)
})
let owner = JSON.parse(fs.readFileSync("./owner.json", "utf8"));
let userO = message.mentions.users.first();
if (!userO) {
userO = message.author;
}
if(!owner[userO.id]) owner[userO.id] = {
owner: 0
};
fs.writeFile("./owner.json", JSON.stringify(owner), (err) => {
if (err) console.log(err)
})
if(upgrade[message.author.id].upgrade == 100){
owner[userO.id].owner++;
}
if(upgrade[message.author.id].upgrade == 210){
owner[userO.id].owner++;
}
if( upgrade[userO.id].upgrade == 0){
var embed = new RichEmbed()
.setColor('RANDOM')
.setDescription('You cannot work at the moment! \n You currently have 0 upgrades! Please buy a upgrade from the market \n **Usage**: `+buy upgrade` **NOTE: Lvl 1 Upgrade is Free**')
message.channel.send(embed)
.then(message => {
message.delete(30000);
})
return;
};
const ms = require('parse-ms')
let cooldown = 60000
cookies.fetchCookies(`lastWork_${message.author.id}`).then(i => {
if (i.text !== null && cooldown - (Date.now() - i.text) > 0) {
let timeObj = ms(cooldown - (Date.now() - i.text));
return message.channel.send(`<:error:473988063001837571> Command Ratelimited! \n Available in :** ${timeObj.seconds} seconds** `) .then(message => {
message.delete(8000);
})
}else{
cookies.updateText(`lastWork_${message.author.id}`, Date.now()).then(() => {
let lol = message.author.id === "293805585378574336"
var embed = new RichEmbed()
.setColor('RANDOM')
.setAuthor(message.author.username, message.author.avatarURL)
.setDescription(lol? `:crown: PengiBoat Developer :tools: \n ------__ **Level: ${upgrade[message.author.id].upgrade}**__ ------ `:`**Your Current Level: ${upgrade[message.author.id].upgrade}**`)
.setTimestamp()
.addField( `<a:tickg:473984512708050945> Worked Successfully!`, owner[userO.id].owner > 0 && owner[userO.id].owner < 1000?`You've Received **__${10 * upgrade[userUp.id].upgrade * 2} Coins__** from upgrades and ownership!`:`Reach Workstats Level __100__ To Receive Ownership!! \n ----- __You've Received : ${10 * upgrade[userUp.id].upgrade} Coins__ from your upgrades ----- `)
.setFooter(message.author.username, message.author.avatarURL)
message.channel.send({embed})
if(owner[userO.id].owner > 0 && owner[userO.id].owner < 1000){
return cookies.updateCookies(`globalCredits_${message.author.id}`, 10 * upgrade[userUp.id].upgrade * 2)
}
if(upgrade[userUp.id].upgrade > 0 && upgrade[userUp.id].upgrade < 500){
return cookies.updateCookies(`globalCredits_${message.author.id}`, 10 * upgrade[userUp.id].upgrade)
}
})
}
})
}
exports.config = {
command: 'work',
aliases: [],
plevel: "User",
description: "work to recieve tips",
usage: "work",
category: "Currency"
};
exports.extra = {
hidden: false
}; | 37.279279 | 379 | 0.541083 |
9c287fd8e507d5143611708c76e84eb404049b8e | 3,245 | ts | TypeScript | examples/authentication/cli/src/commands/login.ts | playhaste/haste-sdk | ced86c6c5e33b32376f435857ed2099d8781814e | [
"MIT"
] | 3 | 2021-08-20T12:38:47.000Z | 2021-10-05T16:56:14.000Z | examples/authentication/cli/src/commands/login.ts | playhaste/haste-sdk | ced86c6c5e33b32376f435857ed2099d8781814e | [
"MIT"
] | 1 | 2021-11-05T15:30:51.000Z | 2021-11-05T15:30:51.000Z | examples/authentication/cli/src/commands/login.ts | playhaste/haste-sdk | ced86c6c5e33b32376f435857ed2099d8781814e | [
"MIT"
] | null | null | null | import { flags } from '@oclif/command';
import cli from 'cli-ux';
import os from 'os';
import axios from 'axios';
import { config } from 'dotenv';
import BaseCommand from '../common/base-command';
import Netrc from 'netrc-parser';
import jwtDecode, { JwtPayload } from 'jwt-decode';
interface NetrcEntry {
login: string;
password: string;
}
export default class Login extends BaseCommand {
static description = 'Login to Haste Arcade';
static examples = ['$ haste login'];
static flags = {
help: flags.help({ char: 'h' }),
};
async sleep(ms: number) {
// eslint-disable-next-line no-promise-executor-return
return new Promise((resolve) => setTimeout(resolve, ms));
}
async fetchAuth(
retries: number,
response: { data: { cliUrl: string; token: string; requestorId: string } },
loginSpinner: { fail: (arg0: string) => void },
): Promise<any> {
try {
const accessTokenResponse = await axios.get<{ access_token: string }>(
`${process.env.AUTH_API_URL}${response.data.cliUrl}/${response.data.requestorId}`,
{
headers: { authorization: `Bearer ${response.data.token}` },
},
);
const decoded = jwtDecode<JwtPayload & { 'https://hastearcade.com/email': string }>(
accessTokenResponse.data.access_token,
);
const email = decoded['https://hastearcade.com/email'];
return {
login: email,
password: accessTokenResponse.data.access_token,
} as NetrcEntry;
} catch (error) {
if (retries > 0 && error.response.status >= 400) {
await this.sleep(10_000);
return this.fetchAuth(retries - 1, response, loginSpinner);
}
loginSpinner.fail(`The login was not completed successfully. Please try again. ${error}`);
throw error;
}
}
async run(): Promise<void> {
config({ path: `${__dirname}/.env` });
await Netrc.load();
await this.removeToken();
const response = await axios.post(`${process.env.AUTH_API_URL}/cli`, { description: os.hostname() }, {});
const browserUrl = `${process.env.AUTH_CLIENT_URL}${response.data.browserUrl}`;
this.logCommandStart(
`The following link will open in your browser to login to Haste. If for some reason it does not open automatically please click here: ${browserUrl}`,
);
await cli.open(browserUrl);
const loginSpinner = this.spinner.add('Waiting for you to login within your browser using the link above');
await this.sleep(10_000);
const auth = await this.fetchAuth(3, response, loginSpinner);
this.saveToken(auth);
loginSpinner.succeed('You are successfully logged in.');
}
private async saveToken(entry: NetrcEntry) {
const hosts = ['api.hastearcade.com'];
hosts.forEach((host) => {
if (!Netrc.machines[host]) Netrc.machines[host] = {};
Netrc.machines[host].login = entry.login;
Netrc.machines[host].password = entry.password;
delete Netrc.machines[host].method;
delete Netrc.machines[host].org;
});
await Netrc.save();
}
private async removeToken() {
const hosts = ['api.hastearcade.com'];
hosts.forEach((host) => {
Netrc.machines[host] = {};
});
await Netrc.save();
}
}
| 30.046296 | 155 | 0.6453 |
3e22dbb458b8ffb3c2c05a164849448e6aa1850a | 521 | swift | Swift | MicroNetworkMocks/Sources/Core/MockNetwork.swift | lexorus/MicroNetwork | 8b49d3c2d5712d62d074b1f9d3004a1d7c6abb3d | [
"MIT"
] | null | null | null | MicroNetworkMocks/Sources/Core/MockNetwork.swift | lexorus/MicroNetwork | 8b49d3c2d5712d62d074b1f9d3004a1d7c6abb3d | [
"MIT"
] | 2 | 2020-04-14T18:30:10.000Z | 2020-06-07T21:09:18.000Z | MicroNetworkMocks/Sources/Core/MockNetwork.swift | lexorus/MicroNetwork | 8b49d3c2d5712d62d074b1f9d3004a1d7c6abb3d | [
"MIT"
] | null | null | null | import Foundation
import MicroNetwork
public final class MockNetwork: Network {
public init() {}
public private(set) var dataTaskURL: URLRequest?
public private(set) var dataTaskCompletion: NetworkResult<Data>?
public var dataTaskStub: NetworkTask = MockNetworkTask()
@discardableResult
public func dataTask(with url: URLRequest, completion: @escaping NetworkResult<Data>) -> NetworkTask {
dataTaskURL = url
dataTaskCompletion = completion
return dataTaskStub
}
}
| 28.944444 | 106 | 0.723608 |
68f96aff415e76c1070339fbd052c417bbb69aab | 4,771 | swift | Swift | Project5/Project5/ViewController.swift | walkmanaly/100daysOfSwift | 20e5e36245cbe43028b8f9b53f41a771844ae8f6 | [
"MIT"
] | null | null | null | Project5/Project5/ViewController.swift | walkmanaly/100daysOfSwift | 20e5e36245cbe43028b8f9b53f41a771844ae8f6 | [
"MIT"
] | null | null | null | Project5/Project5/ViewController.swift | walkmanaly/100daysOfSwift | 20e5e36245cbe43028b8f9b53f41a771844ae8f6 | [
"MIT"
] | null | null | null | //
// ViewController.swift
// Project5
//
// Created by Nick on 2019/4/21.
// Copyright © 2019 Nick. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var allWords = [String]()
var useWords = [String]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promotAnser))
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(startGame))
if let allWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") {
if let allWordsStr = try? String(contentsOf: allWordsURL) {
allWords = allWordsStr.components(separatedBy: "\n")
}
}
if allWords.isEmpty {
allWords = ["fail"]
}
startGame()
}
@objc func startGame() {
title = allWords.randomElement()
useWords.removeAll(keepingCapacity: true)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return useWords.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "word", for: indexPath)
cell.textLabel?.text = useWords[indexPath.row]
return cell
}
@objc func promotAnser() {
let ac = UIAlertController(title: "Word", message: "Typing word", preferredStyle: .alert)
ac.addTextField()
let av = UIAlertAction(title: "submit", style: .default) {
[weak self, weak ac] _ in
if let word = ac?.textFields?[0].text {
self?.submit(word)
}
}
ac.addAction(av)
popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
present(ac, animated: true)
}
func submit(_ anser: String) {
print(anser)
let errorTitle: String
let errorMessage: String
let lowcaseWord = anser.lowercased()
if isPossible(word: lowcaseWord) {
if isOriginal(word: lowcaseWord) {
if isReal(word: lowcaseWord) {
useWords.insert(lowcaseWord, at: 0)
let indexPath = IndexPath(row: 0, section: 0)
tableView.insertRows(at: [indexPath], with: .fade)
return
} else {
errorTitle = "Word not recognised"
errorMessage = "You can't just make them up"
handleErrors(errorTitle: errorTitle, errorMessage: errorMessage)
}
} else {
errorTitle = "Word used already"
errorMessage = "Be more original!"
handleErrors(errorTitle: errorTitle, errorMessage: errorMessage)
}
} else {
guard let title = title?.lowercased() else { return }
errorTitle = "Word not possible"
errorMessage = "You can't spell that word from \(title)"
handleErrors(errorTitle: errorTitle, errorMessage: errorMessage)
}
}
func handleErrors(errorTitle: String, errorMessage: String) {
let ac = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
present(ac, animated: true)
}
func isPossible(word: String) -> Bool {
guard var tempWord = title?.lowercased() else { return false }
for letter in word {
if let position = tempWord.firstIndex(of: letter) {
tempWord.remove(at: position)
} else {
return false
}
}
return true
}
func isOriginal(word: String) -> Bool {
return !useWords.contains(word)
}
func isReal(word: String) -> Bool {
if word.count < 3 {
return false
}
if word.first == title?.first {
return false
}
let checker = UITextChecker()
let range = NSRange(location: 0, length: word.utf16.count)
let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
return misspelledRange.location == NSNotFound
}
}
| 33.598592 | 133 | 0.576189 |
401a10e510fd888a0e80ae7b17e7f43702e5703c | 10,258 | py | Python | cad/application.py | rugleb/cad | 0fd3732b57398e4eacfbc4872286254068d1754a | [
"MIT"
] | 3 | 2019-01-28T14:20:23.000Z | 2020-09-09T20:19:23.000Z | cad/application.py | rugleb/cad | 0fd3732b57398e4eacfbc4872286254068d1754a | [
"MIT"
] | 7 | 2019-01-15T08:30:59.000Z | 2019-01-25T17:11:43.000Z | cad/application.py | rugleb/CAD | 0fd3732b57398e4eacfbc4872286254068d1754a | [
"MIT"
] | 1 | 2021-07-19T07:28:25.000Z | 2021-07-19T07:28:25.000Z | import os
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from cad.sketch import Sketch
from cad.solver import *
directory = os.path.dirname(__file__)
def icon_path(name: str) -> str:
return os.path.join(directory, 'icons', name)
class Application(QMainWindow):
def __init__(self, *args):
super().__init__(*args)
self.sketch = None
self.menu = None
self.toolBar = None
self.toolBarGroup = None
self.initSketch()
self.initMenuBar()
self.initToolBar()
self.initStatusBar()
self.initGeometry()
self.setWindowTitle('Sketch')
def initSketch(self):
self.sketch = Sketch(self)
self.setCentralWidget(self.sketch)
def initMenuBar(self):
self.menu = self.menuBar()
file = self.menu.addMenu('File')
file.addAction(self.exitAction())
file.addAction(self.openAction())
file.addAction(self.saveAction())
edit = self.menu.addMenu('Edit')
edit.addAction(self.undoAction())
edit.addAction(self.copyAction())
edit.addAction(self.pasteAction())
edit.addAction(self.deleteAction())
def undoAction(self):
action = QAction('Undo', self.menu)
action.setShortcut('Ctrl+Z')
action.setStatusTip('Undo')
action.setToolTip('Undo')
return action
def copyAction(self):
action = QAction('Copy', self.menu)
action.setShortcut('Ctrl+C')
action.setStatusTip('Copy')
action.setToolTip('Copy')
return action
def pasteAction(self):
action = QAction('Paste', self.menu)
action.setShortcut('Ctrl+V')
action.setStatusTip('Paste')
action.setToolTip('Paste')
return action
def deleteAction(self):
action = QAction('Delete', self.menu)
action.setShortcut('Delete')
action.setStatusTip('Delete')
action.setToolTip('Delete')
return action
def exitAction(self):
action = QAction('Exit', self.menu)
action.setShortcut('Ctrl+Q')
action.setToolTip('Close application')
action.setStatusTip('Close application')
action.triggered.connect(self.close)
return action
def saveAction(self):
action = QAction('Save As', self.menu)
action.setShortcut('Ctrl+S')
action.setToolTip('Save current application')
action.setStatusTip('Save current application')
action.triggered.connect(self.showSaveDialog)
return action
def openAction(self):
action = QAction('Open', self.menu)
action.setShortcut('Ctrl+O')
action.setToolTip('Open file')
action.setStatusTip('Open file')
action.triggered.connect(self.showOpenDialog)
return action
def initToolBar(self):
self.toolBar = self.addToolBar('Drawing')
self.toolBarGroup = QActionGroup(self.toolBar)
default = self.disableAction()
actions = [
default,
self.lineAction(),
self.pointAction(),
self.parallelAction(),
# self.perpendicularAction(),
self.verticalAction(),
self.horizontalAction(),
self.coincidentAction(),
self.fixedAction(),
self.angleAction(),
self.lengthAction(),
]
for action in actions:
action.setCheckable(True)
action.setParent(self.toolBar)
self.toolBar.addAction(action)
self.toolBarGroup.addAction(action)
default.setChecked(True)
def pointAction(self):
action = QAction('Point')
action.setShortcut('Ctrl+P')
action.setToolTip('Draw point')
action.setStatusTip('Draw point')
action.setIcon(QIcon(icon_path('point.png')))
action.triggered.connect(self.pointActionHandler)
return action
def pointActionHandler(self):
self.sketch.handler = PointDrawing()
def lineAction(self):
action = QAction('Line')
action.setShortcut('Ctrl+L')
action.setToolTip('Draw line')
action.setStatusTip('Draw line')
action.setIcon(QIcon(icon_path('line.png')))
action.triggered.connect(self.lineActionHandler)
return action
def lineActionHandler(self):
self.sketch.handler = LineDrawing()
def horizontalAction(self):
action = QAction('Horizontal')
action.setToolTip('Horizontal constraint')
action.setStatusTip('Horizontal constraint')
action.setIcon(QIcon(icon_path('horizontal.png')))
action.triggered.connect(self.horizontalActionHandler)
return action
def horizontalActionHandler(self):
self.sketch.handler = HorizontalHandler()
def verticalAction(self):
action = QAction('Vertical')
action.setToolTip('Vertical constraint')
action.setStatusTip('Vertical constraint')
action.setIcon(QIcon(icon_path('vertical.png')))
action.triggered.connect(self.verticalActionHandler)
return action
def verticalActionHandler(self):
self.sketch.handler = VerticalHandler()
def angleAction(self):
action = QAction('Angle')
action.setToolTip('Angle constraint')
action.setStatusTip('Angle constraint')
action.setIcon(QIcon(icon_path('angle.png')))
action.triggered.connect(self.angleActionHandler)
return action
def angleActionHandler(self):
def askAngleValue():
label = 'Input angle value:'
title = 'Set angle constraint'
return QInputDialog.getDouble(self.sketch.parent(), title, label, 0)
angle, ok = askAngleValue()
if ok:
self.sketch.handler = AngleHandler(angle)
def lengthAction(self):
action = QAction('Length')
action.setToolTip('Length constraint')
action.setStatusTip('Length constraint')
action.setIcon(QIcon(icon_path('length.png')))
action.triggered.connect(self.lengthActionHandler)
return action
def lengthActionHandler(self):
def askLengthValue():
label = 'Input length value:'
title = 'Set length constraint'
return QInputDialog.getDouble(self.sketch.parent(), title, label, 0, 0)
length, ok = askLengthValue()
if ok:
self.sketch.handler = LengthHandler(length)
def parallelAction(self):
action = QAction('Parallel')
action.setToolTip('Parallel constraint')
action.setStatusTip('Parallel constraint')
action.setIcon(QIcon(icon_path('parallel.png')))
action.triggered.connect(self.parallelsActionHandler)
return action
def parallelsActionHandler(self):
self.sketch.handler = ParallelHandler()
def perpendicularAction(self):
action = QAction('Perpendicular')
action.setToolTip('Perpendicular constraint')
action.setStatusTip('Perpendicular constraint')
action.setIcon(QIcon(icon_path('perpendicular.png')))
action.triggered.connect(self.perpendicularActionHandler)
return action
def perpendicularActionHandler(self):
pass
def coincidentAction(self):
action = QAction('Coincident')
action.setToolTip('Coincident constraint')
action.setStatusTip('Coincident constraint')
action.setIcon(QIcon(icon_path('coincident.png')))
action.triggered.connect(self.coincidentActionHandler)
return action
def coincidentActionHandler(self):
self.sketch.handler = CoincidentHandler()
def fixedAction(self):
action = QAction('Fixed')
action.setToolTip('Fixed constraint')
action.setStatusTip('Fixed constraint')
action.setIcon(QIcon(icon_path('fixed.png')))
action.triggered.connect(self.fixedActionHandler)
return action
def fixedActionHandler(self):
def askCoordinateValue():
label = 'Enter coordinate:'
title = 'Set fixing constraint'
return QInputDialog.getDouble(self.sketch.parent(), title, label, 0)
x, ok = askCoordinateValue()
if ok:
y, ok = askCoordinateValue()
if ok:
self.sketch.handler = FixingHandler(x, y)
def disableAction(self):
action = QAction('Disable')
action.setToolTip('Choose action')
action.setStatusTip('Choose action')
action.setIcon(QIcon(icon_path('cursor.png')))
action.triggered.connect(self.disableActionHandler)
return action
def disableActionHandler(self):
for action in self.toolBarGroup.actions():
action.setChecked(False)
self.toolBarGroup.actions()[0].setChecked(True)
def initStatusBar(self):
self.statusBar().showMessage('Ready')
def initGeometry(self):
desktop = QDesktopWidget()
self.setGeometry(desktop.availableGeometry())
def showOpenDialog(self):
ext = '*.json'
title = 'Open from'
default = '/home/cad.json'
files = QFileDialog().getOpenFileName(self, title, default, ext, options=0)
if files and files[0]:
with open(files[0], 'r') as fp:
fp.read()
def showSaveDialog(self):
ext = '*.json'
title = 'Save as'
default = '/home/cad.json'
files = QFileDialog().getSaveFileName(self, title, default, ext, options=0)
if files and files[0]:
with open(files[0], 'w') as fp:
fp.write('')
def keyPressEvent(self, event):
self.sketch.keyPressEvent(event)
if event.key() == Qt.Key_Escape:
return self.disableActionHandler()
def closeEvent(self, event):
title = 'Close application'
question = 'Are you sure you want to quit?'
default = QMessageBox.No
buttons = QMessageBox.No | QMessageBox.Yes
answer = QMessageBox().question(self, title, question, buttons, default)
if answer == QMessageBox.Yes:
event.accept()
else:
event.ignore()
| 30.990937 | 83 | 0.626633 |
90c0f8e071591a3b8d26ca3393876afd952fc285 | 1,875 | py | Python | alipay/aop/api/domain/SummaryInvoiceBillOpenDTO.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | null | null | null | alipay/aop/api/domain/SummaryInvoiceBillOpenDTO.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | null | null | null | alipay/aop/api/domain/SummaryInvoiceBillOpenDTO.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class SummaryInvoiceBillOpenDTO(object):
def __init__(self):
self._bill_no = None
self._buyer_user_id = None
self._pay_type = None
@property
def bill_no(self):
return self._bill_no
@bill_no.setter
def bill_no(self, value):
self._bill_no = value
@property
def buyer_user_id(self):
return self._buyer_user_id
@buyer_user_id.setter
def buyer_user_id(self, value):
self._buyer_user_id = value
@property
def pay_type(self):
return self._pay_type
@pay_type.setter
def pay_type(self, value):
self._pay_type = value
def to_alipay_dict(self):
params = dict()
if self.bill_no:
if hasattr(self.bill_no, 'to_alipay_dict'):
params['bill_no'] = self.bill_no.to_alipay_dict()
else:
params['bill_no'] = self.bill_no
if self.buyer_user_id:
if hasattr(self.buyer_user_id, 'to_alipay_dict'):
params['buyer_user_id'] = self.buyer_user_id.to_alipay_dict()
else:
params['buyer_user_id'] = self.buyer_user_id
if self.pay_type:
if hasattr(self.pay_type, 'to_alipay_dict'):
params['pay_type'] = self.pay_type.to_alipay_dict()
else:
params['pay_type'] = self.pay_type
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = SummaryInvoiceBillOpenDTO()
if 'bill_no' in d:
o.bill_no = d['bill_no']
if 'buyer_user_id' in d:
o.buyer_user_id = d['buyer_user_id']
if 'pay_type' in d:
o.pay_type = d['pay_type']
return o
| 26.408451 | 77 | 0.585067 |
4562adcff5decc3d0071e9dd52c0bbfd930248fb | 1,404 | swift | Swift | ADCoordinator/Classes/NativeNavigator.swift | emanuelef/Coordinator | cd47f94bbaa792eb48b833a5efe3069a9cd729ee | [
"MIT"
] | 1 | 2020-04-24T08:36:19.000Z | 2020-04-24T08:36:19.000Z | ADCoordinator/Classes/NativeNavigator.swift | emanuelef/Coordinator | cd47f94bbaa792eb48b833a5efe3069a9cd729ee | [
"MIT"
] | 1 | 2020-11-19T07:04:37.000Z | 2020-11-19T07:04:37.000Z | ADCoordinator/Classes/NativeNavigator.swift | emanuelef/Coordinator | cd47f94bbaa792eb48b833a5efe3069a9cd729ee | [
"MIT"
] | 2 | 2020-11-18T15:39:21.000Z | 2021-05-14T15:02:20.000Z | //
// NativeNavigator.swift
// ADCoordinator
//
// Created by Pierre Felgines on 14/02/2020.
//
import Foundation
public protocol NativeNavigator: AnyObject {}
private enum ContextAssociatedKeys {
fileprivate static var deallocObserver: UInt8 = 0
}
extension NativeNavigator where Self: NSObject {
private var deallocObserver: DeallocObserver? {
get {
return objc_getAssociatedObject(
self,
&(ContextAssociatedKeys.deallocObserver)
) as? DeallocObserver
}
set {
guard deallocObserver == nil || newValue == nil else {
preconditionFailure("DeallocObserver is already set")
}
objc_setAssociatedObject(
self,
&(ContextAssociatedKeys.deallocObserver),
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
/**
* Associates an observer to the deallocation of self
* - parameter callback: The callback triggered when self is deallocated
*/
func registerCallbackForDealloc(_ callback: @escaping () -> Void) {
deallocObserver = DeallocObserver(callback: callback)
}
/**
* Removes the current deallocation observer
*/
func removeCallbackForDealloc() {
deallocObserver?.invalidate()
deallocObserver = nil
}
}
| 26 | 76 | 0.61396 |
8d6ff1de1154ef3de113e5203f6c2b748ef63812 | 1,121 | swift | Swift | LS/ChildDetailHeader.swift | codetodayorg/leyladan-sonra-ios | af890093f190679b0f144fe8206edc19cff26e33 | [
"MIT"
] | 1 | 2017-06-24T23:02:14.000Z | 2017-06-24T23:02:14.000Z | LS/ChildDetailHeader.swift | codetodayorg/leyladan-sonra-ios | af890093f190679b0f144fe8206edc19cff26e33 | [
"MIT"
] | 4 | 2017-06-11T00:58:37.000Z | 2017-06-11T01:03:45.000Z | LS/ChildDetailHeader.swift | EnesCakir/leyladan-sonra-ios | af890093f190679b0f144fe8206edc19cff26e33 | [
"MIT"
] | null | null | null | //
// ChildDetailHeader.swift
// LS
//
// Created by Mustafa Enes Cakir on 6/12/16.
// Copyright © 2016 EnesCakir. All rights reserved.
//
import UIKit
import MXParallaxHeader
import AlamofireImage
class ChildDetailHeader: UIView, MXParallaxHeaderProtocol {
@IBOutlet weak var childPhoto: UIImageView!
class func instanciateFromNib() -> ChildDetailHeader {
return Bundle.main.loadNibNamed("ChildDetailHeader", owner: nil, options: nil)![0] as! ChildDetailHeader
}
func setChild(_ child:Child) {
// childName.text = child.name
childPhoto.af_setImage(
withURL: URL(string: Constants.URL.Child(child.image.URL))!,
placeholderImage: UIImage(named: "childNoPhoto"),
imageTransition: .crossDissolve(0.2),
completion: { (_) -> Void in })
}
// MARK: - <MXParallaxHeader>
func parallaxHeaderDidScroll(_ parallaxHeader: MXParallaxHeader) {
// let angle = parallaxHeader.progress * CGFloat(M_PI) * 2
// print(angle)
// self.childPhoto.transform = CGAffineTransformRotate(CGAffineTransformIdentity, angle/3)
}
}
| 26.690476 | 108 | 0.685995 |
3085d842506316eeba3bcf4a716e9886a24d3cc9 | 1,820 | html | HTML | files/realtime.html | Fantastic-4-Devs/at_Aura | 6b9e617e0af19460c39a867a413a4aa57a447858 | [
"MIT"
] | null | null | null | files/realtime.html | Fantastic-4-Devs/at_Aura | 6b9e617e0af19460c39a867a413a4aa57a447858 | [
"MIT"
] | 2 | 2022-02-18T14:10:30.000Z | 2022-02-18T14:13:17.000Z | files/realtime.html | Fantastic-4-Devs/at_Aura | 6b9e617e0af19460c39a867a413a4aa57a447858 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>@ Aura</title>
<link href="css/style.css" rel="stylesheet">
<link href="css/schedule.css" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheets.css">
<link rel='stylesheet' href='https://cdn.quilljs.com/1.3.4/quill.snow.css'>
<link rel='stylesheet' href='https://cdn1.stage.codox.io/lib/css/wave.client.css'><link rel="stylesheet" href="./css/realtime.css">
</head>
<body>
<p>Click on the button to copy the invite link and paste it in the @ Aura app to invite your friends</p>
<input type="text" value="https://fantastic-4-devs.github.io/at_Aura/files/realtime.html" id="myInput">
<button onclick="myFunction()">Copy Link</button>
<script>
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(copyText.value);
/* Alert the copied text */
alert("Copied the Invite Link: " + copyText.value);
}
</script>
<!-- partial:index.partial.html -->
<div class="header">
<span>
Get flowing in real-time with your friends
</span>
</div>
<div class="editors">
<div class="quillEditor">
<div id="quillEditor1Toolbar"> </div>
<div id="quillEditor1"> </div>
</div>
<div class="quillEditor">
<div id="quillEditor2"> </div>
</div>
</div>
<a href="motivate.html" target="_blank">Listen LoFi</a>
<!-- partial -->
<script src='https://cdn.quilljs.com/2.0.0-dev.3/quill.js'></script>
<script src='https://cdn1.stage.codox.io/dsm/lib/api/wave.client.js'></script><script src="./js/realtime.js"></script>
</body>
</html>
| 31.929825 | 131 | 0.657143 |
81e829e9565587b10eec31b78e6e44bd5e40d998 | 748 | go | Go | conoha/identity_api_versions.go | is2ei/conoha-api-go-client | 40c4b26bcecb5b65c97dd6987e545611a05b1db5 | [
"MIT"
] | 2 | 2020-01-24T01:54:08.000Z | 2020-04-25T09:49:59.000Z | conoha/identity_api_versions.go | is2ei/conoha-api-go-client | 40c4b26bcecb5b65c97dd6987e545611a05b1db5 | [
"MIT"
] | null | null | null | conoha/identity_api_versions.go | is2ei/conoha-api-go-client | 40c4b26bcecb5b65c97dd6987e545611a05b1db5 | [
"MIT"
] | 1 | 2021-02-03T20:38:03.000Z | 2021-02-03T20:38:03.000Z | package conoha
import (
"context"
"encoding/json"
"net/http"
)
type getIdentityAPIVersionsResponseParam struct {
Versions identityVersionsValues `json:"versions"`
}
type identityVersionsValues struct {
Values []*Version `json:"values"`
}
// IdentityAPIVersions fetches Identity API versions list.
//
// ConoHa API docs: https://www.conoha.jp/docs/identity-get_version_list.html
func (c *Conoha) IdentityAPIVersions(ctx context.Context) ([]*Version, *ResponseMeta, error) {
apiEndPoint := c.IdentityServiceURL
p := getIdentityAPIVersionsResponseParam{}
contents, meta, err := c.buildAndExecRequest(ctx, http.MethodGet, apiEndPoint, nil)
if err == nil {
err = json.Unmarshal(contents, &p)
}
return p.Versions.Values, meta, err
}
| 22.666667 | 94 | 0.748663 |
7ff36df611a6432c060676da786af23d58754cbf | 11,446 | rs | Rust | execution_engine/src/core/resolvers/v1_resolver.rs | arcolife/casper-node | 82c95c06a1b762304ff8c766ac7473dee819b337 | [
"Apache-2.0"
] | 1 | 2021-10-02T11:46:03.000Z | 2021-10-02T11:46:03.000Z | execution_engine/src/core/resolvers/v1_resolver.rs | arcolife/casper-node | 82c95c06a1b762304ff8c766ac7473dee819b337 | [
"Apache-2.0"
] | 1 | 2020-10-09T23:25:54.000Z | 2020-10-10T00:10:18.000Z | execution_engine/src/core/resolvers/v1_resolver.rs | CasperLabs/test-casper-node-cicd | 92d927f7c91de305f60dc8188a37041a3f50a071 | [
"Apache-2.0"
] | null | null | null | use std::cell::RefCell;
use wasmi::{
memory_units::Pages, Error as InterpreterError, FuncInstance, FuncRef, MemoryDescriptor,
MemoryInstance, MemoryRef, ModuleImportResolver, Signature, ValueType,
};
use super::{
error::ResolverError, memory_resolver::MemoryResolver, v1_function_index::FunctionIndex,
};
pub(crate) struct RuntimeModuleImportResolver {
memory: RefCell<Option<MemoryRef>>,
max_memory: u32,
}
impl Default for RuntimeModuleImportResolver {
fn default() -> Self {
RuntimeModuleImportResolver {
memory: RefCell::new(None),
max_memory: 64,
}
}
}
impl MemoryResolver for RuntimeModuleImportResolver {
fn memory_ref(&self) -> Result<MemoryRef, ResolverError> {
self.memory
.borrow()
.as_ref()
.map(Clone::clone)
.ok_or(ResolverError::NoImportedMemory)
}
}
impl ModuleImportResolver for RuntimeModuleImportResolver {
fn resolve_func(
&self,
field_name: &str,
_signature: &Signature,
) -> Result<FuncRef, InterpreterError> {
let func_ref = match field_name {
"read_value" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::ReadFuncIndex.into(),
),
"read_value_local" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::ReadLocalFuncIndex.into(),
),
"load_named_keys" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], Some(ValueType::I32)),
FunctionIndex::LoadNamedKeysFuncIndex.into(),
),
"write" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], None),
FunctionIndex::WriteFuncIndex.into(),
),
"write_local" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], None),
FunctionIndex::WriteLocalFuncIndex.into(),
),
"add" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], None),
FunctionIndex::AddFuncIndex.into(),
),
"new_uref" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], None),
FunctionIndex::NewFuncIndex.into(),
),
"ret" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], None),
FunctionIndex::RetFuncIndex.into(),
),
"get_key" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 5][..], Some(ValueType::I32)),
FunctionIndex::GetKeyFuncIndex.into(),
),
"has_key" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], Some(ValueType::I32)),
FunctionIndex::HasKeyFuncIndex.into(),
),
"put_key" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], None),
FunctionIndex::PutKeyFuncIndex.into(),
),
"gas" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 1][..], None),
FunctionIndex::GasFuncIndex.into(),
),
"is_valid_uref" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], Some(ValueType::I32)),
FunctionIndex::IsValidURefFnIndex.into(),
),
"revert" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 1][..], None),
FunctionIndex::RevertFuncIndex.into(),
),
"add_associated_key" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::AddAssociatedKeyFuncIndex.into(),
),
"remove_associated_key" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], Some(ValueType::I32)),
FunctionIndex::RemoveAssociatedKeyFuncIndex.into(),
),
"update_associated_key" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::UpdateAssociatedKeyFuncIndex.into(),
),
"set_action_threshold" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], Some(ValueType::I32)),
FunctionIndex::SetActionThresholdFuncIndex.into(),
),
"remove_key" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], None),
FunctionIndex::RemoveKeyFuncIndex.into(),
),
"get_caller" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 1][..], Some(ValueType::I32)),
FunctionIndex::GetCallerIndex.into(),
),
"get_blocktime" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 1][..], None),
FunctionIndex::GetBlocktimeIndex.into(),
),
"create_purse" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], Some(ValueType::I32)),
FunctionIndex::CreatePurseIndex.into(),
),
"transfer_to_account" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], Some(ValueType::I32)),
FunctionIndex::TransferToAccountIndex.into(),
),
"transfer_from_purse_to_account" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 6][..], Some(ValueType::I32)),
FunctionIndex::TransferFromPurseToAccountIndex.into(),
),
"transfer_from_purse_to_purse" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 6][..], Some(ValueType::I32)),
FunctionIndex::TransferFromPurseToPurseIndex.into(),
),
"get_balance" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::GetBalanceIndex.into(),
),
"get_phase" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 1][..], None),
FunctionIndex::GetPhaseIndex.into(),
),
"get_system_contract" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::GetSystemContractIndex.into(),
),
"get_main_purse" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 1][..], None),
FunctionIndex::GetMainPurseIndex.into(),
),
"read_host_buffer" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::ReadHostBufferIndex.into(),
),
"create_contract_package_at_hash" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], None),
FunctionIndex::CreateContractPackageAtHash.into(),
),
"create_contract_user_group" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 8][..], Some(ValueType::I32)),
FunctionIndex::CreateContractUserGroup.into(),
),
"add_contract_version" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 10][..], Some(ValueType::I32)),
FunctionIndex::AddContractVersion.into(),
),
"disable_contract_version" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], Some(ValueType::I32)),
FunctionIndex::DisableContractVersion.into(),
),
"call_contract" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 7][..], Some(ValueType::I32)),
FunctionIndex::CallContractFuncIndex.into(),
),
"call_versioned_contract" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 9][..], Some(ValueType::I32)),
FunctionIndex::CallVersionedContract.into(),
),
"get_named_arg_size" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 3][..], Some(ValueType::I32)),
FunctionIndex::GetRuntimeArgsizeIndex.into(),
),
"get_named_arg" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], Some(ValueType::I32)),
FunctionIndex::GetRuntimeArgIndex.into(),
),
"remove_contract_user_group" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], Some(ValueType::I32)),
FunctionIndex::RemoveContractUserGroupIndex.into(),
),
"provision_contract_user_group_uref" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 5][..], Some(ValueType::I32)),
FunctionIndex::ExtendContractUserGroupURefsIndex.into(),
),
"remove_contract_user_group_urefs" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 6][..], Some(ValueType::I32)),
FunctionIndex::RemoveContractUserGroupURefsIndex.into(),
),
"blake2b" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 4][..], Some(ValueType::I32)),
FunctionIndex::Blake2b.into(),
),
#[cfg(feature = "test-support")]
"print" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], None),
FunctionIndex::PrintIndex.into(),
),
_ => {
return Err(InterpreterError::Function(format!(
"host module doesn't export function with name {}",
field_name
)));
}
};
Ok(func_ref)
}
fn resolve_memory(
&self,
field_name: &str,
descriptor: &MemoryDescriptor,
) -> Result<MemoryRef, InterpreterError> {
if field_name == "memory" {
let effective_max = descriptor.maximum().unwrap_or(self.max_memory + 1);
if descriptor.initial() > self.max_memory || effective_max > self.max_memory {
Err(InterpreterError::Instantiation(
"Module requested too much memory".to_owned(),
))
} else {
// Note: each "page" is 64 KiB
let mem = MemoryInstance::alloc(
Pages(descriptor.initial() as usize),
descriptor.maximum().map(|x| Pages(x as usize)),
)?;
*self.memory.borrow_mut() = Some(mem.clone());
Ok(mem)
}
} else {
Err(InterpreterError::Instantiation(
"Memory imported under unknown name".to_owned(),
))
}
}
}
| 45.241107 | 92 | 0.538267 |
f12352b8552bc37209a52ea8f0f5866e4261782a | 226 | rb | Ruby | lib/syscase/example/optee_smc/example6.rb | syscase/syscase-webui | 3a9e8ebb85745760d7058f003483fef609067079 | [
"MIT"
] | null | null | null | lib/syscase/example/optee_smc/example6.rb | syscase/syscase-webui | 3a9e8ebb85745760d7058f003483fef609067079 | [
"MIT"
] | 9 | 2020-05-22T15:37:49.000Z | 2022-03-30T22:48:14.000Z | lib/syscase/example/optee_smc/example6.rb | syscase/syscase-webui | 3a9e8ebb85745760d7058f003483fef609067079 | [
"MIT"
] | null | null | null | # frozen_string_literal: true
class Syscase
class Example
class OPTEESMC
# OPTEE SMC Example 6
class Example6 < self
def describe
[[optee_revision]]
end
end
end
end
end
| 15.066667 | 29 | 0.597345 |
56b3947580188a3942a65363b83473752aa6b721 | 1,552 | swift | Swift | Sources/surfgen/Helpers/Logger.swift | surfstudio/SurfGen | b1899597a8b16683b7dc6bed5702c5b2348ca3e7 | [
"MIT"
] | 10 | 2021-03-14T08:50:27.000Z | 2022-03-30T09:18:58.000Z | Sources/surfgen/Helpers/Logger.swift | surfstudio/SurfGen | b1899597a8b16683b7dc6bed5702c5b2348ca3e7 | [
"MIT"
] | 36 | 2020-11-16T14:10:45.000Z | 2022-03-13T12:38:26.000Z | Sources/surfgen/Helpers/Logger.swift | surfstudio/SurfGen | b1899597a8b16683b7dc6bed5702c5b2348ca3e7 | [
"MIT"
] | 2 | 2021-11-28T17:56:16.000Z | 2021-12-26T08:06:13.000Z | //
// Logger.swift
//
//
// Created by Dmitry Demyanov on 01.12.2020.
//
import Foundation
import SwiftCLI
import SurfGenKit
import PathKit
class Logger {
func print(_ string: String) {
Term.stdout <<< string
}
func printAsList(_ list: [String]) {
Term.stdout <<< "---------------------------------------".bold
list.forEach { Term.stdout <<< "• " + $0 }
Term.stdout <<< "---------------------------------------\n".bold
}
func printGenerationResult(_ result: [ModelType: [Path]]) {
result.forEach {
switch $0.key {
case .entity:
printListWithHeader("Next Enities were generated:".green, list: $0.value.map { $0.lastComponent })
case .entry:
printListWithHeader("Next Entries were generated".green, list: $0.value.map { $0.lastComponent })
case .enum:
printListWithHeader("Next Enums were generated".green, list: $0.value.map { $0.lastComponent })
}
}
}
func printGenerationResult(_ result: [ServicePart: Path]) {
result.forEach {
Term.stdout <<< "\($0.key.rawValue.capitalizingFirstLetter()): ".green + $0.value.lastComponent
}
}
func printListWithHeader(_ header: String, list: [String]) {
guard !list.isEmpty else { return }
Term.stdout <<< header
printAsList(list)
}
func exitWithError(_ string: String) -> Never {
Term.stderr <<< string.red
exit(EXIT_FAILURE)
}
}
| 27.714286 | 114 | 0.547036 |
d9d4cd4fd1b166475bd811bfa04b31353e3cece6 | 114 | sql | SQL | 07_RestWithASPNET _migrations_and_seeders/RestWithASPNET/RestWithASPNET/db/dataset/V2__Populate_Table_Person .sql | Ramos03/RestWithASP-NET5 | 894a4ca4a97c90116b70eb18150fa19c5b07c2b3 | [
"Apache-2.0"
] | null | null | null | 07_RestWithASPNET _migrations_and_seeders/RestWithASPNET/RestWithASPNET/db/dataset/V2__Populate_Table_Person .sql | Ramos03/RestWithASP-NET5 | 894a4ca4a97c90116b70eb18150fa19c5b07c2b3 | [
"Apache-2.0"
] | null | null | null | 07_RestWithASPNET _migrations_and_seeders/RestWithASPNET/RestWithASPNET/db/dataset/V2__Populate_Table_Person .sql | Ramos03/RestWithASP-NET5 | 894a4ca4a97c90116b70eb18150fa19c5b07c2b3 | [
"Apache-2.0"
] | null | null | null | INSERT INTO `person` VALUES (1,'São Paulo','Vinicius','Male','Ramos'),(2,'São Paulo','Vitoria','Female','Alves'); | 114 | 114 | 0.657895 |
39eca703972519ba53bc5d0282765867d0454b7f | 5,024 | java | Java | app/src/main/java/com/Syrine/mnart/Controllers/Fragments/AllPosts.java | Houssem-Esprit/Mnart | a58990cae117affe8e37e083ef3411bb4da9be7f | [
"Apache-2.0"
] | 5 | 2021-07-16T06:36:08.000Z | 2022-02-14T23:50:55.000Z | app/src/main/java/com/Syrine/mnart/Controllers/Fragments/AllPosts.java | Houssem-Esprit/Mnart | a58990cae117affe8e37e083ef3411bb4da9be7f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/Syrine/mnart/Controllers/Fragments/AllPosts.java | Houssem-Esprit/Mnart | a58990cae117affe8e37e083ef3411bb4da9be7f | [
"Apache-2.0"
] | null | null | null | package com.Syrine.mnart.Controllers.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.Syrine.mnart.Controllers.Adapters.PostCatAdapter;
import com.Syrine.mnart.Controllers.Interfaces.SocketCallbackInterface;
import com.Syrine.mnart.Models.PostByCategory;
import com.Syrine.mnart.R;
import com.Syrine.mnart.Utils.DataManager.UserApi;
import com.Syrine.mnart.Utils.DataManager.UtilApi;
import com.Syrine.mnart.Utils.Session;
import com.ramotion.foldingcell.FoldingCell;
import java.util.List;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.socket.client.Socket;
public class AllPosts extends Fragment {
FoldingCell foldingCell;
RecyclerView allPosts_ReceyclerView;
private static final String TAG = "ALL-POSTS_FRAGMENT";
CompositeDisposable disposable = new CompositeDisposable();
LinearLayoutManager linearLayoutManager;
PostCatAdapter postCatAdapter;
List<PostByCategory> myPostsList;
private UserApi userApi;
Socket mSocket;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View viewroot = inflater.inflate(R.layout.fragment_all_posts, container, false);
// notification socket Check
mSocket = Session.getInstance().getSocket();
mSocket.emit("join", Session.getInstance().getUser().getIdUser());
((SocketCallbackInterface)getActivity()).onNotifSocketEmitedToServer();
// UI
allPosts_ReceyclerView = viewroot.findViewById(R.id.allPosts_RecyclerView);
linearLayoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
allPosts_ReceyclerView.setLayoutManager(linearLayoutManager);
userApi = UtilApi.getUserApi();
getLifecycle().addObserver(new PostCatAdapter());
int IdCat = getArguments().getInt("CatID");
userApi.getPostsByCategory(IdCat)
.toObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<PostByCategory>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.d(TAG,"onSubscribe: created");
disposable.add(d);
}
@Override
public void onNext(@NonNull List<PostByCategory> cat) {
Log.d(TAG,"onNext: ");
postCatAdapter = new PostCatAdapter(getContext(),getActivity(),cat,IdCat);
myPostsList = cat;
allPosts_ReceyclerView.setAdapter(postCatAdapter);
//editor.putInt("idUser",user.getIdUser());
//editor.apply();
}
@Override
public void onError(@NonNull Throwable e) {
Log.d(TAG,"onError: ",e);
}
@Override
public void onComplete() {
Log.d(TAG,"onComplete: created");
disposable.clear();
try {
/* if (getArguments().getString("idPost") != null){
String postId = getArguments().getString("idPost");
for(int i=0;i<myPostsList.size();i++){
if (postId == myPostsList.get(i).getId()){
allPosts_ReceyclerView.getLayoutManager().scrollToPosition(myPostsList.indexOf(myPostsList.get(i)));
LinearLayout view = allPosts_ReceyclerView.findViewHolderForAdapterPosition(myPostsList.indexOf(myPostsList.get(i))).itemView.findViewById(R.id.cell_content_id);
view.setVisibility(View.VISIBLE);
}
}
} */
}catch (Exception e ){e.printStackTrace();}
}
});
return viewroot;
}
@Override
public void onDestroy() {
super.onDestroy();
disposable.clear();
}
@Override
public void onDetach() {
super.onDetach();
disposable.clear();
}
} | 36.671533 | 201 | 0.604299 |
970d051e6e1fc1f190b965ddae064a4304f8e322 | 4,199 | lua | Lua | sample/common/shared_modules/tostring.lua | zsutxz/skynet | 22ee65d28f8c1de64f1fd3d7facca658490d4ad1 | [
"MIT"
] | 5 | 2015-01-05T04:46:53.000Z | 2019-04-15T08:07:56.000Z | sample/common/shared_modules/tostring.lua | zsutxz/skynet | 22ee65d28f8c1de64f1fd3d7facca658490d4ad1 | [
"MIT"
] | 2 | 2019-05-05T09:01:42.000Z | 2019-05-05T10:05:17.000Z | sample/common/shared_modules/tostring.lua | zsutxz/skynet | 22ee65d28f8c1de64f1fd3d7facca658490d4ad1 | [
"MIT"
] | null | null | null | -- This script makes tostring convert tables to a
-- representation of their contents.
-- The real tostring:
_tostring = _tostring or tostring
-- Characters that have non-numeric backslash-escaped versions:
local BsChars = {
["\a"] = "\\a",
["\b"] = "\\b",
["\f"] = "\\f",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
["\v"] = "\\v",
["\""] = "\\\"",
["\\"] = "\\\\"}
-- Is Str an "escapeable" character (a non-printing character other than
-- space, a backslash, or a double quote)?
local function IsEscapeable(Char)
return string.find(Char, "[^%w%p]") -- Non-alphanumeric, non-punct.
and Char ~= " " -- Don't count spaces.
or string.find(Char, '[\\"]') -- A backslash or quote.
end
-- Converts an "escapeable" character (a non-printing character,
-- backslash, or double quote) to its backslash-escaped version; the
-- second argument is used so that numeric character codes can have one
-- or two digits unless three are necessary, which means that the
-- returned value may represent both the character in question and the
-- digit after it:
local function EscapeableToEscaped(Char, FollowingDigit)
if IsEscapeable(Char) then
local Format = FollowingDigit == ""
and "\\%d"
or "\\%03d" .. FollowingDigit
return BsChars[Char]
or string.format(Format, string.byte(Char))
else
return Char .. FollowingDigit
end
end
-- Quotes a string in a Lua- and human-readable way. (This is a
-- replacement for string.format's %q placeholder, whose result
-- isn't always human readable.)
local function StrToStr(Str)
-- return '"' .. string.gsub(Str, "(.)(%d?)", EscapeableToEscaped) .. '"'
return '"' .. Str .. '"'
end
-- Lua keywords:
local Keywords = {["and"] = true, ["break"] = true, ["do"] = true,
["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true,
["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true,
["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true,
["repeat"] = true, ["return"] = true, ["then"] = true,
["true"] = true, ["until"] = true, ["while"] = true}
-- Is Str an identifier?
local function IsIdent(Str)
return not Keywords[Str] and string.find(Str, "^[%a_][%w_]*$")
end
-- Converts a non-table to a Lua- and human-readable string:
local function ScalarToStr(Val)
local Ret
local Type = type(Val)
if Type == "string" then
Ret = StrToStr(Val)
elseif Type == "function" or Type == "userdata" or Type == "thread" then
-- Punt:
Ret = "<" .. _tostring(Val) .. ">"
else
Ret = _tostring(Val)
end -- if
return Ret
end
-- Converts a table to a Lua- and human-readable string.
local function TblToStr(Tbl, Seen)
Seen = Seen or {}
local Ret = {}
if not Seen[Tbl] then
Seen[Tbl] = true
if Tbl["tostring"] then
Ret = Tbl:tostring()
else
local LastArrayKey = 0
for Key, Val in pairs(Tbl) do
if type(Key) == "table" then
Key = "[" .. TblToStr(Key, Seen) .. "]"
elseif type(Key) == "boolean" then
Key = "[" .. _tostring(Key) .. "]"
elseif not IsIdent(Key) then
if type(Key) == "number" and Key == LastArrayKey + 1 then
-- Don't mess with Key if it's an array key.
LastArrayKey = Key
else
Key = "[" .. ScalarToStr(Key) .. "]"
end
end
if type(Val) == "table" then
Val = TblToStr(Val, Seen)
else
Val = ScalarToStr(Val)
end
Ret[#Ret + 1] =
(type(Key) == "string"
and (Key .. " = ") -- Explicit key.
or "") -- Implicit array key.
.. Val
end
Ret = "{" .. table.concat(Ret, ", ") .. "}"
end
Seen[Tbl] = nil
else
Ret = "<cycle to " .. _tostring(Tbl) .. ">"
end
return Ret
end
-- A replacement for tostring that prints tables in Lua- and
-- human-readable format:
function table.tostring(Val)
return type(Val) == "table"
and TblToStr(Val)
or _tostring(Val)
end
| 32.053435 | 78 | 0.552036 |
26835370c6e244fc761f76d359b6520e6128102f | 11,438 | java | Java | core/src/test/java/org/elasticsearch/node/NodeTests.java | tidharm/elasticsearch | a34f5fa8127595534d919646d73dd7a88c21fa65 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/elasticsearch/node/NodeTests.java | tidharm/elasticsearch | a34f5fa8127595534d919646d73dd7a88c21fa65 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/elasticsearch/node/NodeTests.java | tidharm/elasticsearch | a34f5fa8127595534d919646d73dd7a88c21fa65 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.node;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.Version;
import org.elasticsearch.bootstrap.BootstrapCheck;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.transport.MockTcpTransportPlugin;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@LuceneTestCase.SuppressFileSystems(value = "ExtrasFS")
public class NodeTests extends ESTestCase {
public void testNodeName() throws IOException {
final String name = randomBoolean() ? randomAlphaOfLength(10) : null;
Settings.Builder settings = baseSettings();
if (name != null) {
settings.put(Node.NODE_NAME_SETTING.getKey(), name);
}
try (Node node = new MockNode(settings.build(), Collections.singleton(MockTcpTransportPlugin.class))) {
final Settings nodeSettings = randomBoolean() ? node.settings() : node.getEnvironment().settings();
if (name == null) {
assertThat(Node.NODE_NAME_SETTING.get(nodeSettings), equalTo(node.getNodeEnvironment().nodeId().substring(0, 7)));
} else {
assertThat(Node.NODE_NAME_SETTING.get(nodeSettings), equalTo(name));
}
}
}
public static class CheckPlugin extends Plugin {
public static final BootstrapCheck CHECK = new BootstrapCheck() {
@Override
public boolean check() {
return false;
}
@Override
public String errorMessage() {
return "boom";
}
};
@Override
public List<BootstrapCheck> getBootstrapChecks() {
return Collections.singletonList(CHECK);
}
}
public void testLoadPluginBootstrapChecks() throws IOException {
final String name = randomBoolean() ? randomAlphaOfLength(10) : null;
Settings.Builder settings = baseSettings();
if (name != null) {
settings.put(Node.NODE_NAME_SETTING.getKey(), name);
}
AtomicBoolean executed = new AtomicBoolean(false);
try (Node node = new MockNode(settings.build(), Arrays.asList(MockTcpTransportPlugin.class, CheckPlugin.class)) {
@Override
protected void validateNodeBeforeAcceptingRequests(Settings settings, BoundTransportAddress boundTransportAddress,
List<BootstrapCheck> bootstrapChecks) throws NodeValidationException {
assertEquals(1, bootstrapChecks.size());
assertSame(CheckPlugin.CHECK, bootstrapChecks.get(0));
executed.set(true);
throw new NodeValidationException("boom");
}
}) {
expectThrows(NodeValidationException.class, () -> node.start());
assertTrue(executed.get());
}
}
public void testWarnIfPreRelease() {
final Logger logger = mock(Logger.class);
final int id = randomIntBetween(1, 9) * 1000000;
final Version releaseVersion = Version.fromId(id + 99);
final Version preReleaseVersion = Version.fromId(id + randomIntBetween(0, 98));
Node.warnIfPreRelease(releaseVersion, false, logger);
verifyNoMoreInteractions(logger);
reset(logger);
Node.warnIfPreRelease(releaseVersion, true, logger);
verify(logger).warn(
"version [{}] is a pre-release version of Elasticsearch and is not suitable for production", releaseVersion + "-SNAPSHOT");
reset(logger);
final boolean isSnapshot = randomBoolean();
Node.warnIfPreRelease(preReleaseVersion, isSnapshot, logger);
verify(logger).warn(
"version [{}] is a pre-release version of Elasticsearch and is not suitable for production",
preReleaseVersion + (isSnapshot ? "-SNAPSHOT" : ""));
}
public void testNodeAttributes() throws IOException {
String attr = randomAlphaOfLength(5);
Settings.Builder settings = baseSettings().put(Node.NODE_ATTRIBUTES.getKey() + "test_attr", attr);
try (Node node = new MockNode(settings.build(), Collections.singleton(MockTcpTransportPlugin.class))) {
final Settings nodeSettings = randomBoolean() ? node.settings() : node.getEnvironment().settings();
assertEquals(attr, Node.NODE_ATTRIBUTES.get(nodeSettings).getAsMap().get("test_attr"));
}
// leading whitespace not allowed
attr = " leading";
settings = baseSettings().put(Node.NODE_ATTRIBUTES.getKey() + "test_attr", attr);
try (Node node = new MockNode(settings.build(), Collections.singleton(MockTcpTransportPlugin.class))) {
fail("should not allow a node attribute with leading whitespace");
} catch (IllegalArgumentException e) {
assertEquals("node.attr.test_attr cannot have leading or trailing whitespace [ leading]", e.getMessage());
}
// trailing whitespace not allowed
attr = "trailing ";
settings = baseSettings().put(Node.NODE_ATTRIBUTES.getKey() + "test_attr", attr);
try (Node node = new MockNode(settings.build(), Collections.singleton(MockTcpTransportPlugin.class))) {
fail("should not allow a node attribute with trailing whitespace");
} catch (IllegalArgumentException e) {
assertEquals("node.attr.test_attr cannot have leading or trailing whitespace [trailing ]", e.getMessage());
}
}
public void testDefaultPathDataSet() throws IOException {
final Path zero = createTempDir().toAbsolutePath();
final Path one = createTempDir().toAbsolutePath();
final Path defaultPathData = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder()
.put("path.home", "/home")
.put("path.data.0", zero)
.put("path.data.1", one)
.put("default.path.data", defaultPathData)
.build();
try (NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings))) {
final Path defaultPathDataWithNodesAndId = defaultPathData.resolve("nodes/0");
Files.createDirectories(defaultPathDataWithNodesAndId);
final NodeEnvironment.NodePath defaultNodePath = new NodeEnvironment.NodePath(defaultPathDataWithNodesAndId);
final boolean indexExists = randomBoolean();
final List<String> indices;
if (indexExists) {
indices = IntStream.range(0, randomIntBetween(1, 3)).mapToObj(i -> UUIDs.randomBase64UUID()).collect(Collectors.toList());
for (final String index : indices) {
Files.createDirectories(defaultNodePath.indicesPath.resolve(index));
}
} else {
indices = Collections.emptyList();
}
final Logger mock = mock(Logger.class);
if (indexExists) {
final IllegalStateException e = expectThrows(
IllegalStateException.class,
() -> Node.checkForIndexDataInDefaultPathData(settings, nodeEnv, mock));
final String message = String.format(
Locale.ROOT,
"detected index data in default.path.data [%s] where there should not be any; check the logs for details",
defaultPathData);
assertThat(e, hasToString(containsString(message)));
verify(mock)
.error("detected index data in default.path.data [{}] where there should not be any", defaultNodePath.indicesPath);
for (final String index : indices) {
verify(mock).info(
"index folder [{}] in default.path.data [{}] must be moved to any of {}",
index,
defaultNodePath.indicesPath,
Arrays.stream(nodeEnv.nodePaths()).map(np -> np.indicesPath).collect(Collectors.toList()));
}
verifyNoMoreInteractions(mock);
} else {
Node.checkForIndexDataInDefaultPathData(settings, nodeEnv, mock);
verifyNoMoreInteractions(mock);
}
}
}
public void testDefaultPathDataNotSet() throws IOException {
final Path zero = createTempDir().toAbsolutePath();
final Path one = createTempDir().toAbsolutePath();
final Settings settings = Settings.builder()
.put("path.home", "/home")
.put("path.data.0", zero)
.put("path.data.1", one)
.build();
try (NodeEnvironment nodeEnv = new NodeEnvironment(settings, new Environment(settings))) {
final Logger mock = mock(Logger.class);
Node.checkForIndexDataInDefaultPathData(settings, nodeEnv, mock);
verifyNoMoreInteractions(mock);
}
}
private static Settings.Builder baseSettings() {
final Path tempDir = createTempDir();
return Settings.builder()
.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), InternalTestCluster.clusterName("single-node-cluster", randomLong()))
.put(Environment.PATH_HOME_SETTING.getKey(), tempDir)
.put(NetworkModule.HTTP_ENABLED.getKey(), false)
.put(NetworkModule.TRANSPORT_TYPE_KEY, "mock-socket-network")
.put(Node.NODE_DATA_SETTING.getKey(), true);
}
}
| 46.877049 | 139 | 0.649414 |
90c6677d9ad90cb18c00684288f369057ef0552c | 2,181 | py | Python | src/Luogu_user.py | haohaoh4/Luogu_difficulty | 365f3169dc57f24969fe90cdcff5127ab95dadc7 | [
"MIT"
] | 2 | 2018-08-29T07:15:46.000Z | 2018-08-29T07:53:46.000Z | src/Luogu_user.py | haohaoh4/Luogu_difficulty | 365f3169dc57f24969fe90cdcff5127ab95dadc7 | [
"MIT"
] | 1 | 2018-09-15T01:13:40.000Z | 2018-09-15T01:13:40.000Z | src/Luogu_user.py | haohaoh4/Luogu_difficulty | 365f3169dc57f24969fe90cdcff5127ab95dadc7 | [
"MIT"
] | 1 | 2018-08-29T07:18:03.000Z | 2018-08-29T07:18:03.000Z | import requests
import logging
from src.Luogu_problem import Problem
logger = logging.getLogger(__name__)
header = {
'Host': 'www.luogu.org',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Referer': 'http://www.baidu.com',
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
}
class User:
uid = 0
name = ""
done_problems = []
done_nums = 0
done_difficulty = [0 in range(0, 8)]
rating = 0
def __init__(self, uid):
req = requests.get("http://www.luogu.org/space/ajax_getuid?username=%s" % uid, headers=header)
if str(req) != "<Response [200]>":
logger.error("Can't access to Luogu %s." % ("https://www.luogu.org/space/ajax_getuid?username=%s" % uid))
raise IOError("Can't access to Luogu.")
req = str(req.content.decode("utf-8"))
if req.find("404") != -1:
logger.error("User %s not found" % uid)
raise ConnectionError("Can't find user %s." % uid)
user_id_begin = req.find("uid\"")
if req.find("\"", user_id_begin + 4) == -1:
user_id_begin = user_id_begin + 5
user_id_end = req.find("\"}}")-1
else:
user_id_begin = user_id_begin + 6
user_id_end = req.find("}}")-1
user_id = req[user_id_begin:user_id_end]
logger.debug("user_id:%s" % user_id)
logger.debug(user_id_begin)
self.uid = user_id
self.get_base_info()
def __str__(self):
return self.name
def get_base_info(self):
url = "http://www.luogu.org/space/show?uid=%s" % self.uid
req = requests.get(url, headers=header)
if str(req) != "<Response [200]>":
logger.error("Can't access to Luogu.requests info %s.URL is %s" % (req, url))
raise IOError("Can't access to Luogu.")
req = req.content.decode('utf-8')
f = "[<a data-pjax href="
begin = 0
while 1:
begin = req.find(f, begin)
begin = begin + 38
end = req.find("\">", begin)
if req[begin:end] == "<head>\n<meta charset=\"utf-8":
break
logger.debug(req[begin:end])
self.done_nums = self.done_nums + 1
self.done_problems.append(Problem(req[begin:end]))
| 30.291667 | 108 | 0.652453 |
fec59dd0f0a6f2ad5511052414483a57445fa595 | 75,594 | html | HTML | docs/html/class_i_ty_actor.html | ostera/Toasty | 26f062e22cc5c68c04d848a5a6e1326280430408 | [
"MIT"
] | null | null | null | docs/html/class_i_ty_actor.html | ostera/Toasty | 26f062e22cc5c68c04d848a5a6e1326280430408 | [
"MIT"
] | null | null | null | docs/html/class_i_ty_actor.html | ostera/Toasty | 26f062e22cc5c68c04d848a5a6e1326280430408 | [
"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"/>
<title>Toasty!: ITyActor Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.4 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="toastylogosmall.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">Toasty! <span id="projectnumber">0.1</span></div>
<div id="projectbrief">A game framework for the Marmalade SDK.</div>
</td>
</tr>
</tbody>
</table>
</div>
<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>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</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="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('class_i_ty_actor.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pro-attribs">Protected Attributes</a> |
<a href="#friends">Friends</a> </div>
<div class="headertitle">
<div class="title">ITyActor Class Reference</div> </div>
</div>
<div class="contents">
<!-- doxytag: class="ITyActor" -->
<p>Actor class to be used within a scene.
<a href="class_i_ty_actor.html#details">More...</a></p>
<p><code>#include <<a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>></code></p>
<p><a href="class_i_ty_actor-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor_1_1_c_ty_state.html">CTyState</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Inner class used to relate a Actor State with a Sprite. <a href="class_i_ty_actor_1_1_c_ty_state.html#details">More...</a><br/></td></tr>
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#afb266117deb0b8be81325ce76ef7c95b">ITyActor</a> (int64 pID, bool pActive=true, bool pVisible=true, bool pSolid=true, CIwRect pMask=CIwRect(0, 0, 0, 0), CIwSVec2 pPosition=CIwSVec2::g_Zero)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Constructor. <a href="#afb266117deb0b8be81325ce76ef7c95b"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#afc1f27393487c6422303523195c3922c">~ITyActor</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Destructor It actually does nothing but deleting the states. <a href="#afc1f27393487c6422303523195c3922c"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aa988ea01f7b61556918f02ba184b60b3">operator<</a> (<a class="el" href="class_i_ty_actor.html">ITyActor</a> const &pActor)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#af3670099e1c1e77d620c43125dac6e61">IsBuilt</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Is the actor built? <a href="#af3670099e1c1e77d620c43125dac6e61"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#abe293544e0a3823400aaf490b24ae81d">IsActive</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Is the actor active? <a href="#abe293544e0a3823400aaf490b24ae81d"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a5e3d6f0fd5ab67afb6d56488b7a55595">IsVisible</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Is the actor visible? <a href="#a5e3d6f0fd5ab67afb6d56488b7a55595"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a5c1f9e77b0e5903c1f63ac5e2b2c42ad">IsSolid</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Is the actor solid? <a href="#a5c1f9e77b0e5903c1f63ac5e2b2c42ad"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aad869e863d1dc2283d7b33bd2aa02e4b">AddState</a> (<a class="el" href="class_c_ty_sprite.html">CTySprite</a> *pSprite, <a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> pState)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Adds a new state to the State Vector. <a href="#aad869e863d1dc2283d7b33bd2aa02e4b"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a64f9104dbcf4bccbc17121d81b40c9cb">DeleteState</a> (<a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> pState)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Deletes a state from the State Vector. <a href="#a64f9104dbcf4bccbc17121d81b40c9cb"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ab7a324bf10f138f537fe2b869d3aeea5">SetCurrentState</a> (<a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> pState)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Sets a state from the State Vector as current state. <a href="#ab7a324bf10f138f537fe2b869d3aeea5"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aeff5d073d59e661d58e9bdc72370769c">OnCreate</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called once the actor is added to a scene. <a href="#aeff5d073d59e661d58e9bdc72370769c"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a1ceb6a35987a22acb85bdaf9fd23f349">OnDestroy</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called once the actor is removed from a scene. <a href="#a1ceb6a35987a22acb85bdaf9fd23f349"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a3a3295eba0fc092e44a9b690d2d242ab">OnKeyPress</a> (s3eKey pKey)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called on Keyboard Press event. <a href="#a3a3295eba0fc092e44a9b690d2d242ab"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ae0402203392a84e769fad4a989d07b3c">OnKeyRelease</a> (s3eKey pKey)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called on Keyboard Release event. <a href="#ae0402203392a84e769fad4a989d07b3c"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aa6008d50671f63f7ca482b54179b7725">OnKeySustain</a> (s3eKey pKey, int64 pMS)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called if a Key is hold. <a href="#aa6008d50671f63f7ca482b54179b7725"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ae828745012aac359147920ccb42801b9">OnTouchPress</a> (int pX, int pY)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called if the Screen is touched. <a href="#ae828745012aac359147920ccb42801b9"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#adb1cde3971b3d75407a8fbb590f7088a">OnTouchSustain</a> (int pX, int pY, int64 pMS)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called if the Screen is hold. <a href="#adb1cde3971b3d75407a8fbb590f7088a"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a240c68f34a3b90af8bbef1729a74114a">OnTouchRelease</a> (int pX, int pY)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called if a Screentouch is released. <a href="#a240c68f34a3b90af8bbef1729a74114a"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ad07610fc8cd2e0ade09d777979102a22">OnTouchDrag</a> (int pX, int pY, int pRelX, int pRelY)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called if the screen is touch and then dragged. <a href="#ad07610fc8cd2e0ade09d777979102a22"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a9da03663a14f091ce23a5adae98e2302">OnIntersectBoundaries</a> (CIwRect pBoundaries)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called if Actor is about to collide with Scene boundaries. <a href="#a9da03663a14f091ce23a5adae98e2302"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aeed7b53859c91f8be589ff441f36852d">OnStepStart</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called First in each step, if Active. <a href="#aeed7b53859c91f8be589ff441f36852d"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a78ac709f1fdbd9fba59180337be44a7a">OnStep</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called Second in each step, if Active. <a href="#a78ac709f1fdbd9fba59180337be44a7a"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aa539311a3f8cf47dd325f6cb6e7413a6">OnStepEnd</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called after Rendering in each step, if Active. <a href="#aa539311a3f8cf47dd325f6cb6e7413a6"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ac5a0f1ef9aca4cf49893171c130abb9c">OnRender</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called before StepEnd, but at the end of each step, if Visible. <a href="#ac5a0f1ef9aca4cf49893171c130abb9c"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a88b1d350c4649d2df9e358f15fbca9b2">OnCollision</a> (<a class="el" href="class_i_ty_actor.html">ITyActor</a> const &pActor)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Will be called when two actors collide, if Solid. <a href="#a88b1d350c4649d2df9e358f15fbca9b2"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int64 </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a56e1581ea21a61d56ee13065b1bb237d">GetID</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actors ID. <a href="#a56e1581ea21a61d56ee13065b1bb237d"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ad96e4d0568d002ec80b3f3511d34bac4">GetName</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actors Name. <a href="#ad96e4d0568d002ec80b3f3511d34bac4"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#acb6782b902f1d23196ee5d4459a7f4c6">GetRole</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actors Role. <a href="#acb6782b902f1d23196ee5d4459a7f4c6"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a3a317a12d0872943894aef2ab1395c7c">GetDepth</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actors Depth. <a href="#a3a317a12d0872943894aef2ab1395c7c"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#adc9729b29f07da02bbfa26d423901b45">GetCurrentState</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actors Current State. <a href="#adc9729b29f07da02bbfa26d423901b45"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ab1c7d4089d543bf258e02854c00969f0">GetLastState</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actor Last State. <a href="#ab1c7d4089d543bf258e02854c00969f0"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">CIwRect </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a029053700af64bae8290b5dcfa04ceec">GetMask</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actors Mask. <a href="#a029053700af64bae8290b5dcfa04ceec"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">CIwSVec2 </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a545fb58ad751ccbc8a33729ede2b7415">GetPosition</a> () const </td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Accessor for the Actors Position. <a href="#a545fb58ad751ccbc8a33729ede2b7415"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a3ecdf0c6c1502c4b5a4a7227811ad0e3">SetName</a> (std::string pName)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Name. <a href="#a3ecdf0c6c1502c4b5a4a7227811ad0e3"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#abbf80ab3261ea1ffa4a83e8958f486bd">SetRole</a> (std::string pRole)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Role. <a href="#abbf80ab3261ea1ffa4a83e8958f486bd"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a23072345bc259b4a18c702238e3f9249">SetDepth</a> (int pDepth)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Depth. <a href="#a23072345bc259b4a18c702238e3f9249"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ad2a1db314df31d4c1114132154644e2d">SetActive</a> (bool pActive)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Active flag. <a href="#ad2a1db314df31d4c1114132154644e2d"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#af1f3341d3cb568b2420cfce2a570e507">SetVisible</a> (bool pVisible)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Visible flag. <a href="#af1f3341d3cb568b2420cfce2a570e507"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#acc5fe8fe823f7a8f95a6bbe505ebe95a">SetSolid</a> (bool pSolid)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Solid flag. <a href="#acc5fe8fe823f7a8f95a6bbe505ebe95a"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aa119f79b398074a9b9d6281e7b463fee">SetMask</a> (CIwRect pMask)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Collision Mask. <a href="#aa119f79b398074a9b9d6281e7b463fee"></a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a9b37537093a7b6c412d6f1379b4eabb9">SetPosition</a> (CIwSVec2 pPosition)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Mutator for the Actors Position. <a href="#a9b37537093a7b6c412d6f1379b4eabb9"></a><br/></td></tr>
<tr><td colspan="2"><h2><a name="pro-attribs"></a>
Protected Attributes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#afdfb0e1ed5a47085f52f95f276010bb6">m_Name</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a92de9e18b7a31fc93b8bb775922078d4">m_Role</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ac075325d62fdcda89c2a91f2c1298376">m_Depth</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ae460cd48bef240e11cfa5df7a505cbe9">m_Active</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a1019d46cd7502694e5f69c7c4c7be23e">m_Visible</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a0365728019201a011e657ab56e36d06a">m_Solid</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">std::vector< <a class="el" href="class_i_ty_actor_1_1_c_ty_state.html">CTyState</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#aa90c7ebf0af50802126ca951906fb225">m_States</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_i_ty_actor_1_1_c_ty_state.html">CTyState</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#afcdb5a06ae0e2b6d9872fa6f17222487">m_CurrentState</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_i_ty_actor_1_1_c_ty_state.html">CTyState</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ab637fbe1df811cbde3ad2b780f1ea643">m_LastState</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">CIwRect </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#abd0ddacb8e677d2d36ead794883dee4c">m_Mask</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">CIwSVec2 </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#a296ffe4ccf5fad06daf002837b9ec128">m_Position</a></td></tr>
<tr><td colspan="2"><h2><a name="friends"></a>
Friends</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class </td><td class="memItemRight" valign="bottom"><a class="el" href="class_i_ty_actor.html#ac9e603148a462b197c336bd2dedd9f87">CTyScene</a></td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Actor class to be used within a scene. </p>
<p>**********************************************************************************</p>
<dl class="date"><dt><b>Date:</b></dt><dd>2/08/2011 </dd></dl>
<dl class="version"><dt><b>Version:</b></dt><dd>0.1 </dd></dl>
<dl class="author"><dt><b>Author:</b></dt><dd>Leandro Ostera</dd></dl>
<p>Actor class to be used within a Scene class that works with states (<a class="el" href="class_i_ty_actor_1_1_c_ty_state.html" title="Inner class used to relate a Actor State with a Sprite.">CTyState</a>) and is meant to be an interface with some virtual methods to be overloaded. </p>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00046">46</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div><hr/><h2>Constructor & Destructor Documentation</h2>
<a class="anchor" id="afb266117deb0b8be81325ce76ef7c95b"></a><!-- doxytag: member="ITyActor::ITyActor" ref="afb266117deb0b8be81325ce76ef7c95b" args="(int64 pID, bool pActive=true, bool pVisible=true, bool pSolid=true, CIwRect pMask=CIwRect(0, 0, 0, 0), CIwSVec2 pPosition=CIwSVec2::g_Zero)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">ITyActor::ITyActor </td>
<td>(</td>
<td class="paramtype">int64 </td>
<td class="paramname"><em>pID</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>pActive</em> = <code>true</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>pVisible</em> = <code>true</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>pSolid</em> = <code>true</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">CIwRect </td>
<td class="paramname"><em>pMask</em> = <code>CIwRect(0,0,0,0)</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">CIwSVec2 </td>
<td class="paramname"><em>pPosition</em> = <code>CIwSVec2::g_Zero</code> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Constructor. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pID</td><td>Integer value for the Actor ID. </td></tr>
<tr><td class="paramname">pActive</td><td>Boolean value. True if active, false otherwise. </td></tr>
<tr><td class="paramname">pVisible</td><td>Boolean value. True if visible, false otherwise. </td></tr>
<tr><td class="paramname">pSolid</td><td>Boolean value. True if solid, false otherwise. </td></tr>
<tr><td class="paramname">pMask</td><td>CIwRect(x,y,w,h). Actors collision mask, relative to Actors position. </td></tr>
<tr><td class="paramname">pPosition</td><td>CIwSVec2(x,y). Actors position. Relative to Scene position.</td></tr>
</table>
</dd>
</dl>
<p>This is the main constructor. It initializes the following m_rom_erties: </p>
<ul>
<li><code>m_ID</code> , pID. Remember this is a constant! </li>
<li><code>m_Built</code> , true </li>
<li><code>m_Depth</code> , 0 </li>
<li><code>m_Active</code> , true </li>
<li><code>m_Visible</code> , true </li>
<li><code>m_Solid</code> , true </li>
<li><code>m_Mask</code> , CIwRect(0,0,0,0) </li>
<li><code>m_Position</code> , CIwSVec2(0,0) </li>
</ul>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00166">166</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="afc1f27393487c6422303523195c3922c"></a><!-- doxytag: member="ITyActor::~ITyActor" ref="afc1f27393487c6422303523195c3922c" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual ITyActor::~ITyActor </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Destructor It actually does nothing but deleting the states. </p>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00176">176</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="aad869e863d1dc2283d7b33bd2aa02e4b"></a><!-- doxytag: member="ITyActor::AddState" ref="aad869e863d1dc2283d7b33bd2aa02e4b" args="(CTySprite *pSprite, TOASTY_ACTOR_STATE pState)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::AddState </td>
<td>(</td>
<td class="paramtype"><a class="el" href="class_c_ty_sprite.html">CTySprite</a> * </td>
<td class="paramname"><em>pSprite</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> </td>
<td class="paramname"><em>pState</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Adds a new state to the State Vector. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pSprite</td><td>TySprite sprite to associate with pState. </td></tr>
<tr><td class="paramname">pState</td><td>TOASTY_ACTOR_STATE state to associate with pSprite.</td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool True if added succesfully, false if pState is already associated to a Sprite.</dd></dl>
<p>It instantiates a new <a class="el" href="class_i_ty_actor_1_1_c_ty_state.html" title="Inner class used to relate a Actor State with a Sprite.">CTyState</a> object and pushes it back in the m_State vector if pState is not yet associated to a pSprite in the vector. </p>
</div>
</div>
<a class="anchor" id="a64f9104dbcf4bccbc17121d81b40c9cb"></a><!-- doxytag: member="ITyActor::DeleteState" ref="a64f9104dbcf4bccbc17121d81b40c9cb" args="(TOASTY_ACTOR_STATE pState)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::DeleteState </td>
<td>(</td>
<td class="paramtype"><a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> </td>
<td class="paramname"><em>pState</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Deletes a state from the State Vector. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pState</td><td>TOASTY_ACTOR_STATE state to delete.</td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool True if deleted succesfully, false if pState is not in the vector.</dd></dl>
<p>Deletes the state pState from m_State if it is there and if it is not the current state. </p>
</div>
</div>
<a class="anchor" id="adc9729b29f07da02bbfa26d423901b45"></a><!-- doxytag: member="ITyActor::GetCurrentState" ref="adc9729b29f07da02bbfa26d423901b45" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> ITyActor::GetCurrentState </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actors Current State. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>TOASTY_ACTOR_STATE The actors Current State as TOASTY_ACTOR_STATE. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00357">357</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a3a317a12d0872943894aef2ab1395c7c"></a><!-- doxytag: member="ITyActor::GetDepth" ref="a3a317a12d0872943894aef2ab1395c7c" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int ITyActor::GetDepth </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actors Depth. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>int The actors Depth. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00351">351</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a56e1581ea21a61d56ee13065b1bb237d"></a><!-- doxytag: member="ITyActor::GetID" ref="a56e1581ea21a61d56ee13065b1bb237d" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int64 ITyActor::GetID </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actors ID. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>int64 The actors ID. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00333">333</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ab1c7d4089d543bf258e02854c00969f0"></a><!-- doxytag: member="ITyActor::GetLastState" ref="ab1c7d4089d543bf258e02854c00969f0" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> ITyActor::GetLastState </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actor Last State. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>TOASTY_ACTOR_STATE The actors Last State as TOASTY_ACTOR_STATE. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00363">363</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a029053700af64bae8290b5dcfa04ceec"></a><!-- doxytag: member="ITyActor::GetMask" ref="a029053700af64bae8290b5dcfa04ceec" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">CIwRect ITyActor::GetMask </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actors Mask. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>CIwRect The actors mask as CIwRect. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00369">369</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ad96e4d0568d002ec80b3f3511d34bac4"></a><!-- doxytag: member="ITyActor::GetName" ref="ad96e4d0568d002ec80b3f3511d34bac4" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string ITyActor::GetName </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actors Name. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>std::string The actors Name. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00339">339</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a545fb58ad751ccbc8a33729ede2b7415"></a><!-- doxytag: member="ITyActor::GetPosition" ref="a545fb58ad751ccbc8a33729ede2b7415" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">CIwSVec2 ITyActor::GetPosition </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actors Position. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>CIwSVec2 The actors position as CIwSVec2. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00375">375</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="acb6782b902f1d23196ee5d4459a7f4c6"></a><!-- doxytag: member="ITyActor::GetRole" ref="acb6782b902f1d23196ee5d4459a7f4c6" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string ITyActor::GetRole </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Accessor for the Actors Role. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>std::string The actors Role. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00345">345</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="abe293544e0a3823400aaf490b24ae81d"></a><!-- doxytag: member="ITyActor::IsActive" ref="abe293544e0a3823400aaf490b24ae81d" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::IsActive </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Is the actor active? </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool True if active, false otherwise. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00193">193</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="af3670099e1c1e77d620c43125dac6e61"></a><!-- doxytag: member="ITyActor::IsBuilt" ref="af3670099e1c1e77d620c43125dac6e61" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::IsBuilt </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Is the actor built? </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool True if built, false otherwise. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00187">187</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a5c1f9e77b0e5903c1f63ac5e2b2c42ad"></a><!-- doxytag: member="ITyActor::IsSolid" ref="a5c1f9e77b0e5903c1f63ac5e2b2c42ad" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::IsSolid </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Is the actor solid? </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool True if solid, false otherwise. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00205">205</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a5e3d6f0fd5ab67afb6d56488b7a55595"></a><!-- doxytag: member="ITyActor::IsVisible" ref="a5e3d6f0fd5ab67afb6d56488b7a55595" args="() const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::IsVisible </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Is the actor visible? </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool True if visible, false otherwise. </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00199">199</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a88b1d350c4649d2df9e358f15fbca9b2"></a><!-- doxytag: member="ITyActor::OnCollision" ref="a88b1d350c4649d2df9e358f15fbca9b2" args="(ITyActor const &pActor)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnCollision </td>
<td>(</td>
<td class="paramtype"><a class="el" href="class_i_ty_actor.html">ITyActor</a> const & </td>
<td class="paramname"><em>pActor</em></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called when two actors collide, if Solid. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00327">327</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="aeff5d073d59e661d58e9bdc72370769c"></a><!-- doxytag: member="ITyActor::OnCreate" ref="aeff5d073d59e661d58e9bdc72370769c" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual bool ITyActor::OnCreate </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called once the actor is added to a scene. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00243">243</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a1ceb6a35987a22acb85bdaf9fd23f349"></a><!-- doxytag: member="ITyActor::OnDestroy" ref="a1ceb6a35987a22acb85bdaf9fd23f349" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual bool ITyActor::OnDestroy </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called once the actor is removed from a scene. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00249">249</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a9da03663a14f091ce23a5adae98e2302"></a><!-- doxytag: member="ITyActor::OnIntersectBoundaries" ref="a9da03663a14f091ce23a5adae98e2302" args="(CIwRect pBoundaries)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnIntersectBoundaries </td>
<td>(</td>
<td class="paramtype">CIwRect </td>
<td class="paramname"><em>pBoundaries</em></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called if Actor is about to collide with Scene boundaries. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00297">297</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a3a3295eba0fc092e44a9b690d2d242ab"></a><!-- doxytag: member="ITyActor::OnKeyPress" ref="a3a3295eba0fc092e44a9b690d2d242ab" args="(s3eKey pKey)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnKeyPress </td>
<td>(</td>
<td class="paramtype">s3eKey </td>
<td class="paramname"><em>pKey</em></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called on Keyboard Press event. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00255">255</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ae0402203392a84e769fad4a989d07b3c"></a><!-- doxytag: member="ITyActor::OnKeyRelease" ref="ae0402203392a84e769fad4a989d07b3c" args="(s3eKey pKey)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnKeyRelease </td>
<td>(</td>
<td class="paramtype">s3eKey </td>
<td class="paramname"><em>pKey</em></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called on Keyboard Release event. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00261">261</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="aa6008d50671f63f7ca482b54179b7725"></a><!-- doxytag: member="ITyActor::OnKeySustain" ref="aa6008d50671f63f7ca482b54179b7725" args="(s3eKey pKey, int64 pMS)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnKeySustain </td>
<td>(</td>
<td class="paramtype">s3eKey </td>
<td class="paramname"><em>pKey</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int64 </td>
<td class="paramname"><em>pMS</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called if a Key is hold. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00267">267</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ac5a0f1ef9aca4cf49893171c130abb9c"></a><!-- doxytag: member="ITyActor::OnRender" ref="ac5a0f1ef9aca4cf49893171c130abb9c" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnRender </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called before StepEnd, but at the end of each step, if Visible. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00321">321</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a78ac709f1fdbd9fba59180337be44a7a"></a><!-- doxytag: member="ITyActor::OnStep" ref="a78ac709f1fdbd9fba59180337be44a7a" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnStep </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called Second in each step, if Active. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00309">309</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="aa539311a3f8cf47dd325f6cb6e7413a6"></a><!-- doxytag: member="ITyActor::OnStepEnd" ref="aa539311a3f8cf47dd325f6cb6e7413a6" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnStepEnd </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called after Rendering in each step, if Active. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00315">315</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="aeed7b53859c91f8be589ff441f36852d"></a><!-- doxytag: member="ITyActor::OnStepStart" ref="aeed7b53859c91f8be589ff441f36852d" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnStepStart </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called First in each step, if Active. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00303">303</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ad07610fc8cd2e0ade09d777979102a22"></a><!-- doxytag: member="ITyActor::OnTouchDrag" ref="ad07610fc8cd2e0ade09d777979102a22" args="(int pX, int pY, int pRelX, int pRelY)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnTouchDrag </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>pX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>pY</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>pRelX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>pRelY</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called if the screen is touch and then dragged. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00291">291</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ae828745012aac359147920ccb42801b9"></a><!-- doxytag: member="ITyActor::OnTouchPress" ref="ae828745012aac359147920ccb42801b9" args="(int pX, int pY)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnTouchPress </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>pX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>pY</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called if the Screen is touched. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00273">273</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a240c68f34a3b90af8bbef1729a74114a"></a><!-- doxytag: member="ITyActor::OnTouchRelease" ref="a240c68f34a3b90af8bbef1729a74114a" args="(int pX, int pY)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnTouchRelease </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>pX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>pY</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called if a Screentouch is released. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00285">285</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="adb1cde3971b3d75407a8fbb590f7088a"></a><!-- doxytag: member="ITyActor::OnTouchSustain" ref="adb1cde3971b3d75407a8fbb590f7088a" args="(int pX, int pY, int64 pMS)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void ITyActor::OnTouchSustain </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>pX</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>pY</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int64 </td>
<td class="paramname"><em>pMS</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [inline, virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Will be called if the Screen is hold. </p>
<dl class="return"><dt><b>Returns:</b></dt><dd>void </dd></dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00279">279</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="aa988ea01f7b61556918f02ba184b60b3"></a><!-- doxytag: member="ITyActor::operator<" ref="aa988ea01f7b61556918f02ba184b60b3" args="(ITyActor const &pActor)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::operator< </td>
<td>(</td>
<td class="paramtype"><a class="el" href="class_i_ty_actor.html">ITyActor</a> const & </td>
<td class="paramname"><em>pActor</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00178">178</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ad2a1db314df31d4c1114132154644e2d"></a><!-- doxytag: member="ITyActor::SetActive" ref="ad2a1db314df31d4c1114132154644e2d" args="(bool pActive)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetActive </td>
<td>(</td>
<td class="paramtype">bool </td>
<td class="paramname"><em>pActive</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Active flag. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pActive</td><td>boolean for Active; </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00399">399</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ab7a324bf10f138f537fe2b869d3aeea5"></a><!-- doxytag: member="ITyActor::SetCurrentState" ref="ab7a324bf10f138f537fe2b869d3aeea5" args="(TOASTY_ACTOR_STATE pState)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool ITyActor::SetCurrentState </td>
<td>(</td>
<td class="paramtype"><a class="el" href="_ty_actor_8h.html#aceba83227db82b051b04ff8e90d63a51">TOASTY_ACTOR_STATE</a> </td>
<td class="paramname"><em>pState</em></td><td>)</td>
<td></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Sets a state from the State Vector as current state. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pState</td><td>TOASTY_ACTOR_STATE state to set as current.</td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd>bool True if set succesfully, false such state is not in the State Vector. </dd></dl>
</div>
</div>
<a class="anchor" id="a23072345bc259b4a18c702238e3f9249"></a><!-- doxytag: member="ITyActor::SetDepth" ref="a23072345bc259b4a18c702238e3f9249" args="(int pDepth)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetDepth </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>pDepth</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Depth. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pDepth</td><td>int for the Depth. </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00393">393</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="aa119f79b398074a9b9d6281e7b463fee"></a><!-- doxytag: member="ITyActor::SetMask" ref="aa119f79b398074a9b9d6281e7b463fee" args="(CIwRect pMask)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetMask </td>
<td>(</td>
<td class="paramtype">CIwRect </td>
<td class="paramname"><em>pMask</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Collision Mask. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pMask</td><td>CIwRect rect for the Collision Mask. </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00417">417</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a3ecdf0c6c1502c4b5a4a7227811ad0e3"></a><!-- doxytag: member="ITyActor::SetName" ref="a3ecdf0c6c1502c4b5a4a7227811ad0e3" args="(std::string pName)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetName </td>
<td>(</td>
<td class="paramtype">std::string </td>
<td class="paramname"><em>pName</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Name. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pName</td><td>std::string of the name. </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00381">381</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a9b37537093a7b6c412d6f1379b4eabb9"></a><!-- doxytag: member="ITyActor::SetPosition" ref="a9b37537093a7b6c412d6f1379b4eabb9" args="(CIwSVec2 pPosition)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetPosition </td>
<td>(</td>
<td class="paramtype">CIwSVec2 </td>
<td class="paramname"><em>pPosition</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Position. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pPosition</td><td>CIwSVec2 vector for Position. </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00423">423</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="abbf80ab3261ea1ffa4a83e8958f486bd"></a><!-- doxytag: member="ITyActor::SetRole" ref="abbf80ab3261ea1ffa4a83e8958f486bd" args="(std::string pRole)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetRole </td>
<td>(</td>
<td class="paramtype">std::string </td>
<td class="paramname"><em>pRole</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Role. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pRole</td><td>std::string of the Role. </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00387">387</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="acc5fe8fe823f7a8f95a6bbe505ebe95a"></a><!-- doxytag: member="ITyActor::SetSolid" ref="acc5fe8fe823f7a8f95a6bbe505ebe95a" args="(bool pSolid)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetSolid </td>
<td>(</td>
<td class="paramtype">bool </td>
<td class="paramname"><em>pSolid</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Solid flag. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pSolid</td><td>boolean for Solid; </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00411">411</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="af1f3341d3cb568b2420cfce2a570e507"></a><!-- doxytag: member="ITyActor::SetVisible" ref="af1f3341d3cb568b2420cfce2a570e507" args="(bool pVisible)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void ITyActor::SetVisible </td>
<td>(</td>
<td class="paramtype">bool </td>
<td class="paramname"><em>pVisible</em></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Mutator for the Actors Visible flag. </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">pVisible</td><td>boolean for Visible; </td></tr>
</table>
</dd>
</dl>
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00405">405</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<hr/><h2>Friends And Related Function Documentation</h2>
<a class="anchor" id="ac9e603148a462b197c336bd2dedd9f87"></a><!-- doxytag: member="ITyActor::CTyScene" ref="ac9e603148a462b197c336bd2dedd9f87" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">friend class <a class="el" href="class_c_ty_scene.html">CTyScene</a><code> [friend]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00144">144</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<hr/><h2>Member Data Documentation</h2>
<a class="anchor" id="ae460cd48bef240e11cfa5df7a505cbe9"></a><!-- doxytag: member="ITyActor::m_Active" ref="ae460cd48bef240e11cfa5df7a505cbe9" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool <a class="el" href="class_i_ty_actor.html#ae460cd48bef240e11cfa5df7a505cbe9">ITyActor::m_Active</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00078">78</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="afcdb5a06ae0e2b6d9872fa6f17222487"></a><!-- doxytag: member="ITyActor::m_CurrentState" ref="afcdb5a06ae0e2b6d9872fa6f17222487" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="class_i_ty_actor_1_1_c_ty_state.html">CTyState</a>* <a class="el" href="class_i_ty_actor.html#afcdb5a06ae0e2b6d9872fa6f17222487">ITyActor::m_CurrentState</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00127">127</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ac075325d62fdcda89c2a91f2c1298376"></a><!-- doxytag: member="ITyActor::m_Depth" ref="ac075325d62fdcda89c2a91f2c1298376" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="class_i_ty_actor.html#ac075325d62fdcda89c2a91f2c1298376">ITyActor::m_Depth</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00073">73</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="ab637fbe1df811cbde3ad2b780f1ea643"></a><!-- doxytag: member="ITyActor::m_LastState" ref="ab637fbe1df811cbde3ad2b780f1ea643" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="class_i_ty_actor_1_1_c_ty_state.html">CTyState</a>* <a class="el" href="class_i_ty_actor.html#ab637fbe1df811cbde3ad2b780f1ea643">ITyActor::m_LastState</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00132">132</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="abd0ddacb8e677d2d36ead794883dee4c"></a><!-- doxytag: member="ITyActor::m_Mask" ref="abd0ddacb8e677d2d36ead794883dee4c" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">CIwRect <a class="el" href="class_i_ty_actor.html#abd0ddacb8e677d2d36ead794883dee4c">ITyActor::m_Mask</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00137">137</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="afdfb0e1ed5a47085f52f95f276010bb6"></a><!-- doxytag: member="ITyActor::m_Name" ref="afdfb0e1ed5a47085f52f95f276010bb6" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_i_ty_actor.html#afdfb0e1ed5a47085f52f95f276010bb6">ITyActor::m_Name</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00063">63</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a296ffe4ccf5fad06daf002837b9ec128"></a><!-- doxytag: member="ITyActor::m_Position" ref="a296ffe4ccf5fad06daf002837b9ec128" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">CIwSVec2 <a class="el" href="class_i_ty_actor.html#a296ffe4ccf5fad06daf002837b9ec128">ITyActor::m_Position</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00142">142</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a92de9e18b7a31fc93b8bb775922078d4"></a><!-- doxytag: member="ITyActor::m_Role" ref="a92de9e18b7a31fc93b8bb775922078d4" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::string <a class="el" href="class_i_ty_actor.html#a92de9e18b7a31fc93b8bb775922078d4">ITyActor::m_Role</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00068">68</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a0365728019201a011e657ab56e36d06a"></a><!-- doxytag: member="ITyActor::m_Solid" ref="a0365728019201a011e657ab56e36d06a" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool <a class="el" href="class_i_ty_actor.html#a0365728019201a011e657ab56e36d06a">ITyActor::m_Solid</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00088">88</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="aa90c7ebf0af50802126ca951906fb225"></a><!-- doxytag: member="ITyActor::m_States" ref="aa90c7ebf0af50802126ca951906fb225" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">std::vector<<a class="el" href="class_i_ty_actor_1_1_c_ty_state.html">CTyState</a>> <a class="el" href="class_i_ty_actor.html#aa90c7ebf0af50802126ca951906fb225">ITyActor::m_States</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00122">122</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<a class="anchor" id="a1019d46cd7502694e5f69c7c4c7be23e"></a><!-- doxytag: member="ITyActor::m_Visible" ref="a1019d46cd7502694e5f69c7c4c7be23e" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">bool <a class="el" href="class_i_ty_actor.html#a1019d46cd7502694e5f69c7c4c7be23e">ITyActor::m_Visible</a><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Definition at line <a class="el" href="_ty_actor_8h_source.html#l00083">83</a> of file <a class="el" href="_ty_actor_8h_source.html">TyActor.h</a>.</p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>D:/development/cpp/toasty/include/<a class="el" href="_ty_actor_8h_source.html">TyActor.h</a></li>
</ul>
</div>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="class_i_ty_actor.html">ITyActor</a> </li>
<li class="footer">Generated on Fri Aug 12 2011 00:58:42 for Toasty! by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Friends</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</body>
</html>
| 50.598394 | 1,100 | 0.649126 |
a17acfac3bcf74e6ec4c8e5738134c66975c438b | 2,113 | go | Go | cmd/rollback/main.go | lgray/gowaves | 86b30fcdc3480fd2952b82a36909350361c291a5 | [
"MIT"
] | 72 | 2018-10-01T14:14:53.000Z | 2022-03-25T21:06:56.000Z | cmd/rollback/main.go | lgray/gowaves | 86b30fcdc3480fd2952b82a36909350361c291a5 | [
"MIT"
] | 110 | 2018-10-19T15:09:03.000Z | 2022-03-24T09:56:56.000Z | cmd/rollback/main.go | lgray/gowaves | 86b30fcdc3480fd2952b82a36909350361c291a5 | [
"MIT"
] | 31 | 2018-10-30T15:07:03.000Z | 2022-03-29T23:57:11.000Z | package main
import (
"flag"
"github.com/wavesplatform/gowaves/pkg/settings"
"github.com/wavesplatform/gowaves/pkg/state"
"github.com/wavesplatform/gowaves/pkg/util/common"
"github.com/wavesplatform/gowaves/pkg/util/fdlimit"
"go.uber.org/zap"
)
var (
logLevel = flag.String("log-level", "INFO", "Logging level. Supported levels: DEBUG, INFO, WARN, ERROR, FATAL. Default logging level INFO.")
statePath = flag.String("state-path", "", "Path to node's state directory")
blockchainType = flag.String("blockchain-type", "mainnet", "Blockchain type: mainnet/testnet/stagenet")
height = flag.Uint64("height", 0, "Height to rollback")
buildExtendedApi = flag.Bool("build-extended-api", false, "Builds extended API. Note that state must be reimported in case it wasn't imported with similar flag set")
buildStateHashes = flag.Bool("build-state-hashes", false, "Calculate and store state hashes for each block height.")
)
func main() {
flag.Parse()
maxFDs, err := fdlimit.MaxFDs()
if err != nil {
zap.S().Fatalf("Initialization error: %v", err)
}
_, err = fdlimit.RaiseMaxFDs(maxFDs)
if err != nil {
zap.S().Fatalf("Initialization error: %v", err)
}
common.SetupLogger(*logLevel)
cfg, err := settings.BlockchainSettingsByTypeName(*blockchainType)
if err != nil {
zap.S().Error(err)
return
}
params := state.DefaultStateParams()
params.StorageParams.DbParams.OpenFilesCacheCapacity = int(maxFDs - 10)
params.BuildStateHashes = *buildStateHashes
params.StoreExtendedApiData = *buildExtendedApi
s, err := state.NewState(*statePath, params, cfg)
if err != nil {
zap.S().Error(err)
return
}
defer func() {
err = s.Close()
if err != nil {
zap.S().Errorf("Failed to close state: %v", err)
}
}()
curHeight, err := s.Height()
if err != nil {
zap.S().Error(err)
return
}
zap.S().Infof("Current height: %d", curHeight)
err = s.RollbackToHeight(*height)
if err != nil {
zap.S().Error(err)
return
}
curHeight, err = s.Height()
if err != nil {
zap.S().Error(err)
return
}
zap.S().Infof("Current height: %d", curHeight)
}
| 26.746835 | 166 | 0.683862 |
a20df74851686bffa59aadf87858d6daff6d1fe6 | 7,521 | dart | Dart | lib/ui/screens/home.dart | 04burhanuddin/App-Covid19-Flutter | 091e4f3fc255ed1095dfca7312f4aa1d7ae47b69 | [
"BSD-2-Clause"
] | 1 | 2021-04-03T05:53:08.000Z | 2021-04-03T05:53:08.000Z | lib/ui/screens/home.dart | 04burhanuddin/App-Covid19-Flutter | 091e4f3fc255ed1095dfca7312f4aa1d7ae47b69 | [
"BSD-2-Clause"
] | null | null | null | lib/ui/screens/home.dart | 04burhanuddin/App-Covid19-Flutter | 091e4f3fc255ed1095dfca7312f4aa1d7ae47b69 | [
"BSD-2-Clause"
] | null | null | null | part of 'screens.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<DataIndonesia> dataIndonesia;
Future<DataIndonesia> getDataIndonesia() async {
var dio = Dio();
final response = await dio.get('https://api.kawalcorona.com/indonesia/');
print(response.data);
if (response.statusCode == 200) {
return DataIndonesia.fromJson(response.data[0]);
} else {
throw Exception('Gagal mengambil data');
}
}
@override
void initState() {
super.initState();
dataIndonesia = getDataIndonesia();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: background,
appBar: AppBar(
title: Text("Covid Indonesia"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: FutureBuilder<DataIndonesia>(
future: dataIndonesia,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Container(
child: Center(
child: GridView.count(
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 2,
children: <Widget>[
// Kasus positif
Container(
padding: EdgeInsets.only(left: 15, top: 34),
color: positif,
height: 200,
child: Column(
children: <Widget>[
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Positif",
style: TextStyle(fontSize: 20),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.centerLeft,
child: new Text(
"${snapshot.data.positif}",
style: TextStyle(
fontSize: 30, fontWeight: FontWeight.w500),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Orang",
style: TextStyle(fontSize: 15),
),
)
],
),
),
// Kasus dirawat
Container(
padding: EdgeInsets.only(left: 15, top: 34),
color: dirawat,
height: 200,
child: Column(
children: <Widget>[
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Dirawat",
style: TextStyle(fontSize: 20),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.centerLeft,
child: new Text(
"${snapshot.data.dirawat}",
style: TextStyle(
fontSize: 30, fontWeight: FontWeight.w500),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Orang",
style: TextStyle(fontSize: 15),
),
)
],
),
),
// Kasus sembuh
Container(
padding: EdgeInsets.only(left: 15, top: 34),
color: sembuh,
height: 200,
child: Column(
children: <Widget>[
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Sembuh",
style: TextStyle(fontSize: 20),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.centerLeft,
child: new Text(
"${snapshot.data.sembuh}",
style: TextStyle(
fontSize: 30, fontWeight: FontWeight.w500),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Orang",
style: TextStyle(fontSize: 15),
),
)
],
),
),
// Kasus Meninggal
Container(
padding: EdgeInsets.only(left: 15, top: 34),
color: meninggal,
height: 200,
child: Column(
children: <Widget>[
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Meninggal",
style: TextStyle(fontSize: 20),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.centerLeft,
child: new Text(
"${snapshot.data.meninggal}",
style: TextStyle(
fontSize: 30, fontWeight: FontWeight.w500),
),
),
Padding(padding: EdgeInsets.all(10)),
new Align(
alignment: Alignment.topLeft,
child: new Text(
"Orang",
style: TextStyle(fontSize: 15),
),
)
],
),
),
],
),
),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
| 37.232673 | 77 | 0.341843 |
e648af8acf42bae5f57be7319aaf2f5750ddf83a | 651 | go | Go | log/zap_test.go | sqjian/toolkit | 75f50aadbdaff3b1566ca21561108ec65283c086 | [
"Apache-2.0"
] | null | null | null | log/zap_test.go | sqjian/toolkit | 75f50aadbdaff3b1566ca21561108ec65283c086 | [
"Apache-2.0"
] | 1 | 2022-03-09T14:23:03.000Z | 2022-03-09T14:23:05.000Z | log/zap_test.go | sqjian/toolkit | 75f50aadbdaff3b1566ca21561108ec65283c086 | [
"Apache-2.0"
] | null | null | null | package log
import (
"testing"
)
func TestLogger(t *testing.T) {
logger, loggerErr := newZapLogger(&Meta{
FileName: "go-kit.log",
MaxSize: 3,
MaxBackups: 3,
MaxAge: 3,
Level: Debug,
Console: true,
})
if loggerErr != nil {
t.Fatal(loggerErr)
}
{
t.Log(logger.SetLevelOTF(Warn))
logger.Debugf("testing infof...")
logger.Infof("testing Infof...")
logger.Warnf("testing Warnf...")
logger.Errorf("testing Errorf...")
}
{
t.Log(logger.SetLevelOTF(Warn))
logger.Debugf("testing infof...")
logger.Infof("testing Infof...")
logger.Warnf("testing Warnf...")
logger.Errorf("testing Errorf...")
}
}
| 18.083333 | 41 | 0.628264 |
866b8b9f4ccfd874c34b9134ccfb76f518332059 | 7,634 | go | Go | internal/mail/rfc2822/date_test.go | robdefeo/mailchain | 26cae20e86d526468adefc332e612f7e2431c523 | [
"Apache-2.0"
] | null | null | null | internal/mail/rfc2822/date_test.go | robdefeo/mailchain | 26cae20e86d526468adefc332e612f7e2431c523 | [
"Apache-2.0"
] | null | null | null | internal/mail/rfc2822/date_test.go | robdefeo/mailchain | 26cae20e86d526468adefc332e612f7e2431c523 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Mailchain Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rfc2822
import (
"net/mail"
"testing"
"time"
)
func TestDateParsing(t *testing.T) {
tests := []struct {
dateStr string
exp time.Time
}{
// RFC 5322, Appendix A.1.1
{
"Fri, 21 Nov 1997 09:55:06 -0600",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
},
// RFC 5322, Appendix A.6.2
// Obsolete date.
{
"21 Nov 97 09:55:06 GMT",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("GMT", 0)),
},
// Commonly found format not specified by RFC 5322.
{
"Fri, 21 Nov 1997 09:55:06 -0600 (MDT)",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
},
{
"Thu, 20 Nov 1997 09:55:06 -0600 (MDT)",
time.Date(1997, 11, 20, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
},
{
"Thu, 20 Nov 1997 09:55:06 GMT (GMT)",
time.Date(1997, 11, 20, 9, 55, 6, 0, time.UTC),
},
{
"Fri, 21 Nov 1997 09:55:06 +1300 (TOT)",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", +13*60*60)),
},
}
for _, test := range tests {
hdr := mail.Header{
"Date": []string{test.dateStr},
}
date, err := hdr.Date()
if err != nil {
t.Errorf("Header(Date: %s).Date(): %v", test.dateStr, err)
} else if !date.Equal(test.exp) {
t.Errorf("Header(Date: %s).Date() = %+v, want %+v", test.dateStr, date, test.exp)
}
date, err = mailParseDate(test.dateStr)
if err != nil {
t.Errorf("mailParseDate(%s): %v", test.dateStr, err)
} else if !date.Equal(test.exp) {
t.Errorf("mailParseDate(%s) = %+v, want %+v", test.dateStr, date, test.exp)
}
}
}
func TestDateParsingCFWS(t *testing.T) {
tests := []struct {
dateStr string
exp time.Time
valid bool
}{
// FWS-only. No date.
{
" ",
// nil is not allowed
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// FWS is allowed before optional day of week.
{
" Fri, 21 Nov 1997 09:55:06 -0600",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
true,
},
{
"21 Nov 1997 09:55:06 -0600",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
true,
},
{
"Fri 21 Nov 1997 09:55:06 -0600",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false, // missing ,
},
// FWS is allowed before day of month but HTAB fails.
{
"Fri, 21 Nov 1997 09:55:06 -0600",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
true,
},
// FWS is allowed before and after year but HTAB fails.
{
"Fri, 21 Nov 1997 09:55:06 -0600",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
true,
},
// FWS is allowed before zone but HTAB is not handled. Obsolete timezone is handled.
{
"Fri, 21 Nov 1997 09:55:06 CST",
time.Time{},
true,
},
// FWS is allowed after date and a CRLF is already replaced.
{
"Fri, 21 Nov 1997 09:55:06 CST (no leading FWS and a trailing CRLF) \r\n",
time.Time{},
true,
},
// CFWS is a reduced set of US-ASCII where space and accentuated are obsolete. No error.
{
"Fri, 21 Nov 1997 09:55:06 -0600 (MDT and non-US-ASCII signs éèç )",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
true,
},
// CFWS is allowed after zone including a nested comment.
// Trailing FWS is allowed.
{
"Fri, 21 Nov 1997 09:55:06 -0600 \r\n (thisisa(valid)cfws) \t ",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
true,
},
// CRLF is incomplete and misplaced.
{
"Fri, 21 Nov 1997 \r 09:55:06 -0600 \r\n (thisisa(valid)cfws) \t ",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// CRLF is complete but misplaced. No error is returned.
{
"Fri, 21 Nov 199\r\n7 09:55:06 -0600 \r\n (thisisa(valid)cfws) \t ",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
true, // should be false in the strict interpretation of RFC 5322.
},
// Invalid ASCII in date.
{
"Fri, 21 Nov 1997 ù 09:55:06 -0600 \r\n (thisisa(valid)cfws) \t ",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// CFWS chars () in date.
{
"Fri, 21 Nov () 1997 09:55:06 -0600 \r\n (thisisa(valid)cfws) \t ",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// Timezone is invalid but T is found in comment.
{
"Fri, 21 Nov 1997 09:55:06 -060 \r\n (Thisisa(valid)cfws) \t ",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// Date has no month.
{
"Fri, 21 1997 09:55:06 -0600",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// Invalid month : OCT iso Oct
{
"Fri, 21 OCT 1997 09:55:06 CST",
time.Time{},
false,
},
// A too short time zone.
{
"Fri, 21 Nov 1997 09:55:06 -060",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// A too short obsolete time zone.
{
"Fri, 21 1997 09:55:06 GT",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
false,
},
// Ensure that the presence of "T" in the date
// doesn't trip out ParseDate, as per issue 39260.
{
"Tue, 26 May 2020 14:04:40 GMT",
time.Date(2020, 05, 26, 14, 04, 40, 0, time.UTC),
true,
},
{
"Tue, 26 May 2020 14:04:40 UT",
time.Date(2020, 05, 26, 14, 04, 40, 0, time.UTC),
false,
},
{
"Thu, 21 May 2020 14:04:40 UT",
time.Date(2020, 05, 21, 14, 04, 40, 0, time.UTC),
false,
},
{
"Thu, 21 May 2020 14:04:40 UTC",
time.Date(2020, 05, 21, 14, 04, 40, 0, time.UTC),
true,
},
{
"Fri, 21 Nov 1997 09:55:06 GMT (GMT)",
time.Date(1997, 11, 21, 9, 55, 6, 0, time.UTC),
true,
},
}
for _, test := range tests {
hdr := mail.Header{
"Date": []string{test.dateStr},
}
date, err := hdr.Date()
if err != nil && test.valid {
t.Errorf("Header(Date: %s).Date(): %v", test.dateStr, err)
} else if err == nil && test.exp.IsZero() {
// OK. Used when exact result depends on the
// system's local zoneinfo.
} else if err == nil && !date.Equal(test.exp) && test.valid {
t.Errorf("Header(Date: %s).Date() = %+v, want %+v", test.dateStr, date, test.exp)
} else if err == nil && !test.valid { // an invalid expression was tested
t.Errorf("Header(Date: %s).Date() did not return an error but %v", test.dateStr, date)
}
date, err = mailParseDate(test.dateStr)
if err != nil && test.valid {
t.Errorf("mailParseDate(%s): %v", test.dateStr, err)
} else if err == nil && test.exp.IsZero() {
// OK. Used when exact result depends on the
// system's local zoneinfo.
} else if err == nil && !test.valid { // an invalid expression was tested
t.Errorf("mailParseDate(%s) did not return an error but %v", test.dateStr, date)
} else if err == nil && test.valid && !date.Equal(test.exp) {
t.Errorf("mailParseDate(%s) = %+v, want %+v", test.dateStr, date, test.exp)
}
}
}
| 30.055118 | 90 | 0.581478 |
84f019dd2b84170056cc560e653bad8dbd5d7644 | 3,068 | h | C | src/web_curl.h | paladin-t/bitty | a09d45ba5b0f038d19d80ef7b98d8342d328bccc | [
"BSD-3-Clause"
] | 63 | 2020-10-22T10:31:00.000Z | 2022-03-25T15:54:14.000Z | src/web_curl.h | paladin-t/bitty | a09d45ba5b0f038d19d80ef7b98d8342d328bccc | [
"BSD-3-Clause"
] | 1 | 2021-05-08T18:14:06.000Z | 2021-05-08T18:14:06.000Z | src/web_curl.h | paladin-t/bitty | a09d45ba5b0f038d19d80ef7b98d8342d328bccc | [
"BSD-3-Clause"
] | 6 | 2021-03-09T07:20:53.000Z | 2022-02-13T05:23:52.000Z | /*
** Bitty
**
** An itty bitty game engine.
**
** Copyright (C) 2020 - 2021 Tony Wang, all rights reserved
**
** For the latest info, see https://github.com/paladin-t/bitty/
*/
#ifndef __WEB_CURL_H__
#define __WEB_CURL_H__
#include "web.h"
#if BITTY_WEB_ENABLED
# include "../lib/curl/include/curl/curl.h"
#endif /* BITTY_WEB_ENABLED */
#if BITTY_MULTITHREAD_ENABLED
# include <thread>
#endif /* BITTY_MULTITHREAD_ENABLED */
/*
** {===========================================================================
** Macros and constants
*/
#ifndef WEB_FETCH_TIMEOUT_SECONDS
# define WEB_FETCH_TIMEOUT_SECONDS 20l
#endif /* WEB_FETCH_TIMEOUT_SECONDS */
#ifndef WEB_FETCH_CONNECTION_TIMEOUT_SECONDS
# define WEB_FETCH_CONNECTION_TIMEOUT_SECONDS 10l
#endif /* WEB_FETCH_CONNECTION_TIMEOUT_SECONDS */
/* ===========================================================================} */
/*
** {===========================================================================
** Fetch implementation with the cURL backend
*/
#if BITTY_WEB_ENABLED
class FetchCurl : public Fetch {
private:
enum States {
IDLE,
BUSY,
RESPONDED
};
private:
/**< States. */
Atomic<States> _state;
/**< Options. */
Text::Array _headers;
struct curl_slist* _headersOpt = nullptr;
long _timeout = WEB_FETCH_TIMEOUT_SECONDS;
long _connTimeout = WEB_FETCH_CONNECTION_TIMEOUT_SECONDS;
DataTypes _responseHint = STRING;
/**< Connection. */
CURL* _curl = nullptr;
/**< Callbacks. */
class Bytes* _response = nullptr;
std::string _error;
RespondedHandler _rspHandler;
ErrorHandler _errHandler;
/**< Threading. */
#if BITTY_MULTITHREAD_ENABLED
std::thread _thread;
#endif /* BITTY_MULTITHREAD_ENABLED */
mutable RecursiveMutex _lock;
public:
FetchCurl();
virtual ~FetchCurl() override;
virtual unsigned type(void) const override;
virtual bool open(void) override;
virtual bool close(void) override;
virtual DataTypes dataType(void) const override;
virtual void dataType(DataTypes y) override;
virtual void url(const char* url) override;
virtual void options(const Variant &options) override;
virtual void headers(const Text::Array &headers) override;
virtual void method(const char* method) override;
virtual void body(const char* body) override;
virtual void timeout(long t, long conn) override;
virtual bool perform(void) override;
virtual void clear(void) override;
virtual bool update(double delta) override;
virtual const RespondedHandler &respondedCallback(void) const override;
virtual const ErrorHandler &errorCallback(void) const override;
virtual void callback(const RespondedHandler &cb) override;
virtual void callback(const ErrorHandler &cb) override;
private:
void reset(void);
static size_t receive(void* ptr, size_t size, size_t nmemb, void* stream);
};
#endif /* BITTY_WEB_ENABLED */
/* ===========================================================================} */
#endif /* __WEB_CURL_H__ */
| 24.741935 | 83 | 0.644068 |
a9abd5543ebb901d3bf23dcddb982e846e488f1f | 5,377 | html | HTML | 500E/ijs.0.025718-0-000.pbm/results/phylotree/001.hocr.html | ContentMine/ijsem | 1235b5eab144ff152ea0ae21570f3323c3b8e57c | [
"CC0-1.0"
] | 1 | 2015-09-14T19:11:29.000Z | 2015-09-14T19:11:29.000Z | 500E/ijs.0.025718-0-000.pbm/results/phylotree/001.hocr.html | ContentMine/ijsem | 1235b5eab144ff152ea0ae21570f3323c3b8e57c | [
"CC0-1.0"
] | 3 | 2015-08-28T11:31:39.000Z | 2015-09-15T06:49:26.000Z | 500E/ijs.0.025718-0-000.pbm/results/phylotree/001.hocr.html | ContentMine/ijsem | 1235b5eab144ff152ea0ae21570f3323c3b8e57c | [
"CC0-1.0"
] | null | null | null | <body xmlns="http://www.w3.org/1999/xhtml"><div class="ocr_page" id="page_1" title="image "/Users/pm286/workspace/ami-plugin/../ijsem/500E/ijs.0.025718-0-000.pbm/image/ijs.0.025718-0-000.pbm.png"; bbox 0 0 1775 1205; ppageno 0"><div id="block_1_1" title="bbox 830 0 1491 30" class="block"><p class="ocr_par" dir="ltr" id="par_1" title="bbox 830 0 1491 30"><span class="ocr_line" id="line_1" title="bbox 830 0 1491 30"><span>76</span><span>Rhodanobacter</span><span>fulvus</span><span>Jip2T</span><span>(AB100608)</span></span></p></div><div id="block_2_2" title="bbox 71 53 1759 112" class="block"><p class="ocr_par" dir="ltr" id="par_2" title="bbox 71 53 1759 112"><span class="ocr_line" id="line_2" title="bbox 992 53 1759 83"><span>Rhodanobacter</span><span>ginsenosidimutans</span><span>Gsoli</span><span>3054T</span><span>(EU332826)</span></span><span class="ocr_line" id="line_3" title="bbox 71 95 112 112"><span>0</span><span>01</span></span></p></div><div id="block_3_3" title="bbox 7 106 1451 134" class="block"><p class="ocr_par" dir="ltr" id="par_3" title="bbox 7 106 1451 134"><span class="ocr_line" id="line_4" title="bbox 7 106 1451 134"><span>I91</span><span>Rhodanobacter</span><span>soli</span><span>DCY45T</span><span>(FJ605268)</span></span></p></div><div id="block_4_4" title="bbox 712 131 1610 190" class="block"><p class="ocr_par" dir="ltr" id="par_4" title="bbox 712 131 1610 190"><span class="ocr_line" id="line_5" title="bbox 712 131 737 147"><span>85</span></span><span class="ocr_line" id="line_6" title="bbox 1003 160 1610 190"><span>Rhodanobacter</span><span>thiooxydans</span><span>LCSQT</span><span>(AB2861</span><span>79)</span></span></p></div><div id="block_5_5" title="bbox 548 213 1775 830" class="block"><p class="ocr_par" dir="ltr" id="par_5" title="bbox 548 213 1775 830"><span class="ocr_line" id="line_7" title="bbox 1097 213 1775 241"><span>Rhodanobacter</span><span>lindaniclasticus</span><span>RP5557T(AF039167)</span></span><span class="ocr_line" id="line_8" title="bbox 828 267 1413 296"><span>Rhodanobacter</span><span>spathiphylli</span><span>B397</span><span>(AMO87226)</span></span><span class="ocr_line" id="line_9" title="bbox 548 316 1440 348"><span>85</span><span>Rhodanobacter</span><span>terrae</span><span>GP18-1T</span><span>(EF166076)</span></span><span class="ocr_line" id="line_10" title="bbox 873 373 1549 402"><span>Rhodanobacter</span><span>panaciterrae</span><span>LnR5-47T</span><span>(EU332829)</span></span><span class="ocr_line" id="line_11" title="bbox 655 427 1547 457"><span>76</span><span>Rhodanobacter</span><span>ginsengisoli</span><span>GR1</span><span>7-7T</span><span>(EF1</span><span>66075)</span></span><span class="ocr_line" id="line_12" title="bbox 713 480 1276 510"><span>Dyella</span><span>ginsengisoli</span><span>Gsoil</span><span>30467</span><span>(AB245367)</span></span><span class="ocr_line" id="line_13" title="bbox 759 533 1182 563"><span>Dyella</span><span>soliJS12-10T</span><span>(EU604272)</span></span><span class="ocr_line" id="line_14" title="bbox 729 587 1253 617"><span>Dyella</span><span>thiooxydans</span><span>ATSB10T</span><span>(EF397574)</span></span><span class="ocr_line" id="line_15" title="bbox 937 641 1381 668"><span>Frateuria</span><span>terrea</span><span>VA24T</span><span>(EU682683)</span></span><span class="ocr_line" id="line_16" title="bbox 838 694 1364 722"><span>Frateuria</span><span>aurantia</span><span>IFO</span><span>32457</span><span>(ABO91</span><span>194)</span></span><span class="ocr_line" id="line_17" title="bbox 779 747 1298 777"><span>Dyella</span><span>japonica</span><span>IAM</span><span>150697</span><span>(AB1</span><span>10498)</span></span><span class="ocr_line" id="line_18" title="bbox 820 800 1313 830"><span>Dyella</span><span>marensis</span><span>CS5-B2T</span><span>(AM939778)</span></span></p></div><div id="block_6_6" title="bbox 371 854 1548 992" class="block"><p class="ocr_par" dir="ltr" id="par_6" title="bbox 371 854 1548 992"><span class="ocr_line" id="line_19" title="bbox 656 854 1227 884"><span>99</span><span>Dyella</span><span>koreensis</span><span>BB4T</span><span>(AY884571)</span></span><span class="ocr_line" id="line_20" title="bbox 371 908 1409 936"><span>72</span><span>Luteibacter</span><span>rhizovicinus</span><span>LJ96T</span><span>(AJ580498)</span></span><span class="ocr_line" id="line_21" title="bbox 643 961 1548 992"><span>100</span><span>Luteibacter</span><span>anthropi</span><span>CCUG</span><span>25036T(FM212561)</span></span></p></div><div id="block_7_7" title="bbox 629 1014 1681 1205" class="block"><p class="ocr_par" dir="ltr" id="par_7" title="bbox 629 1014 1681 1205"><span class="ocr_line" id="line_22" title="bbox 900 1014 1507 1044"><span>Luteibacter</span><span>yeojuensis</span><span>R2A16-1OT</span><span>(DQ181549)</span></span><span class="ocr_line" id="line_23" title="bbox 641 1068 1076 1098"><span>Dyella</span><span>terrae</span><span>JS14-6T</span><span>(EU604273)</span></span><span class="ocr_line" id="line_24" title="bbox 629 1121 1160 1149"><span>Fulvfmonas</span><span>soli</span><span>LMG</span><span>19981</span><span>T(</span><span>AJ31</span><span>1653)</span></span><span class="ocr_line" id="line_25" title="bbox 1095 1174 1681 1205"><span>Xanthomonas</span><span>campestris</span><span>LMG</span><span>568T(X95917)</span></span></p></div></div></body> | 5,377 | 5,377 | 0.715269 |
658f17c7e112a10aa4cbdea2cb29c502a74fbdc2 | 1,091 | lua | Lua | main.lua | Rio-PUC-Games/LovelEditor | 5f7c8741a3e157d458c4053752f83d018a0ddda8 | [
"MIT"
] | null | null | null | main.lua | Rio-PUC-Games/LovelEditor | 5f7c8741a3e157d458c4053752f83d018a0ddda8 | [
"MIT"
] | null | null | null | main.lua | Rio-PUC-Games/LovelEditor | 5f7c8741a3e157d458c4053752f83d018a0ddda8 | [
"MIT"
] | null | null | null | io.stdout:setvbuf("no")
local screen
local str
function love.load()
require('src.DAO').start()
screen = require ('src.MainScreen')
--love.keyboard.setKeyRepeat(true)
local img = love.graphics.newImage('bil1.png')
love.mouse.setCursor(love.mouse.newCursor(img:getData(), img:getWidth()/2,img:getHeight()/2))
str = love.filesystem.getSourceBaseDirectory()
--str = require('src.saveUtils').getFolderPath()
end
function love.update(dt)
screen:update(dt)
end
function love.draw()
screen:draw()
--[[
local x, y = love.mouse.getPosition()
love.graphics.setColor(0,0,0)
love.graphics.print(x..'\n'..y,x,y-28)
]]
--[[
love.graphics.rectangle('fill',0,0,200,100)
love.graphics.setColor(0,255,0)
love.graphics.print(str)
]]
end
function love.wheelmoved(x,y)
screen:wheelmoved(x,y)
end
function love.mousepressed(x,y,b)
screen:mousepressed(x,y,b)
end
function love.mousemoved(x,y,dx,dy)
screen:mousemoved(x,y,dx,dy)
end
function love.mousereleased(x,y,b)
screen:mousereleased(x,y,b)
end
function love.keypressed(key)
print('key = '..key)
screen:keypressed(key)
end | 20.584906 | 94 | 0.719523 |
32d9ae46bade139fb5c3a9f0aa2e2e99bde6213e | 68 | swift | Swift | Sources/SwiftKitUI/Generic/NerverView.swift | swiftkitui/SwiftKitUI | 9084aff3b48283c4cc6cd627a47926d1fe4dbfb6 | [
"MIT"
] | 7 | 2019-07-09T02:39:16.000Z | 2021-04-12T07:02:46.000Z | Sources/SwiftKitUI/Generic/NerverView.swift | swiftkitui/SwiftKitUI | 9084aff3b48283c4cc6cd627a47926d1fe4dbfb6 | [
"MIT"
] | 1 | 2020-08-24T10:35:43.000Z | 2020-08-24T10:35:43.000Z | Sources/SwiftKitUI/Generic/NerverView.swift | swiftkitui/SwiftKitUI | 9084aff3b48283c4cc6cd627a47926d1fe4dbfb6 | [
"MIT"
] | 1 | 2020-05-04T01:44:32.000Z | 2020-05-04T01:44:32.000Z | //
// NerverView.swift
//
//
// Created by 张行 on 2019/7/8.
//
| 7.555556 | 30 | 0.5 |
d2907ddbf439605b80f1f11e6f43bf8eb7de44c5 | 2,383 | php | PHP | src/Models/PreviewOapiProcessinstanceCspaceParams/request.php | sdk-team/-php-test | b7c652901d9af6a76959bdb249e5c45dfae3ac64 | [
"Apache-2.0"
] | null | null | null | src/Models/PreviewOapiProcessinstanceCspaceParams/request.php | sdk-team/-php-test | b7c652901d9af6a76959bdb249e5c45dfae3ac64 | [
"Apache-2.0"
] | null | null | null | src/Models/PreviewOapiProcessinstanceCspaceParams/request.php | sdk-team/-php-test | b7c652901d9af6a76959bdb249e5c45dfae3ac64 | [
"Apache-2.0"
] | null | null | null | <?php
// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\SDK_DATA_1598238000612\Models\PreviewOapiProcessinstanceCspaceParams;
use AlibabaCloud\Tea\Model;
class request extends Model {
protected $_name = [
'agentid' => 'agentid',
'processInstanceId' => 'process_instance_id',
'fileId' => 'file_id',
'userid' => 'userid',
'fileidList' => 'fileid_list',
];
public function validate() {
Model::validateRequired('processInstanceId', $this->processInstanceId, true);
Model::validateRequired('userid', $this->userid, true);
}
public function toMap() {
$res = [];
if (null !== $this->agentid) {
$res['agentid'] = $this->agentid;
}
if (null !== $this->processInstanceId) {
$res['process_instance_id'] = $this->processInstanceId;
}
if (null !== $this->fileId) {
$res['file_id'] = $this->fileId;
}
if (null !== $this->userid) {
$res['userid'] = $this->userid;
}
if (null !== $this->fileidList) {
$res['fileid_list'] = $this->fileidList;
}
return $res;
}
/**
* @param array $map
* @return request
*/
public static function fromMap($map = []) {
$model = new self();
if(isset($map['agentid'])){
$model->agentid = $map['agentid'];
}
if(isset($map['process_instance_id'])){
$model->processInstanceId = $map['process_instance_id'];
}
if(isset($map['file_id'])){
$model->fileId = $map['file_id'];
}
if(isset($map['userid'])){
$model->userid = $map['userid'];
}
if(isset($map['fileid_list'])){
if(!empty($map['fileid_list'])){
$model->fileidList = $map['fileid_list'];
}
}
return $model;
}
/**
* @description 应用id
* @var int
*/
public $agentid;
/**
* @description 实例id
* @var string
*/
public $processInstanceId;
/**
* @description 附件id
* @var string
*/
public $fileId;
/**
* @description 授权用户id
* @var string
*/
public $userid;
/**
* @description 附件id列表,支持批量授权
* @var array
*/
public $fileidList;
}
| 25.084211 | 96 | 0.508183 |
15f6a9213b997cbdf7914a726f2077ac87d7ae14 | 52 | rb | Ruby | app/models/presentation/seminar.rb | naofumi/ponzu | ee685824a6876b71ac768067bb6d2c04738a9601 | [
"BSD-Source-Code"
] | null | null | null | app/models/presentation/seminar.rb | naofumi/ponzu | ee685824a6876b71ac768067bb6d2c04738a9601 | [
"BSD-Source-Code"
] | null | null | null | app/models/presentation/seminar.rb | naofumi/ponzu | ee685824a6876b71ac768067bb6d2c04738a9601 | [
"BSD-Source-Code"
] | null | null | null | class Presentation::Seminar < Presentation::Oral
end | 26 | 48 | 0.826923 |
39c5ef82012fa95a5792da2ed9999839cf137b9a | 820 | js | JavaScript | test/specs/aws/dynamo/schema/serialization/attributes/MapSerializerSpec.js | barchart/common-node-js | b3cf32f07d9a8a93b3485ad11170d542b2a1c371 | [
"MIT"
] | 1 | 2020-04-02T20:05:13.000Z | 2020-04-02T20:05:13.000Z | test/specs/aws/dynamo/schema/serialization/attributes/MapSerializerSpec.js | barchart/common-node-js | b3cf32f07d9a8a93b3485ad11170d542b2a1c371 | [
"MIT"
] | 1 | 2018-01-26T09:08:28.000Z | 2019-07-25T20:13:36.000Z | test/specs/aws/dynamo/schema/serialization/attributes/MapSerializerSpec.js | barchart/barchart-common-node-js | 391a5f19c36b4505ad38696d2f52b541af0b44cb | [
"MIT"
] | 1 | 2021-02-01T04:47:15.000Z | 2021-02-01T04:47:15.000Z | const MapSerializer = require('../../../../../../../aws/dynamo/schema/serialization/attributes/NestedSerializers').MapSerializer;
describe('When a MapSerializer is instantiated', () => {
'use strict';
let serializer;
beforeEach(() => {
serializer = new MapSerializer();
});
it('it serializes { "Name": "Joe", "Age": 35 } as { "M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}} }', () => {
let serialized = serializer.serialize({ Name: 'Joe', Age: 35 });
expect(serialized.M).toEqual({ Name: { S: 'Joe' }, Age: { N: '35' } });
});
it('it deserializes { "M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}} } as { "Name": "Joe", "Age": 35 }', () => {
let deserialized = serializer.deserialize({ M: { Name: { S: 'Joe' }, Age: { N: 35 } } });
expect(deserialized).toEqual({ Name: 'Joe', Age: 35 });
});
});
| 34.166667 | 129 | 0.547561 |
48de592d49c987a4f121a56a0e2253fd170b1487 | 10,524 | c | C | sys/src/cmd/disk/prep/edit.c | ekaitz-zarraga/jehanne | 431c7ae36521d0d931a21e1100d8522893d22a35 | [
"RSA-MD"
] | null | null | null | sys/src/cmd/disk/prep/edit.c | ekaitz-zarraga/jehanne | 431c7ae36521d0d931a21e1100d8522893d22a35 | [
"RSA-MD"
] | null | null | null | sys/src/cmd/disk/prep/edit.c | ekaitz-zarraga/jehanne | 431c7ae36521d0d931a21e1100d8522893d22a35 | [
"RSA-MD"
] | null | null | null | /*
* This file is part of the UCB release of Plan 9. It is subject to the license
* terms in the LICENSE file found in the top-level directory of this
* distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
* part of the UCB release of Plan 9, including this file, may be copied,
* modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
/* Portions of this file are Copyright (C) 2015-2018 Giacomo Tesio <giacomo@tesio.it>
* See /doc/license/gpl-2.0.txt for details about the licensing.
*/
/* Portions of this file are Copyright (C) 9front's team.
* See /doc/license/9front-mit for details about the licensing.
* See http://code.9front.org/hg/plan9front/ for a list of authors.
*/
/*
* disk partition editor
*/
#include <u.h>
#include <lib9.h>
#include <bio.h>
#include <ctype.h>
#include <disk.h>
#include "edit.h"
#undef write
char*
getline(Edit *edit)
{
static int inited;
static Biobuf bin;
char *p;
int n;
if(!inited){
Binit(&bin, 0, OREAD);
inited = 1;
}
p = Brdline(&bin, '\n');
n = Blinelen(&bin);
if(p == nil || n < 1){
if(edit->changed)
fprint(2, "?warning: changes not written\n");
exits(0);
}
p[n - 1] = '\0';
while(isspace(*p))
p++;
return p;
}
Part*
findpart(Edit *edit, char *name)
{
int i;
for(i=0; i<edit->npart; i++)
if(strcmp(edit->part[i]->name, name) == 0)
return edit->part[i];
return nil;
}
static char*
okname(Edit *edit, char *name)
{
int i;
static char msg[100];
if(name[0] == '\0')
return "partition has no name";
// if(strlen(name) >= NAMELEN)
// return "name too int32_t";
//
for(i=0; i<edit->npart; i++) {
if(strcmp(name, edit->part[i]->name) == 0) {
sprint(msg, "already have partition with name \"%s\"", name);
return msg;
}
}
return nil;
}
char*
addpart(Edit *edit, Part *p)
{
int i;
static char msg[100];
char *err;
if(err = okname(edit, p->name))
return err;
for(i=0; i<edit->npart; i++) {
if(p->start < edit->part[i]->end && edit->part[i]->start < p->end) {
sprint(msg, "\"%s\" %lld-%lld overlaps with \"%s\" %lld-%lld",
p->name, p->start, p->end,
edit->part[i]->name, edit->part[i]->start, edit->part[i]->end);
// return msg;
}
}
if(edit->npart >= nelem(edit->part))
return "too many partitions";
edit->part[i=edit->npart++] = p;
for(; i > 0 && p->start < edit->part[i-1]->start; i--) {
edit->part[i] = edit->part[i-1];
edit->part[i-1] = p;
}
if(p->changed)
edit->changed = 1;
return nil;
}
char*
delpart(Edit *edit, Part *p)
{
int i;
for(i=0; i<edit->npart; i++)
if(edit->part[i] == p)
break;
assert(i < edit->npart);
edit->npart--;
for(; i<edit->npart; i++)
edit->part[i] = edit->part[i+1];
edit->changed = 1;
return nil;
}
static char*
editdot(Edit *edit, int argc, char **argv)
{
char *err;
int64_t ndot;
if(argc == 1) {
print("\t. %lld\n", edit->dot);
return nil;
}
if(argc > 2)
return "args";
if(err = parseexpr(argv[1], edit->dot, edit->end, edit->end, edit->unitsz, &ndot))
return err;
edit->dot = ndot;
return nil;
}
static char*
editadd(Edit *edit, int argc, char **argv)
{
char *name, *err, *q;
static char msg[100];
int64_t start, end, maxend;
int i;
if(argc < 2)
return "args";
name = estrdup(argv[1]);
if((err = okname(edit, name)) || (err = edit->okname(edit, name)))
return err;
if(argc >= 3)
q = argv[2];
else {
fprint(2, "start %s: ", edit->unit);
q = getline(edit);
}
if(err = parseexpr(q, edit->dot, edit->end, edit->end, edit->unitsz, &start))
return err;
if(start < 0 || start >= edit->end)
return "start out of range";
for(i=0; i < edit->npart; i++) {
if(edit->part[i]->start <= start && start < edit->part[i]->end) {
sprint(msg, "start %s in partition \"%s\"", edit->unit, edit->part[i]->name);
return msg;
}
}
maxend = edit->end;
for(i=0; i < edit->npart; i++)
if(start < edit->part[i]->start && edit->part[i]->start < maxend)
maxend = edit->part[i]->start;
if(argc >= 4)
q = argv[3];
else {
fprint(2, "end [%lld..%lld] ", start, maxend);
q = getline(edit);
}
if(err = parseexpr(q, edit->dot, maxend, edit->end, edit->unitsz, &end))
return err;
if(start == end)
return "size zero partition";
if(end <= start || end > maxend)
return "end out of range";
if(argc > 4)
return "args";
if(err = edit->add(edit, name, start, end))
return err;
edit->dot = end;
return nil;
}
static char*
editdel(Edit *edit, int argc, char **argv)
{
Part *p;
if(argc != 2)
return "args";
if((p = findpart(edit, argv[1])) == nil)
return "no such partition";
return edit->del(edit, p);
}
static char *helptext =
". [newdot] - display or set value of dot\n"
"a name [start [end]] - add partition\n"
"d name - delete partition\n"
"h - print help message\n"
"p - print partition table\n"
"P - print commands to update sd(3) device\n"
"w - write partition table\n"
"q - quit\n";
static char*
edithelp(Edit *edit, int _, char** __)
{
print("%s", helptext);
if(edit->help)
return edit->help(edit);
return nil;
}
static char*
editprint(Edit *edit, int argc, char** _)
{
int64_t lastend;
int i;
Part **part;
if(argc != 1)
return "args";
lastend = 0;
part = edit->part;
for(i=0; i<edit->npart; i++) {
if(lastend < part[i]->start)
edit->sum(edit, nil, lastend, part[i]->start);
edit->sum(edit, part[i], part[i]->start, part[i]->end);
lastend = part[i]->end;
}
if(lastend < edit->end)
edit->sum(edit, nil, lastend, edit->end);
return nil;
}
char*
editwrite(Edit *edit, int argc, char** _)
{
int i;
char *err;
if(argc != 1)
return "args";
if(edit->disk->rdonly)
return "read only";
err = edit->write(edit);
if(err)
return err;
for(i=0; i<edit->npart; i++)
edit->part[i]->changed = 0;
edit->changed = 0;
return nil;
}
static char*
editquit(Edit *edit, int argc, char** _)
{
if(argc != 1) {
return "args";
}
if(edit->changed && (!edit->warned || edit->lastcmd != 'q')) {
edit->warned = 1;
return "changes unwritten";
}
exits(0);
return nil; /* not reached */
}
char*
editctlprint(Edit *edit, int argc, char ** _)
{
if(argc != 1)
return "args";
if(edit->printctl)
edit->printctl(edit, 1);
else
ctldiff(edit, 1);
return nil;
}
typedef struct Cmd Cmd;
struct Cmd {
char c;
char *(*fn)(Edit*, int ,char**);
};
Cmd cmds[] = {
'.', editdot,
'a', editadd,
'd', editdel,
'?', edithelp,
'h', edithelp,
'P', editctlprint,
'p', editprint,
'w', editwrite,
'q', editquit,
};
void
runcmd(Edit *edit, char *cmd)
{
char *f[10], *err;
int i, nf;
while(*cmd && isspace(*cmd))
cmd++;
nf = tokenize(cmd, f, nelem(f));
if(nf >= 10) {
fprint(2, "?\n");
return;
}
if(nf < 1)
return;
if(strlen(f[0]) != 1) {
fprint(2, "?\n");
return;
}
err = nil;
for(i=0; i<nelem(cmds); i++) {
if(cmds[i].c == f[0][0]) {
err = cmds[i].fn(edit, nf, f);
break;
}
}
if(i == nelem(cmds)){
if(edit->ext)
err = edit->ext(edit, nf, f);
else
err = "unknown command";
}
if(err)
fprint(2, "?%s\n", err);
edit->lastcmd = f[0][0];
}
static Part*
ctlmkpart(char *name, int64_t start, int64_t end, int changed)
{
Part *p;
p = emalloc(sizeof(*p));
p->name = estrdup(name);
p->ctlname = estrdup(name);
p->start = start;
p->end = end;
p->changed = changed;
return p;
}
static void
rdctlpart(Edit *edit)
{
int i, nline, nf;
char *line[128];
char buf[4096];
int64_t a, b;
char *f[5];
Disk *disk;
disk = edit->disk;
edit->nctlpart = 0;
seek(disk->ctlfd, 0, 0);
if(readn(disk->ctlfd, buf, sizeof buf) <= 0) {
return;
}
nline = getfields(buf, line, nelem(line), 1, "\n");
for(i=0; i<nline; i++){
if(strncmp(line[i], "part ", 5) != 0)
continue;
nf = getfields(line[i], f, nelem(f), 1, " \t\r");
if(nf != 4 || strcmp(f[0], "part") != 0)
break;
a = strtoll(f[2], 0, 0);
b = strtoll(f[3], 0, 0);
if(a >= b)
break;
/* only gather partitions contained in the disk partition we are editing */
if(a < disk->offset || disk->offset+disk->secs < b)
continue;
a -= disk->offset;
b -= disk->offset;
/* the partition we are editing does not count */
if(strcmp(f[1], disk->part) == 0)
continue;
if(edit->nctlpart >= nelem(edit->ctlpart)) {
fprint(2, "?too many partitions in ctl file\n");
exits("ctlpart");
}
edit->ctlpart[edit->nctlpart++] = ctlmkpart(f[1], a, b, 0);
}
}
static int64_t
ctlstart(Part *p)
{
if(p->ctlstart)
return p->ctlstart;
return p->start;
}
static int64_t
ctlend(Part *p)
{
if(p->ctlend)
return p->ctlend;
return p->end;
}
static int
areequiv(Part *p, Part *q)
{
if(p->ctlname[0]=='\0' || q->ctlname[0]=='\0')
return 0;
return strcmp(p->ctlname, q->ctlname) == 0
&& ctlstart(p) == ctlstart(q) && ctlend(p) == ctlend(q);
}
static void
unchange(Edit *edit, Part *p)
{
int i;
Part *q;
for(i=0; i<edit->nctlpart; i++) {
q = edit->ctlpart[i];
if(p->start <= q->start && q->end <= p->end) {
q->changed = 0;
}
}
assert(p->changed == 0);
}
int
ctldiff(Edit *edit, int ctlfd)
{
int i, j, waserr;
Part *p;
int64_t offset;
rdctlpart(edit);
/* everything is bogus until we prove otherwise */
for(i=0; i<edit->nctlpart; i++)
edit->ctlpart[i]->changed = 1;
/*
* partitions with same info have not changed,
* and neither have partitions inside them.
*/
for(i=0; i<edit->nctlpart; i++)
for(j=0; j<edit->npart; j++)
if(areequiv(edit->ctlpart[i], edit->part[j])) {
unchange(edit, edit->ctlpart[i]);
break;
}
waserr = 0;
/*
* delete all the changed partitions except data (we'll add them back if necessary)
*/
for(i=0; i<edit->nctlpart; i++) {
p = edit->ctlpart[i];
if(p->changed)
if(fprint(ctlfd, "delpart %s\n", p->ctlname)<0) {
fprint(2, "delpart failed: %s: %r\n", p->ctlname);
waserr = -1;
}
}
/*
* add all the partitions from the real list;
* this is okay since adding a parition with
* information identical to what is there is a no-op.
*/
offset = edit->disk->offset;
for(i=0; i<edit->npart; i++) {
p = edit->part[i];
if(p->ctlname[0]) {
if(fprint(ctlfd, "part %s %lld %lld\n", p->ctlname, offset+ctlstart(p), offset+ctlend(p)) < 0) {
fprint(2, "adding part failed: %s: %r\n", p->ctlname);
waserr = -1;
}
}
}
return waserr;
}
void*
emalloc(uint32_t sz)
{
void *v;
v = malloc(sz);
if(v == nil)
sysfatal("malloc %lud fails", sz);
memset(v, 0, sz);
return v;
}
char*
estrdup(char *s)
{
s = strdup(s);
if(s == nil)
sysfatal("strdup (%.10s) fails", s);
return s;
}
| 18.59364 | 99 | 0.592645 |
f05f3d26056a6f24ec4198f8e3f11a1da995bc57 | 7,555 | js | JavaScript | pohlig-hellman/bin/index.js | ReSource-Network/secrets.js | 243e447581a9b98fa22e951ce0d1b8afe0a36fe6 | [
"MIT"
] | 3 | 2021-05-19T03:18:56.000Z | 2021-06-27T04:11:39.000Z | pohlig-hellman/bin/index.js | ReSource-Network/secrets.js | 243e447581a9b98fa22e951ce0d1b8afe0a36fe6 | [
"MIT"
] | null | null | null | pohlig-hellman/bin/index.js | ReSource-Network/secrets.js | 243e447581a9b98fa22e951ce0d1b8afe0a36fe6 | [
"MIT"
] | 2 | 2020-06-19T20:22:40.000Z | 2021-05-25T22:59:32.000Z | "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
// IMPORTS
// ================================================================================================
const jsbn_1 = require("jsbn");
const util = require("./util");
// MODULE VARIABLES
// ================================================================================================
const SECURE_PRIME_LENGTH = 2048;
const MIN_PRIME_LENGTH = 4; // min allowed bit length for the prime
function createCipher(groupPrimeOrLength) {
return __awaiter(this, void 0, void 0, function* () {
let prime;
if (Buffer.isBuffer(groupPrimeOrLength)) {
prime = groupPrimeOrLength;
}
else if (typeof groupPrimeOrLength === 'number') {
if (groupPrimeOrLength < MIN_PRIME_LENGTH) {
throw new TypeError('Cannot create cipher: prime length is too small');
}
prime = yield util.generateSafePrime(groupPrimeOrLength);
}
else if (typeof groupPrimeOrLength === 'string') {
prime = util.getPrime(groupPrimeOrLength);
}
else if (groupPrimeOrLength === null || groupPrimeOrLength === undefined) {
prime = util.getPrime('modp2048');
}
else {
throw new TypeError('Cannot create cipher: prime is invalid');
}
const key = yield util.generateKey(prime);
return new Cipher(prime, key);
});
}
exports.createCipher = createCipher;
function mergeKeys(key1, key2) {
// validate key1
if (key1 === undefined || key1 === null) {
throw new TypeError(`Cannot merge keys: key1 is ${key1}`);
}
else if (!Buffer.isBuffer(key1)) {
throw new TypeError('Cannot merge keys: key1 is invalid');
}
else if (key1.byteLength === 0) {
throw new TypeError('Cannot merge keys: key1 is invalid');
}
// validate key2
if (key2 === undefined || key2 === null) {
throw new TypeError(`Cannot merge keys: key2 is ${key2}`);
}
else if (!Buffer.isBuffer(key2)) {
throw new TypeError('Cannot merge keys: key2 is invalid');
}
else if (key2.byteLength === 0) {
throw new TypeError('Cannot merge keys: key2 is invalid');
}
// convert keys to BigInts
const k1 = util.bufferToBigInt(key1);
const k2 = util.bufferToBigInt(key2);
// multiply and return
const k12 = k1.multiply(k2);
return util.bigIntToBuffer(k12);
}
exports.mergeKeys = mergeKeys;
// CIPHER DEFINITION
// ================================================================================================
class Cipher {
// CONSTRUCTOR
// --------------------------------------------------------------------------------------------
constructor(prime, enkey) {
// validate prime parameter
if (prime === undefined || prime === null) {
throw new TypeError(`Cannot create cipher: prime is ${prime}`);
}
else if (!Buffer.isBuffer(prime)) {
throw new TypeError('Cannot create cipher: prime is invalid');
}
// validate enkey parameter
if (enkey === undefined || enkey === null) {
throw new TypeError(`Cannot create cipher: enkey is ${enkey}`);
}
else if (!Buffer.isBuffer(enkey)) {
throw new TypeError('Cannot create cipher: enkey is invalid');
}
// set prime
this.prime = prime;
this.p = util.checkPrime(this.prime);
if (!this.p) {
throw new TypeError('Cannot create cipher: prime is not a prime');
}
else if (this.p.bitLength() < SECURE_PRIME_LENGTH) {
if (this.p.bitLength() < MIN_PRIME_LENGTH) {
throw new TypeError('Cannot create cipher: prime is too small');
}
console.warn('The prime you are using is too small for secure encryption');
}
// set encryption key
this.enkey = enkey;
this.e = util.bufferToBigInt(enkey);
if (!util.isValidKey(this.p, this.e)) {
throw new Error('Cannot create cipher: the encryption key is invalid');
}
// calculate and set decryption key
this.d = this.e.modInverse(this.p.subtract(jsbn_1.BigInteger.ONE));
this.dekey = util.bigIntToBuffer(this.d);
}
// PUBLIC FUNCTIONS
// --------------------------------------------------------------------------------------------
encrypt(data, encoding) {
if (data === undefined || data === null) {
throw new TypeError(`Cannot encrypt: data is ${data}`);
}
else if (data === '') {
throw new TypeError(`Cannot encrypt: data is an empty string`);
}
// prepare the data
let buf;
if (Buffer.isBuffer(data)) {
buf = data;
}
else if (typeof data === 'string') {
if (encoding === undefined) {
encoding = 'utf8';
}
if (encoding !== 'utf8' && encoding !== 'hex' && encoding !== 'base64') {
throw new TypeError('Cannot encrypt: encoding is invalid');
}
buf = Buffer.from(data, encoding);
}
else {
throw new TypeError('Cannot encrypt: data is invalid');
}
// convert data to numeric representation and make sure it is not bigger than prime
const m = util.bufferToBigInt(buf);
if (m.compareTo(this.p) >= 0) {
throw new TypeError('Cannot encrypt: data is too large');
}
// encrypt and return buffer
const c = m.modPow(this.e, this.p);
return util.bigIntToBuffer(c);
}
decrypt(data, encoding) {
if (data === undefined || data === null) {
throw new TypeError(`Cannot decrypt: data is ${data}`);
}
// prepare the data
let buf;
if (Buffer.isBuffer(data)) {
buf = data;
}
else if (typeof data === 'string') {
if (data === '') {
throw new TypeError(`Cannot decrypt: data is an empty string`);
}
if (encoding === undefined) {
encoding = 'hex';
}
if (encoding !== 'hex' && encoding !== 'base64') {
throw new TypeError('Cannot decrypt: encoding is invalid');
}
buf = Buffer.from(data, encoding);
}
else {
throw new TypeError('Cannot decrypt: data is invalid');
}
// convert buffer to bigint and check the size
const c = util.bufferToBigInt(buf);
if (c.bitLength() > this.p.bitLength()) {
throw new TypeError('Cannot decrypt: data is too large');
}
// decrypt and return the buffer
const m = c.modPow(this.d, this.p);
return util.bigIntToBuffer(m);
}
}
exports.Cipher = Cipher;
//# sourceMappingURL=index.js.map | 40.61828 | 151 | 0.530245 |
2a2029e9fe59fec7ac422210692cafe137fc3fe9 | 1,087 | java | Java | src/main/java/se/mickelus/tetra/data/deserializer/ItemPredicateDeserializer.java | LordGrimmauld/tetra | f083a963de952d5a60d96f4706a97557b0737fe8 | [
"MIT"
] | null | null | null | src/main/java/se/mickelus/tetra/data/deserializer/ItemPredicateDeserializer.java | LordGrimmauld/tetra | f083a963de952d5a60d96f4706a97557b0737fe8 | [
"MIT"
] | null | null | null | src/main/java/se/mickelus/tetra/data/deserializer/ItemPredicateDeserializer.java | LordGrimmauld/tetra | f083a963de952d5a60d96f4706a97557b0737fe8 | [
"MIT"
] | null | null | null | package se.mickelus.tetra.data.deserializer;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import net.minecraft.advancements.critereon.ItemPredicate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.ParametersAreNonnullByDefault;
import java.lang.reflect.Type;
@ParametersAreNonnullByDefault
public class ItemPredicateDeserializer implements JsonDeserializer<ItemPredicate> {
private static final Logger logger = LogManager.getLogger();
public static ItemPredicate deserialize(JsonElement json) {
try {
return ItemPredicate.fromJson(json);
} catch (JsonParseException e) {
logger.debug("Failed to parse item predicate from \"{}\": '{}'", json, e.getMessage());
// todo: debug level log
return null;
}
}
@Override
public ItemPredicate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return deserialize(json);
}
}
| 32.939394 | 129 | 0.799448 |
5039ccb1e8b7b50b67ffb1728f3312e3ea652404 | 1,017 | go | Go | pkg/snowflake/scim_integration.go | gouline/terraform-provider-snowflake | d8616f2100421fe4e3b4734b40ae28801e4193ac | [
"MIT"
] | 274 | 2019-02-13T18:10:52.000Z | 2022-03-31T17:49:07.000Z | pkg/snowflake/scim_integration.go | gouline/terraform-provider-snowflake | d8616f2100421fe4e3b4734b40ae28801e4193ac | [
"MIT"
] | 767 | 2019-01-17T21:36:54.000Z | 2022-03-31T23:08:35.000Z | pkg/snowflake/scim_integration.go | scottnguyen/terraform-provider-snowflake | 3f310a38c26931d0d33bee19797ec32c13add121 | [
"MIT"
] | 237 | 2019-04-05T21:22:16.000Z | 2022-03-16T19:01:31.000Z | package snowflake
import (
"database/sql"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
// ScimIntegration returns a pointer to a Builder that abstracts the DDL operations for an api integration.
//
// Supported DDL operations are:
// - CREATE SECURITY INTEGRATION
// - ALTER SECURITY INTEGRATION
// - DROP INTEGRATION
// - SHOW INTEGRATIONS
// - DESCRIBE INTEGRATION
//
// [Snowflake Reference](https://docs.snowflake.com/en/sql-reference/ddl-user-security.html#security-integrations)
func ScimIntegration(name string) *Builder {
return &Builder{
entityType: SecurityIntegrationType,
name: name,
}
}
type scimIntegration struct {
Name sql.NullString `db:"name"`
Category sql.NullString `db:"category"`
IntegrationType sql.NullString `db:"type"`
CreatedOn sql.NullString `db:"created_on"`
}
func ScanScimIntegration(row *sqlx.Row) (*scimIntegration, error) {
r := &scimIntegration{}
return r, errors.Wrap(row.StructScan(r), "error scanning struct")
}
| 26.763158 | 114 | 0.718781 |
a00ab9fc928ef50e627730e71c5dd2206aca13ce | 691 | kt | Kotlin | src/commonMain/kotlin/guru/zoroark/lixy/matchers/LixyTokenRecognizerIgnored.kt | utybo/Lixy | 1849bb1d75c1c775c28b4e411fb705a4d642fc89 | [
"Apache-2.0"
] | 35 | 2020-01-19T00:19:21.000Z | 2022-01-12T05:43:24.000Z | src/commonMain/kotlin/guru/zoroark/lixy/matchers/LixyTokenRecognizerIgnored.kt | utybo/Lixy | 1849bb1d75c1c775c28b4e411fb705a4d642fc89 | [
"Apache-2.0"
] | 3 | 2020-01-26T00:02:49.000Z | 2020-05-03T20:20:08.000Z | src/commonMain/kotlin/guru/zoroark/lixy/matchers/LixyTokenRecognizerIgnored.kt | utybo/Lixy | 1849bb1d75c1c775c28b4e411fb705a4d642fc89 | [
"Apache-2.0"
] | 2 | 2020-04-21T00:53:25.000Z | 2020-05-03T09:01:35.000Z | package guru.zoroark.lixy.matchers
/**
* A type of matcher that ignores anything that matches the recognizer and
* provides no result otherwise.
*/
class LixyTokenRecognizerIgnored(
/**
* The recognizer this matcher will use
*/
val recognizer: LixyTokenRecognizer,
/**
* The behavior to follow for determining the next state
*/
nextStateBehavior: LixyNextStateBehavior
) : LixyTokenMatcher(nextStateBehavior) {
override fun match(s: String, startAt: Int): LixyMatcherResult {
val (_, endsAt) = recognizer.recognize(s, startAt)
?: return LixyNoMatchResult
return LixyIgnoreMatchResult(endsAt, nextStateBehavior)
}
}
| 30.043478 | 74 | 0.701881 |
e72d960c096cf522fd060fc5ed13f58e7adb1d20 | 240 | js | JavaScript | index.js | SoraJin424/eslint-config | 7582c847b5f3652881ffd3707d50dc9b65bfdac9 | [
"MIT"
] | null | null | null | index.js | SoraJin424/eslint-config | 7582c847b5f3652881ffd3707d50dc9b65bfdac9 | [
"MIT"
] | null | null | null | index.js | SoraJin424/eslint-config | 7582c847b5f3652881ffd3707d50dc9b65bfdac9 | [
"MIT"
] | null | null | null | const { hasAnyDep } = require('ptils');
const typescript = hasAnyDep('typescript') && 'nineko/typescript';
const vue2 = hasAnyDep('vue') && 'nineko/vue2';
module.exports = {
extends: ['nineko/base', typescript, vue2].filter(Boolean)
};
| 26.666667 | 66 | 0.683333 |
75feaa51c25d19afbcd67f35c2a4428afb91dd7a | 54 | php | PHP | include/Zend/Gdata/Books/PaxHeader/CollectionEntry.php | Bvdldf/ABP | 245d36043db59568fc373951dc477ba4c8454c77 | [
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null | include/Zend/Gdata/Books/PaxHeader/CollectionEntry.php | Bvdldf/ABP | 245d36043db59568fc373951dc477ba4c8454c77 | [
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null | include/Zend/Gdata/Books/PaxHeader/CollectionEntry.php | Bvdldf/ABP | 245d36043db59568fc373951dc477ba4c8454c77 | [
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null | 30 mtime=1556801605.588341484
24 SCHILY.fflags=extent
| 18 | 29 | 0.851852 |
719b9d760f77e5e5859d96d8593a3aa176dc5190 | 73 | ts | TypeScript | src/types/imports.ts | patsissons/webrx-react | 227b83b91aa8a247db9b8f450e7cfa7dd47ec09c | [
"MIT"
] | 23 | 2016-11-09T19:12:05.000Z | 2018-10-27T15:19:53.000Z | src/types/imports.ts | patsissons/webrx-react | 227b83b91aa8a247db9b8f450e7cfa7dd47ec09c | [
"MIT"
] | 105 | 2016-11-10T02:01:38.000Z | 2018-04-23T22:11:15.000Z | src/types/imports.ts | patsissons/webrx-react | 227b83b91aa8a247db9b8f450e7cfa7dd47ec09c | [
"MIT"
] | 6 | 2016-12-22T09:03:49.000Z | 2021-04-02T12:02:30.000Z | // no imports at the moment so just export an empty structure
export {};
| 24.333333 | 61 | 0.739726 |
797bfa4f2602aaa7c0ad4ff0b048d2cb9e925d0f | 967 | dart | Dart | lib/widgets/cabin/cabin_dropdown.dart | albertmir/cabin_booking | bf99e1d512a2c282ea43988fd047ab3480f60606 | [
"MIT"
] | null | null | null | lib/widgets/cabin/cabin_dropdown.dart | albertmir/cabin_booking | bf99e1d512a2c282ea43988fd047ab3480f60606 | [
"MIT"
] | null | null | null | lib/widgets/cabin/cabin_dropdown.dart | albertmir/cabin_booking | bf99e1d512a2c282ea43988fd047ab3480f60606 | [
"MIT"
] | null | null | null | import 'package:cabin_booking/model/cabin_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
class CabinDropdown extends StatelessWidget {
final String value;
final void Function(String) onChanged;
const CabinDropdown({
this.value,
this.onChanged,
});
@override
Widget build(BuildContext context) {
return Consumer<CabinManager>(
builder: (context, cabinManager, child) {
return DropdownButtonFormField<String>(
value: value,
onChanged: onChanged,
items: [
for (final cabin in cabinManager.cabins)
DropdownMenuItem(
value: cabin.id,
child: Text(
'${AppLocalizations.of(context).cabin} ${cabin.number}',
),
),
],
isExpanded: true,
);
},
);
}
}
| 26.135135 | 74 | 0.601861 |
92b241df8b93d7f38b369b2b0d3cf903f05a86f3 | 304 | h | C | src/util/dl.h | dburkart/nord | 9b7d671e5ab223e23799e0af1341568392990339 | [
"BSD-2-Clause"
] | 1 | 2021-12-04T09:33:08.000Z | 2021-12-04T09:33:08.000Z | src/util/dl.h | gideonw/nord | a0615d913d577f509bbe7a4e59910c5dafc9813b | [
"BSD-2-Clause"
] | null | null | null | src/util/dl.h | gideonw/nord | a0615d913d577f509bbe7a4e59910c5dafc9813b | [
"BSD-2-Clause"
] | 1 | 2021-12-04T09:33:02.000Z | 2021-12-04T09:33:02.000Z | /*
* Copyright (c) 2021, Dana Burkart <dana.burkart@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#ifndef DL_H
#define DL_H
#include "util/platform.h"
/*
* Platform-agnostic way to load in symbols from the current
* executable.
*/
void *dynamic_load_self(const char *symbol);
#endif
| 16 | 60 | 0.703947 |
9bd9872a2febeac93c5a0f7e0d06f9b2ee5f50e9 | 406 | js | JavaScript | src/js/day3/systems/9_extras/plotters/plotSimpleGraph.js | Matoseb/2112-ecal | 0eea6ad09c8db213715700691a1073c30e7a2d55 | [
"MIT"
] | 1 | 2022-01-14T07:33:46.000Z | 2022-01-14T07:33:46.000Z | src/js/day3/systems/9_extras/plotters/plotSimpleGraph.js | Matoseb/2112-ecal | 0eea6ad09c8db213715700691a1073c30e7a2d55 | [
"MIT"
] | null | null | null | src/js/day3/systems/9_extras/plotters/plotSimpleGraph.js | Matoseb/2112-ecal | 0eea6ad09c8db213715700691a1073c30e7a2d55 | [
"MIT"
] | 2 | 2021-12-08T09:43:40.000Z | 2021-12-09T07:43:30.000Z | //dessine les séries de valeurs sous forme de lignes
function simpleGraph( ctx, values0, values1 )
{
//assigne le contexte à l'utilistaire de dessin
G.ctx = ctx;
//trace le graphe des températures en rouge
ctx.strokeStyle = "#F00";
G.polyline( values0 );
//scatterplot des vitesse du vent en bleu
ctx.fillStyle = "#09C";
values1.forEach( function( p ){G.disc(p, 2);} );
}
| 27.066667 | 52 | 0.662562 |
dd6de5c688763b832b873a575bae0edc4be0ea6a | 1,977 | php | PHP | resources/views/posts/index.blade.php | giorgian96/gestionarea_cheltuielilor | 04399161ef2c540402f87135e431cfbaaaf8847e | [
"MIT"
] | null | null | null | resources/views/posts/index.blade.php | giorgian96/gestionarea_cheltuielilor | 04399161ef2c540402f87135e431cfbaaaf8847e | [
"MIT"
] | null | null | null | resources/views/posts/index.blade.php | giorgian96/gestionarea_cheltuielilor | 04399161ef2c540402f87135e431cfbaaaf8847e | [
"MIT"
] | null | null | null | @extends('layouts.app')
@section('content')
@if(count($days) > 0)
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Selectați luna
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
@foreach ($months as $month)
<a href="#" class="dropdown-item">{{$month}}</a>
@endforeach
</div>
</div>
@foreach($days as $day => $posts)
<div class="card mt-3">
<div class="card-header">
<span>{{$day}}</span>
<span class="float-right">
@if(array_key_exists($day, $incomes) && array_key_exists($day, $expenses))
Incomes: {{$incomes[$day]}} | Expenses: {{$expenses[$day]}}
@elseif(array_key_exists($day, $incomes))
Incomes: {{$incomes[$day]}}
@elseif(array_key_exists($day, $expenses))
Expenses: {{$expenses[$day]}}
@endif
</span>
</div>
@foreach ($posts as $post)
<div class="card-body">
<h3 class="card-title"><a href="/posts/{{$post->id}}">{{$post->type}}</a></h3>
<p>{{$post->memo}}, {{$post->amount}}</p>
<small>de {{$post->user->name}}</small>
</div>
@if(!$loop->last)
<hr>
@endif
@endforeach
</div>
<br>
@endforeach
{{-- paginate
{{$posts->links()}} --}}
@else
<p>No posts found</p>
@endif
@endsection | 42.06383 | 166 | 0.41477 |
2dc9539ba527b2875d13060d0588dfeec7cf9ab5 | 222 | rs | Rust | src/test/ui/consts/auxiliary/issue-63226.rs | mbc-git/rust | 2c7bc5e33c25e29058cbafefe680da8d5e9220e9 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 66,762 | 2015-01-01T08:32:03.000Z | 2022-03-31T23:26:40.000Z | src/test/ui/consts/auxiliary/issue-63226.rs | maxrovskyi/rust | 51558ccb8e7cea87c6d1c494abad5451e5759979 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 76,993 | 2015-01-01T00:06:33.000Z | 2022-03-31T23:59:15.000Z | src/test/ui/consts/auxiliary/issue-63226.rs | maxrovskyi/rust | 51558ccb8e7cea87c6d1c494abad5451e5759979 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 11,787 | 2015-01-01T00:01:19.000Z | 2022-03-31T19:03:42.000Z | pub struct VTable{
state:extern "C" fn(),
}
impl VTable{
pub const fn vtable()->&'static VTable{
Self::VTABLE
}
const VTABLE: &'static VTable =
&VTable{state};
}
extern "C" fn state() {}
| 14.8 | 43 | 0.563063 |
6e3ec0de96d4c105500ad9174bb47298fbe5addb | 196 | kt | Kotlin | app/src/main/java/com/rorpage/purtyweather/ui/theme/Color.kt | rorpage/purty-weather | c093616d527d5a8d10a49b281f8c33399b1f4910 | [
"MIT"
] | null | null | null | app/src/main/java/com/rorpage/purtyweather/ui/theme/Color.kt | rorpage/purty-weather | c093616d527d5a8d10a49b281f8c33399b1f4910 | [
"MIT"
] | 16 | 2020-10-12T18:46:13.000Z | 2021-10-20T23:22:48.000Z | app/src/main/java/com/rorpage/purtyweather/ui/theme/Color.kt | rorpage/purty-weather | c093616d527d5a8d10a49b281f8c33399b1f4910 | [
"MIT"
] | 4 | 2020-10-05T19:16:23.000Z | 2020-10-30T13:58:12.000Z | package com.rorpage.purtyweather.ui.theme
import androidx.compose.ui.graphics.Color
val PurtyBlue = Color(0xFF87CEEB)
val PurtyBlueLight = Color(0xFFb9ffff)
val PurtyBlueDark = Color(0xFF539db8) | 28 | 41 | 0.826531 |
9cf813bc3a041f971d8e652ab507a733107171a4 | 719 | kt | Kotlin | ui/kotlinx-coroutines-android/android-unit-tests/test/ordered/tests/TestComponent.kt | jura73/kotlinx.coroutines | 64be7952806a0e7211ba3e513317a2772f6aacb5 | [
"Apache-2.0"
] | 4 | 2019-08-07T12:45:20.000Z | 2021-06-30T09:40:35.000Z | ui/kotlinx-coroutines-android/android-unit-tests/test/ordered/tests/TestComponent.kt | jura73/kotlinx.coroutines | 64be7952806a0e7211ba3e513317a2772f6aacb5 | [
"Apache-2.0"
] | 6 | 2019-01-28T14:38:29.000Z | 2019-01-28T15:55:22.000Z | ui/kotlinx-coroutines-android/android-unit-tests/test/ordered/tests/TestComponent.kt | jura73/kotlinx.coroutines | 64be7952806a0e7211ba3e513317a2772f6aacb5 | [
"Apache-2.0"
] | 1 | 2020-05-18T13:59:30.000Z | 2020-05-18T13:59:30.000Z | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package ordered.tests
import kotlinx.coroutines.*
public class TestComponent {
internal lateinit var caughtException: Throwable
private val scope =
CoroutineScope(SupervisorJob() + Dispatchers.Main + CoroutineExceptionHandler { _, e -> caughtException = e})
public var launchCompleted = false
public var delayedLaunchCompleted = false
fun launchSomething() {
scope.launch {
launchCompleted = true
}
}
fun launchDelayed() {
scope.launch {
delay(Long.MAX_VALUE)
delayedLaunchCompleted = true
}
}
}
| 24.793103 | 117 | 0.655076 |
d1d0046e041b1c87e68d259098295b2060b6dc29 | 753 | swift | Swift | Sources/Ultramarine/Extensions/Result.swift | niaeashes/ultramarine | e3b18ae6c5cd02244098726fbfbfb60fcdee19b8 | [
"MIT"
] | 1 | 2020-07-13T00:50:53.000Z | 2020-07-13T00:50:53.000Z | Sources/Ultramarine/Extensions/Result.swift | niaeashes/ultramarine | e3b18ae6c5cd02244098726fbfbfb60fcdee19b8 | [
"MIT"
] | null | null | null | Sources/Ultramarine/Extensions/Result.swift | niaeashes/ultramarine | e3b18ae6c5cd02244098726fbfbfb60fcdee19b8 | [
"MIT"
] | null | null | null | //
// Result.swift
// Ultramarine
//
// MARK: - Result.
extension Transmit {
public func ifSuccess<S, F>(_ completion: @escaping (S) -> Void) -> Transmit<Value> where Value == Result<S, F> {
return map {
switch $0 {
case .success(let value):
completion(value)
default:
break
}
return $0
}
}
public func ifFailure<S, F>(_ completion: @escaping (F) -> Void) -> Transmit<Value> where Value == Result<S, F> {
return map {
switch $0 {
case .failure(let error):
completion(error)
default:
break
}
return $0
}
}
}
| 22.147059 | 117 | 0.450199 |
f3fc16f6471115372789be85c91628ca67259709 | 1,351 | kt | Kotlin | android/watchface/src/main/java/com/benoitletondor/pixelminimalwatchface/drawer/digital/SecondsRingDrawer.kt | t-st92/PixelMinimalWatchFace | b806a2b892d1ab3716594b9890c7d83c83b8011c | [
"Apache-2.0"
] | null | null | null | android/watchface/src/main/java/com/benoitletondor/pixelminimalwatchface/drawer/digital/SecondsRingDrawer.kt | t-st92/PixelMinimalWatchFace | b806a2b892d1ab3716594b9890c7d83c83b8011c | [
"Apache-2.0"
] | null | null | null | android/watchface/src/main/java/com/benoitletondor/pixelminimalwatchface/drawer/digital/SecondsRingDrawer.kt | t-st92/PixelMinimalWatchFace | b806a2b892d1ab3716594b9890c7d83c83b8011c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 Benoit LETONDOR
*
* 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.
*/
package com.benoitletondor.pixelminimalwatchface.drawer.digital
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import java.util.*
interface SecondsRingDrawer {
fun drawSecondRing(
canvas: Canvas,
calendar: Calendar,
paint: Paint,
)
}
class SecondRingDrawerImpl(
private val screenWidth: Int,
private val screenHeight: Int,
) : SecondsRingDrawer {
override fun drawSecondRing(
canvas: Canvas,
calendar: Calendar,
paint: Paint,
) {
val endAngle = (calendar.get(Calendar.SECOND) * 6).toFloat()
canvas.drawArc(0F, 0F, screenWidth.toFloat(), screenHeight.toFloat(), 270F, endAngle, false, paint)
}
} | 31.418605 | 107 | 0.702443 |
c7e2040ee0f462d19e9f5dd0797cd8871716f381 | 1,447 | java | Java | net.qnenet.flowOSGiBasicStarter/src/com/example/starter/base/osgi/VaadinServletRegistration.java | QNENet/qne-flow-0.0.2 | 3a9d2f5355a3d1c79cb0b6904956c6007469ba36 | [
"Apache-2.0"
] | null | null | null | net.qnenet.flowOSGiBasicStarter/src/com/example/starter/base/osgi/VaadinServletRegistration.java | QNENet/qne-flow-0.0.2 | 3a9d2f5355a3d1c79cb0b6904956c6007469ba36 | [
"Apache-2.0"
] | null | null | null | net.qnenet.flowOSGiBasicStarter/src/com/example/starter/base/osgi/VaadinServletRegistration.java | QNENet/qne-flow-0.0.2 | 3a9d2f5355a3d1c79cb0b6904956c6007469ba36 | [
"Apache-2.0"
] | null | null | null | package com.example.starter.base.osgi;
import java.util.Hashtable;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
import com.vaadin.flow.server.VaadinServlet;
/**
* Register a VaadinServlet via HTTP Whiteboard specification
*/
@Component(immediate = true)
public class VaadinServletRegistration {
/**
* This class is a workaround for #4367. This will be removed after the
* issue is fixed.
*/
private static class FixedVaadinServlet extends VaadinServlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
getService().setClassLoader(getClass().getClassLoader());
}
}
@Activate
void activate(BundleContext ctx) {
Hashtable<String, Object> properties = new Hashtable<>();
properties.put(
HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ASYNC_SUPPORTED,
true);
properties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN,
"/*");
ctx.registerService(Servlet.class, new FixedVaadinServlet(),
properties);
}
}
| 30.145833 | 80 | 0.710435 |
d28dbe75e6988cac01bae3097aef1ed5b8f4e2b0 | 5,567 | php | PHP | resources/views/hoadon/create.blade.php | Phamngoan1999/-qlcuahang | f605829d71196291bdeb3433f49892d53eea2409 | [
"MIT"
] | null | null | null | resources/views/hoadon/create.blade.php | Phamngoan1999/-qlcuahang | f605829d71196291bdeb3433f49892d53eea2409 | [
"MIT"
] | null | null | null | resources/views/hoadon/create.blade.php | Phamngoan1999/-qlcuahang | f605829d71196291bdeb3433f49892d53eea2409 | [
"MIT"
] | null | null | null | @extends('header.quanly')
@section('content')
<div class="content-wrapper">
<div class="row">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Thêm phụ tùng sửa chữa</h4>
<form action="{{route('quanlysuachua.luuhoadon')}}" id="form-hoa-don" class="chi-tiet-hoa-don" method="POST">
@csrf
<div class="row">
<div class="col-md-5">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="">Chọn cửa hàng sửa chữa</label>
<select class="js-example-basic-single w-100 ma-cua-hang" name="iMa_cua_hang">
<option value="">Chọn cửa hàng</option>
@foreach($danhsachCuaHang as $cuahang)
<option value="{{$cuahang->id}}">{{$cuahang->ten_cua_hang}}</option>
@endforeach
</select>
</div>
<div class="error error-iMa_cua_hang"></div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="">Chọn xe sửa chữa</label>
<select class="js-example-basic-single w-100 xe-sua-chua" name="iMa_xe" >
<option value="">Chọn xe sửa chữa</option>
@foreach($danhsachXe as$xe)
<option value="{{$xe->id}}">{{$xe->dongxe->ten_dong_xe}}-{{$xe->bien_so}}</option>
@endforeach
</select>
</div>
<div class="error error-iMa_xe"></div>
</div>
</div>
<div class="row" style="padding-bottom: 20px;">
<div class="col-md-5">
<button type="button" class="btn btn-info" id="add-phu-tung" data-url="{{route('quanlysuachua.list-dich-vu')}}">
<i class="fa-solid fa-plus"></i> Thêm phụ tùng</button>
</div>
<div class="col-md-7">
<div class="error error-phutung"></div>
</div>
</div>
</div>
<div class="col-md-7">
<div id="list-phu-tung"></div>
<div class="col-md-7">
<div class="error error-phutung-rong"></div>
</div>
</div>
</div>
<div class="row group-btn">
<div class="col-md-12">
<button type="button" class="btn btn-primary" id="add-luu-thong-tin" >Lưu thông tin</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modal-list-dich-vu" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Thêm phụ tùng</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Đóng</button>
<button type="button" class="btn btn-primary" id="luu-dich-vu" data-url="{{route("quanlysuachua.list-dich-vu-select")}}">Lưu dịch vụ</button>
</div>
</div>
</div>
</div>
<style>
@media (min-width: 576px)
{
.modal-dialog {
max-width: 800px!important;
margin: 30px auto;
}
}
</style>
<script type="module" src="{{asset('js/admin/hoa_don.js')}}"></script>
@endsection
| 56.806122 | 161 | 0.346147 |
38996219cd42b864e0e74c7d07f27a63da5b8929 | 975 | h | C | Source/Ocean.Core/OceanCell.h | AndreyTalanin/Ocean | 81de89c501cda56a21fa20816250a930c6c1acfe | [
"MIT"
] | null | null | null | Source/Ocean.Core/OceanCell.h | AndreyTalanin/Ocean | 81de89c501cda56a21fa20816250a930c6c1acfe | [
"MIT"
] | null | null | null | Source/Ocean.Core/OceanCell.h | AndreyTalanin/Ocean | 81de89c501cda56a21fa20816250a930c6c1acfe | [
"MIT"
] | null | null | null | // Ocean - Copyright © Andrey Talanin 2020
// This file is subject to the terms and conditions defined in the
// file 'LICENSE.md', which is a part of this source code package.
#ifndef _OCEANCELL_H_
#define _OCEANCELL_H_
#include <cstdint>
#include "OceanObject.h"
class Ocean;
class OceanCell
{
private:
int32_t m_x;
int32_t m_y;
Ocean *m_ocean;
OceanObject *m_object;
public:
OceanCell(int32_t x, int32_t y, Ocean *ocean);
int32_t GetX() const;
int32_t GetY() const;
Ocean *GetOcean() const;
OceanObject *GetObject() const;
void SetObject(OceanObject *object);
bool ContainsObject() const;
bool IsMostNorthernCell() const;
bool IsMostSouthernCell() const;
bool IsMostWesternCell() const;
bool IsMostEasternCell() const;
OceanCell *GetCellOnNorth() const;
OceanCell *GetCellOnSouth() const;
OceanCell *GetCellOnWest() const;
OceanCell *GetCellOnEast() const;
};
#endif // _OCEANCELL_H_
| 21.666667 | 66 | 0.704615 |
8743bdfed0f315d7cf7de9bd1ca33496a04f653f | 4,413 | html | HTML | example/layouts/partials/home/benefits.html | johnatasjmo/dashcore-theme | 36fc98f313e64bfe09a7c8bc55e6ce00c900771d | [
"MIT"
] | null | null | null | example/layouts/partials/home/benefits.html | johnatasjmo/dashcore-theme | 36fc98f313e64bfe09a7c8bc55e6ce00c900771d | [
"MIT"
] | null | null | null | example/layouts/partials/home/benefits.html | johnatasjmo/dashcore-theme | 36fc98f313e64bfe09a7c8bc55e6ce00c900771d | [
"MIT"
] | null | null | null | <!-- ./Tons of benefits -->
<section class="section overflow-hidden">
<div class="container bring-to-front">
<div class="row gap-y align-items-center">
<div class="col-md-6 col-lg-5 mr-lg-auto">
<div class="center-xy op-1">
<div class="shape shape-background rounded-circle shadow-lg bg-info" style="width: 600px; height: 600px;" data-aos="zoom-in"></div>
</div>
<div class="device-twin align-items-center">
<div class="mockup absolute" data-aos="fade-left">
<div class="screen"><img src="img/screens/app/{{.Site.Data.text.benefitsImage1}}.png" alt="..."></div><span class="button"></span>
</div>
<div class="iphone-x front mr-0">
<div class="screen shadow-box"><img src="img/screens/app/{{.Site.Data.text.benefitsImage2}}.png" alt="..."></div>
<div class="notch"></div>
</div>
</div>
</div>
<div class="col-md-6 text-center text-md-left">
<div class="section-heading"><i class="fas fa-mountain fa-3x text-info mb-3"></i>
<h2 class="bold font-md"> {{.Site.Data.text.benefitsHeader}} </h2>
<p> {{.Site.Data.text.benefitsSubHeader}} </p>
</div>
<div class="row gap-y">
<div class="col-md-6">
<div class="media flex-column flex-lg-row align-items-center align-items-md-start"><i class="fab fa-android fa-2x text-info mx-auto ml-md-0 mr-md-3 stroke-primary"></i>
<div class="media-body mt-3 mt-md-0">
<h5 class="bold mt-0 mb-1">{{.Site.Data.text.benefitsTitle1}} </h5>
<p class="m-0 d-md-none d-lg-block"> {{.Site.Data.text.benefitsBody1}} </p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="media flex-column flex-lg-row align-items-center align-items-md-start"><i class="fab fa-apple fa-2x text-info mx-auto ml-md-0 mr-md-3 stroke-primary"></i>
<div class="media-body mt-3 mt-md-0">
<h5 class="bold mt-0 mb-1"> {{.Site.Data.text.benefitsTitle2}} </h5>
<p class="m-0 d-md-none d-lg-block"> {{.Site.Data.text.benefitsBody2}} </p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="media flex-column flex-lg-row align-items-center align-items-md-start"><i class="fas fa-mobile-alt fa-2x text-info mx-auto ml-md-0 mr-md-3 stroke-primary"></i>
<div class="media-body mt-3 mt-md-0">
<h5 class="bold mt-0 mb-1"> {{.Site.Data.text.benefitsTitle2}} </h5>
<p class="m-0 d-md-none d-lg-block"> {{.Site.Data.text.benefitsBody3}} </p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="media flex-column flex-lg-row align-items-center align-items-md-start"><i class="fas fa-desktop fa-2x text-info mx-auto ml-md-0 mr-md-3 stroke-primary"></i>
<div class="media-body mt-3 mt-md-0">
<h5 class="bold mt-0 mb-1"> {{.Site.Data.text.benefitsTitle3}} </h5>
<p class="m-0 d-md-none d-lg-block"> {{.Site.Data.text.benefitsBody3}} </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section> | 72.344262 | 203 | 0.410605 |
580786a1bc384b6107648301c7c2c58881f647e7 | 575 | h | C | blatSrc/inc/rainbow.h | zrhanna/blatq | 52aca91382dd17255e83bc95a9fa567c11a29d1f | [
"MIT"
] | 3 | 2019-06-12T15:21:58.000Z | 2021-07-16T00:48:21.000Z | blatSrc/inc/rainbow.h | calacademy-research/BLATq | 52aca91382dd17255e83bc95a9fa567c11a29d1f | [
"MIT"
] | 3 | 2016-12-26T15:47:06.000Z | 2019-06-28T01:29:47.000Z | lib/kent/src/inc/rainbow.h | ma-compbio/DESCHRAMBLER | a5ab2d8649f7b594aefb0e3d20de9b18854d24cc | [
"MIT"
] | 3 | 2018-10-26T21:45:32.000Z | 2020-03-08T21:35:13.000Z | /* rainbow - stuff to generate rainbow colors. */
#ifndef RAINBOW_H
#define RAINBOW_H
#ifndef MEMGFX_H
#include "memgfx.h"
#endif
struct rgbColor saturatedRainbowAtPos(double pos);
/* Given pos, a number between 0 and 1, return a saturated rainbow rgbColor
* where 0 maps to red, 0.1 is orange, and 0.9 is violet and 1.0 is back to red */
struct rgbColor lightRainbowAtPos(double pos);
/* Given pos, a number between 0 and 1, return a lightish rainbow rgbColor
* where 0 maps to red, 0.1 is orange, and 0.9 is violet and 1.0 is back to red */
#endif /* RAINBOW_H */
| 30.263158 | 83 | 0.728696 |
2ca3b04c1bfcba101be613708e949fe3e6e30f6c | 625 | kt | Kotlin | modules/ui/src/main/kotlin/com/harleyoconnor/gitdesk/ui/menubar/SelectableGenericStyledArea.kt | Harleyoc1/GitDesk | 88e49e1e3f1072fd16e7651dc716b891c50cfa71 | [
"MIT"
] | null | null | null | modules/ui/src/main/kotlin/com/harleyoconnor/gitdesk/ui/menubar/SelectableGenericStyledArea.kt | Harleyoc1/GitDesk | 88e49e1e3f1072fd16e7651dc716b891c50cfa71 | [
"MIT"
] | null | null | null | modules/ui/src/main/kotlin/com/harleyoconnor/gitdesk/ui/menubar/SelectableGenericStyledArea.kt | Harleyoc1/GitDesk | 88e49e1e3f1072fd16e7651dc716b891c50cfa71 | [
"MIT"
] | null | null | null | package com.harleyoconnor.gitdesk.ui.menubar
import org.fxmisc.richtext.GenericStyledArea
/**
*
* @author Harley O'Connor
*/
data class SelectableGenericStyledArea(
private val styledArea: GenericStyledArea<*, *, *>
) : Selectable {
override fun isFocused(): Boolean = styledArea.isFocused
override fun getSelection(): String = styledArea.selectedText
override fun removeSelection(): String {
val selection = getSelection()
styledArea.deleteText(styledArea.selection)
return selection
}
override fun replaceSelection(text: String) = styledArea.replaceSelection(text)
} | 26.041667 | 83 | 0.728 |
fbc59c39e1a5a013f8bba256409131a18b7f5747 | 384 | h | C | src/utils/DragonPID.h | Team302/2017Steamworks | 757a5332c47dd007482e30ee067852d13582ba39 | [
"MIT"
] | null | null | null | src/utils/DragonPID.h | Team302/2017Steamworks | 757a5332c47dd007482e30ee067852d13582ba39 | [
"MIT"
] | 1 | 2018-09-07T14:14:28.000Z | 2018-09-13T04:01:33.000Z | src/utils/DragonPID.h | Team302/2017Steamworks | 757a5332c47dd007482e30ee067852d13582ba39 | [
"MIT"
] | null | null | null | /*
* DragonPID.h
*
* Created on: Sep 15, 2016
* Author: Eric and Mike
*/
#ifndef SRC_DragonPID_H_
#define SRC_DragonPID_H_
namespace Team302 //HI I FIX UR CODE XDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
{
class DragonPID {
public:
DragonPID();
virtual ~DragonPID();
static float PControl(float currentVal, float targetVal, float Kp);
};
}
#endif /* SRC_DRAGONPID_H_ */
| 19.2 | 79 | 0.729167 |
8e21683935e711cc69e0c8c7cf757d625a7b8073 | 299 | asm | Assembly | try/boot_sect_main.asm | benediktweihs/os-tutorial | 629db14e01141622fce72e12d17ddb56f0e98312 | [
"BSD-3-Clause"
] | null | null | null | try/boot_sect_main.asm | benediktweihs/os-tutorial | 629db14e01141622fce72e12d17ddb56f0e98312 | [
"BSD-3-Clause"
] | null | null | null | try/boot_sect_main.asm | benediktweihs/os-tutorial | 629db14e01141622fce72e12d17ddb56f0e98312 | [
"BSD-3-Clause"
] | null | null | null | [org 0x7c00]
mov [BOOT_ENTRY], dl
mov bp, 0x9000 ; stack
mov sp, bp
mov bx, MSG_REAL_MODE
call print
;activate 32-bit protected mode
;
MSG_REAL_MODE db "Started in 16-bit Real Mode", 0
len equ $ - MSG_REAL_MODE
BOOT_ENTRY db 0
%include "./boot_print_16real.asm"
times 510-($-$$) db 0
dw 0xaa55
| 14.95 | 49 | 0.722408 |
5b09cf8266db8bdf3289746c788492d65040dad9 | 326 | asm | Assembly | programs/oeis/121/A121201.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/121/A121201.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/121/A121201.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A121201: 7^n+5^n-2n.
; 2,10,70,462,3018,19922,133262,901654,6155410,42306714,292240854,2026154846,14085427802,98109713506,684326588446,4778079088038,33385518460194,233393453440298,1632228295176038,11417968671701230
mov $2,$0
cal $0,81188 ; 6th binomial transform of (1,0,1,0,1,.....), A059841.
sub $0,$2
mov $1,$0
mul $1,2
| 36.222222 | 193 | 0.760736 |
2392ea900ba56777cf97ea476dc007b3b94ed3a3 | 83 | kt | Kotlin | app/src/main/java/me/hufman/androidautoidrive/music/RepeatMode.kt | einarjegorov/AndroidAutoIdrive | fff6878aae4be8278d08723707d1b15e241b432a | [
"MIT"
] | 300 | 2019-02-28T17:41:46.000Z | 2021-08-25T12:18:49.000Z | app/src/main/java/me/hufman/androidautoidrive/music/RepeatMode.kt | einarjegorov/AndroidAutoIdrive | fff6878aae4be8278d08723707d1b15e241b432a | [
"MIT"
] | 287 | 2019-03-12T20:33:19.000Z | 2021-08-28T10:26:35.000Z | app/src/main/java/me/hufman/androidautoidrive/music/RepeatMode.kt | einarjegorov/AndroidAutoIdrive | fff6878aae4be8278d08723707d1b15e241b432a | [
"MIT"
] | 64 | 2019-03-12T19:37:17.000Z | 2021-08-08T18:04:15.000Z | package me.hufman.androidautoidrive.music
enum class RepeatMode {
ALL, ONE, OFF
} | 16.6 | 41 | 0.783133 |
fb24d99ae7e2784a434356828e2d949d8670859c | 2,518 | kt | Kotlin | vknews/src/main/java/com/stacktivity/vknews/adapter/fingerprints/NewsVerticalImageFingerprint.kt | FireTiger33/VkCup_2021_android | 1a1677790fab113fb00c314b5a46f96bae1542ab | [
"Apache-2.0"
] | null | null | null | vknews/src/main/java/com/stacktivity/vknews/adapter/fingerprints/NewsVerticalImageFingerprint.kt | FireTiger33/VkCup_2021_android | 1a1677790fab113fb00c314b5a46f96bae1542ab | [
"Apache-2.0"
] | null | null | null | vknews/src/main/java/com/stacktivity/vknews/adapter/fingerprints/NewsVerticalImageFingerprint.kt | FireTiger33/VkCup_2021_android | 1a1677790fab113fb00c314b5a46f96bae1542ab | [
"Apache-2.0"
] | null | null | null | package com.stacktivity.vknews.adapter.fingerprints
import android.graphics.drawable.Drawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.stacktivity.vknews.R.layout.news_card_with_background_image
import com.stacktivity.vknews.adapter.NewsCardViewHolder
import com.stacktivity.vknews.adapter.NewsCardWithImageViewHolder
import com.stacktivity.vknews.adapter.NewsItemFingerprint
import com.stacktivity.vknews.databinding.NewsCardWithBackgroundImageBinding
import com.stacktivity.vknews.model.NewsItem
/**
* Fingerprint ViewHolder with text and vertical image
*
* @see NewsCardWithTextFingerprint
* @see NewsCardWithImageFingerprint
*/
class NewsCardWithBackgroundImageFingerprint : NewsItemFingerprint<NewsCardWithBackgroundImageBinding> {
override fun isRelativeItem(item: NewsItem): Boolean {
return if (item.imageWidth == null || item.imageHeight == null) {
false
} else item.imageWidth <= item.imageHeight
}
override fun getLayoutId() = news_card_with_background_image
override fun getViewHolder(
layoutInflater: LayoutInflater,
parent: ViewGroup
): NewsCardViewHolder<NewsCardWithBackgroundImageBinding> {
return CardWithBackgroundImageViewHolder(
NewsCardWithBackgroundImageBinding.inflate(layoutInflater, parent, false)
)
}
}
class CardWithBackgroundImageViewHolder(
binding: NewsCardWithBackgroundImageBinding
) : NewsCardWithImageViewHolder<NewsCardWithBackgroundImageBinding>(binding) {
override val imageContainer: View get() = binding.image
override val avatarContainer: View get() = binding.info.avatar
override fun onBind(item: NewsItem) {
reset()
binding.apply {
info.username.text = item.sourceInfo.name
info.timePassed.text = item.timePassed
text.text = item.text
bottomTextFix(text)
socialActions.likesCount.text = item.numLikes
socialActions.commentsCount.text = item.numComments
socialActions.repostsCount.text = item.numReposts
}
}
private fun reset() {
binding.image.setImageDrawable(null)
binding.text.gravity = Gravity.BOTTOM
}
override fun setImage(drawable: Drawable) {
binding.image.setImageDrawable(drawable)
}
override fun setUserAvatar(drawable: Drawable) {
binding.info.avatar.setImageDrawable(drawable)
}
} | 34.972222 | 104 | 0.74305 |
2f7cbdce379f39d1b19452735c82e0fd4b7701eb | 1,108 | swift | Swift | iOS_Swift_Learning/LNFTabBarController.swift | MrLiu163/iOS_Swift_Learning | 5c718a5473005763d3f38358adfe60652bd2de3c | [
"MIT"
] | null | null | null | iOS_Swift_Learning/LNFTabBarController.swift | MrLiu163/iOS_Swift_Learning | 5c718a5473005763d3f38358adfe60652bd2de3c | [
"MIT"
] | null | null | null | iOS_Swift_Learning/LNFTabBarController.swift | MrLiu163/iOS_Swift_Learning | 5c718a5473005763d3f38358adfe60652bd2de3c | [
"MIT"
] | null | null | null | //
// LNFTabBarController.swift
// iOS_Swift_Learning
//
// Created by mrliu on 2020/12/6.
//
import UIKit
class LNFTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
let firstVc = UIViewController.init()
firstVc.navigationItem.title = "收藏"
firstVc.view.backgroundColor = UIColor.lightGray
let firstNavi = UINavigationController.init(rootViewController: firstVc)
firstNavi.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarItem.SystemItem.favorites, tag: 100)
let secondVc = UIViewController.init()
secondVc.navigationItem.title = "更多"
secondVc.view.backgroundColor = UIColor.systemBlue
let secondNavi = UINavigationController.init(rootViewController: secondVc)
secondNavi.tabBarItem = UITabBarItem.init(tabBarSystemItem: UITabBarItem.SystemItem.more, tag: 101)
self.viewControllers = [firstNavi, secondNavi]
}
}
| 34.625 | 111 | 0.697653 |
f99eecd4b9674b4c0c8b7e7401a92decf821432d | 5,771 | go | Go | src/builder/pkg.go | KevinParnell/solbuild | c894514bafcdf7944f4067f9f78a2421b1add669 | [
"Apache-2.0"
] | 1 | 2019-07-16T07:22:50.000Z | 2019-07-16T07:22:50.000Z | src/builder/pkg.go | KevinParnell/solbuild | c894514bafcdf7944f4067f9f78a2421b1add669 | [
"Apache-2.0"
] | null | null | null | src/builder/pkg.go | KevinParnell/solbuild | c894514bafcdf7944f4067f9f78a2421b1add669 | [
"Apache-2.0"
] | null | null | null | //
// Copyright © 2016 Ikey Doherty <ikey@solus-project.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package builder
import (
"builder/source"
"encoding/xml"
"errors"
"fmt"
"github.com/go-yaml/yaml"
"io/ioutil"
"os"
"strings"
)
// PackageType is simply the type of package we're building, i.e. xml / pspec
type PackageType string
const (
// PackageTypeXML is the legacy package format, to be removed with sol introduction.
PackageTypeXML PackageType = "legacy"
// PackageTypeYpkg is the native build format of Solus, the package.yml format
PackageTypeYpkg PackageType = "ypkg"
// PackageTypeIndex is a faux type to enable indexing
PackageTypeIndex PackageType = "index"
)
var (
// IndexPackage is used by the index command to make use of the overlayfs
// system.
IndexPackage = Package{
Name: "index",
Version: "1.0.1",
Type: PackageTypeIndex,
Release: 1,
Path: "",
}
)
// Package is the main item we deal with, avoiding the internals
type Package struct {
Name string // Name of the package
Version string // Version of this package
Release int // Solus upgrades are based entirely on relno
Type PackageType // ypkg or pspec.xml legacy
Path string // Path to the build spec
Sources []source.Source // Each package has 0 or more sources that we fetch
CanNetwork bool // Only applicable to ypkg builds
}
// YmlPackage is a parsed ypkg build file
type YmlPackage struct {
Name string
Version string
Release int
Networking bool // If set to false (default) we disable networking in the build
Source []map[string]string
}
// XMLUpdate represents an update in the package history
type XMLUpdate struct {
Release int `xml:"release,attr"`
Date string
Version string
Comment string
Name string
Email string
}
// XMLArchive is an <Archive> line in Source section
type XMLArchive struct {
Type string `xml:"type,attr"`
SHA1Sum string `xml:"sha1sum,attr"`
URI string `xml:",chardata"`
}
// XMLSource is the actual source info for each pspec.xml
type XMLSource struct {
Homepage string
Name string
Archive []XMLArchive
}
// XMLPackage contains all of the pspec.xml metadata
type XMLPackage struct {
Name string
Source XMLSource
History []XMLUpdate `xml:"History>Update"`
}
// NewPackage will attempt to parse the given path, and return a new Package
// instance if this succeeds.
func NewPackage(path string) (*Package, error) {
if strings.HasSuffix(path, ".xml") {
return NewXMLPackage(path)
}
return NewYmlPackage(path)
}
// NewXMLPackage will attempt to parse the pspec.xml file @ path
func NewXMLPackage(path string) (*Package, error) {
var by []byte
var err error
var fi *os.File
fi, err = os.Open(path)
if err != nil {
return nil, err
}
defer fi.Close()
by, err = ioutil.ReadAll(fi)
if err != nil {
return nil, err
}
xpkg := &XMLPackage{}
if err = xml.Unmarshal(by, xpkg); err != nil {
return nil, err
}
if len(xpkg.History) < 1 {
return nil, errors.New("xml: Malformed pspec file")
}
upd := xpkg.History[0]
ret := &Package{
Name: strings.TrimSpace(xpkg.Source.Name),
Version: strings.TrimSpace(upd.Version),
Release: upd.Release,
Type: PackageTypeXML,
Path: path,
CanNetwork: true,
}
for _, archive := range xpkg.Source.Archive {
source, err := source.New(archive.URI, archive.SHA1Sum, true)
if err != nil {
return nil, err
}
ret.Sources = append(ret.Sources, source)
}
if ret.Name == "" {
return nil, errors.New("xml: Missing name in package")
}
if ret.Version == "" {
return nil, errors.New("xml: Missing version in package")
}
if ret.Release < 0 {
return nil, fmt.Errorf("xml: Invalid release in package: %d", ret.Release)
}
return ret, nil
}
// NewYmlPackage will attempt to parse the ypkg package.yml file @ path
func NewYmlPackage(path string) (*Package, error) {
var by []byte
var err error
var fi *os.File
fi, err = os.Open(path)
if err != nil {
return nil, err
}
defer fi.Close()
by, err = ioutil.ReadAll(fi)
if err != nil {
return nil, err
}
ret, err := NewYmlPackageFromBytes(by)
if err != nil {
return nil, err
}
ret.Path = path
return ret, nil
}
// NewYmlPackageFromBytes will attempt to parse the ypkg package.yml in memory
func NewYmlPackageFromBytes(by []byte) (*Package, error) {
var err error
ypkg := &YmlPackage{Networking: false}
if err = yaml.Unmarshal(by, ypkg); err != nil {
return nil, err
}
ret := &Package{
Name: strings.TrimSpace(ypkg.Name),
Version: strings.TrimSpace(ypkg.Version),
Release: ypkg.Release,
Type: PackageTypeYpkg,
CanNetwork: ypkg.Networking,
}
for _, row := range ypkg.Source {
for key, value := range row {
source, err := source.New(key, value, false)
if err != nil {
return nil, err
}
ret.Sources = append(ret.Sources, source)
}
}
if ret.Name == "" {
return nil, errors.New("ypkg: Missing name in package")
}
if ret.Version == "" {
return nil, errors.New("ypkg: Missing version in package")
}
if ret.Release < 0 {
return nil, fmt.Errorf("ypkg: Invalid release in package: %d", ret.Release)
}
return ret, nil
}
| 24.875 | 85 | 0.680991 |
86c3c69e03538ab20c98e61c6dd1553038f0f35a | 5,919 | go | Go | gooxml/docx_test.go | carmel/go-demo | 0857edec44b1b2610b9b312306e2e0b3e742f75f | [
"Apache-2.0"
] | null | null | null | gooxml/docx_test.go | carmel/go-demo | 0857edec44b1b2610b9b312306e2e0b3e742f75f | [
"Apache-2.0"
] | null | null | null | gooxml/docx_test.go | carmel/go-demo | 0857edec44b1b2610b9b312306e2e0b3e742f75f | [
"Apache-2.0"
] | null | null | null | package gooxml
import (
"fmt"
"log"
"testing"
"time"
"github.com/carmel/gooxml/color"
"github.com/carmel/gooxml/common"
"github.com/carmel/gooxml/document"
"github.com/carmel/gooxml/measurement"
"github.com/carmel/gooxml/schema/soo/wml"
)
var lorem = "我是一段很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本"
func TestImage(t *testing.T) {
doc := document.New()
img1, _ := common.ImageFromFile("1.png")
img2, _ := common.ImageFromFile("2.png")
img3, _ := common.ImageFromFile("3.png")
img1ref, _ := doc.AddImage(img1)
img2ref, _ := doc.AddImage(img2)
img3ref, _ := doc.AddImage(img3)
{
table := doc.AddTable()
// 4 inches wide
table.Properties().SetWidthPercent(100)
table.Properties().Borders().SetAll(wml.ST_BorderSingle, color.Auto, measurement.Zero)
table.Properties().SetAlignment(wml.ST_JcTableCenter)
row := table.AddRow()
// row.Properties().SetHeight(2*measurement.Inch, wml.ST_HeightRuleExact)
cell := row.AddCell()
cell.Properties().SetVerticalAlignment(wml.ST_VerticalJcCenter)
cell.Properties().SetColumnSpan(2)
para := cell.AddParagraph()
para.Properties().SetAlignment(wml.ST_JcCenter)
run := para.AddRun()
run.Properties().SetFontFamily("仿宋")
run.AddText("Cells can span multiple columns")
row = table.AddRow()
cell = row.AddCell()
cell.Properties().SetVerticalAlignment(wml.ST_VerticalJcCenter)
cell.Properties().SetVerticalMerge(wml.ST_MergeRestart)
cell.AddParagraph().AddRun().AddText("Vertical Merge")
para = row.AddCell().AddParagraph()
para.Properties().SetAlignment(wml.ST_JcCenter)
para.AddRun().AddDrawingInline(img1ref)
row = table.AddRow()
cell = row.AddCell()
cell.Properties().SetVerticalMerge(wml.ST_MergeContinue)
cell.AddParagraph()
row.AddCell().AddParagraph().AddRun().AddText("1122")
row = table.AddRow()
row.AddCell().AddParagraph().AddRun().AddText("Street Address")
row.AddCell().AddParagraph().AddRun().AddText("111 Country Road")
}
doc.AddParagraph()
{
para := doc.AddParagraph()
anchored, err := para.AddRun().AddDrawingAnchored(img1ref)
if err != nil {
log.Fatalf("unable to add anchored image: %s", err)
}
anchored.SetName("Gopher")
anchored.SetSize(2*measurement.Inch, 2*measurement.Inch)
anchored.SetOrigin(wml.WdST_RelFromHPage, wml.WdST_RelFromVTopMargin)
anchored.SetHAlignment(wml.WdST_AlignHCenter)
anchored.SetYOffset(3 * measurement.Inch)
anchored.SetTextWrapSquare(wml.WdST_WrapTextBothSides)
run := para.AddRun()
for i := 0; i < 16; i++ {
run.AddText(lorem)
// drop an inline image in
if i == 13 {
inl, err := run.AddDrawingInline(img2ref)
if err != nil {
log.Fatalf("unable to add inline image: %s", err)
}
inl.SetSize(1*measurement.Inch, 1*measurement.Inch)
}
if i == 15 {
inl, err := run.AddDrawingInline(img3ref)
if err != nil {
log.Fatalf("unable to add inline image: %s", err)
}
inl.SetSize(1*measurement.Inch, 1*measurement.Inch)
}
}
}
doc.SaveToFile("image.docx")
}
func TestDocproperties(t *testing.T) {
doc, err := document.Open("document.docx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
cp := doc.CoreProperties
// You can read properties from the document
fmt.Println("Title:", cp.Title())
fmt.Println("Author:", cp.Author())
fmt.Println("Description:", cp.Description())
fmt.Println("Last Modified By:", cp.LastModifiedBy())
fmt.Println("Category:", cp.Category())
fmt.Println("Content Status:", cp.ContentStatus())
fmt.Println("Created:", cp.Created())
fmt.Println("Modified:", cp.Modified())
// And change them as well
cp.SetTitle("CP Invoices")
cp.SetAuthor("John Doe")
cp.SetCategory("Invoices")
cp.SetContentStatus("Draft")
cp.SetLastModifiedBy("Jane Smith")
cp.SetCreated(time.Now())
cp.SetModified(time.Now())
doc.SaveToFile("document.docx")
}
func TestTemp(t *testing.T) {
// When Word saves a document, it removes all unused styles. This means to
// copy the styles from an existing document, you must first create a
// document that contains text in each style of interest. As an example,
// see the template.docx in this directory. It contains a paragraph set in
// each style that Word supports by default.
doc, err := document.OpenTemplate("temp.docx")
if err != nil {
log.Fatalf("error opening Windows Word 2016 document: %s", err)
}
// We can now print out all styles in the document, verifying that they
// exist.
for _, s := range doc.Styles.Styles() {
fmt.Println("style", s.Name(), "has ID of", s.StyleID(), "type is", s.Type())
}
// And create documents setting their style to the style ID (not style name).
para := doc.AddParagraph()
para.SetStyle("Title")
para.AddRun().AddText("My Document Title")
para = doc.AddParagraph()
para.SetStyle("Subtitle")
para.AddRun().AddText("Document Subtitle")
para = doc.AddParagraph()
para.SetStyle("Heading1")
para.AddRun().AddText("Major Section")
para = doc.AddParagraph()
para = doc.AddParagraph()
for i := 0; i < 4; i++ {
para.AddRun().AddText(lorem)
}
para = doc.AddParagraph()
para.SetStyle("Heading2")
para.AddRun().AddText("Minor Section")
para = doc.AddParagraph()
for i := 0; i < 4; i++ {
para.AddRun().AddText(lorem)
}
// using a pre-defined table style
table := doc.AddTable()
table.Properties().SetWidthPercent(90)
table.Properties().SetStyle("GridTable4-Accent1")
look := table.Properties().TableLook()
// these have default values in the style, so we manually turn some of them off
look.SetFirstColumn(false)
look.SetFirstRow(true)
look.SetLastColumn(false)
look.SetLastRow(true)
look.SetHorizontalBanding(true)
for r := 0; r < 5; r++ {
row := table.AddRow()
for c := 0; c < 5; c++ {
cell := row.AddCell()
cell.AddParagraph().AddRun().AddText(fmt.Sprintf("row %d col %d", r+1, c+1))
}
}
doc.SaveToFile("use-template.docx")
}
| 30.045685 | 109 | 0.701977 |
d26f116c5c0c8f2bc6a0f74a3ce3aa4d4002434a | 956 | php | PHP | app/Http/Controllers/Api/ShoppingCartController.php | PamelaPz/Laravel_CRM | bca25ad900b3c0bdcd75b04b1f4005e73e460972 | [
"MIT"
] | 4 | 2020-06-18T21:05:04.000Z | 2021-07-01T06:55:42.000Z | app/Http/Controllers/Api/ShoppingCartController.php | PamelaPz/Laravel_CRM | bca25ad900b3c0bdcd75b04b1f4005e73e460972 | [
"MIT"
] | null | null | null | app/Http/Controllers/Api/ShoppingCartController.php | PamelaPz/Laravel_CRM | bca25ad900b3c0bdcd75b04b1f4005e73e460972 | [
"MIT"
] | 2 | 2020-06-11T21:32:37.000Z | 2021-03-11T00:58:05.000Z | <?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Utils\ShoppingCartUtil;
use Illuminate\Http\Request;
class ShoppingCartController extends Controller
{
public function products(Request $request)
{
$sCartUtil = new ShoppingCartUtil($request->user());
return response()->json($sCartUtil->getCartProducts(), 200);
}
public function addProduct(Request $request)
{
$request->validate([
'product_id' => 'required|integer',
'qty' => 'required|integer',
]);
$sCartUtil = new ShoppingCartUtil($request->user());
$response = $sCartUtil->addProduct($request->product_id, $request->qty);
return response()->json($response, 201);
}
public function deleteProduct(Request $request)
{
$request->validate([
'product_id' => 'required|integer',
]);
$sCartUtil = new ShoppingCartUtil($request->user());
return response()->json($sCartUtil->deleteProduct($request->product_id), 200);
}
}
| 21.727273 | 80 | 0.708159 |
8225c6b03a0202703f23b02688ea1f5dda071ddc | 5,169 | asm | Assembly | Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0x84_notsx.log_21829_2923.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0x84_notsx.log_21829_2923.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0x84_notsx.log_21829_2923.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x16975, %rbx
nop
nop
cmp %rax, %rax
mov $0x6162636465666768, %r10
movq %r10, %xmm3
vmovups %ymm3, (%rbx)
nop
nop
cmp %r9, %r9
lea addresses_UC_ht+0x156c5, %rsi
lea addresses_D_ht+0x12d95, %rdi
clflush (%rdi)
nop
nop
nop
nop
dec %rdx
mov $109, %rcx
rep movsw
nop
nop
nop
nop
nop
add $6286, %rsi
lea addresses_A_ht+0x17fb5, %r10
nop
nop
nop
nop
xor %rcx, %rcx
movl $0x61626364, (%r10)
nop
nop
nop
inc %r10
lea addresses_D_ht+0x1caa5, %rsi
lea addresses_D_ht+0x11d25, %rdi
clflush (%rdi)
nop
nop
inc %r10
mov $18, %rcx
rep movsw
nop
add $28071, %rdi
lea addresses_normal_ht+0x145e5, %r10
nop
nop
nop
cmp $28921, %rdx
mov (%r10), %si
nop
cmp $44286, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r15
push %rax
push %rcx
// Faulty Load
lea addresses_D+0x66c5, %rax
nop
nop
nop
add $61111, %rcx
mov (%rax), %r13
lea oracles, %r10
and $0xff, %r13
shlq $12, %r13
mov (%r10,%r13,1), %r13
pop %rcx
pop %rax
pop %r15
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_D', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_D', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_WC_ht', 'same': True, 'size': 32, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 5, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
| 44.179487 | 2,999 | 0.66183 |
747364c32ea972e2084f25087e6f00d93647054f | 50,940 | h | C | Zmeya.h | sthagen/Zmeya | 36ddd2104044aa5cbdb7bd83fd6bf373d3f9f4a3 | [
"MIT"
] | 89 | 2021-03-18T05:09:51.000Z | 2022-02-27T12:38:34.000Z | Zmeya.h | sthagen/Zmeya | 36ddd2104044aa5cbdb7bd83fd6bf373d3f9f4a3 | [
"MIT"
] | null | null | null | Zmeya.h | sthagen/Zmeya | 36ddd2104044aa5cbdb7bd83fd6bf373d3f9f4a3 | [
"MIT"
] | 2 | 2021-09-15T09:58:39.000Z | 2022-02-16T05:23:33.000Z | // The MIT License (MIT)
//
// Copyright (c) 2021 Sergey Makeev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <array>
#include <cstddef>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <assert.h>
#include <xmmintrin.h>
// This macro is only needed if you want to create serializable data
// (deserialization doesn't need this)
//#define ZMEYA_ENABLE_SERIALIZE_SUPPORT
#define ZMEYA_ASSERT(cond) assert(cond)
//#define ZMEYA_NODISCARD [[nodiscard]]
#define ZMEYA_NODISCARD
#define ZMEYA_MAX_ALIGN (64)
#ifdef _DEBUG
#define ZMEYA_VALIDATE_HASH_DUPLICATES
#endif
namespace zm
{
#define ZMEYA_MURMURHASH_MAGIC64A 0xc6a4a7935bd1e995LLU
inline uint64_t murmur_hash_process64a(const char* key, uint32_t len, uint64_t seed)
{
const uint64_t m = ZMEYA_MURMURHASH_MAGIC64A;
const int r = 47;
uint64_t h = seed ^ (len * m);
const uint64_t* data = (const uint64_t*)key;
const uint64_t* end = data + (len / 8);
while (data != end)
{
uint64_t k = *data++;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
const unsigned char* data2 = (const unsigned char*)data;
switch (len & 7)
{
case 7:
h ^= (uint64_t)((uint64_t)data2[6] << (uint64_t)48);
case 6:
h ^= (uint64_t)((uint64_t)data2[5] << (uint64_t)40);
case 5:
h ^= (uint64_t)((uint64_t)data2[4] << (uint64_t)32);
case 4:
h ^= (uint64_t)((uint64_t)data2[3] << (uint64_t)24);
case 3:
h ^= (uint64_t)((uint64_t)data2[2] << (uint64_t)16);
case 2:
h ^= (uint64_t)((uint64_t)data2[1] << (uint64_t)8);
case 1:
h ^= (uint64_t)((uint64_t)data2[0]);
h *= m;
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
#undef ZMEYA_MURMURHASH_MAGIC64A
//
// Functions and types to interact with the application
// Feel free to replace them to your engine specific functions
//
namespace AppInterop
{
// hasher
template <typename T> ZMEYA_NODISCARD inline size_t hasher(const T& v) { return std::hash<T>{}(v); }
// string hasher
ZMEYA_NODISCARD inline size_t hashString(const char* str)
{
size_t len = std::strlen(str);
uint64_t hash = zm::murmur_hash_process64a(str, uint32_t(len), 13061979);
return size_t(hash);
}
// aligned allocator
ZMEYA_NODISCARD inline void* aligned_alloc(size_t size, size_t alignment) { return _mm_malloc(size, alignment); }
// aligned free
inline void aligned_free(void* p) { _mm_free(p); }
} // namespace AppInterop
// absolute offset/difference type
using offset_t = std::uintptr_t;
using diff_t = std::ptrdiff_t;
// relative offset type
using roffset_t = int32_t;
ZMEYA_NODISCARD inline offset_t toAbsolute(offset_t base, roffset_t offset)
{
offset_t res = base + diff_t(offset);
return res;
}
ZMEYA_NODISCARD inline uintptr_t toAbsoluteAddr(uintptr_t base, roffset_t offset)
{
uintptr_t res = base + ptrdiff_t(offset);
return res;
}
#ifdef ZMEYA_ENABLE_SERIALIZE_SUPPORT
template <typename T> class BlobPtr;
#endif
/*
Pointer - self-relative pointer relative to its own memory address
*/
template <typename T> class Pointer
{
// addr = this + offset
// offset(0) = this = nullptr (here is the limitation, pointer can't point to itself)
// this extra offset fits well into the x86/ARM addressing modes
// see for details https://godbolt.org/z/aTTW9E7o9
roffset_t relativeOffset;
bool isEqual(const Pointer& other) const noexcept { return get() == other.get(); }
ZMEYA_NODISCARD T* getUnsafe() const noexcept
{
uintptr_t self = uintptr_t(this);
// dereferencing a NULL pointer is undefined behavior, so we can skip nullptr check
ZMEYA_ASSERT(relativeOffset != 0);
uintptr_t addr = toAbsoluteAddr(self, relativeOffset);
return reinterpret_cast<T*>(addr);
}
public:
Pointer() noexcept = default;
// Pointer(const Pointer&) = delete;
// Pointer& operator=(const Pointer&) = delete;
ZMEYA_NODISCARD T* get() const noexcept
{
uintptr_t self = uintptr_t(this);
uintptr_t addr = (relativeOffset == 0) ? uintptr_t(0) : toAbsoluteAddr(self, relativeOffset);
return reinterpret_cast<T*>(addr);
}
#ifdef ZMEYA_ENABLE_SERIALIZE_SUPPORT
Pointer& operator=(const BlobPtr<T>& other);
#endif
// Note: implicit conversion operator
// operator const T*() const noexcept { return get(); }
// operator T*() noexcept { return get(); }
ZMEYA_NODISCARD T* operator->() const noexcept { return getUnsafe(); }
ZMEYA_NODISCARD T& operator*() const noexcept { return *(getUnsafe()); }
ZMEYA_NODISCARD bool operator==(const Pointer& other) const noexcept { return isEqual(other); }
ZMEYA_NODISCARD bool operator!=(const Pointer& other) const noexcept { return !isEqual(other); }
operator bool() const noexcept { return relativeOffset != 0; }
ZMEYA_NODISCARD bool operator==(std::nullptr_t) const noexcept { return relativeOffset == 0; }
ZMEYA_NODISCARD bool operator!=(std::nullptr_t) const noexcept { return relativeOffset != 0; }
friend class BlobBuilder;
};
/*
String
*/
class String
{
Pointer<char> data;
public:
String() noexcept = default;
// String(const String&) = delete;
// String& operator=(const String&) = delete;
bool isEqual(const char* s2) const noexcept
{
const char* s1 = c_str();
return (std::strcmp(s1, s2) == 0);
}
ZMEYA_NODISCARD const char* c_str() const noexcept
{
const char* v = data.get();
if (v != nullptr)
{
return v;
}
return "";
}
ZMEYA_NODISCARD bool empty() const noexcept { return data.get() != nullptr; }
ZMEYA_NODISCARD bool operator==(const String& other) const noexcept
{
// both strings can point to the same memory (fast-path)
if (other.c_str() == c_str())
{
return true;
}
return isEqual(other.c_str());
}
ZMEYA_NODISCARD bool operator!=(const String& other) const noexcept
{
// both strings can point to the same memory (fast-path)
if (other.c_str() == c_str())
{
return false;
}
return !isEqual(other.c_str());
}
friend class BlobBuilder;
};
ZMEYA_NODISCARD inline bool operator==(const String& left, const char* const right) noexcept { return left.isEqual(right); }
ZMEYA_NODISCARD inline bool operator!=(const String& left, const char* const right) noexcept { return !left.isEqual(right); }
ZMEYA_NODISCARD inline bool operator==(const char* const left, const String& right) noexcept { return right.isEqual(left); }
ZMEYA_NODISCARD inline bool operator!=(const char* const left, const String& right) noexcept { return !right.isEqual(left); }
ZMEYA_NODISCARD inline bool operator==(const String& left, const std::string& right) noexcept { return left.isEqual(right.c_str()); }
ZMEYA_NODISCARD inline bool operator!=(const String& left, const std::string& right) noexcept { return !left.isEqual(right.c_str()); }
ZMEYA_NODISCARD inline bool operator==(const std::string& left, const String& right) noexcept { return right.isEqual(left.c_str()); }
ZMEYA_NODISCARD inline bool operator!=(const std::string& left, const String& right) noexcept { return !right.isEqual(left.c_str()); }
/*
Array
*/
template <typename T> class Array
{
roffset_t relativeOffset;
uint32_t numElements;
private:
ZMEYA_NODISCARD const T* getConstData() const noexcept
{
uintptr_t addr = toAbsoluteAddr(uintptr_t(this), relativeOffset);
return reinterpret_cast<const T*>(addr);
}
ZMEYA_NODISCARD T* getData() const noexcept { return const_cast<T*>(getConstData()); }
public:
Array() noexcept = default;
// Array(const Array&) = delete;
// Array& operator=(const Array&) = delete;
ZMEYA_NODISCARD size_t size() const noexcept { return size_t(numElements); }
ZMEYA_NODISCARD T& operator[](const size_t index) noexcept
{
T* data = getData();
return data[index];
}
ZMEYA_NODISCARD const T& operator[](const size_t index) const noexcept
{
const T* data = getConstData();
return data[index];
}
ZMEYA_NODISCARD const T* at(const size_t index) const
{
ZMEYA_ASSERT(index < size());
const T* data = getConstData();
return data[index];
}
ZMEYA_NODISCARD T* data() noexcept { return getData(); }
ZMEYA_NODISCARD const T* data() const noexcept { return getConstData(); }
ZMEYA_NODISCARD const T* begin() const noexcept
{
const T* data = getConstData();
return data;
};
ZMEYA_NODISCARD const T* end() const noexcept
{
const T* data = getConstData();
return data + size();
};
ZMEYA_NODISCARD bool empty() const noexcept { return size() == 0; }
friend class BlobBuilder;
};
/*
Hash adapters
*/
// (key) generic adapter
template <typename Item> struct HashKeyAdapterGeneric
{
typedef Item ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hasher(item); }
static bool eq(const ItemType& a, const ItemType& b) { return a == b; }
};
// (key) adapter for std::string
struct HashKeyAdapterStdString
{
typedef std::string ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hashString(item.c_str()); }
static bool eq(const ItemType& a, const ItemType& b) { return a == b; }
};
// (key,value) generic adapter
template <typename Item> struct HashKeyValueAdapterGeneric
{
typedef Item ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hasher(item.first); }
static bool eq(const ItemType& a, const ItemType& b) { return a.first == b.first; }
};
// (key,value) adapter for std::string
template <typename Value> struct HashKeyValueAdapterStdString
{
typedef std::pair<const std::string, Value> ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hashString(item.first.c_str()); }
static bool eq(const ItemType& a, const ItemType& b) { return a.first == b.first; }
};
// (key) adapter for String and null-terminated c strings >> SearchAdapterCStrToString
// used only for search
struct HashKeyAdapterCStr
{
typedef const char* ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hashString(item); }
static bool eq(const String& a, const ItemType& b) { return a == b; }
};
/*
HashSet
*/
template <typename Key> class HashSet
{
public:
typedef Key Item;
struct Bucket
{
uint32_t beginIndex;
uint32_t endIndex;
};
Array<Bucket> buckets;
Array<Item> items;
template <typename Key2, typename Adapter> ZMEYA_NODISCARD bool containsImpl(const Key2& key) const noexcept
{
size_t numBuckets = buckets.size();
if (numBuckets == 0)
{
return false;
}
size_t hashMod = numBuckets;
size_t hash = Adapter::hash(key);
size_t bucketIndex = hash % hashMod;
const Bucket& bucket = buckets[bucketIndex];
for (size_t i = bucket.beginIndex; i < bucket.endIndex; i++)
{
const Key& item = items[i];
if (Adapter::eq(item, key))
{
return true;
}
}
return false;
}
public:
HashSet() noexcept = default;
// HashSet(const HashSet&) = delete;
// HashSet& operator=(const HashSet&) = delete;
ZMEYA_NODISCARD size_t size() const noexcept { return items.size(); }
ZMEYA_NODISCARD bool empty() const noexcept { return items.empty(); }
ZMEYA_NODISCARD const Item* begin() const noexcept { return items.begin(); }
ZMEYA_NODISCARD const Item* end() const noexcept { return items.end(); }
ZMEYA_NODISCARD bool contains(const char* key) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
return containsImpl<const char*, HashKeyAdapterCStr>(key);
}
ZMEYA_NODISCARD bool contains(const Key& key) const noexcept { return containsImpl<Key, HashKeyAdapterGeneric<Key>>(key); }
friend class BlobBuilder;
};
/*
Pair
*/
template <typename T1, typename T2> struct Pair
{
T1 first;
T2 second;
Pair() noexcept = default;
Pair(const T1& t1, const T2& t2) noexcept
: first(t1)
, second(t2)
{
}
};
/*
HashMap
*/
template <typename Key, typename Value> class HashMap
{
typedef Pair<const Key, Value> Item;
struct Bucket
{
uint32_t beginIndex;
uint32_t endIndex;
};
Array<Bucket> buckets;
Array<Item> items;
template <typename Adapter, typename Key2> ZMEYA_NODISCARD const Value* findImpl(const Key2& key) const noexcept
{
size_t numBuckets = buckets.size();
if (numBuckets == 0)
{
return nullptr;
}
size_t hashMod = numBuckets;
size_t hash = Adapter::hash(key);
size_t bucketIndex = hash % hashMod;
const Bucket& bucket = buckets[bucketIndex];
for (size_t i = bucket.beginIndex; i < bucket.endIndex; i++)
{
const Item& item = items[i];
if (Adapter::eq(item.first, key))
{
return &item.second;
}
}
return nullptr;
}
public:
HashMap() noexcept = default;
// HashMap(const HashMap&) = delete;
// HashMap& operator=(const HashMap&) = delete;
ZMEYA_NODISCARD size_t size() const noexcept { return items.size(); }
ZMEYA_NODISCARD bool empty() const noexcept { return items.empty(); }
ZMEYA_NODISCARD const Item* begin() const noexcept { return items.begin(); }
ZMEYA_NODISCARD const Item* end() const noexcept { return items.end(); }
ZMEYA_NODISCARD bool contains(const Key& key) const noexcept { return find(key) != nullptr; }
ZMEYA_NODISCARD Value* find(const Key& key) noexcept
{
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
return res ? const_cast<Value*>(res) : nullptr;
}
ZMEYA_NODISCARD const Value* find(const Key& key) const noexcept
{
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
return res;
}
ZMEYA_NODISCARD const Value& find(const Key& key, const Value& valueIfNotFound) const noexcept
{
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return *res;
}
return valueIfNotFound;
}
ZMEYA_NODISCARD bool contains(const char* key) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
return find(key) != nullptr;
}
ZMEYA_NODISCARD Value* find(const char* key) noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
return res ? const_cast<Value*>(res) : nullptr;
}
ZMEYA_NODISCARD const Value* find(const char* key) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
return res;
}
ZMEYA_NODISCARD const Value& find(const char* key, const Value& valueIfNotFound) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return *res;
}
return valueIfNotFound;
}
ZMEYA_NODISCARD const char* find(const Key& key, const char* valueIfNotFound) const noexcept
{
static_assert(std::is_same<Value, String>::value, "To use this function, the value type must be Zmeya::String");
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return res->c_str();
}
return valueIfNotFound;
}
ZMEYA_NODISCARD const char* find(const char* key, const char* valueIfNotFound) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
static_assert(std::is_same<Value, String>::value, "To use this function, the value type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return res->c_str();
}
return valueIfNotFound;
}
friend class BlobBuilder;
};
#ifdef ZMEYA_ENABLE_SERIALIZE_SUPPORT
ZMEYA_NODISCARD inline diff_t diff(offset_t a, offset_t b) noexcept
{
diff_t res = a - b;
return res;
}
ZMEYA_NODISCARD inline offset_t diffAddr(uintptr_t a, uintptr_t b)
{
ZMEYA_ASSERT(a >= b);
uintptr_t res = a - b;
ZMEYA_ASSERT(res <= uintptr_t(std::numeric_limits<offset_t>::max()));
return offset_t(res);
}
ZMEYA_NODISCARD inline roffset_t toRelativeOffset(diff_t v)
{
ZMEYA_ASSERT(v >= diff_t(std::numeric_limits<roffset_t>::min()));
ZMEYA_ASSERT(v <= diff_t(std::numeric_limits<roffset_t>::max()));
return roffset_t(v);
}
constexpr bool inline isPowerOfTwo(size_t v) { return v && ((v & (v - 1)) == 0); }
class BlobBuilder;
/*
This is a non-serializable pointer to blob internal memory
Note: blob is able to relocate its own memory that's is why we cannot use
standard pointers or references
*/
template <typename T> class BlobPtr
{
std::weak_ptr<const BlobBuilder> blob;
offset_t absoluteOffset = 0;
bool isEqual(const BlobPtr& other) const
{
if (blob != other.blob)
{
return false;
}
return absoluteOffset == other.absoluteOffset;
}
public:
explicit BlobPtr(std::weak_ptr<const BlobBuilder>&& _blob, offset_t _absoluteOffset)
: blob(std::move(_blob))
, absoluteOffset(_absoluteOffset)
{
}
BlobPtr() = default;
BlobPtr(BlobPtr&&) = default;
BlobPtr& operator=(BlobPtr&&) = default;
BlobPtr(const BlobPtr&) = default;
BlobPtr& operator=(const BlobPtr&) = default;
template <typename T2> BlobPtr(const BlobPtr<T2>& other)
{
static_assert(std::is_convertible<T2*, T*>::value, "Uncompatible types");
blob = other.blob;
absoluteOffset = other.absoluteOffset;
}
template <class T2> friend class BlobPtr;
offset_t getAbsoluteOffset() const { return absoluteOffset; }
ZMEYA_NODISCARD T* get() const;
T* operator->() const { return get(); }
T& operator*() const { return *(get()); }
operator bool() const { return get() != nullptr; }
bool operator==(const BlobPtr& other) const { return isEqual(other); }
bool operator!=(const BlobPtr& other) const { return !isEqual(other); }
template <typename T2> friend class Pointer;
};
/*
Blob allocator - aligned allocator for internal Blob usage
*/
template <typename T, int Alignment> class BlobBuilderAllocator : public std::allocator<T>
{
public:
typedef size_t size_type;
typedef T* pointer;
typedef const T* const_pointer;
template <typename _Tp1> struct rebind
{
typedef BlobBuilderAllocator<_Tp1, Alignment> other;
};
pointer allocate(size_type n)
{
void* const pv = AppInterop::aligned_alloc(n * sizeof(T), Alignment);
return static_cast<pointer>(pv);
}
void deallocate(pointer p, size_type) { AppInterop::aligned_free(p); }
BlobBuilderAllocator()
: std::allocator<T>()
{
}
BlobBuilderAllocator(const BlobBuilderAllocator& a)
: std::allocator<T>(a)
{
}
template <class U>
BlobBuilderAllocator(const BlobBuilderAllocator<U, Alignment>& a)
: std::allocator<T>(a)
{
}
~BlobBuilderAllocator() {}
};
/*
Span
*/
template <typename T> struct Span
{
T* data = nullptr;
size_t size = 0;
Span() = default;
Span(T* _data, size_t _size)
: data(_data)
, size(_size)
{
}
};
template <typename T> std::weak_ptr<T> weak_from(T* p)
{
std::shared_ptr<T> shared = p->shared_from_this();
return shared;
}
/*
Blob - a binary blob of data that is able to store POD types and special
"movable" data structures Note: Zmeya containers can be freely moved in
memory and deserialize from raw bytes without any extra work.
*/
class BlobBuilder : public std::enable_shared_from_this<BlobBuilder>
{
std::vector<char, BlobBuilderAllocator<char, ZMEYA_MAX_ALIGN>> data;
private:
ZMEYA_NODISCARD const char* get(offset_t absoluteOffset) const
{
ZMEYA_ASSERT(absoluteOffset < data.size());
return &data[absoluteOffset];
}
template <typename T> ZMEYA_NODISCARD BlobPtr<T> getBlobPtr(const T* p) const
{
ZMEYA_ASSERT(containsPointer(p));
offset_t absoluteOffset = diffAddr(uintptr_t(p), uintptr_t(data.data()));
return BlobPtr<T>(weak_from(this), absoluteOffset);
}
struct PrivateToken
{
};
public:
BlobBuilder() = delete;
BlobBuilder(size_t initialSizeInBytes, PrivateToken)
{
static_assert(std::is_trivially_copyable<Pointer<int>>::value, "Pointer is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<Array<int>>::value, "Array is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<HashSet<int>>::value, "HashSet is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<Pair<int, float>>::value, "Pair is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<HashMap<int, int>>::value, "HashMap is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<String>::value, "String is_trivially_copyable check failed");
data.reserve(initialSizeInBytes);
}
bool containsPointer(const void* p) const { return (!data.empty() && (p >= &data.front() && p <= &data.back())); }
BlobPtr<char> allocate(size_t numBytes, size_t alignment)
{
ZMEYA_ASSERT(isPowerOfTwo(alignment));
ZMEYA_ASSERT(alignment < ZMEYA_MAX_ALIGN);
//
size_t cursor = data.size();
// padding / alignment
size_t off = cursor & (alignment - 1);
size_t padding = 0;
if (off != 0)
{
padding = alignment - off;
}
size_t absoluteOffset = cursor + padding;
size_t numBytesToAllocate = numBytes + padding;
// Allocate more memory
// Note: new memory is filled with zeroes
// Zmeya containers rely on this behavior and we want to have all the padding zeroed as well
data.resize(data.size() + numBytesToAllocate, char(0));
// check alignment
ZMEYA_ASSERT((uintptr_t(&data[absoluteOffset]) & (alignment - 1)) == 0);
ZMEYA_ASSERT(absoluteOffset < size_t(std::numeric_limits<offset_t>::max()));
return BlobPtr<char>(weak_from(this), offset_t(absoluteOffset));
}
template <typename T, typename... _Valty> void placementCtor(void* ptr, _Valty&&... _Val)
{
::new (const_cast<void*>(static_cast<const volatile void*>(ptr))) T(std::forward<_Valty>(_Val)...);
}
template <typename T, typename... _Valty> BlobPtr<T> allocate(_Valty&&... _Val)
{
// compile time checks
static_assert(std::is_trivially_copyable<T>::value, "Only trivially copyable types allowed");
constexpr size_t alignOfT = std::alignment_of<T>::value;
static_assert(isPowerOfTwo(alignOfT), "Non power of two alignment not supported");
static_assert(alignOfT < ZMEYA_MAX_ALIGN, "Unsupported alignment");
constexpr size_t sizeOfT = sizeof(T);
BlobPtr<char> ptr = allocate(sizeOfT, alignOfT);
placementCtor<T>(ptr.get(), std::forward<_Valty>(_Val)...);
return BlobPtr<T>(weak_from(this), ptr.getAbsoluteOffset());
}
template <typename T> T& getDirectMemoryAccess(offset_t absoluteOffset)
{
const char* p = get(absoluteOffset);
return *const_cast<T*>(reinterpret_cast<const T*>(p));
}
template <typename T> void setArrayOffset(const BlobPtr<Array<T>>& dst, offset_t absoluteOffset)
{
dst->relativeOffset = toRelativeOffset(diff(absoluteOffset, dst.getAbsoluteOffset()));
}
template <typename T> offset_t resizeArrayWithoutInitialization(Array<T>& _dst, size_t numElements)
{
constexpr size_t alignOfT = std::alignment_of<T>::value;
constexpr size_t sizeOfT = sizeof(T);
static_assert((sizeOfT % alignOfT) == 0, "The size must be a multiple of the alignment");
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
// An array can be assigned/resized only once (non empty array detected)
ZMEYA_ASSERT(dst->relativeOffset == 0 && dst->numElements == 0);
BlobPtr<char> arrData = allocate(sizeOfT * numElements, alignOfT);
ZMEYA_ASSERT(numElements < size_t(std::numeric_limits<uint32_t>::max()));
dst->numElements = uint32_t(numElements);
setArrayOffset(dst, arrData.getAbsoluteOffset());
return arrData.getAbsoluteOffset();
}
// resize array (using copy constructor)
template <typename T> offset_t resizeArray(Array<T>& _dst, size_t numElements, const T& emptyElement)
{
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
offset_t absoluteOffset = resizeArrayWithoutInitialization(_dst, numElements);
T* current = &getDirectMemoryAccess<T>(absoluteOffset);
for (size_t i = 0; i < numElements; i++)
{
// call copy ctor
placementCtor<T>(current, emptyElement);
current++;
}
return absoluteOffset;
}
// resize array (using default constructor)
template <typename T> offset_t resizeArray(Array<T>& _dst, size_t numElements)
{
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
offset_t absoluteOffset = resizeArrayWithoutInitialization(_dst, numElements);
T* current = &getDirectMemoryAccess<T>(absoluteOffset);
for (size_t i = 0; i < numElements; i++)
{
// default ctor
placementCtor<T>(current);
current++;
}
return absoluteOffset;
}
// copyTo array fast (without using convertor)
template <typename T> offset_t copyToArrayFast(Array<T>& _dst, const T* begin, size_t numElements)
{
static_assert(std::is_trivially_copyable<T>::value, "Only trivially copyable types allowed");
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
offset_t absoluteOffset = resizeArrayWithoutInitialization(_dst, numElements);
T* arrData = &getDirectMemoryAccess<T>(absoluteOffset);
std::memcpy(arrData, begin, sizeof(T) * numElements);
return absoluteOffset;
}
// copyTo array from range
template <typename T, typename Iter, typename ConvertorFunc>
offset_t copyToArray(Array<T>& _dst, const Iter begin, const Iter end, int64_t size, ConvertorFunc convertorFunc)
{
size_t numElements = (size >= 0) ? size_t(size) : std::distance(begin, end);
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
resizeArray(_dst, numElements);
BlobPtr<T> firstElement = getBlobPtr(dst->data());
offset_t absoluteOffset = firstElement.getAbsoluteOffset();
offset_t currentIndex = 0;
for (Iter cur = begin; cur != end; ++cur)
{
offset_t currentItemAbsoluteOffset = absoluteOffset + sizeof(T) * currentIndex;
convertorFunc(this, currentItemAbsoluteOffset, *cur);
currentIndex++;
}
return absoluteOffset;
}
// copyTo hash container
template <typename ItemSrcAdapter, typename ItemDstAdapter, typename HashType, typename Iter, typename ConvertorFunc>
void copyToHash(HashType& _dst, Iter begin, Iter end, int64_t size, ConvertorFunc convertorFunc)
{
// Note: this bucketing method relies on the fact that the input data set is (already) unique
size_t numElements = (size >= 0) ? size_t(size) : std::distance(begin, end);
ZMEYA_ASSERT(numElements > 0);
size_t numBuckets = numElements * 2;
ZMEYA_ASSERT(numBuckets < size_t(std::numeric_limits<uint32_t>::max()));
size_t hashMod = numBuckets;
BlobPtr<HashType> dst = getBlobPtr(&_dst);
// allocate buckets & items
resizeArray(dst->buckets, numBuckets);
// 1-st pass count the number of elements per bucket (beginIndex / endIndex)
typename HashType::Bucket* buckets = &dst->buckets[0];
for (Iter cur = begin; cur != end; ++cur)
{
const auto& current = *cur;
size_t hash = ItemSrcAdapter::hash(current);
size_t bucketIndex = hash % hashMod;
buckets[bucketIndex].beginIndex++; // temporary use beginIndex to store the number of items
}
size_t beginIndex = 0;
for (size_t bucketIndex = 0; bucketIndex < numBuckets; bucketIndex++)
{
typename HashType::Bucket& bucket = buckets[bucketIndex];
size_t numElementsInBucket = bucket.beginIndex;
bucket.beginIndex = uint32_t(beginIndex);
bucket.endIndex = bucket.beginIndex;
beginIndex += numElementsInBucket;
}
// 2-st pass copy items
offset_t absoluteOffset = resizeArrayWithoutInitialization(dst->items, numElements);
for (Iter cur = begin; cur != end; ++cur)
{
const auto& current = *cur;
size_t hash = ItemSrcAdapter::hash(current);
size_t bucketIndex = hash % hashMod;
typename HashType::Bucket& bucket = dst->buckets[bucketIndex];
uint32_t elementIndex = bucket.endIndex;
offset_t currentItemAbsoluteOffset = absoluteOffset + sizeof(typename ItemDstAdapter::ItemType) * offset_t(elementIndex);
convertorFunc(this, currentItemAbsoluteOffset, *cur);
#ifdef ZMEYA_VALIDATE_HASH_DUPLICATES
const typename ItemDstAdapter::ItemType& lastItem =
getDirectMemoryAccess<typename ItemDstAdapter::ItemType>(currentItemAbsoluteOffset);
size_t newItemHash = ItemDstAdapter::hash(lastItem);
// inconsistent hashing! hash(srcItem) != hash(dstItem)
ZMEYA_ASSERT(hash == newItemHash);
for (uint32_t testElementIndex = bucket.beginIndex; testElementIndex < bucket.endIndex; testElementIndex++)
{
offset_t testItemAbsoluteOffset = absoluteOffset + sizeof(typename ItemDstAdapter::ItemType) * offset_t(testElementIndex);
const typename ItemDstAdapter::ItemType& testItem =
getDirectMemoryAccess<typename ItemDstAdapter::ItemType>(testItemAbsoluteOffset);
ZMEYA_ASSERT(!ItemDstAdapter::eq(testItem, lastItem));
}
#endif
bucket.endIndex++;
}
}
// assignTo pointer
template <typename T> static void assignTo(Pointer<T>& dst, std::nullptr_t) { dst.relativeOffset = 0; }
// assignTo pointer from absolute offset
template <typename T> void assignTo(Pointer<T>& _dst, offset_t targetAbsoluteOffset)
{
BlobPtr<Pointer<T>> dst = getBlobPtr(&_dst);
roffset_t relativeOffset = toRelativeOffset(diff(targetAbsoluteOffset, dst.getAbsoluteOffset()));
ZMEYA_ASSERT(relativeOffset != 0);
dst->relativeOffset = relativeOffset;
}
// copyTo pointer from BlobPtr
template <typename T> void assignTo(Pointer<T>& dst, const BlobPtr<T>& src) { assignTo(dst, src.getAbsoluteOffset()); }
// copyTo pointer from RawPointer
template <typename T> void assignTo(Pointer<T>& dst, const T* _src)
{
const BlobPtr<T> src = getBlobPtr(_src);
assignTo(dst, src);
}
// copyTo pointer from reference
template <typename T> void assignTo(Pointer<T>& dst, const T& src) { assignTo(dst, &src); }
// copyTo array from std::vector
template <typename T, typename TAllocator> void copyTo(Array<T>& dst, const std::vector<T, TAllocator>& src)
{
ZMEYA_ASSERT(src.size() > 0);
copyToArrayFast(dst, src.data(), src.size());
}
// specialization for vector of vectors
template <typename T, typename TAllocator1, typename TAllocator2>
void copyTo(Array<Array<T>>& dst, const std::vector<std::vector<T, TAllocator2>, TAllocator1>& src)
{
ZMEYA_ASSERT(src.size() > 0);
copyToArray(dst, src.begin(), src.end(), src.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const std::vector<T>& src) {
Array<T>& dst = blobBuilder->getDirectMemoryAccess<Array<T>>(dstAbsoluteOffset);
blobBuilder->copyTo(dst, src);
});
}
// specialization for vector of strings
template <typename T, typename TAllocator> void copyTo(Array<String>& dst, const std::vector<T, TAllocator>& src)
{
ZMEYA_ASSERT(src.size() > 0);
copyToArray(dst, src.begin(), src.end(), src.size(), [](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const T& src) {
String& dst = blobBuilder->getDirectMemoryAccess<String>(dstAbsoluteOffset);
blobBuilder->copyTo(dst, src);
});
}
// copyTo array from std::initializer_list
template <typename T> void copyTo(Array<T>& dst, std::initializer_list<T> list)
{
ZMEYA_ASSERT(list.size() > 0);
copyToArrayFast(dst, list.begin(), list.size());
}
// specialization for std::initializer_list<std::string>
void copyTo(Array<String>& dst, std::initializer_list<const char*> list)
{
ZMEYA_ASSERT(list.size() > 0);
copyToArray(dst, list.begin(), list.end(), list.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const char* const& src) {
String& dst = blobBuilder->getDirectMemoryAccess<String>(dstAbsoluteOffset);
blobBuilder->copyTo(dst, src);
});
}
// copyTo array from std::array
template <typename T, size_t NumElements> void copyTo(Array<T>& dst, const std::array<T, NumElements>& src)
{
ZMEYA_ASSERT(src.size() > 0);
copyToArrayFast(dst, src.data(), src.size());
}
// specialization for array of strings
template <typename T, size_t NumElements> void copyTo(Array<String>& dst, const std::array<T, NumElements>& src)
{
ZMEYA_ASSERT(src.size() > 0);
copyToArray(dst, src.begin(), src.end(), src.size(), [](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const T& src) {
String& dst = blobBuilder->getDirectMemoryAccess<String>(dstAbsoluteOffset);
blobBuilder->copyTo(dst, src);
});
}
// copyTo hash set from std::unordered_set
template <typename Key, typename Hasher, typename KeyEq, typename TAllocator>
void copyTo(HashSet<Key>& dst, const std::unordered_set<Key, Hasher, KeyEq, TAllocator>& src)
{
typedef HashKeyAdapterGeneric<Key> DstItemAdapter;
typedef HashKeyAdapterGeneric<Key> SrcItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, src.begin(), src.end(), src.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
dstElem = srcElem;
});
}
// copyTo hash set from std::unordered_set (specialization for string key)
template <typename Hasher, typename KeyEq, typename TAllocator>
void copyTo(HashSet<String>& dst, const std::unordered_set<std::string, Hasher, KeyEq, TAllocator>& src)
{
typedef HashKeyAdapterStdString SrcItemAdapter;
typedef HashKeyAdapterGeneric<String> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, src.begin(), src.end(), src.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
blobBuilder->copyTo(dstElem, srcElem);
});
}
// copyTo hash set from std::initializer_list
template <typename Key> void copyTo(HashSet<Key>& dst, std::initializer_list<Key> list)
{
typedef HashKeyAdapterGeneric<Key> SrcItemAdapter;
typedef HashKeyAdapterGeneric<Key> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, list.begin(), list.end(), list.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
dstElem = srcElem;
});
}
// copyTo hash set from std::initializer_list (specialization for string key)
void copyTo(HashSet<String>& dst, std::initializer_list<std::string> list)
{
typedef HashKeyAdapterStdString SrcItemAdapter;
typedef HashKeyAdapterGeneric<String> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, list.begin(), list.end(), list.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
blobBuilder->copyTo(dstElem, srcElem);
});
}
// copyTo hash map from std::unordered_map
template <typename Key, typename Value, typename Hasher, typename KeyEq, typename TAllocator>
void copyTo(HashMap<Key, Value>& dst, const std::unordered_map<Key, Value, Hasher, KeyEq, TAllocator>& src)
{
typedef HashKeyValueAdapterGeneric<std::pair<const Key, Value>> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<Key, Value>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, src.begin(), src.end(), src.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
dstElem.first = srcElem.first;
dstElem.second = srcElem.second;
});
}
// copyTo hash set from std::unordered_map (specialization for string key)
template <typename Value, typename Hasher, typename KeyEq, typename TAllocator>
void copyTo(HashMap<String, Value>& dst, const std::unordered_map<std::string, Value, Hasher, KeyEq, TAllocator>& src)
{
typedef HashKeyValueAdapterStdString<Value> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<String, Value>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, src.begin(), src.end(), src.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
blobBuilder->copyTo(dstElem.first, srcElem.first);
dstElem.second = srcElem.second;
});
}
// copyTo hash set from std::unordered_map (specialization for string value)
template <typename Key, typename Hasher, typename KeyEq, typename TAllocator>
void copyTo(HashMap<Key, String>& dst, const std::unordered_map<Key, std::string, Hasher, KeyEq, TAllocator>& src)
{
typedef HashKeyValueAdapterGeneric<std::pair<const Key, std::string>> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<Key, String>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, src.begin(), src.end(), src.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
dstElem.first = srcElem.first;
blobBuilder->copyTo(dstElem.second, srcElem.second);
});
}
// copyTo hash set from std::unordered_map (specialization for string key/value)
template <typename Hasher, typename KeyEq, typename TAllocator>
void copyTo(HashMap<String, String>& dst, const std::unordered_map<std::string, std::string, Hasher, KeyEq, TAllocator>& src)
{
typedef HashKeyValueAdapterStdString<std::string> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<String, String>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, src.begin(), src.end(), src.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
blobBuilder->copyTo(dstElem.first, srcElem.first);
blobBuilder->copyTo(dstElem.second, srcElem.second);
});
}
// copyTo hash map from std::initializer_list
template <typename Key, typename Value> void copyTo(HashMap<Key, Value>& dst, std::initializer_list<std::pair<const Key, Value>> list)
{
typedef HashKeyValueAdapterGeneric<std::pair<const Key, Value>> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<Key, Value>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, list.begin(), list.end(), list.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
dstElem.first = srcElem.first;
dstElem.second = srcElem.second;
});
}
// copyTo hash map from std::initializer_list (specialization for string key)
template <typename Value> void copyTo(HashMap<String, Value>& dst, std::initializer_list<std::pair<const std::string, Value>> list)
{
typedef HashKeyValueAdapterStdString<Value> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<String, Value>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, list.begin(), list.end(), list.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
blobBuilder->copyTo(dstElem.first, srcElem.first);
dstElem.second = srcElem.second;
});
}
// copyTo hash map from std::initializer_list (specialization for string value)
template <typename Key> void copyTo(HashMap<Key, String>& dst, std::initializer_list<std::pair<const Key, std::string>> list)
{
typedef HashKeyValueAdapterGeneric<std::pair<const Key, std::string>> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<Key, String>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, list.begin(), list.end(), list.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
dstElem.first = srcElem.first;
blobBuilder->copyTo(dstElem.second, srcElem.second);
});
}
// copyTo hash map from std::initializer_list (specialization for string key)
void copyTo(HashMap<String, String>& dst, std::initializer_list<std::pair<const std::string, std::string>> list)
{
typedef HashKeyValueAdapterStdString<std::string> SrcItemAdapter;
typedef HashKeyValueAdapterGeneric<Pair<String, String>> DstItemAdapter;
copyToHash<SrcItemAdapter, DstItemAdapter>(
dst, list.begin(), list.end(), list.size(),
[](BlobBuilder* blobBuilder, offset_t dstAbsoluteOffset, const typename SrcItemAdapter::ItemType& srcElem) {
typename DstItemAdapter::ItemType& dstElem =
blobBuilder->getDirectMemoryAccess<typename DstItemAdapter::ItemType>(dstAbsoluteOffset);
blobBuilder->copyTo(dstElem.first, srcElem.first);
blobBuilder->copyTo(dstElem.second, srcElem.second);
});
}
// copyTo string from const char* and size
void copyTo(String& _dst, const char* src, size_t len)
{
ZMEYA_ASSERT(src != nullptr && len > 0);
BlobPtr<String> dst(getBlobPtr(&_dst));
BlobPtr<char> stringData = allocate<char>(src[0]);
if (len > 0)
{
for (size_t i = 1; i < len; i++)
{
allocate<char>(src[i]);
}
allocate<char>('\0');
}
assignTo(dst->data, stringData);
}
// copyTo string from std::string
void copyTo(String& dst, const std::string& src) { copyTo(dst, src.c_str(), src.size()); }
// copyTo string from null teminated c-string
void copyTo(String& _dst, const char* src)
{
ZMEYA_ASSERT(src != nullptr);
size_t len = std::strlen(src);
copyTo(_dst, src, len);
}
// referTo another String (it is not a copy, the destination string will refer to the same data)
void referTo(String& dst, const String& src)
{
BlobPtr<char> stringData = getBlobPtr(src.c_str());
assignTo(dst.data, stringData);
}
// referTo another Array (it is not a copy, the destination string will refer to the same data)
template <typename T> void referTo(Array<T>& _dst, const Array<T>& src)
{
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
BlobPtr<T> arrData = getBlobPtr(src.data());
dst->numElements = uint32_t(src.size());
setArrayOffset(dst, arrData.getAbsoluteOffset());
}
// referTo another HashSet (it is not a copy, the destination string will refer to the same data)
template <typename Key> void referTo(HashSet<Key>& dst, const HashSet<Key>& src)
{
referTo(dst.buckets, src.buckets);
referTo(dst.items, src.items);
}
// referTo another HashMap (it is not a copy, the destination string will refer to the same data)
template <typename Key, typename Value> void referTo(HashMap<Key, Value>& dst, const HashMap<Key, Value>& src)
{
referTo(dst.buckets, src.buckets);
referTo(dst.items, src.items);
}
Span<char> finalize(size_t desiredSizeShouldBeMultipleOf = 4)
{
size_t numPaddingBytes = desiredSizeShouldBeMultipleOf - (data.size() % desiredSizeShouldBeMultipleOf);
allocate(numPaddingBytes, 1);
ZMEYA_ASSERT((data.size() % desiredSizeShouldBeMultipleOf) == 0);
return Span<char>(data.data(), data.size());
}
ZMEYA_NODISCARD static std::shared_ptr<BlobBuilder> create(size_t initialSizeInBytes = 2048)
{
return std::make_shared<BlobBuilder>(initialSizeInBytes, PrivateToken{});
}
template <typename T> friend class BlobPtr;
};
template <typename T> ZMEYA_NODISCARD T* BlobPtr<T>::get() const
{
std::shared_ptr<const BlobBuilder> p = blob.lock();
if (!p)
{
return nullptr;
}
return reinterpret_cast<T*>(const_cast<char*>(p->get(absoluteOffset)));
}
template <typename T> Pointer<T>& Pointer<T>::operator=(const BlobPtr<T>& other)
{
Pointer<T>& self = *this;
std::shared_ptr<const BlobBuilder> p = other.blob.lock();
BlobBuilder* blobBuilder = const_cast<BlobBuilder*>(p.get());
if (!blobBuilder)
{
BlobBuilder::assignTo(self, nullptr);
}
else
{
blobBuilder->assignTo(self, other);
}
return self;
}
#endif
} // namespace zm
namespace std
{
template <> struct hash<zm::String>
{
size_t operator()(zm::String const& s) const noexcept
{
const char* str = s.c_str();
return zm::AppInterop::hashString(str);
}
};
} // namespace std
| 36.594828 | 138 | 0.654083 |
85f35e09b7a59a1fd368b2fdfcc7277a60b5cf82 | 1,156 | c | C | src/qemu/src-pmp/tests/virtio-serial-test.c | pmp-tool/PMP | ef5e05fb4612bb622a9e1039f772c6234b87df7d | [
"MIT"
] | 8 | 2020-09-06T12:49:00.000Z | 2022-03-09T04:02:06.000Z | src/qemu/src-pmp/tests/virtio-serial-test.c | newthis/PMP | ef5e05fb4612bb622a9e1039f772c6234b87df7d | [
"MIT"
] | null | null | null | src/qemu/src-pmp/tests/virtio-serial-test.c | newthis/PMP | ef5e05fb4612bb622a9e1039f772c6234b87df7d | [
"MIT"
] | 7 | 2020-09-08T15:14:34.000Z | 2021-06-24T18:03:49.000Z | /*
* QTest testcase for VirtIO Serial
*
* Copyright (c) 2014 SUSE LINUX Products GmbH
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#include "qemu/osdep.h"
#include "libqtest.h"
#include "libqos/virtio-serial.h"
/* Tests only initialization so far. TODO: Replace with functional tests */
static void virtio_serial_nop(void *obj, void *data, QGuestAllocator *alloc)
{
/* no operation */
}
static void serial_hotplug(void *obj, void *data, QGuestAllocator *alloc)
{
qtest_qmp_device_add("virtserialport", "hp-port", "{}");
qtest_qmp_device_del("hp-port");
}
static void register_virtio_serial_test(void)
{
QOSGraphTestOptions opts = { };
opts.edge.before_cmd_line = "-device virtconsole,bus=vser0.0";
qos_add_test("console-nop", "virtio-serial", virtio_serial_nop, &opts);
opts.edge.before_cmd_line = "-device virtserialport,bus=vser0.0";
qos_add_test("serialport-nop", "virtio-serial", virtio_serial_nop, &opts);
qos_add_test("hotplug", "virtio-serial", serial_hotplug, NULL);
}
libqos_init(register_virtio_serial_test);
| 29.641026 | 78 | 0.725779 |
89bca97b7adc23e23a89d0afa2478e93a312905b | 80 | dart | Dart | lib/qr_scanner.dart | rajveermalviya/qr_scanner_flutter | 160aa81f7a236b95fb3ad95c6c4729977c333e51 | [
"Apache-2.0"
] | 3 | 2021-09-01T17:53:46.000Z | 2022-01-28T10:18:24.000Z | lib/qr_scanner.dart | rajveermalviya/qr_scanner_flutter | 160aa81f7a236b95fb3ad95c6c4729977c333e51 | [
"Apache-2.0"
] | null | null | null | lib/qr_scanner.dart | rajveermalviya/qr_scanner_flutter | 160aa81f7a236b95fb3ad95c6c4729977c333e51 | [
"Apache-2.0"
] | null | null | null | export 'src/qr_scanner_controller.dart';
export 'src/qr_scanner_preview.dart';
| 20 | 40 | 0.8125 |
cfeb97742a575097c51598bd82f455d942b7420f | 11,486 | dart | Dart | packages/flutter/test/material/circle_avatar_test.dart | devansh12b2/flutter | ba01ec8faae9a9be3cd90ee2b7357a803b7a7178 | [
"BSD-3-Clause"
] | 13 | 2021-09-30T10:31:12.000Z | 2022-03-23T06:20:21.000Z | packages/flutter/test/material/circle_avatar_test.dart | devansh12b2/flutter | ba01ec8faae9a9be3cd90ee2b7357a803b7a7178 | [
"BSD-3-Clause"
] | 31 | 2020-08-18T13:19:33.000Z | 2022-03-31T07:35:08.000Z | packages/flutter/test/material/circle_avatar_test.dart | Cruising0904/flutter | 5f105a6ca7a5ac7b8bc9b241f4c2d86f4188cf5c | [
"BSD-3-Clause"
] | 6 | 2020-07-29T15:15:17.000Z | 2021-01-01T05:31:09.000Z | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../image_data.dart';
import '../painting/mocks_for_image_cache.dart';
void main() {
testWidgets('CircleAvatar with dark background color', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
radius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
testWidgets('CircleAvatar with light background color', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade100;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
radius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorDark));
});
testWidgets('CircleAvatar with image background', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundImage: MemoryImage(Uint8List.fromList(kTransparentImage)),
radius: 50.0,
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.image!.fit, equals(BoxFit.cover));
});
testWidgets('CircleAvatar with image foreground', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
child: CircleAvatar(
foregroundImage: MemoryImage(Uint8List.fromList(kBlueRectPng)),
radius: 50.0,
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.image!.fit, equals(BoxFit.cover));
});
testWidgets('CircleAvatar backgroundImage is used as a fallback for foregroundImage', (WidgetTester tester) async {
final ErrorImageProvider errorImage = ErrorImageProvider();
bool caughtForegroundImageError = false;
await tester.pumpWidget(
wrap(
child: RepaintBoundary(
child: CircleAvatar(
foregroundImage: errorImage,
backgroundImage: MemoryImage(Uint8List.fromList(kBlueRectPng)),
radius: 50.0,
onForegroundImageError: (_,__) => caughtForegroundImageError = true,
),
),
),
);
expect(caughtForegroundImageError, true);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.image!.fit, equals(BoxFit.cover));
await expectLater(
find.byType(CircleAvatar),
matchesGoldenFile('circle_avatar.fallback.png'),
);
});
testWidgets('CircleAvatar with foreground color', (WidgetTester tester) async {
final Color foregroundColor = Colors.red.shade100;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
foregroundColor: foregroundColor,
child: const Text('Z'),
),
),
);
final ThemeData fallback = ThemeData.fallback();
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(40.0, 40.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(fallback.primaryColorDark));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(foregroundColor));
});
testWidgets('CircleAvatar with light theme', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
primaryColor: Colors.grey.shade100,
primaryColorBrightness: Brightness.light,
);
await tester.pumpWidget(
wrap(
child: Theme(
data: theme,
child: const CircleAvatar(
child: Text('Z'),
),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(theme.primaryColorLight));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(theme.primaryTextTheme.headline6!.color));
});
testWidgets('CircleAvatar with dark theme', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
primaryColor: Colors.grey.shade800,
primaryColorBrightness: Brightness.dark,
);
await tester.pumpWidget(
wrap(
child: Theme(
data: theme,
child: const CircleAvatar(
child: Text('Z'),
),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(theme.primaryColorDark));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(theme.primaryTextTheme.headline6!.color));
});
testWidgets('CircleAvatar text does not expand with textScaleFactor', (WidgetTester tester) async {
final Color foregroundColor = Colors.red.shade100;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
foregroundColor: foregroundColor,
child: const Text('Z'),
),
),
);
expect(tester.getSize(find.text('Z')), equals(const Size(16.0, 16.0)));
await tester.pumpWidget(
wrap(
child: MediaQuery(
data: const MediaQueryData(
textScaleFactor: 2.0,
size: Size(111.0, 111.0),
devicePixelRatio: 1.1,
padding: EdgeInsets.all(11.0),
),
child: CircleAvatar(
child: Builder(
builder: (BuildContext context) {
final MediaQueryData data = MediaQuery.of(context);
// These should not change.
expect(data.size, equals(const Size(111.0, 111.0)));
expect(data.devicePixelRatio, equals(1.1));
expect(data.padding, equals(const EdgeInsets.all(11.0)));
// This should be overridden to 1.0.
expect(data.textScaleFactor, equals(1.0));
return const Text('Z');
},
),
),
),
),
);
expect(tester.getSize(find.text('Z')), equals(const Size(16.0, 16.0)));
});
testWidgets('CircleAvatar respects minRadius', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: UnconstrainedBox(
child: CircleAvatar(
backgroundColor: backgroundColor,
minRadius: 50.0,
child: const Text('Z'),
),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
testWidgets('CircleAvatar respects maxRadius', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
maxRadius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
testWidgets('CircleAvatar respects setting both minRadius and maxRadius', (WidgetTester tester) async {
final Color backgroundColor = Colors.blue.shade900;
await tester.pumpWidget(
wrap(
child: CircleAvatar(
backgroundColor: backgroundColor,
maxRadius: 50.0,
minRadius: 50.0,
child: const Text('Z'),
),
),
);
final RenderConstrainedBox box = tester.renderObject(find.byType(CircleAvatar));
expect(box.size, equals(const Size(100.0, 100.0)));
final RenderDecoratedBox child = box.child! as RenderDecoratedBox;
final BoxDecoration decoration = child.decoration as BoxDecoration;
expect(decoration.color, equals(backgroundColor));
final RenderParagraph paragraph = tester.renderObject(find.text('Z'));
expect(paragraph.text.style!.color, equals(ThemeData.fallback().primaryColorLight));
});
}
Widget wrap({ required Widget child }) {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: Center(child: child),
),
);
}
| 35.89375 | 117 | 0.671426 |
d9fb849406d6086e6b6e0b5ba780d399028081c2 | 867 | kt | Kotlin | src/main/kotlin/org/devmpv/telebot/service/WeatherCacheService.kt | devmpv/telebot | 1172b6531cd7708da1f872d2bd52807b64da63f8 | [
"MIT"
] | null | null | null | src/main/kotlin/org/devmpv/telebot/service/WeatherCacheService.kt | devmpv/telebot | 1172b6531cd7708da1f872d2bd52807b64da63f8 | [
"MIT"
] | null | null | null | src/main/kotlin/org/devmpv/telebot/service/WeatherCacheService.kt | devmpv/telebot | 1172b6531cd7708da1f872d2bd52807b64da63f8 | [
"MIT"
] | null | null | null | package org.devmpv.telebot.service
import mu.KotlinLogging
import org.devmpv.telebot.client.openweather.OpenWeatherClient
import org.devmpv.telebot.config.properties.CacheProperties
import org.devmpv.telebot.domain.weather.WeatherReport
import org.devmpv.telebot.utils.toWeatherReport
import org.springframework.cache.annotation.CachePut
import org.springframework.stereotype.Service
@Service
class WeatherCacheService(
private val openWeatherClient: OpenWeatherClient
) {
private val logger = KotlinLogging.logger {}
@CachePut(cacheNames = [CacheProperties.CacheName.WEATHER_CURRENT.name], key = "#city")
fun updateCurrentWeather(city: String): WeatherReport? {
val report = openWeatherClient.getOneCallResponse()?.toWeatherReport()
logger.debug { "Updating weather cache for $city. Report=$report" }
return report
}
}
| 36.125 | 91 | 0.787774 |
37eb929e64d93c06d318775df498585fb97a3891 | 1,334 | sql | SQL | src/1-Phenotype-web/ext/wgetdl/curation.sql | glasgowm148/osgenome_rccx | 08f82ddf85253f3911ca5f7ccfdc5ef6cd2b3220 | [
"MIT",
"Unlicense"
] | 8 | 2019-09-17T10:22:40.000Z | 2022-03-30T22:22:19.000Z | src/1-Phenotype-web/ext/wgetdl/curation.sql | glasgowm148/osgenome_rccx | 08f82ddf85253f3911ca5f7ccfdc5ef6cd2b3220 | [
"MIT",
"Unlicense"
] | 4 | 2021-02-02T10:36:55.000Z | 2021-11-30T13:17:52.000Z | src/1-Phenotype-web/ext/wgetdl/curation.sql | glasgowm148/osgenome_rccx | 08f82ddf85253f3911ca5f7ccfdc5ef6cd2b3220 | [
"MIT",
"Unlicense"
] | 2 | 2019-09-11T00:10:26.000Z | 2021-01-21T22:38:01.000Z | use pgvis_for_get;
DROP TABLE IF EXISTS entry_tag;
DROP TABLE IF EXISTS entry_variant;
DROP TABLE IF EXISTS save_info;
DROP TABLE IF EXISTS variant;
DROP TABLE IF EXISTS category;
DROP TABLE IF EXISTS saved_variant;
DROP TABLE IF EXISTS entry;
DROP TABLE IF EXISTS tag;
DROP TABLE IF EXISTS saved_tag;
CREATE TABLE variant (
name varchar(20) NOT NULL,
type varchar(20),
certainty varchar(20),
health_effect varchar(20),
risk int,
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
)
ENGINE = InnoDB;
CREATE TABLE category (
variant int NOT NULL,
category varchar(50)
)
ENGINE = InnoDB;
CREATE TABLE saved_variant (
user varchar(20) NOT NULL,
variant varchar(20) NOT NULL,
accordion int,
notebook int,
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
)
ENGINE = InnoDB;
CREATE TABLE entry (
id int NOT NULL AUTO_INCREMENT,
title varchar(200),
url varchar(200),
summary varchar(1000),
PRIMARY KEY (id)
)
ENGINE = InnoDB;
CREATE TABLE saved_tag (
id int NOT NULL AUTO_INCREMENT,
user varchar(20),
tag varchar(100),
notebook int,
PRIMARY KEY (id)
)
ENGINE = InnoDB;
CREATE TABLE entry_tag (
entry int,
tag int
)
ENGINE = InnoDB;
CREATE TABLE entry_variant (
entry int,
variant int
)
ENGINE = InnoDB;
CREATE TABLE save_info (
saved_variant int NOT NULL,
carrier varchar(20)
)
ENGINE = InnoDB;
| 17.786667 | 35 | 0.74063 |
428b51a920e8e2bbb0986ba6045b54449eb6b10e | 3,325 | swift | Swift | Dispatcher-SwiftUI-Core/Dispatcher-SwiftUI-Core/ Diagram Components/Thread.swift | almaleh/Dispatcher | 56a950b46d50a0a6da3bfa2535a2006414e5c7e8 | [
"MIT"
] | 77 | 2020-01-28T16:43:54.000Z | 2022-03-15T04:13:04.000Z | Dispatcher-SwiftUI-Core/Dispatcher-SwiftUI-Core/ Diagram Components/Thread.swift | almaleh/Dispatcher | 56a950b46d50a0a6da3bfa2535a2006414e5c7e8 | [
"MIT"
] | null | null | null | Dispatcher-SwiftUI-Core/Dispatcher-SwiftUI-Core/ Diagram Components/Thread.swift | almaleh/Dispatcher | 56a950b46d50a0a6da3bfa2535a2006414e5c7e8 | [
"MIT"
] | 14 | 2020-04-09T18:13:48.000Z | 2022-03-15T12:08:21.000Z | //
// Thread.swift
// Dispatcher
//
// Created by Besher on 2020-01-17.
// Copyright © 2020 Besher Al Maleh. All rights reserved.
//
import SwiftUI
struct Thread: View {
@State private var emojiOpacity: Double = 0.0
@State private var emojiScale: CGFloat = 0.5
@State private var threadLength: CGFloat = 0.0
@State private var taskOpacity = 0.0
@State private var visibleTasks = [Task]()
let topic: Topic
let type: QueueType
let tasks: [Task]
let isShadow: Bool
var body: some View {
VStack {
Text("🧵")
.font(.largeTitle)
.padding(.bottom, -10)
.opacity(emojiOpacity)
.animation(.default)
.scaleEffect(emojiScale)
.animation(
Animation.interpolatingSpring(mass: 0.5, stiffness: 35, damping: 15, initialVelocity: 20)
)
ZStack (alignment: .top) {
WavyLine(threadLength: threadLength)
.stroke(Color.yellow, lineWidth: 3)
.animation(Animation
.easeInOut(duration: 1.5)
.delay(0.5))
VStack (alignment: .center) {
ForEach(0..<visibleTasks.count, id: \.self) { idx in
self.getTask(at: idx)
.opacity(self.taskOpacity)
.onAppear {
withAnimation(.default) {
self.taskOpacity = 1.0
}
}
}
}
}
}
.padding(20)
.onAppear {
var delay = 0.0
if self.topic == .sync && self.type != .main || self.isShadow {
delay = 999
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.unrollThread()
}
// Delay before showing tasks
let taskDisplayDelay = self.topic == .async || self.topic == .concurrent ? 0.5 : 1.5
DispatchQueue.main.asyncAfter(deadline: .now() + taskDisplayDelay) {
self.visibleTasks = self.tasks
}
}
}
func getTask(at index: Int) -> AnyView {
let task = visibleTasks[index]
switch task.taskType {
case .workBlock:
return AnyView(WorkBlock(task: task))
case .statement(let type):
return AnyView(Statement(type: type, task: task))
case .shadow:
return AnyView(Statement(type: .shadow, task: task))
}
}
func unrollThread() {
self.emojiOpacity = 1.0
self.emojiScale = 1.0
self.threadLength = 0.7
}
init(topic: Topic, type: QueueType, tasks: [Task], threadID: Int, isShadow: Bool = false) {
self.topic = topic
self.type = type
self.tasks = tasks.filter { $0.threadID == threadID }
self.isShadow = isShadow
}
}
struct Thread_Previews: PreviewProvider {
static var previews: some View {
Thread(topic: .sync, type: .main, tasks: TaskGenerator.createSyncTasks(), threadID: 0)
}
}
| 31.367925 | 109 | 0.493835 |
52c4e34597a4b3707a49f0621fdf8d0f96533988 | 1,163 | asm | Assembly | playWithNumbers/primeNumber/PrimeNumberHaunting.asm | MinhasKamal/AlgorithmsImplementation | 29e45b8b19aaea9a1946fbdfa2da585c5f09b118 | [
"MIT"
] | 70 | 2016-11-21T10:28:30.000Z | 2022-03-15T08:38:10.000Z | playWithNumbers/primeNumber/PrimeNumberHaunting.asm | amitkarn/AlgorithmImplementations | 29e45b8b19aaea9a1946fbdfa2da585c5f09b118 | [
"MIT"
] | null | null | null | playWithNumbers/primeNumber/PrimeNumberHaunting.asm | amitkarn/AlgorithmImplementations | 29e45b8b19aaea9a1946fbdfa2da585c5f09b118 | [
"MIT"
] | 36 | 2016-11-28T08:07:42.000Z | 2022-03-15T08:38:13.000Z | ##Writer: Minhas Kamal
##Date: 01-MAY-2014
##Function: Finds prime numbers in a certain range.
#####**data**#####
.data
prompt: .asciiz "Enter your range: "
new_line: .asciiz "\n"
#####**text**#####
.text
main:
la $a0, prompt #prompt for user input
li $v0, 4
syscall
li $v0, 5 #take start integer
syscall
add $t1, $v0, $zero
li $t0, 2 #see if divisible by 2 or not (even or odd)
div $t4, $t1, $t0
mul $t4, $t4, $t0
bne $t4, $t1, odd
addi $t1, $t1, 1 #if even make odd
odd:
li $v0, 5 #take stop integer
syscall
add $t2, $v0, $zero
addi $t3, $t1, -2 #loop controller
loop_1:
addi $t3, $t3, 2
ble $t3, 1, loop_1 #loopback when <=1 is inputted
beq $t3, 3, isPrime #when 3 is inputted
bgt $t3, $t2, exit #when >$t2 exit
li $t0, 3 #loop controller #starts from 3 to last
div $t4, $t3, $t0
loop_2:
div $t4, $t3, $t0 #see if divisible or not
mul $t4, $t4, $t0
beq $t4, $t3, isNotPrime
addi $t0, $t0, 2 #continue the loop
blt $t0, $t4, loop_2
isPrime:
add $a0, $t3, $zero
li $v0, 1
syscall
la $a0, new_line
li $v0, 4
syscall
j loop_1
isNotPrime:
j loop_1
exit:
li $v0, 10
syscall
| 16.855072 | 57 | 0.598452 |
9c7bc8e625c2f80b023de4150e0e816c0a57f69a | 3,648 | js | JavaScript | apps/native-component-list/screens/HapticsScreen.js | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | 2 | 2019-05-23T20:39:18.000Z | 2019-05-24T14:00:32.000Z | apps/native-component-list/screens/HapticsScreen.js | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | null | null | null | apps/native-component-list/screens/HapticsScreen.js | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | null | null | null | import React from 'react';
import { SectionList, StyleSheet, Text, View } from 'react-native';
import { Haptics } from 'expo';
import Button from '../components/Button';
import Colors from '../constants/Colors';
import MonoText from '../components/MonoText';
const sections = [
{
method: Haptics.notificationAsync,
data: [
{
accessor: 'Haptics.NotificationFeedbackType.Success',
value: Haptics.NotificationFeedbackType.Success,
},
{
accessor: 'Haptics.NotificationFeedbackType.Warning',
value: Haptics.NotificationFeedbackType.Warning,
},
{
accessor: 'Haptics.NotificationFeedbackType.Error',
value: Haptics.NotificationFeedbackType.Error,
},
],
},
{
method: Haptics.impactAsync,
data: [
{
accessor: 'Haptics.ImpactFeedbackStyle.Light',
value: Haptics.ImpactFeedbackStyle.Light,
},
{
accessor: 'Haptics.ImpactFeedbackStyle.Medium',
value: Haptics.ImpactFeedbackStyle.Medium,
},
{
accessor: 'Haptics.ImpactFeedbackStyle.Heavy',
value: Haptics.ImpactFeedbackStyle.Heavy,
},
],
},
{
method: Haptics.selectionAsync,
data: [{}],
},
];
class HapticsScreen extends React.Component {
static navigationOptions = {
title: 'Haptics Feedback',
};
renderItem = ({ item, section: { method } }) => <Item method={method} type={item} />;
renderSectionHeader = ({ section: { method } }) => <Header title={method.name} />;
keyExtractor = ({ accessor, value }) => `key-${accessor}-${value}`;
render() {
return (
<View style={styles.container}>
<SectionList
style={styles.list}
sections={sections}
renderItem={this.renderItem}
renderSectionHeader={this.renderSectionHeader}
keyExtractor={this.keyExtractor}
/>
</View>
);
}
}
class Item extends React.Component {
get code() {
const {
method,
type: { accessor },
} = this.props;
return `Haptics.${method.name}(${accessor || ''})`;
}
render() {
const {
method,
type: { value },
} = this.props;
return (
<View style={styles.itemContainer}>
<HapticButton style={styles.button} method={method} type={value} />
<MonoText containerStyle={styles.itemText}>{this.code}</MonoText>
</View>
);
}
}
class Header extends React.Component {
render() {
const { title } = this.props;
return (
<View style={styles.headerContainer}>
<Text style={styles.headerText}>{title}</Text>
</View>
);
}
}
class HapticButton extends React.Component {
onPress = () => {
const { method, type } = this.props;
method(type);
};
render() {
return <Button onPress={this.onPress} style={this.props.style} title="Run" />;
}
}
const styles = StyleSheet.create({
container: {
paddingVertical: 16,
flex: 1,
backgroundColor: Colors.greyBackground,
},
list: {
flex: 1,
paddingHorizontal: 12,
},
headerContainer: {
alignItems: 'stretch',
borderBottomColor: Colors.border,
borderBottomWidth: StyleSheet.hairlineWidth,
backgroundColor: Colors.greyBackground,
},
headerText: {
color: Colors.tintColor,
paddingVertical: 4,
fontSize: 14,
fontWeight: 'bold',
},
itemContainer: {
flexDirection: 'row',
alignItems: 'center',
},
itemText: {
borderWidth: 0,
flex: 1,
marginVertical: 8,
paddingVertical: 18,
paddingLeft: 12,
},
button: {
marginRight: 16,
},
});
export default HapticsScreen;
| 22.943396 | 87 | 0.609649 |
b91431bf3406fbe8ef1a25b3bf8521601873e13a | 3,767 | sql | SQL | create.sql | plain16mtd/database | fef48a14dc0ca004a23845c497246458901a37cf | [
"Apache-2.0"
] | null | null | null | create.sql | plain16mtd/database | fef48a14dc0ca004a23845c497246458901a37cf | [
"Apache-2.0"
] | null | null | null | create.sql | plain16mtd/database | fef48a14dc0ca004a23845c497246458901a37cf | [
"Apache-2.0"
] | null | null | null | # ---------------------------------------------------------------------- #
# Script generated with: DeZign for Databases V9.1.0 #
# Target DBMS: MySQL 5 #
# Project file: Project1.dez #
# Project name: #
# Author: #
# Script type: Database creation script #
# Created on: 2015-12-16 16:26 #
# ---------------------------------------------------------------------- #
# ---------------------------------------------------------------------- #
# Add tables #
# ---------------------------------------------------------------------- #
# ---------------------------------------------------------------------- #
# Add table "Manufacturer" #
# ---------------------------------------------------------------------- #
CREATE TABLE `Manufacturer` (
`ManufacturerID` CHAR(10) NOT NULL,
`ManufacturerName` VARCHAR(40),
`ManufacturerContact` VARCHAR(40),
PRIMARY KEY (`ManufacturerID`)
);
# ---------------------------------------------------------------------- #
# Add table "ComputerType" #
# ---------------------------------------------------------------------- #
CREATE TABLE `ComputerType` (
`ComputerTypeID` CHAR(2) NOT NULL,
`TypeName` VARCHAR(40),
`TypeDescription` VARCHAR(100),
CONSTRAINT `PK_ComputerType` PRIMARY KEY (`ComputerTypeID`)
);
# ---------------------------------------------------------------------- #
# Add table "User" #
# ---------------------------------------------------------------------- #
CREATE TABLE `User` (
`UserID` CHAR(40) NOT NULL,
`UserName` VARCHAR(40),
`UserEmail` VARCHAR(40),
`UserCall` CHAR(40),
CONSTRAINT `PK_User` PRIMARY KEY (`UserID`)
);
# ---------------------------------------------------------------------- #
# Add table "Computer" #
# ---------------------------------------------------------------------- #
CREATE TABLE `Computer` (
`ComputerID` CHAR(3) NOT NULL,
`ComputerName` VARCHAR(40),
`OS` VARCHAR(40),
`ComputerTypeID` CHAR(2),
`ManufacturerID` CHAR(10),
CONSTRAINT `PK_Computer` PRIMARY KEY (`ComputerID`)
);
# ---------------------------------------------------------------------- #
# Add table "ComputerUser" #
# ---------------------------------------------------------------------- #
CREATE TABLE `ComputerUser` (
`ComputerID` CHAR(3) NOT NULL,
`UserID` CHAR(10),
CONSTRAINT `PK_ComputerUser` PRIMARY KEY (`ComputerID`)
);
# ---------------------------------------------------------------------- #
# Add foreign key constraints #
# ---------------------------------------------------------------------- #
ALTER TABLE `Computer` ADD CONSTRAINT `ComputerType_Computer`
FOREIGN KEY (`ComputerTypeID`) REFERENCES `ComputerType` (`ComputerTypeID`);
ALTER TABLE `Computer` ADD CONSTRAINT `Manufacturer_Computer`
FOREIGN KEY (`ManufacturerID`) REFERENCES `Manufacturer` (`ManufacturerID`);
ALTER TABLE `ComputerUser` ADD CONSTRAINT `User_ComputerUser`
FOREIGN KEY (`UserID`) REFERENCES `User` (`UserID`);
ALTER TABLE `ComputerUser` ADD CONSTRAINT `Computer_ComputerUser`
FOREIGN KEY (`ComputerID`) REFERENCES `Computer` (`ComputerID`);
| 42.806818 | 80 | 0.351473 |
7bca1812fec87ed1aa679f9646177c1eac2530a7 | 1,353 | css | CSS | client/src/assets/styles.css | anyrange/enis2 | 738a61b19228e791ae9b0cf45b9dba33a49282b0 | [
"MIT"
] | 5 | 2021-07-16T15:55:47.000Z | 2022-02-19T12:18:29.000Z | client/src/assets/styles.css | anyrange/enis2 | 738a61b19228e791ae9b0cf45b9dba33a49282b0 | [
"MIT"
] | null | null | null | client/src/assets/styles.css | anyrange/enis2 | 738a61b19228e791ae9b0cf45b9dba33a49282b0 | [
"MIT"
] | null | null | null | body {
@apply text-black dark:text-white antialiased;
@apply bg-gray-50 dark:bg-gray-900-spotify;
-webkit-tap-highlight-color: rgba(255, 255, 255, 0);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
overflow: overlay;
overscroll-behavior-y: none;
}
html {
--autofill-background: #eff6ff;
--autofill-color: #000000;
--scroll-picker-border-color: white;
--scroll-picker-item-color: #333;
}
html.dark {
--autofill-background: #282828;
--autofill-color: #ffffff;
--scroll-picker-border-color: #1d1d1d;
--scroll-picker-item-color: #ababab;
}
html.custom-scrollbar ::-webkit-scrollbar {
@apply w-1.5;
}
html.custom-scrollbar ::-webkit-scrollbar-thumb {
@apply bg-gray-400-spotify rounded-lg;
}
html.dark.custom-scrollbar ::-webkit-scrollbar-thumb {
@apply bg-gray-600-spotify rounded-lg;
}
html.modal-opened {
overflow: initial;
}
html.modal-opened body {
overflow: hidden;
touch-action: none;
-ms-touch-action: none;
position: relative;
height: 100%;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
a {
@apply default-focus rounded;
}
| 21.822581 | 81 | 0.689579 |
58ba1b4814bc3cb56ef47b62c9c0d7884df00327 | 2,122 | kt | Kotlin | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/internal/navigation/DepartEventFactory.kt | pouzadf/mapbox-navigation-android | a72b132e5339dcb7f7298b1970748678e5b18838 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1 | 2019-11-26T01:58:28.000Z | 2019-11-26T01:58:28.000Z | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/internal/navigation/DepartEventFactory.kt | pouzadf/mapbox-navigation-android | a72b132e5339dcb7f7298b1970748678e5b18838 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/internal/navigation/DepartEventFactory.kt | pouzadf/mapbox-navigation-android | a72b132e5339dcb7f7298b1970748678e5b18838 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | package com.mapbox.services.android.navigation.v5.internal.navigation
import com.mapbox.services.android.navigation.v5.internal.location.MetricsLocation
import com.mapbox.services.android.navigation.v5.internal.navigation.metrics.SessionState
import com.mapbox.services.android.navigation.v5.internal.navigation.routeprogress.MetricsRouteProgress
import java.util.Date
internal class DepartEventFactory(private val departEventHandler: DepartEventHandler) {
companion object {
private const val INITIAL_LEG_INDEX = -1
}
private var currentLegIndex = INITIAL_LEG_INDEX
fun send(
sessionState: SessionState,
routeProgress: MetricsRouteProgress,
location: MetricsLocation
): SessionState {
val checkedSessionState = checkResetForNewLeg(sessionState, routeProgress)
this.currentLegIndex = routeProgress.legIndex
return if (isValidDeparture(checkedSessionState, routeProgress)) {
sendToHandler(checkedSessionState, routeProgress, location)
} else {
checkedSessionState
}
}
fun reset() {
currentLegIndex = INITIAL_LEG_INDEX
}
private fun checkResetForNewLeg(
sessionState: SessionState,
routeProgress: MetricsRouteProgress
): SessionState {
if (shouldResetDepartureDate(routeProgress)) {
sessionState.startTimestamp = null
}
return sessionState
}
private fun shouldResetDepartureDate(routeProgress: MetricsRouteProgress): Boolean =
currentLegIndex != routeProgress.legIndex
private fun isValidDeparture(
sessionState: SessionState,
routeProgress: MetricsRouteProgress
): Boolean =
sessionState.startTimestamp == null && routeProgress.distanceTraveled > 0
private fun sendToHandler(
sessionState: SessionState,
routeProgress: MetricsRouteProgress,
location: MetricsLocation
): SessionState {
sessionState.startTimestamp = Date()
departEventHandler.send(sessionState, routeProgress, location)
return sessionState
}
}
| 33.68254 | 103 | 0.721489 |
7f727a6b2c0d63d63d974aa8c47df251961e4bf4 | 250 | swift | Swift | UIWindow+Ex.swift | JemesL/SaePlayer | a4433d0d42d5a1b5d0448728d85433a59f1a1835 | [
"MIT"
] | null | null | null | UIWindow+Ex.swift | JemesL/SaePlayer | a4433d0d42d5a1b5d0448728d85433a59f1a1835 | [
"MIT"
] | null | null | null | UIWindow+Ex.swift | JemesL/SaePlayer | a4433d0d42d5a1b5d0448728d85433a59f1a1835 | [
"MIT"
] | null | null | null | //
// UIWindow+Ex.swift
// SaePlayer
//
// Created by Jemesl on 2020/7/9.
//
import Foundation
extension UIWindow {
static func getKeyWindow() -> UIWindow? {
return UIApplication.shared.windows.filter({ $0.isKeyWindow }).last
}
}
| 17.857143 | 75 | 0.656 |
b8e9e6b09dfc5f1fd53b9095ee4626e47f4baa73 | 1,257 | swift | Swift | UdacityMentorDashboard/Models/Project.swift | dnKaratzas/udacity-mentor-dashboard | 1eda6f69faaa6c577c72487d3f3af0e10b6b17d6 | [
"Apache-2.0"
] | 8 | 2018-07-12T19:42:42.000Z | 2020-08-03T02:37:49.000Z | UdacityMentorDashboard/Models/Project.swift | dnKaratzas/udacity-mentor-dashboard | 1eda6f69faaa6c577c72487d3f3af0e10b6b17d6 | [
"Apache-2.0"
] | null | null | null | UdacityMentorDashboard/Models/Project.swift | dnKaratzas/udacity-mentor-dashboard | 1eda6f69faaa6c577c72487d3f3af0e10b6b17d6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Dionysios Karatzas
*
* 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 Foundation
final class Project: NSObject, Codable {
private let _id: Int?
private let _name: String?
enum CodingKeys: String, CodingKey {
case _id = "id"
case _name = "name"
}
init(id: Int?, name: String?) {
self._id = id
self._name = name
super.init()
}
// MARK: Getters
@objc dynamic var id: String {
if let value = _id {
return String(value)
} else {
return ""
}
}
@objc dynamic var name: String {
if let value = _name {
return value
} else {
return ""
}
}
}
| 24.647059 | 75 | 0.608592 |
e600688c92bb3eb85d20588588415f8b3531ad2b | 631 | go | Go | message/bundle.go | tribalwarshelp/dcbot | 38d24b59beec3e8da100b0dad789350f1e90e3c2 | [
"MIT"
] | 1 | 2021-01-25T23:16:57.000Z | 2021-01-25T23:16:57.000Z | message/bundle.go | tribalwarshelp/dcbot | 38d24b59beec3e8da100b0dad789350f1e90e3c2 | [
"MIT"
] | 3 | 2021-07-06T07:06:44.000Z | 2021-08-30T08:21:01.000Z | message/bundle.go | tribalwarshelp/dcbot | 38d24b59beec3e8da100b0dad789350f1e90e3c2 | [
"MIT"
] | null | null | null | package message
import (
"os"
"path/filepath"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
var lang = language.English
var bundle = i18n.NewBundle(lang)
func GetDefaultLanguage() language.Tag {
return lang
}
func NewLocalizer(l ...string) *i18n.Localizer {
return i18n.NewLocalizer(bundle, append(l, lang.String())...)
}
func LanguageTags() []language.Tag {
return bundle.LanguageTags()
}
func LoadMessages(root string) error {
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if path != root {
bundle.MustLoadMessageFile(path)
}
return nil
})
}
| 18.028571 | 82 | 0.716323 |
f4c03e3cd89113551411fe45f9cbdf3638c6711e | 4,190 | go | Go | modules/hbs/cache/agents.go | bbaobelief/falcon-plus | d149b70307a9b9677adbe26e282aa4ce4a31170f | [
"Apache-2.0"
] | 37 | 2020-04-22T08:52:44.000Z | 2022-01-09T02:48:03.000Z | modules/hbs/cache/agents.go | bbaobelief/falcon-plus | d149b70307a9b9677adbe26e282aa4ce4a31170f | [
"Apache-2.0"
] | 4 | 2020-04-23T03:23:40.000Z | 2020-04-23T04:56:38.000Z | modules/hbs/cache/agents.go | bbaobelief/falcon-plus | d149b70307a9b9677adbe26e282aa4ce4a31170f | [
"Apache-2.0"
] | 7 | 2020-04-23T03:52:26.000Z | 2021-11-22T06:51:51.000Z | // Copyright 2017 Xiaomi, 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.
package cache
// 每个agent心跳上来的时候立马更新一下数据库是没必要的
// 缓存起来,每隔一个小时写一次DB
// 提供http接口查询机器信息,排查重名机器的时候比较有用
import (
"log"
"sync"
"time"
"github.com/open-falcon/falcon-plus/common/model"
"github.com/open-falcon/falcon-plus/modules/hbs/db"
"github.com/open-falcon/falcon-plus/modules/hbs/g"
)
type SafeAgents struct {
sync.RWMutex
M map[string]*model.AgentUpdateInfo
}
var Agents = NewSafeAgents()
var NewAgentUpgradeArgs = &model.AgentUpgradeArgs{WgetUrl: "", Version: ""}
//var UpgradeAgentMap = NewUpgradeAgents()
var NowAgentVersionMap = sync.Map{}
type UpgradeAgent struct {
Timestamp int64 `json:"timestamp"`
LastVersion string `json:"lastversion"`
ThisVersion string `json:"thisversion"`
}
type UpgradeAgents struct {
Map sync.Map
}
func NewUpgradeAgents() *UpgradeAgents {
return &UpgradeAgents{Map: sync.Map{}}
}
func NewSafeAgents() *SafeAgents {
return &SafeAgents{M: make(map[string]*model.AgentUpdateInfo)}
}
func (this *SafeAgents) Put(req *model.AgentReportRequest) {
val := &model.AgentUpdateInfo{
LastUpdate: time.Now().Unix(),
ReportRequest: req,
}
agentInfo, exists := this.Get(req.Hostname)
//log.Println("is_exists",exists)
if !exists {
//log.Println("cache_miss",req.Hostname,req.IP)
// 不存在更新db
go db.UpdateAgentNew(val)
} else {
//存在但是信息不同:只打印下信息不更新了
if agentInfo.ReportRequest.IP != req.IP || agentInfo.ReportRequest.AgentVersion != req.AgentVersion {
log.Printf("cache_hit_but_updb:%v %v %v %v %v %v %v %v",
agentInfo.ReportRequest.Hostname,
req.Hostname,
agentInfo.ReportRequest.IP,
req.IP,
agentInfo.ReportRequest.AgentVersion,
req.AgentVersion,
agentInfo.ReportRequest.PluginVersion,
req.PluginVersion)
}
}
this.Lock()
this.M[req.Hostname] = val
defer this.Unlock()
}
func (this *SafeAgents) Get(hostname string) (*model.AgentUpdateInfo, bool) {
this.RLock()
defer this.RUnlock()
val, exists := this.M[hostname]
return val, exists
}
func (this *SafeAgents) Delete(hostname string) {
this.Lock()
defer this.Unlock()
delete(this.M, hostname)
}
func (this *SafeAgents) Keys() []string {
this.RLock()
defer this.RUnlock()
count := len(this.M)
keys := make([]string, count)
i := 0
for hostname := range this.M {
keys[i] = hostname
i++
}
return keys
}
func (this *SafeAgents) AgentVersions() map[string]string {
this.RLock()
defer this.RUnlock()
maps := make(map[string]string)
i := 0
for hostname := range this.M {
value, _ := this.Get(hostname)
maps[hostname] = value.ReportRequest.AgentVersion
i++
}
return maps
}
func (this *SafeAgents) AgentVersionsNew() map[string]string {
this.RLock()
defer this.RUnlock()
maps := make(map[string]string)
i := 0
for hostname := range this.M {
value, _ := this.Get(hostname)
maps[hostname] = value.ReportRequest.AgentVersion
i++
}
return maps
}
func DeleteStaleAgents() {
duration := time.Minute * 15 * time.Duration(g.Config().MapCleanInterval)
for {
time.Sleep(duration)
deleteStaleAgents()
}
}
func deleteStaleAgents() {
// 一天都没有心跳的Agent,从内存中干掉
before := time.Now().Unix() - 60*10*g.Config().MapCleanInterval
keys := Agents.Keys()
count := len(keys)
if count == 0 {
return
}
for i := 0; i < count; i++ {
curr, _ := Agents.Get(keys[i])
if curr.LastUpdate < before {
NowAgentVersionMap.Delete(curr.ReportRequest.Hostname)
Agents.Delete(curr.ReportRequest.Hostname)
}
}
}
func (this *UpgradeAgents) UpgradeAgentKeys() (len int, keys []string) {
f := func(k, v interface{}) bool {
len++
keys = append(keys, k.(string))
return true
}
this.Map.Range(f)
return
}
| 23.021978 | 103 | 0.704296 |
d2ad9512d851e7f922b9a8d432684fd36ded0723 | 2,506 | php | PHP | resources/views/dashboard.blade.php | tnaffh/iob | fa305af0b093e789e56b748c77a4c820f65c9c90 | [
"MIT"
] | null | null | null | resources/views/dashboard.blade.php | tnaffh/iob | fa305af0b093e789e56b748c77a4c820f65c9c90 | [
"MIT"
] | null | null | null | resources/views/dashboard.blade.php | tnaffh/iob | fa305af0b093e789e56b748c77a4c820f65c9c90 | [
"MIT"
] | null | null | null | @extends('layouts.app')
@section('content')
<div class="container">
<div class="row profile">
<div class="col-md-3">
<div class="profile-sidebar">
<!-- SIDEBAR USERPIC -->
<div class="profile-userpic">
<img src="https://api.adorable.io/avatars/285/{{ Auth::user()->email }}.png" class="img-responsive" alt="">
</div>
<!-- END SIDEBAR USERPIC -->
<!-- SIDEBAR USER TITLE -->
<div class="profile-usertitle">
<div class="profile-usertitle-name">
{{ Auth::user()->name }}
</div>
<div class="profile-usertitle-job">
{{ Auth::user()->role }}
</div>
</div>
<!-- END SIDEBAR USER TITLE -->
<!-- SIDEBAR BUTTONS -->
<div class="profile-userbuttons">
<button type="button" class="btn btn-danger btn-sm">Update profile</button>
</div>
<!-- END SIDEBAR BUTTONS -->
<!-- SIDEBAR MENU -->
<div class="profile-usermenu">
<ul class="nav">
<li class="{{ 'tabs.index' === Route::currentRouteName() ? 'active' : '' }}">
<a href="{{ route('tabs.index') }}">
<i class="glyphicon glyphicon-home"></i>
Overview </a>
</li>
<li class="{{ 'tabs.courses' === Route::currentRouteName() ? 'active' : '' }}">
<a href="{{ route('tabs.courses') }}">
<i class="glyphicon glyphicon-list"></i>
Courses </a>
</li>
<li class="{{ 'tabs.exams' === Route::currentRouteName() ? 'active' : '' }}">
<a href="{{ route('tabs.exams') }}">
<i class="glyphicon glyphicon-pencil"></i>
Exams </a>
</li>
</ul>
</div>
<!-- END MENU -->
</div>
</div>
<div class="col-md-9">
<div class="">
@include( Route::currentRouteName())
</div>
</div>
</div>
</div>
@endsection
| 39.777778 | 127 | 0.373105 |
928262739262ed5749ac1e36bbc045c87a4a8580 | 954 | h | C | stingray_sdk/plugin_foundation/color.h | stefanseibert/interactive-ml | c9af95678264c9da9b6041b96be0a474d724aae0 | [
"Apache-2.0"
] | 1 | 2018-02-19T22:15:05.000Z | 2018-02-19T22:15:05.000Z | stingray_sdk/plugin_foundation/color.h | stefanseibert/interactive-ml | c9af95678264c9da9b6041b96be0a474d724aae0 | [
"Apache-2.0"
] | null | null | null | stingray_sdk/plugin_foundation/color.h | stefanseibert/interactive-ml | c9af95678264c9da9b6041b96be0a474d724aae0 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "platform.h"
#include "math.h"
namespace stingray_plugin_foundation {
typedef unsigned int Color8;
__forceinline Color8 color8(unsigned char a, unsigned char r, unsigned char g, unsigned char b)
{
return (a << 24) | (r << 16) | (g << 8) | b;
}
__forceinline unsigned char alpha(Color8 c) {return (c >> 24) & 0xff;}
__forceinline unsigned char red(Color8 c) {return (c >> 16) & 0xff;}
__forceinline unsigned char green(Color8 c) {return (c >> 8) & 0xff;}
__forceinline unsigned char blue(Color8 c) {return (c >> 0) & 0xff;}
__forceinline void set_alpha(Color8& c, unsigned char a) { c &= 0x00ffffff; c |= (a << 24); }
template<>
__forceinline Color8 lerp(const Color8& a, const Color8& b, float t) {
return color8(
lerp(alpha(a), alpha(b), t),
lerp(red(a), red(b), t),
lerp(blue(a), blue(b), t),
lerp(green(a), green(b), t));
}
struct Color32 {
float r, g, b, a;
};
} // namespace stingray_plugin_foundation
| 26.5 | 96 | 0.667715 |
0ecdab71b4325a78814cb94e8715db242a58794d | 1,734 | ts | TypeScript | src/useLocalStorage/useLocalStorage.ts | kaansey/react-localstorage-hook | 1124cbdd027ff29460226ccc0d0ebfcbae1da163 | [
"MIT"
] | 2 | 2020-11-16T07:20:09.000Z | 2020-11-17T00:49:05.000Z | src/useLocalStorage/useLocalStorage.ts | kaansey/react-localstorage-hook | 1124cbdd027ff29460226ccc0d0ebfcbae1da163 | [
"MIT"
] | 1 | 2020-10-02T13:55:57.000Z | 2020-10-02T13:55:57.000Z | src/useLocalStorage/useLocalStorage.ts | kaansey/react-localstorage-hook | 1124cbdd027ff29460226ccc0d0ebfcbae1da163 | [
"MIT"
] | null | null | null | import { useState, useLayoutEffect, useCallback } from 'react'
const localStorageHook = (key: string, defaultValue: any) => {
const [value, setValue] = useState(() => {
const storageValue = localStorage.getItem(key)
return storageValue === null ? defaultValue : JSON.parse(storageValue)
})
const updateValue = useCallback(
newValue => {
setValue(() => {
localStorage.setItem(key, JSON.stringify(newValue))
return newValue
})
},
[key]
)
useLayoutEffect(() => {
const onStorage = (event: any) => {
if (event.storageArea === localStorage && event.key === key) {
setValue(
event.newValue === null ? defaultValue : JSON.parse(event.newValue)
)
}
}
window.addEventListener('storage', onStorage)
return () => window.removeEventListener('storage', onStorage)
})
return [value, updateValue]
}
const createLocalStorageHook = (key: string, defaultValue: any) => {
const updates: Array<any> = []
return () => {
const [value, setValue] = localStorageHook(key, defaultValue)
const updateValue = useCallback(newValue => {
for (const update of updates) {
update(newValue)
}
}, [])
useLayoutEffect(() => {
updates.push(setValue)
return () => {
updates.splice(updates.indexOf(setValue), 1)
}
}, [setValue])
return [value, updateValue]
}
}
const hookInstances: Record<string, any> = {}
const useLocalStorage = (key: string, defaultValue: any = '') => {
if (key in hookInstances) {
return hookInstances[key]()
}
hookInstances[key] = createLocalStorageHook(key, defaultValue)
return hookInstances[key]()
}
export default useLocalStorage
| 24.771429 | 77 | 0.626874 |
ad97e06fc3e8943eb8f85ef946e4be3619a8d0b8 | 12,242 | rs | Rust | cranelift/codegen/src/legalizer/mod.rs | 1Crazymoney/wasmtime | 76afcab0c2bc9568b01a9aff09b90cb1641e9674 | [
"Apache-2.0"
] | 2 | 2021-10-02T02:57:57.000Z | 2021-10-02T14:26:24.000Z | cranelift/codegen/src/legalizer/mod.rs | 1Crazymoney/wasmtime | 76afcab0c2bc9568b01a9aff09b90cb1641e9674 | [
"Apache-2.0"
] | null | null | null | cranelift/codegen/src/legalizer/mod.rs | 1Crazymoney/wasmtime | 76afcab0c2bc9568b01a9aff09b90cb1641e9674 | [
"Apache-2.0"
] | null | null | null | //! Legalize instructions.
//!
//! A legal instruction is one that can be mapped directly to a machine code instruction for the
//! target ISA. The `legalize_function()` function takes as input any function and transforms it
//! into an equivalent function using only legal instructions.
//!
//! The characteristics of legal instructions depend on the target ISA, so any given instruction
//! can be legal for one ISA and illegal for another.
//!
//! Besides transforming instructions, the legalizer also fills out the `function.encodings` map
//! which provides a legal encoding recipe for every instruction.
//!
//! The legalizer does not deal with register allocation constraints. These constraints are derived
//! from the encoding recipes, and solved later by the register allocator.
use crate::cursor::{Cursor, FuncCursor};
use crate::flowgraph::ControlFlowGraph;
use crate::ir::types::I32;
use crate::ir::{self, InstBuilder, MemFlags};
use crate::isa::TargetIsa;
mod globalvalue;
mod heap;
mod table;
use self::globalvalue::expand_global_value;
use self::heap::expand_heap_addr;
use self::table::expand_table_addr;
/// Perform a simple legalization by expansion of the function, without
/// platform-specific transforms.
pub fn simple_legalize(func: &mut ir::Function, cfg: &mut ControlFlowGraph, isa: &dyn TargetIsa) {
macro_rules! expand_imm_op {
($pos:ident, $inst:ident: $from:ident => $to:ident) => {{
let (arg, imm) = match $pos.func.dfg[$inst] {
ir::InstructionData::BinaryImm64 {
opcode: _,
arg,
imm,
} => (arg, imm),
_ => panic!(
concat!("Expected ", stringify!($from), ": {}"),
$pos.func.dfg.display_inst($inst, None)
),
};
let ty = $pos.func.dfg.value_type(arg);
let imm = $pos.ins().iconst(ty, imm);
$pos.func.dfg.replace($inst).$to(arg, imm);
}};
($pos:ident, $inst:ident<$ty:ident>: $from:ident => $to:ident) => {{
let (arg, imm) = match $pos.func.dfg[$inst] {
ir::InstructionData::BinaryImm64 {
opcode: _,
arg,
imm,
} => (arg, imm),
_ => panic!(
concat!("Expected ", stringify!($from), ": {}"),
$pos.func.dfg.display_inst($inst, None)
),
};
let imm = $pos.ins().iconst($ty, imm);
$pos.func.dfg.replace($inst).$to(arg, imm);
}};
}
let mut pos = FuncCursor::new(func);
let func_begin = pos.position();
pos.set_position(func_begin);
while let Some(_block) = pos.next_block() {
let mut prev_pos = pos.position();
while let Some(inst) = pos.next_inst() {
match pos.func.dfg[inst].opcode() {
// control flow
ir::Opcode::BrIcmp => expand_br_icmp(inst, &mut pos.func, cfg, isa),
ir::Opcode::Trapnz | ir::Opcode::Trapz | ir::Opcode::ResumableTrapnz => {
expand_cond_trap(inst, &mut pos.func, cfg, isa);
}
// memory and constants
ir::Opcode::GlobalValue => expand_global_value(inst, &mut pos.func, cfg, isa),
ir::Opcode::HeapAddr => expand_heap_addr(inst, &mut pos.func, cfg, isa),
ir::Opcode::StackLoad => expand_stack_load(inst, &mut pos.func, cfg, isa),
ir::Opcode::StackStore => expand_stack_store(inst, &mut pos.func, cfg, isa),
ir::Opcode::TableAddr => expand_table_addr(inst, &mut pos.func, cfg, isa),
// bitops
ir::Opcode::BandImm => expand_imm_op!(pos, inst: band_imm => band),
ir::Opcode::BorImm => expand_imm_op!(pos, inst: bor_imm => bor),
ir::Opcode::BxorImm => expand_imm_op!(pos, inst: bxor_imm => bxor),
ir::Opcode::IaddImm => expand_imm_op!(pos, inst: iadd_imm => iadd),
// bitshifting
ir::Opcode::IshlImm => expand_imm_op!(pos, inst<I32>: ishl_imm => ishl),
ir::Opcode::RotlImm => expand_imm_op!(pos, inst<I32>: rotl_imm => rotl),
ir::Opcode::RotrImm => expand_imm_op!(pos, inst<I32>: rotr_imm => rotr),
ir::Opcode::SshrImm => expand_imm_op!(pos, inst<I32>: sshr_imm => sshr),
ir::Opcode::UshrImm => expand_imm_op!(pos, inst<I32>: ushr_imm => ushr),
// math
ir::Opcode::IrsubImm => {
let (arg, imm) = match pos.func.dfg[inst] {
ir::InstructionData::BinaryImm64 {
opcode: _,
arg,
imm,
} => (arg, imm),
_ => panic!(
"Expected irsub_imm: {}",
pos.func.dfg.display_inst(inst, None)
),
};
let ty = pos.func.dfg.value_type(arg);
let imm = pos.ins().iconst(ty, imm);
pos.func.dfg.replace(inst).isub(imm, arg); // note: arg order reversed
}
ir::Opcode::ImulImm => expand_imm_op!(pos, inst: imul_imm => imul),
ir::Opcode::SdivImm => expand_imm_op!(pos, inst: sdiv_imm => sdiv),
ir::Opcode::SremImm => expand_imm_op!(pos, inst: srem_imm => srem),
ir::Opcode::UdivImm => expand_imm_op!(pos, inst: udiv_imm => udiv),
ir::Opcode::UremImm => expand_imm_op!(pos, inst: urem_imm => urem),
// comparisons
ir::Opcode::IfcmpImm => expand_imm_op!(pos, inst: ifcmp_imm => ifcmp),
ir::Opcode::IcmpImm => {
let (cc, x, y) = match pos.func.dfg[inst] {
ir::InstructionData::IntCompareImm {
opcode: _,
cond,
arg,
imm,
} => (cond, arg, imm),
_ => panic!(
"Expected ircmp_imm: {}",
pos.func.dfg.display_inst(inst, None)
),
};
let ty = pos.func.dfg.value_type(x);
let y = pos.ins().iconst(ty, y);
pos.func.dfg.replace(inst).icmp(cc, x, y);
}
_ => {
prev_pos = pos.position();
continue;
}
};
// Legalization implementations require fixpoint loop here.
// TODO: fix this.
pos.set_position(prev_pos);
}
}
}
/// Custom expansion for conditional trap instructions.
/// TODO: Add CFG support to the Rust DSL patterns so we won't have to do this.
fn expand_cond_trap(
inst: ir::Inst,
func: &mut ir::Function,
cfg: &mut ControlFlowGraph,
_isa: &dyn TargetIsa,
) {
// Parse the instruction.
let trapz;
let (arg, code, opcode) = match func.dfg[inst] {
ir::InstructionData::CondTrap { opcode, arg, code } => {
// We want to branch *over* an unconditional trap.
trapz = match opcode {
ir::Opcode::Trapz => true,
ir::Opcode::Trapnz | ir::Opcode::ResumableTrapnz => false,
_ => panic!("Expected cond trap: {}", func.dfg.display_inst(inst, None)),
};
(arg, code, opcode)
}
_ => panic!("Expected cond trap: {}", func.dfg.display_inst(inst, None)),
};
// Split the block after `inst`:
//
// trapnz arg
// ..
//
// Becomes:
//
// brz arg, new_block_resume
// jump new_block_trap
//
// new_block_trap:
// trap
//
// new_block_resume:
// ..
let old_block = func.layout.pp_block(inst);
let new_block_trap = func.dfg.make_block();
let new_block_resume = func.dfg.make_block();
// Replace trap instruction by the inverted condition.
if trapz {
func.dfg.replace(inst).brnz(arg, new_block_resume, &[]);
} else {
func.dfg.replace(inst).brz(arg, new_block_resume, &[]);
}
// Add jump instruction after the inverted branch.
let mut pos = FuncCursor::new(func).after_inst(inst);
pos.use_srcloc(inst);
pos.ins().jump(new_block_trap, &[]);
// Insert the new label and the unconditional trap terminator.
pos.insert_block(new_block_trap);
match opcode {
ir::Opcode::Trapz | ir::Opcode::Trapnz => {
pos.ins().trap(code);
}
ir::Opcode::ResumableTrapnz => {
pos.ins().resumable_trap(code);
pos.ins().jump(new_block_resume, &[]);
}
_ => unreachable!(),
}
// Insert the new label and resume the execution when the trap fails.
pos.insert_block(new_block_resume);
// Finally update the CFG.
cfg.recompute_block(pos.func, old_block);
cfg.recompute_block(pos.func, new_block_resume);
cfg.recompute_block(pos.func, new_block_trap);
}
fn expand_br_icmp(
inst: ir::Inst,
func: &mut ir::Function,
cfg: &mut ControlFlowGraph,
_isa: &dyn TargetIsa,
) {
let (cond, a, b, destination, block_args) = match func.dfg[inst] {
ir::InstructionData::BranchIcmp {
cond,
destination,
ref args,
..
} => (
cond,
args.get(0, &func.dfg.value_lists).unwrap(),
args.get(1, &func.dfg.value_lists).unwrap(),
destination,
args.as_slice(&func.dfg.value_lists)[2..].to_vec(),
),
_ => panic!("Expected br_icmp {}", func.dfg.display_inst(inst, None)),
};
let old_block = func.layout.pp_block(inst);
func.dfg.clear_results(inst);
let icmp_res = func.dfg.replace(inst).icmp(cond, a, b);
let mut pos = FuncCursor::new(func).after_inst(inst);
pos.use_srcloc(inst);
pos.ins().brnz(icmp_res, destination, &block_args);
cfg.recompute_block(pos.func, destination);
cfg.recompute_block(pos.func, old_block);
}
/// Expand illegal `stack_load` instructions.
fn expand_stack_load(
inst: ir::Inst,
func: &mut ir::Function,
_cfg: &mut ControlFlowGraph,
isa: &dyn TargetIsa,
) {
let ty = func.dfg.value_type(func.dfg.first_result(inst));
let addr_ty = isa.pointer_type();
let mut pos = FuncCursor::new(func).at_inst(inst);
pos.use_srcloc(inst);
let (stack_slot, offset) = match pos.func.dfg[inst] {
ir::InstructionData::StackLoad {
opcode: _opcode,
stack_slot,
offset,
} => (stack_slot, offset),
_ => panic!(
"Expected stack_load: {}",
pos.func.dfg.display_inst(inst, None)
),
};
let addr = pos.ins().stack_addr(addr_ty, stack_slot, offset);
// Stack slots are required to be accessible and aligned.
let mflags = MemFlags::trusted();
pos.func.dfg.replace(inst).load(ty, mflags, addr, 0);
}
/// Expand illegal `stack_store` instructions.
fn expand_stack_store(
inst: ir::Inst,
func: &mut ir::Function,
_cfg: &mut ControlFlowGraph,
isa: &dyn TargetIsa,
) {
let addr_ty = isa.pointer_type();
let mut pos = FuncCursor::new(func).at_inst(inst);
pos.use_srcloc(inst);
let (val, stack_slot, offset) = match pos.func.dfg[inst] {
ir::InstructionData::StackStore {
opcode: _opcode,
arg,
stack_slot,
offset,
} => (arg, stack_slot, offset),
_ => panic!(
"Expected stack_store: {}",
pos.func.dfg.display_inst(inst, None)
),
};
let addr = pos.ins().stack_addr(addr_ty, stack_slot, offset);
let mut mflags = MemFlags::new();
// Stack slots are required to be accessible and aligned.
mflags.set_notrap();
mflags.set_aligned();
pos.func.dfg.replace(inst).store(mflags, val, addr, 0);
}
| 36.762763 | 99 | 0.540516 |
398c1c53fd572f6afdaf7503179dfb351bfc1eb3 | 744 | swift | Swift | NHS-COVID-19/Core/Sources/Domain/ExposureNotification/Feature.swift | faberga/covid-19-app-ios-ag-public | ee43e47aa1c082ea0bbfb0a971327dea807e4533 | [
"MIT"
] | null | null | null | NHS-COVID-19/Core/Sources/Domain/ExposureNotification/Feature.swift | faberga/covid-19-app-ios-ag-public | ee43e47aa1c082ea0bbfb0a971327dea807e4533 | [
"MIT"
] | null | null | null | NHS-COVID-19/Core/Sources/Domain/ExposureNotification/Feature.swift | faberga/covid-19-app-ios-ag-public | ee43e47aa1c082ea0bbfb0a971327dea807e4533 | [
"MIT"
] | null | null | null | //
// Copyright © 2020 NHSX. All rights reserved.
//
import Foundation
public enum Feature: CaseIterable {
/// Allows people to tell the app they have had a negative test result from a
/// daily contact testing programme. This will release them from self-isolation
/// so that exposure notifications continue to work, in case they test
/// positive or come into contact with COVID again.
case dailyContactTesting
/// Shows information about daily contact testing on the screen people see when
/// they get notified of a potential exposure to COVID-19.
/// - SeeAlso: `dailyContactTesting`
case offerDCTOnExposureNotification
public static let productionEnabledFeatures: [Feature] = []
}
| 33.818182 | 83 | 0.717742 |
e3f441d10241b721d4bd58e71eed700747dfd13e | 3,111 | sql | SQL | sql/test_site.sql | cybervictimssl/MrRobotCTF | 86e37e1cc767740171ef9e8b2db2e1ec92be1fb0 | [
"Apache-2.0"
] | null | null | null | sql/test_site.sql | cybervictimssl/MrRobotCTF | 86e37e1cc767740171ef9e8b2db2e1ec92be1fb0 | [
"Apache-2.0"
] | null | null | null | sql/test_site.sql | cybervictimssl/MrRobotCTF | 86e37e1cc767740171ef9e8b2db2e1ec92be1fb0 | [
"Apache-2.0"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 28, 2020 at 10:29 PM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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: `test_site`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_flag`
--
CREATE TABLE `tbl_flag` (
`id` int(2) NOT NULL,
`flag` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tbl_flag`
--
INSERT INTO `tbl_flag` (`id`, `flag`) VALUES
(0, 'f4fc80e5e72d80c4ced184f0f9dec60c'),
(1, 'c98b8b5385c34b66da50d038de45eb46');
-- --------------------------------------------------------
--
-- Table structure for table `tbl_member`
--
CREATE TABLE `tbl_member` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(200) NOT NULL,
`email` varchar(255) NOT NULL,
`lvl0` int(11) NOT NULL DEFAULT 0,
`lvl1` int(11) NOT NULL DEFAULT 0,
`lvl2` int(11) NOT NULL DEFAULT 0,
`lvl3` int(11) NOT NULL DEFAULT 0,
`lvl4` int(11) NOT NULL DEFAULT 0,
`lvl5` int(11) NOT NULL DEFAULT 0,
`lvl6` int(11) NOT NULL DEFAULT 0,
`lvl7` int(11) NOT NULL DEFAULT 0,
`lvl8` int(11) NOT NULL DEFAULT 0,
`lvl9` int(11) NOT NULL DEFAULT 0,
`lvl10` int(11) NOT NULL DEFAULT 0,
`points` int(2) NOT NULL DEFAULT 0,
`create_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_member`
--
INSERT INTO `tbl_member` (`id`, `username`, `password`, `email`, `lvl0`, `lvl1`, `lvl2`, `lvl3`, `lvl4`, `lvl5`, `lvl6`, `lvl7`, `lvl8`, `lvl9`, `lvl10`, `points`, `create_at`) VALUES
(1, 'sandun', '$2y$10$p9KRpJbIlTi8CkcWQeB36e09VRwz.RrtPHzy3SWoxN9qxtlnh4Mq.', 'sandundananjaya@sd.com', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '2020-09-28 19:35:08'),
(2, 'nadeesh', '$2y$10$A9ATvTNiX2zWC.TMLaCTruuedrNTAOiqfG5534meUD.UcJlumqy56', 'saasdndundananjaya@asdil.com', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '2020-09-22 15:51:03'),
(3, 'ac', '$2y$10$UugQosG0O7a/eOTXgWFuDuint2PcgLwjFJ2xaAsiM1x8dFnbSC/Hm', 'ac@abs.com', 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '2020-09-28 20:22:16');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_flag`
--
ALTER TABLE `tbl_flag`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tbl_member`
--
ALTER TABLE `tbl_member`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_member`
--
ALTER TABLE `tbl_member`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
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 */;
| 28.805556 | 183 | 0.657988 |
5c555ff80d28b536d51064769bc0c35916f431f1 | 1,283 | h | C | src/imagestoreupdatesource.h | hemeraos/gravity-software-manager-plugin | 952845567f9eeeae6856d4d83ff55a823d943ab2 | [
"Apache-2.0"
] | null | null | null | src/imagestoreupdatesource.h | hemeraos/gravity-software-manager-plugin | 952845567f9eeeae6856d4d83ff55a823d943ab2 | [
"Apache-2.0"
] | null | null | null | src/imagestoreupdatesource.h | hemeraos/gravity-software-manager-plugin | 952845567f9eeeae6856d4d83ff55a823d943ab2 | [
"Apache-2.0"
] | 1 | 2021-02-08T17:53:35.000Z | 2021-02-08T17:53:35.000Z | /*
*
*/
#ifndef GRAVITY_NETWORKENDPOINTUPDATESOURCE_H
#define GRAVITY_NETWORKENDPOINTUPDATESOURCE_H
#include "updatesource.h"
#include <QtCore/QUrl>
#include <QtNetwork/QSslConfiguration>
class QNetworkAccessManager;
class QNetworkRequest;
namespace Hemera {
class Operation;
}
class ImageStoreUpdateSourcePrivate;
class ImageStoreUpdateSource : public UpdateSource
{
Q_OBJECT
Q_DISABLE_COPY(ImageStoreUpdateSource)
public:
explicit ImageStoreUpdateSource(const QUrl &endpointUrl, const QString &apiKey, QObject *parent = nullptr);
virtual ~ImageStoreUpdateSource();
public Q_SLOTS:
virtual Hemera::Operation *checkForUpdates(Hemera::SoftwareManagement::SystemUpdate::UpdateType preferredUpdateType) override final;
virtual Hemera::UrlOperation *downloadAvailableUpdate() override final;
protected:
virtual void initImpl() override final;
private:
QByteArray astarteAPIKey();
void setupRequestHeaders(QNetworkRequest *request);
QUrl m_endpointUrl;
QString m_apiKey;
QString m_applianceName;
QByteArray m_hardwareId;
QByteArray m_astarteAPIKey;
QNetworkAccessManager *m_nam;
QJsonObject m_metadata;
friend class CheckForImageStoreUpdatesOperation;
};
#endif // GRAVITY_NETWORKENDPOINTUPDATESOURCE_H
| 23.327273 | 136 | 0.792673 |
855ad0719dca60666f526ae68d8108439f8cb381 | 261 | js | JavaScript | static/api/cpp/search/classes_a.js | jadarve/lluvia-docs | 0f4c77998377bf56515f1fce81c5c7905ff172c4 | [
"MIT"
] | null | null | null | static/api/cpp/search/classes_a.js | jadarve/lluvia-docs | 0f4c77998377bf56515f1fce81c5c7905ff172c4 | [
"MIT"
] | 13 | 2020-06-03T00:04:25.000Z | 2022-01-25T01:00:39.000Z | static/api/cpp/search/classes_a.js | jadarve/lluvia-docs | 0f4c77998377bf56515f1fce81c5c7905ff172c4 | [
"MIT"
] | 1 | 2021-06-04T22:49:56.000Z | 2021-06-04T22:49:56.000Z | var searchData=
[
['vec3_449',['vec3',['../structll_1_1vec3.html',1,'ll']]],
['vec3_3c_20uint32_5ft_20_3e_450',['vec3< uint32_t >',['../structll_1_1vec3.html',1,'ll']]],
['vkheapinfo_451',['VkHeapInfo',['../structll_1_1VkHeapInfo.html',1,'ll']]]
];
| 37.285714 | 100 | 0.651341 |
c4ab3d6d3ac154bd58adacc354251f40be3ecdcb | 21,155 | h | C | net.ssa/xr_3da/Collide/cl_intersect.h | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | xr_3da/Collide/cl_intersect.h | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | xr_3da/Collide/cl_intersect.h | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | //---------------------------------------------------------------------------
#ifndef intersectH
#define intersectH
#include "cl_defs.h"
namespace RAPID {
//----------------------------------------------------------------------
// Name : intersectRaySphere()
// Input : rO - origin of ray in world space
// rV - vector describing direction of ray in world space
// sO - Origin of sphere
// sR - radius of sphere
// Notes : Normalized directional vectors expected
// -----------------------------------------------------------------------
IC bool IntersectRaySphere(const Fvector& rO, const Fvector& rV, const Fvector& sO, float sR)
{
Fvector Q;
Q.sub(sO,rO);
float c = Q.magnitude();
float v = Q.dotproduct(rV);
float d = sR*sR - (c*c - v*v);
// If there was no intersection, return -1
return (d > 0.0);
}
//-- Ray-Triangle : 2nd level of indirection --------------------------------
IC bool TestRayTri(const Fvector& C, const Fvector& D, Fvector** p, float& u, float& v, float& range, bool bCull)
{
Fvector edge1, edge2, tvec, pvec, qvec;
float det,inv_det;
// find vectors for two edges sharing vert0
edge1.sub(*p[1], *p[0]);
edge2.sub(*p[2], *p[0]);
// begin calculating determinant - also used to calculate U parameter
pvec.crossproduct(D, edge2);
// if determinant is near zero, ray lies in plane of triangle
det = edge1.dotproduct(pvec);
if (bCull){ // define TEST_CULL if culling is desired
if (det < EPS) return false;
tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec); // calculate U parameter and test bounds
if (u < 0.0 || u > det) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec); // calculate V parameter and test bounds
if (v < 0.0 || u + v > det) return false;
range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle
inv_det = 1.0f / det;
range *= inv_det;
u *= inv_det;
v *= inv_det;
}else{ // the non-culling branch
if (det > -EPS && det < EPS) return false;
inv_det = 1.0f / det;
tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
if (u < 0.0f || u > 1.0f) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
if (v < 0.0f || u + v > 1.0f) return false;
range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
}
return true;
}
//-- Ray-Triangle : 1st level of indirection --------------------------------
IC bool TestRayTri(const Fvector& C, const Fvector& D, Fvector* p, float& u, float& v, float& range, bool bCull)
{
Fvector edge1, edge2, tvec, pvec, qvec;
float det,inv_det;
// find vectors for two edges sharing vert0
edge1.sub(p[1], p[0]);
edge2.sub(p[2], p[0]);
// begin calculating determinant - also used to calculate U parameter
pvec.crossproduct(D, edge2);
// if determinant is near zero, ray lies in plane of triangle
det = edge1.dotproduct(pvec);
if (bCull){ // define TEST_CULL if culling is desired
if (det < EPS) return false;
tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec); // calculate U parameter and test bounds
if (u < 0.0f || u > det) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec); // calculate V parameter and test bounds
if (v < 0.0f || u + v > det) return false;
range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle
inv_det = 1.0f / det;
range *= inv_det;
u *= inv_det;
v *= inv_det;
}else{ // the non-culling branch
if (det > -EPS && det < EPS) return false;
inv_det = 1.0f / det;
tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
if (u < 0.0f || u > 1.0f) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
if (v < 0.0f || u + v > 1.0f) return false;
range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
}
return true;
}
//-- Ray-Triangle(always return range) : 1st level of indirection --------------------------------
IC bool TestRayTri2(const Fvector& C, const Fvector& D, Fvector* p, float& range)
{
Fvector edge1, edge2, tvec, pvec, qvec;
float det,inv_det,u,v;
// find vectors for two edges sharing vert0
edge1.sub(p[1], p[0]);
edge2.sub(p[2], p[0]);
// begin calculating determinant - also used to calculate U parameter
pvec.crossproduct(D, edge2);
// if determinant is near zero, ray lies in plane of triangle
det = edge1.dotproduct(pvec);
if (fabsf(det) < EPS_S) { range=-1; return false; }
inv_det = 1.0f / det;
tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects plane
if (u < 0.0f || u > 1.0f) return false;
v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
if (v < 0.0f || u + v > 1.0f) return false;
return true;
}
//---------------------------------------------------------------------------
// macros for fast arithmetic
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// compare [-r,r] to [NdD+dt*NdW]
#define TESTV0(NdD, R) \
if (NdD> R) return false;\
else if (NdD<-R) return false;
//---------------------------------------------------------------------------
// compare [-r,r] to [min{p,p+d0,p+d1},max{p,p+d0,p+d1}]
#define TESTV1(p,d0,d1,r){ \
if ( (p) > (r) ){ \
if ( (d0) >= 0.0f ){ \
if ( (d1) >= 0.0f ){ \
return false; \
}else{ \
if ( (p)+(d1) > (r) ) \
return false; \
} \
}else if ( (d1) <= (d0) ){ \
if ( (p)+(d1) > (r) ) \
return false; \
}else{ \
if ( (p)+(d0) > (r) ) \
return false; \
} \
}else if ( (p) < -(r) ){ \
if ( (d0) <= 0.0f ){ \
if ( (d1) <= 0.0f ){ \
return false; \
}else{ \
if ( (p)+(d1) < -(r) ) \
return false; \
} \
}else if ( (d1) >= (d0) ){ \
if ( (p)+(d1) < -(r) ) \
return false; \
}else{ \
if ( (p)+(d0) < -(r) ) \
return false; \
} \
} \
}
//---------------------------------------------------------------------------
// compare [-r,r] to [min{p,p+d},max{p,p+d}]
#define TESTV2(p,d,r){ \
if ( (p) > (r) ){ \
if ( (d) >= 0.0f ){ return false; \
}else{ if ( (p)+(d) > (r) ) return false; } \
}else if ( (p) < -(r) ){ \
if ( (d) <= 0.0f ){ return false; \
}else{ if ( (p)+(d) < -(r) ) return false; } \
} \
}
//---------------------------------------------------------------------------
IC bool TestBBoxTri(const Fmatrix33& A, const Fvector& T, const Fvector& extA, Fvector** p, BOOL bCulling){
// construct triangle normal, difference of center and vertex (18 ops)
Fvector D, E[2], N;
E[0].sub(*p[1],*p[0]);
E[1].sub(*p[2],*p[0]);
N.crossproduct(E[0],E[1]);
if (bCulling&&(A.k.dotproduct(N)>=0)) return false;
D.sub(*p[0],T);
// axis C+t*N
float A0dN = A.i.dotproduct(N);
float A1dN = A.j.dotproduct(N);
float A2dN = A.k.dotproduct(N);
float R = fabsf(extA.x*A0dN)+fabsf(extA.y*A1dN)+fabsf(extA.z*A2dN);
float NdD = N.dotproduct(D);
TESTV0(NdD,R); //AXIS_N
// axis C+t*A0
float A0dD = A.i.dotproduct(D);
float A0dE0 = A.i.dotproduct(E[0]);
float A0dE1 = A.i.dotproduct(E[1]);
TESTV1(A0dD,A0dE0,A0dE1,extA.x); //AXIS_A0
// axis C+t*A1
float A1dD = A.j.dotproduct(D);
float A1dE0 = A.j.dotproduct(E[0]);
float A1dE1 = A.j.dotproduct(E[1]);
TESTV1(A1dD,A1dE0,A1dE1,extA.y); //AXIS_A1
// axis C+t*A2
float A2dD = A.k.dotproduct(D);
float A2dE0 = A.k.dotproduct(E[0]);
float A2dE1 = A.k.dotproduct(E[1]);
TESTV1(A2dD,A2dE0,A2dE1,extA.z); //AXIS_A2
// axis C+t*A0xE0
Fvector A0xE0;
A0xE0.crossproduct(A.i,E[0]);
float A0xE0dD = A0xE0.dotproduct(D);
R = fabsf(extA.y*A2dE0)+fabsf(extA.z*A1dE0);
TESTV2(A0xE0dD,A0dN,R); //AXIS_A0xE0
// axis C+t*A0xE1
Fvector A0xE1;
A0xE1.crossproduct(A.i,E[1]);
float A0xE1dD = A0xE1.dotproduct(D);
R = fabsf(extA.y*A2dE1)+fabsf(extA.z*A1dE1);
TESTV2(A0xE1dD,-A0dN,R); //AXIS_A0xE1
// axis C+t*A0xE2
float A1dE2 = A1dE1-A1dE0;
float A2dE2 = A2dE1-A2dE0;
float A0xE2dD = A0xE1dD-A0xE0dD;
R = fabsf(extA.y*A2dE2)+fabsf(extA.z*A1dE2);
TESTV2(A0xE2dD,-A0dN,R); //AXIS_A0xE2
// axis C+t*A1xE0
Fvector A1xE0;
A1xE0.crossproduct(A.j,E[0]);
float A1xE0dD = A1xE0.dotproduct(D);
R = fabsf(extA.x*A2dE0)+fabsf(extA.z*A0dE0);
TESTV2(A1xE0dD,A1dN,R); //AXIS_A1xE0
// axis C+t*A1xE1
Fvector A1xE1;
A1xE1.crossproduct(A.j,E[1]);
float A1xE1dD = A1xE1.dotproduct(D);
R = fabsf(extA.x*A2dE1)+fabsf(extA.z*A0dE1);
TESTV2(A1xE1dD,-A1dN,R); //AXIS_A1xE1
// axis C+t*A1xE2
float A0dE2 = A0dE1-A0dE0;
float A1xE2dD = A1xE1dD-A1xE0dD;
R = fabsf(extA.x*A2dE2)+fabsf(extA.z*A0dE2);
TESTV2(A1xE2dD,-A1dN,R); //AXIS_A1xE2
// axis C+t*A2xE0
Fvector A2xE0;
A2xE0.crossproduct(A.k,E[0]);
float A2xE0dD = A2xE0.dotproduct(D);
R = fabsf(extA.x*A1dE0)+fabsf(extA.y*A0dE0);
TESTV2(A2xE0dD,A2dN,R); //AXIS_A2xE0
// axis C+t*A2xE1
Fvector A2xE1;
A2xE1.crossproduct(A.k,E[1]);
float A2xE1dD = A2xE1.dotproduct(D);
R = fabsf(extA.x*A1dE1)+fabsf(extA.y*A0dE1);
TESTV2(A2xE1dD,-A2dN,R); //AXIS_A2xE1
// axis C+t*A2xE2
float A2xE2dD = A2xE1dD-A2xE0dD;
R = fabsf(extA.x*A1dE2)+fabsf(extA.y*A0dE2);
TESTV2(A2xE2dD,-A2dN,R); //AXIS_A2xE2
// intersection occurs
return true;
}
IC bool TestBBoxTri(const Fmatrix33& A, const Fvector& T, const Fvector& extA, Fvector* p, BOOL bCulling){
// construct triangle normal, difference of center and vertex (18 ops)
Fvector D, E[2], N;
E[0].sub(p[1],p[0]);
E[1].sub(p[2],p[0]);
N.crossproduct(E[0],E[1]);
if (bCulling&&(A.k.dotproduct(N)>=0)) return false;
D.sub(p[0],T);
// axis C+t*N
float A0dN = A.i.dotproduct(N);
float A1dN = A.j.dotproduct(N);
float A2dN = A.k.dotproduct(N);
float R = fabsf(extA.x*A0dN)+fabsf(extA.y*A1dN)+fabsf(extA.z*A2dN);
float NdD = N.dotproduct(D);
TESTV0(NdD,R); //AXIS_N
// axis C+t*A0
float A0dD = A.i.dotproduct(D);
float A0dE0 = A.i.dotproduct(E[0]);
float A0dE1 = A.i.dotproduct(E[1]);
TESTV1(A0dD,A0dE0,A0dE1,extA.x); //AXIS_A0
// axis C+t*A1
float A1dD = A.j.dotproduct(D);
float A1dE0 = A.j.dotproduct(E[0]);
float A1dE1 = A.j.dotproduct(E[1]);
TESTV1(A1dD,A1dE0,A1dE1,extA.y); //AXIS_A1
// axis C+t*A2
float A2dD = A.k.dotproduct(D);
float A2dE0 = A.k.dotproduct(E[0]);
float A2dE1 = A.k.dotproduct(E[1]);
TESTV1(A2dD,A2dE0,A2dE1,extA.z); //AXIS_A2
// axis C+t*A0xE0
Fvector A0xE0;
A0xE0.crossproduct(A.i,E[0]);
float A0xE0dD = A0xE0.dotproduct(D);
R = fabsf(extA.y*A2dE0)+fabsf(extA.z*A1dE0);
TESTV2(A0xE0dD,A0dN,R); //AXIS_A0xE0
// axis C+t*A0xE1
Fvector A0xE1;
A0xE1.crossproduct(A.i,E[1]);
float A0xE1dD = A0xE1.dotproduct(D);
R = fabsf(extA.y*A2dE1)+fabsf(extA.z*A1dE1);
TESTV2(A0xE1dD,-A0dN,R); //AXIS_A0xE1
// axis C+t*A0xE2
float A1dE2 = A1dE1-A1dE0;
float A2dE2 = A2dE1-A2dE0;
float A0xE2dD = A0xE1dD-A0xE0dD;
R = fabsf(extA.y*A2dE2)+fabsf(extA.z*A1dE2);
TESTV2(A0xE2dD,-A0dN,R); //AXIS_A0xE2
// axis C+t*A1xE0
Fvector A1xE0;
A1xE0.crossproduct(A.j,E[0]);
float A1xE0dD = A1xE0.dotproduct(D);
R = fabsf(extA.x*A2dE0)+fabsf(extA.z*A0dE0);
TESTV2(A1xE0dD,A1dN,R); //AXIS_A1xE0
// axis C+t*A1xE1
Fvector A1xE1;
A1xE1.crossproduct(A.j,E[1]);
float A1xE1dD = A1xE1.dotproduct(D);
R = fabsf(extA.x*A2dE1)+fabsf(extA.z*A0dE1);
TESTV2(A1xE1dD,-A1dN,R); //AXIS_A1xE1
// axis C+t*A1xE2
float A0dE2 = A0dE1-A0dE0;
float A1xE2dD = A1xE1dD-A1xE0dD;
R = fabsf(extA.x*A2dE2)+fabsf(extA.z*A0dE2);
TESTV2(A1xE2dD,-A1dN,R); //AXIS_A1xE2
// axis C+t*A2xE0
Fvector A2xE0;
A2xE0.crossproduct(A.k,E[0]);
float A2xE0dD = A2xE0.dotproduct(D);
R = fabsf(extA.x*A1dE0)+fabsf(extA.y*A0dE0);
TESTV2(A2xE0dD,A2dN,R); //AXIS_A2xE0
// axis C+t*A2xE1
Fvector A2xE1;
A2xE1.crossproduct(A.k,E[1]);
float A2xE1dD = A2xE1.dotproduct(D);
R = fabsf(extA.x*A1dE1)+fabsf(extA.y*A0dE1);
TESTV2(A2xE1dD,-A2dN,R); //AXIS_A2xE1
// axis C+t*A2xE2
float A2xE2dD = A2xE1dD-A2xE0dD;
R = fabsf(extA.x*A1dE2)+fabsf(extA.y*A0dE2);
TESTV2(A2xE2dD,-A2dN,R); //AXIS_A2xE2
// intersection occurs
return true;
}
IC bool TestBBoxTri(const bbox& bb,Fvector** p, BOOL bCulling){
// convenience variables
Fmatrix33 T;
T.transpose(bb.pR);
return TestBBoxTri(T, bb.pT, bb.d, p, bCulling);
}
//---------------------------------------------------------------------------}
//----------------------------------------------------------------------------
IC float MgcSqrDistance (const Fvector& rkPoint, const Fvector& orig, const Fvector& e0,const Fvector& e1){
Fvector kDiff;
kDiff.sub(orig,rkPoint);
float fA00 = e0.square_magnitude();
float fA01 = e0.dotproduct(e1);
float fA11 = e1.square_magnitude();
float fB0 = kDiff.dotproduct(e0);
float fB1 = kDiff.dotproduct(e1);
float fC = kDiff.square_magnitude();
float fDet = fabsf(fA00*fA11-fA01*fA01);
float fS = fA01*fB1-fA11*fB0;
float fT = fA01*fB0-fA00*fB1;
float fSqrDist;
if ( fS + fT <= fDet ){
if ( fS < 0.0f ){
if ( fT < 0.0f ){ // region 4
if ( fB0 < 0.0f ){
fT = 0.0f;
if ( -fB0 >= fA00 ){
fS = 1.0f;
fSqrDist = fA00+2.0f*fB0+fC;
}else{
fS = -fB0/fA00;
fSqrDist = fB0*fS+fC;
}
}else{
fS = 0.0f;
if ( fB1 >= 0.0f ){
fT = 0.0f;
fSqrDist = fC;
}else if ( -fB1 >= fA11 ){
fT = 1.0f;
fSqrDist = fA11+2.0f*fB1+fC;
}else{
fT = -fB1/fA11;
fSqrDist = fB1*fT+fC;
}
}
}else{ // region 3
fS = 0.0f;
if ( fB1 >= 0.0f ){
fT = 0.0f;
fSqrDist = fC;
}else if ( -fB1 >= fA11 ){
fT = 1;
fSqrDist = fA11+2.0f*fB1+fC;
}else{
fT = -fB1/fA11;
fSqrDist = fB1*fT+fC;
}
}
}else if ( fT < 0.0f ){ // region 5
fT = 0.0f;
if ( fB0 >= 0.0f ){
fS = 0.0f;
fSqrDist = fC;
}else if ( -fB0 >= fA00 ){
fS = 1.0;
fSqrDist = fA00+2.0f*fB0+fC;
}else{
fS = -fB0/fA00;
fSqrDist = fB0*fS+fC;
}
}else{ // region 0
// minimum at interior point
float fInvDet = 1.0f/fDet;
fS *= fInvDet;
fT *= fInvDet;
fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
}
}else{
float fTmp0, fTmp1, fNumer, fDenom;
if ( fS < 0.0f ){ // region 2
fTmp0 = fA01 + fB0;
fTmp1 = fA11 + fB1;
if ( fTmp1 > fTmp0 ){
fNumer = fTmp1 - fTmp0;
fDenom = fA00-2.0f*fA01+fA11;
if ( fNumer >= fDenom ){
fS = 1.0f;
fT = 0.0f;
fSqrDist = fA00+2.0f*fB0+fC;
}else{
fS = fNumer/fDenom;
fT = 1.0f - fS;
fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
}
}else{
fS = 0.0f;
if ( fTmp1 <= 0.0f ){
fT = 1.0f;
fSqrDist = fA11+2.0f*fB1+fC;
}else if ( fB1 >= 0.0f ){
fT = 0.0f;
fSqrDist = fC;
}else{
fT = -fB1/fA11;
fSqrDist = fB1*fT+fC;
}
}
}else if ( fT < 0.0 ){ // region 6
fTmp0 = fA01 + fB1;
fTmp1 = fA00 + fB0;
if ( fTmp1 > fTmp0 ){
fNumer = fTmp1 - fTmp0;
fDenom = fA00-2.0f*fA01+fA11;
if ( fNumer >= fDenom ){
fT = 1.0f;
fS = 0.0f;
fSqrDist = fA11+2.0f*fB1+fC;
}else{
fT = fNumer/fDenom;
fS = 1.0f - fT;
fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
}
}else{
fT = 0.0f;
if ( fTmp1 <= 0.0f ){
fS = 1.0f;
fSqrDist = fA00+2.0f*fB0+fC;
}else if ( fB0 >= 0.0f ){
fS = 0.0f;
fSqrDist = fC;
}else{
fS = -fB0/fA00;
fSqrDist = fB0*fS+fC;
}
}
}else{ // region 1
fNumer = fA11 + fB1 - fA01 - fB0;
if ( fNumer <= 0.0f ){
fS = 0.0f;
fT = 1.0f;
fSqrDist = fA11+2.0f*fB1+fC;
}else{
fDenom = fA00-2.0f*fA01+fA11;
if ( fNumer >= fDenom ){
fS = 1.0f;
fT = 0.0f;
fSqrDist = fA00+2.0f*fB0+fC;
}else{
fS = fNumer/fDenom;
fT = 1.0f - fS;
fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
}
}
}
}
return fabsf(fSqrDist);
}
IC bool TestSphereTri(const Fvector& sphereOrigin, float sphereRadius,
const Fvector& orig, const Fvector& e0,const Fvector& e1)
{
float fRSqr = sphereRadius*sphereRadius;
Fvector kV0mC;
kV0mC.sub(orig, sphereOrigin);
// count the number of triangle vertices inside the sphere
int iInside = 0;
// test if v0 is inside the sphere
if ( kV0mC.square_magnitude() <= fRSqr )
iInside++;
// test if v1 is inside the sphere
Fvector kDiff;
kDiff.add(kV0mC, e0);
if ( kDiff.square_magnitude() <= fRSqr )
iInside++;
// test if v2 is inside the sphere
kDiff.add(kV0mC, e1);
if ( kDiff.square_magnitude() <= fRSqr )
iInside++;
// triangle does not traversely intersect sphere
if ( iInside == 3 ) return false;
// triangle transversely intersects sphere
if ( iInside > 0 ) return true;
// All vertices are outside the sphere, but the triangle might still
// intersect the sphere. This is the case when the distance from the
// sphere center to the triangle is smaller than the radius.
float fSqrDist = MgcSqrDistance(sphereOrigin,orig,e0,e1);
return fSqrDist < fRSqr;
}
//---------------------------------------------------------------------------
};
#endif
| 35.258333 | 114 | 0.489104 |
0a198b45c79d3602ed9ba5869eaea3849e73c54d | 447 | swift | Swift | SkyUtils/Locking.swift | skylarsch/SkyUtils | 59255c2e28145ee0d7a8fb8513b901738c8c1e40 | [
"MIT"
] | null | null | null | SkyUtils/Locking.swift | skylarsch/SkyUtils | 59255c2e28145ee0d7a8fb8513b901738c8c1e40 | [
"MIT"
] | null | null | null | SkyUtils/Locking.swift | skylarsch/SkyUtils | 59255c2e28145ee0d7a8fb8513b901738c8c1e40 | [
"MIT"
] | null | null | null | //
// Locking.swift
// SkyUtils
//
// Created by Skylar Schipper on 8/24/16.
// Copyright © 2016 Skylar Schipper. All rights reserved.
//
public protocol Locking {
mutating func lock()
mutating func unlock()
mutating func tryLock() -> Bool
}
public extension Locking {
mutating func sync<T>(_ block: (Void) throws -> (T)) rethrows -> T {
self.lock()
defer { self.unlock() }
return try block()
}
}
| 20.318182 | 72 | 0.612975 |
06ebbddc4638dc47a6af4852b7d4006de626ce6d | 10,728 | kt | Kotlin | app/src/main/java/com/uiuang/cloudknowledge/ui/fragment/home/WanHomeFragment.kt | uiuang/CloudKnowledge | 0a5d9e980f24abc6067392fc83fd930047b7d85e | [
"Apache-2.0"
] | 2 | 2020-08-04T05:19:00.000Z | 2021-01-17T08:39:11.000Z | app/src/main/java/com/uiuang/cloudknowledge/ui/fragment/home/WanHomeFragment.kt | uiuang/CloudKnowledge | 0a5d9e980f24abc6067392fc83fd930047b7d85e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/uiuang/cloudknowledge/ui/fragment/home/WanHomeFragment.kt | uiuang/CloudKnowledge | 0a5d9e980f24abc6067392fc83fd930047b7d85e | [
"Apache-2.0"
] | null | null | null | package com.uiuang.cloudknowledge.ui.fragment.home
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.kingja.loadsir.core.LoadService
import com.uiuang.cloudknowledge.R
import com.uiuang.cloudknowledge.app.base.BaseFragment
import com.uiuang.cloudknowledge.bean.event.CollectBus
import com.uiuang.cloudknowledge.bean.wan.WebBean
import com.uiuang.cloudknowledge.data.enums.CollectType
import com.uiuang.cloudknowledge.databinding.HeaderWanAndroidBinding
import com.uiuang.cloudknowledge.databinding.IncludeListBinding
import com.uiuang.cloudknowledge.ext.*
import com.uiuang.cloudknowledge.ui.adapter.wan.WanAndroidAdapter
import com.uiuang.cloudknowledge.ui.adapter.wan.WanBannerAdapter
import com.uiuang.cloudknowledge.utils.toast
import com.uiuang.cloudknowledge.viewmodel.request.RequestCollectViewModel
import com.uiuang.cloudknowledge.viewmodel.request.RequestWanHomeViewModel
import com.uiuang.cloudknowledge.viewmodel.state.HomeViewModel
import com.uiuang.cloudknowledge.weight.recyclerview.DefineLoadMoreView
import com.uiuang.mvvm.ext.nav
import com.uiuang.mvvm.ext.navigateAction
import com.uiuang.mvvm.util.dp2px
import com.uiuang.mvvm.util.screenWidth
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.include_list.*
import kotlinx.android.synthetic.main.include_recyclerview.*
import kotlinx.android.synthetic.main.include_toolbar.*
class WanHomeFragment : BaseFragment<HomeViewModel, IncludeListBinding>() {
//界面状态管理者
private lateinit var loadSir: LoadService<Any>
//收藏viewModel
private val requestCollectViewModel: RequestCollectViewModel by viewModels()
private val requestWanHomeViewModel: RequestWanHomeViewModel by viewModels()
//recyclerview的底部加载view 因为要在首页动态改变他的颜色,所以加了他这个字段
private lateinit var footView: DefineLoadMoreView
private lateinit var headerWanAndroidBinding: HeaderWanAndroidBinding
private val wanAndroidAdapter: WanAndroidAdapter by lazy {
WanAndroidAdapter(arrayListOf())
}
private val wanBannerAdapter: WanBannerAdapter by lazy {
WanBannerAdapter(arrayListOf())
}
companion object {
@JvmStatic
fun newInstance() = WanHomeFragment()
}
override fun layoutId(): Int = R.layout.include_list
override fun initView(savedInstanceState: Bundle?) {
//状态页配置
loadSir = loadServiceInit(swipeRefresh) {
//点击重试时触发的操作
loadSir.showLoading()
requestWanHomeViewModel.getWanAndroidBanner()
}
//初始化recyclerView
headerWanAndroidBinding = DataBindingUtil.inflate<HeaderWanAndroidBinding>(
layoutInflater,
R.layout.header_wan_android,
null,
false
)
val px = requireActivity().dp2px(100)
val screenWidth: Int = requireActivity().screenWidth
val width: Int = screenWidth.minus(px)
val height: Float = width / 1.8f
val lp = ConstraintLayout.LayoutParams(screenWidth, height.toInt())
headerWanAndroidBinding.banner.layoutParams = lp
headerWanAndroidBinding.radioGroup.visibility = View.VISIBLE
headerWanAndroidBinding.rb1.setOnCheckedChangeListener { _, isChecked ->
refresh(isChecked, isArticle = true, isRefresh = true)
}
headerWanAndroidBinding.rb2.setOnCheckedChangeListener { _, isChecked ->
refresh(isChecked, isArticle = false, isRefresh = true)
}
recyclerView.addHeaderView(headerWanAndroidBinding.root)
recyclerView.init(
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false),
wanAndroidAdapter
).let {
it.addItemDecoration(
DividerItemDecoration(
requireActivity(),
DividerItemDecoration.VERTICAL
)
)
footView = it.initFooter(SwipeRecyclerView.LoadMoreListener {
if (headerWanAndroidBinding.rb1.isChecked) {
refresh(isChecked = true, isArticle = true, isRefresh = false)
} else {
refresh(isChecked = true, isArticle = false, isRefresh = false)
}
})
// //初始化FloatingActionButton
it.initFloatBtn(floatBtn)
}
//初始化 SwipeRefreshLayout
swipeRefresh.init {
//触发刷新监听时请求数据
requestWanHomeViewModel.getWanAndroidBanner()
if (headerWanAndroidBinding.rb1.isChecked) {
refresh(isChecked = true, isArticle = true, isRefresh = true)
} else {
refresh(isChecked = true, isArticle = false, isRefresh = true)
}
}
headerWanAndroidBinding.banner.run {
addBannerLifecycleObserver(this@WanHomeFragment)//添加生命周期观察者
adapter = wanBannerAdapter
indicator = CircleIndicator(requireActivity())
setOnBannerListener { _, position ->
val item = wanBannerAdapter.getData(position)
nav().navigateAction(R.id.action_global_webViewFragment, Bundle().apply {
val webBean = WebBean(
item.id,
false,
item.title,
item.url,
CollectType.Url.type
)
putParcelable("webBean", webBean)
})
//// openDetail(item.url, item.title)
}
}
wanAndroidAdapter.run {
addChildClickViewIds(R.id.tv_tag_name)
setOnItemClickListener { _, view, position ->
val item = getItem(position - this@WanHomeFragment.recyclerView.headerCount)
nav().navigateAction(R.id.action_global_webViewFragment, Bundle().apply {
val webBean = WebBean(
item.id,
item.collect,
item.title,
item.link,
CollectType.Article.type
)
putParcelable("webBean", webBean)
})
}
setCollectClick { item, v, position ->
if (v.isChecked) {
requestCollectViewModel.unCollect(item.id)
} else {
requestCollectViewModel.collect(item.id)
}
}
setOnItemChildClickListener { _, view, position ->
when (view.id) {
R.id.tv_tag_name -> getItem(position - 1).chapterName?.toast()
}
}
}
}
override fun createObserver() {
requestWanHomeViewModel.wanAndroidBannerBean.observe(viewLifecycleOwner, Observer {
//设值 新写了个拓展函数,搞死了这个恶心的重复代码
val listData = it.listData
if (it.isSuccess) {
loadSir.showSuccess()
headerWanAndroidBinding.banner.setDatas(listData)
} else loadSir.showError()
})
requestWanHomeViewModel.articlesBean.observe(viewLifecycleOwner, Observer {
loadListData(it, wanAndroidAdapter, loadSir, recyclerView, swipeRefresh)
})
requestCollectViewModel.collectUiState.observe(viewLifecycleOwner, Observer {
if (it.isSuccess) {
//收藏或取消收藏操作成功,发送全局收藏消息
eventViewModel.collectEvent.value =
CollectBus(
it.id,
it.collect
)
} else {
showMessage(it.errorMsg)
for (index in wanAndroidAdapter.data.indices) {
if (wanAndroidAdapter.data[index].id == it.id) {
wanAndroidAdapter.data[index].collect = it.collect
wanAndroidAdapter.notifyItemChanged(index)
break
}
}
}
})
appViewModel.run {
//监听账户信息是否改变 有值时(登录)将相关的数据设置为已收藏,为空时(退出登录),将已收藏的数据变为未收藏
userinfo.observe(viewLifecycleOwner, Observer {
if (it != null) {
it.collectIds.forEach { id ->
for (item in wanAndroidAdapter.data) {
if (id.toInt() == item.id) {
item.collect = true
break
}
}
}
} else {
for (item in wanAndroidAdapter.data) {
item.collect = false
}
}
wanAndroidAdapter.notifyDataSetChanged()
})
//监听全局的主题颜色改变
appColor.observe(viewLifecycleOwner, Observer {
setUiTheme(it, toolbar, floatBtn, swipeRefresh, loadSir, footView,headerWanAndroidBinding.viewLine,headerWanAndroidBinding.rb1,headerWanAndroidBinding.rb2)
})
//监听全局的列表动画改编
appAnimation.observe(viewLifecycleOwner, Observer {
wanAndroidAdapter.setAdapterAnimation(it)
})
//监听全局的收藏信息 收藏的Id跟本列表的数据id匹配则需要更新
eventViewModel.collectEvent.observe(viewLifecycleOwner, Observer {
for (index in wanAndroidAdapter.data.indices) {
if (wanAndroidAdapter.data[index].id == it.id) {
wanAndroidAdapter.data[index].collect = it.collect
wanAndroidAdapter.notifyItemChanged(index)
break
}
}
})
}
}
override fun lazyLoadData() {
//设置界面 加载中
loadSir.showLoading()
requestWanHomeViewModel.getWanAndroidBanner()
refresh(isChecked = true, isArticle = true, isRefresh = true)
}
private fun refresh(isChecked: Boolean, isArticle: Boolean, isRefresh: Boolean) {
if (isChecked) {
swipeRefresh.isRefreshing = true
wanAndroidAdapter.setNoImage(isArticle)
if (isArticle)
requestWanHomeViewModel.getHomeArticleList(isRefresh, null)
else
requestWanHomeViewModel.getHomeProjectList(isRefresh)
}
}
} | 40.029851 | 171 | 0.603747 |
e8db7b8afe28efde2a5b3d53186f27fb42108a8d | 1,912 | py | Python | src/test/tests/hybrid/missingdata.py | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 226 | 2018-12-29T01:13:49.000Z | 2022-03-30T19:16:31.000Z | src/test/tests/hybrid/missingdata.py | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 5,100 | 2019-01-14T18:19:25.000Z | 2022-03-31T23:08:36.000Z | src/test/tests/hybrid/missingdata.py | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 84 | 2019-01-24T17:41:50.000Z | 2022-03-10T10:01:46.000Z | # ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: missingdata.py
#
# Tests: missing data
#
# Programmer: Brad Whitlock
# Date: Thu Jan 19 09:49:15 PST 2012
#
# Modifications:
#
# ----------------------------------------------------------------------------
def SetTheView():
v = GetView2D()
v.viewportCoords = (0.02, 0.98, 0.25, 1)
SetView2D(v)
def test0(datapath):
TestSection("Missing data")
OpenDatabase(pjoin(datapath,"earth.nc"))
AddPlot("Pseudocolor", "height")
DrawPlots()
SetTheView()
Test("missingdata_0_00")
ChangeActivePlotsVar("carbon_particulates")
Test("missingdata_0_01")
ChangeActivePlotsVar("seatemp")
Test("missingdata_0_02")
ChangeActivePlotsVar("population")
Test("missingdata_0_03")
# Pick on higher zone numbers to make sure pick works.
PickByNode(domain=0, element=833621)
TestText("missingdata_0_04", GetPickOutput())
DeleteAllPlots()
def test1(datapath):
TestSection("Expressions and missing data")
OpenDatabase(pjoin(datapath,"earth.nc"))
DefineScalarExpression("meaningless", "carbon_particulates + seatemp")
AddPlot("Pseudocolor", "meaningless")
DrawPlots()
SetTheView()
Test("missingdata_1_00")
DeleteAllPlots()
DefineVectorExpression("color", "color(red,green,blue)")
AddPlot("Truecolor", "color")
DrawPlots()
ResetView()
SetTheView()
Test("missingdata_1_01")
DefineVectorExpression("color2", "color(population*0.364,green,blue)")
ChangeActivePlotsVar("color2")
v1 = GetView2D()
v1.viewportCoords = (0.02, 0.98, 0.02, 0.98)
v1.windowCoords = (259.439, 513.299, 288.93, 540) #25.466)
SetView2D(v1)
Test("missingdata_1_02")
def main():
datapath = data_path("netcdf_test_data")
test0(datapath)
test1(datapath)
main()
Exit()
| 26.555556 | 78 | 0.619247 |
c8c89346e89883c82d2f0a0df4831a54ad6aa594 | 905 | swift | Swift | build/src/Models/WfmBuShortTermForecastUpdateCompleteTopicBuShortTermForecastNotification.swift | MyPureCloud/platform-client-sdk-ios | d69e3deedbbe2f30c3641a5c8b4e66eb5eb6858b | [
"MIT"
] | null | null | null | build/src/Models/WfmBuShortTermForecastUpdateCompleteTopicBuShortTermForecastNotification.swift | MyPureCloud/platform-client-sdk-ios | d69e3deedbbe2f30c3641a5c8b4e66eb5eb6858b | [
"MIT"
] | null | null | null | build/src/Models/WfmBuShortTermForecastUpdateCompleteTopicBuShortTermForecastNotification.swift | MyPureCloud/platform-client-sdk-ios | d69e3deedbbe2f30c3641a5c8b4e66eb5eb6858b | [
"MIT"
] | 1 | 2021-05-11T21:57:38.000Z | 2021-05-11T21:57:38.000Z | //
// WfmBuShortTermForecastUpdateCompleteTopicBuShortTermForecastNotification.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class WfmBuShortTermForecastUpdateCompleteTopicBuShortTermForecastNotification: Codable {
public enum Status: String, Codable {
case processing = "Processing"
case complete = "Complete"
case canceled = "Canceled"
case error = "Error"
}
public var status: Status?
public var result: WfmBuShortTermForecastUpdateCompleteTopicBuShortTermForecast?
public var operationId: String?
public init(status: Status?, result: WfmBuShortTermForecastUpdateCompleteTopicBuShortTermForecast?, operationId: String?) {
self.status = status
self.result = result
self.operationId = operationId
}
}
| 24.459459 | 127 | 0.704972 |
5c741a769388db4baf147eac11e9d0323cbe2550 | 475 | h | C | CC98Lite/Models/CC98Forum.h | xueshoulai/CC98Lite | 830612d1c102c3acd90c47f157df67ef9a217aa8 | [
"Unlicense"
] | 1 | 2016-01-04T11:46:14.000Z | 2016-01-04T11:46:14.000Z | CC98Lite/Models/CC98Forum.h | xueshoulai/CC98Lite | 830612d1c102c3acd90c47f157df67ef9a217aa8 | [
"Unlicense"
] | null | null | null | CC98Lite/Models/CC98Forum.h | xueshoulai/CC98Lite | 830612d1c102c3acd90c47f157df67ef9a217aa8 | [
"Unlicense"
] | null | null | null | //
// CC98Forum.h
// CC98Lite
//
// Created by S on 15/6/8.
// Copyright (c) 2015年 zju. All rights reserved.
//
#import <Foundation/Foundation.h>
@class UIImage;
@class CC98PersonalPartition;
@interface CC98Forum : NSObject
@property (weak, readonly) UIImage *logo;
@property (nonatomic, readonly) CC98PersonalPartition *personalPartition;
+ (CC98Forum *)sharedInstance;
- (void)commonPartitionsWithBlock:(void (^)(NSArray *partitions, NSError *error))block;
@end
| 19.791667 | 87 | 0.730526 |
0b306e809cb7c5ad319eabca404494268373c70e | 13,195 | py | Python | ml/association/apriori.py | thorwhalen/ut | 353a4629c35a2cca76ef91a4d5209afe766433b4 | [
"MIT"
] | 4 | 2016-12-17T20:06:10.000Z | 2021-11-19T04:45:29.000Z | ml/association/apriori.py | thorwhalen/ut | 353a4629c35a2cca76ef91a4d5209afe766433b4 | [
"MIT"
] | 11 | 2021-01-06T05:35:11.000Z | 2022-03-11T23:28:31.000Z | ml/association/apriori.py | thorwhalen/ut | 353a4629c35a2cca76ef91a4d5209afe766433b4 | [
"MIT"
] | 3 | 2015-06-12T10:44:16.000Z | 2021-07-26T18:39:47.000Z | """Association mining -- apriori algo"""
__author__ = 'thor'
from numpy import *
# Modified from:
# Everaldo Aguiar & Reid Johnson (https://github.com/cse40647/cse40647/blob/sp.14/10%20-%20Apriori.ipynb)
#
# Itself Modified from:
# Marcel Caraciolo (https://gist.github.com/marcelcaraciolo/1423287)
#
# Functions to compute and extract association rules from a given frequent
# itemset generated by the Apriori algorithm.
import pandas as pd
from statsmodels.stats.proportion import samplesize_confint_proportion
def choose_sample_size(min_confidence, alpha=0.05, half_length=None):
if half_length is None:
t = 0.20 * min_confidence if min_confidence < 0.5 else 0.20 * (1 - min_confidence)
half_length = max(0.01, t) # choose half length to be a proportion (0.2) of min_confidence
return samplesize_confint_proportion(
proportion=min_confidence,
half_length=half_length,
alpha=alpha,
method='normal')
def association_rules(dataset, min_confidence=0.2, min_support=None, output='dataframe', verbose=False):
assert min_confidence > 0 and min_confidence <= 1, "min_confidence must be between 0 and 1"
if min_support is None:
# if no min_support is given, choose it to be the sample size you need to get 95% conf in proportion estimate
min_support = choose_sample_size(min_confidence, alpha=0.05, half_length=None)
if min_support > 1:
min_support /= float(len(dataset))
F, support_data = apriori(dataset, min_support=min_support, verbose=False)
H = generate_rules(F, support_data, min_confidence=min_confidence, verbose=verbose)
if output == 'triple':
return H
elif output == 'dataframe':
def set_to_string(s):
return str(", ".join(s))
support_df = pd.DataFrame({'condition': list(map(set_to_string, list(support_data.keys()))),
'condition_frequency': list(support_data.values())})
support_df['condition_count'] = len(dataset) * support_df['condition_frequency']
d = pd.DataFrame([{'condition': set_to_string(condition),
'effect': set_to_string(effect),
'effect_frequency': support}
for condition, effect, support in H])
d = pd.merge(d, support_df, how='inner', on='condition')
d['condition_and_effect_count'] = d['effect_frequency'] * d['condition_count']
d = d[['condition', 'effect', 'effect_frequency', 'condition_count', 'condition_and_effect_count',
'condition_frequency']]
return d.sort('effect_frequency', ascending=False).reset_index(drop=True)
def apriori(dataset, min_support=0.5, verbose=False):
"""Implements the Apriori algorithm.
The Apriori algorithm will iteratively generate new candidate
k-itemsets using the frequent (k-1)-itemsets found in the previous
iteration.
Parameters
----------
dataset : list
The dataset (a list of transactions) from which to generate
candidate itemsets.
min_support : float
The minimum support threshold. Defaults to 0.5.
Returns
-------
F : list
The list of frequent itemsets.
support_data : dict
The support data for all candidate itemsets.
References
----------
.. [1] R. Agrawal, R. Srikant, "Fast Algorithms for Mining Association
Rules", 1994.
"""
C1 = create_candidates(dataset)
D = list(map(set, dataset))
F1, support_data = support_prune(D, C1, min_support, verbose=False) # prune candidate 1-itemsets
F = [F1] # list of frequent itemsets; initialized to frequent 1-itemsets
k = 2 # the itemset cardinality
while (len(F[k - 2]) > 0):
Ck = apriori_gen(F[k-2], k) # generate candidate itemsets
Fk, supK = support_prune(D, Ck, min_support) # prune candidate itemsets
support_data.update(supK) # update the support counts to reflect pruning
F.append(Fk) # add the pruned candidate itemsets to the list of frequent itemsets
k += 1
if verbose:
# Print a list of all the frequent itemsets.
for kset in F:
for item in kset:
print(("" \
+ "{" \
+ "".join(str(i) + ", " for i in iter(item)).rstrip(', ') \
+ "}" \
+ ": sup = " + str(round(support_data[item], 3))))
return F, support_data
def create_candidates(dataset, verbose=False):
"""Creates a list of candidate 1-itemsets from a list of transactions.
Parameters
----------
dataset : list
The dataset (a list of transactions) from which to generate candidate
itemsets.
Returns
-------
The list of candidate itemsets (c1) passed as a frozenset (a set that is
immutable and hashable).
"""
c1 = [] # list of all items in the database of transactions
for transaction in dataset:
for item in transaction:
if not [item] in c1:
c1.append([item])
c1.sort()
if verbose:
# Print a list of all the candidate items.
print(("" \
+ "{" \
+ "".join(str(i[0]) + ", " for i in iter(c1)).rstrip(', ') \
+ "}"))
# Map c1 to a frozenset because it will be the key of a dictionary.
return list(map(frozenset, c1))
def support_prune(dataset, candidates, min_support, verbose=False):
"""Returns all candidate itemsets that meet a minimum support threshold.
By the apriori principle, if an itemset is frequent, then all of its
subsets must also be frequent. As a result, we can perform support-based
pruning to systematically control the exponential growth of candidate
itemsets. Thus, itemsets that do not meet the minimum support level are
pruned from the input list of itemsets (dataset).
Parameters
----------
dataset : list
The dataset (a list of transactions) from which to generate candidate
itemsets.
candidates : frozenset
The list of candidate itemsets.
min_support : float
The minimum support threshold.
Returns
-------
retlist : list
The list of frequent itemsets.
support_data : dict
The support data for all candidate itemsets.
"""
sscnt = {} # set for support counts
for tid in dataset:
for can in candidates:
if can.issubset(tid):
sscnt.setdefault(can, 0)
sscnt[can] += 1
num_items = float(len(dataset)) # total number of transactions in the dataset
retlist = [] # array for unpruned itemsets
support_data = {} # set for support data for corresponding itemsets
for key in sscnt:
# Calculate the support of itemset key.
support = sscnt[key] / num_items
if support >= min_support:
retlist.insert(0, key)
support_data[key] = support
# Print a list of the pruned itemsets.
if verbose:
for kset in retlist:
for item in kset:
print(("{" + str(item) + "}"))
print("")
for key in sscnt:
print(("" \
+ "{" \
+ "".join([str(i) + ", " for i in iter(key)]).rstrip(', ') \
+ "}" \
+ ": sup = " + str(support_data[key])))
return retlist, support_data
def apriori_gen(freq_sets, k):
"""Generates candidate itemsets (via the F_k-1 x F_k-1 method).
This operation generates new candidate k-itemsets based on the frequent
(k-1)-itemsets found in the previous iteration. The candidate generation
procedure merges a pair of frequent (k-1)-itemsets only if their first k-2
items are identical.
Parameters
----------
freq_sets : list
The list of frequent (k-1)-itemsets.
k : integer
The cardinality of the current itemsets being evaluated.
Returns
-------
retlist : list
The list of merged frequent itemsets.
"""
retList = [] # list of merged frequent itemsets
lenLk = len(freq_sets) # number of frequent itemsets
for i in range(lenLk):
for j in range(i+1, lenLk):
a=list(freq_sets[i])
b=list(freq_sets[j])
a.sort()
b.sort()
F1 = a[:k-2] # first k-2 items of freq_sets[i]
F2 = b[:k-2] # first k-2 items of freq_sets[j]
if F1 == F2: # if the first k-2 items are identical
# Merge the frequent itemsets.
retList.append(freq_sets[i] | freq_sets[j])
return retList
def rules_from_conseq(freq_set, H, support_data, rules, min_confidence=0.5, verbose=False):
"""Generates a set of candidate rules.
Parameters
----------
freq_set : frozenset
The complete list of frequent itemsets.
H : list
A list of frequent itemsets (of a particular length).
support_data : dict
The support data for all candidate itemsets.
rules : list
A potentially incomplete set of candidate rules above the minimum
confidence threshold.
min_confidence : float
The minimum confidence threshold. Defaults to 0.5.
"""
m = len(H[0])
if m == 1:
Hmp1 = calc_confidence(freq_set, H, support_data, rules, min_confidence, verbose)
if (len(freq_set) > (m+1)):
Hmp1 = apriori_gen(H, m+1) # generate candidate itemsets
Hmp1 = calc_confidence(freq_set, Hmp1, support_data, rules, min_confidence, verbose)
if len(Hmp1) > 1:
# If there are candidate rules above the minimum confidence
# threshold, recurse on the list of these candidate rules.
rules_from_conseq(freq_set, Hmp1, support_data, rules, min_confidence, verbose)
def calc_confidence(freq_set, H, support_data, rules, min_confidence=0.5, verbose=False):
"""Evaluates the generated rules.
One measurement for quantifying the goodness of association rules is
confidence. The confidence for a rule 'P implies H' (P -> H) is defined as
the support for P and H divided by the support for P
(support (P|H) / support(P)), where the | symbol denotes the set union
(thus P|H means all the items in set P or in set H).
To calculate the confidence, we iterate through the frequent itemsets and
associated support data. For each frequent itemset, we divide the support
of the itemset by the support of the antecedent (left-hand-side of the
rule).
Parameters
----------
freq_set : frozenset
The complete list of frequent itemsets.
H : list
A list of frequent itemsets (of a particular length).
min_support : float
The minimum support threshold.
rules : list
A potentially incomplete set of candidate rules above the minimum
confidence threshold.
min_confidence : float
The minimum confidence threshold. Defaults to 0.5.
Returns
-------
pruned_H : list
The list of candidate rules above the minimum confidence threshold.
"""
pruned_H = [] # list of candidate rules above the minimum confidence threshold
for conseq in H: # iterate over the frequent itemsets
conf = support_data[freq_set] / support_data[freq_set - conseq]
if conf >= min_confidence:
rules.append((freq_set - conseq, conseq, conf))
pruned_H.append(conseq)
if verbose:
print(("" \
+ "{" \
+ "".join([str(i) + ", " for i in iter(freq_set-conseq)]).rstrip(', ') \
+ "}" \
+ " ---> " \
+ "{" \
+ "".join([str(i) + ", " for i in iter(conseq)]).rstrip(', ') \
+ "}" \
+ ": conf = " + str(round(conf, 3)) \
+ ", sup = " + str(round(support_data[freq_set], 3))))
return pruned_H
def generate_rules(F, support_data, min_confidence=0.5, verbose=True):
"""Generates a set of candidate rules from a list of frequent itemsets.
For each frequent itemset, we calculate the confidence of using a
particular item as the rule consequent (right-hand-side of the rule). By
testing and merging the remaining rules, we recursively create a list of
pruned rules.
Parameters
----------
F : list
A list of frequent itemsets.
support_data : dict
The corresponding support data for the frequent itemsets (L).
min_confidence : float
The minimum confidence threshold. Defaults to 0.5.
Returns
-------
rules : list
The list of candidate rules above the minimum confidence threshold.
"""
rules = []
for i in range(1, len(F)):
for freq_set in F[i]:
H1 = [frozenset([itemset]) for itemset in freq_set]
if (i > 1):
rules_from_conseq(freq_set, H1, support_data, rules, min_confidence, verbose)
else:
calc_confidence(freq_set, H1, support_data, rules, min_confidence, verbose)
return rules
| 35.093085 | 117 | 0.617582 |
956be369536396461b046d09849fdd2a2b8ee7d8 | 865 | css | CSS | css/style.css | fdezcaminero/Microverse-Project-Number-3 | e103587c2b5d7327317ec7050f97ef255a36a2e2 | [
"MIT"
] | null | null | null | css/style.css | fdezcaminero/Microverse-Project-Number-3 | e103587c2b5d7327317ec7050f97ef255a36a2e2 | [
"MIT"
] | null | null | null | css/style.css | fdezcaminero/Microverse-Project-Number-3 | e103587c2b5d7327317ec7050f97ef255a36a2e2 | [
"MIT"
] | null | null | null | html, body{
margin: 0;
padding: 0;
}
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
#welcome-section {
height: 100vh;
background-color: lightseagreen;
margin-top: 100px;
display: flex;
flex-direction: column;
align-items: center;
font-size: 30px;
}
#navbar {
position: fixed;
top: 0;
height: 100px;
width: 100%;
background-color: #ccc;
font-size: 25px;
}
#menu-items {
right: 0;
text-align: right;
padding: 30px;
}
#projects{
height: 400px;
padding: 50px;
}
#contact{
}
#contact-items{
padding: 10px;
display: block;
margin-left: auto;
margin-right: auto;
width: 60%;
border: 1px solid #000;
box-shadow: 2px 2px 2px #ccc;
}
.titles
{
font-weight: bold;
}
| 13.307692 | 43 | 0.560694 |
3a09c966b5abae1c57dad4424d8e1625182823f0 | 1,647 | swift | Swift | Mobile/CarWashService/Views/ClientCar/CarBrandModelSelector.swift | GUSAR1T0/CarWashSystem | 61f69c9ed4b71cd734762db925da35b8392c6946 | [
"MIT"
] | 1 | 2020-03-26T03:54:05.000Z | 2020-03-26T03:54:05.000Z | Mobile/CarWashService/Views/ClientCar/CarBrandModelSelector.swift | GUSAR1T0/CarWashSystem | 61f69c9ed4b71cd734762db925da35b8392c6946 | [
"MIT"
] | 48 | 2019-10-30T18:40:59.000Z | 2020-01-17T09:20:37.000Z | Mobile/CarWashService/Views/ClientCar/CarBrandModelSelector.swift | GUSAR1T0/CarWashSystem | 61f69c9ed4b71cd734762db925da35b8392c6946 | [
"MIT"
] | null | null | null | //
// Created by Roman Mashenkin on 13.12.2019.
// Copyright (c) 2019 VXDESIGN.STORE. All rights reserved.
//
import SwiftUI
struct CarBrandModelSelector: View {
@EnvironmentObject private var lookupStorage: LookupStorage
private var isCarModelChooseModalActive: Binding<Bool>
private var modelId: Binding<Int?>
init(modelId: Binding<Int?>, isCarModelChooseModalActive: Binding<Bool>) {
self.modelId = modelId
self.isCarModelChooseModalActive = isCarModelChooseModalActive
}
var body: some View {
if let clientLookupModel = lookupStorage.clientLookupModel {
return AnyView(
VStack {
List(clientLookupModel.carBrandModelsModels) { carBrandModels in
NavigationLink(destination: CarModelSelector(
brandId: carBrandModels.id,
brandName: carBrandModels.name,
modelId: self.modelId,
isCarModelChooseModalActive: self.isCarModelChooseModalActive)
) {
Text(carBrandModels.name)
}
.padding()
.font(.system(size: 18, weight: .bold))
.navigationBarTitle("Choose a car brand")
}
}
.frame(minWidth: 0, maxWidth: .infinity)
)
} else {
return AnyView(EmptyView())
}
}
}
| 38.302326 | 98 | 0.508804 |
918d742ed5c64fcf1539391216491fd32c62e7c1 | 2,125 | html | HTML | app/index.html | torvalde/mjolfjell-homepage | 2e618bb352d70ffd6c75822c87fc094674900bbc | [
"MIT"
] | null | null | null | app/index.html | torvalde/mjolfjell-homepage | 2e618bb352d70ffd6c75822c87fc094674900bbc | [
"MIT"
] | null | null | null | app/index.html | torvalde/mjolfjell-homepage | 2e618bb352d70ffd6c75822c87fc094674900bbc | [
"MIT"
] | null | null | null | <!doctype html>
<html lang="nb">
<head>
<!-- The first thing in any HTML file should be the charset -->
<meta charset="utf-8">
<!-- Make the page mobile compatible -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="google-site-verification" content="8QavdBnJmoPyrnKS2KL9rDEAqHdPKPwkjWJHLpTXz8Y" />
<!-- Allow installing the app to the homescreen -->
<link rel="manifest" href="manifest.json">
<link href="//cdn.muicss.com/mui-0.9.7/css/mui.min.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="https://cdn.emailjs.com/dist/email.min.js"></script>
<script type="text/javascript">
(function(){
emailjs.init("user_M7W1T0wehYaTcWdnU2Bvz");
})();
</script>
<meta name="mobile-web-app-capable" content="yes">
<title>Mjølfjell Ungdomsherberge</title>
</head>
<body>
<!-- Display a message if JS has been disabled on the browser. -->
<noscript>If you're seeing this message, that means <strong>JavaScript has been disabled on your browser</strong>, please <strong>enable JS</strong> to make this app work.</noscript>
<!-- The app hooks into this div -->
<div id="app"></div>
<!-- Open Sans Font -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,400i,700" rel="stylesheet">
<!-- A lot of magic happens in this file. HtmlWebpackPlugin automatically includes all assets (e.g. bundle.js, main.css) with the correct HTML tags, which is why they are missing in this HTML file. Don't add any assets here! (Check out webpackconfig.js if you want to know more) -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-93056432-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html> | 51.829268 | 286 | 0.656941 |