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
12e2ad4fc6525e0a31ce4b9546d519cb7efc7a48
2,551
kt
Kotlin
koma-core-api/common/src/koma/internal/default/generated/matrix/DefaultIntMatrixFactory.kt
drmoose/koma
765dfb206cada4b682a94e140a40ba6c6e95667b
[ "Apache-2.0" ]
233
2017-05-03T16:54:08.000Z
2021-12-04T03:20:04.000Z
koma-core-api/common/src/koma/internal/default/generated/matrix/DefaultIntMatrixFactory.kt
drmoose/koma
765dfb206cada4b682a94e140a40ba6c6e95667b
[ "Apache-2.0" ]
70
2017-05-07T20:07:37.000Z
2021-08-11T20:33:13.000Z
koma-core-api/common/src/koma/internal/default/generated/matrix/DefaultIntMatrixFactory.kt
drmoose/koma
765dfb206cada4b682a94e140a40ba6c6e95667b
[ "Apache-2.0" ]
31
2017-05-18T09:04:56.000Z
2021-05-07T22:40:26.000Z
/** * THIS FILE IS AUTOGENERATED, DO NOT MODIFY. EDIT THE FILES IN templates/ * AND RUN ./gradlew :codegen INSTEAD! */ package koma.internal.default.generated.matrix import koma.* import koma.matrix.* import koma.extensions.* import koma.internal.notImplemented import koma.internal.getRng import koma.internal.syncNotNative class DefaultIntMatrixFactory: MatrixFactory<Matrix<Int>> { override fun zeros(rows: Int, cols: Int) = DefaultIntMatrix(rows, cols) override fun create(data: IntRange): Matrix<Int> { val input = data.map { it.toInt() } val out = DefaultIntMatrix(1, input.size) input.forEachIndexed { idx, ele -> out[idx] = ele } return out } override fun create(data: DoubleArray): Matrix<Int> { val out = DefaultIntMatrix(1, data.size) data.forEachIndexed { idx, ele -> out[idx] = ele.toInt() } return out } override fun create(data: Array<DoubleArray>): Matrix<Int> { val out = DefaultIntMatrix(data.size, data[0].size) data.forEachIndexed { rowIdx, row -> row.forEachIndexed { colIdx, ele -> out[rowIdx, colIdx] = ele.toInt() } } return out } override fun ones(rows: Int, cols: Int): Matrix<Int> = zeros(rows, cols).fill {_,_-> 1.toInt()} override fun eye(size: Int): Matrix<Int> = eye(size, size) override fun eye(rows: Int, cols: Int): Matrix<Int> = zeros(rows, cols) .fill {row,col->if (row==col) 1.toInt() else 0.toInt() } override fun rand(rows: Int, cols: Int): Matrix<Int> { val array = zeros(rows, cols) val rng = getRng() syncNotNative(rng) { array.fill { _, _ -> rng.nextDoubleUnsafe().toInt() } } return array; } override fun randn(rows: Int, cols: Int): Matrix<Int> { val array = zeros(rows, cols) val rng = getRng() syncNotNative(rng) { array.fill { _, _ -> rng.nextGaussianUnsafe().toInt() } } return array; } override fun arange(start: Double, stop: Double, increment: Double): Matrix<Int> { error(notImplemented) } override fun arange(start: Double, stop: Double): Matrix<Int> { error(notImplemented) } override fun arange(start: Int, stop: Int, increment: Int): Matrix<Int> { error(notImplemented) } override fun arange(start: Int, stop: Int): Matrix<Int> { error(notImplemented) } }
29.321839
86
0.596629
16b2dc7a9c949e5854dafdae45d687b2d70ae681
118
kt
Kotlin
src/main/kotlin/io/github/gciatto/kt/node/FileLineTransformer.kt
gciatto/kt-npm-publish
2db056208571d9b547dcdd223ceec812f81504c3
[ "Apache-2.0" ]
12
2020-11-09T17:38:25.000Z
2021-06-19T10:29:06.000Z
src/main/kotlin/io/github/gciatto/kt/node/FileLineTransformer.kt
gciatto/kt-npm-publish
2db056208571d9b547dcdd223ceec812f81504c3
[ "Apache-2.0" ]
2
2021-06-08T12:09:01.000Z
2021-07-14T12:29:46.000Z
src/main/kotlin/io/github/gciatto/kt/node/FileLineTransformer.kt
gciatto/kt-npm-publish
2db056208571d9b547dcdd223ceec812f81504c3
[ "Apache-2.0" ]
1
2021-05-17T23:54:54.000Z
2021-05-17T23:54:54.000Z
package io.github.gciatto.kt.node import java.io.File typealias FileLineTransformer = (File, Int, String) -> String
19.666667
61
0.771186
797dc90b9ce78cbf86a3aa4526fae41bd6bfc77b
2,145
swift
Swift
Sources/ISO/DecoderConfigDescriptor.swift
Jaumo/HaishinKit.swift
f9257e686773dbb4621a3860a6f50bcad098a378
[ "BSD-3-Clause" ]
1,672
2017-07-26T18:16:54.000Z
2022-03-29T09:28:58.000Z
Sources/ISO/DecoderConfigDescriptor.swift
Jaumo/HaishinKit.swift
f9257e686773dbb4621a3860a6f50bcad098a378
[ "BSD-3-Clause" ]
614
2017-07-29T10:40:28.000Z
2022-03-31T12:47:25.000Z
Sources/ISO/DecoderConfigDescriptor.swift
Jaumo/HaishinKit.swift
f9257e686773dbb4621a3860a6f50bcad098a378
[ "BSD-3-Clause" ]
459
2017-07-31T09:27:17.000Z
2022-03-14T08:16:18.000Z
import Foundation struct DecoderConfigDescriptor: BaseDescriptor { static let tag: UInt8 = 0x04 // MARK: BaseDescriptor let tag: UInt8 = Self.tag var size: UInt32 = 0 // MARK: DecoderConfigDescriptor var objectTypeIndication: UInt8 = 0 var streamType: UInt8 = 0 var upStream = false var bufferSizeDB: UInt32 = 0 var maxBitrate: UInt32 = 0 var avgBitrate: UInt32 = 0 var decSpecificInfo = DecoderSpecificInfo() var profileLevelIndicationIndexDescriptor = ProfileLevelIndicationIndexDescriptor() } extension DecoderConfigDescriptor: DataConvertible { // MARK: DataConvertible var data: Data { get { let buffer = ByteArray() .writeUInt8(tag) .writeUInt32(0) .writeUInt8(objectTypeIndication) .writeUInt8(streamType << 2 | (upStream ? 1 : 0) << 1 | 1) .writeUInt24(bufferSizeDB) .writeUInt32(maxBitrate) .writeUInt32(avgBitrate) .writeBytes(decSpecificInfo.data) .writeBytes(profileLevelIndicationIndexDescriptor.data) writeSize(buffer) return buffer.data } set { do { let buffer = ByteArray(data: newValue) _ = try buffer.readUInt8() size = try readSize(buffer) objectTypeIndication = try buffer.readUInt8() let first = try buffer.readUInt8() streamType = (first >> 2) upStream = (first & 2) != 0 bufferSizeDB = try buffer.readUInt24() maxBitrate = try buffer.readUInt32() avgBitrate = try buffer.readUInt32() let position = buffer.position decSpecificInfo.data = try buffer.readBytes(buffer.bytesAvailable) buffer.position = position + Int(decSpecificInfo.size) + 5 profileLevelIndicationIndexDescriptor.data = try buffer.readBytes(buffer.bytesAvailable) } catch { logger.error(error) } } } }
36.982759
104
0.58042
5366fb3e58903b60b805be1e09fdead94867a6b5
1,919
swift
Swift
chapter-3-4 UINavigationCOntroller 2/demoApp/demoApp/SecondSubViewController.swift
grehujt/learningSwift
1271d39d22ad7fe4e46fe998176c13efcf629d3a
[ "MIT" ]
null
null
null
chapter-3-4 UINavigationCOntroller 2/demoApp/demoApp/SecondSubViewController.swift
grehujt/learningSwift
1271d39d22ad7fe4e46fe998176c13efcf629d3a
[ "MIT" ]
null
null
null
chapter-3-4 UINavigationCOntroller 2/demoApp/demoApp/SecondSubViewController.swift
grehujt/learningSwift
1271d39d22ad7fe4e46fe998176c13efcf629d3a
[ "MIT" ]
null
null
null
// // SecondSubViewController.swift // demoApp // // Created by kris on 8/5/16. // Copyright © 2016 kris. All rights reserved. // import UIKit class SecondSubViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Second Page" self.view.backgroundColor = UIColor.purpleColor() let btHide = UIButton(frame: CGRectMake(40, 200, 240, 30)) btHide.setTitle("hide navi bar", forState: .Normal) btHide.backgroundColor = UIColor.orangeColor() btHide.addTarget(self, action: #selector(SecondSubViewController.hideNaviBar), forControlEvents: .TouchUpInside) self.view.addSubview(btHide) let btHideToolBar = UIButton(frame: CGRectMake(40, 260, 240, 30)) btHideToolBar.setTitle("hide tool bar", forState: .Normal) btHideToolBar.backgroundColor = UIColor.orangeColor() btHideToolBar.addTarget(self, action: #selector(SecondSubViewController.hideToolBar), forControlEvents: .TouchUpInside) self.view.addSubview(btHideToolBar) } func hideNaviBar() { self.navigationController?.setNavigationBarHidden(true, animated: true) } func hideToolBar() { self.navigationController?.setToolbarHidden(true, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
33.086207
127
0.681605
1819c58d6343affd74a6f19963c3101fc675ebf7
4,286
css
CSS
styles/responsive.css
dev-gustavo-henrique/4elementos
2c9edd41fb9f46eae58e53b215d0bca9cb511734
[ "MIT" ]
null
null
null
styles/responsive.css
dev-gustavo-henrique/4elementos
2c9edd41fb9f46eae58e53b215d0bca9cb511734
[ "MIT" ]
null
null
null
styles/responsive.css
dev-gustavo-henrique/4elementos
2c9edd41fb9f46eae58e53b215d0bca9cb511734
[ "MIT" ]
null
null
null
/* ====================== *Media Queries* ====================== */ @media only screen and (max-width: 320px) { .results { padding: 0; min-width: 94vw; } .results > div{ min-width: 100%; } .resultsDiv > div { padding-right: 0!important; } } @media only screen and (min-width: 425px) { .page-main { min-width: 90%; } } /* When the height of the screen is less than 450 pixels, change the font-size of the links and position the close button again, so they don't overlap */ @media screen and (max-height: 450px) { .overlay a { font-size: 20px } .overlay .closebtn { font-size: 40px; top: 15px; right: 35px; } } @media only screen and (max-width: 690px) { p { font-size: 14px; } .div-start { display: none; } .quiz-container h3 { margin-top: 20px; font-size: 16px; } .quiz-container p { font-size: 16px; text-align: justify; text-justify: newspaper; margin: 2px; } .endTest { width: 90%; padding: 15px; } .results { flex-direction: column; align-items: stretch; } .results > div{ min-width: 100%; } .results > div:not(last-child), .resultDivs > div:not(last-child), .results > div > div { margin-bottom: 3rem; } .heading { text-indent: 23px; } h3#agentName { text-align: center; } } @media only screen and (max-width: 768px) { .container { min-width: 90vw; padding: 10px; text-align: center; } .results.container{ padding: 25px; min-width: 90vw; } .resultsDiv > div { padding-right: 45px; display: flex; flex-direction: column; justify-content: space-between; gap: 12px; } h3 { margin-top: 20px; } p { font-size: 16px; margin: 2px; padding: 0 5px; } .imgSocial { filter: var(--filter); } .brand { gap: 4rem; } .brand .description, .brand .warnings{ flex-basis: 100%; } .simbolosHome { justify-content: center; } .start { min-width: 100%; } .quiz-container { width: 90%; } .question { margin-right: 15px!important; margin-left: 15px!important; } .controls { margin-bottom: 25px; } .option input[type="button"], .previous, .sendButton, .inputName { width: 90%!important; } .results img { width: 80px; height: 80px; } .footer-page { width: 100%; } } @media only screen and (min-width: 740px) { .content { flex-direction: column; } .brand { min-width: 100% } .content > { min-width: 100%; } } @media only screen and (min-width: 770px) { .results.container { min-width: 90vw; } } @media only screen and (min-width: 1440px) { .container{ max-width: 80vw; } h1 { font-size: 32px; } h2 { font-size: 30px; } h3 { font-size: 28px; } p { font-size: 15px; } .results .otherInfo { align-self: flex-start; flex-basis: 46%; } .start { font-size: 28px; } .quiz-container { width: 65vw!important; } .endTest { width: 40vw!important; } .question { width: 50%; font-size: 18px; } .options { gap: .625rem; } .option input{ min-width: 23rem!important; } .descElemento, .agradeciment { max-width: 100%!important; align-items: stretch; } .results.container { margin-top: 2rem; min-width: 80vw!important; } .results { justify-content: space-around; } .footer { display: flex; flex-wrap: wrap; flex-direction: column; flex: 1; max-width: 41%; margin-top: 5rem; margin-left: 6rem; } .footer-page { width: 30%; color: var(--white); } }
15.642336
153
0.484368
0721a17278dc77691d70c97a54fae534be5e631e
1,373
kts
Kotlin
coroutine-tracing-api-core/build.gradle.kts
Shinigami072/OpenTracing-Kotlin-Coroutine-Integration
3f4453d7612a6bbe87aa440306d1751a131dd4b4
[ "MIT" ]
13
2020-01-22T19:16:33.000Z
2021-09-23T20:13:14.000Z
coroutine-tracing-api-core/build.gradle.kts
Shinigami072/OpenTracing-Kotlin-Coroutine-Integration
3f4453d7612a6bbe87aa440306d1751a131dd4b4
[ "MIT" ]
2
2020-01-11T00:46:42.000Z
2020-05-01T20:45:57.000Z
coroutine-tracing-api-core/build.gradle.kts
Shinigami072/OpenTracing-Kotlin-Coroutine-Integration
3f4453d7612a6bbe87aa440306d1751a131dd4b4
[ "MIT" ]
3
2020-03-25T20:03:58.000Z
2021-09-22T12:38:55.000Z
val coroutines_version: String by project val opentracing_version: String by project val slf4j_version: String by project val kotlin_logging_version: String by project val junit_version: String by project val logback_version: String by project plugins { kotlin("jvm") } dependencies { implementation(kotlin("stdlib-jdk8")) implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("io.opentracing:opentracing-api:$opentracing_version") implementation("io.opentracing:opentracing-util:$opentracing_version") implementation("io.github.microutils:kotlin-logging:$kotlin_logging_version") implementation("org.slf4j:slf4j-api:$slf4j_version") testImplementation("org.junit.jupiter:junit-jupiter-api:$junit_version") testImplementation("io.opentracing:opentracing-mock:$opentracing_version") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$junit_version") testRuntimeOnly("ch.qos.logback:logback-classic:$logback_version") } tasks { compileKotlin { kotlinOptions.jvmTarget = "1.8" kotlinOptions.freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } test { useJUnitPlatform() } }
35.205128
91
0.761107
e8fc72a77fdd416f9afae8ddad6132491cc5fabf
4,405
py
Python
c4/system/history.py
Brewgarten/c4-system-manager
6fdec33ced4b1cb32d82a24cd168447a899b7e10
[ "MIT" ]
null
null
null
c4/system/history.py
Brewgarten/c4-system-manager
6fdec33ced4b1cb32d82a24cd168447a899b7e10
[ "MIT" ]
1
2017-10-17T21:51:40.000Z
2017-10-17T21:51:40.000Z
c4/system/history.py
Brewgarten/c4-system-manager
6fdec33ced4b1cb32d82a24cd168447a899b7e10
[ "MIT" ]
null
null
null
""" Copyright (c) IBM 2015-2017. All Rights Reserved. Project name: c4-system-manager This project is licensed under the MIT License, see LICENSE """ from abc import ABCMeta, abstractmethod class DeviceHistory(object): """ Device manager history """ __metaclass__ = ABCMeta @abstractmethod def add(self, node, name, status, ttl=None): """ Add status for device manager with specified name on specified node :param node: node name :type node: str :param name: device manager name :type name: str :param status: status :type status: :class:`DeviceManagerStatus` :param ttl: time to live (in seconds), infinite by default :type ttl: int """ @abstractmethod def get(self, node, name, limit=None): """ Get status history for device manager with specified name on specified node :param node: node name :type node: str :param name: device manager name :type name: str :param limit: number of statuses to return :type limit: int :returns: list of history entries :rtype: [:class:`Entry`] """ @abstractmethod def getAll(self): """ Get status history for all device managers on all nodes :returns: list of history entries :rtype: [:class:`Entry`] """ @abstractmethod def getLatest(self, node, name): """ Get latest status for device manager with specified name on specified node :param node: node name :type node: str :param name: device manager name :type name: str :returns: history entry :rtype: :class:`Entry` """ @abstractmethod def remove(self, node=None, name=None): """ Remove status history for device managers with specified names on specified nodes. node and name: remove history for specific device on a specific node node and no name remove history for all devices on a specific node no node and name remove history for specific device on all nodes no node and no name remove history for all devices on all nodes :param node: node name :type node: str :param name: device manager name :type name: str """ class Entry(object): """ History entry with timestamp and status information :param timestamp: datetime instance :type timestamp: :class:`Datetime` :param status: status :type status: :class:`SystemManagerStatus` or :class:`DeviceManagerStatus` """ def __init__(self, timestamp, status): self.timestamp = timestamp self.status = status class NodeHistory(object): """ System manager history """ __metaclass__ = ABCMeta @abstractmethod def add(self, node, status, ttl=None): """ Add status for system manager with on specified node :param node: node name :type node: str :param status: status :type status: :class:`SystemManagerStatus` :param ttl: time to live (in seconds), infinite by default :type ttl: int """ @abstractmethod def get(self, node, limit=None): """ Get status history for system manager on specified node :param node: node name :type node: str :param limit: number of statuses to return :type limit: int :returns: list of history entries :rtype: [:class:`Entry`] """ @abstractmethod def getAll(self): """ Get status history for all system managers on all nodes :returns: list of history entries :rtype: [:class:`Entry`] """ @abstractmethod def getLatest(self, node): """ Get latest status for system manager on specified node :param node: node name :type node: str :returns: history entry :rtype: :class:`Entry` """ @abstractmethod def remove(self, node=None): """ Remove status history for system managers on specified nodes. node: remove history for specific node no node remove history for all nodes :param node: node name :type node: str """
26.065089
90
0.595687
2f78ce8101bd3b75a09df07ed5a25532b5cbbb44
879
php
PHP
src/Facades/Menu.php
isakzhanov-r/laravel-menus
82d32703f8c89240f2af6c17af87f109f31014f5
[ "MIT" ]
null
null
null
src/Facades/Menu.php
isakzhanov-r/laravel-menus
82d32703f8c89240f2af6c17af87f109f31014f5
[ "MIT" ]
null
null
null
src/Facades/Menu.php
isakzhanov-r/laravel-menus
82d32703f8c89240f2af6c17af87f109f31014f5
[ "MIT" ]
null
null
null
<?php namespace IsakzhanovR\Menus\Facades; use Closure; use Illuminate\Support\Facades\Facade; use IsakzhanovR\Menus\Support\Item; use IsakzhanovR\Menus\Support\Menu as MenuSupport; /** * @method static MenuSupport make(string $name, Closure $callback = null) * @method static MenuSupport generate($name, $items, Closure $callback = null) * @method static bool exists(string $name) * @method static self add(Item $item) * @method static self action($action, string $title, $parameters = [], bool $absolute = true) * @method static self link($path, string $title, $extra = [], bool $secure = null) * @method static self route(string $name, string $title, $parameters = [], bool $absolute = true) * * @see \IsakzhanovR\Menus\Support\Menu */ class Menu extends Facade { protected static function getFacadeAccessor() { return MenuSupport::class; } }
31.392857
98
0.712173
6cb69be429b5c9898b2be110a2d0ef40a009570d
447
asm
Assembly
libsrc/graphics/retrofit/drawr_callee.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
640
2017-01-14T23:33:45.000Z
2022-03-30T11:28:42.000Z
libsrc/graphics/retrofit/drawr_callee.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
1,600
2017-01-15T16:12:02.000Z
2022-03-31T12:11:12.000Z
libsrc/graphics/retrofit/drawr_callee.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
215
2017-01-17T10:43:03.000Z
2022-03-23T17:25:02.000Z
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; ; $Id: drawr_callee.asm $ ; ; ; CALLER LINKAGE FOR FUNCTION POINTERS ; ----- void drawr(int x2, int y2) SECTION code_graphics PUBLIC drawr_callee PUBLIC _drawr_callee EXTERN drawr .drawr_callee ._drawr_callee pop af ; ret addr pop bc pop de push af ; ret addr push de push bc call drawr pop bc pop bc ret
12.416667
54
0.675615
39cf883609b1ad7b05b949f709850e1d3bdf2a96
230
js
JavaScript
components/global/card.js
First-Inu/FINUv2_frontend
c63a57b0dd8229bba277806cdfb42728313669b4
[ "MIT" ]
null
null
null
components/global/card.js
First-Inu/FINUv2_frontend
c63a57b0dd8229bba277806cdfb42728313669b4
[ "MIT" ]
12
2022-03-07T11:25:56.000Z
2022-03-31T11:23:44.000Z
components/global/card.js
First-Inu/FINUv2_frontend
c63a57b0dd8229bba277806cdfb42728313669b4
[ "MIT" ]
null
null
null
export default function Card(props) { const classes = props.className ? props.className : '' return ( <div className={"p-5 rounded-lg border-2 m-1 mb-6 card-boxshadow " + classes}> {props.children} </div> ); }
25.555556
82
0.63913
fb10f079f1a61c01a2d7bf1c23c5507072c05d45
1,860
go
Go
test/normal/fmapjoin_test.go
josephbuchma/goderive
2ec743906baa9dc47346a25e57cbbe4da399921e
[ "Apache-2.0" ]
1,024
2017-02-16T02:26:46.000Z
2022-03-29T19:10:18.000Z
test/normal/fmapjoin_test.go
josephbuchma/goderive
2ec743906baa9dc47346a25e57cbbe4da399921e
[ "Apache-2.0" ]
68
2017-02-12T17:02:49.000Z
2022-01-07T08:19:03.000Z
test/normal/fmapjoin_test.go
josephbuchma/goderive
2ec743906baa9dc47346a25e57cbbe4da399921e
[ "Apache-2.0" ]
52
2017-08-24T09:58:10.000Z
2022-03-10T06:26:23.000Z
// Copyright 2017 Walter Schulze // // 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 test import ( "reflect" "strconv" "strings" "testing" ) func TestFmapJoin(t *testing.T) { ss := []string{"a,b", "c,d"} split := func(s string) []string { return strings.Split(s, ",") } got := deriveJoinSS(deriveFmapSS(split, ss)) want := []string{"a", "b", "c", "d"} if !reflect.DeepEqual(got, want) { t.Fatalf("got %v, want %v", got, want) } } func TestFmapJoinError(t *testing.T) { read := func() (string, error) { return "1", nil } parseInt := func(i string) (int64, error) { ii, err := strconv.ParseInt(i, 10, 64) return int64(ii), err } got, err := deriveJoinEE(deriveFmapEE64(parseInt, read)) if err != nil { t.Fatal(err) } want := int64(1) if got != want { t.Fatalf("got %d, want %d", got, want) } } func wordsize(line string) <-chan int { c := make(chan int) go func() { words := strings.Split(line, " ") for _, word := range words { c <- len(word) } close(c) }() return c } func TestFmapJoinChannel(t *testing.T) { cc := deriveFmapChanChan(wordsize, toChan(lines)) sizes := deriveJoinChannels(cc) want := 2 + 4 + 2 + 5 + 7 + 4 + 7 + 4 + 7 + 5 + 7 + 4 + 7 + 7 + 7 + 4 got := 0 for i := range sizes { got += i } if got != want { t.Fatalf("got %d, want %d", got, want) } }
22.962963
76
0.629032
eac3407b433af2a409236f0838e4520e445fa80c
656
kt
Kotlin
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/extensions/JsonExtensions.kt
yalab/HTTP-Shortcuts
b111a781b14ac0598da68671181607e7cf0d4e84
[ "MIT" ]
null
null
null
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/extensions/JsonExtensions.kt
yalab/HTTP-Shortcuts
b111a781b14ac0598da68671181607e7cf0d4e84
[ "MIT" ]
null
null
null
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/extensions/JsonExtensions.kt
yalab/HTTP-Shortcuts
b111a781b14ac0598da68671181607e7cf0d4e84
[ "MIT" ]
null
null
null
package ch.rmy.android.http_shortcuts.extensions import org.json.JSONArray import org.json.JSONException import org.json.JSONObject fun JSONArray.toListOfStrings(): List<String> = mutableListOf<String>().also { list -> for (i in 0..length()) { try { list.add(getString(i)) } catch (e: JSONException) { // ignore } } } fun JSONArray.toListOfObjects(): List<JSONObject> = mutableListOf<JSONObject>().also { list -> for (i in 0..length()) { optJSONObject(i)?.let { element -> list.add(element) } } }
25.230769
51
0.547256
819a1e5a9a357cb6db0378f73b1cb134eac0225f
312
kt
Kotlin
app/src/main/java/com/vn/ntesco/model/Response/DetailPostResponse.kt
hoaphanit/ntesco.android.github
bf0a47a50eeb3d7113586417e07e7729fc1bb521
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/vn/ntesco/model/Response/DetailPostResponse.kt
hoaphanit/ntesco.android.github
bf0a47a50eeb3d7113586417e07e7729fc1bb521
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/vn/ntesco/model/Response/DetailPostResponse.kt
hoaphanit/ntesco.android.github
bf0a47a50eeb3d7113586417e07e7729fc1bb521
[ "Apache-2.0" ]
null
null
null
package com.vn.ntesco.model.Response import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.vn.ntesco.model.AboutUs import com.vn.ntesco.model.Post class DetailPostResponse : NTescoResponse(){ @SerializedName("data") @Expose var data : Post? = null }
26
49
0.775641
d46923569569e38b2e35800f9dfd5afc8e667b9a
127
rs
Rust
src/error.rs
jkcclemens/rust-cat
89f227ed9aeb0719973aba829b35dbbe2ed6ae09
[ "MIT" ]
null
null
null
src/error.rs
jkcclemens/rust-cat
89f227ed9aeb0719973aba829b35dbbe2ed6ae09
[ "MIT" ]
null
null
null
src/error.rs
jkcclemens/rust-cat
89f227ed9aeb0719973aba829b35dbbe2ed6ae09
[ "MIT" ]
null
null
null
use std::io; #[derive(Debug, Fail)] pub enum CatError { #[fail(display = "An IO error occurred: {}", _0)] Io(io::Error) }
15.875
51
0.606299
b3058829e7afabe50f9a6d43527446275dcd1d29
825
rb
Ruby
deploy/vagrant/core/config_openstack.rb
weiranyiran/alluxio
e9d242659df65e29cb20567a6e72343376c2bf88
[ "Apache-2.0" ]
7
2015-07-22T07:03:20.000Z
2018-08-19T11:42:11.000Z
deploy/vagrant/core/config_openstack.rb
weiranyiran/alluxio
e9d242659df65e29cb20567a6e72343376c2bf88
[ "Apache-2.0" ]
7
2020-01-31T18:17:36.000Z
2021-12-09T20:30:27.000Z
deploy/vagrant/core/config_openstack.rb
weiranyiran/alluxio
e9d242659df65e29cb20567a6e72343376c2bf88
[ "Apache-2.0" ]
11
2015-02-20T11:35:35.000Z
2018-08-19T11:42:14.000Z
# -*- mode: ruby -*- # vi: set ft=ruby : # OpenStack specific configurations go here def config_os(config, i, total, name) config.vm.box = "dummy" config.vm.box_url = "https://github.com/cloudbau/vagrant-openstack-plugin/raw/master/dummy.box" # Make sure the private key from the key pair is provided config.ssh.private_key_path = KEY_PATH config.vm.synced_folder ".", "/vagrant", disabled: true config.vm.provider :openstack do |os| os.username = ENV['OS_USERNAME'] os.api_key = ENV['OS_PASSWORD'] os.flavor = FLAVOR os.image = /#{Regexp.quote(IMAGE)}/ os.endpoint = KEYSTONE os.security_groups = SECURITY_GROUP os.ssh_username = SSH_USERNAME os.keypair_name = KEYPAIR_NAME os.floating_ip = "auto" os.server_name = TAG + name end end
28.448276
79
0.667879
6bbb925febeed31f8338682de606f264484e6511
1,412
kt
Kotlin
MultiPlatformLibrary/src/commonMain/kotlin/me/randheer/covidstatsin/domain/model/DistrictUiModel.kt
randheercode/CovidStatsIn
fba8818238e45db108e846680ff0949f8e10dae7
[ "Apache-2.0" ]
null
null
null
MultiPlatformLibrary/src/commonMain/kotlin/me/randheer/covidstatsin/domain/model/DistrictUiModel.kt
randheercode/CovidStatsIn
fba8818238e45db108e846680ff0949f8e10dae7
[ "Apache-2.0" ]
null
null
null
MultiPlatformLibrary/src/commonMain/kotlin/me/randheer/covidstatsin/domain/model/DistrictUiModel.kt
randheercode/CovidStatsIn
fba8818238e45db108e846680ff0949f8e10dae7
[ "Apache-2.0" ]
null
null
null
package me.randheer.covidstatsin.domain.model import kotlinx.serialization.Serializable import me.randheer.covidstatsin.db.CovidDistrictStats import me.randheer.covidstatsin.domain.abstraction.Mapper import me.randheer.covidstatsin.utils.toDisplayFormat @Serializable class DistrictUiModel( val stateCode: String, val name: String, val confirmed: String, val deceased: String, val recovered: String, val tested: String, val vaccinated1: String, val vaccinated2: String ) { val confirmedTitle: String = "Confirmed" val deceasedTitle: String = "Deceased" val recoveredTitle: String = "Recovered" val testedTitle: String = "Tested" val vaccinated1Title: String = "Partially Vaccinated" val vaccinated2Title: String = "Fully Vaccinated" } class DistrictUiModelMapper : Mapper<CovidDistrictStats, DistrictUiModel> { override fun map(input: CovidDistrictStats): DistrictUiModel { return DistrictUiModel( stateCode = input.stateCode, name = input.name, confirmed = input.confirmed.toDisplayFormat(), deceased = input.deceased.toDisplayFormat(), recovered = input.recovered.toDisplayFormat(), tested = input.tested.toDisplayFormat(), vaccinated1 = input.vaccinated1.toDisplayFormat(), vaccinated2 = input.vaccinated2.toDisplayFormat() ) } }
34.439024
75
0.709632
2a44aacc3fcdd3c878caded329fa9082d95d4143
7,453
java
Java
src/de.hpi.swa.trufflesqueak/src/de/hpi/swa/trufflesqueak/model/WeakVariablePointersObject.java
LinqLover/trufflesqueak
1a49ae5b8ddd69079164508baca4c474ef405cde
[ "MIT" ]
null
null
null
src/de.hpi.swa.trufflesqueak/src/de/hpi/swa/trufflesqueak/model/WeakVariablePointersObject.java
LinqLover/trufflesqueak
1a49ae5b8ddd69079164508baca4c474ef405cde
[ "MIT" ]
null
null
null
src/de.hpi.swa.trufflesqueak/src/de/hpi/swa/trufflesqueak/model/WeakVariablePointersObject.java
LinqLover/trufflesqueak
1a49ae5b8ddd69079164508baca4c474ef405cde
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-2020 Software Architecture Group, Hasso Plattner Institute * * Licensed under the MIT License. */ package de.hpi.swa.trufflesqueak.model; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.Arrays; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.profiles.BranchProfile; import com.oracle.truffle.api.profiles.ConditionProfile; import de.hpi.swa.trufflesqueak.image.SqueakImageChunk; import de.hpi.swa.trufflesqueak.image.SqueakImageContext; import de.hpi.swa.trufflesqueak.image.SqueakImageWriter; import de.hpi.swa.trufflesqueak.model.layout.ObjectLayout; import de.hpi.swa.trufflesqueak.nodes.SqueakGuards; import de.hpi.swa.trufflesqueak.nodes.accessing.AbstractPointersObjectNodes.AbstractPointersObjectWriteNode; import de.hpi.swa.trufflesqueak.nodes.accessing.SqueakObjectIdentityNode; import de.hpi.swa.trufflesqueak.util.ObjectGraphUtils.ObjectTracer; import de.hpi.swa.trufflesqueak.util.UnsafeUtils; public final class WeakVariablePointersObject extends AbstractPointersObject { private static final WeakRef NIL_REF = new WeakRef(NilObject.SINGLETON); private WeakRef[] variablePart; public WeakVariablePointersObject(final SqueakImageContext image, final long hash, final ClassObject classObject) { super(image, hash, classObject); } public WeakVariablePointersObject(final SqueakImageContext image, final ClassObject classObject, final ObjectLayout layout, final int variableSize) { super(image, classObject, layout); variablePart = new WeakRef[variableSize]; Arrays.fill(variablePart, NIL_REF); } public WeakVariablePointersObject(final SqueakImageContext image, final ClassObject classObject, final int variableSize) { super(image, classObject); variablePart = new WeakRef[variableSize]; Arrays.fill(variablePart, NIL_REF); } private WeakVariablePointersObject(final WeakVariablePointersObject original) { super(original); variablePart = original.variablePart.clone(); } @Override public void fillin(final SqueakImageChunk chunk) { final AbstractPointersObjectWriteNode writeNode = AbstractPointersObjectWriteNode.getUncached(); final Object[] pointersObject = chunk.getPointers(); fillInLayoutAndExtensions(); final int instSize = getSqueakClass().getBasicInstanceSize(); for (int i = 0; i < instSize; i++) { writeNode.execute(this, i, pointersObject[i]); } variablePart = new WeakRef[pointersObject.length - instSize]; for (int i = instSize; i < pointersObject.length; i++) { putIntoVariablePartSlow(i - instSize, pointersObject[i]); } assert size() == pointersObject.length; } public void become(final WeakVariablePointersObject other) { becomeLayout(other); final WeakRef[] otherVariablePart = other.variablePart; other.variablePart = variablePart; variablePart = otherVariablePart; } @Override public int size() { return instsize() + variablePart.length; } public Object[] getVariablePart() { return variablePart; } public int getVariablePartSize() { return variablePart.length; } public Object getFromVariablePart(final int index) { return NilObject.nullToNil(UnsafeUtils.getWeakRef(variablePart, index).get()); } public Object getFromVariablePart(final int index, final ConditionProfile nilProfile) { return NilObject.nullToNil(UnsafeUtils.getWeakRef(variablePart, index).get(), nilProfile); } private void putIntoVariablePartSlow(final int index, final Object value) { putIntoVariablePart(index, value, BranchProfile.getUncached(), ConditionProfile.getUncached()); } public void putIntoVariablePart(final int index, final Object value, final BranchProfile nilProfile, final ConditionProfile primitiveProfile) { if (value == NilObject.SINGLETON) { nilProfile.enter(); UnsafeUtils.putWeakRef(variablePart, index, NIL_REF); } else { UnsafeUtils.putWeakRef(variablePart, index, new WeakRef(value, primitiveProfile.profile(SqueakGuards.isUsedJavaPrimitive(value)) ? null : image.weakPointersQueue)); } } public boolean pointsTo(final SqueakObjectIdentityNode identityNode, final Object thang) { return layoutValuesPointTo(identityNode, thang) || variablePartPointsTo(thang); } private boolean variablePartPointsTo(final Object thang) { for (final WeakRef weakRef : variablePart) { if (weakRef.get() == thang) { return true; } } return false; } public WeakVariablePointersObject shallowCopy() { return new WeakVariablePointersObject(this); } @Override public void pointersBecomeOneWay(final Object[] from, final Object[] to, final boolean copyHash) { layoutValuesBecomeOneWay(from, to, copyHash); final int variableSize = variablePart.length; if (variableSize > 0) { for (int i = 0; i < from.length; i++) { final Object fromPointer = from[i]; for (int j = 0; j < variableSize; j++) { final Object object = getFromVariablePart(j); if (object == fromPointer) { putIntoVariablePartSlow(j, to[i]); copyHash(fromPointer, to[i], copyHash); } } } } } @Override public void tracePointers(final ObjectTracer tracer) { super.traceLayoutObjects(tracer); /* Weak pointers excluded from tracing. */ } @Override public void write(final SqueakImageWriter writer) { if (super.writeHeaderAndLayoutObjects(writer)) { for (int i = 0; i < variablePart.length; i++) { /* * Since weak pointers are excluded from tracing, ignore (replace with nil) all * objects that have not been traced somewhere else. */ writer.writeObjectIfTracedElseNil(getFromVariablePart(i)); } } } @Override public String toString() { CompilerAsserts.neverPartOfCompilation(); final StringBuilder sb = new StringBuilder(64); if (variablePart.length > 0) { final Object referent = variablePart[0].get(); sb.append('[').append(referent); if (variablePart[0].isEnqueued()) { sb.append(" (marked as garbage)"); } if (variablePart.length > 1) { sb.append("..."); } sb.append(']'); } return sb.append(" a ").append(getSqueakClassName()).append(" @").append(Integer.toHexString(hashCode())).append(" of size ").append(variablePart.length).toString(); } /* * Final subclass for TruffleSqueak to help Graal's inlining (and to avoid corresponding * performance warnings. */ public static final class WeakRef extends WeakReference<Object> { public WeakRef(final Object referent) { super(referent); } public WeakRef(final Object referent, final ReferenceQueue<Object> q) { super(referent, q); } } }
38.417526
176
0.664565
b764bc64b123f14b283dadf9879e424f4def10a8
681
kt
Kotlin
app/src/main/java/ru/bilchuk/dictionary/presentation/gallery/ImageViewHolder.kt
Art-bond/DictionaryContentProvider
0395850a91941616cf50752242c924f1826e739f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/bilchuk/dictionary/presentation/gallery/ImageViewHolder.kt
Art-bond/DictionaryContentProvider
0395850a91941616cf50752242c924f1826e739f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/bilchuk/dictionary/presentation/gallery/ImageViewHolder.kt
Art-bond/DictionaryContentProvider
0395850a91941616cf50752242c924f1826e739f
[ "Apache-2.0" ]
null
null
null
package ru.bilchuk.dictionary.presentation.gallery import android.view.View import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import ru.bilchuk.dictionary.R import ru.bilchuk.dictionary.data.models.MediaStoreImage /** * Basic [RecyclerView.ViewHolder] for our gallery. */ class ImageViewHolder(view: View, onClick: (MediaStoreImage) -> Unit) : RecyclerView.ViewHolder(view) { val rootView = view val imageView: ImageView = view.findViewById(R.id.image) init { imageView.setOnClickListener { val image = rootView.tag as? MediaStoreImage ?: return@setOnClickListener onClick(image) } } }
29.608696
85
0.729809
578506fc9e9ee4eccce23110dd01405568267a39
2,158
h
C
heron/tmaster/src/cpp/manager/tcontroller.h
takeratta/heron
7b7c38594186f009741c62d379364b9b45d82b61
[ "Apache-2.0" ]
1
2021-06-29T07:00:10.000Z
2021-06-29T07:00:10.000Z
heron/tmaster/src/cpp/manager/tcontroller.h
kalimfaria/heron
d59bd016b826006e2af22c7a6452342f5e7d637c
[ "Apache-2.0" ]
null
null
null
heron/tmaster/src/cpp/manager/tcontroller.h
kalimfaria/heron
d59bd016b826006e2af22c7a6452342f5e7d637c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Twitter, 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. */ #ifndef __TCONTROLLER_H_ #define __TCONTROLLER_H_ #include "network/network.h" #include "proto/tmaster.pb.h" #include "basics/basics.h" namespace heron { namespace tmaster { class TMaster; class TController { public: TController(EventLoop* eventLoop, const NetworkOptions& options, TMaster* tmaster); virtual ~TController(); // Starts the controller sp_int32 Start(); // Called by the tmaster when it gets response form ckptmgr void HandleCleanStatefulCheckpointResponse(proto::system::StatusCode _status); private: // Handlers for the requests // In all the below handlers, the incoming _request // parameter is now owned by the // TController class as is the norm with HeronServer. void HandleActivateRequest(IncomingHTTPRequest* request); void HandleActivateRequestDone(IncomingHTTPRequest* request, proto::system::StatusCode); void HandleDeActivateRequest(IncomingHTTPRequest* request); void HandleDeActivateRequestDone(IncomingHTTPRequest* request, proto::system::StatusCode); void HandleCleanStatefulCheckpointRequest(IncomingHTTPRequest* request); void HandleCleanStatefulCheckpointRequestDone(IncomingHTTPRequest* request, proto::system::StatusCode); // We are a http server HTTPServer* http_server_; // our tmaster TMaster* tmaster_; // The callback to be called upon receiving clean stateful checkpoint response std::function<void(proto::system::StatusCode)> clean_stateful_checkpoint_cb_; }; } // namespace tmaster } // namespace heron #endif
32.208955
92
0.752549
f55fdd9a966d65456d57390d01b1f94ee4ff78bd
305
css
CSS
privacy/index.css
NeconixDotCom/TimeTracker
e24eb5dd21ee65b8f5f58bc119cf4cb82c88a52c
[ "MIT" ]
null
null
null
privacy/index.css
NeconixDotCom/TimeTracker
e24eb5dd21ee65b8f5f58bc119cf4cb82c88a52c
[ "MIT" ]
null
null
null
privacy/index.css
NeconixDotCom/TimeTracker
e24eb5dd21ee65b8f5f58bc119cf4cb82c88a52c
[ "MIT" ]
null
null
null
* { font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; line-height: 1.6em; } body { background-color: silver; } .main-container { background-color: white; margin: 0 auto; max-width: 600px; padding: 1em 2em 2em 2em; } h3 { color: dodgerblue; }
16.052632
103
0.67541
e7ea5fbf2a5ea893fa5d02bc075a60e6e8983358
4,580
py
Python
app/request.py
angelakarenzi5/News-Highlight
3eae6f743f9e5d9eb4ea80b29ae0e2c57dd0aa62
[ "Unlicense" ]
null
null
null
app/request.py
angelakarenzi5/News-Highlight
3eae6f743f9e5d9eb4ea80b29ae0e2c57dd0aa62
[ "Unlicense" ]
null
null
null
app/request.py
angelakarenzi5/News-Highlight
3eae6f743f9e5d9eb4ea80b29ae0e2c57dd0aa62
[ "Unlicense" ]
null
null
null
from app import app import urllib.request,json from .models import source from .models import article Source = source.Source Article = article.Article # Getting api key api_key = app.config['NEWS_API_KEY'] # Getting the source base url base_url = app.config["SOURCE_API_BASE_URL"] article_url = app.config["ARTICLE_API_BASE_URL"] def process_results(source_list): ''' Function that processes the source result and transform them to a list of Objects Args: source_list: A list of dictionaries that contain source details Returns : source_results: A list of source objects ''' source_results = [] for source_item in source_list: id = source_item.get('id') name = source_item.get('name') description= source_item.get('description') url = source_item.get('url') category = source_item.get('category') language = source_item.get('language') country = source_item.get('country') if url: source_object = Source(id,name,description,url,category,language,country) source_results.append(source_object) return source_results def get_sources(category): ''' Function that gets the json response to our url request ''' get_sources_url = base_url.format(category,api_key) with urllib.request.urlopen(get_sources_url) as url: get_sources_data = url.read() get_sources_response = json.loads(get_sources_data) source_results = None if get_sources_response['sources']: source_results_list = get_sources_response['sources'] source_results = process_results(source_results_list) return source_results def get_articles(category): ''' Function that gets the json response to our url request ''' get_articles_url = article_url.format(category,api_key) with urllib.request.urlopen(get_articles_url) as url: get_articles_data = url.read() get_articles_response = json.loads(get_articles_data) article_results = None if get_articles_response['articles']: article_results_list = get_articles_response['articles'] article_results = process_results(article_results_list) return article_results def get_source(id): get_sources_details_url = article_url.format(id,api_key) with urllib.request.urlopen(get_sources_details_url) as url: source_details_data = url.read() source_details_response = json.loads(source_details_data) source_object = None if source_details_response: id = source_details_response.get('id') name = source_details_response.get('name') description = source_details_response.get('description') url = source_details_response.get('url') category = source_details_response.get('category') language = source_details_response.get('language') country = source_details_response.get('country') source_object = Source(id,name,description,url,category,language,country) return source_object def process_articles(article_list): ''' Function that processes the article result and transform them to a list of Objects Args: article_list: A list of dictionaries that contain article details Returns : article_results: A list of article objects ''' article_results = [] for article_item in article_list: author = article_item.get('author') title = article_item.get('title') description= article_item.get('description') url =article_item.get('url') urlToImage = article_item.get('urlToImage') publishedAt = article_item.get('publishedAt') content = article_item.get('content') if url: article_object =Article(author,title,description, url, urlToImage,publishedAt,content) article_results.append(article_object) return article_results def get_articles(source): ''' Function that gets the json response to our url request ''' get_articles_url = article_url.format(source,api_key) with urllib.request.urlopen(get_articles_url) as url: get_articles_data = url.read() get_articles_response = json.loads(get_articles_data) article_results = None if get_articles_response['articles']: article_results_list = get_articles_response['articles'] article_results = process_articles(article_results_list) return article_results
31.156463
98
0.691921
e5dab46a9cc4b08cff3119f9a3046320b2ebf389
172
sql
SQL
Backend/migrations/0016.addTable-userGenreMeta.sql
PvanTurennout/IPSENH
13186221c027090404ed7d69ad08afbfcbc0782f
[ "MIT" ]
null
null
null
Backend/migrations/0016.addTable-userGenreMeta.sql
PvanTurennout/IPSENH
13186221c027090404ed7d69ad08afbfcbc0782f
[ "MIT" ]
null
null
null
Backend/migrations/0016.addTable-userGenreMeta.sql
PvanTurennout/IPSENH
13186221c027090404ed7d69ad08afbfcbc0782f
[ "MIT" ]
null
null
null
CREATE TABLE IF NOT EXISTS user_genre_meta ( user INT, genre VARCHAR(50), amount_played INT, PRIMARY KEY (user, genre), FOREIGN KEY (user) REFERENCES Users(userId) );
21.5
44
0.744186
1648aec156b1345ca3530540c9bafdd7df97ef65
25,937
h
C
Backends/Graphics5/Direct3D12/Sources/kinc/backend/graphics5/commandlist.c.h
foundry2D/Kinc
890baf38d0be53444ebfdeac8662479b23d169ea
[ "Zlib" ]
150
2017-01-18T17:13:00.000Z
2019-05-29T02:44:18.000Z
Backends/Graphics5/Direct3D12/Sources/kinc/backend/graphics5/commandlist.c.h
foundry2D/Kinc
890baf38d0be53444ebfdeac8662479b23d169ea
[ "Zlib" ]
116
2017-01-04T09:02:18.000Z
2019-05-29T11:10:30.000Z
Backends/Graphics5/Direct3D12/Sources/kinc/backend/graphics5/commandlist.c.h
foundry2D/Kinc
890baf38d0be53444ebfdeac8662479b23d169ea
[ "Zlib" ]
143
2017-01-24T16:26:15.000Z
2019-05-29T14:07:33.000Z
#include <kinc/graphics5/commandlist.h> #include <kinc/graphics5/constantbuffer.h> #include <kinc/graphics5/indexbuffer.h> #include <kinc/graphics5/pipeline.h> #include <kinc/graphics5/vertexbuffer.h> #include <kinc/window.h> extern ID3D12CommandQueue *commandQueue; extern kinc_g5_texture_t *currentTextures[textureCount]; extern kinc_g5_render_target_t *currentRenderTargets[textureCount]; /*const int constantBufferMultiply = 1024; int currentConstantBuffer = 0; ID3D12Resource* vertexConstantBuffer; ID3D12Resource* fragmentConstantBuffer; bool created = false; void createConstantBuffer() { if (created) return; created = true; device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(sizeof(vertexConstants) * constantBufferMultiply), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_GRAPHICS_PPV_ARGS(&vertexConstantBuffer)); void* p; vertexConstantBuffer->Map(0, nullptr, &p); ZeroMemory(p, sizeof(vertexConstants) * constantBufferMultiply); vertexConstantBuffer->Unmap(0, nullptr); device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(sizeof(fragmentConstants) * constantBufferMultiply), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_GRAPHICS_PPV_ARGS(&fragmentConstantBuffer)); fragmentConstantBuffer->Map(0, nullptr, &p); ZeroMemory(p, sizeof(fragmentConstants) * constantBufferMultiply); fragmentConstantBuffer->Unmap(0, nullptr); }*/ static UINT64 renderFenceValue = 0; static ID3D12Fence *renderFence; static HANDLE renderFenceEvent; static kinc_g5_render_target_t *currentRenderTarget = NULL; static int currentRenderTargetCount = 0; static D3D12_CPU_DESCRIPTOR_HANDLE targetDescriptors[16]; static void init() { static bool initialized = false; if (!initialized) { initialized = true; renderFenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL); device->lpVtbl->CreateFence(device, 0, D3D12_FENCE_FLAG_NONE, &IID_ID3D12Fence, &renderFence); } } /*void waitForFence(ID3D12Fence *fence, UINT64 completionValue, HANDLE waitEvent) { if (fence->GetCompletedValue() < completionValue) { fence->SetEventOnCompletion(completionValue, waitEvent); WaitForSingleObject(waitEvent, INFINITE); } }*/ static void graphicsFlush(struct kinc_g5_command_list *list, ID3D12CommandAllocator *commandAllocator) { list->impl._commandList->lpVtbl->Close(list->impl._commandList); list->impl.closed = true; ID3D12CommandList *commandLists[] = {(ID3D12CommandList *)list->impl._commandList}; commandQueue->lpVtbl->ExecuteCommandLists(commandQueue, 1, commandLists); commandQueue->lpVtbl->Signal(commandQueue, renderFence, ++renderFenceValue); } static void graphicsWait(struct kinc_g5_command_list *list, ID3D12CommandAllocator *commandAllocator) { waitForFence(renderFence, renderFenceValue, renderFenceEvent); commandAllocator->lpVtbl->Reset(commandAllocator); list->impl._commandList->lpVtbl->Reset(list->impl._commandList, commandAllocator, NULL); if (currentRenderTarget != NULL) { if (currentRenderTarget->impl.depthStencilDescriptorHeap != NULL) { D3D12_CPU_DESCRIPTOR_HANDLE heapStart = GetCPUDescriptorHandle(currentRenderTarget->impl.depthStencilDescriptorHeap); list->impl._commandList->lpVtbl->OMSetRenderTargets(list->impl._commandList, currentRenderTargetCount, &targetDescriptors[0], false, &heapStart); } else { list->impl._commandList->lpVtbl->OMSetRenderTargets(list->impl._commandList, currentRenderTargetCount, &targetDescriptors[0], false, NULL); } list->impl._commandList->lpVtbl->RSSetViewports(list->impl._commandList, 1, (D3D12_VIEWPORT *)&currentRenderTarget->impl.viewport); list->impl._commandList->lpVtbl->RSSetScissorRects(list->impl._commandList, 1, (D3D12_RECT *)&currentRenderTarget->impl.scissor); } } static void graphicsFlushAndWait(struct kinc_g5_command_list *list, ID3D12CommandAllocator *commandAllocator) { graphicsFlush(list, commandAllocator); graphicsWait(list, commandAllocator); } static int formatSize(DXGI_FORMAT format) { switch (format) { case DXGI_FORMAT_R32G32B32A32_FLOAT: return 16; case DXGI_FORMAT_R16G16B16A16_FLOAT: return 8; case DXGI_FORMAT_R16_FLOAT: return 2; case DXGI_FORMAT_R8_UNORM: return 1; default: return 4; } } void kinc_g5_command_list_init(struct kinc_g5_command_list *list) { init(); list->impl.closed = false; device->lpVtbl->CreateCommandAllocator(device, D3D12_COMMAND_LIST_TYPE_DIRECT, &IID_ID3D12CommandAllocator, &list->impl._commandAllocator); device->lpVtbl->CreateCommandList(device, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, list->impl._commandAllocator, NULL, &IID_ID3D12GraphicsCommandList, &list->impl._commandList); //_commandList->Close(); // createConstantBuffer(); list->impl._indexCount = 0; } void kinc_g5_command_list_destroy(struct kinc_g5_command_list *list) {} void kinc_g5_command_list_begin(struct kinc_g5_command_list *list) { if (list->impl.closed) { list->impl.closed = false; waitForFence(renderFence, list->impl.current_fence_value, renderFenceEvent); list->impl._commandAllocator->lpVtbl->Reset(list->impl._commandAllocator); list->impl._commandList->lpVtbl->Reset(list->impl._commandList, list->impl._commandAllocator, NULL); } } void kinc_g5_command_list_end(struct kinc_g5_command_list *list) { graphicsFlush(list, list->impl._commandAllocator); list->impl.current_fence_value = ++renderFenceValue; commandQueue->lpVtbl->Signal(commandQueue, renderFence, list->impl.current_fence_value); } void kinc_g5_command_list_clear(struct kinc_g5_command_list *list, kinc_g5_render_target_t *renderTarget, unsigned flags, unsigned color, float depth, int stencil) { if (flags & KINC_G5_CLEAR_COLOR) { float clearColor[] = {((color & 0x00ff0000) >> 16) / 255.0f, ((color & 0x0000ff00) >> 8) / 255.0f, (color & 0x000000ff) / 255.0f, ((color & 0xff000000) >> 24) / 255.0f}; list->impl._commandList->lpVtbl->ClearRenderTargetView(list->impl._commandList, GetCPUDescriptorHandle(renderTarget->impl.renderTargetDescriptorHeap), clearColor, 0, NULL); } if ((flags & KINC_G5_CLEAR_DEPTH) || (flags & KINC_G5_CLEAR_STENCIL)) { D3D12_CLEAR_FLAGS d3dflags = (flags & KINC_G5_CLEAR_DEPTH) && (flags & KINC_G5_CLEAR_STENCIL) ? D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL : (flags & KINC_G5_CLEAR_DEPTH) ? D3D12_CLEAR_FLAG_DEPTH : D3D12_CLEAR_FLAG_STENCIL; list->impl._commandList->lpVtbl->ClearDepthStencilView(list->impl._commandList, GetCPUDescriptorHandle(renderTarget->impl.depthStencilDescriptorHeap), d3dflags, depth, stencil, 0, NULL); } } void kinc_g5_command_list_render_target_to_framebuffer_barrier(struct kinc_g5_command_list *list, kinc_g5_render_target_t *renderTarget) { D3D12_RESOURCE_BARRIER barrier; barrier.Transition.pResource = renderTarget->impl.renderTarget; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; list->impl._commandList->lpVtbl->ResourceBarrier(list->impl._commandList, 1, &barrier); } void kinc_g5_command_list_framebuffer_to_render_target_barrier(struct kinc_g5_command_list *list, kinc_g5_render_target_t *renderTarget) { D3D12_RESOURCE_BARRIER barrier; barrier.Transition.pResource = renderTarget->impl.renderTarget; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; list->impl._commandList->lpVtbl->ResourceBarrier(list->impl._commandList, 1, &barrier); } void kinc_g5_command_list_texture_to_render_target_barrier(struct kinc_g5_command_list *list, kinc_g5_render_target_t *renderTarget) { if (renderTarget->impl.resourceState != RenderTargetResourceStateRenderTarget) { D3D12_RESOURCE_BARRIER barrier; barrier.Transition.pResource = renderTarget->impl.renderTarget; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; list->impl._commandList->lpVtbl->ResourceBarrier(list->impl._commandList, 1, &barrier); renderTarget->impl.resourceState = RenderTargetResourceStateRenderTarget; } } void kinc_g5_command_list_render_target_to_texture_barrier(struct kinc_g5_command_list *list, kinc_g5_render_target_t *renderTarget) { if (renderTarget->impl.resourceState != RenderTargetResourceStateTexture) { D3D12_RESOURCE_BARRIER barrier; barrier.Transition.pResource = renderTarget->impl.renderTarget; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; list->impl._commandList->lpVtbl->ResourceBarrier(list->impl._commandList, 1, &barrier); renderTarget->impl.resourceState = RenderTargetResourceStateTexture; } } void kinc_g5_command_list_set_pipeline_layout(struct kinc_g5_command_list *list) { kinc_g5_internal_setConstants(list->impl._commandList, list->impl._currentPipeline); } void kinc_g5_command_list_set_vertex_constant_buffer(struct kinc_g5_command_list *list, kinc_g5_constant_buffer_t *buffer, int offset, size_t size) { #ifdef KORE_DXC if (list->impl._currentPipeline->impl.vertexConstantsSize > 0) { if (list->impl._currentPipeline->impl.textures > 0) { list->impl._commandList->SetGraphicsRootConstantBufferView(2, buffer->impl.constant_buffer->GetGPUVirtualAddress() + offset); } else { list->impl._commandList->SetGraphicsRootConstantBufferView(0, buffer->impl.constant_buffer->GetGPUVirtualAddress() + offset); } } #else list->impl._commandList->lpVtbl->SetGraphicsRootConstantBufferView( list->impl._commandList, 2, buffer->impl.constant_buffer->lpVtbl->GetGPUVirtualAddress(buffer->impl.constant_buffer) + offset); #endif } void kinc_g5_command_list_set_fragment_constant_buffer(struct kinc_g5_command_list *list, kinc_g5_constant_buffer_t *buffer, int offset, size_t size) { #ifdef KORE_DXC if (list->impl._currentPipeline->impl.fragmentConstantsSize > 0) { // list->impl._commandList->SetGraphicsRootConstantBufferView(3, buffer->impl.constant_buffer->GetGPUVirtualAddress() + offset); } #else list->impl._commandList->lpVtbl->SetGraphicsRootConstantBufferView( list->impl._commandList, 3, buffer->impl.constant_buffer->lpVtbl->GetGPUVirtualAddress(buffer->impl.constant_buffer) + offset); #endif } void kinc_g5_command_list_draw_indexed_vertices(struct kinc_g5_command_list *list) { kinc_g5_command_list_draw_indexed_vertices_from_to(list, 0, list->impl._indexCount); } void kinc_g5_command_list_draw_indexed_vertices_from_to(struct kinc_g5_command_list *list, int start, int count) { list->impl._commandList->lpVtbl->IASetPrimitiveTopology(list->impl._commandList, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); /*u8* data; D3D12_RANGE range; range.Begin = currentConstantBuffer * sizeof(vertexConstants); range.End = range.Begin + sizeof(vertexConstants); vertexConstantBuffer->Map(0, &range, (void**)&data); memcpy(data + currentConstantBuffer * sizeof(vertexConstants), vertexConstants, sizeof(vertexConstants)); vertexConstantBuffer->Unmap(0, &range); range.Begin = currentConstantBuffer * sizeof(fragmentConstants); range.End = range.Begin + sizeof(fragmentConstants); fragmentConstantBuffer->Map(0, &range, (void**)&data); memcpy(data + currentConstantBuffer * sizeof(fragmentConstants), fragmentConstants, sizeof(fragmentConstants)); fragmentConstantBuffer->Unmap(0, &range); _commandList->SetGraphicsRootConstantBufferView(1, vertexConstantBuffer->GetGPUVirtualAddress() + currentConstantBuffer * sizeof(vertexConstants)); _commandList->SetGraphicsRootConstantBufferView(2, fragmentConstantBuffer->GetGPUVirtualAddress() + currentConstantBuffer * sizeof(fragmentConstants)); ++currentConstantBuffer; if (currentConstantBuffer >= constantBufferMultiply) { currentConstantBuffer = 0; }*/ list->impl._commandList->lpVtbl->DrawIndexedInstanced(list->impl._commandList, count, 1, start, 0, 0); } void kinc_g5_command_list_draw_indexed_vertices_from_to_from(struct kinc_g5_command_list *list, int start, int count, int vertex_offset) { list->impl._commandList->lpVtbl->IASetPrimitiveTopology(list->impl._commandList, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); list->impl._commandList->lpVtbl->DrawIndexedInstanced(list->impl._commandList, count, 1, start, vertex_offset, 0); } void kinc_g5_command_list_draw_indexed_vertices_instanced(kinc_g5_command_list_t *list, int instanceCount) { kinc_g5_command_list_draw_indexed_vertices_instanced_from_to(list, instanceCount, 0, list->impl._indexCount); } void kinc_g5_command_list_draw_indexed_vertices_instanced_from_to(kinc_g5_command_list_t *list, int instanceCount, int start, int count) { list->impl._commandList->lpVtbl->IASetPrimitiveTopology(list->impl._commandList, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); list->impl._commandList->lpVtbl->DrawIndexedInstanced(list->impl._commandList, count, instanceCount, start, 0, 0); } void kinc_g5_command_list_execute_and_wait(struct kinc_g5_command_list *list) { graphicsFlushAndWait(list, list->impl._commandAllocator); } void kinc_g5_command_list_execute(struct kinc_g5_command_list *list) { graphicsFlush(list, list->impl._commandAllocator); } bool kinc_g5_non_pow2_textures_qupported(void) { return true; } void kinc_g5_command_list_viewport(struct kinc_g5_command_list *list, int x, int y, int width, int height) { D3D12_VIEWPORT viewport; viewport.TopLeftX = (float)x; viewport.TopLeftY = (float)y; viewport.Width = (float)width; viewport.Height = (float)height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; list->impl._commandList->lpVtbl->RSSetViewports(list->impl._commandList, 1, &viewport); } void kinc_g5_command_list_scissor(struct kinc_g5_command_list *list, int x, int y, int width, int height) { D3D12_RECT scissor; scissor.left = x; scissor.top = y; scissor.right = x + width; scissor.bottom = y + height; list->impl._commandList->lpVtbl->RSSetScissorRects(list->impl._commandList, 1, &scissor); } void kinc_g5_command_list_disable_scissor(struct kinc_g5_command_list *list) { if (currentRenderTarget != NULL) { list->impl._commandList->lpVtbl->RSSetScissorRects(list->impl._commandList, 1, (D3D12_RECT *)&currentRenderTarget->impl.scissor); } else { D3D12_RECT scissor; scissor.left = 0; scissor.top = 0; scissor.right = kinc_window_width(0); scissor.bottom = kinc_window_height(0); list->impl._commandList->lpVtbl->RSSetScissorRects(list->impl._commandList, 1, &scissor); } } void kinc_g5_command_list_set_pipeline(struct kinc_g5_command_list *list, kinc_g5_pipeline_t *pipeline) { list->impl._currentPipeline = pipeline; list->impl._commandList->lpVtbl->SetPipelineState(list->impl._commandList, pipeline->impl.pso); for (int i = 0; i < textureCount; ++i) { currentRenderTargets[i] = NULL; currentTextures[i] = NULL; } } void kinc_g5_command_list_set_vertex_buffers(struct kinc_g5_command_list *list, kinc_g5_vertex_buffer_t **buffers, int *offsets, int count) { D3D12_VERTEX_BUFFER_VIEW *views = (D3D12_VERTEX_BUFFER_VIEW *)alloca(sizeof(D3D12_VERTEX_BUFFER_VIEW) * count); ZeroMemory(views, sizeof(D3D12_VERTEX_BUFFER_VIEW) * count); for (int i = 0; i < count; ++i) { views[i].BufferLocation = buffers[i]->impl.uploadBuffer->lpVtbl->GetGPUVirtualAddress(buffers[i]->impl.uploadBuffer) + offsets[i] * kinc_g5_vertex_buffer_stride(buffers[i]); views[i].SizeInBytes = (kinc_g5_vertex_buffer_count(buffers[i]) - offsets[i]) * kinc_g5_vertex_buffer_stride(buffers[i]); views[i].StrideInBytes = kinc_g5_vertex_buffer_stride(buffers[i]); // * kinc_g5_vertex_buffer_count(buffers[i]); } list->impl._commandList->lpVtbl->IASetVertexBuffers(list->impl._commandList, 0, count, views); } void kinc_g5_command_list_set_index_buffer(struct kinc_g5_command_list *list, kinc_g5_index_buffer_t *buffer) { list->impl._indexCount = kinc_g5_index_buffer_count(buffer); list->impl._commandList->lpVtbl->IASetIndexBuffer(list->impl._commandList, (D3D12_INDEX_BUFFER_VIEW *)&buffer->impl.index_buffer_view); } void kinc_g5_command_list_set_render_targets(struct kinc_g5_command_list *list, kinc_g5_render_target_t **targets, int count) { currentRenderTarget = targets[0]; currentRenderTargetCount = count; for (int i = 0; i < count; ++i) { targetDescriptors[i] = GetCPUDescriptorHandle(targets[i]->impl.renderTargetDescriptorHeap); } graphicsFlushAndWait(list, list->impl._commandAllocator); } void kinc_g5_command_list_upload_vertex_buffer(kinc_g5_command_list_t *list, struct kinc_g5_vertex_buffer *buffer) {} void kinc_g5_command_list_upload_index_buffer(kinc_g5_command_list_t *list, kinc_g5_index_buffer_t *buffer) { kinc_g5_internal_index_buffer_upload(buffer, list->impl._commandList); } void kinc_g5_command_list_upload_texture(kinc_g5_command_list_t *list, kinc_g5_texture_t *texture) { D3D12_RESOURCE_DESC Desc = D3D12ResourceGetDesc(texture->impl.image); ID3D12Device *device; texture->impl.image->lpVtbl->GetDevice(texture->impl.image, &IID_ID3D12Device, &device); D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint; device->lpVtbl->GetCopyableFootprints(device, &Desc, 0, 1, 0, &footprint, NULL, NULL, NULL); device->lpVtbl->Release(device); D3D12_TEXTURE_COPY_LOCATION source = {0}; source.pResource = texture->impl.uploadImage; source.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; source.PlacedFootprint = footprint; D3D12_TEXTURE_COPY_LOCATION destination = {0}; destination.pResource = texture->impl.image; destination.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; destination.SubresourceIndex = 0; list->impl._commandList->lpVtbl->CopyTextureRegion(list->impl._commandList, &destination, 0, 0, 0, &source, NULL); D3D12_RESOURCE_BARRIER transition = {0}; transition.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; transition.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; transition.Transition.pResource = texture->impl.image; transition.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; transition.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; transition.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; list->impl._commandList->lpVtbl->ResourceBarrier(list->impl._commandList, 1, &transition); } #if defined(KORE_WINDOWS) || defined(KORE_WINDOWSAPP) static int d3d12_textureAlignment() { return D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; } #else int d3d12_textureAlignment(); #endif void kinc_g5_command_list_get_render_target_pixels(kinc_g5_command_list_t *list, kinc_g5_render_target_t *render_target, uint8_t *data) { DXGI_FORMAT dxgiFormat = D3D12ResourceGetDesc(render_target->impl.renderTarget).Format; int formatByteSize = formatSize(dxgiFormat); int rowPitch = render_target->texWidth * formatByteSize; int align = rowPitch % d3d12_textureAlignment(); if (align != 0) rowPitch = rowPitch + (d3d12_textureAlignment() - align); // Create readback buffer if (render_target->impl.renderTargetReadback == NULL) { D3D12_HEAP_PROPERTIES heapProperties; heapProperties.Type = D3D12_HEAP_TYPE_READBACK; heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProperties.CreationNodeMask = 1; heapProperties.VisibleNodeMask = 1; D3D12_RESOURCE_DESC resourceDesc; resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; resourceDesc.Alignment = 0; resourceDesc.Width = rowPitch * render_target->texHeight; resourceDesc.Height = 1; resourceDesc.DepthOrArraySize = 1; resourceDesc.MipLevels = 1; resourceDesc.Format = DXGI_FORMAT_UNKNOWN; resourceDesc.SampleDesc.Count = 1; resourceDesc.SampleDesc.Quality = 0; resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; device->lpVtbl->CreateCommittedResource(device, &heapProperties, D3D12_HEAP_FLAG_NONE, &resourceDesc, D3D12_RESOURCE_STATE_COPY_DEST, NULL, &IID_ID3D12Resource, &render_target->impl.renderTargetReadback); } // Copy render target to readback buffer D3D12_RESOURCE_STATES sourceState = render_target->impl.resourceState == RenderTargetResourceStateRenderTarget ? D3D12_RESOURCE_STATE_RENDER_TARGET : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; { D3D12_RESOURCE_BARRIER barrier; barrier.Transition.pResource = render_target->impl.renderTarget; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.StateBefore = sourceState; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; list->impl._commandList->lpVtbl->ResourceBarrier(list->impl._commandList, 1, &barrier); } D3D12_TEXTURE_COPY_LOCATION source; source.pResource = render_target->impl.renderTarget; source.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; source.SubresourceIndex = 0; D3D12_TEXTURE_COPY_LOCATION dest; dest.pResource = render_target->impl.renderTargetReadback; dest.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; dest.PlacedFootprint.Offset = 0; dest.PlacedFootprint.Footprint.Format = dxgiFormat; dest.PlacedFootprint.Footprint.Width = render_target->texWidth; dest.PlacedFootprint.Footprint.Height = render_target->texHeight; dest.PlacedFootprint.Footprint.Depth = 1; dest.PlacedFootprint.Footprint.RowPitch = rowPitch; list->impl._commandList->lpVtbl->CopyTextureRegion(list->impl._commandList, &dest, 0, 0, 0, &source, NULL); { D3D12_RESOURCE_BARRIER barrier; barrier.Transition.pResource = render_target->impl.renderTarget; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; barrier.Transition.StateAfter = sourceState; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; list->impl._commandList->lpVtbl->ResourceBarrier(list->impl._commandList, 1, &barrier); } graphicsFlushAndWait(list, list->impl._commandAllocator); // Read buffer void *p; render_target->impl.renderTargetReadback->lpVtbl->Map(render_target->impl.renderTargetReadback, 0, NULL, &p); memcpy(data, p, render_target->texWidth * render_target->texHeight * formatByteSize); render_target->impl.renderTargetReadback->lpVtbl->Unmap(render_target->impl.renderTargetReadback, 0, NULL); } void kinc_g5_command_list_compute(kinc_g5_command_list_t *list, int x, int y, int z) { list->impl._commandList->lpVtbl->Dispatch(list->impl._commandList, x, y, z); } void kinc_g5_command_list_set_texture_addressing(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit, kinc_g5_texture_direction_t dir, kinc_g5_texture_addressing_t addressing) {} void kinc_g5_command_list_set_texture_magnification_filter(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t texunit, kinc_g5_texture_filter_t filter) { bilinearFiltering = filter != KINC_G5_TEXTURE_FILTER_POINT; } void kinc_g5_command_list_set_texture_minification_filter(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t texunit, kinc_g5_texture_filter_t filter) { bilinearFiltering = filter != KINC_G5_TEXTURE_FILTER_POINT; } void kinc_g5_command_list_set_texture_mipmap_filter(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t texunit, kinc_g5_mipmap_filter_t filter) {} void kinc_g5_command_list_set_render_target_face(kinc_g5_command_list_t *list, kinc_g5_render_target_t *texture, int face) {} /* void Graphics5::setVertexBuffers(VertexBuffer** buffers, int count) { buffers[0]->_set(0); } void Graphics5::setIndexBuffer(IndexBuffer& buffer) { buffer._set(); } */ void kinc_g5_command_list_set_texture(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit, kinc_g5_texture_t *texture) { kinc_g5_internal_texture_set(texture, unit.impl.unit); } bool kinc_g5_command_list_init_occlusion_query(kinc_g5_command_list_t *list, unsigned *occlusionQuery) { return false; } void kinc_g5_command_list_set_image_texture(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit, kinc_g5_texture_t *texture) {} void kinc_g5_command_list_delete_occlusion_query(kinc_g5_command_list_t *list, unsigned occlusionQuery) {} void kinc_g5_command_list_render_occlusion_query(kinc_g5_command_list_t *list, unsigned occlusionQuery, int triangles) {} bool kinc_g5_command_list_are_query_results_available(kinc_g5_command_list_t *list, unsigned occlusionQuery) { return false; } void kinc_g5_command_list_get_query_result(kinc_g5_command_list_t *list, unsigned occlusionQuery, unsigned *pixelCount) {} /*void Graphics5::setPipeline(PipelineState* pipeline) { pipeline->set(pipeline); }*/
47.158182
157
0.795967
3b2ca582eac62c04b4c8610ce4e62f718189eec2
569
c
C
examples/10_dokonale_cislo.c
Wanzaz/test_2
41ee70b16ecbbe0d4fb22e3b873cd8848f6c98ad
[ "MIT" ]
null
null
null
examples/10_dokonale_cislo.c
Wanzaz/test_2
41ee70b16ecbbe0d4fb22e3b873cd8848f6c98ad
[ "MIT" ]
null
null
null
examples/10_dokonale_cislo.c
Wanzaz/test_2
41ee70b16ecbbe0d4fb22e3b873cd8848f6c98ad
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> /*10. Je celé číslo n dokonalé? U dokonalého čísla platí, že se rovná součtu svých dělitelů. Např. 6 = 1 + 2 + 3*/ int dokonale(int n) { int i, s=0; for(i=1; i<= n/2; i++) { if(n%i==0) s = s + i; } if(s==n) //return (s==n); return 1; else return 0; } int main() { int n; printf("Enter number: "); scanf("%d", &n); if (dokonale(n)==1) printf("Cislo %d je dokonale", n); else printf("Cislo %d neni dokonale", n); return 0; }
16.257143
114
0.492091
2a10cb28ad7b153f89d1c5f2bf3f69641c519dcd
1,282
java
Java
grandroid-core/src/main/java/com/grasea/grandroid/adapter/RecyclerItemConfig.java
Grasea/Grandroid2
662c3e9ca379b6bb7bd58496fd1fa49faa0181c0
[ "Apache-2.0" ]
4
2016-07-13T14:46:33.000Z
2019-05-22T09:16:38.000Z
grandroid-core/src/main/java/com/grasea/grandroid/adapter/RecyclerItemConfig.java
Grasea/Grandroid2
662c3e9ca379b6bb7bd58496fd1fa49faa0181c0
[ "Apache-2.0" ]
null
null
null
grandroid-core/src/main/java/com/grasea/grandroid/adapter/RecyclerItemConfig.java
Grasea/Grandroid2
662c3e9ca379b6bb7bd58496fd1fa49faa0181c0
[ "Apache-2.0" ]
2
2019-05-22T09:16:41.000Z
2021-06-28T16:15:30.000Z
package com.grasea.grandroid.adapter; /** * Copyright (C) 2016 Alan Ding * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 android.support.v7.widget.RecyclerView; /** * Created by Alan Ding on 2016/5/27. */ public class RecyclerItemConfig<VH extends RecyclerView.ViewHolder> { public int itemIds; public Class<VH> vhClass; public RecyclerItemConfig() { boolean hasItemLayout = this.getClass().isAnnotationPresent(ItemConfig.class); if (!hasItemLayout) { throw new NullPointerException("Didn't find any ItemLayout annotation."); } ItemConfig annotation = this.getClass().getAnnotation(ItemConfig.class); itemIds = annotation.id(); vhClass = annotation.viewHolder(); } }
33.736842
86
0.706708
d6793b0aba6b72a767653a242e63abb361e32347
3,041
swift
Swift
LineSDK/LineSDK/Networking/Images/ImageManager.swift
dodiwahyu/line-sdk-ios-swift
d9bc605d9f1c14465eb56aadc1f5c3d4cdc2b7e4
[ "Apache-2.0" ]
739
2018-11-20T06:19:45.000Z
2022-03-28T10:53:21.000Z
LineSDK/LineSDK/Networking/Images/ImageManager.swift
dodiwahyu/line-sdk-ios-swift
d9bc605d9f1c14465eb56aadc1f5c3d4cdc2b7e4
[ "Apache-2.0" ]
89
2018-11-20T08:50:26.000Z
2022-02-24T03:06:31.000Z
LineSDK/LineSDK/Networking/Images/ImageManager.swift
dodiwahyu/line-sdk-ios-swift
d9bc605d9f1c14465eb56aadc1f5c3d4cdc2b7e4
[ "Apache-2.0" ]
89
2018-11-20T07:03:29.000Z
2022-03-04T10:17:07.000Z
// // ImageManager.swift // // Copyright (c) 2016-present, LINE Corporation. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by LINE Corporation. // // As with any software that integrates with the LINE Corporation platform, your use of this software // is subject to the LINE Developers Agreement [http://terms2.line.me/LINE_Developers_Agreement]. // This copyright 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. // import UIKit typealias ImageSettingResult = Result<UIImage, LineSDKError> class ImageManager { typealias TaskToken = UInt private var currentToken: TaskToken = 0 func nextToken() -> TaskToken { if currentToken < TaskToken.max - 1 { currentToken += 1 } else { currentToken = 1 } return currentToken } static let shared = ImageManager() let downloader = ImageDownloader() let cache: NSCache<NSURL, UIImage> private init() { cache = NSCache() cache.countLimit = 500 } func getImage( _ url: URL, taskToken: TaskToken, callbackQueue: CallbackQueue = .currentMainOrAsync, completion: @escaping (ImageSettingResult, TaskToken) -> Void) { getImage(url, callbackQueue: callbackQueue) { completion($0, taskToken) } } func getImage( _ url: URL, callbackQueue: CallbackQueue = .currentMainOrAsync, completion: ((ImageSettingResult) -> Void)? = nil) { let nsURL = url as NSURL if let image = cache.object(forKey: nsURL) { if let completion = completion { callbackQueue.execute { completion(.success(image)) } } return } downloader.download(url: url, callbackQueue: callbackQueue) { result in let callbackResult: ImageSettingResult switch result { case .success(let image): self.cache.setObject(image, forKey: nsURL) callbackResult = .success(image) case .failure(let error): callbackResult = .failure(error) } if let completion = completion { callbackQueue.execute { completion(callbackResult) } } } } func purgeCache() { cache.removeAllObjects() } }
32.698925
102
0.644854
16c5ad86cd82ede7749039f69f9eab6aa6ad6753
1,381
kt
Kotlin
stopwatch-core/src/main/java/com/danielbostwick/stopwatch/core/service/DefaultStopwatchService.kt
bostwick/android-stopwatch
94735805b22592f077a40b5578d661983a57b42a
[ "BSD-3-Clause" ]
29
2015-02-25T23:04:31.000Z
2021-02-17T11:28:06.000Z
stopwatch-core/src/main/java/com/danielbostwick/stopwatch/core/service/DefaultStopwatchService.kt
bostwick/android-stopwatch
94735805b22592f077a40b5578d661983a57b42a
[ "BSD-3-Clause" ]
4
2016-04-28T18:25:07.000Z
2018-02-15T08:44:15.000Z
stopwatch-core/src/main/java/com/danielbostwick/stopwatch/core/service/DefaultStopwatchService.kt
bostwick/android-stopwatch
94735805b22592f077a40b5578d661983a57b42a
[ "BSD-3-Clause" ]
21
2015-02-25T23:04:28.000Z
2021-12-15T05:51:26.000Z
package com.danielbostwick.stopwatch.core.service import com.danielbostwick.stopwatch.core.model.Stopwatch import com.danielbostwick.stopwatch.core.model.StopwatchState.PAUSED import com.danielbostwick.stopwatch.core.model.StopwatchState.STARTED import org.joda.time.DateTime import org.joda.time.Duration import org.joda.time.Interval class DefaultStopwatchService : StopwatchService { override fun create() = Stopwatch(PAUSED, DateTime.now(), Duration.ZERO) override fun start(stopwatch: Stopwatch, startedAt: DateTime) = when (stopwatch.state) { PAUSED -> Stopwatch(STARTED, DateTime.now(), stopwatch.offset) STARTED -> stopwatch } override fun pause(stopwatch: Stopwatch, pausedAt: DateTime) = when (stopwatch.state) { PAUSED -> stopwatch STARTED -> Stopwatch(PAUSED, DateTime.now(), newOffset(stopwatch.offset, stopwatch.startedAt, pausedAt)) } override fun reset(stopwatch: Stopwatch) = create() override fun timeElapsed(stopwatch: Stopwatch, now: DateTime): Duration = when (stopwatch.state) { PAUSED -> stopwatch.offset STARTED -> stopwatch.offset.plus(Interval(stopwatch.startedAt, now).toDuration()) } private fun newOffset(existingOffset: Duration, startedAt: DateTime, pausedAt: DateTime) = existingOffset.plus(Interval(startedAt, pausedAt).toDuration()) }
39.457143
102
0.738595
77dc628b667e03b20e1edf93e26555d7ef12180a
348
lua
Lua
repositories/redis/luaScripts/increment.lua
EthanAmador/redis-luaScript
9aa3a5336fd68e5aaf7d54d7ad7e208458ddfcab
[ "MIT" ]
null
null
null
repositories/redis/luaScripts/increment.lua
EthanAmador/redis-luaScript
9aa3a5336fd68e5aaf7d54d7ad7e208458ddfcab
[ "MIT" ]
null
null
null
repositories/redis/luaScripts/increment.lua
EthanAmador/redis-luaScript
9aa3a5336fd68e5aaf7d54d7ad7e208458ddfcab
[ "MIT" ]
null
null
null
local function createIfNotExists(keyName) if redis.call('EXISTS',keyName) == 0 then redis.call('SET',keyName,0) end end local keyName = KEYS[1] local increment = ARGV[1] createIfNotExists(keyName) local keyValue = redis.call('GET',keyName); keyValue = keyValue + increment redis.call('SET', keyName,keyValue) return keyValue
29
45
0.718391
5b175b219a0692a2df8cd6b1cedfce902d4856fd
2,932
c
C
src/pack.c
macton/shannon-fano
e82a26939f34180aff25f5676dd9cc6392b78367
[ "BSD-3-Clause" ]
null
null
null
src/pack.c
macton/shannon-fano
e82a26939f34180aff25f5676dd9cc6392b78367
[ "BSD-3-Clause" ]
null
null
null
src/pack.c
macton/shannon-fano
e82a26939f34180aff25f5676dd9cc6392b78367
[ "BSD-3-Clause" ]
1
2019-06-13T12:15:36.000Z
2019-06-13T12:15:36.000Z
#include "main.h" static ptab ptable[MAPSIZE]; static char codes[MAPSIZE][256]; void pack(const char *input, const char *output) { #ifdef STAT clock_t time1, time2; time1 = clock(); #endif int c, i, j; FILE *infile = fopen(input, "r"); assert(infile); int size = ptablebuild(infile, ptable); encode(0, size - 1); printf("code table size: %d\n", size); #ifdef STAT FILE *codetable = fopen("codetable", "wb"); assert(codetable); for (i = 0; i < size; ++i) { fprintf(codetable, "%c %s %f \n", ptable[i].ch, codes[ptable[i].ch], ptable[i].p); printf("%c->%s\n", ptable[i].ch, codes[ptable[i].ch]); } fclose(codetable); #endif for (i = 0; i < size; ++i) printf("%c->%s\n", ptable[i].ch, codes[ptable[i].ch]); FILE *outfile = fopen(output, "wb"); assert(outfile); putc(size - 1, outfile); buffer buff; buff.size = buff.v = 0; char codesize[8], codebit[8], *ch; for (i = 0; i < size; ++i) { c = ptable[i].ch; chartobit(c, codebit); for (j = 0; j < 8; ++j) writebit(outfile, &buff, codebit[j]); // 8 bits of the code chartobit(strlen(codes[c]) - 1, codesize); for (j = 0; j < 8; ++j) writebit(outfile, &buff, codesize[j]); // size of code j = -1; ch = codes[c]; while (ch[++j] != '\0') writebit(outfile, &buff, ch[j]); // code } fseek(infile, 0, SEEK_SET); while ((c = getc(infile)) != EOF) { ch = codes[c]; j = -1; while (ch[++j] != '\0') writebit(outfile, &buff, ch[j]); } if (buff.size != 8) putc(buff.v, outfile); putc(buff.size, outfile); fclose(outfile); fclose(infile); #ifdef STAT time2 = clock(); printf("time:%f\n", (double)(time2 - time1) / (double)CLOCKS_PER_SEC); #endif } int ptablebuild(FILE *infile, ptab ptable[]) { int freq_table[MAPSIZE], i, c; unsigned long total = 0; for (i = 0; i < MAPSIZE; ++i) freq_table[i] = 0; while ((c = getc(infile)) != EOF) { freq_table[c]++; total++; } double ftot = (double)total; int size = 0; for (i = 0; i < MAPSIZE; ++i) { if (!freq_table[i]) continue; ptable[size].ch = i; ptable[size].p = (double)freq_table[i] / ftot; size++; } quicksort(ptable, 0, size); return size; } void encode(int li, int ri) { if (li == ri) return; int i, isp; float p, phalf; if (ri - li == 1) { charcat(codes[ptable[li].ch], '0'); charcat(codes[ptable[ri].ch], '1'); } else { phalf = 0; for(i = li; i <= ri; ++i) phalf += ptable[i].p; p = 0; isp = -1; phalf *= 0.5f; for(i = li; i <= ri; ++i) { if(p <= phalf) charcat(codes[ptable[i].ch], '0'); else { charcat(codes[ptable[i].ch], '1'); if(isp < 0) isp = i; } p += ptable[i].p; } if (isp < 0) isp = li + 1; encode(li, isp - 1); encode(isp, ri); } } void charcat(char s[], char t) { int i = 0; while (s[i] != '\0') i++; s[i++] = t; s[i++] = '\0'; }
16.947977
85
0.536835
86a289bcf9ce1febf6414ad4df0e8eaf8b9c59a9
1,985
rs
Rust
rust-hdl-pcb/src/kemet_ceramic_caps.rs
edgex004/rust-hdl
91e27f63a96137563c3e3aded06f7fc462d3ce8c
[ "MIT" ]
null
null
null
rust-hdl-pcb/src/kemet_ceramic_caps.rs
edgex004/rust-hdl
91e27f63a96137563c3e3aded06f7fc462d3ce8c
[ "MIT" ]
null
null
null
rust-hdl-pcb/src/kemet_ceramic_caps.rs
edgex004/rust-hdl
91e27f63a96137563c3e3aded06f7fc462d3ce8c
[ "MIT" ]
null
null
null
use rust_hdl_pcb_core::prelude::*; fn map_part_number_to_size(part: &str) -> SizeCode { (&part[1..=4]).parse().unwrap() } fn map_part_number_to_voltage(part: &str) -> f64 { match &part[10..11] { "9" => 6.3, "8" => 10.0, "4" => 16.0, "3" => 25.0, "6" => 35.0, "5" => 50.0, "1" => 100.0, "2" => 200.0, "A" => 250.0, _ => panic!("No working voltage for {}", part), } } fn map_part_number_to_dielectric(part: &str) -> DielectricCode { match &part[5..6] { "C" => DielectricCode::X7R, _ => panic!("Unknown dielectric code for Kemet {}", part), } } fn map_part_number_to_pf(part: &str) -> f64 { map_three_digit_cap_to_pf(&part[6..9]) } fn map_part_number_to_tolerance(part: &str) -> CapacitorTolerance { match &part[9..10] { "J" => CapacitorTolerance::FivePercent, "K" => CapacitorTolerance::TenPercent, "M" => CapacitorTolerance::TwentyPercent, _ => panic!("Unknon capacitor tolerance indicator {}", part), } } pub fn make_kemet_ceramic_capacitor(part_number: &str) -> CircuitNode { assert_eq!(&part_number[0..1], "C"); let size = map_part_number_to_size(part_number); let tolerance = map_part_number_to_tolerance(part_number); let value_pf = map_part_number_to_pf(part_number); let value = map_pf_to_label(value_pf); let dielectric = map_part_number_to_dielectric(part_number); let voltage = map_part_number_to_voltage(part_number); let label = format!("{} {} {}V {}", value, tolerance, voltage, dielectric); let manufacturer = Manufacturer { name: "Kemet".to_string(), part_number: part_number.to_owned(), }; let description = format!("Kemet X7R Series MLCC Capacitor SMD {} {}", size, label); make_mlcc( label, manufacturer, description, size, value_pf, dielectric, voltage, tolerance, ) }
29.626866
88
0.598992
3ef74a45487ef684eda81fe738c3e8bee9e2a584
2,861
h
C
src/ScoreTracker.h
syi47/spacebilliards
39a0a55761917144920a0a5ac4ff145a83d69a55
[ "Apache-2.0" ]
null
null
null
src/ScoreTracker.h
syi47/spacebilliards
39a0a55761917144920a0a5ac4ff145a83d69a55
[ "Apache-2.0" ]
null
null
null
src/ScoreTracker.h
syi47/spacebilliards
39a0a55761917144920a0a5ac4ff145a83d69a55
[ "Apache-2.0" ]
null
null
null
/* Copyright 2009 Tatham Johnson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <string> #include <vector> class Score { public: ///Constructor /** @param time Time, in Milliseconds, of the score @param name The name of the Player who owns the score **/ Score(int time, const std::string& name) : m_Time(time), m_Name(name) {} int Time() const { return m_Time; } ///< The time of the score const std::string& Name() const { return m_Name; } ///< The name of the player who owns the score bool operator<(const Score& rvalue) const { return m_Time < rvalue.Time(); } ///< Used to sort the scores private: int m_Time; std::string m_Name; }; class ScoreTracker { public: ///Constructor /** @param fileName The location of the file to save and load scores to/from **/ ScoreTracker(const std::string& fileName); ///Destructor ~ScoreTracker(void); ///Saves the scores to the file void save(); ///Loads the scores from the file void load(); ///Adds a score to the current scores. /** Note: does not automatically save the scores **/ void addScore(int time, const std::string& name); ///Rates a score against the current high scores /** @param time The time to test against the current high scores @return The high score that the time would displace, or -1 if not a high score **/ int rateScore(int time); ///Gets the number of scores currently stored /** @return The number of scores **/ int count() const {return m_Scores.size(); } ///Clears all the high scores /** This will clear all the scores stored inside the file as well **/ void clearScores(); ///Gets the score at the given index const Score& at(int index) const; ///Gets the score at the given index, using square bracket operators const Score& operator[](int index) const { return at(index); } ///Returns the index of the last score added int lastScoreIndex() { return m_LastScoreIndex; } private: private: ///Sorts the scores lowest (best) to highest (worst) void sortScores(); ///Removes scores from memory, but does not delete scores from disk void removeCachedScores(); private: std::string m_FileName; std::vector<Score> m_Scores; int m_LastScoreIndex; typedef std::vector<Score>::iterator ScoreIterator; };
29.802083
107
0.692765
72ba66a1ffade0abd7d9777fb505ec5a703b5441
4,797
lua
Lua
layout/stack.lua
ErikRoelofs/renderer
f0702d05752859a6d097f39e08ed97256e677f09
[ "MIT" ]
1
2016-09-26T18:49:36.000Z
2016-09-26T18:49:36.000Z
layout/stack.lua
ErikRoelofs/looky
f0702d05752859a6d097f39e08ed97256e677f09
[ "MIT" ]
null
null
null
layout/stack.lua
ErikRoelofs/looky
f0702d05752859a6d097f39e08ed97256e677f09
[ "MIT" ]
null
null
null
local renderChildren = function(self) self:renderBackground() local locX, locY = self:startCoordsBasedOnGravity() for k, v in ipairs(self.children) do love.graphics.push() love.graphics.translate( self.scaffold[v][1], self.scaffold[v][2]) v:render() love.graphics.pop() end end local function scaffoldViews(self) local hTilt, vTilt local tilt = function (number, direction) if self.tiltDirection[direction] == "start" then return (self.tiltAmount[direction] * (#self.children-1)) - (self.tiltAmount[direction] * number) elseif self.tiltDirection[direction] == "none" then return 0 elseif self.tiltDirection[direction] == "end" then return self.tiltAmount[direction] * number end end local locX, locY = self:startCoordsBasedOnGravity() for k, v in ipairs(self.children) do self.scaffold[v] = { locX + tilt(k-1, 1), locY + tilt(k-1, 2) } end end local function layout(self, children) local maxWidth = self:availableWidth() local maxHeight = self:availableHeight() for k, v in ipairs(children) do local childWidth, childHeight if v:desiredWidth() == "fill" then childWidth = maxWidth else childWidth = math.min(maxWidth, v:desiredWidth()) end if v:desiredHeight() == "fill" then childHeight = maxHeight else childHeight = math.min(maxHeight, v:desiredHeight()) end v:setDimensions(childWidth, childHeight) end for k, v in ipairs(children) do v:layoutingPass() end self:scaffoldViews() end local function containerWidth(self) local width = 0 for k, v in ipairs(self.children) do if v:desiredWidth() == "fill" then return "fill" else if v:desiredWidth() > width then width = v:desiredWidth() end end end return width + (self.tiltAmount[1] * #self.children) end local function containerHeight(self) local height = 0 for k, v in ipairs(self.children) do if v:desiredHeight() == "fill" then return "fill" else if v:desiredHeight() > height then height = v:desiredHeight() end end end height = height + (self.tiltAmount[2] * #self.children) return height end local function clickShouldTargetChild(self, x, y, child) local relativeX = x - self.scaffold[v][1] local relativeY = y - self.scaffold[v][2] return relativeX > 0 and relativeY > 0 and relativeX < child:getGrantedWidth() and relativeY < child:getGrantedHeight() end local function signalTargetedChildren(self, signal, payload) for i, v in ipairs(self:getChildren()) do if clickShouldTargetChild(self, payload.x, payload.y, child) then local thisPayload = { x = payload.x - self.scaffold[child][1] , y = payload.y - self.scaffold[child][2] } v:receiveSignal(signal, thisPayload) end end end return function(looky) return { build = function (options) local base = looky:makeBaseLayout(options) base.renderCustom = renderChildren base.layoutingPass = function(self) layout(self, self.children) end base.contentWidth = containerWidth base.contentHeight = containerHeight base.tiltDirection = options.tiltDirection or {"none", "none"} base.tiltAmount = options.tiltAmount or {0,0} base.scaffoldViews = scaffoldViews base.scaffold = {} base.getLocationOffset = getLocationOffset if not options.signalHandlers then options.signalHandlers = {} if not options.signalHandlers.leftclick then options.signalHandlers.leftclick = signalTargetedChildren end end base.signalHandlers = options.signalHandlers base.update = function(self, dt) for k, v in ipairs(self.children) do v:update(dt) end end base.translateCoordsToChild = function(self, child, x, y) return x - self.scaffold[child][1], y - self.scaffold[child][2] end base.translateCoordsFromChild = function(self, child, x, y) return x + self.scaffold[child][1], y + self.scaffold[child][2] end return base end, schema = looky:extendSchema("base", { tiltAmount = { required = false, schemaType = "table", options = { { required = true, schemaType = "number" }, { required = true, schemaType = "number" }, } }, tiltDirection = { required = false, schemaType = "table", options = { { required = true, schemaType = "fromList", list = { "start", "none", "end" } }, { required = true, schemaType = "fromList", list = { "start", "none", "end" } } } } }) } end
29.611111
111
0.631228
04108e947a54ae058a80cfc202a80959843732ca
124,295
js
JavaScript
tests/baked_texture_test/js/ThreeExtras.js
duhnnie/3-dreams-of-black
15aded97f57a82e5a4c95c4e74bcd603b3fc6e1e
[ "Apache-2.0" ]
475
2015-01-02T07:49:46.000Z
2022-03-17T04:01:47.000Z
tests/baked_texture_test/js/ThreeExtras.js
duhnnie/3-dreams-of-black
15aded97f57a82e5a4c95c4e74bcd603b3fc6e1e
[ "Apache-2.0" ]
3
2015-03-06T10:51:03.000Z
2019-09-10T19:39:39.000Z
tests/baked_texture_test/js/ThreeExtras.js
duhnnie/3-dreams-of-black
15aded97f57a82e5a4c95c4e74bcd603b3fc6e1e
[ "Apache-2.0" ]
130
2015-01-15T02:08:21.000Z
2021-12-20T19:15:22.000Z
// ThreeExtras.js r32 - http://github.com/mrdoob/three.js var THREE=THREE||{};THREE.Color=function(a){this.autoUpdate=true;this.setHex(a)}; THREE.Color.prototype={setRGB:function(a,b,d){this.r=a;this.g=b;this.b=d;if(this.autoUpdate){this.updateHex();this.updateStyleString()}},setHex:function(a){this.hex=~~a&16777215;if(this.autoUpdate){this.updateRGBA();this.updateStyleString()}},updateHex:function(){this.hex=~~(this.r*255)<<16^~~(this.g*255)<<8^~~(this.b*255)},updateRGBA:function(){this.r=(this.hex>>16&255)/255;this.g=(this.hex>>8&255)/255;this.b=(this.hex&255)/255},updateStyleString:function(){this.__styleString="rgb("+~~(this.r*255)+ ","+~~(this.g*255)+","+~~(this.b*255)+")"},clone:function(){return new THREE.Color(this.hex)},toString:function(){return"THREE.Color ( r: "+this.r+", g: "+this.g+", b: "+this.b+", hex: "+this.hex+" )"}};THREE.Vector2=function(a,b){this.x=a||0;this.y=b||0}; THREE.Vector2.prototype={set:function(a,b){this.x=a;this.y=b;return this},copy:function(a){this.x=a.x;this.y=a.y;return this},addSelf:function(a){this.x+=a.x;this.y+=a.y;return this},add:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},subSelf:function(a){this.x-=a.x;this.y-=a.y;return this},sub:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},unit:function(){this.multiplyScalar(1/this.length());return this},length:function(){return Math.sqrt(this.x* this.x+this.y*this.y)},lengthSq:function(){return this.x*this.x+this.y*this.y},negate:function(){this.x=-this.x;this.y=-this.y;return this},clone:function(){return new THREE.Vector2(this.x,this.y)},toString:function(){return"THREE.Vector2 ("+this.x+", "+this.y+")"}};THREE.Vector3=function(a,b,d){this.x=a||0;this.y=b||0;this.z=d||0}; THREE.Vector3.prototype={set:function(a,b,d){this.x=a;this.y=b;this.z=d;return this},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addSelf:function(a){this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},sub:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},subSelf:function(a){this.x-=a.x;this.y-=a.y;this.z-=a.z;return this}, cross:function(a,b){this.x=a.y*b.z-a.z*b.y;this.y=a.z*b.x-a.x*b.z;this.z=a.x*b.y-a.y*b.x;return this},crossSelf:function(a){var b=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-b*a.z;this.z=b*a.y-d*a.x;return this},multiply:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},multiplySelf:function(a){this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},divideSelf:function(a){this.x/=a.x;this.y/=a.y;this.z/= a.z;return this},divideScalar:function(a){this.x/=a;this.y/=a;this.z/=a;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},distanceTo:function(a){var b=this.x-a.x,d=this.y-a.y;a=this.z-a.z;return Math.sqrt(b*b+d*d+a*a)},distanceToSquared:function(a){var b=this.x-a.x,d=this.y-a.y;a=this.z-a.z;return b*b+d*d+a*a},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},negate:function(){this.x= -this.x;this.y=-this.y;this.z=-this.z;return this},normalize:function(){var a=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);a>0?this.multiplyScalar(1/a):this.set(0,0,0);return this},setLength:function(a){return this.normalize().multiplyScalar(a)},isZero:function(){return Math.abs(this.x)<1.0E-4&&Math.abs(this.y)<1.0E-4&&Math.abs(this.z)<1.0E-4},clone:function(){return new THREE.Vector3(this.x,this.y,this.z)},toString:function(){return"THREE.Vector3 ( "+this.x+", "+this.y+", "+this.z+" )"}}; THREE.Vector4=function(a,b,d,e){this.x=a||0;this.y=b||0;this.z=d||0;this.w=e||1}; THREE.Vector4.prototype={set:function(a,b,d,e){this.x=a;this.y=b;this.z=d;this.w=e;return this},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=a.w||1;return this},add:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addSelf:function(a){this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},sub:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},subSelf:function(a){this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w; return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},divideScalar:function(a){this.x/=a;this.y/=a;this.z/=a;this.w/=a;return this},lerpSelf:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b},clone:function(){return new THREE.Vector4(this.x,this.y,this.z,this.w)},toString:function(){return"THREE.Vector4 ("+this.x+", "+this.y+", "+this.z+", "+this.w+")"}}; THREE.Ray=function(a,b){this.origin=a||new THREE.Vector3;this.direction=b||new THREE.Vector3}; THREE.Ray.prototype={intersectScene:function(a){var b,d,e=a.objects,g=[];a=0;for(b=e.length;a<b;a++){d=e[a];if(d instanceof THREE.Mesh)g=g.concat(this.intersectObject(d))}g.sort(function(h,j){return h.distance-j.distance});return g},intersectObject:function(a){function b(H,s,K,o){o=o.clone().subSelf(s);K=K.clone().subSelf(s);var f=H.clone().subSelf(s);H=o.dot(o);s=o.dot(K);o=o.dot(f);var n=K.dot(K);K=K.dot(f);f=1/(H*n-s*s);n=(n*o-s*K)*f;H=(H*K-s*o)*f;return n>0&&H>0&&n+H<1}var d,e,g,h,j,c,k,m,p,z, q,v=a.geometry,A=v.vertices,B=[];d=0;for(e=v.faces.length;d<e;d++){g=v.faces[d];z=this.origin.clone();q=this.direction.clone();h=a.matrix.multiplyVector3(A[g.a].position.clone());j=a.matrix.multiplyVector3(A[g.b].position.clone());c=a.matrix.multiplyVector3(A[g.c].position.clone());k=g instanceof THREE.Face4?a.matrix.multiplyVector3(A[g.d].position.clone()):null;m=a.rotationMatrix.multiplyVector3(g.normal.clone());p=q.dot(m);if(p<0){m=m.dot((new THREE.Vector3).sub(h,z))/p;z=z.addSelf(q.multiplyScalar(m)); if(g instanceof THREE.Face3){if(b(z,h,j,c)){g={distance:this.origin.distanceTo(z),point:z,face:g,object:a};B.push(g)}}else if(g instanceof THREE.Face4)if(b(z,h,j,k)||b(z,j,c,k)){g={distance:this.origin.distanceTo(z),point:z,face:g,object:a};B.push(g)}}}return B}}; THREE.Rectangle=function(){function a(){h=e-b;j=g-d}var b,d,e,g,h,j,c=true;this.getX=function(){return b};this.getY=function(){return d};this.getWidth=function(){return h};this.getHeight=function(){return j};this.getLeft=function(){return b};this.getTop=function(){return d};this.getRight=function(){return e};this.getBottom=function(){return g};this.set=function(k,m,p,z){c=false;b=k;d=m;e=p;g=z;a()};this.addPoint=function(k,m){if(c){c=false;b=k;d=m;e=k;g=m}else{b=b<k?b:k;d=d<m?d:m;e=e>k?e:k;g=g>m? g:m}a()};this.add3Points=function(k,m,p,z,q,v){if(c){c=false;b=k<p?k<q?k:q:p<q?p:q;d=m<z?m<v?m:v:z<v?z:v;e=k>p?k>q?k:q:p>q?p:q;g=m>z?m>v?m:v:z>v?z:v}else{b=k<p?k<q?k<b?k:b:q<b?q:b:p<q?p<b?p:b:q<b?q:b;d=m<z?m<v?m<d?m:d:v<d?v:d:z<v?z<d?z:d:v<d?v:d;e=k>p?k>q?k>e?k:e:q>e?q:e:p>q?p>e?p:e:q>e?q:e;g=m>z?m>v?m>g?m:g:v>g?v:g:z>v?z>g?z:g:v>g?v:g}a()};this.addRectangle=function(k){if(c){c=false;b=k.getLeft();d=k.getTop();e=k.getRight();g=k.getBottom()}else{b=b<k.getLeft()?b:k.getLeft();d=d<k.getTop()?d:k.getTop(); e=e>k.getRight()?e:k.getRight();g=g>k.getBottom()?g:k.getBottom()}a()};this.inflate=function(k){b-=k;d-=k;e+=k;g+=k;a()};this.minSelf=function(k){b=b>k.getLeft()?b:k.getLeft();d=d>k.getTop()?d:k.getTop();e=e<k.getRight()?e:k.getRight();g=g<k.getBottom()?g:k.getBottom();a()};this.instersects=function(k){return Math.min(e,k.getRight())-Math.max(b,k.getLeft())>=0&&Math.min(g,k.getBottom())-Math.max(d,k.getTop())>=0};this.empty=function(){c=true;g=e=d=b=0;a()};this.isEmpty=function(){return c};this.toString= function(){return"THREE.Rectangle ( left: "+b+", right: "+e+", top: "+d+", bottom: "+g+", width: "+h+", height: "+j+" )"}};THREE.Matrix3=function(){this.m=[]};THREE.Matrix3.prototype={transpose:function(){var a,b=this.m;a=b[1];b[1]=b[3];b[3]=a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this}}; THREE.Matrix4=function(a,b,d,e,g,h,j,c,k,m,p,z,q,v,A,B){this.n11=a||1;this.n12=b||0;this.n13=d||0;this.n14=e||0;this.n21=g||0;this.n22=h||1;this.n23=j||0;this.n24=c||0;this.n31=k||0;this.n32=m||0;this.n33=p||1;this.n34=z||0;this.n41=q||0;this.n42=v||0;this.n43=A||0;this.n44=B||1;this.flat=Array(16);this.m33=new THREE.Matrix3}; THREE.Matrix4.prototype={identity:function(){this.n11=1;this.n21=this.n14=this.n13=this.n12=0;this.n22=1;this.n32=this.n31=this.n24=this.n23=0;this.n33=1;this.n43=this.n42=this.n41=this.n34=0;this.n44=1;return this},set:function(a,b,d,e,g,h,j,c,k,m,p,z,q,v,A,B){this.n11=a;this.n12=b;this.n13=d;this.n14=e;this.n21=g;this.n22=h;this.n23=j;this.n24=c;this.n31=k;this.n32=m;this.n33=p;this.n34=z;this.n41=q;this.n42=v;this.n43=A;this.n44=B;return this},copy:function(a){this.n11=a.n11;this.n12=a.n12;this.n13= a.n13;this.n14=a.n14;this.n21=a.n21;this.n22=a.n22;this.n23=a.n23;this.n24=a.n24;this.n31=a.n31;this.n32=a.n32;this.n33=a.n33;this.n34=a.n34;this.n41=a.n41;this.n42=a.n42;this.n43=a.n43;this.n44=a.n44;return this},lookAt:function(a,b,d){var e=THREE.Matrix4.__tmpVec1,g=THREE.Matrix4.__tmpVec2,h=THREE.Matrix4.__tmpVec3;h.sub(a,b).normalize();e.cross(d,h).normalize();g.cross(h,e).normalize();this.n11=e.x;this.n12=e.y;this.n13=e.z;this.n14=-e.dot(a);this.n21=g.x;this.n22=g.y;this.n23=g.z;this.n24=-g.dot(a); this.n31=h.x;this.n32=h.y;this.n33=h.z;this.n34=-h.dot(a);this.n43=this.n42=this.n41=0;this.n44=1;return this},multiplyVector3:function(a){var b=a.x,d=a.y,e=a.z,g=1/(this.n41*b+this.n42*d+this.n43*e+this.n44);a.x=(this.n11*b+this.n12*d+this.n13*e+this.n14)*g;a.y=(this.n21*b+this.n22*d+this.n23*e+this.n24)*g;a.z=(this.n31*b+this.n32*d+this.n33*e+this.n34)*g;return a},multiplyVector4:function(a){var b=a.x,d=a.y,e=a.z,g=a.w;a.x=this.n11*b+this.n12*d+this.n13*e+this.n14*g;a.y=this.n21*b+this.n22*d+this.n23* e+this.n24*g;a.z=this.n31*b+this.n32*d+this.n33*e+this.n34*g;a.w=this.n41*b+this.n42*d+this.n43*e+this.n44*g;return a},crossVector:function(a){var b=new THREE.Vector4;b.x=this.n11*a.x+this.n12*a.y+this.n13*a.z+this.n14*a.w;b.y=this.n21*a.x+this.n22*a.y+this.n23*a.z+this.n24*a.w;b.z=this.n31*a.x+this.n32*a.y+this.n33*a.z+this.n34*a.w;b.w=a.w?this.n41*a.x+this.n42*a.y+this.n43*a.z+this.n44*a.w:1;return b},multiply:function(a,b){var d=a.n11,e=a.n12,g=a.n13,h=a.n14,j=a.n21,c=a.n22,k=a.n23,m=a.n24,p=a.n31, z=a.n32,q=a.n33,v=a.n34,A=a.n41,B=a.n42,H=a.n43,s=a.n44,K=b.n11,o=b.n12,f=b.n13,n=b.n14,y=b.n21,r=b.n22,x=b.n23,L=b.n24,u=b.n31,C=b.n32,E=b.n33,D=b.n34,w=b.n41,N=b.n42,I=b.n43,T=b.n44;this.n11=d*K+e*y+g*u+h*w;this.n12=d*o+e*r+g*C+h*N;this.n13=d*f+e*x+g*E+h*I;this.n14=d*n+e*L+g*D+h*T;this.n21=j*K+c*y+k*u+m*w;this.n22=j*o+c*r+k*C+m*N;this.n23=j*f+c*x+k*E+m*I;this.n24=j*n+c*L+k*D+m*T;this.n31=p*K+z*y+q*u+v*w;this.n32=p*o+z*r+q*C+v*N;this.n33=p*f+z*x+q*E+v*I;this.n34=p*n+z*L+q*D+v*T;this.n41=A*K+B*y+ H*u+s*w;this.n42=A*o+B*r+H*C+s*N;this.n43=A*f+B*x+H*E+s*I;this.n44=A*n+B*L+H*D+s*T;return this},multiplySelf:function(a){var b=this.n11,d=this.n12,e=this.n13,g=this.n14,h=this.n21,j=this.n22,c=this.n23,k=this.n24,m=this.n31,p=this.n32,z=this.n33,q=this.n34,v=this.n41,A=this.n42,B=this.n43,H=this.n44,s=a.n11,K=a.n21,o=a.n31,f=a.n41,n=a.n12,y=a.n22,r=a.n32,x=a.n42,L=a.n13,u=a.n23,C=a.n33,E=a.n43,D=a.n14,w=a.n24,N=a.n34;a=a.n44;this.n11=b*s+d*K+e*o+g*f;this.n12=b*n+d*y+e*r+g*x;this.n13=b*L+d*u+e*C+g* E;this.n14=b*D+d*w+e*N+g*a;this.n21=h*s+j*K+c*o+k*f;this.n22=h*n+j*y+c*r+k*x;this.n23=h*L+j*u+c*C+k*E;this.n24=h*D+j*w+c*N+k*a;this.n31=m*s+p*K+z*o+q*f;this.n32=m*n+p*y+z*r+q*x;this.n33=m*L+p*u+z*C+q*E;this.n34=m*D+p*w+z*N+q*a;this.n41=v*s+A*K+B*o+H*f;this.n42=v*n+A*y+B*r+H*x;this.n43=v*L+A*u+B*C+H*E;this.n44=v*D+A*w+B*N+H*a;return this},multiplyScalar:function(a){this.n11*=a;this.n12*=a;this.n13*=a;this.n14*=a;this.n21*=a;this.n22*=a;this.n23*=a;this.n24*=a;this.n31*=a;this.n32*=a;this.n33*=a;this.n34*= a;this.n41*=a;this.n42*=a;this.n43*=a;this.n44*=a;return this},determinant:function(){var a=this.n11,b=this.n12,d=this.n13,e=this.n14,g=this.n21,h=this.n22,j=this.n23,c=this.n24,k=this.n31,m=this.n32,p=this.n33,z=this.n34,q=this.n41,v=this.n42,A=this.n43,B=this.n44;return e*j*m*q-d*c*m*q-e*h*p*q+b*c*p*q+d*h*z*q-b*j*z*q-e*j*k*v+d*c*k*v+e*g*p*v-a*c*p*v-d*g*z*v+a*j*z*v+e*h*k*A-b*c*k*A-e*g*m*A+a*c*m*A+b*g*z*A-a*h*z*A-d*h*k*B+b*j*k*B+d*g*m*B-a*j*m*B-b*g*p*B+a*h*p*B},transpose:function(){function a(b,d, e){var g=b[d];b[d]=b[e];b[e]=g}a(this,"n21","n12");a(this,"n31","n13");a(this,"n32","n23");a(this,"n41","n14");a(this,"n42","n24");a(this,"n43","n34");return this},clone:function(){var a=new THREE.Matrix4;a.n11=this.n11;a.n12=this.n12;a.n13=this.n13;a.n14=this.n14;a.n21=this.n21;a.n22=this.n22;a.n23=this.n23;a.n24=this.n24;a.n31=this.n31;a.n32=this.n32;a.n33=this.n33;a.n34=this.n34;a.n41=this.n41;a.n42=this.n42;a.n43=this.n43;a.n44=this.n44;return a},flatten:function(){var a=this.flat;a[0]=this.n11; a[1]=this.n21;a[2]=this.n31;a[3]=this.n41;a[4]=this.n12;a[5]=this.n22;a[6]=this.n32;a[7]=this.n42;a[8]=this.n13;a[9]=this.n23;a[10]=this.n33;a[11]=this.n43;a[12]=this.n14;a[13]=this.n24;a[14]=this.n34;a[15]=this.n44;return a},setTranslation:function(a,b,d){this.set(1,0,0,a,0,1,0,b,0,0,1,d,0,0,0,1);return this},setScale:function(a,b,d){this.set(a,0,0,0,0,b,0,0,0,0,d,0,0,0,0,1);return this},setRotX:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},setRotY:function(a){var b= Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},setRotZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},setRotAxis:function(a,b){var d=Math.cos(b),e=Math.sin(b),g=1-d,h=a.x,j=a.y,c=a.z,k=g*h,m=g*j;this.set(k*h+d,k*j-e*c,k*c+e*j,0,k*j+e*c,m*j+d,m*c-e*h,0,k*c-e*j,m*c+e*h,g*c*c+d,0,0,0,0,1);return this},toString:function(){return"| "+this.n11+" "+this.n12+" "+this.n13+" "+this.n14+" |\n| "+this.n21+" "+this.n22+" "+ this.n23+" "+this.n24+" |\n| "+this.n31+" "+this.n32+" "+this.n33+" "+this.n34+" |\n| "+this.n41+" "+this.n42+" "+this.n43+" "+this.n44+" |"}};THREE.Matrix4.translationMatrix=function(a,b,d){var e=new THREE.Matrix4;e.setTranslation(a,b,d);return e};THREE.Matrix4.scaleMatrix=function(a,b,d){var e=new THREE.Matrix4;e.setScale(a,b,d);return e};THREE.Matrix4.rotationXMatrix=function(a){var b=new THREE.Matrix4;b.setRotX(a);return b}; THREE.Matrix4.rotationYMatrix=function(a){var b=new THREE.Matrix4;b.setRotY(a);return b};THREE.Matrix4.rotationZMatrix=function(a){var b=new THREE.Matrix4;b.setRotZ(a);return b};THREE.Matrix4.rotationAxisAngleMatrix=function(a,b){var d=new THREE.Matrix4;d.setRotAxis(a,b);return d}; THREE.Matrix4.makeInvert=function(a){var b=a.n11,d=a.n12,e=a.n13,g=a.n14,h=a.n21,j=a.n22,c=a.n23,k=a.n24,m=a.n31,p=a.n32,z=a.n33,q=a.n34,v=a.n41,A=a.n42,B=a.n43,H=a.n44,s=new THREE.Matrix4;s.n11=c*q*A-k*z*A+k*p*B-j*q*B-c*p*H+j*z*H;s.n12=g*z*A-e*q*A-g*p*B+d*q*B+e*p*H-d*z*H;s.n13=e*k*A-g*c*A+g*j*B-d*k*B-e*j*H+d*c*H;s.n14=g*c*p-e*k*p-g*j*z+d*k*z+e*j*q-d*c*q;s.n21=k*z*v-c*q*v-k*m*B+h*q*B+c*m*H-h*z*H;s.n22=e*q*v-g*z*v+g*m*B-b*q*B-e*m*H+b*z*H;s.n23=g*c*v-e*k*v-g*h*B+b*k*B+e*h*H-b*c*H;s.n24=e*k*m-g*c*m+ g*h*z-b*k*z-e*h*q+b*c*q;s.n31=j*q*v-k*p*v+k*m*A-h*q*A-j*m*H+h*p*H;s.n32=g*p*v-d*q*v-g*m*A+b*q*A+d*m*H-b*p*H;s.n33=e*k*v-g*j*v+g*h*A-b*k*A-d*h*H+b*j*H;s.n34=g*j*m-d*k*m-g*h*p+b*k*p+d*h*q-b*j*q;s.n41=c*p*v-j*z*v-c*m*A+h*z*A+j*m*B-h*p*B;s.n42=d*z*v-e*p*v+e*m*A-b*z*A-d*m*B+b*p*B;s.n43=e*j*v-d*c*v-e*h*A+b*c*A+d*h*B-b*j*B;s.n44=d*c*m-e*j*m+e*h*p-b*c*p-d*h*z+b*j*z;s.multiplyScalar(1/a.determinant());return s}; THREE.Matrix4.makeInvert3x3=function(a){var b=a.flatten();a=a.m33;var d=a.m,e=b[10]*b[5]-b[6]*b[9],g=-b[10]*b[1]+b[2]*b[9],h=b[6]*b[1]-b[2]*b[5],j=-b[10]*b[4]+b[6]*b[8],c=b[10]*b[0]-b[2]*b[8],k=-b[6]*b[0]+b[2]*b[4],m=b[9]*b[4]-b[5]*b[8],p=-b[9]*b[0]+b[1]*b[8],z=b[5]*b[0]-b[1]*b[4];b=b[0]*e+b[1]*j+b[2]*m;if(b==0)throw"matrix not invertible";b=1/b;d[0]=b*e;d[1]=b*g;d[2]=b*h;d[3]=b*j;d[4]=b*c;d[5]=b*k;d[6]=b*m;d[7]=b*p;d[8]=b*z;return a}; THREE.Matrix4.makeFrustum=function(a,b,d,e,g,h){var j,c,k;j=new THREE.Matrix4;c=2*g/(b-a);k=2*g/(e-d);a=(b+a)/(b-a);d=(e+d)/(e-d);e=-(h+g)/(h-g);g=-2*h*g/(h-g);j.n11=c;j.n12=0;j.n13=a;j.n14=0;j.n21=0;j.n22=k;j.n23=d;j.n24=0;j.n31=0;j.n32=0;j.n33=e;j.n34=g;j.n41=0;j.n42=0;j.n43=-1;j.n44=0;return j};THREE.Matrix4.makePerspective=function(a,b,d,e){var g;a=d*Math.tan(a*Math.PI/360);g=-a;return THREE.Matrix4.makeFrustum(g*b,a*b,g,a,d,e)}; THREE.Matrix4.makeOrtho=function(a,b,d,e,g,h){var j,c,k,m;j=new THREE.Matrix4;c=b-a;k=d-e;m=h-g;a=(b+a)/c;d=(d+e)/k;g=(h+g)/m;j.n11=2/c;j.n12=0;j.n13=0;j.n14=-a;j.n21=0;j.n22=2/k;j.n23=0;j.n24=-d;j.n31=0;j.n32=0;j.n33=-2/m;j.n34=-g;j.n41=0;j.n42=0;j.n43=0;j.n44=1;return j};THREE.Matrix4.__tmpVec1=new THREE.Vector3;THREE.Matrix4.__tmpVec2=new THREE.Vector3;THREE.Matrix4.__tmpVec3=new THREE.Vector3; THREE.Vertex=function(a,b){this.position=a||new THREE.Vector3;this.positionWorld=new THREE.Vector3;this.positionScreen=new THREE.Vector4;this.normal=b||new THREE.Vector3;this.normalWorld=new THREE.Vector3;this.normalScreen=new THREE.Vector3;this.tangent=new THREE.Vector4;this.__visible=true};THREE.Vertex.prototype={toString:function(){return"THREE.Vertex ( position: "+this.position+", normal: "+this.normal+" )"}}; THREE.Face3=function(a,b,d,e,g){this.a=a;this.b=b;this.c=d;this.centroid=new THREE.Vector3;this.normal=e instanceof THREE.Vector3?e:new THREE.Vector3;this.vertexNormals=e instanceof Array?e:[];this.materials=g instanceof Array?g:[g]};THREE.Face3.prototype={toString:function(){return"THREE.Face3 ( "+this.a+", "+this.b+", "+this.c+" )"}}; THREE.Face4=function(a,b,d,e,g,h){this.a=a;this.b=b;this.c=d;this.d=e;this.centroid=new THREE.Vector3;this.normal=g instanceof THREE.Vector3?g:new THREE.Vector3;this.vertexNormals=g instanceof Array?g:[];this.materials=h instanceof Array?h:[h]};THREE.Face4.prototype={toString:function(){return"THREE.Face4 ( "+this.a+", "+this.b+", "+this.c+" "+this.d+" )"}};THREE.UV=function(a,b){this.u=a||0;this.v=b||0}; THREE.UV.prototype={copy:function(a){this.u=a.u;this.v=a.v},toString:function(){return"THREE.UV ("+this.u+", "+this.v+")"}};THREE.Geometry=function(){this.vertices=[];this.faces=[];this.uvs=[];this.boundingSphere=this.boundingBox=null;this.geometryChunks={};this.hasTangents=false}; THREE.Geometry.prototype={computeCentroids:function(){var a,b,d;a=0;for(b=this.faces.length;a<b;a++){d=this.faces[a];d.centroid.set(0,0,0);if(d instanceof THREE.Face3){d.centroid.addSelf(this.vertices[d.a].position);d.centroid.addSelf(this.vertices[d.b].position);d.centroid.addSelf(this.vertices[d.c].position);d.centroid.divideScalar(3)}else if(d instanceof THREE.Face4){d.centroid.addSelf(this.vertices[d.a].position);d.centroid.addSelf(this.vertices[d.b].position);d.centroid.addSelf(this.vertices[d.c].position); d.centroid.addSelf(this.vertices[d.d].position);d.centroid.divideScalar(4)}}},computeFaceNormals:function(a){var b,d,e,g,h,j,c=new THREE.Vector3,k=new THREE.Vector3;e=0;for(g=this.vertices.length;e<g;e++){h=this.vertices[e];h.normal.set(0,0,0)}e=0;for(g=this.faces.length;e<g;e++){h=this.faces[e];if(a&&h.vertexNormals.length){c.set(0,0,0);b=0;for(d=h.normal.length;b<d;b++)c.addSelf(h.vertexNormals[b]);c.divideScalar(3)}else{b=this.vertices[h.a];d=this.vertices[h.b];j=this.vertices[h.c];c.sub(j.position, d.position);k.sub(b.position,d.position);c.crossSelf(k)}c.isZero()||c.normalize();h.normal.copy(c)}},computeVertexNormals:function(){var a,b,d,e;if(this.__tmpVertices==undefined){e=this.__tmpVertices=Array(this.vertices.length);a=0;for(b=this.vertices.length;a<b;a++)e[a]=new THREE.Vector3;a=0;for(b=this.faces.length;a<b;a++){d=this.faces[a];if(d instanceof THREE.Face3)d.vertexNormals=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3];else if(d instanceof THREE.Face4)d.vertexNormals=[new THREE.Vector3, new THREE.Vector3,new THREE.Vector3,new THREE.Vector3]}}else{e=this.__tmpVertices;a=0;for(b=this.vertices.length;a<b;a++)e[a].set(0,0,0)}a=0;for(b=this.faces.length;a<b;a++){d=this.faces[a];if(d instanceof THREE.Face3){e[d.a].addSelf(d.normal);e[d.b].addSelf(d.normal);e[d.c].addSelf(d.normal)}else if(d instanceof THREE.Face4){e[d.a].addSelf(d.normal);e[d.b].addSelf(d.normal);e[d.c].addSelf(d.normal);e[d.d].addSelf(d.normal)}}a=0;for(b=this.vertices.length;a<b;a++)e[a].normalize();a=0;for(b=this.faces.length;a< b;a++){d=this.faces[a];if(d instanceof THREE.Face3){d.vertexNormals[0].copy(e[d.a]);d.vertexNormals[1].copy(e[d.b]);d.vertexNormals[2].copy(e[d.c])}else if(d instanceof THREE.Face4){d.vertexNormals[0].copy(e[d.a]);d.vertexNormals[1].copy(e[d.b]);d.vertexNormals[2].copy(e[d.c]);d.vertexNormals[3].copy(e[d.d])}}},computeTangents:function(){function a(D,w,N,I,T,V,O){h=D.vertices[w].position;j=D.vertices[N].position;c=D.vertices[I].position;k=g[T];m=g[V];p=g[O];z=j.x-h.x;q=c.x-h.x;v=j.y-h.y;A=c.y-h.y; B=j.z-h.z;H=c.z-h.z;s=m.u-k.u;K=p.u-k.u;o=m.v-k.v;f=p.v-k.v;n=1/(s*f-K*o);x.set((f*z-o*q)*n,(f*v-o*A)*n,(f*B-o*H)*n);L.set((s*q-K*z)*n,(s*A-K*v)*n,(s*H-K*B)*n);y[w].addSelf(x);y[N].addSelf(x);y[I].addSelf(x);r[w].addSelf(L);r[N].addSelf(L);r[I].addSelf(L)}var b,d,e,g,h,j,c,k,m,p,z,q,v,A,B,H,s,K,o,f,n,y=[],r=[],x=new THREE.Vector3,L=new THREE.Vector3,u=new THREE.Vector3,C=new THREE.Vector3,E=new THREE.Vector3;b=0;for(d=this.vertices.length;b<d;b++){y[b]=new THREE.Vector3;r[b]=new THREE.Vector3}b=0; for(d=this.faces.length;b<d;b++){e=this.faces[b];g=this.uvs[b];if(e instanceof THREE.Face3){a(this,e.a,e.b,e.c,0,1,2);this.vertices[e.a].normal.copy(e.vertexNormals[0]);this.vertices[e.b].normal.copy(e.vertexNormals[1]);this.vertices[e.c].normal.copy(e.vertexNormals[2])}else if(e instanceof THREE.Face4){a(this,e.a,e.b,e.c,0,1,2);a(this,e.a,e.b,e.d,0,1,3);this.vertices[e.a].normal.copy(e.vertexNormals[0]);this.vertices[e.b].normal.copy(e.vertexNormals[1]);this.vertices[e.c].normal.copy(e.vertexNormals[2]); this.vertices[e.d].normal.copy(e.vertexNormals[3])}}b=0;for(d=this.vertices.length;b<d;b++){E.copy(this.vertices[b].normal);e=y[b];u.copy(e);u.subSelf(E.multiplyScalar(E.dot(e))).normalize();C.cross(this.vertices[b].normal,e);e=C.dot(r[b]);e=e<0?-1:1;this.vertices[b].tangent.set(u.x,u.y,u.z,e)}this.hasTangents=true},computeBoundingBox:function(){var a;if(this.vertices.length>0){this.boundingBox={x:[this.vertices[0].position.x,this.vertices[0].position.x],y:[this.vertices[0].position.y,this.vertices[0].position.y], z:[this.vertices[0].position.z,this.vertices[0].position.z]};for(var b=1,d=this.vertices.length;b<d;b++){a=this.vertices[b];if(a.position.x<this.boundingBox.x[0])this.boundingBox.x[0]=a.position.x;else if(a.position.x>this.boundingBox.x[1])this.boundingBox.x[1]=a.position.x;if(a.position.y<this.boundingBox.y[0])this.boundingBox.y[0]=a.position.y;else if(a.position.y>this.boundingBox.y[1])this.boundingBox.y[1]=a.position.y;if(a.position.z<this.boundingBox.z[0])this.boundingBox.z[0]=a.position.z;else if(a.position.z> this.boundingBox.z[1])this.boundingBox.z[1]=a.position.z}}},computeBoundingSphere:function(){for(var a=this.boundingSphere===null?0:this.boundingSphere.radius,b=0,d=this.vertices.length;b<d;b++)a=Math.max(a,this.vertices[b].position.length());this.boundingSphere={radius:a}},sortFacesByMaterial:function(){function a(p){var z=[];b=0;for(d=p.length;b<d;b++)p[b]==undefined?z.push("undefined"):z.push(p[b].toString());return z.join("_")}var b,d,e,g,h,j,c,k,m={};e=0;for(g=this.faces.length;e<g;e++){h=this.faces[e]; j=h.materials;c=a(j);if(m[c]==undefined)m[c]={hash:c,counter:0};k=m[c].hash+"_"+m[c].counter;if(this.geometryChunks[k]==undefined)this.geometryChunks[k]={faces:[],materials:j,vertices:0};h=h instanceof THREE.Face3?3:4;if(this.geometryChunks[k].vertices+h>65535){m[c].counter+=1;k=m[c].hash+"_"+m[c].counter;if(this.geometryChunks[k]==undefined)this.geometryChunks[k]={faces:[],materials:j,vertices:0}}this.geometryChunks[k].faces.push(e);this.geometryChunks[k].vertices+=h}},toString:function(){return"THREE.Geometry ( vertices: "+ this.vertices+", faces: "+this.faces+", uvs: "+this.uvs+" )"}}; THREE.Camera=function(a,b,d,e){this.fov=a;this.aspect=b;this.near=d;this.far=e;this.position=new THREE.Vector3;this.target={position:new THREE.Vector3};this.autoUpdateMatrix=true;this.projectionMatrix=null;this.matrix=new THREE.Matrix4;this.up=new THREE.Vector3(0,1,0);this.tmpVec=new THREE.Vector3;this.translateX=function(g){this.tmpVec.sub(this.target.position,this.position).normalize().multiplyScalar(g);this.tmpVec.crossSelf(this.up);this.position.addSelf(this.tmpVec);this.target.position.addSelf(this.tmpVec)}; this.translateZ=function(g){this.tmpVec.sub(this.target.position,this.position).normalize().multiplyScalar(g);this.position.subSelf(this.tmpVec);this.target.position.subSelf(this.tmpVec)};this.updateMatrix=function(){this.matrix.lookAt(this.position,this.target.position,this.up)};this.updateProjectionMatrix=function(){this.projectionMatrix=THREE.Matrix4.makePerspective(this.fov,this.aspect,this.near,this.far)};this.updateProjectionMatrix()}; THREE.Camera.prototype={toString:function(){return"THREE.Camera ( "+this.position+", "+this.target.position+" )"}};THREE.Light=function(a){this.color=new THREE.Color(a)};THREE.AmbientLight=function(a){THREE.Light.call(this,a)};THREE.AmbientLight.prototype=new THREE.Light;THREE.AmbientLight.prototype.constructor=THREE.AmbientLight;THREE.DirectionalLight=function(a,b){THREE.Light.call(this,a);this.position=new THREE.Vector3(0,1,0);this.intensity=b||1};THREE.DirectionalLight.prototype=new THREE.Light; THREE.DirectionalLight.prototype.constructor=THREE.DirectionalLight;THREE.PointLight=function(a,b){THREE.Light.call(this,a);this.position=new THREE.Vector3;this.intensity=b||1};THREE.DirectionalLight.prototype=new THREE.Light;THREE.DirectionalLight.prototype.constructor=THREE.PointLight; THREE.Object3D=function(){this.id=THREE.Object3DCounter.value++;this.position=new THREE.Vector3;this.rotation=new THREE.Vector3;this.scale=new THREE.Vector3(1,1,1);this.matrix=new THREE.Matrix4;this.rotationMatrix=new THREE.Matrix4;this.tmpMatrix=new THREE.Matrix4;this.screen=new THREE.Vector3;this.visible=this.autoUpdateMatrix=true}; THREE.Object3D.prototype={updateMatrix:function(){var a=this.position,b=this.rotation,d=this.scale,e=this.tmpMatrix;this.matrix.setTranslation(a.x,a.y,a.z);this.rotationMatrix.setRotX(b.x);if(b.y!=0){e.setRotY(b.y);this.rotationMatrix.multiplySelf(e)}if(b.z!=0){e.setRotZ(b.z);this.rotationMatrix.multiplySelf(e)}this.matrix.multiplySelf(this.rotationMatrix);if(d.x!=0||d.y!=0||d.z!=0){e.setScale(d.x,d.y,d.z);this.matrix.multiplySelf(e)}}};THREE.Object3DCounter={value:0}; THREE.Particle=function(a){THREE.Object3D.call(this);this.materials=a instanceof Array?a:[a];this.autoUpdateMatrix=false};THREE.Particle.prototype=new THREE.Object3D;THREE.Particle.prototype.constructor=THREE.Particle;THREE.ParticleSystem=function(a,b){THREE.Object3D.call(this);this.geometry=a;this.materials=b instanceof Array?b:[b];this.autoUpdateMatrix=false};THREE.ParticleSystem.prototype=new THREE.Object3D;THREE.ParticleSystem.prototype.constructor=THREE.ParticleSystem; THREE.Line=function(a,b,d){THREE.Object3D.call(this);this.geometry=a;this.materials=b instanceof Array?b:[b];this.type=d!=undefined?d:THREE.LineStrip};THREE.LineStrip=0;THREE.LinePieces=1;THREE.Line.prototype=new THREE.Object3D;THREE.Line.prototype.constructor=THREE.Line;THREE.Mesh=function(a,b){THREE.Object3D.call(this);this.geometry=a;this.materials=b instanceof Array?b:[b];this.overdraw=this.doubleSided=this.flipSided=false;this.geometry.boundingSphere||this.geometry.computeBoundingSphere()}; THREE.Mesh.prototype=new THREE.Object3D;THREE.Mesh.prototype.constructor=THREE.Mesh;THREE.FlatShading=0;THREE.SmoothShading=1;THREE.NormalBlending=0;THREE.AdditiveBlending=1;THREE.SubtractiveBlending=2; THREE.LineBasicMaterial=function(a){this.color=new THREE.Color(16777215);this.opacity=1;this.blending=THREE.NormalBlending;this.linewidth=1;this.linejoin=this.linecap="round";if(a){a.color!==undefined&&this.color.setHex(a.color);if(a.opacity!==undefined)this.opacity=a.opacity;if(a.blending!==undefined)this.blending=a.blending;if(a.linewidth!==undefined)this.linewidth=a.linewidth;if(a.linecap!==undefined)this.linecap=a.linecap;if(a.linejoin!==undefined)this.linejoin=a.linejoin}}; THREE.LineBasicMaterial.prototype={toString:function(){return"THREE.LineBasicMaterial (<br/>color: "+this.color+"<br/>opacity: "+this.opacity+"<br/>blending: "+this.blending+"<br/>linewidth: "+this.linewidth+"<br/>linecap: "+this.linecap+"<br/>linejoin: "+this.linejoin+"<br/>)"}}; THREE.MeshBasicMaterial=function(a){this.id=THREE.MeshBasicMaterialCounter.value++;this.color=new THREE.Color(16777215);this.env_map=this.map=null;this.combine=THREE.MultiplyOperation;this.reflectivity=1;this.refraction_ratio=0.98;this.fog=true;this.opacity=1;this.shading=THREE.SmoothShading;this.blending=THREE.NormalBlending;this.wireframe=false;this.wireframe_linewidth=1;this.wireframe_linejoin=this.wireframe_linecap="round";if(a){a.color!==undefined&&this.color.setHex(a.color);if(a.map!==undefined)this.map= a.map;if(a.env_map!==undefined)this.env_map=a.env_map;if(a.combine!==undefined)this.combine=a.combine;if(a.reflectivity!==undefined)this.reflectivity=a.reflectivity;if(a.refraction_ratio!==undefined)this.refraction_ratio=a.refraction_ratio;if(a.fog!==undefined)this.fog=a.fog;if(a.opacity!==undefined)this.opacity=a.opacity;if(a.shading!==undefined)this.shading=a.shading;if(a.blending!==undefined)this.blending=a.blending;if(a.wireframe!==undefined)this.wireframe=a.wireframe;if(a.wireframe_linewidth!== undefined)this.wireframe_linewidth=a.wireframe_linewidth;if(a.wireframe_linecap!==undefined)this.wireframe_linecap=a.wireframe_linecap;if(a.wireframe_linejoin!==undefined)this.wireframe_linejoin=a.wireframe_linejoin}}; THREE.MeshBasicMaterial.prototype={toString:function(){return"THREE.MeshBasicMaterial (<br/>id: "+this.id+"<br/>color: "+this.color+"<br/>map: "+this.map+"<br/>env_map: "+this.env_map+"<br/>combine: "+this.combine+"<br/>reflectivity: "+this.reflectivity+"<br/>refraction_ratio: "+this.refraction_ratio+"<br/>opacity: "+this.opacity+"<br/>blending: "+this.blending+"<br/>wireframe: "+this.wireframe+"<br/>wireframe_linewidth: "+this.wireframe_linewidth+"<br/>wireframe_linecap: "+this.wireframe_linecap+ "<br/>wireframe_linejoin: "+this.wireframe_linejoin+"<br/>)"}};THREE.MeshBasicMaterialCounter={value:0}; THREE.MeshLambertMaterial=function(a){this.id=THREE.MeshLambertMaterialCounter.value++;this.color=new THREE.Color(16777215);this.env_map=this.map=null;this.combine=THREE.MultiplyOperation;this.reflectivity=1;this.refraction_ratio=0.98;this.fog=true;this.opacity=1;this.shading=THREE.SmoothShading;this.blending=THREE.NormalBlending;this.wireframe=false;this.wireframe_linewidth=1;this.wireframe_linejoin=this.wireframe_linecap="round";if(a){a.color!==undefined&&this.color.setHex(a.color);if(a.map!==undefined)this.map= a.map;if(a.env_map!==undefined)this.env_map=a.env_map;if(a.combine!==undefined)this.combine=a.combine;if(a.reflectivity!==undefined)this.reflectivity=a.reflectivity;if(a.refraction_ratio!==undefined)this.refraction_ratio=a.refraction_ratio;if(a.fog!==undefined)this.fog=a.fog;if(a.opacity!==undefined)this.opacity=a.opacity;if(a.shading!==undefined)this.shading=a.shading;if(a.blending!==undefined)this.blending=a.blending;if(a.wireframe!==undefined)this.wireframe=a.wireframe;if(a.wireframe_linewidth!== undefined)this.wireframe_linewidth=a.wireframe_linewidth;if(a.wireframe_linecap!==undefined)this.wireframe_linecap=a.wireframe_linecap;if(a.wireframe_linejoin!==undefined)this.wireframe_linejoin=a.wireframe_linejoin}}; THREE.MeshLambertMaterial.prototype={toString:function(){return"THREE.MeshLambertMaterial (<br/>id: "+this.id+"<br/>color: "+this.color+"<br/>map: "+this.map+"<br/>env_map: "+this.env_map+"<br/>combine: "+this.combine+"<br/>reflectivity: "+this.reflectivity+"<br/>refraction_ratio: "+this.refraction_ratio+"<br/>opacity: "+this.opacity+"<br/>shading: "+this.shading+"<br/>blending: "+this.blending+"<br/>wireframe: "+this.wireframe+"<br/>wireframe_linewidth: "+this.wireframe_linewidth+"<br/>wireframe_linecap: "+ this.wireframe_linecap+"<br/>wireframe_linejoin: "+this.wireframe_linejoin+"<br/> )"}};THREE.MeshLambertMaterialCounter={value:0}; THREE.MeshPhongMaterial=function(a){this.id=THREE.MeshPhongMaterialCounter.value++;this.color=new THREE.Color(16777215);this.ambient=new THREE.Color(328965);this.specular=new THREE.Color(1118481);this.shininess=30;this.env_map=this.specular_map=this.map=null;this.combine=THREE.MultiplyOperation;this.reflectivity=1;this.refraction_ratio=0.98;this.fog=true;this.opacity=1;this.shading=THREE.SmoothShading;this.blending=THREE.NormalBlending;this.wireframe=false;this.wireframe_linewidth=1;this.wireframe_linejoin= this.wireframe_linecap="round";if(a){if(a.color!==undefined)this.color=new THREE.Color(a.color);if(a.ambient!==undefined)this.ambient=new THREE.Color(a.ambient);if(a.specular!==undefined)this.specular=new THREE.Color(a.specular);if(a.shininess!==undefined)this.shininess=a.shininess;if(a.map!==undefined)this.map=a.map;if(a.specular_map!==undefined)this.specular_map=a.specular_map;if(a.env_map!==undefined)this.env_map=a.env_map;if(a.combine!==undefined)this.combine=a.combine;if(a.reflectivity!==undefined)this.reflectivity= a.reflectivity;if(a.refraction_ratio!==undefined)this.refraction_ratio=a.refraction_ratio;if(a.fog!==undefined)this.fog=a.fog;if(a.opacity!==undefined)this.opacity=a.opacity;if(a.shading!==undefined)this.shading=a.shading;if(a.blending!==undefined)this.blending=a.blending;if(a.wireframe!==undefined)this.wireframe=a.wireframe;if(a.wireframe_linewidth!==undefined)this.wireframe_linewidth=a.wireframe_linewidth;if(a.wireframe_linecap!==undefined)this.wireframe_linecap=a.wireframe_linecap;if(a.wireframe_linejoin!== undefined)this.wireframe_linejoin=a.wireframe_linejoin}}; THREE.MeshPhongMaterial.prototype={toString:function(){return"THREE.MeshPhongMaterial (<br/>id: "+this.id+"<br/>color: "+this.color+"<br/>ambient: "+this.ambient+"<br/>specular: "+this.specular+"<br/>shininess: "+this.shininess+"<br/>map: "+this.map+"<br/>specular_map: "+this.specular_map+"<br/>env_map: "+this.env_map+"<br/>combine: "+this.combine+"<br/>reflectivity: "+this.reflectivity+"<br/>refraction_ratio: "+this.refraction_ratio+"<br/>opacity: "+this.opacity+"<br/>shading: "+this.shading+"<br/>wireframe: "+ this.wireframe+"<br/>wireframe_linewidth: "+this.wireframe_linewidth+"<br/>wireframe_linecap: "+this.wireframe_linecap+"<br/>wireframe_linejoin: "+this.wireframe_linejoin+"<br/>)"}};THREE.MeshPhongMaterialCounter={value:0}; THREE.MeshDepthMaterial=function(a){this.opacity=1;this.shading=THREE.SmoothShading;this.blending=THREE.NormalBlending;this.wireframe=false;this.wireframe_linewidth=1;this.wireframe_linejoin=this.wireframe_linecap="round";if(a){if(a.opacity!==undefined)this.opacity=a.opacity;if(a.blending!==undefined)this.blending=a.blending}};THREE.MeshDepthMaterial.prototype={toString:function(){return"THREE.MeshDepthMaterial"}}; THREE.MeshNormalMaterial=function(a){this.opacity=1;this.shading=THREE.FlatShading;this.blending=THREE.NormalBlending;if(a){if(a.opacity!==undefined)this.opacity=a.opacity;if(a.shading!==undefined)this.shading=a.shading;if(a.blending!==undefined)this.blending=a.blending}};THREE.MeshNormalMaterial.prototype={toString:function(){return"THREE.MeshNormalMaterial"}};THREE.MeshFaceMaterial=function(){};THREE.MeshFaceMaterial.prototype={toString:function(){return"THREE.MeshFaceMaterial"}}; THREE.MeshShaderMaterial=function(a){this.id=THREE.MeshShaderMaterialCounter.value++;this.vertex_shader=this.fragment_shader="void main() {}";this.uniforms={};this.opacity=1;this.shading=THREE.SmoothShading;this.blending=THREE.NormalBlending;this.wireframe=false;this.wireframe_linewidth=1;this.wireframe_linejoin=this.wireframe_linecap="round";if(a){if(a.fragment_shader!==undefined)this.fragment_shader=a.fragment_shader;if(a.vertex_shader!==undefined)this.vertex_shader=a.vertex_shader;if(a.uniforms!== undefined)this.uniforms=a.uniforms;if(a.shading!==undefined)this.shading=a.shading;if(a.blending!==undefined)this.blending=a.blending;if(a.wireframe!==undefined)this.wireframe=a.wireframe;if(a.wireframe_linewidth!==undefined)this.wireframe_linewidth=a.wireframe_linewidth;if(a.wireframe_linecap!==undefined)this.wireframe_linecap=a.wireframe_linecap;if(a.wireframe_linejoin!==undefined)this.wireframe_linejoin=a.wireframe_linejoin}}; THREE.MeshShaderMaterial.prototype={toString:function(){return"THREE.MeshShaderMaterial (<br/>id: "+this.id+"<br/>blending: "+this.blending+"<br/>wireframe: "+this.wireframe+"<br/>wireframe_linewidth: "+this.wireframe_linewidth+"<br/>wireframe_linecap: "+this.wireframe_linecap+"<br/>wireframe_linejoin: "+this.wireframe_linejoin+"<br/>)"}};THREE.MeshShaderMaterialCounter={value:0}; THREE.ParticleBasicMaterial=function(a){this.color=new THREE.Color(16777215);this.map=null;this.opacity=1;this.blending=THREE.NormalBlending;this.offset=new THREE.Vector2;if(a){a.color!==undefined&&this.color.setHex(a.color);if(a.map!==undefined)this.map=a.map;if(a.opacity!==undefined)this.opacity=a.opacity;if(a.blending!==undefined)this.blending=a.blending}}; THREE.ParticleBasicMaterial.prototype={toString:function(){return"THREE.ParticleBasicMaterial (<br/>color: "+this.color+"<br/>map: "+this.map+"<br/>opacity: "+this.opacity+"<br/>blending: "+this.blending+"<br/>)"}};THREE.ParticleCircleMaterial=function(a){this.color=new THREE.Color(16777215);this.opacity=1;this.blending=THREE.NormalBlending;if(a){a.color!==undefined&&this.color.setHex(a.color);if(a.opacity!==undefined)this.opacity=a.opacity;if(a.blending!==undefined)this.blending=a.blending}}; THREE.ParticleCircleMaterial.prototype={toString:function(){return"THREE.ParticleCircleMaterial (<br/>color: "+this.color+"<br/>opacity: "+this.opacity+"<br/>blending: "+this.blending+"<br/>)"}};THREE.ParticleDOMMaterial=function(a){this.domElement=a};THREE.ParticleDOMMaterial.prototype={toString:function(){return"THREE.ParticleDOMMaterial ( domElement: "+this.domElement+" )"}}; THREE.Texture=function(a,b,d,e,g,h){this.image=a;this.mapping=b!==undefined?b:new THREE.UVMapping;this.wrap_s=d!==undefined?d:THREE.ClampToEdgeWrapping;this.wrap_t=e!==undefined?e:THREE.ClampToEdgeWrapping;this.mag_filter=g!==undefined?g:THREE.LinearFilter;this.min_filter=h!==undefined?h:THREE.LinearMipMapLinearFilter}; THREE.Texture.prototype={clone:function(){return new THREE.Texture(this.image,this.mapping,this.wrap_s,this.wrap_t,this.mag_filter,this.min_filter)},toString:function(){return"THREE.Texture (<br/>image: "+this.image+"<br/>wrap_s: "+this.wrap_s+"<br/>wrap_t: "+this.wrap_t+"<br/>mag_filter: "+this.mag_filter+"<br/>min_filter: "+this.min_filter+"<br/>)"}};THREE.MultiplyOperation=0;THREE.MixOperation=1;THREE.RepeatWrapping=0;THREE.ClampToEdgeWrapping=1;THREE.MirroredRepeatWrapping=2; THREE.NearestFilter=3;THREE.NearestMipMapNearestFilter=4;THREE.NearestMipMapLinearFilter=5;THREE.LinearFilter=6;THREE.LinearMipMapNearestFilter=7;THREE.LinearMipMapLinearFilter=8;THREE.ByteType=9;THREE.UnsignedByteType=10;THREE.ShortType=11;THREE.UnsignedShortType=12;THREE.IntType=13;THREE.UnsignedIntType=14;THREE.FloatType=15;THREE.AlphaFormat=16;THREE.RGBFormat=17;THREE.RGBAFormat=18;THREE.LuminanceFormat=19;THREE.LuminanceAlphaFormat=20; THREE.RenderTarget=function(a,b,d){this.width=a;this.height=b;d=d||{};this.wrap_s=d.wrap_s!==undefined?d.wrap_s:THREE.ClampToEdgeWrapping;this.wrap_t=d.wrap_t!==undefined?d.wrap_t:THREE.ClampToEdgeWrapping;this.mag_filter=d.mag_filter!==undefined?d.mag_filter:THREE.LinearFilter;this.min_filter=d.min_filter!==undefined?d.min_filter:THREE.LinearMipMapLinearFilter;this.format=d.format!==undefined?d.format:THREE.RGBFormat;this.type=d.type!==undefined?d.type:THREE.UnsignedByteType}; var Uniforms={clone:function(a){var b,d,e,g={};for(b in a){g[b]={};for(d in a[b]){e=a[b][d];g[b][d]=e instanceof THREE.Color||e instanceof THREE.Vector3||e instanceof THREE.Texture?e.clone():e}}return g},merge:function(a){var b,d,e,g={};for(b=0;b<a.length;b++){e=this.clone(a[b]);for(d in e)g[d]=e[d]}return g}};THREE.CubeReflectionMapping=function(){};THREE.CubeRefractionMapping=function(){};THREE.LatitudeReflectionMapping=function(){};THREE.LatitudeRefractionMapping=function(){}; THREE.SphericalReflectionMapping=function(){};THREE.SphericalRefractionMapping=function(){};THREE.UVMapping=function(){}; THREE.Scene=function(){this.objects=[];this.lights=[];this.fog=null;this.addObject=function(a){this.objects.indexOf(a)===-1&&this.objects.push(a)};this.removeObject=function(a){a=this.objects.indexOf(a);a!==-1&&this.objects.splice(a,1)};this.addLight=function(a){this.lights.indexOf(a)===-1&&this.lights.push(a)};this.removeLight=function(a){a=this.lights.indexOf(a);a!==-1&&this.lights.splice(a,1)};this.toString=function(){return"THREE.Scene ( "+this.objects+" )"}}; THREE.Fog=function(a,b,d){this.color=new THREE.Color(a);this.near=b||1;this.far=d||1E3};THREE.FogExp2=function(a,b){this.color=new THREE.Color(a);this.density=b||2.5E-4}; THREE.Projector=function(){function a(r,x){return x.z-r.z}function b(r,x){var L=0,u=1,C=r.z+r.w,E=x.z+x.w,D=-r.z+r.w,w=-x.z+x.w;if(C>=0&&E>=0&&D>=0&&w>=0)return true;else if(C<0&&E<0||D<0&&w<0)return false;else{if(C<0)L=Math.max(L,C/(C-E));else if(E<0)u=Math.min(u,C/(C-E));if(D<0)L=Math.max(L,D/(D-w));else if(w<0)u=Math.min(u,D/(D-w));if(u<L)return false;else{r.lerpSelf(x,L);x.lerpSelf(r,1-u);return true}}}var d,e,g=[],h,j,c,k=[],m,p,z=[],q,v,A=[],B=new THREE.Vector4,H=new THREE.Vector4,s=new THREE.Matrix4, K=new THREE.Matrix4,o=[],f=new THREE.Vector4,n=new THREE.Vector4,y;this.projectObjects=function(r,x,L){var u=[],C,E;e=0;s.multiply(x.projectionMatrix,x.matrix);o[0]=new THREE.Vector4(s.n41-s.n11,s.n42-s.n12,s.n43-s.n13,s.n44-s.n14);o[1]=new THREE.Vector4(s.n41+s.n11,s.n42+s.n12,s.n43+s.n13,s.n44+s.n14);o[2]=new THREE.Vector4(s.n41+s.n21,s.n42+s.n22,s.n43+s.n23,s.n44+s.n24);o[3]=new THREE.Vector4(s.n41-s.n21,s.n42-s.n22,s.n43-s.n23,s.n44-s.n24);o[4]=new THREE.Vector4(s.n41-s.n31,s.n42-s.n32,s.n43- s.n33,s.n44-s.n34);o[5]=new THREE.Vector4(s.n41+s.n31,s.n42+s.n32,s.n43+s.n33,s.n44+s.n34);x=0;for(C=o.length;x<C;x++){E=o[x];E.divideScalar(Math.sqrt(E.x*E.x+E.y*E.y+E.z*E.z))}C=r.objects;r=0;for(x=C.length;r<x;r++){E=C[r];var D;if(!(D=!E.visible)){if(D=E instanceof THREE.Mesh){a:{D=void 0;for(var w=E.position,N=-E.geometry.boundingSphere.radius*Math.max(E.scale.x,Math.max(E.scale.y,E.scale.z)),I=0;I<6;I++){D=o[I].x*w.x+o[I].y*w.y+o[I].z*w.z+o[I].w;if(D<=N){D=false;break a}}D=true}D=!D}D=D}if(!D){d= g[e]=g[e]||new THREE.RenderableObject;B.copy(E.position);s.multiplyVector3(B);d.object=E;d.z=B.z;u.push(d);e++}}L&&u.sort(a);return u};this.projectScene=function(r,x,L){var u=[],C=x.near,E=x.far,D,w,N,I,T,V,O,ca,W,Q,S,aa,X,F,R,U;c=p=v=0;x.autoUpdateMatrix&&x.updateMatrix();s.multiply(x.projectionMatrix,x.matrix);V=this.projectObjects(r,x,true);r=0;for(D=V.length;r<D;r++){O=V[r].object;if(O.visible){O.autoUpdateMatrix&&O.updateMatrix();ca=O.matrix;W=O.rotationMatrix;Q=O.materials;S=O.overdraw;if(O instanceof THREE.Mesh){aa=O.geometry;X=aa.vertices;w=0;for(N=X.length;w<N;w++){F=X[w];F.positionWorld.copy(F.position);ca.multiplyVector3(F.positionWorld);I=F.positionScreen;I.copy(F.positionWorld);s.multiplyVector4(I);I.x/=I.w;I.y/=I.w;F.__visible=I.z>C&&I.z<E}aa=aa.faces;w=0;for(N=aa.length;w<N;w++){F=aa[w];if(F instanceof THREE.Face3){I=X[F.a];T=X[F.b];R=X[F.c];if(I.__visible&&T.__visible&&R.__visible)if(O.doubleSided||O.flipSided!=(R.positionScreen.x-I.positionScreen.x)*(T.positionScreen.y-I.positionScreen.y)- (R.positionScreen.y-I.positionScreen.y)*(T.positionScreen.x-I.positionScreen.x)<0){h=k[c]=k[c]||new THREE.RenderableFace3;h.v1.positionWorld.copy(I.positionWorld);h.v2.positionWorld.copy(T.positionWorld);h.v3.positionWorld.copy(R.positionWorld);h.v1.positionScreen.copy(I.positionScreen);h.v2.positionScreen.copy(T.positionScreen);h.v3.positionScreen.copy(R.positionScreen);h.normalWorld.copy(F.normal);W.multiplyVector3(h.normalWorld);h.centroidWorld.copy(F.centroid);ca.multiplyVector3(h.centroidWorld); h.centroidScreen.copy(h.centroidWorld);s.multiplyVector3(h.centroidScreen);R=F.vertexNormals;y=h.vertexNormalsWorld;I=0;for(T=R.length;I<T;I++){U=y[I]=y[I]||new THREE.Vector3;U.copy(R[I]);W.multiplyVector3(U)}h.z=h.centroidScreen.z;h.meshMaterials=Q;h.faceMaterials=F.materials;h.overdraw=S;if(O.geometry.uvs[w]){h.uvs[0]=O.geometry.uvs[w][0];h.uvs[1]=O.geometry.uvs[w][1];h.uvs[2]=O.geometry.uvs[w][2]}u.push(h);c++}}else if(F instanceof THREE.Face4){I=X[F.a];T=X[F.b];R=X[F.c];U=X[F.d];if(I.__visible&& T.__visible&&R.__visible&&U.__visible)if(O.doubleSided||O.flipSided!=((U.positionScreen.x-I.positionScreen.x)*(T.positionScreen.y-I.positionScreen.y)-(U.positionScreen.y-I.positionScreen.y)*(T.positionScreen.x-I.positionScreen.x)<0||(T.positionScreen.x-R.positionScreen.x)*(U.positionScreen.y-R.positionScreen.y)-(T.positionScreen.y-R.positionScreen.y)*(U.positionScreen.x-R.positionScreen.x)<0)){h=k[c]=k[c]||new THREE.RenderableFace3;h.v1.positionWorld.copy(I.positionWorld);h.v2.positionWorld.copy(T.positionWorld); h.v3.positionWorld.copy(U.positionWorld);h.v1.positionScreen.copy(I.positionScreen);h.v2.positionScreen.copy(T.positionScreen);h.v3.positionScreen.copy(U.positionScreen);h.normalWorld.copy(F.normal);W.multiplyVector3(h.normalWorld);h.centroidWorld.copy(F.centroid);ca.multiplyVector3(h.centroidWorld);h.centroidScreen.copy(h.centroidWorld);s.multiplyVector3(h.centroidScreen);h.z=h.centroidScreen.z;h.meshMaterials=Q;h.faceMaterials=F.materials;h.overdraw=S;if(O.geometry.uvs[w]){h.uvs[0]=O.geometry.uvs[w][0]; h.uvs[1]=O.geometry.uvs[w][1];h.uvs[2]=O.geometry.uvs[w][3]}u.push(h);c++;j=k[c]=k[c]||new THREE.RenderableFace3;j.v1.positionWorld.copy(T.positionWorld);j.v2.positionWorld.copy(R.positionWorld);j.v3.positionWorld.copy(U.positionWorld);j.v1.positionScreen.copy(T.positionScreen);j.v2.positionScreen.copy(R.positionScreen);j.v3.positionScreen.copy(U.positionScreen);j.normalWorld.copy(h.normalWorld);j.centroidWorld.copy(h.centroidWorld);j.centroidScreen.copy(h.centroidScreen);j.z=j.centroidScreen.z;j.meshMaterials= Q;j.faceMaterials=F.materials;j.overdraw=S;if(O.geometry.uvs[w]){j.uvs[0]=O.geometry.uvs[w][1];j.uvs[1]=O.geometry.uvs[w][2];j.uvs[2]=O.geometry.uvs[w][3]}u.push(j);c++}}}}else if(O instanceof THREE.Line){K.multiply(s,ca);X=O.geometry.vertices;F=X[0];F.positionScreen.copy(F.position);K.multiplyVector4(F.positionScreen);w=1;for(N=X.length;w<N;w++){I=X[w];I.positionScreen.copy(I.position);K.multiplyVector4(I.positionScreen);T=X[w-1];f.copy(I.positionScreen);n.copy(T.positionScreen);if(b(f,n)){f.multiplyScalar(1/ f.w);n.multiplyScalar(1/n.w);m=z[p]=z[p]||new THREE.RenderableLine;m.v1.positionScreen.copy(f);m.v2.positionScreen.copy(n);m.z=Math.max(f.z,n.z);m.materials=O.materials;u.push(m);p++}}}else if(O instanceof THREE.Particle){H.set(O.position.x,O.position.y,O.position.z,1);s.multiplyVector4(H);H.z/=H.w;if(H.z>0&&H.z<1){q=A[v]=A[v]||new THREE.RenderableParticle;q.x=H.x/H.w;q.y=H.y/H.w;q.z=H.z;q.rotation=O.rotation.z;q.scale.x=O.scale.x*Math.abs(q.x-(H.x+x.projectionMatrix.n11)/(H.w+x.projectionMatrix.n14)); q.scale.y=O.scale.y*Math.abs(q.y-(H.y+x.projectionMatrix.n22)/(H.w+x.projectionMatrix.n24));q.materials=O.materials;u.push(q);v++}}}}L&&u.sort(a);return u};this.unprojectVector=function(r,x){var L=THREE.Matrix4.makeInvert(x.matrix);L.multiplySelf(THREE.Matrix4.makeInvert(x.projectionMatrix));L.multiplyVector3(r);return r}}; THREE.DOMRenderer=function(){THREE.Renderer.call(this);var a=null,b=new THREE.Projector,d,e,g,h;this.domElement=document.createElement("div");this.setSize=function(j,c){d=j;e=c;g=d/2;h=e/2};this.render=function(j,c){var k,m,p,z,q,v,A,B;a=b.projectScene(j,c);k=0;for(m=a.length;k<m;k++){q=a[k];if(q instanceof THREE.RenderableParticle){A=q.x*g+g;B=q.y*h+h;p=0;for(z=q.material.length;p<z;p++){v=q.material[p];if(v instanceof THREE.ParticleDOMMaterial){v=v.domElement;v.style.left=A+"px";v.style.top=B+"px"}}}}}}; THREE.CanvasRenderer=function(){function a(la){if(q!=la)m.globalAlpha=q=la}function b(la){if(v!=la){switch(la){case THREE.NormalBlending:m.globalCompositeOperation="source-over";break;case THREE.AdditiveBlending:m.globalCompositeOperation="lighter";break;case THREE.SubtractiveBlending:m.globalCompositeOperation="darker"}v=la}}var d=null,e=new THREE.Projector,g=document.createElement("canvas"),h,j,c,k,m=g.getContext("2d"),p=null,z=null,q=1,v=0,A=null,B=null,H=1,s,K,o,f,n,y,r,x,L,u=new THREE.Color, C=new THREE.Color,E=new THREE.Color,D=new THREE.Color,w=new THREE.Color,N,I,T,V,O,ca,W,Q,S,aa=new THREE.Rectangle,X=new THREE.Rectangle,F=new THREE.Rectangle,R=false,U=new THREE.Color,ha=new THREE.Color,ga=new THREE.Color,t=new THREE.Color,J=Math.PI*2,G=new THREE.Vector3,Y,ba,fa,ia,pa,ra,xa=16;Y=document.createElement("canvas");Y.width=Y.height=2;ba=Y.getContext("2d");ba.fillStyle="rgba(0,0,0,1)";ba.fillRect(0,0,2,2);fa=ba.getImageData(0,0,2,2);ia=fa.data;pa=document.createElement("canvas");pa.width= pa.height=xa;ra=pa.getContext("2d");ra.translate(-xa/2,-xa/2);ra.scale(xa,xa);xa--;this.domElement=g;this.sortElements=this.sortObjects=this.autoClear=true;this.setSize=function(la,va){h=la;j=va;c=h/2;k=j/2;g.width=h;g.height=j;aa.set(-c,-k,c,k);q=1;v=0;B=A=null;H=1};this.setClearColor=function(la,va){p=la!==null?new THREE.Color(la):null;z=va;X.set(-c,-k,c,k);m.setTransform(1,0,0,-1,c,k);this.clear()};this.clear=function(){if(!X.isEmpty()){X.inflate(1);X.minSelf(aa);if(p!==null){b(THREE.NormalBlending); a(1);m.fillStyle="rgba("+Math.floor(p.r*255)+","+Math.floor(p.g*255)+","+Math.floor(p.b*255)+","+z+")";m.fillRect(X.getX(),X.getY(),X.getWidth(),X.getHeight())}else m.clearRect(X.getX(),X.getY(),X.getWidth(),X.getHeight());X.empty()}};this.render=function(la,va){function Oa(M){var da,$,P,Z=M.lights;ha.setRGB(0,0,0);ga.setRGB(0,0,0);t.setRGB(0,0,0);M=0;for(da=Z.length;M<da;M++){$=Z[M];P=$.color;if($ instanceof THREE.AmbientLight){ha.r+=P.r;ha.g+=P.g;ha.b+=P.b}else if($ instanceof THREE.DirectionalLight){ga.r+= P.r;ga.g+=P.g;ga.b+=P.b}else if($ instanceof THREE.PointLight){t.r+=P.r;t.g+=P.g;t.b+=P.b}}}function Ca(M,da,$,P){var Z,ea,ka,ma,na=M.lights;M=0;for(Z=na.length;M<Z;M++){ea=na[M];ka=ea.color;ma=ea.intensity;if(ea instanceof THREE.DirectionalLight){ea=$.dot(ea.position)*ma;if(ea>0){P.r+=ka.r*ea;P.g+=ka.g*ea;P.b+=ka.b*ea}}else if(ea instanceof THREE.PointLight){G.sub(ea.position,da);G.normalize();ea=$.dot(G)*ma;if(ea>0){P.r+=ka.r*ea;P.g+=ka.g*ea;P.b+=ka.b*ea}}}}function Pa(M,da,$){if($.opacity!=0){a($.opacity); b($.blending);var P,Z,ea,ka,ma,na;if($ instanceof THREE.ParticleBasicMaterial){if($.map){ka=$.map;ma=ka.width>>1;na=ka.height>>1;Z=da.scale.x*c;ea=da.scale.y*k;$=Z*ma;P=ea*na;F.set(M.x-$,M.y-P,M.x+$,M.y+P);if(aa.instersects(F)){m.save();m.translate(M.x,M.y);m.rotate(-da.rotation);m.scale(Z,-ea);m.translate(-ma,-na);m.drawImage(ka,0,0);m.restore()}}}else if($ instanceof THREE.ParticleCircleMaterial){if(R){U.r=ha.r+ga.r+t.r;U.g=ha.g+ga.g+t.g;U.b=ha.b+ga.b+t.b;u.r=$.color.r*U.r;u.g=$.color.g*U.g;u.b= $.color.b*U.b;u.updateStyleString()}else u.__styleString=$.color.__styleString;$=da.scale.x*c;P=da.scale.y*k;F.set(M.x-$,M.y-P,M.x+$,M.y+P);if(aa.instersects(F)){Z=u.__styleString;if(B!=Z)m.fillStyle=B=Z;m.save();m.translate(M.x,M.y);m.rotate(-da.rotation);m.scale($,P);m.beginPath();m.arc(0,0,1,0,J,true);m.closePath();m.fill();m.restore()}}}}function Qa(M,da,$,P){if(P.opacity!=0){a(P.opacity);b(P.blending);m.beginPath();m.moveTo(M.positionScreen.x,M.positionScreen.y);m.lineTo(da.positionScreen.x, da.positionScreen.y);m.closePath();if(P instanceof THREE.LineBasicMaterial){u.__styleString=P.color.__styleString;M=P.linewidth;if(H!=M)m.lineWidth=H=M;M=u.__styleString;if(A!=M)m.strokeStyle=A=M;m.stroke();F.inflate(P.linewidth*2)}}}function Ka(M,da,$,P,Z,ea){if(Z.opacity!=0){a(Z.opacity);b(Z.blending);f=M.positionScreen.x;n=M.positionScreen.y;y=da.positionScreen.x;r=da.positionScreen.y;x=$.positionScreen.x;L=$.positionScreen.y;m.beginPath();m.moveTo(f,n);m.lineTo(y,r);m.lineTo(x,L);m.lineTo(f,n); m.closePath();if(Z instanceof THREE.MeshBasicMaterial)if(Z.map)Z.map.image.loaded&&Z.map.mapping instanceof THREE.UVMapping&&za(f,n,y,r,x,L,Z.map.image,P.uvs[0].u,P.uvs[0].v,P.uvs[1].u,P.uvs[1].v,P.uvs[2].u,P.uvs[2].v);else if(Z.env_map){if(Z.env_map.image.loaded)if(Z.env_map.mapping instanceof THREE.SphericalReflectionMapping){M=va.matrix;G.copy(P.vertexNormalsWorld[0]);V=(G.x*M.n11+G.y*M.n12+G.z*M.n13)*0.5+0.5;O=-(G.x*M.n21+G.y*M.n22+G.z*M.n23)*0.5+0.5;G.copy(P.vertexNormalsWorld[1]);ca=(G.x*M.n11+ G.y*M.n12+G.z*M.n13)*0.5+0.5;W=-(G.x*M.n21+G.y*M.n22+G.z*M.n23)*0.5+0.5;G.copy(P.vertexNormalsWorld[2]);Q=(G.x*M.n11+G.y*M.n12+G.z*M.n13)*0.5+0.5;S=-(G.x*M.n21+G.y*M.n22+G.z*M.n23)*0.5+0.5;za(f,n,y,r,x,L,Z.env_map.image,V,O,ca,W,Q,S)}}else Z.wireframe?Da(Z.color.__styleString,Z.wireframe_linewidth):Ea(Z.color.__styleString);else if(Z instanceof THREE.MeshLambertMaterial){if(Z.map&&!Z.wireframe){Z.map.mapping instanceof THREE.UVMapping&&za(f,n,y,r,x,L,Z.map.image,P.uvs[0].u,P.uvs[0].v,P.uvs[1].u,P.uvs[1].v, P.uvs[2].u,P.uvs[2].v);b(THREE.SubtractiveBlending)}if(R)if(!Z.wireframe&&Z.shading==THREE.SmoothShading&&P.vertexNormalsWorld.length==3){C.r=E.r=D.r=ha.r;C.g=E.g=D.g=ha.g;C.b=E.b=D.b=ha.b;Ca(ea,P.v1.positionWorld,P.vertexNormalsWorld[0],C);Ca(ea,P.v2.positionWorld,P.vertexNormalsWorld[1],E);Ca(ea,P.v3.positionWorld,P.vertexNormalsWorld[2],D);w.r=(E.r+D.r)*0.5;w.g=(E.g+D.g)*0.5;w.b=(E.b+D.b)*0.5;T=La(C,E,D,w);za(f,n,y,r,x,L,T,0,0,1,0,0,1)}else{U.r=ha.r;U.g=ha.g;U.b=ha.b;Ca(ea,P.centroidWorld,P.normalWorld, U);u.r=Z.color.r*U.r;u.g=Z.color.g*U.g;u.b=Z.color.b*U.b;u.updateStyleString();Z.wireframe?Da(u.__styleString,Z.wireframe_linewidth):Ea(u.__styleString)}else Z.wireframe?Da(Z.color.__styleString,Z.wireframe_linewidth):Ea(Z.color.__styleString)}else if(Z instanceof THREE.MeshDepthMaterial){N=va.near;I=va.far;C.r=C.g=C.b=1-Ga(M.positionScreen.z,N,I);E.r=E.g=E.b=1-Ga(da.positionScreen.z,N,I);D.r=D.g=D.b=1-Ga($.positionScreen.z,N,I);w.r=(E.r+D.r)*0.5;w.g=(E.g+D.g)*0.5;w.b=(E.b+D.b)*0.5;T=La(C,E,D,w); za(f,n,y,r,x,L,T,0,0,1,0,0,1)}else if(Z instanceof THREE.MeshNormalMaterial){u.r=Ha(P.normalWorld.x);u.g=Ha(P.normalWorld.y);u.b=Ha(P.normalWorld.z);u.updateStyleString();Z.wireframe?Da(u.__styleString,Z.wireframe_linewidth):Ea(u.__styleString)}}}function Da(M,da){if(A!=M)m.strokeStyle=A=M;if(H!=da)m.lineWidth=H=da;m.stroke();F.inflate(da*2)}function Ea(M){if(B!=M)m.fillStyle=B=M;m.fill()}function za(M,da,$,P,Z,ea,ka,ma,na,sa,oa,ta,Aa){var wa,ua;wa=ka.width-1;ua=ka.height-1;ma*=wa;na*=ua;sa*=wa;oa*= ua;ta*=wa;Aa*=ua;$-=M;P-=da;Z-=M;ea-=da;sa-=ma;oa-=na;ta-=ma;Aa-=na;ua=1/(sa*Aa-ta*oa);wa=(Aa*$-oa*Z)*ua;oa=(Aa*P-oa*ea)*ua;$=(sa*Z-ta*$)*ua;P=(sa*ea-ta*P)*ua;M=M-wa*ma-$*na;da=da-oa*ma-P*na;m.save();m.transform(wa,oa,$,P,M,da);m.clip();m.drawImage(ka,0,0);m.restore()}function La(M,da,$,P){var Z=~~(M.r*255),ea=~~(M.g*255);M=~~(M.b*255);var ka=~~(da.r*255),ma=~~(da.g*255);da=~~(da.b*255);var na=~~($.r*255),sa=~~($.g*255);$=~~($.b*255);var oa=~~(P.r*255),ta=~~(P.g*255);P=~~(P.b*255);ia[0]=Z<0?0:Z>255? 255:Z;ia[1]=ea<0?0:ea>255?255:ea;ia[2]=M<0?0:M>255?255:M;ia[4]=ka<0?0:ka>255?255:ka;ia[5]=ma<0?0:ma>255?255:ma;ia[6]=da<0?0:da>255?255:da;ia[8]=na<0?0:na>255?255:na;ia[9]=sa<0?0:sa>255?255:sa;ia[10]=$<0?0:$>255?255:$;ia[12]=oa<0?0:oa>255?255:oa;ia[13]=ta<0?0:ta>255?255:ta;ia[14]=P<0?0:P>255?255:P;ba.putImageData(fa,0,0);ra.drawImage(Y,0,0);return pa}function Ga(M,da,$){M=(M-da)/($-da);return M*M*(3-2*M)}function Ha(M){M=(M+1)*0.5;return M<0?0:M>1?1:M}function Ia(M,da){var $=da.x-M.x,P=da.y-M.y,Z= 1/Math.sqrt($*$+P*P);$*=Z;P*=Z;da.x+=$;da.y+=P;M.x-=$;M.y-=P}var Fa,Ma,ja,qa,ya,Ja,Na,Ba;m.setTransform(1,0,0,-1,c,k);this.autoClear&&this.clear();d=e.projectScene(la,va,this.sortElements);(R=la.lights.length>0)&&Oa(la);Fa=0;for(Ma=d.length;Fa<Ma;Fa++){ja=d[Fa];F.empty();if(ja instanceof THREE.RenderableParticle){s=ja;s.x*=c;s.y*=k;qa=0;for(ya=ja.materials.length;qa<ya;qa++)Pa(s,ja,ja.materials[qa],la)}else if(ja instanceof THREE.RenderableLine){s=ja.v1;K=ja.v2;s.positionScreen.x*=c;s.positionScreen.y*= k;K.positionScreen.x*=c;K.positionScreen.y*=k;F.addPoint(s.positionScreen.x,s.positionScreen.y);F.addPoint(K.positionScreen.x,K.positionScreen.y);if(aa.instersects(F)){qa=0;for(ya=ja.materials.length;qa<ya;)Qa(s,K,ja,ja.materials[qa++],la)}}else if(ja instanceof THREE.RenderableFace3){s=ja.v1;K=ja.v2;o=ja.v3;s.positionScreen.x*=c;s.positionScreen.y*=k;K.positionScreen.x*=c;K.positionScreen.y*=k;o.positionScreen.x*=c;o.positionScreen.y*=k;if(ja.overdraw){Ia(s.positionScreen,K.positionScreen);Ia(K.positionScreen, o.positionScreen);Ia(o.positionScreen,s.positionScreen)}F.add3Points(s.positionScreen.x,s.positionScreen.y,K.positionScreen.x,K.positionScreen.y,o.positionScreen.x,o.positionScreen.y);if(aa.instersects(F)){qa=0;for(ya=ja.meshMaterials.length;qa<ya;){Ba=ja.meshMaterials[qa++];if(Ba instanceof THREE.MeshFaceMaterial){Ja=0;for(Na=ja.faceMaterials.length;Ja<Na;)(Ba=ja.faceMaterials[Ja++])&&Ka(s,K,o,ja,Ba,la)}else Ka(s,K,o,ja,Ba,la)}}}X.addRectangle(F)}m.setTransform(1,0,0,1,0,0)}}; THREE.SVGRenderer=function(){function a(V,O,ca){var W,Q,S,aa;W=0;for(Q=V.lights.length;W<Q;W++){S=V.lights[W];if(S instanceof THREE.DirectionalLight){aa=O.normalWorld.dot(S.position)*S.intensity;if(aa>0){ca.r+=S.color.r*aa;ca.g+=S.color.g*aa;ca.b+=S.color.b*aa}}else if(S instanceof THREE.PointLight){L.sub(S.position,O.centroidWorld);L.normalize();aa=O.normalWorld.dot(L)*S.intensity;if(aa>0){ca.r+=S.color.r*aa;ca.g+=S.color.g*aa;ca.b+=S.color.b*aa}}}}function b(V,O,ca,W,Q,S){D=e(w++);D.setAttribute("d", "M "+V.positionScreen.x+" "+V.positionScreen.y+" L "+O.positionScreen.x+" "+O.positionScreen.y+" L "+ca.positionScreen.x+","+ca.positionScreen.y+"z");if(Q instanceof THREE.MeshBasicMaterial)o.__styleString=Q.color.__styleString;else if(Q instanceof THREE.MeshLambertMaterial)if(K){f.r=n.r;f.g=n.g;f.b=n.b;a(S,W,f);o.r=Q.color.r*f.r;o.g=Q.color.g*f.g;o.b=Q.color.b*f.b;o.updateStyleString()}else o.__styleString=Q.color.__styleString;else if(Q instanceof THREE.MeshDepthMaterial){x=1-Q.__2near/(Q.__farPlusNear- W.z*Q.__farMinusNear);o.setRGB(x,x,x)}else Q instanceof THREE.MeshNormalMaterial&&o.setRGB(g(W.normalWorld.x),g(W.normalWorld.y),g(W.normalWorld.z));Q.wireframe?D.setAttribute("style","fill: none; stroke: "+o.__styleString+"; stroke-width: "+Q.wireframe_linewidth+"; stroke-opacity: "+Q.opacity+"; stroke-linecap: "+Q.wireframe_linecap+"; stroke-linejoin: "+Q.wireframe_linejoin):D.setAttribute("style","fill: "+o.__styleString+"; fill-opacity: "+Q.opacity);c.appendChild(D)}function d(V,O,ca,W,Q,S,aa){D= e(w++);D.setAttribute("d","M "+V.positionScreen.x+" "+V.positionScreen.y+" L "+O.positionScreen.x+" "+O.positionScreen.y+" L "+ca.positionScreen.x+","+ca.positionScreen.y+" L "+W.positionScreen.x+","+W.positionScreen.y+"z");if(S instanceof THREE.MeshBasicMaterial)o.__styleString=S.color.__styleString;else if(S instanceof THREE.MeshLambertMaterial)if(K){f.r=n.r;f.g=n.g;f.b=n.b;a(aa,Q,f);o.r=S.color.r*f.r;o.g=S.color.g*f.g;o.b=S.color.b*f.b;o.updateStyleString()}else o.__styleString=S.color.__styleString; else if(S instanceof THREE.MeshDepthMaterial){x=1-S.__2near/(S.__farPlusNear-Q.z*S.__farMinusNear);o.setRGB(x,x,x)}else S instanceof THREE.MeshNormalMaterial&&o.setRGB(g(Q.normalWorld.x),g(Q.normalWorld.y),g(Q.normalWorld.z));S.wireframe?D.setAttribute("style","fill: none; stroke: "+o.__styleString+"; stroke-width: "+S.wireframe_linewidth+"; stroke-opacity: "+S.opacity+"; stroke-linecap: "+S.wireframe_linecap+"; stroke-linejoin: "+S.wireframe_linejoin):D.setAttribute("style","fill: "+o.__styleString+ "; fill-opacity: "+S.opacity);c.appendChild(D)}function e(V){if(u[V]==null){u[V]=document.createElementNS("http://www.w3.org/2000/svg","path");T==0&&u[V].setAttribute("shape-rendering","crispEdges");return u[V]}return u[V]}function g(V){return V<0?Math.min((1+V)*0.5,0.5):0.5+Math.min(V*0.5,0.5)}var h=null,j=new THREE.Projector,c=document.createElementNS("http://www.w3.org/2000/svg","svg"),k,m,p,z,q,v,A,B,H=new THREE.Rectangle,s=new THREE.Rectangle,K=false,o=new THREE.Color(16777215),f=new THREE.Color(16777215), n=new THREE.Color(0),y=new THREE.Color(0),r=new THREE.Color(0),x,L=new THREE.Vector3,u=[],C=[],E=[],D,w,N,I,T=1;this.domElement=c;this.sortElements=this.sortObjects=this.autoClear=true;this.setQuality=function(V){switch(V){case "high":T=1;break;case "low":T=0}};this.setSize=function(V,O){k=V;m=O;p=k/2;z=m/2;c.setAttribute("viewBox",-p+" "+-z+" "+k+" "+m);c.setAttribute("width",k);c.setAttribute("height",m);H.set(-p,-z,p,z)};this.clear=function(){for(;c.childNodes.length>0;)c.removeChild(c.childNodes[0])}; this.render=function(V,O){var ca,W,Q,S,aa,X,F,R;this.autoClear&&this.clear();h=j.projectScene(V,O,this.sortElements);I=N=w=0;if(K=V.lights.length>0){F=V.lights;n.setRGB(0,0,0);y.setRGB(0,0,0);r.setRGB(0,0,0);ca=0;for(W=F.length;ca<W;ca++){Q=F[ca];S=Q.color;if(Q instanceof THREE.AmbientLight){n.r+=S.r;n.g+=S.g;n.b+=S.b}else if(Q instanceof THREE.DirectionalLight){y.r+=S.r;y.g+=S.g;y.b+=S.b}else if(Q instanceof THREE.PointLight){r.r+=S.r;r.g+=S.g;r.b+=S.b}}}ca=0;for(W=h.length;ca<W;ca++){F=h[ca];s.empty(); if(F instanceof THREE.RenderableParticle){q=F;q.x*=p;q.y*=-z;Q=0;for(S=F.materials.length;Q<S;Q++)if(R=F.materials[Q]){aa=q;X=F;R=R;var U=N++;if(C[U]==null){C[U]=document.createElementNS("http://www.w3.org/2000/svg","circle");T==0&&C[U].setAttribute("shape-rendering","crispEdges")}D=C[U];D.setAttribute("cx",aa.x);D.setAttribute("cy",aa.y);D.setAttribute("r",X.scale.x*p);if(R instanceof THREE.ParticleCircleMaterial){if(K){f.r=n.r+y.r+r.r;f.g=n.g+y.g+r.g;f.b=n.b+y.b+r.b;o.r=R.color.r*f.r;o.g=R.color.g* f.g;o.b=R.color.b*f.b;o.updateStyleString()}else o=R.color;D.setAttribute("style","fill: "+o.__styleString)}c.appendChild(D)}}else if(F instanceof THREE.RenderableLine){q=F.v1;v=F.v2;q.positionScreen.x*=p;q.positionScreen.y*=-z;v.positionScreen.x*=p;v.positionScreen.y*=-z;s.addPoint(q.positionScreen.x,q.positionScreen.y);s.addPoint(v.positionScreen.x,v.positionScreen.y);if(H.instersects(s)){Q=0;for(S=F.materials.length;Q<S;)if(R=F.materials[Q++]){aa=q;X=v;R=R;U=I++;if(E[U]==null){E[U]=document.createElementNS("http://www.w3.org/2000/svg", "line");T==0&&E[U].setAttribute("shape-rendering","crispEdges")}D=E[U];D.setAttribute("x1",aa.positionScreen.x);D.setAttribute("y1",aa.positionScreen.y);D.setAttribute("x2",X.positionScreen.x);D.setAttribute("y2",X.positionScreen.y);if(R instanceof THREE.LineBasicMaterial){o.__styleString=R.color.__styleString;D.setAttribute("style","fill: none; stroke: "+o.__styleString+"; stroke-width: "+R.linewidth+"; stroke-opacity: "+R.opacity+"; stroke-linecap: "+R.linecap+"; stroke-linejoin: "+R.linejoin); c.appendChild(D)}}}}else if(F instanceof THREE.RenderableFace3){q=F.v1;v=F.v2;A=F.v3;q.positionScreen.x*=p;q.positionScreen.y*=-z;v.positionScreen.x*=p;v.positionScreen.y*=-z;A.positionScreen.x*=p;A.positionScreen.y*=-z;s.addPoint(q.positionScreen.x,q.positionScreen.y);s.addPoint(v.positionScreen.x,v.positionScreen.y);s.addPoint(A.positionScreen.x,A.positionScreen.y);if(H.instersects(s)){Q=0;for(S=F.meshMaterials.length;Q<S;){R=F.meshMaterials[Q++];if(R instanceof THREE.MeshFaceMaterial){aa=0;for(X= F.faceMaterials.length;aa<X;)(R=F.faceMaterials[aa++])&&b(q,v,A,F,R,V)}else R&&b(q,v,A,F,R,V)}}}else if(F instanceof THREE.RenderableFace4){q=F.v1;v=F.v2;A=F.v3;B=F.v4;q.positionScreen.x*=p;q.positionScreen.y*=-z;v.positionScreen.x*=p;v.positionScreen.y*=-z;A.positionScreen.x*=p;A.positionScreen.y*=-z;B.positionScreen.x*=p;B.positionScreen.y*=-z;s.addPoint(q.positionScreen.x,q.positionScreen.y);s.addPoint(v.positionScreen.x,v.positionScreen.y);s.addPoint(A.positionScreen.x,A.positionScreen.y);s.addPoint(B.positionScreen.x, B.positionScreen.y);if(H.instersects(s)){Q=0;for(S=F.meshMaterials.length;Q<S;){R=F.meshMaterials[Q++];if(R instanceof THREE.MeshFaceMaterial){aa=0;for(X=F.faceMaterials.length;aa<X;)(R=F.faceMaterials[aa++])&&d(q,v,A,B,F,R,V)}else R&&d(q,v,A,B,F,R,V)}}}}}}; THREE.WebGLRenderer=function(a){function b(f,n){f.fragment_shader=n.fragment_shader;f.vertex_shader=n.vertex_shader;f.uniforms=Uniforms.clone(n.uniforms)}function d(f,n){f.uniforms.color.value.setRGB(f.color.r*f.opacity,f.color.g*f.opacity,f.color.b*f.opacity);f.uniforms.opacity.value=f.opacity;f.uniforms.map.texture=f.map;f.uniforms.env_map.texture=f.env_map;f.uniforms.reflectivity.value=f.reflectivity;f.uniforms.refraction_ratio.value=f.refraction_ratio;f.uniforms.combine.value=f.combine;f.uniforms.useRefract.value= f.env_map&&f.env_map.mapping instanceof THREE.CubeRefractionMapping;if(n){f.uniforms.fogColor.value.setHex(n.color.hex);if(n instanceof THREE.Fog){f.uniforms.fogNear.value=n.near;f.uniforms.fogFar.value=n.far}else if(n instanceof THREE.FogExp2)f.uniforms.fogDensity.value=n.density}}function e(f,n){f.uniforms.color.value.setRGB(f.color.r*f.opacity,f.color.g*f.opacity,f.color.b*f.opacity);f.uniforms.opacity.value=f.opacity;if(n){f.uniforms.fogColor.value.setHex(n.color.hex);if(n instanceof THREE.Fog){f.uniforms.fogNear.value= n.near;f.uniforms.fogFar.value=n.far}else if(n instanceof THREE.FogExp2)f.uniforms.fogDensity.value=n.density}}function g(f,n){var y;if(f=="fragment")y=c.createShader(c.FRAGMENT_SHADER);else if(f=="vertex")y=c.createShader(c.VERTEX_SHADER);c.shaderSource(y,n);c.compileShader(y);if(!c.getShaderParameter(y,c.COMPILE_STATUS)){alert(c.getShaderInfoLog(y));return null}return y}function h(f){switch(f){case THREE.RepeatWrapping:return c.REPEAT;case THREE.ClampToEdgeWrapping:return c.CLAMP_TO_EDGE;case THREE.MirroredRepeatWrapping:return c.MIRRORED_REPEAT; case THREE.NearestFilter:return c.NEAREST;case THREE.NearestMipMapNearestFilter:return c.NEAREST_MIPMAP_NEAREST;case THREE.NearestMipMapLinearFilter:return c.NEAREST_MIPMAP_LINEAR;case THREE.LinearFilter:return c.LINEAR;case THREE.LinearMipMapNearestFilter:return c.LINEAR_MIPMAP_NEAREST;case THREE.LinearMipMapLinearFilter:return c.LINEAR_MIPMAP_LINEAR;case THREE.ByteType:return c.BYTE;case THREE.UnsignedByteType:return c.UNSIGNED_BYTE;case THREE.ShortType:return c.SHORT;case THREE.UnsignedShortType:return c.UNSIGNED_SHORT; case THREE.IntType:return c.INT;case THREE.UnsignedShortType:return c.UNSIGNED_INT;case THREE.FloatType:return c.FLOAT;case THREE.AlphaFormat:return c.ALPHA;case THREE.RGBFormat:return c.RGB;case THREE.RGBAFormat:return c.RGBA;case THREE.LuminanceFormat:return c.LUMINANCE;case THREE.LuminanceAlphaFormat:return c.LUMINANCE_ALPHA}return 0}var j=document.createElement("canvas"),c,k=null,m=null,p=new THREE.Matrix4,z,q=new Float32Array(16),v=new Float32Array(16),A=new Float32Array(16),B=new Float32Array(9), H=new Float32Array(16),s=true,K=new THREE.Color(0),o=0;if(a){if(a.antialias!==undefined)s=a.antialias;a.clearColor!==undefined&&K.setHex(a.clearColor);if(a.clearAlpha!==undefined)o=a.clearAlpha}this.domElement=j;this.autoClear=true;(function(f,n,y){try{c=j.getContext("experimental-webgl",{antialias:f})}catch(r){}if(!c){alert("WebGL not supported");throw"cannot create webgl context";}c.clearColor(0,0,0,1);c.clearDepth(1);c.enable(c.DEPTH_TEST);c.depthFunc(c.LEQUAL);c.frontFace(c.CCW);c.cullFace(c.BACK); c.enable(c.CULL_FACE);c.enable(c.BLEND);c.blendFunc(c.ONE,c.ONE_MINUS_SRC_ALPHA);c.clearColor(n.r,n.g,n.b,y)})(s,K,o);this.context=c;this.lights={ambient:[0,0,0],directional:{length:0,colors:[],positions:[]},point:{length:0,colors:[],positions:[]}};this.setSize=function(f,n){j.width=f;j.height=n;c.viewport(0,0,j.width,j.height)};this.setClearColor=function(f,n){var y=new THREE.Color(f);c.clearColor(y.r,y.g,y.b,n)};this.clear=function(){c.clear(c.COLOR_BUFFER_BIT|c.DEPTH_BUFFER_BIT)};this.setupLights= function(f,n){var y,r,x,L=0,u=0,C=0,E,D,w,N=this.lights,I=N.directional.colors,T=N.directional.positions,V=N.point.colors,O=N.point.positions,ca=0,W=0;y=0;for(r=n.length;y<r;y++){x=n[y];E=x.color;D=x.position;w=x.intensity;if(x instanceof THREE.AmbientLight){L+=E.r;u+=E.g;C+=E.b}else if(x instanceof THREE.DirectionalLight){I[ca*3]=E.r*w;I[ca*3+1]=E.g*w;I[ca*3+2]=E.b*w;T[ca*3]=D.x;T[ca*3+1]=D.y;T[ca*3+2]=D.z;ca+=1}else if(x instanceof THREE.PointLight){V[W*3]=E.r*w;V[W*3+1]=E.g*w;V[W*3+2]=E.b*w;O[W* 3]=D.x;O[W*3+1]=D.y;O[W*3+2]=D.z;W+=1}}N.point.length=W;N.directional.length=ca;N.ambient[0]=L;N.ambient[1]=u;N.ambient[2]=C};this.createParticleBuffers=function(f){f.__webGLVertexBuffer=c.createBuffer();f.__webGLFaceBuffer=c.createBuffer()};this.createLineBuffers=function(f){f.__webGLVertexBuffer=c.createBuffer();f.__webGLLineBuffer=c.createBuffer()};this.createMeshBuffers=function(f){f.__webGLVertexBuffer=c.createBuffer();f.__webGLNormalBuffer=c.createBuffer();f.__webGLTangentBuffer=c.createBuffer(); f.__webGLUVBuffer=c.createBuffer();f.__webGLFaceBuffer=c.createBuffer();f.__webGLLineBuffer=c.createBuffer()};this.initLineBuffers=function(f){var n=f.vertices.length;f.__vertexArray=new Float32Array(n*3);f.__lineArray=new Uint16Array(n);f.__webGLLineCount=n};this.initMeshBuffers=function(f,n){var y,r,x=0,L=0,u=0,C=n.geometry.faces,E=f.faces;y=0;for(r=E.length;y<r;y++){fi=E[y];face=C[fi];if(face instanceof THREE.Face3){x+=3;L+=1;u+=3}else if(face instanceof THREE.Face4){x+=4;L+=2;u+=4}}f.__vertexArray= new Float32Array(x*3);f.__normalArray=new Float32Array(x*3);f.__tangentArray=new Float32Array(x*4);f.__uvArray=new Float32Array(x*2);f.__faceArray=new Uint16Array(L*3);f.__lineArray=new Uint16Array(u*2);x=false;y=0;for(r=n.materials.length;y<r;y++){C=n.materials[y];if(C instanceof THREE.MeshFaceMaterial){C=0;for(E=f.materials.length;C<E;C++)if(f.materials[C]&&f.materials[C].shading!=undefined&&f.materials[C].shading==THREE.SmoothShading){x=true;break}}else if(C&&C.shading!=undefined&&C.shading==THREE.SmoothShading){x= true;break}if(x)break}f.__needsSmoothNormals=x;f.__webGLFaceCount=L*3;f.__webGLLineCount=u*2};this.setMeshBuffers=function(f,n,y,r,x,L,u,C){var E,D,w,N,I,T,V,O,ca,W=0,Q=0,S=0,aa=0,X=0,F=0,R=0,U=f.__vertexArray,ha=f.__uvArray,ga=f.__normalArray,t=f.__tangentArray,J=f.__faceArray,G=f.__lineArray,Y=f.__needsSmoothNormals,ba=n.geometry,fa=ba.vertices,ia=f.faces,pa=ba.faces,ra=ba.uvs;n=0;for(E=ia.length;n<E;n++){D=ia[n];w=pa[D];D=ra[D];N=w.vertexNormals;I=w.normal;if(w instanceof THREE.Face3){if(r){T= fa[w.a].position;V=fa[w.b].position;O=fa[w.c].position;U[Q]=T.x;U[Q+1]=T.y;U[Q+2]=T.z;U[Q+3]=V.x;U[Q+4]=V.y;U[Q+5]=V.z;U[Q+6]=O.x;U[Q+7]=O.y;U[Q+8]=O.z;Q+=9}if(C&&ba.hasTangents){T=fa[w.a].tangent;V=fa[w.b].tangent;O=fa[w.c].tangent;t[F]=T.x;t[F+1]=T.y;t[F+2]=T.z;t[F+3]=T.w;t[F+4]=V.x;t[F+5]=V.y;t[F+6]=V.z;t[F+7]=V.w;t[F+8]=O.x;t[F+9]=O.y;t[F+10]=O.z;t[F+11]=O.w;F+=12}if(u)if(N.length==3&&Y)for(w=0;w<3;w++){I=N[w];ga[X]=I.x;ga[X+1]=I.y;ga[X+2]=I.z;X+=3}else for(w=0;w<3;w++){ga[X]=I.x;ga[X+1]=I.y; ga[X+2]=I.z;X+=3}if(L&&D)for(w=0;w<3;w++){N=D[w];ha[S]=N.u;ha[S+1]=N.v;S+=2}if(x){J[aa]=W;J[aa+1]=W+1;J[aa+2]=W+2;aa+=3;G[R]=W;G[R+1]=W+1;G[R+2]=W;G[R+3]=W+2;G[R+4]=W+1;G[R+5]=W+2;R+=6;W+=3}}else if(w instanceof THREE.Face4){if(r){T=fa[w.a].position;V=fa[w.b].position;O=fa[w.c].position;ca=fa[w.d].position;U[Q]=T.x;U[Q+1]=T.y;U[Q+2]=T.z;U[Q+3]=V.x;U[Q+4]=V.y;U[Q+5]=V.z;U[Q+6]=O.x;U[Q+7]=O.y;U[Q+8]=O.z;U[Q+9]=ca.x;U[Q+10]=ca.y;U[Q+11]=ca.z;Q+=12}if(C&&ba.hasTangents){T=fa[w.a].tangent;V=fa[w.b].tangent; O=fa[w.c].tangent;w=fa[w.d].tangent;t[F]=T.x;t[F+1]=T.y;t[F+2]=T.z;t[F+3]=T.w;t[F+4]=V.x;t[F+5]=V.y;t[F+6]=V.z;t[F+7]=V.w;t[F+8]=O.x;t[F+9]=O.y;t[F+10]=O.z;t[F+11]=O.w;t[F+12]=w.x;t[F+13]=w.y;t[F+14]=w.z;t[F+15]=w.w;F+=16}if(u)if(N.length==4&&Y)for(w=0;w<4;w++){I=N[w];ga[X]=I.x;ga[X+1]=I.y;ga[X+2]=I.z;X+=3}else for(w=0;w<4;w++){ga[X]=I.x;ga[X+1]=I.y;ga[X+2]=I.z;X+=3}if(L&&D)for(w=0;w<4;w++){N=D[w];ha[S]=N.u;ha[S+1]=N.v;S+=2}if(x){J[aa]=W;J[aa+1]=W+1;J[aa+2]=W+2;J[aa+3]=W;J[aa+4]=W+2;J[aa+5]=W+3;aa+= 6;G[R]=W;G[R+1]=W+1;G[R+2]=W;G[R+3]=W+3;G[R+4]=W+1;G[R+5]=W+2;G[R+6]=W+2;G[R+7]=W+3;R+=8;W+=4}}}if(r){c.bindBuffer(c.ARRAY_BUFFER,f.__webGLVertexBuffer);c.bufferData(c.ARRAY_BUFFER,U,y)}if(u){c.bindBuffer(c.ARRAY_BUFFER,f.__webGLNormalBuffer);c.bufferData(c.ARRAY_BUFFER,ga,y)}if(C&&ba.hasTangents){c.bindBuffer(c.ARRAY_BUFFER,f.__webGLTangentBuffer);c.bufferData(c.ARRAY_BUFFER,t,y)}if(L&&S>0){c.bindBuffer(c.ARRAY_BUFFER,f.__webGLUVBuffer);c.bufferData(c.ARRAY_BUFFER,ha,y)}if(x){c.bindBuffer(c.ELEMENT_ARRAY_BUFFER, f.__webGLFaceBuffer);c.bufferData(c.ELEMENT_ARRAY_BUFFER,J,y);c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,f.__webGLLineBuffer);c.bufferData(c.ELEMENT_ARRAY_BUFFER,G,y)}};this.setLineBuffers=function(f,n,y,r){var x,L,u=f.vertices,C=u.length,E=f.__vertexArray,D=f.__lineArray;if(y)for(y=0;y<C;y++){x=u[y].position;L=y*3;E[L]=x.x;E[L+1]=x.y;E[L+2]=x.z}if(r)for(y=0;y<C;y++)D[y]=y;c.bindBuffer(c.ARRAY_BUFFER,f.__webGLVertexBuffer);c.bufferData(c.ARRAY_BUFFER,E,n);c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,f.__webGLLineBuffer); c.bufferData(c.ELEMENT_ARRAY_BUFFER,D,n)};this.setParticleBuffers=function(){};this.renderBuffer=function(f,n,y,r,x,L){var u,C,E,D;if(!r.program){if(r instanceof THREE.MeshDepthMaterial){b(r,THREE.ShaderLib.depth);r.uniforms.mNear.value=f.near;r.uniforms.mFar.value=f.far}else if(r instanceof THREE.MeshNormalMaterial)b(r,THREE.ShaderLib.normal);else if(r instanceof THREE.MeshBasicMaterial){b(r,THREE.ShaderLib.basic);d(r,y)}else if(r instanceof THREE.MeshLambertMaterial){b(r,THREE.ShaderLib.lambert); d(r,y)}else if(r instanceof THREE.MeshPhongMaterial){b(r,THREE.ShaderLib.phong);d(r,y)}else if(r instanceof THREE.LineBasicMaterial){b(r,THREE.ShaderLib.basic);e(r,y)}var w,N,I;w=D=C=0;for(N=n.length;w<N;w++){I=n[w];I instanceof THREE.DirectionalLight&&D++;I instanceof THREE.PointLight&&C++}if(C+D<=4){w=D;C=C}else{w=Math.ceil(4*D/(C+D));C=4-w}C={directional:w,point:C};D={fog:y,map:r.map,env_map:r.env_map,maxDirLights:C.directional,maxPointLights:C.point};C=r.fragment_shader;w=r.vertex_shader;N=c.createProgram(); I=["#ifdef GL_ES\nprecision highp float;\n#endif","#define MAX_DIR_LIGHTS "+D.maxDirLights,"#define MAX_POINT_LIGHTS "+D.maxPointLights,D.fog?"#define USE_FOG":"",D.fog instanceof THREE.FogExp2?"#define FOG_EXP2":"",D.map?"#define USE_MAP":"",D.env_map?"#define USE_ENVMAP":"","uniform mat4 viewMatrix;\nuniform vec3 cameraPosition;\n"].join("\n");D=[c.getParameter(c.MAX_VERTEX_TEXTURE_IMAGE_UNITS)>0?"#define VERTEX_TEXTURES":"","#define MAX_DIR_LIGHTS "+D.maxDirLights,"#define MAX_POINT_LIGHTS "+D.maxPointLights, D.map?"#define USE_MAP":"",D.env_map?"#define USE_ENVMAP":"","uniform mat4 objectMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\n"].join("\n");c.attachShader(N,g("fragment",I+C));c.attachShader(N,g("vertex",D+w));c.linkProgram(N);c.getProgramParameter(N,c.LINK_STATUS)||alert("Could not initialise shaders\nVALIDATE_STATUS: "+ c.getProgramParameter(N,c.VALIDATE_STATUS)+", gl error ["+c.getError()+"]");N.uniforms={};N.attributes={};r.program=N;C=["viewMatrix","modelViewMatrix","projectionMatrix","normalMatrix","objectMatrix","cameraPosition"];for(u in r.uniforms)C.push(u);u=r.program;w=0;for(N=C.length;w<N;w++){I=C[w];u.uniforms[I]=c.getUniformLocation(u,I)}u=r.program;C=["position","normal","uv","tangent"];w=0;for(N=C.length;w<N;w++){I=C[w];u.attributes[I]=c.getAttribLocation(u,I)}}u=r.program;if(u!=k){c.useProgram(u); k=u}this.loadCamera(u,f);this.loadMatrices(u);if(r instanceof THREE.MeshPhongMaterial||r instanceof THREE.MeshLambertMaterial){this.setupLights(u,n);f=this.lights;r.uniforms.enableLighting.value=f.directional.length+f.point.length;r.uniforms.ambientLightColor.value=f.ambient;r.uniforms.directionalLightColor.value=f.directional.colors;r.uniforms.directionalLightDirection.value=f.directional.positions;r.uniforms.pointLightColor.value=f.point.colors;r.uniforms.pointLightPosition.value=f.point.positions}if(r instanceof THREE.MeshBasicMaterial||r instanceof THREE.MeshLambertMaterial||r instanceof THREE.MeshPhongMaterial)d(r,y);r instanceof THREE.LineBasicMaterial&&e(r,y);if(r instanceof THREE.MeshPhongMaterial){r.uniforms.ambient.value.setRGB(r.ambient.r,r.ambient.g,r.ambient.b);r.uniforms.specular.value.setRGB(r.specular.r,r.specular.g,r.specular.b);r.uniforms.shininess.value=r.shininess}y=r.uniforms;for(E in y)if(w=u.uniforms[E]){n=y[E];C=n.type;f=n.value;if(C=="i")c.uniform1i(w,f);else if(C=="f")c.uniform1f(w, f);else if(C=="fv1")c.uniform1fv(w,f);else if(C=="fv")c.uniform3fv(w,f);else if(C=="v2")c.uniform2f(w,f.x,f.y);else if(C=="v3")c.uniform3f(w,f.x,f.y,f.z);else if(C=="c")c.uniform3f(w,f.r,f.g,f.b);else if(C=="t"){c.uniform1i(w,f);if(n=n.texture)if(n.image instanceof Array&&n.image.length==6){n=n;f=f;if(n.image.length==6){if(!n.image.__webGLTextureCube&&!n.image.__cubeMapInitialized&&n.image.loadCount==6){n.image.__webGLTextureCube=c.createTexture();c.bindTexture(c.TEXTURE_CUBE_MAP,n.image.__webGLTextureCube); c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE);c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE);c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MAG_FILTER,c.LINEAR);c.texParameteri(c.TEXTURE_CUBE_MAP,c.TEXTURE_MIN_FILTER,c.LINEAR_MIPMAP_LINEAR);for(C=0;C<6;++C)c.texImage2D(c.TEXTURE_CUBE_MAP_POSITIVE_X+C,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n.image[C]);c.generateMipmap(c.TEXTURE_CUBE_MAP);c.bindTexture(c.TEXTURE_CUBE_MAP,null);n.image.__cubeMapInitialized=true}c.activeTexture(c.TEXTURE0+ f);c.bindTexture(c.TEXTURE_CUBE_MAP,n.image.__webGLTextureCube)}}else{n=n;f=f;if(!n.__webGLTexture&&n.image.loaded){n.__webGLTexture=c.createTexture();c.bindTexture(c.TEXTURE_2D,n.__webGLTexture);c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n.image);c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,h(n.wrap_s));c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,h(n.wrap_t));c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,h(n.mag_filter));c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,h(n.min_filter)); c.generateMipmap(c.TEXTURE_2D);c.bindTexture(c.TEXTURE_2D,null)}c.activeTexture(c.TEXTURE0+f);c.bindTexture(c.TEXTURE_2D,n.__webGLTexture)}}}E=u.attributes;c.bindBuffer(c.ARRAY_BUFFER,x.__webGLVertexBuffer);c.vertexAttribPointer(E.position,3,c.FLOAT,false,0,0);c.enableVertexAttribArray(E.position);if(E.normal>=0){c.bindBuffer(c.ARRAY_BUFFER,x.__webGLNormalBuffer);c.vertexAttribPointer(E.normal,3,c.FLOAT,false,0,0);c.enableVertexAttribArray(E.normal)}if(E.tangent>=0){c.bindBuffer(c.ARRAY_BUFFER,x.__webGLTangentBuffer); c.vertexAttribPointer(E.tangent,4,c.FLOAT,false,0,0);c.enableVertexAttribArray(E.tangent)}if(E.uv>=0)if(x.__webGLUVBuffer){c.bindBuffer(c.ARRAY_BUFFER,x.__webGLUVBuffer);c.vertexAttribPointer(E.uv,2,c.FLOAT,false,0,0);c.enableVertexAttribArray(E.uv)}else c.disableVertexAttribArray(E.uv);if(r.wireframe||r instanceof THREE.LineBasicMaterial){E=r.wireframe_linewidth!==undefined?r.wireframe_linewidth:r.linewidth!==undefined?r.linewidth:1;r=r instanceof THREE.LineBasicMaterial&&L.type==THREE.LineStrip? c.LINE_STRIP:c.LINES;c.lineWidth(E);c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,x.__webGLLineBuffer);c.drawElements(r,x.__webGLLineCount,c.UNSIGNED_SHORT,0)}else{c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,x.__webGLFaceBuffer);c.drawElements(c.TRIANGLES,x.__webGLFaceCount,c.UNSIGNED_SHORT,0)}};this.renderPass=function(f,n,y,r,x,L,u){var C,E,D,w,N;D=0;for(w=r.materials.length;D<w;D++){C=r.materials[D];if(C instanceof THREE.MeshFaceMaterial){C=0;for(E=x.materials.length;C<E;C++)if((N=x.materials[C])&&N.blending==L&& N.opacity<1==u){this.setBlending(N.blending);this.renderBuffer(f,n,y,N,x,r)}}else if((N=C)&&N.blending==L&&N.opacity<1==u){this.setBlending(N.blending);this.renderBuffer(f,n,y,N,x,r)}}};this.render=function(f,n,y,r){var x,L,u,C=f.lights,E=f.fog;this.initWebGLObjects(f);r=r!==undefined?r:true;if(y&&!y.__webGLFramebuffer){y.__webGLFramebuffer=c.createFramebuffer();y.__webGLRenderbuffer=c.createRenderbuffer();y.__webGLTexture=c.createTexture();c.bindRenderbuffer(c.RENDERBUFFER,y.__webGLRenderbuffer); c.renderbufferStorage(c.RENDERBUFFER,c.DEPTH_COMPONENT16,y.width,y.height);c.bindTexture(c.TEXTURE_2D,y.__webGLTexture);c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,h(y.wrap_s));c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,h(y.wrap_t));c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,h(y.mag_filter));c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,h(y.min_filter));c.texImage2D(c.TEXTURE_2D,0,h(y.format),y.width,y.height,0,h(y.format),h(y.type),null);c.bindFramebuffer(c.FRAMEBUFFER,y.__webGLFramebuffer); c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,y.__webGLTexture,0);c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_ATTACHMENT,c.RENDERBUFFER,y.__webGLRenderbuffer);c.bindTexture(c.TEXTURE_2D,null);c.bindRenderbuffer(c.RENDERBUFFER,null);c.bindFramebuffer(c.FRAMEBUFFER,null)}if(y){x=y.__webGLFramebuffer;u=y.width;L=y.height}else{x=null;u=j.width;L=j.height}if(x!=m){c.bindFramebuffer(c.FRAMEBUFFER,x);c.viewport(0,0,u,L);r&&c.clear(c.COLOR_BUFFER_BIT|c.DEPTH_BUFFER_BIT);m=x}this.autoClear&& this.clear();n.autoUpdateMatrix&&n.updateMatrix();q.set(n.matrix.flatten());A.set(n.projectionMatrix.flatten());r=0;for(x=f.__webGLObjects.length;r<x;r++){L=f.__webGLObjects[r];u=L.object;L=L.buffer;if(u.visible){this.setupMatrices(u,n);this.renderPass(n,C,E,u,L,THREE.NormalBlending,false)}}r=0;for(x=f.__webGLObjects.length;r<x;r++){L=f.__webGLObjects[r];u=L.object;L=L.buffer;if(u.visible){this.setupMatrices(u,n);if(u.doubleSided)c.disable(c.CULL_FACE);else{c.enable(c.CULL_FACE);u.flipSided?c.frontFace(c.CW): c.frontFace(c.CCW)}this.renderPass(n,C,E,u,L,THREE.AdditiveBlending,false);this.renderPass(n,C,E,u,L,THREE.SubtractiveBlending,false);this.renderPass(n,C,E,u,L,THREE.AdditiveBlending,true);this.renderPass(n,C,E,u,L,THREE.SubtractiveBlending,true);this.renderPass(n,C,E,u,L,THREE.NormalBlending,true)}}if(y&&y.min_filter!==THREE.NearestFilter&&y.min_filter!==THREE.LinearFilter){c.bindTexture(c.TEXTURE_2D,y.__webGLTexture);c.generateMipmap(c.TEXTURE_2D);c.bindTexture(c.TEXTURE_2D,null)}};this.initWebGLObjects= function(f){function n(D,w,N,I){if(D[w]==undefined){f.__webGLObjects.push({buffer:N,object:I});D[w]=1}}var y,r,x,L,u,C,E;if(!f.__webGLObjects){f.__webGLObjects=[];f.__webGLObjectsMap={}}y=0;for(r=f.objects.length;y<r;y++){x=f.objects[y];u=x.geometry;if(f.__webGLObjectsMap[x.id]==undefined)f.__webGLObjectsMap[x.id]={};E=f.__webGLObjectsMap[x.id];if(x instanceof THREE.Mesh){for(L in u.geometryChunks){C=u.geometryChunks[L];if(!C.__webGLVertexBuffer){this.createMeshBuffers(C);this.initMeshBuffers(C,x); u.__dirtyVertices=true;u.__dirtyElements=true;u.__dirtyUvs=true;u.__dirtyNormals=true;u.__dirtyTangents=true}if(u.__dirtyVertices||u.__dirtyElements||u.__dirtyUvs)this.setMeshBuffers(C,x,c.DYNAMIC_DRAW,u.__dirtyVertices,u.__dirtyElements,u.__dirtyUvs,u.__dirtyNormals,u.__dirtyTangents);n(E,L,C,x)}u.__dirtyVertices=false;u.__dirtyElements=false;u.__dirtyUvs=false;u.__dirtyNormals=false;u.__dirtyTangents=false}else if(x instanceof THREE.Line){if(!u.__webGLVertexBuffer){this.createLineBuffers(u);this.initLineBuffers(u); u.__dirtyVertices=true;u.__dirtyElements=true}u.__dirtyVertices&&this.setLineBuffers(u,c.DYNAMIC_DRAW,u.__dirtyVertices,u.__dirtyElements);n(E,0,u,x);u.__dirtyVertices=false;u.__dirtyElements=false}else if(x instanceof THREE.ParticleSystem){u.__webGLVertexBuffer||this.createParticleBuffers(u);n(E,0,u,x)}}};this.removeObject=function(f,n){var y,r;for(y=f.__webGLObjects.length-1;y>=0;y--){r=f.__webGLObjects[y].object;n==r&&f.__webGLObjects.splice(y,1)}};this.setupMatrices=function(f,n){f.autoUpdateMatrix&& f.updateMatrix();p.multiply(n.matrix,f.matrix);v.set(p.flatten());z=THREE.Matrix4.makeInvert3x3(p).transpose();B.set(z.m);H.set(f.matrix.flatten())};this.loadMatrices=function(f){c.uniformMatrix4fv(f.uniforms.viewMatrix,false,q);c.uniformMatrix4fv(f.uniforms.modelViewMatrix,false,v);c.uniformMatrix4fv(f.uniforms.projectionMatrix,false,A);c.uniformMatrix3fv(f.uniforms.normalMatrix,false,B);c.uniformMatrix4fv(f.uniforms.objectMatrix,false,H)};this.loadCamera=function(f,n){c.uniform3f(f.uniforms.cameraPosition, n.position.x,n.position.y,n.position.z)};this.setBlending=function(f){switch(f){case THREE.AdditiveBlending:c.blendEquation(c.FUNC_ADD);c.blendFunc(c.ONE,c.ONE);break;case THREE.SubtractiveBlending:c.blendFunc(c.DST_COLOR,c.ZERO);break;default:c.blendEquation(c.FUNC_ADD);c.blendFunc(c.ONE,c.ONE_MINUS_SRC_ALPHA)}};this.setFaceCulling=function(f,n){if(f){!n||n=="ccw"?c.frontFace(c.CCW):c.frontFace(c.CW);if(f=="back")c.cullFace(c.BACK);else f=="front"?c.cullFace(c.FRONT):c.cullFace(c.FRONT_AND_BACK); c.enable(c.CULL_FACE)}else c.disable(c.CULL_FACE)};this.supportsVertexTextures=function(){return c.getParameter(c.MAX_VERTEX_TEXTURE_IMAGE_UNITS)>0}}; THREE.Snippets={fog_pars_fragment:"#ifdef USE_FOG\nuniform vec3 fogColor;\n#ifdef FOG_EXP2\nuniform float fogDensity;\n#else\nuniform float fogNear;\nuniform float fogFar;\n#endif\n#endif",fog_fragment:"#ifdef USE_FOG\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n#ifdef FOG_EXP2\nconst float LOG2 = 1.442695;\nfloat fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n#else\nfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n#endif\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, 1.0 ), fogFactor );\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\nvarying vec3 vReflect;\nuniform float reflectivity;\nuniform samplerCube env_map;\nuniform int combine;\n#endif", envmap_fragment:"#ifdef USE_ENVMAP\ncubeColor = textureCube( env_map, vec3( -vReflect.x, vReflect.yz ) );\nif ( combine == 1 ) {\ngl_FragColor = mix( gl_FragColor, cubeColor, reflectivity );\n} else {\ngl_FragColor = gl_FragColor * cubeColor;\n}\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\nvarying vec3 vReflect;\nuniform float refraction_ratio;\nuniform bool useRefract;\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\nvec4 mPosition = objectMatrix * vec4( position, 1.0 );\nvec3 nWorld = mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal;\nif ( useRefract ) {\nvReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refraction_ratio );\n} else {\nvReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );\n}\n#endif", map_pars_fragment:"#ifdef USE_MAP\nvarying vec2 vUv;\nuniform sampler2D map;\n#endif",map_pars_vertex:"#ifdef USE_MAP\nvarying vec2 vUv;\n#endif",map_fragment:"#ifdef USE_MAP\nmapColor = texture2D( map, vUv );\n#endif",map_vertex:"#ifdef USE_MAP\nvUv = uv;\n#endif",lights_pars_vertex:"uniform bool enableLighting;\nuniform vec3 ambientLightColor;\n#if MAX_DIR_LIGHTS > 0\nuniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\nuniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n#endif\n#if MAX_POINT_LIGHTS > 0\nuniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\nuniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n#ifdef PHONG\nvarying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];\n#endif\n#endif", lights_vertex:"if ( !enableLighting ) {\nvLightWeighting = vec3( 1.0 );\n} else {\nvLightWeighting = ambientLightColor;\n#if MAX_DIR_LIGHTS > 0\nfor( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {\nvec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );\nfloat directionalLightWeighting = max( dot( transformedNormal, normalize( lDirection.xyz ) ), 0.0 );\nvLightWeighting += directionalLightColor[ i ] * directionalLightWeighting;\n}\n#endif\n#if MAX_POINT_LIGHTS > 0\nfor( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {\nvec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\nvec3 pointLightVector = normalize( lPosition.xyz - mvPosition.xyz );\nfloat pointLightWeighting = max( dot( transformedNormal, pointLightVector ), 0.0 );\nvLightWeighting += pointLightColor[ i ] * pointLightWeighting;\n#ifdef PHONG\nvPointLightVector[ i ] = pointLightVector;\n#endif\n}\n#endif\n}", lights_pars_fragment:"#if MAX_DIR_LIGHTS > 0\nuniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n#endif\n#if MAX_POINT_LIGHTS > 0\nvarying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];\n#endif\nvarying vec3 vViewPosition;\nvarying vec3 vNormal;",lights_fragment:"vec3 normal = normalize( vNormal );\nvec3 viewPosition = normalize( vViewPosition );\nvec4 mSpecular = vec4( specular, opacity );\n#if MAX_POINT_LIGHTS > 0\nvec4 pointDiffuse = vec4( 0.0 );\nvec4 pointSpecular = vec4( 0.0 );\nfor( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {\nvec3 pointVector = normalize( vPointLightVector[ i ] );\nvec3 pointHalfVector = normalize( vPointLightVector[ i ] + vViewPosition );\nfloat pointDotNormalHalf = dot( normal, pointHalfVector );\nfloat pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );\nfloat pointSpecularWeight = 0.0;\nif ( pointDotNormalHalf >= 0.0 )\npointSpecularWeight = pow( pointDotNormalHalf, shininess );\npointDiffuse += mColor * pointDiffuseWeight;\npointSpecular += mSpecular * pointSpecularWeight;\n}\n#endif\n#if MAX_DIR_LIGHTS > 0\nvec4 dirDiffuse = vec4( 0.0 );\nvec4 dirSpecular = vec4( 0.0 );\nfor( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {\nvec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );\nvec3 dirVector = normalize( lDirection.xyz );\nvec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );\nfloat dirDotNormalHalf = dot( normal, dirHalfVector );\nfloat dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );\nfloat dirSpecularWeight = 0.0;\nif ( dirDotNormalHalf >= 0.0 )\ndirSpecularWeight = pow( dirDotNormalHalf, shininess );\ndirDiffuse += mColor * dirDiffuseWeight;\ndirSpecular += mSpecular * dirSpecularWeight;\n}\n#endif\nvec4 totalLight = vec4( ambient, opacity );\n#if MAX_DIR_LIGHTS > 0\ntotalLight += dirDiffuse + dirSpecular;\n#endif\n#if MAX_POINT_LIGHTS > 0\ntotalLight += pointDiffuse + pointSpecular;\n#endif"}; THREE.UniformsLib={common:{color:{type:"c",value:new THREE.Color(15658734)},opacity:{type:"f",value:1},map:{type:"t",value:0,texture:null},env_map:{type:"t",value:1,texture:null},useRefract:{type:"i",value:0},reflectivity:{type:"f",value:1},refraction_ratio:{type:"f",value:0.98},combine:{type:"i",value:0},fogDensity:{type:"f",value:2.5E-4},fogNear:{type:"f",value:1},fogFar:{type:"f",value:2E3},fogColor:{type:"c",value:new THREE.Color(16777215)}},lights:{enableLighting:{type:"i",value:1},ambientLightColor:{type:"fv", value:[]},directionalLightDirection:{type:"fv",value:[]},directionalLightColor:{type:"fv",value:[]},pointLightPosition:{type:"fv",value:[]},pointLightColor:{type:"fv",value:[]}}}; THREE.ShaderLib={depth:{uniforms:{mNear:{type:"f",value:1},mFar:{type:"f",value:2E3}},fragment_shader:"uniform float mNear;\nuniform float mFar;\nvoid main() {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat color = 1.0 - smoothstep( mNear, mFar, depth );\ngl_FragColor = vec4( vec3( color ), 1.0 );\n}",vertex_shader:"void main() {\ngl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"},normal:{uniforms:{},fragment_shader:"varying vec3 vNormal;\nvoid main() {\ngl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, 1.0 );\n}", vertex_shader:"varying vec3 vNormal;\nvoid main() {\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\nvNormal = normalize( normalMatrix * normal );\ngl_Position = projectionMatrix * mvPosition;\n}"},basic:{uniforms:THREE.UniformsLib.common,fragment_shader:["uniform vec3 color;\nuniform float opacity;",THREE.Snippets.map_pars_fragment,THREE.Snippets.envmap_pars_fragment,THREE.Snippets.fog_pars_fragment,"void main() {\nvec4 mColor = vec4( color, opacity );\nvec4 mapColor = vec4( 1.0 );\nvec4 cubeColor = vec4( 1.0 );", THREE.Snippets.map_fragment,"gl_FragColor = mColor * mapColor;",THREE.Snippets.envmap_fragment,THREE.Snippets.fog_fragment,"}"].join("\n"),vertex_shader:[THREE.Snippets.map_pars_vertex,THREE.Snippets.envmap_pars_vertex,"void main() {\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",THREE.Snippets.map_vertex,THREE.Snippets.envmap_vertex,"gl_Position = projectionMatrix * mvPosition;\n}"].join("\n")},lambert:{uniforms:Uniforms.merge([THREE.UniformsLib.common,THREE.UniformsLib.lights]),fragment_shader:["uniform vec3 color;\nuniform float opacity;\nvarying vec3 vLightWeighting;", THREE.Snippets.map_pars_fragment,THREE.Snippets.envmap_pars_fragment,THREE.Snippets.fog_pars_fragment,"void main() {\nvec4 mColor = vec4( color, opacity );\nvec4 mapColor = vec4( 1.0 );\nvec4 cubeColor = vec4( 1.0 );",THREE.Snippets.map_fragment,"gl_FragColor = mColor * mapColor * vec4( vLightWeighting, 1.0 );",THREE.Snippets.envmap_fragment,THREE.Snippets.fog_fragment,"}"].join("\n"),vertex_shader:["varying vec3 vLightWeighting;",THREE.Snippets.map_pars_vertex,THREE.Snippets.envmap_pars_vertex, THREE.Snippets.lights_pars_vertex,"void main() {\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",THREE.Snippets.map_vertex,THREE.Snippets.envmap_vertex,"vec3 transformedNormal = normalize( normalMatrix * normal );",THREE.Snippets.lights_vertex,"gl_Position = projectionMatrix * mvPosition;\n}"].join("\n")},phong:{uniforms:Uniforms.merge([THREE.UniformsLib.common,THREE.UniformsLib.lights,{ambient:{type:"c",value:new THREE.Color(328965)},specular:{type:"c",value:new THREE.Color(1118481)}, shininess:{type:"f",value:30}}]),fragment_shader:["uniform vec3 color;\nuniform float opacity;\nuniform vec3 ambient;\nuniform vec3 specular;\nuniform float shininess;\nvarying vec3 vLightWeighting;",THREE.Snippets.map_pars_fragment,THREE.Snippets.envmap_pars_fragment,THREE.Snippets.fog_pars_fragment,THREE.Snippets.lights_pars_fragment,"void main() {\nvec4 mColor = vec4( color, opacity );\nvec4 mapColor = vec4( 1.0 );\nvec4 cubeColor = vec4( 1.0 );",THREE.Snippets.map_fragment,THREE.Snippets.lights_fragment, "gl_FragColor = mapColor * totalLight * vec4( vLightWeighting, 1.0 );",THREE.Snippets.envmap_fragment,THREE.Snippets.fog_fragment,"}"].join("\n"),vertex_shader:["#define PHONG\nvarying vec3 vLightWeighting;\nvarying vec3 vViewPosition;\nvarying vec3 vNormal;",THREE.Snippets.map_pars_vertex,THREE.Snippets.envmap_pars_vertex,THREE.Snippets.lights_pars_vertex,"void main() {\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",THREE.Snippets.map_vertex,THREE.Snippets.envmap_vertex,"#ifndef USE_ENVMAP\nvec4 mPosition = objectMatrix * vec4( position, 1.0 );\n#endif\nvViewPosition = cameraPosition - mPosition.xyz;\nvec3 transformedNormal = normalize( normalMatrix * normal );\nvNormal = transformedNormal;", THREE.Snippets.lights_vertex,"gl_Position = projectionMatrix * mvPosition;\n}"].join("\n")}};THREE.RenderableObject=function(){this.z=this.object=null};THREE.RenderableFace3=function(){this.z=null;this.v1=new THREE.Vertex;this.v2=new THREE.Vertex;this.v3=new THREE.Vertex;this.centroidWorld=new THREE.Vector3;this.centroidScreen=new THREE.Vector3;this.normalWorld=new THREE.Vector3;this.vertexNormalsWorld=[];this.faceMaterials=this.meshMaterials=null;this.overdraw=false;this.uvs=[null,null,null]}; THREE.RenderableParticle=function(){this.rotation=this.z=this.y=this.x=null;this.scale=new THREE.Vector2;this.materials=null};THREE.RenderableLine=function(){this.z=null;this.v1=new THREE.Vertex;this.v2=new THREE.Vertex;this.materials=null}; var GeometryUtils={merge:function(a,b){var d=b instanceof THREE.Mesh,e=a.vertices.length,g=d?b.geometry:b,h=a.vertices,j=g.vertices,c=a.faces,k=g.faces,m=a.uvs;g=g.uvs;d&&b.autoUpdateMatrix&&b.updateMatrix();for(var p=0,z=j.length;p<z;p++){var q=new THREE.Vertex(j[p].position.clone());d&&b.matrix.multiplyVector3(q.position);h.push(q)}p=0;for(z=k.length;p<z;p++){j=k[p];var v,A=j.vertexNormals;if(j instanceof THREE.Face3)v=new THREE.Face3(j.a+e,j.b+e,j.c+e);else if(j instanceof THREE.Face4)v=new THREE.Face4(j.a+ e,j.b+e,j.c+e,j.d+e);v.centroid.copy(j.centroid);v.normal.copy(j.normal);d=0;for(h=A.length;d<h;d++){q=A[d];v.vertexNormals.push(q.clone())}v.materials=j.materials.slice();c.push(v)}p=0;for(z=g.length;p<z;p++){e=g[p];c=[];d=0;for(h=e.length;d<h;d++)c.push(new THREE.UV(e[d].u,e[d].v));m.push(c)}}},ImageUtils={loadTexture:function(a,b){var d=new Image;d.onload=function(){this.loaded=true};d.src=a;return new THREE.Texture(d,b)},loadArray:function(a){var b,d,e=[];b=e.loadCount=0;for(d=a.length;b<d;++b){e[b]= new Image;e[b].loaded=0;e[b].onload=function(){e.loadCount+=1;this.loaded=true};e[b].src=a[b]}return e}},SceneUtils={loadScene:function(a,b){var d,e,g,h,j,c,k,m,p,z,q,v,A,B,H,s=new Worker(a);s.onmessage=function(K){function o(){for(d in f.objects)if(!n.objects[d]){g=f.objects[d];if(z=n.geometries[g.geometry]){A=[];for(i=0;i<g.materials.length;i++)A[i]=n.materials[g.materials[i]];j=g.position;c=g.rotation;k=g.scale;object=new THREE.Mesh(z,A);object.position.set(j[0],j[1],j[2]);object.rotation.set(c[0], c[1],c[2]);object.scale.set(k[0],k[1],k[2]);object.visible=g.visible;n.scene.addObject(object);n.objects[d]=object}}}var f=K.data;console.log(f);var n={scene:new THREE.Scene,geometries:{},materials:{},objects:{},cameras:{}};for(d in f.geometries){e=f.geometries[d];if(e.type=="cube"){z=new Cube(e.width,e.height,e.depth,e.segments_width,e.segments_height,null,e.flipped,e.sides);n.geometries[d]=z}else if(e.type=="plane"){z=new Plane(e.width,e.height,e.segments_width,e.segments_height);n.geometries[d]= z}else if(e.type=="sphere"){z=new Sphere(e.radius,e.segments_width,e.segments_height);n.geometries[d]=z}else if(e.type=="bin_mesh"){B||(B=new THREE.Loader);H=function(y){console.log(y);n.geometries[d]=y;o()};B.loadBinary({model:"obj/male02/Male02_bin.js",callback:H})}}for(d in f.materials){h=f.materials[d];q=new THREE[h.type](h.parameters);n.materials[d]=q}o();for(d in f.lights){l=f.lights[d];if(l.type=="directional"){j=l.direction;light=new THREE.DirectionalLight;light.position.set(j[0],j[1],j[2]); light.position.normalize()}else if(l.type=="point"){j=l.position;light=new THREE.PointLight;light.position.set(j[0],j[1],j[2])}p=l.color;light.color.setRGB(p[0],p[1],p[2]);n.scene.addLight(light)}for(d in f.cameras){p=f.cameras[d];if(p.type=="perspective")v=new THREE.Camera(p.fov,p.aspect,p.near,p.far);else if(p.type=="ortho"){v=new THREE.Camera;v.projectionMatrix=THREE.Matrix4.makeOrtho(p.left,p.right,p.top,p.bottom,p.near,p.far)}j=p.position;m=p.target;v.position.set(j[0],j[1],j[2]);v.target.position.set(m[0], m[1],m[2]);n.cameras[d]=v}n.currentCamera=n.cameras[f.defaults.camera];b(n)};s.postMessage(0)},addMesh:function(a,b,d,e,g,h,j,c,k,m){b=new THREE.Mesh(b,m);b.scale.x=b.scale.y=b.scale.z=d;b.position.x=e;b.position.y=g;b.position.z=h;b.rotation.x=j;b.rotation.y=c;b.rotation.z=k;a.addObject(b);return b},addPanoramaCubeWebGL:function(a,b,d){var e=ShaderUtils.lib.cube;e.uniforms.tCube.texture=d;d=new THREE.MeshShaderMaterial({fragment_shader:e.fragment_shader,vertex_shader:e.vertex_shader,uniforms:e.uniforms}); b=new THREE.Mesh(new Cube(b,b,b,1,1,null,true),d);a.addObject(b);return b},addPanoramaCube:function(a,b,d){var e=[];e.push(new THREE.MeshBasicMaterial({map:new THREE.Texture(d[0])}));e.push(new THREE.MeshBasicMaterial({map:new THREE.Texture(d[1])}));e.push(new THREE.MeshBasicMaterial({map:new THREE.Texture(d[2])}));e.push(new THREE.MeshBasicMaterial({map:new THREE.Texture(d[3])}));e.push(new THREE.MeshBasicMaterial({map:new THREE.Texture(d[4])}));e.push(new THREE.MeshBasicMaterial({map:new THREE.Texture(d[5])})); b=new THREE.Mesh(new Cube(b,b,b,1,1,e,true),new THREE.MeshFaceMaterial);a.addObject(b);return b},addPanoramaCubePlanes:function(a,b,d){var e=b/2;b=new Plane(b,b);var g=Math.PI/2,h=Math.PI;SceneUtils.addMesh(a,b,1,0,0,-e,0,0,0,new THREE.MeshBasicMaterial({map:new THREE.Texture(d[5])}));SceneUtils.addMesh(a,b,1,-e,0,0,0,g,0,new THREE.MeshBasicMaterial({map:new THREE.Texture(d[0])}));SceneUtils.addMesh(a,b,1,e,0,0,0,-g,0,new THREE.MeshBasicMaterial({map:new THREE.Texture(d[1])}));SceneUtils.addMesh(a, b,1,0,e,0,g,0,h,new THREE.MeshBasicMaterial({map:new THREE.Texture(d[2])}));SceneUtils.addMesh(a,b,1,0,-e,0,-g,0,h,new THREE.MeshBasicMaterial({map:new THREE.Texture(d[3])}))}},ShaderUtils={lib:{fresnel:{uniforms:{mRefractionRatio:{type:"f",value:1.02},mFresnelBias:{type:"f",value:0.1},mFresnelPower:{type:"f",value:2},mFresnelScale:{type:"f",value:1},tCube:{type:"t",value:1,texture:null}},fragment_shader:"uniform samplerCube tCube;\nvarying vec3 vReflect;\nvarying vec3 vRefract[3];\nvarying float vReflectionFactor;\nvoid main() {\nvec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );\nvec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );\nrefractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;\nrefractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;\nrefractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;\nrefractedColor.a = 1.0;\ngl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );\n}", vertex_shader:"uniform float mRefractionRatio;\nuniform float mFresnelBias;\nuniform float mFresnelScale;\nuniform float mFresnelPower;\nvarying vec3 vReflect;\nvarying vec3 vRefract[3];\nvarying float vReflectionFactor;\nvoid main(void) {\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\nvec4 mPosition = objectMatrix * vec4( position, 1.0 );\nvec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );\nvec3 I = mPosition.xyz - cameraPosition;\nvReflect = reflect( I, nWorld );\nvRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );\nvRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );\nvRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );\nvReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );\ngl_Position = projectionMatrix * mvPosition;\n}"}, normal:{uniforms:{enableAO:{type:"i",value:0},enableDiffuse:{type:"i",value:0},tDiffuse:{type:"t",value:0,texture:null},tNormal:{type:"t",value:2,texture:null},tAO:{type:"t",value:3,texture:null},uNormalScale:{type:"f",value:1},tDisplacement:{type:"t",value:4,texture:null},uDisplacementBias:{type:"f",value:-0.5},uDisplacementScale:{type:"f",value:2.5},uPointLightPos:{type:"v3",value:new THREE.Vector3},uPointLightColor:{type:"c",value:new THREE.Color(15658734)},uDirLightPos:{type:"v3",value:new THREE.Vector3}, uDirLightColor:{type:"c",value:new THREE.Color(15658734)},uAmbientLightColor:{type:"c",value:new THREE.Color(328965)},uDiffuseColor:{type:"c",value:new THREE.Color(15658734)},uSpecularColor:{type:"c",value:new THREE.Color(1118481)},uAmbientColor:{type:"c",value:new THREE.Color(328965)},uShininess:{type:"f",value:30}},fragment_shader:"uniform vec3 uDirLightPos;\nuniform vec3 uAmbientLightColor;\nuniform vec3 uDirLightColor;\nuniform vec3 uPointLightColor;\nuniform vec3 uAmbientColor;\nuniform vec3 uDiffuseColor;\nuniform vec3 uSpecularColor;\nuniform float uShininess;\nuniform bool enableDiffuse;\nuniform bool enableAO;\nuniform sampler2D tDiffuse;\nuniform sampler2D tNormal;\nuniform sampler2D tAO;\nuniform float uNormalScale;\nvarying vec3 vTangent;\nvarying vec3 vBinormal;\nvarying vec3 vNormal;\nvarying vec2 vUv;\nvarying vec3 vPointLightVector;\nvarying vec3 vViewPosition;\nvoid main() {\nvec3 diffuseTex = vec3( 1.0, 1.0, 1.0 );\nvec3 aoTex = vec3( 1.0, 1.0, 1.0 );\nvec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;\nnormalTex.xy *= uNormalScale;\nnormalTex = normalize( normalTex );\nif( enableDiffuse )\ndiffuseTex = texture2D( tDiffuse, vUv ).xyz;\nif( enableAO )\naoTex = texture2D( tAO, vUv ).xyz;\nmat3 tsb = mat3( vTangent, vBinormal, vNormal );\nvec3 finalNormal = tsb * normalTex;\nvec3 normal = normalize( finalNormal );\nvec3 viewPosition = normalize( vViewPosition );\nvec4 pointDiffuse = vec4( 0.0, 0.0, 0.0, 0.0 );\nvec4 pointSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );\nvec3 pointVector = normalize( vPointLightVector );\nvec3 pointHalfVector = normalize( vPointLightVector + vViewPosition );\nfloat pointDotNormalHalf = dot( normal, pointHalfVector );\nfloat pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );\nfloat pointSpecularWeight = 0.0;\nif ( pointDotNormalHalf >= 0.0 )\npointSpecularWeight = pow( pointDotNormalHalf, uShininess );\npointDiffuse += vec4( uDiffuseColor, 1.0 ) * pointDiffuseWeight;\npointSpecular += vec4( uSpecularColor, 1.0 ) * pointSpecularWeight;\nvec4 dirDiffuse = vec4( 0.0, 0.0, 0.0, 0.0 );\nvec4 dirSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );\nvec4 lDirection = viewMatrix * vec4( uDirLightPos, 0.0 );\nvec3 dirVector = normalize( lDirection.xyz );\nvec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );\nfloat dirDotNormalHalf = dot( normal, dirHalfVector );\nfloat dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );\nfloat dirSpecularWeight = 0.0;\nif ( dirDotNormalHalf >= 0.0 )\ndirSpecularWeight = pow( dirDotNormalHalf, uShininess );\ndirDiffuse += vec4( uDiffuseColor, 1.0 ) * dirDiffuseWeight;\ndirSpecular += vec4( uSpecularColor, 1.0 ) * dirSpecularWeight;\nvec4 totalLight = vec4( uAmbientLightColor * uAmbientColor, 1.0 );\ntotalLight += vec4( uDirLightColor, 1.0 ) * ( dirDiffuse + dirSpecular );\ntotalLight += vec4( uPointLightColor, 1.0 ) * ( pointDiffuse + pointSpecular );\ngl_FragColor = vec4( totalLight.xyz * aoTex * diffuseTex, 1.0 );\n}", vertex_shader:"attribute vec4 tangent;\nuniform vec3 uPointLightPos;\n#ifdef VERTEX_TEXTURES\nuniform sampler2D tDisplacement;\nuniform float uDisplacementScale;\nuniform float uDisplacementBias;\n#endif\nvarying vec3 vTangent;\nvarying vec3 vBinormal;\nvarying vec3 vNormal;\nvarying vec2 vUv;\nvarying vec3 vPointLightVector;\nvarying vec3 vViewPosition;\nvoid main() {\nvec4 mPosition = objectMatrix * vec4( position, 1.0 );\nvViewPosition = cameraPosition - mPosition.xyz;\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\nvNormal = normalize( normalMatrix * normal );\nvTangent = normalize( normalMatrix * tangent.xyz );\nvBinormal = cross( vNormal, vTangent ) * tangent.w;\nvBinormal = normalize( vBinormal );\nvUv = uv;\nvec4 lPosition = viewMatrix * vec4( uPointLightPos, 1.0 );\nvPointLightVector = normalize( lPosition.xyz - mvPosition.xyz );\n#ifdef VERTEX_TEXTURES\nvec3 dv = texture2D( tDisplacement, uv ).xyz;\nfloat df = uDisplacementScale * dv.x + uDisplacementBias;\nvec4 displacedPosition = vec4( vNormal.xyz * df, 0.0 ) + mvPosition;\ngl_Position = projectionMatrix * displacedPosition;\n#else\ngl_Position = projectionMatrix * mvPosition;\n#endif\n}"}, cube:{uniforms:{tCube:{type:"t",value:1,texture:null}},vertex_shader:"varying vec3 vViewPosition;\nvoid main() {\nvec4 mPosition = objectMatrix * vec4( position, 1.0 );\nvViewPosition = cameraPosition - mPosition.xyz;\ngl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragment_shader:"uniform samplerCube tCube;\nvarying vec3 vViewPosition;\nvoid main() {\nvec3 wPos = cameraPosition - vViewPosition;\ngl_FragColor = textureCube( tCube, vec3( - wPos.x, wPos.yz ) );\n}"},basic:{uniforms:{}, vertex_shader:"void main() {\ngl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragment_shader:"void main() {\ngl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);\n}"}}},Cube=function(a,b,d,e,g,h,j,c){function k(B,H,s,K,o,f,n,y){var r,x,L=e||1,u=g||1,C=L+1,E=u+1,D=o/2,w=f/2;o=o/L;var N=f/u,I=m.vertices.length;if(B=="x"&&H=="y"||B=="y"&&H=="x")r="z";else if(B=="x"&&H=="z"||B=="z"&&H=="x")r="y";else if(B=="z"&&H=="y"||B=="y"&&H=="z")r="x";for(x=0;x<E;x++)for(f=0;f<C;f++){var T=new THREE.Vector3; T[B]=(f*o-D)*s;T[H]=(x*N-w)*K;T[r]=n;m.vertices.push(new THREE.Vertex(T))}for(x=0;x<u;x++)for(f=0;f<L;f++){m.faces.push(new THREE.Face4(f+C*x+I,f+C*(x+1)+I,f+1+C*(x+1)+I,f+1+C*x+I,null,y));m.uvs.push([new THREE.UV(f/L,x/u),new THREE.UV(f/L,(x+1)/u),new THREE.UV((f+1)/L,(x+1)/u),new THREE.UV((f+1)/L,x/u)])}}THREE.Geometry.call(this);var m=this,p=a/2,z=b/2,q=d/2;j=j?-1:1;if(h!==undefined)if(h instanceof Array)this.materials=h;else{this.materials=[];for(var v=0;v<6;v++)this.materials.push([h])}else this.materials= [];this.sides={px:true,nx:true,py:true,ny:true,pz:true,nz:true};if(c!=undefined)for(var A in c)if(this.sides[A]!=undefined)this.sides[A]=c[A];this.sides.px&&k("z","y",1*j,-1,d,b,-p,this.materials[0]);this.sides.nx&&k("z","y",-1*j,-1,d,b,p,this.materials[1]);this.sides.py&&k("x","z",1*j,1,a,d,z,this.materials[2]);this.sides.ny&&k("x","z",1*j,-1,a,d,-z,this.materials[3]);this.sides.pz&&k("x","y",1*j,-1,a,b,q,this.materials[4]);this.sides.nz&&k("x","y",-1*j,-1,a,b,-q,this.materials[5]);(function(){for(var B= [],H=[],s=0,K=m.vertices.length;s<K;s++){for(var o=m.vertices[s],f=false,n=0,y=B.length;n<y;n++){var r=B[n];if(o.position.x==r.position.x&&o.position.y==r.position.y&&o.position.z==r.position.z){H[s]=n;f=true;break}}if(!f){H[s]=B.length;B.push(new THREE.Vertex(o.position.clone()))}}s=0;for(K=m.faces.length;s<K;s++){o=m.faces[s];o.a=H[o.a];o.b=H[o.b];o.c=H[o.c];o.d=H[o.d]}m.vertices=B})();this.computeCentroids();this.computeFaceNormals();this.sortFacesByMaterial()};Cube.prototype=new THREE.Geometry; Cube.prototype.constructor=Cube; var Cylinder=function(a,b,d,e,g){function h(m,p,z){j.vertices.push(new THREE.Vertex(new THREE.Vector3(m,p,z)))}THREE.Geometry.call(this);var j=this,c=Math.PI,k;for(k=0;k<a;k++)h(Math.sin(2*c*k/a)*b,Math.cos(2*c*k/a)*b,0);for(k=0;k<a;k++)h(Math.sin(2*c*k/a)*d,Math.cos(2*c*k/a)*d,e);for(k=0;k<a;k++)j.faces.push(new THREE.Face4(k,k+a,a+(k+1)%a,(k+1)%a));if(d!=0){h(0,0,-g);for(k=a;k<a+a/2;k++)j.faces.push(new THREE.Face4(2*a,(2*k-2*a)%a,(2*k-2*a+1)%a,(2*k-2*a+2)%a))}if(b!=0){h(0,0,e+g);for(k=a+a/2;k< 2*a;k++)j.faces.push(new THREE.Face4((2*k-2*a+2)%a+a,(2*k-2*a+1)%a+a,(2*k-2*a)%a+a,2*a+1))}this.computeCentroids();this.computeFaceNormals();this.sortFacesByMaterial()};Cylinder.prototype=new THREE.Geometry;Cylinder.prototype.constructor=Cylinder; var Plane=function(a,b,d,e){THREE.Geometry.call(this);var g,h=a/2,j=b/2;d=d||1;e=e||1;var c=d+1,k=e+1;a=a/d;var m=b/e;for(g=0;g<k;g++)for(b=0;b<c;b++)this.vertices.push(new THREE.Vertex(new THREE.Vector3(b*a-h,-(g*m-j),0)));for(g=0;g<e;g++)for(b=0;b<d;b++){this.faces.push(new THREE.Face4(b+c*g,b+c*(g+1),b+1+c*(g+1),b+1+c*g));this.uvs.push([new THREE.UV(b/d,g/e),new THREE.UV(b/d,(g+1)/e),new THREE.UV((b+1)/d,(g+1)/e),new THREE.UV((b+1)/d,g/e)])}this.computeCentroids();this.computeFaceNormals();this.sortFacesByMaterial()}; Plane.prototype=new THREE.Geometry;Plane.prototype.constructor=Plane; var Sphere=function(a,b,d){THREE.Geometry.call(this);var e,g=Math.PI,h=Math.max(3,b||8),j=Math.max(2,d||6);b=[];for(d=0;d<j+1;d++){e=d/j;var c=a*Math.cos(e*g),k=a*Math.sin(e*g),m=[],p=0;for(e=0;e<h;e++){var z=2*e/h,q=k*Math.sin(z*g);z=k*Math.cos(z*g);(d==0||d==j)&&e>0||(p=this.vertices.push(new THREE.Vertex(new THREE.Vector3(z,c,q)))-1);m.push(p)}b.push(m)}var v,A,B;g=b.length;for(d=0;d<g;d++){h=b[d].length;if(d>0)for(e=0;e<h;e++){m=e==h-1;j=b[d][m?0:e+1];c=b[d][m?h-1:e];k=b[d-1][m?h-1:e];m=b[d-1][m? 0:e+1];q=d/(g-1);v=(d-1)/(g-1);A=(e+1)/h;z=e/h;p=new THREE.UV(1-A,q);q=new THREE.UV(1-z,q);z=new THREE.UV(1-z,v);var H=new THREE.UV(1-A,v);if(d<b.length-1){v=this.vertices[j].position.clone();A=this.vertices[c].position.clone();B=this.vertices[k].position.clone();v.normalize();A.normalize();B.normalize();this.faces.push(new THREE.Face3(j,c,k,[new THREE.Vector3(v.x,v.y,v.z),new THREE.Vector3(A.x,A.y,A.z),new THREE.Vector3(B.x,B.y,B.z)]));this.uvs.push([p,q,z])}if(d>1){v=this.vertices[j].position.clone(); A=this.vertices[k].position.clone();B=this.vertices[m].position.clone();v.normalize();A.normalize();B.normalize();this.faces.push(new THREE.Face3(j,k,m,[new THREE.Vector3(v.x,v.y,v.z),new THREE.Vector3(A.x,A.y,A.z),new THREE.Vector3(B.x,B.y,B.z)]));this.uvs.push([p,z,H])}}}this.computeCentroids();this.computeFaceNormals();this.computeVertexNormals();this.sortFacesByMaterial();this.boundingSphere={radius:a}};Sphere.prototype=new THREE.Geometry;Sphere.prototype.constructor=Sphere; function LathedObject(a,b,d){THREE.Geometry.call(this);b=b||12;d=d||2*Math.PI;b=d/b;for(var e=[],g=[],h=[],j=[],c=0;c<a.length;c++){this.vertices.push(new THREE.Vertex(a[c]));g[c]=this.vertices.length-1;e[c]=new THREE.Vector3(a[c].x,a[c].y,a[c].z)}for(var k=THREE.Matrix4.rotationZMatrix(b),m=0;m<=d+0.0010;m+=b){for(c=0;c<e.length;c++)if(m<d){e[c]=k.multiplyVector3(e[c].clone());this.vertices.push(new THREE.Vertex(e[c]));h[c]=this.vertices.length-1}else h=j;if(m==0)j=g;for(c=0;c<g.length-1;c++){this.faces.push(new THREE.Face4(h[c], h[c+1],g[c+1],g[c]));this.uvs.push([new THREE.UV(m/d,c/a.length),new THREE.UV(m/d,(c+1)/a.length),new THREE.UV((m-b)/d,(c+1)/a.length),new THREE.UV((m-b)/d,c/a.length)])}g=h;h=[]}this.computeCentroids();this.computeFaceNormals();this.computeVertexNormals();this.sortFacesByMaterial()}LathedObject.prototype=new THREE.Geometry;LathedObject.prototype.constructor=LathedObject;THREE.Loader=function(a){this.statusDomElement=(this.showStatus=a)?this.addStatusElement():null}; THREE.Loader.prototype={addStatusElement:function(){var a=document.createElement("div");a.style.fontSize="0.8em";a.style.textAlign="left";a.style.background="#b00";a.style.color="#fff";a.style.width="140px";a.style.padding="0.25em 0.25em 0.25em 0.5em";a.style.position="absolute";a.style.right="0px";a.style.top="0px";a.style.zIndex=1E3;a.innerHTML="Loading ...";return a},updateProgress:function(a){var b="Loaded ";b+=a.total?(100*a.loaded/a.total).toFixed(0)+"%":(a.loaded/1E3).toFixed(2)+" KB";this.statusDomElement.innerHTML= b},loadAsciiOld:function(a,b){var d=document.createElement("script");d.type="text/javascript";d.onload=b;d.src=a;document.getElementsByTagName("head")[0].appendChild(d)},loadAscii:function(a){var b=a.model,d=a.callback,e=a.texture_path?a.texture_path:THREE.Loader.prototype.extractUrlbase(b);a=(new Date).getTime();b=new Worker(b);b.onmessage=function(g){THREE.Loader.prototype.createModel(g.data,d,e)};b.postMessage(a)},loadBinary:function(a){var b=a.model,d=a.callback,e=a.texture_path?a.texture_path: THREE.Loader.prototype.extractUrlbase(b),g=a.bin_path?a.bin_path:THREE.Loader.prototype.extractUrlbase(b);a=(new Date).getTime();b=new Worker(b);var h=this.showProgress?THREE.Loader.prototype.updateProgress:null;b.onmessage=function(j){THREE.Loader.prototype.loadAjaxBuffers(j.data.buffers,j.data.materials,d,g,e,h)};b.onerror=function(j){alert("worker.onerror: "+j.message+"\n"+j.data);j.preventDefault()};b.postMessage(a)},loadAjaxBuffers:function(a,b,d,e,g,h){var j=new XMLHttpRequest,c=e+"/"+a,k=0; j.onreadystatechange=function(){if(j.readyState==4)j.status==200||j.status==0?THREE.Loader.prototype.createBinModel(j.responseText,d,g,b):alert("Couldn't load ["+c+"] ["+j.status+"]");else if(j.readyState==3){if(h){if(k==0)k=j.getResponseHeader("Content-Length");h({total:k,loaded:j.responseText.length})}}else if(j.readyState==2)k=j.getResponseHeader("Content-Length")};j.open("GET",c,true);j.overrideMimeType("text/plain; charset=x-user-defined");j.setRequestHeader("Content-Type","text/plain");j.send(null)}, createBinModel:function(a,b,d,e){var g=function(h){function j(t,J){var G=p(t,J),Y=p(t,J+1),ba=p(t,J+2),fa=p(t,J+3),ia=(fa<<1&255|ba>>7)-127;G=(ba&127)<<16|Y<<8|G;if(G==0&&ia==-127)return 0;return(1-2*(fa>>7))*(1+G*Math.pow(2,-23))*Math.pow(2,ia)}function c(t,J){var G=p(t,J),Y=p(t,J+1),ba=p(t,J+2);return(p(t,J+3)<<24)+(ba<<16)+(Y<<8)+G}function k(t,J){var G=p(t,J);return(p(t,J+1)<<8)+G}function m(t,J){var G=p(t,J);return G>127?G-256:G}function p(t,J){return t.charCodeAt(J)&255}function z(t){var J, G,Y;J=c(a,t);G=c(a,t+y);Y=c(a,t+r);t=k(a,t+x);THREE.Loader.prototype.f3(s,J,G,Y,t)}function q(t){var J,G,Y,ba,fa,ia;J=c(a,t);G=c(a,t+y);Y=c(a,t+r);ba=k(a,t+x);fa=c(a,t+L);ia=c(a,t+u);t=c(a,t+C);THREE.Loader.prototype.f3n(s,f,J,G,Y,ba,fa,ia,t)}function v(t){var J,G,Y,ba;J=c(a,t);G=c(a,t+E);Y=c(a,t+D);ba=c(a,t+w);t=k(a,t+N);THREE.Loader.prototype.f4(s,J,G,Y,ba,t)}function A(t){var J,G,Y,ba,fa,ia,pa,ra;J=c(a,t);G=c(a,t+E);Y=c(a,t+D);ba=c(a,t+w);fa=k(a,t+N);ia=c(a,t+I);pa=c(a,t+T);ra=c(a,t+V);t=c(a,t+ O);THREE.Loader.prototype.f4n(s,f,J,G,Y,ba,fa,ia,pa,ra,t)}function B(t){var J,G;J=c(a,t);G=c(a,t+ca);t=c(a,t+W);THREE.Loader.prototype.uv3(s,n[J*2],n[J*2+1],n[G*2],n[G*2+1],n[t*2],n[t*2+1])}function H(t){var J,G,Y;J=c(a,t);G=c(a,t+Q);Y=c(a,t+S);t=c(a,t+aa);THREE.Loader.prototype.uv4(s,n[J*2],n[J*2+1],n[G*2],n[G*2+1],n[Y*2],n[Y*2+1],n[t*2],n[t*2+1])}var s=this,K=0,o,f=[],n=[],y,r,x,L,u,C,E,D,w,N,I,T,V,O,ca,W,Q,S,aa,X,F,R,U,ha,ga;THREE.Geometry.call(this);THREE.Loader.prototype.init_materials(s,e,h); o={signature:a.substr(K,8),header_bytes:p(a,K+8),vertex_coordinate_bytes:p(a,K+9),normal_coordinate_bytes:p(a,K+10),uv_coordinate_bytes:p(a,K+11),vertex_index_bytes:p(a,K+12),normal_index_bytes:p(a,K+13),uv_index_bytes:p(a,K+14),material_index_bytes:p(a,K+15),nvertices:c(a,K+16),nnormals:c(a,K+16+4),nuvs:c(a,K+16+8),ntri_flat:c(a,K+16+12),ntri_smooth:c(a,K+16+16),ntri_flat_uv:c(a,K+16+20),ntri_smooth_uv:c(a,K+16+24),nquad_flat:c(a,K+16+28),nquad_smooth:c(a,K+16+32),nquad_flat_uv:c(a,K+16+36),nquad_smooth_uv:c(a, K+16+40)};K+=o.header_bytes;y=o.vertex_index_bytes;r=o.vertex_index_bytes*2;x=o.vertex_index_bytes*3;L=o.vertex_index_bytes*3+o.material_index_bytes;u=o.vertex_index_bytes*3+o.material_index_bytes+o.normal_index_bytes;C=o.vertex_index_bytes*3+o.material_index_bytes+o.normal_index_bytes*2;E=o.vertex_index_bytes;D=o.vertex_index_bytes*2;w=o.vertex_index_bytes*3;N=o.vertex_index_bytes*4;I=o.vertex_index_bytes*4+o.material_index_bytes;T=o.vertex_index_bytes*4+o.material_index_bytes+o.normal_index_bytes; V=o.vertex_index_bytes*4+o.material_index_bytes+o.normal_index_bytes*2;O=o.vertex_index_bytes*4+o.material_index_bytes+o.normal_index_bytes*3;ca=o.uv_index_bytes;W=o.uv_index_bytes*2;Q=o.uv_index_bytes;S=o.uv_index_bytes*2;aa=o.uv_index_bytes*3;h=o.vertex_index_bytes*3+o.material_index_bytes;ga=o.vertex_index_bytes*4+o.material_index_bytes;X=o.ntri_flat*h;F=o.ntri_smooth*(h+o.normal_index_bytes*3);R=o.ntri_flat_uv*(h+o.uv_index_bytes*3);U=o.ntri_smooth_uv*(h+o.normal_index_bytes*3+o.uv_index_bytes* 3);ha=o.nquad_flat*ga;h=o.nquad_smooth*(ga+o.normal_index_bytes*4);ga=o.nquad_flat_uv*(ga+o.uv_index_bytes*4);K+=function(t){var J,G,Y,ba=o.vertex_coordinate_bytes*3,fa=t+o.nvertices*ba;for(t=t;t<fa;t+=ba){J=j(a,t);G=j(a,t+o.vertex_coordinate_bytes);Y=j(a,t+o.vertex_coordinate_bytes*2);THREE.Loader.prototype.v(s,J,G,Y)}return o.nvertices*ba}(K);K+=function(t){var J,G,Y,ba=o.normal_coordinate_bytes*3,fa=t+o.nnormals*ba;for(t=t;t<fa;t+=ba){J=m(a,t);G=m(a,t+o.normal_coordinate_bytes);Y=m(a,t+o.normal_coordinate_bytes* 2);f.push(J/127,G/127,Y/127)}return o.nnormals*ba}(K);K+=function(t){var J,G,Y=o.uv_coordinate_bytes*2,ba=t+o.nuvs*Y;for(t=t;t<ba;t+=Y){J=j(a,t);G=j(a,t+o.uv_coordinate_bytes);n.push(J,G)}return o.nuvs*Y}(K);K=K;X=K+X;F=X+F;R=F+R;U=R+U;ha=U+ha;h=ha+h;ga=h+ga;(function(t){var J,G=o.vertex_index_bytes*3+o.material_index_bytes,Y=G+o.uv_index_bytes*3,ba=t+o.ntri_flat_uv*Y;for(J=t;J<ba;J+=Y){z(J);B(J+G)}return ba-t})(F);(function(t){var J,G=o.vertex_index_bytes*3+o.material_index_bytes+o.normal_index_bytes* 3,Y=G+o.uv_index_bytes*3,ba=t+o.ntri_smooth_uv*Y;for(J=t;J<ba;J+=Y){q(J);B(J+G)}return ba-t})(R);(function(t){var J,G=o.vertex_index_bytes*4+o.material_index_bytes,Y=G+o.uv_index_bytes*4,ba=t+o.nquad_flat_uv*Y;for(J=t;J<ba;J+=Y){v(J);H(J+G)}return ba-t})(h);(function(t){var J,G=o.vertex_index_bytes*4+o.material_index_bytes+o.normal_index_bytes*4,Y=G+o.uv_index_bytes*4,ba=t+o.nquad_smooth_uv*Y;for(J=t;J<ba;J+=Y){A(J);H(J+G)}return ba-t})(ga);(function(t){var J,G=o.vertex_index_bytes*3+o.material_index_bytes, Y=t+o.ntri_flat*G;for(J=t;J<Y;J+=G)z(J);return Y-t})(K);(function(t){var J,G=o.vertex_index_bytes*3+o.material_index_bytes+o.normal_index_bytes*3,Y=t+o.ntri_smooth*G;for(J=t;J<Y;J+=G)q(J);return Y-t})(X);(function(t){var J,G=o.vertex_index_bytes*4+o.material_index_bytes,Y=t+o.nquad_flat*G;for(J=t;J<Y;J+=G)v(J);return Y-t})(U);(function(t){var J,G=o.vertex_index_bytes*4+o.material_index_bytes+o.normal_index_bytes*4,Y=t+o.nquad_smooth*G;for(J=t;J<Y;J+=G)A(J);return Y-t})(ha);this.computeCentroids(); this.computeFaceNormals();this.sortFacesByMaterial()};g.prototype=new THREE.Geometry;g.prototype.constructor=g;b(new g(d))},createModel:function(a,b,d){var e=function(g){var h=this;THREE.Geometry.call(this);THREE.Loader.prototype.init_materials(h,a.materials,g);(function(){var j,c,k,m,p;j=0;for(c=a.vertices.length;j<c;j+=3){k=a.vertices[j];m=a.vertices[j+1];p=a.vertices[j+2];THREE.Loader.prototype.v(h,k,m,p)}})();(function(){function j(A,B){THREE.Loader.prototype.f3(h,A[B],A[B+1],A[B+2],A[B+3])}function c(A, B){THREE.Loader.prototype.f3n(h,a.normals,A[B],A[B+1],A[B+2],A[B+3],A[B+4],A[B+5],A[B+6])}function k(A,B){THREE.Loader.prototype.f4(h,A[B],A[B+1],A[B+2],A[B+3],A[B+4])}function m(A,B){THREE.Loader.prototype.f4n(h,a.normals,A[B],A[B+1],A[B+2],A[B+3],A[B+4],A[B+5],A[B+6],A[B+7],A[B+8])}function p(A,B){var H,s,K;H=A[B];s=A[B+1];K=A[B+2];THREE.Loader.prototype.uv3(h,a.uvs[H*2],a.uvs[H*2+1],a.uvs[s*2],a.uvs[s*2+1],a.uvs[K*2],a.uvs[K*2+1])}function z(A,B){var H,s,K,o;H=A[B];s=A[B+1];K=A[B+2];o=A[B+3];THREE.Loader.prototype.uv4(h, a.uvs[H*2],a.uvs[H*2+1],a.uvs[s*2],a.uvs[s*2+1],a.uvs[K*2],a.uvs[K*2+1],a.uvs[o*2],a.uvs[o*2+1])}var q,v;q=0;for(v=a.triangles_uv.length;q<v;q+=7){j(a.triangles_uv,q);p(a.triangles_uv,q+4)}q=0;for(v=a.triangles_n_uv.length;q<v;q+=10){c(a.triangles_n_uv,q);p(a.triangles_n_uv,q+7)}q=0;for(v=a.quads_uv.length;q<v;q+=9){k(a.quads_uv,q);z(a.quads_uv,q+5)}q=0;for(v=a.quads_n_uv.length;q<v;q+=13){m(a.quads_n_uv,q);z(a.quads_n_uv,q+9)}q=0;for(v=a.triangles.length;q<v;q+=4)j(a.triangles,q);q=0;for(v=a.triangles_n.length;q< v;q+=7)c(a.triangles_n,q);q=0;for(v=a.quads.length;q<v;q+=5)k(a.quads,q);q=0;for(v=a.quads_n.length;q<v;q+=9)m(a.quads_n,q)})();this.computeCentroids();this.computeFaceNormals();this.sortFacesByMaterial()};e.prototype=new THREE.Geometry;e.prototype.constructor=e;b(new e(d))},v:function(a,b,d,e){a.vertices.push(new THREE.Vertex(new THREE.Vector3(b,d,e)))},f3:function(a,b,d,e,g){a.faces.push(new THREE.Face3(b,d,e,null,a.materials[g]))},f4:function(a,b,d,e,g,h){a.faces.push(new THREE.Face4(b,d,e,g,null, a.materials[h]))},f3n:function(a,b,d,e,g,h,j,c,k){h=a.materials[h];var m=b[c*3],p=b[c*3+1];c=b[c*3+2];var z=b[k*3],q=b[k*3+1];k=b[k*3+2];a.faces.push(new THREE.Face3(d,e,g,[new THREE.Vector3(b[j*3],b[j*3+1],b[j*3+2]),new THREE.Vector3(m,p,c),new THREE.Vector3(z,q,k)],h))},f4n:function(a,b,d,e,g,h,j,c,k,m,p){j=a.materials[j];var z=b[k*3],q=b[k*3+1];k=b[k*3+2];var v=b[m*3],A=b[m*3+1];m=b[m*3+2];var B=b[p*3],H=b[p*3+1];p=b[p*3+2];a.faces.push(new THREE.Face4(d,e,g,h,[new THREE.Vector3(b[c*3],b[c*3+1], b[c*3+2]),new THREE.Vector3(z,q,k),new THREE.Vector3(v,A,m),new THREE.Vector3(B,H,p)],j))},uv3:function(a,b,d,e,g,h,j){var c=[];c.push(new THREE.UV(b,d));c.push(new THREE.UV(e,g));c.push(new THREE.UV(h,j));a.uvs.push(c)},uv4:function(a,b,d,e,g,h,j,c,k){var m=[];m.push(new THREE.UV(b,d));m.push(new THREE.UV(e,g));m.push(new THREE.UV(h,j));m.push(new THREE.UV(c,k));a.uvs.push(m)},init_materials:function(a,b,d){a.materials=[];for(var e=0;e<b.length;++e)a.materials[e]=[THREE.Loader.prototype.createMaterial(b[e], d)]},createMaterial:function(a,b){function d(h){h=Math.log(h)/Math.LN2;return Math.floor(h)==h}var e,g;if(a.map_diffuse&&b){g=document.createElement("canvas");e=new THREE.MeshLambertMaterial({map:new THREE.Texture(g)});g=new Image;g.onload=function(){if(!d(this.width)||!d(this.height)){var h=Math.pow(2,Math.round(Math.log(this.width)/Math.LN2)),j=Math.pow(2,Math.round(Math.log(this.height)/Math.LN2));e.map.image.width=h;e.map.image.height=j;e.map.image.getContext("2d").drawImage(this,0,0,h,j)}else e.map.image= this;e.map.image.loaded=1};g.src=b+"/"+a.map_diffuse}else if(a.col_diffuse){g=(a.col_diffuse[0]*255<<16)+(a.col_diffuse[1]*255<<8)+a.col_diffuse[2]*255;e=new THREE.MeshLambertMaterial({color:g,opacity:a.transparency})}else e=a.a_dbg_color?new THREE.MeshLambertMaterial({color:a.a_dbg_color}):new THREE.MeshLambertMaterial({color:15658734});return e},extractUrlbase:function(a){a=a.split("/");a.pop();return a.join("/")}};
489.350394
2,961
0.73019
3e305e18caecf6a7d77748a6d0b65a68d42fa369
121
h
C
src/Menu/ToggleOption.h
nightmareci/shiromino
ddcf6cc8659a3006b8960fa677d0392813d3e698
[ "CC-BY-4.0", "MIT" ]
6
2020-02-10T12:42:59.000Z
2020-08-17T21:04:25.000Z
src/Menu/ToggleOption.h
nightmareci/shiromino
ddcf6cc8659a3006b8960fa677d0392813d3e698
[ "CC-BY-4.0", "MIT" ]
null
null
null
src/Menu/ToggleOption.h
nightmareci/shiromino
ddcf6cc8659a3006b8960fa677d0392813d3e698
[ "CC-BY-4.0", "MIT" ]
7
2020-05-08T09:47:44.000Z
2020-10-26T21:30:51.000Z
#pragma once namespace Shiro { struct ToggleOptionData { bool *param; std::string labels[2]; }; }
17.285714
30
0.586777
867012d916288cd4069bdd77e804bf029e186e52
5,878
rs
Rust
src/image.rs
daj-code/floki
aad9593e109dd837809cb3fd2178ce4729f2a61f
[ "MIT" ]
null
null
null
src/image.rs
daj-code/floki
aad9593e109dd837809cb3fd2178ce4729f2a61f
[ "MIT" ]
5
2021-09-27T18:17:49.000Z
2022-01-18T18:21:58.000Z
src/image.rs
daj-code/floki
aad9593e109dd837809cb3fd2178ce4729f2a61f
[ "MIT" ]
null
null
null
use failure::Error; use quicli::prelude::*; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use yaml_rust::YamlLoader; use crate::errors::{FlokiError, FlokiSubprocessExitStatus}; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct BuildSpec { name: String, #[serde(default = "default_dockerfile")] dockerfile: PathBuf, #[serde(default = "default_context")] context: PathBuf, target: Option<String>, } #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct YamlSpec { pub file: PathBuf, key: String, } fn default_dockerfile() -> PathBuf { "Dockerfile".into() } fn default_context() -> PathBuf { ".".into() } #[derive(Debug, PartialEq, Serialize, Deserialize)] #[serde(untagged)] pub enum Image { Name(String), Build { build: BuildSpec }, Yaml { yaml: YamlSpec }, } impl Image { /// Name of the image pub fn name(&self) -> Result<String, Error> { match *self { Image::Name(ref s) => Ok(s.clone()), Image::Build { ref build } => Ok(build.name.clone() + ":floki"), Image::Yaml { ref yaml } => { let contents = fs::read_to_string(&yaml.file)?; let raw = YamlLoader::load_from_str(&contents)?; let path = yaml.key.split('.').collect::<Vec<_>>(); let mut val = &raw[0]; for key in &path { // Yaml arrays and maps with scalar keys can both be indexed by // usize, so heuristically prefer a usize index to a &str index. val = match key.parse::<usize>() { Ok(x) => &val[x], Err(_) => &val[*key], }; } val.as_str() .map(std::string::ToString::to_string) .ok_or_else(|| { FlokiError::FailedToFindYamlKey { key: yaml.key.to_string(), file: yaml.file.display().to_string(), } .into() }) } } } /// Do the required work to get the image, and then return /// it's name pub fn obtain_image(&self, floki_root: &Path) -> Result<String, Error> { match *self { // Deal with the case where want to build an image Image::Build { ref build } => { let mut command = Command::new("docker"); command .arg("build") .arg("-t") .arg(self.name()?) .arg("-f") .arg(&floki_root.join(&build.dockerfile)); if let Some(target) = &build.target { command.arg("--target").arg(target); } let exit_status = command .arg(&floki_root.join(&build.context)) .spawn()? .wait()?; if exit_status.success() { Ok(self.name()?) } else { Err(FlokiError::FailedToBuildImage { image: self.name()?, exit_status: FlokiSubprocessExitStatus { process_description: "docker build".into(), exit_status, }, } .into()) } } // All other cases we just return the name _ => Ok(self.name()?), } } } // Now we have some functions which are useful in general /// Wrapper to pull an image by it's name pub fn pull_image(name: &str) -> Result<(), Error> { debug!("Pulling image: {}", name); let exit_status = Command::new("docker") .arg("pull") .arg(name) .spawn()? .wait()?; if exit_status.success() { Ok(()) } else { Err(FlokiError::FailedToPullImage { image: name.into(), exit_status: FlokiSubprocessExitStatus { process_description: "docker pull".into(), exit_status, }, } .into()) } } /// Determine whether an image exists locally pub fn image_exists_locally(name: &str) -> Result<bool, Error> { let ret = Command::new("docker") .args(&["history", "docker:stable-dind"]) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .map_err(|e| FlokiError::FailedToCheckForImage { image: name.to_string(), error: e, })?; Ok(ret.code() == Some(0)) } #[cfg(test)] mod test { use super::*; use serde_yaml; #[derive(Debug, PartialEq, Serialize, Deserialize)] struct TestImage { image: Image, } #[test] fn test_image_spec_by_string() { let yaml = "image: foo"; let expected = TestImage { image: Image::Name("foo".into()), }; let actual: TestImage = serde_yaml::from_str(yaml).unwrap(); assert!(actual == expected); } #[test] fn test_image_spec_by_build_spec() { let yaml = "image:\n build:\n name: foo\n dockerfile: Dockerfile.test \n context: ./context\n target: builder"; let expected = TestImage { image: Image::Build { build: BuildSpec { name: "foo".into(), dockerfile: "Dockerfile.test".into(), context: "./context".into(), target: Some("builder".into()), }, }, }; let actual: TestImage = serde_yaml::from_str(yaml).unwrap(); assert!(actual == expected); } }
30.298969
132
0.484689
5f0e0b705c650888e6a1c7bb92439febdc1a9e91
192
ts
TypeScript
implementations/typescript/tests/operator/less_than_or_equal_to_when_equal.spec.ts
JosephNaberhaus/agnostic
241d33f7dea12a29e3c45d22b5c8570edc2b0412
[ "MIT" ]
null
null
null
implementations/typescript/tests/operator/less_than_or_equal_to_when_equal.spec.ts
JosephNaberhaus/agnostic
241d33f7dea12a29e3c45d22b5c8570edc2b0412
[ "MIT" ]
null
null
null
implementations/typescript/tests/operator/less_than_or_equal_to_when_equal.spec.ts
JosephNaberhaus/agnostic
241d33f7dea12a29e3c45d22b5c8570edc2b0412
[ "MIT" ]
null
null
null
import { expect } from 'chai'; describe('TypeScript', () => { describe('Operator', () => { it('LessThanOrEqualToWhenEqual', () => { expect(10 <= 10).to.be.true; }); }); });
19.2
44
0.520833
d84ab6a9cad84a34ade5ed2caf191f382d7975f2
145
sql
SQL
sql_and_node/movies-App/db/migrations/migration-07242017.sql
myfriendtania/PostgreSQL
65e4f15b9c9f5a8a129ffa2a9190aa7b8324f488
[ "PostgreSQL" ]
1
2021-05-18T20:53:35.000Z
2021-05-18T20:53:35.000Z
sql_and_node/movies-App/db/migrations/migration-07242017.sql
myfriendtania/PostgreSQL
65e4f15b9c9f5a8a129ffa2a9190aa7b8324f488
[ "PostgreSQL" ]
null
null
null
sql_and_node/movies-App/db/migrations/migration-07242017.sql
myfriendtania/PostgreSQL
65e4f15b9c9f5a8a129ffa2a9190aa7b8324f488
[ "PostgreSQL" ]
1
2022-02-23T09:50:20.000Z
2022-02-23T09:50:20.000Z
\c delorean_movies_dev CREATE TABLE IF NOT EXISTS movies ( id SERIAL PRIMARY KEY, title VARCHAR(255), year BIGINT, genre VARCHAR(255) );
18.125
35
0.731034
86ba5194b078a22319981b37fe1902b2584fae13
49
rs
Rust
build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/compilers/GroovyClassFilter.rs
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/compilers/GroovyClassFilter.rs
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
build/classes/visao/jasperreports-6.15.0/src/net/sf/jasperreports/compilers/GroovyClassFilter.rs
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
net.sf.jasperreports.compilers.GroovyClassFilter
24.5
48
0.897959
56a84be513e5c743897966d8cb399ad03926eab7
205
ts
TypeScript
lib/fetcher/profiles/IProfileFetcher.d.ts
gatesolve/planner.js
7e0179e0c82214c552fa55ab0faed9e142427d64
[ "MIT" ]
null
null
null
lib/fetcher/profiles/IProfileFetcher.d.ts
gatesolve/planner.js
7e0179e0c82214c552fa55ab0faed9e142427d64
[ "MIT" ]
null
null
null
lib/fetcher/profiles/IProfileFetcher.d.ts
gatesolve/planner.js
7e0179e0c82214c552fa55ab0faed9e142427d64
[ "MIT" ]
null
null
null
import Profile from "../../entities/profile/Profile"; export default interface IProfileFetcher { parseProfileBlob(blob: object, id: string): Promise<Profile>; get(url: string): Promise<Profile>; }
34.166667
65
0.731707
77e57aae25476783412603e36caaa852e987551e
1,174
rs
Rust
contract/src/geohash.rs
enigmampc/safetraceV2
6d0598e75c109cab0300e67366074656b9d9b64a
[ "MIT" ]
4
2020-11-22T08:37:05.000Z
2021-01-21T09:20:04.000Z
contract/src/geohash.rs
enigmampc/safetraceV2
6d0598e75c109cab0300e67366074656b9d9b64a
[ "MIT" ]
null
null
null
contract/src/geohash.rs
enigmampc/safetraceV2
6d0598e75c109cab0300e67366074656b9d9b64a
[ "MIT" ]
null
null
null
use cosmwasm_std::{StdError, StdResult}; use geohash::{encode, Coordinate}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; const PRECISION: usize = 9usize; /// return the geohash to a precision degree specified by `PRECISION`. /// 7 ~ 76m /// 8 ~ 20m /// 9 ~ 7m /// 10 ~ 1m pub fn ghash(x: f64, y: f64) -> StdResult<String> { encode( Coordinate { x, // lng y, // lat }, PRECISION, ) .map_err(|_| StdError::generic_err(format!("Cannot encode data to geohash ({}, {})", x, y))) } pub fn neighbors(geohash: &String) -> StdResult<Vec<String>> { let mut all: Vec<String> = vec![]; let positions = geohash::neighbors(geohash) .map_err(|_| StdError::generic_err("Failed to decode geohash"))?; all.push(positions.n); all.push(positions.ne); all.push(positions.e); all.push(positions.se); all.push(positions.s); all.push(positions.sw); all.push(positions.w); all.push(positions.nw); Ok(all) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct GeoLocationTime { pub geohash: String, pub timestamp_ms: u64, }
24.458333
96
0.625213
46ad28146bd64adb699e33270b59873618d8d999
145
css
CSS
docs/stylesheets/extra.css
adverley/folding-demonstrations
cdb769d69b6fa504a5da02d86bb131d7b9bdc6ff
[ "CC-BY-4.0" ]
1
2021-07-21T04:36:45.000Z
2021-07-21T04:36:45.000Z
docs/stylesheets/extra.css
adverley/folding-demonstrations
cdb769d69b6fa504a5da02d86bb131d7b9bdc6ff
[ "CC-BY-4.0" ]
null
null
null
docs/stylesheets/extra.css
adverley/folding-demonstrations
cdb769d69b6fa504a5da02d86bb131d7b9bdc6ff
[ "CC-BY-4.0" ]
null
null
null
.md-typeset { font-size: 15px; } .md-footer { font-size: 15px; } .md-footer-nav__link, .md-footer-nav__title { font-size: initial; }
14.5
45
0.627586
261a0d698dc68097efa663be00acba5d065c6ec4
1,973
java
Java
matos-android/src/main/java/android/os/Power.java
Orange-OpenSource/matos-profiles
fb27c246911437070052197aa3ef91f9aaac6fc3
[ "Apache-2.0" ]
4
2015-05-31T02:12:56.000Z
2016-01-27T11:53:06.000Z
matos-android/src/main/java/android/os/Power.java
Orange-OpenSource/matos-profiles
fb27c246911437070052197aa3ef91f9aaac6fc3
[ "Apache-2.0" ]
null
null
null
matos-android/src/main/java/android/os/Power.java
Orange-OpenSource/matos-profiles
fb27c246911437070052197aa3ef91f9aaac6fc3
[ "Apache-2.0" ]
5
2015-05-31T00:15:20.000Z
2021-06-22T10:21:38.000Z
package android.os; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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. * #L% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public class Power { // Fields public static final int PARTIAL_WAKE_LOCK = 1; public static final int FULL_WAKE_LOCK = 2; public static final int BRIGHTNESS_OFF = 0; public static final int BRIGHTNESS_DIM = 20; public static final int BRIGHTNESS_ON = 255; public static final int BRIGHTNESS_LOW_BATTERY = 10; public static final int LOW_BATTERY_THRESHOLD = 10; // Constructors private Power(){ } // Methods @com.francetelecom.rd.stubs.annotation.UseRule(value = "Power.shutdown", report = "-") public static void shutdown(){ } @com.francetelecom.rd.stubs.annotation.UseRule(value = "Power.reboot", report = "-") public static void reboot(java.lang.String arg1) throws java.io.IOException{ } @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "Power.releaseWakeLock", pos = 1, report = "-") public static void releaseWakeLock(java.lang.String arg1){ } @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "Power.acquireWakeLock", pos = 2, report = "-") public static void acquireWakeLock(int arg1, java.lang.String arg2){ } public static int setLastUserActivityTimeout(long arg1){ return 0; } public static int setScreenState(boolean arg1){ return 0; } }
28.185714
105
0.714648
58168f9e003194ccb85c421d9d31e2980c89e3c2
208
h
C
linux_Latexey/include/main.h
ray-pH/Latexey
beae653e3af91b1c449b19f261ae2386d4f11a45
[ "MIT" ]
null
null
null
linux_Latexey/include/main.h
ray-pH/Latexey
beae653e3af91b1c449b19f261ae2386d4f11a45
[ "MIT" ]
null
null
null
linux_Latexey/include/main.h
ray-pH/Latexey
beae653e3af91b1c449b19f261ae2386d4f11a45
[ "MIT" ]
null
null
null
#include <wx/wx.h> #include <string.h> #include "latexey.h" // class TaskBarIcon; class MyApp : public wxApp{ public: virtual bool OnInit(); std::string getDirPath(); private: std::string execDir; };
17.333333
27
0.6875
169d7024ac9d62a771d402f59303d70fb44b125e
7,282
c
C
bsp/apm32/libraries/APM32F10x_Library/USB_Device_Lib/Driver/src/drv_usb_device.c
cazure/rt-thread
1bdde743433d331740766c895ff867df6268df20
[ "Apache-2.0" ]
1
2022-03-02T12:48:01.000Z
2022-03-02T12:48:01.000Z
bsp/apm32/libraries/APM32F10x_Library/USB_Device_Lib/Driver/src/drv_usb_device.c
cazure/rt-thread
1bdde743433d331740766c895ff867df6268df20
[ "Apache-2.0" ]
1
2018-12-20T00:02:50.000Z
2018-12-20T00:02:50.000Z
bsp/apm32/libraries/APM32F10x_Library/USB_Device_Lib/Driver/src/drv_usb_device.c
cazure/rt-thread
1bdde743433d331740766c895ff867df6268df20
[ "Apache-2.0" ]
1
2022-01-25T02:14:32.000Z
2022-01-25T02:14:32.000Z
/*! * @file drv_usb_device.c * * @brief This file contains all the functions for the USBD peripheral * * @version V1.0.0 * * @date 2021-12-06 * * @attention * * Copyright (C) 2020-2022 Geehy Semiconductor * * You may not use this file except in compliance with the * GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE). * * The program is only for reference, which is distributed in the hope * that it will be usefull and instructional for customers to develop * their software. Unless required by applicable law or agreed to in * writing, the program is distributed on an "AS IS" BASIS, WITHOUT * ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied. * See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions * and limitations under the License. */ #include "drv_usb_device.h" /*! * @brief Set Endpoint type * * @param ep: Endpoint number * * @param type: Endpoint type * * @retval None */ void USBD_SetEPType(uint8_t ep, USBD_REG_EP_TYPE_T type) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg &= ~USBD_EP_BIT_TYPE; reg |= type << 9; USBD->EP[ep].EP = reg; } /*! * @brief Set EP kind * * @param ep: Endpoint number * * @retval None */ void USBD_SetEPKind(uint8_t ep) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg |= USBD_EP_BIT_KIND; USBD->EP[ep].EP = reg; } /*! * @brief Reset EP kind * * @param ep: Endpoint number * * @retval None */ void USBD_ResetEPKind(uint8_t ep) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg &= ~USBD_EP_BIT_KIND; USBD->EP[ep].EP = reg; } /*! * @brief Reset EP CTFR bit * * @param ep: Endpoint number * * @retval None */ void USBD_ResetEPRxFlag(uint8_t ep) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg &= ~USBD_EP_BIT_CTFR; USBD->EP[ep].EP = reg; } /*! * @brief Reset EP CTFT bit * * @param ep: Endpoint number * * @retval None */ void USBD_ResetEPTxFlag(uint8_t ep) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg &= ~USBD_EP_BIT_CTFT; USBD->EP[ep].EP = reg; } /*! * @brief Toggle Tx DTOG * * @param ep: Endpoint number * * @retval None */ void USBD_ToggleTx(uint8_t ep) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg |= USBD_EP_BIT_TXDTOG; USBD->EP[ep].EP = reg; } /*! * @brief Toggle Rx DTOG * * @param ep: Endpoint number * * @retval None */ void USBD_ToggleRx(uint8_t ep) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg |= USBD_EP_BIT_RXDTOG; USBD->EP[ep].EP = reg; } /*! * @brief Reset Toggle Tx DTOG * * @param ep: Endpoint number * * @retval None */ void USBD_ResetTxToggle(uint8_t ep) { if (USBD->EP[ep].EP_B.TXDTOG) { USBD_ToggleTx(ep); } } /*! * @brief Reset Toggle Rx DTOG * * @param ep: Endpoint number * * @retval None */ void USBD_ResetRxToggle(uint8_t ep) { if (USBD->EP[ep].EP_B.RXDTOG) { USBD_ToggleRx(ep); } } /*! * @brief Set EP address * * @param ep: Endpoint number * * @param addr: Address * * @retval None */ void USBD_SetEpAddr(uint8_t ep, uint8_t addr) { __IOM uint32_t reg; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT); reg &= ~USBD_EP_BIT_ADDR; reg |= addr; USBD->EP[ep].EP = reg; } /*! * @brief Set EP Tx status * * @param ep: Endpoint number * * @param status: status * * @retval None */ void USBD_SetEPTxStatus(uint8_t ep, USBD_EP_STATUS_T status) { __IOM uint32_t reg; status <<= 4; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT | USBD_EP_BIT_TXSTS); reg ^= ((uint32_t)status & (uint32_t)USBD_EP_BIT_TXSTS); USBD->EP[ep].EP = reg; } /*! * @brief Set EP Rx status * * @param ep: Endpoint number * * @param status: status * * @retval None */ void USBD_SetEPRxStatus(uint8_t ep, USBD_EP_STATUS_T status) { __IOM uint32_t reg; uint32_t tmp; tmp = status << 12; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT | USBD_EP_BIT_RXSTS); reg ^= (tmp & USBD_EP_BIT_RXSTS); USBD->EP[ep].EP = reg; } /*! * @brief Set EP Tx and Rx status * * @param ep: Endpoint number * * @param status: status * * @retval None */ void USBD_SetEPTxRxStatus(uint8_t ep, USBD_EP_STATUS_T txStatus, USBD_EP_STATUS_T rxStatus) { __IOM uint32_t reg; uint32_t tmp; reg = USBD->EP[ep].EP; reg &= (uint32_t)(USBD_EP_MASK_DEFAULT | USBD_EP_BIT_RXSTS | USBD_EP_BIT_TXSTS); tmp = rxStatus << 12; reg ^= (tmp & USBD_EP_BIT_RXSTS); tmp = txStatus << 4; reg ^= (tmp & USBD_EP_BIT_TXSTS); USBD->EP[ep].EP = reg; } /*! * @brief Set EP Rx Count * * @param ep: Endpoint number * * @param cnt: Rx count * * @retval None */ void USBD_SetEPRxCnt(uint8_t ep, uint32_t cnt) { __IOM uint16_t *p; __IOM uint16_t block = 0; p = USBD_ReadEPRxCntPointer(ep); if (cnt > 62) { block = cnt >> 5; if (!(cnt & 0x1f)) { block -= 1; } *p = (block << 10) | 0x8000; } else { block = cnt >> 1; if (cnt & 0x01) { block += 1; } *p = (block << 10); } } /*! * @brief Write a buffer of data to a selected endpoint * * @param ep: Endpoint number * * @retval wBuf: The pointer to the buffer of data to be written to the endpoint * * @param wLen: Number of data to be written (in bytes) * * @retval None */ void USBD_WriteDataToEP(uint8_t ep, uint8_t *wBuf, uint32_t wLen) { uint32_t i; #ifdef APM32F0xx_USB uint16_t *epAddr; uint16_t tmp; #else uint32_t *epAddr; uint32_t tmp; #endif wLen = (wLen + 1) >> 1; epAddr = USBD_ReadEPTxBufferPointer(ep); for (i = 0; i < wLen; i++) { tmp = *wBuf++; tmp = ((*wBuf++) << 8) | tmp; *epAddr++ = tmp; } } /*! * @brief Read a buffer of data to a selected endpoint * * @param ep: Endpoint number * * @retval wBuf: The pointer to the buffer of data to be read to the endpoint * * @param wLen: Number of data to be read (in bytes) * * @retval None */ void USBD_ReadDataFromEP(uint8_t ep, uint8_t *rBuf, uint32_t rLen) { #ifdef APM32F0xx_USB uint16_t *epAddr; #else uint32_t *epAddr; #endif uint32_t i, tmp, cnt; cnt = rLen >> 1; epAddr = USBD_ReadEPRxBufferPointer(ep); for (i = 0; i < cnt; i++) { tmp = *epAddr++; *rBuf++ = tmp & 0xFF; *rBuf++ = (tmp >> 8) & 0xFF; } if (rLen & 1) { tmp = *epAddr; *rBuf = tmp & 0xFF; } }
18.024752
91
0.574018
e758d99e0889dedb0fe8d2a65ca2c9210e1dd1cc
179
js
JavaScript
events/messageDelete.js
mirko93s/Chill-Bot
37af48561d101c8c5c2608d4034cd4d38e63ab5f
[ "Apache-2.0" ]
null
null
null
events/messageDelete.js
mirko93s/Chill-Bot
37af48561d101c8c5c2608d4034cd4d38e63ab5f
[ "Apache-2.0" ]
null
null
null
events/messageDelete.js
mirko93s/Chill-Bot
37af48561d101c8c5c2608d4034cd4d38e63ab5f
[ "Apache-2.0" ]
null
null
null
module.exports = (client, msg) => { if (client.settings.has(msg.guild.id, `reactionroles.${msg.id}`)) return client.settings.delete(msg.guild.id, `reactionroles.${msg.id}`); };
59.666667
139
0.687151
5ec7926ca5e76118ce7f5d26b5b32467b7f5e2f7
485
lua
Lua
Spellshock2/Data/Scripts/ChargeUpBarVisibility.lua
Core-Team-META/Game-Spellshock-2
6e51dd778c5ea078b8efe4a4aa543115dc0f2ddb
[ "Apache-2.0" ]
1
2021-11-02T16:01:38.000Z
2021-11-02T16:01:38.000Z
Spellshock2/Data/Scripts/ChargeUpBarVisibility.lua
Core-Team-META/Game-Spellshock-2
6e51dd778c5ea078b8efe4a4aa543115dc0f2ddb
[ "Apache-2.0" ]
null
null
null
Spellshock2/Data/Scripts/ChargeUpBarVisibility.lua
Core-Team-META/Game-Spellshock-2
6e51dd778c5ea078b8efe4a4aa543115dc0f2ddb
[ "Apache-2.0" ]
1
2021-11-02T17:17:10.000Z
2021-11-02T17:17:10.000Z
-- Simple script that makes the root visible or invisible when the global menu changes, only used on ChargeUpBar local ROOT = script:GetCustomProperty("Root"):WaitForObject() local wasVisible = true function Tick() if not _G.MENU_TABLE then return end local isVisible = (_G.CurrentMenu == _G.MENU_TABLE["NONE"]) if isVisible ~= wasVisible then wasVisible = isVisible ROOT.visibility = isVisible and Visibility.INHERIT or Visibility.FORCE_OFF end end
32.333333
112
0.738144
3102946f5649bcd769be437ef734662b36f934ce
849
swift
Swift
Sources/PropertyWrappers/ExpirableValue.swift
kojirou1994/Kwift
9a60adf4e4767014cc9850f80c2d71afe708dd41
[ "MIT" ]
null
null
null
Sources/PropertyWrappers/ExpirableValue.swift
kojirou1994/Kwift
9a60adf4e4767014cc9850f80c2d71afe708dd41
[ "MIT" ]
null
null
null
Sources/PropertyWrappers/ExpirableValue.swift
kojirou1994/Kwift
9a60adf4e4767014cc9850f80c2d71afe708dd41
[ "MIT" ]
null
null
null
import Foundation @propertyWrapper public struct Expirable<Value> { internal let duration: TimeInterval internal var storage: (value: Value, expirationDate: Date)? public init(duration: TimeInterval) { self.duration = duration storage = nil } // public init(wrappedValue: Value, expirationDate: Date, duration: TimeInterval) { // self.duration = duration // storage = (wrappedValue, expirationDate) // } public var wrappedValue: Value? { get { isValid ? storage?.value : nil } set { storage = newValue.map { ($0, Date().addingTimeInterval(duration)) } } } public var isValid: Bool { storage.map { $0.expirationDate >= Date() } ?? false } public mutating func set(_ newValue: Value, expirationDate: Date) { storage = (newValue, expirationDate) } }
22.945946
88
0.648999
dfdf0a0793736d8413235dfb32e0be3aa6c6d834
2,778
ts
TypeScript
projects/ng-translation/src/lib/components/ng-trans-subcontent/ng-trans-subcontent.component.spec.ts
wjx774326739/ng-translation
adc0c53a14bb40cf256f75b082a0a3eb69cea37b
[ "MIT" ]
3
2022-02-28T14:30:53.000Z
2022-02-28T14:53:39.000Z
projects/ng-translation/src/lib/components/ng-trans-subcontent/ng-trans-subcontent.component.spec.ts
wjx774326739/ng-translation
adc0c53a14bb40cf256f75b082a0a3eb69cea37b
[ "MIT" ]
3
2022-03-02T13:04:02.000Z
2022-03-11T14:45:22.000Z
projects/ng-translation/src/lib/components/ng-trans-subcontent/ng-trans-subcontent.component.spec.ts
bigBear713/ng-translation
adc0c53a14bb40cf256f75b082a0a3eb69cea37b
[ "MIT" ]
null
null
null
import { ChangeDetectorRef, Component, TemplateRef, ViewChild } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NgTransTestingModule } from '../../testing'; import { NgTransSubcontentComponent } from './ng-trans-subcontent.component'; @Component({ selector: 'mock-tpl-ref', template: ` <ng-template #tplRef>{{content}}</ng-template> <ng-template #tplRefWithList let-list="list"> <p *ngFor="let item of list">{{item}}</p> </ng-template> `, }) export class MockTplRefComponent { @ViewChild('tplRef') tplRef!: TemplateRef<any>; @ViewChild('tplRefWithList') tplRefWithList!: TemplateRef<any>; content = 'mock templateRef content'; } describe('Component: NgTransSubcontent', () => { let component: NgTransSubcontentComponent; let fixture: ComponentFixture<NgTransSubcontentComponent>; let hostEle: HTMLElement; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [NgTransTestingModule], declarations: [MockTplRefComponent] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(NgTransSubcontentComponent); component = fixture.componentInstance; fixture.detectChanges(); hostEle = fixture.debugElement.nativeElement; }); it('should be created', () => { expect(component).toBeTruthy(); }); it('the content is a string value', () => { const content = 'test content'; component.content = content; detectChanges(); expect(hostEle.textContent?.trim()).toEqual(content); }); it('the content is a templateRef type value', () => { const mockTplRefFixture = TestBed.createComponent(MockTplRefComponent); const mockTplRefComp = mockTplRefFixture.componentInstance; mockTplRefFixture.detectChanges(); const content = mockTplRefComp.tplRef; component.content = content; detectChanges(); expect(hostEle.textContent?.trim()).toEqual(mockTplRefComp.content); }); it('the content is a templateRef type value with string list param', () => { const mockList = ['mock list 1', 'mock list 2']; const mockTplRefFixture = TestBed.createComponent(MockTplRefComponent); const mockTplRefComp = mockTplRefFixture.componentInstance; mockTplRefFixture.detectChanges(); const content = mockTplRefComp.tplRefWithList; component.content = content; component.list = mockList; detectChanges(); const listFromDom = Array.from(hostEle.querySelectorAll('p')).map(item => item.textContent?.trim()); expect(listFromDom).toEqual(mockList); }); function detectChanges() { const changeDR = fixture.componentRef.injector.get(ChangeDetectorRef); changeDR.markForCheck(); fixture.detectChanges(); } });
30.195652
104
0.703744
fe0eb07061b39334d48339b985fe3b2b23be1f6e
486
h
C
src/r2048u64t.h
cipherboy/ppc64le-2048-widemul
65050476b2da7b028e4fc91dacc002868eea46d1
[ "BSD-3-Clause" ]
null
null
null
src/r2048u64t.h
cipherboy/ppc64le-2048-widemul
65050476b2da7b028e4fc91dacc002868eea46d1
[ "BSD-3-Clause" ]
null
null
null
src/r2048u64t.h
cipherboy/ppc64le-2048-widemul
65050476b2da7b028e4fc91dacc002868eea46d1
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <stdint.h> typedef struct { uint64_t data[64]; // Length in bits uint16_t length; } _u64t; extern void u64t_translate(_u64t *ret, r2048bn *parameter); extern void r2048bn_translate(r2048bn *ret, _u64t *parameter); extern void u64t_modulus(_u64t *ret_n, _u64t *prime_p, _u64t *prime_q); extern void u64t_exponent(_u64t *ret_decryption, _u64t *mod_n, _u64t *exp_e); extern void u64t_crypt(_u64t *ret, _u64t *message, _u64t *mod_n, _u64t *exponent);
27
82
0.744856
e52b5bf96b39ec51d6656bd3a65b5d5c1e225174
1,066
ts
TypeScript
test.ts
kitsonk/resvg-wasm
9fb916e037f0d3a92b4481c0b0cc5a92703c13b7
[ "MIT" ]
1
2021-11-30T02:51:04.000Z
2021-11-30T02:51:04.000Z
test.ts
kitsonk/resvg-wasm
9fb916e037f0d3a92b4481c0b0cc5a92703c13b7
[ "MIT" ]
null
null
null
test.ts
kitsonk/resvg-wasm
9fb916e037f0d3a92b4481c0b0cc5a92703c13b7
[ "MIT" ]
null
null
null
import { assertEquals } from "https://deno.land/std@0.116.0/testing/asserts.ts"; import { render } from "./mod.ts"; Deno.test({ name: "basic", fn() { const data = render( `<?xml version="1.0" encoding="UTF-8"?> <svg width="820px" height="312px" viewBox="0 0 820 312" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>Testing</title> <g id="testing" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <rect fill="#FFFFFF" x="0" y="0" width="820" height="312"></rect> <text id="test-text" font-family="sans-serif" font-size="32" font-weight="bold" fill="#111827"> <tspan x="51" y="90">Testing Testing Testing</tspan> </text> <text id="monospace" font-family="monospace" font-size="32" font-weight="normal" fill="#2D53A4"> <tspan x="502" y="233">Monospace</tspan> </text> </g> </svg>`, ); assertEquals(data.byteLength, 9651); }, });
42.64
154
0.558161
6626288a1a71712e36a973419fdacdd96c3c4911
189
kt
Kotlin
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/elements/ExpressionResolvedValueArgument.kt
timrijckaert/arrow-meta
2928e8a63d125c4537fb4480c25e508b1df615b2
[ "Apache-2.0" ]
4
2022-03-18T12:35:49.000Z
2022-03-22T10:56:29.000Z
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/elements/ExpressionResolvedValueArgument.kt
timrijckaert/arrow-meta
2928e8a63d125c4537fb4480c25e508b1df615b2
[ "Apache-2.0" ]
4
2022-03-17T13:23:35.000Z
2022-03-21T09:10:01.000Z
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/elements/ExpressionResolvedValueArgument.kt
timrijckaert/arrow-meta
2928e8a63d125c4537fb4480c25e508b1df615b2
[ "Apache-2.0" ]
null
null
null
package arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements interface ExpressionResolvedValueArgument { val argumentExpression: Expression? val isSpread: Boolean }
27
79
0.835979
bd678844424a88330ecee714ef93621dd3764236
4,126
rs
Rust
oak_functions/lookup_data_generator/src/data.rs
shikharvashistha/oak
411ce33cd8732ec3c4288da0fafd5907473d6337
[ "Apache-2.0" ]
null
null
null
oak_functions/lookup_data_generator/src/data.rs
shikharvashistha/oak
411ce33cd8732ec3c4288da0fafd5907473d6337
[ "Apache-2.0" ]
null
null
null
oak_functions/lookup_data_generator/src/data.rs
shikharvashistha/oak
411ce33cd8732ec3c4288da0fafd5907473d6337
[ "Apache-2.0" ]
null
null
null
// // Copyright 2021 The Project Oak Authors // // 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. // use anyhow::Context; use bytes::BytesMut; use oak_functions_abi::proto::Entry; use prost::Message; use rand::Rng; use serde::Serialize; fn create_bytes<R: Rng>(rng: &mut R, size_bytes: usize) -> Vec<u8> { let mut buf = vec![0u8; size_bytes]; rng.fill(buf.as_mut_slice()); buf } fn create_random_entry<R: Rng>( rng: &mut R, key_size_bytes: usize, value_size_bytes: usize, ) -> Entry { Entry { key: create_bytes(rng, key_size_bytes), value: create_bytes(rng, value_size_bytes), } } /// Generates random lookup entries with the specified sizes for keys and values and serializes it /// to bytes. pub fn generate_and_serialize_random_entries<R: Rng>( rng: &mut R, key_size_bytes: usize, value_size_bytes: usize, entries: usize, ) -> anyhow::Result<BytesMut> { let mut buf = BytesMut::new(); for _ in 0..entries { let entry = create_random_entry(rng, key_size_bytes, value_size_bytes); entry .encode_length_delimited(&mut buf) .context("could not encode entry")?; } Ok(buf) } #[derive(Serialize)] struct WeatherValue { temperature_degrees_celsius: i32, } fn create_weather_entry<R: Rng>(rng: &mut R, lat: i32, lon: i32) -> Entry { let key = format!("{},{}", lat, lon); let value = serde_json::to_string(&create_weather_value(rng)).unwrap(); Entry { key: key.as_bytes().to_vec(), value: value.as_bytes().to_vec(), } } fn create_weather_value<R: Rng>(rng: &mut R) -> WeatherValue { let dist = rand::distributions::Uniform::new(-30, 40); WeatherValue { temperature_degrees_celsius: rng.sample(dist), } } /// Generates a dense set of random weather lookup entries with one entry for each comibnation of /// full degree of longitude and latitude. pub fn generate_and_serialize_weather_entries<R: Rng>(rng: &mut R) -> anyhow::Result<BytesMut> { let mut buf = BytesMut::new(); for lat in -90..=90 { for lon in -180..=180 { let entry = create_weather_entry(rng, lat, lon); entry .encode_length_delimited(&mut buf) .context("could not encode entry")?; } } Ok(buf) } /// Generates a sparse set of random weather lookup entries with a random location for each entry. pub fn generate_and_serialize_sparse_weather_entries<R: Rng>( rng: &mut R, entries: usize, ) -> anyhow::Result<BytesMut> { let mut buf = BytesMut::new(); let lat_dist = rand::distributions::Uniform::new(-90_000, 90_000); let lon_dist = rand::distributions::Uniform::new(-180_000, 180_000); let mut keys = vec![]; for _ in 0..entries { let latitude_millidegrees: i32 = rng.sample(lat_dist); let longitude_millidegrees: i32 = rng.sample(lon_dist); let key = [ latitude_millidegrees.to_be_bytes(), longitude_millidegrees.to_be_bytes(), ] .concat(); keys.push(key.clone()); let value = serde_json::to_string(&create_weather_value(rng)).unwrap(); let entry = Entry { key: key.clone(), value: value.as_bytes().to_vec(), }; entry .encode_length_delimited(&mut buf) .context("could not encode entry")?; } let index = Entry { key: "index".as_bytes().to_vec(), value: keys.concat(), }; index .encode_length_delimited(&mut buf) .context("could not encode index")?; Ok(buf) }
31.496183
98
0.642996
f6e42bc21f02affcb6df6e49cb779a3cbb2f3da1
2,869
swift
Swift
FloatCoin/PairVC.swift
kaunteya/FloatCoin
fd8ff099f22657695c4a4aca012bf06a72ad84aa
[ "MIT" ]
10
2018-10-07T04:05:23.000Z
2022-02-12T19:01:00.000Z
FloatCoin/PairVC.swift
kaunteya/FloatCoin
fd8ff099f22657695c4a4aca012bf06a72ad84aa
[ "MIT" ]
null
null
null
FloatCoin/PairVC.swift
kaunteya/FloatCoin
fd8ff099f22657695c4a4aca012bf06a72ad84aa
[ "MIT" ]
3
2018-12-08T02:04:17.000Z
2021-02-18T21:37:28.000Z
// // PairVC.swift // FloatCoin // // Created by Kaunteya Suryawanshi on 25/12/17. // Copyright © 2017 Kaunteya Suryawanshi. All rights reserved. // import AppKit class PairVC: NSViewController { @IBOutlet weak var exchangePopupButton: NSPopUpButton! @IBOutlet weak var basePopupButton: NSPopUpButton! @IBOutlet weak var fiatPopUpButton: NSPopUpButton! @IBOutlet weak var infoLabel: NSTextField! var selectedExchange: Exchange { return Exchange.allCases[exchangePopupButton.indexOfSelectedItem] } var selectedBase: Currency { assert( basePopupButton.indexOfSelectedItem >= 0) return selectedExchange.type.baseCurrencies[basePopupButton.indexOfSelectedItem] } var selectedFIAT: Currency { assert(fiatPopUpButton.indexOfSelectedItem >= 0) return selectedExchange.type.FIATCurriences(crypto: selectedBase)[fiatPopUpButton.indexOfSelectedItem] } var selectedPair: Pair { return Pair(selectedBase, selectedFIAT) } override func viewDidLoad() { super.viewDidLoad() Exchange.allCases.forEach { (ex) in exchangePopupButton.addItem(withTitle: ex.description) } actionExchangeSelected(nil) infoLabel.isHidden = true } @IBAction func actionExchangeSelected(_ sender: NSPopUpButton?) { let baseCurriencies = selectedExchange.type.baseCurrencies basePopupButton.removeAllItems() baseCurriencies.forEach { basePopupButton.addItem(withTitle: $0.stringValue) } basePopupButton.selectItem(at: 0) let fiatList = selectedExchange.type.FIATCurriences(crypto: baseCurriencies.first!) fiatPopUpButton.removeAllItems() fiatList.forEach { fiatPopUpButton.addItem(withTitle: $0.stringValue) } } @IBAction func actionBaseCurrencySelected(_ sender: NSPopUpButton) { fiatPopUpButton.removeAllItems() let fiatList = selectedExchange.type.FIATCurriences(crypto: selectedBase) fiatList.forEach { fiatPopUpButton.addItem(withTitle: $0.stringValue) } } func show(info: String) { infoLabel.stringValue = info infoLabel.textColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) infoLabel.isHidden = false infoLabel.alignment = .center } @IBAction func add(_ sender: Any) { guard !UserDefaults.has(exchange: selectedExchange, pair: selectedPair) else { Log.warning("Already contains \(selectedExchange.description) \(selectedPair.description)"); show(info: "\(selectedPair.description) already added") return } UserDefaults.add(exchange: selectedExchange, pair: Pair(selectedBase, selectedFIAT)) self.dismiss(sender) } }
33.752941
114
0.686999
1841e94f18ebb1db5d263f6c79e86ba69f8b1573
703
rb
Ruby
lib/discovery_service.rb
REANNZ/discovery-service
10b8b10e1503e36c8e094bfc604efc3da4a58cc2
[ "Apache-2.0" ]
null
null
null
lib/discovery_service.rb
REANNZ/discovery-service
10b8b10e1503e36c8e094bfc604efc3da4a58cc2
[ "Apache-2.0" ]
1
2020-03-09T02:27:46.000Z
2020-03-09T02:27:46.000Z
lib/discovery_service.rb
REANNZ/discovery-service
10b8b10e1503e36c8e094bfc604efc3da4a58cc2
[ "Apache-2.0" ]
null
null
null
# frozen_string_literal: true require 'yaml' require 'discovery_service/persistence' require 'discovery_service/cookie' require 'discovery_service/response' require 'discovery_service/entity' require 'discovery_service/validation' require 'discovery_service/auditing' require 'discovery_service/embedded_wayf' require 'discovery_service/application' require 'discovery_service/renderer' require 'discovery_service/metadata' require 'discovery_service/event_consignment' # Top-level module for the Discovery Service project. module DiscoveryService CONFIG_FILE = 'config/discovery_service.yml' class <<self attr_reader :configuration end @configuration = YAML.load_file(CONFIG_FILE) end
26.037037
53
0.830725
4f9a40ddaeef2dfe752121a12c272ab3436c571f
1,978
lua
Lua
hammerspoon/init.lua
inoc603/dotfiles
a7c7592a59d51bb45a8d7977e51293ac2e845e1b
[ "MIT" ]
1
2017-04-20T13:24:50.000Z
2017-04-20T13:24:50.000Z
hammerspoon/init.lua
inoc603/dotfiles
a7c7592a59d51bb45a8d7977e51293ac2e845e1b
[ "MIT" ]
null
null
null
hammerspoon/init.lua
inoc603/dotfiles
a7c7592a59d51bb45a8d7977e51293ac2e845e1b
[ "MIT" ]
null
null
null
hs.hotkey.bind({"cmd", "ctrl"}, "r", function() hs.reload() end) hs.alert.show("Config loaded") function posX(screen) x, y = screen:position() return x end function screenAtCenter() local screens = hs.screen.allScreens() table.sort(screens, function(a, b) return posX(a) < posX(b) end) return screens[math.ceil(#screens/2)] end local wf=hs.window.filter function startsWith(str, start) return str:sub(1, #start) == start end local alacrittyPrefix = "alacritty-" local appCache = {} function moveToCenter(w) if startsWith(w:title(), alacrittyPrefix) then w:moveToScreen(screenAtCenter(), 0) end end -- when alacritty windows is created or focused by hot key, make sure it's in the center screen. local alacritty = wf.new(false):setAppFilter('Alacritty', {allowTitles=1}) alacritty:subscribe(wf.windowCreated, moveToCenter) alacritty:subscribe(wf.windowFocused, moveToCenter) function launchAlacritty(title, commands) title = alacrittyPrefix .. title app = appCache[title] if app == nil then app = hs.window.get(title) appCache[title] = app end if app == nil then params = {"-t", title, "--config-file", os.getenv("HOME") .. "/.alacritty.yml"} if commands then table.insert(params, "-e") for i, v in ipairs(commands) do table.insert(params, v) end end hs.task.new( "/Applications/Alacritty.app/Contents/MacOS/alacritty", function() print("STOPPED", title) appCache[title] = nil end, params ):start() else app:focus() end end -- ssh to devbox and attach to the last used tmux session. hs.hotkey.bind({"cmd", "ctrl"}, "k", function() launchAlacritty("remote", {"ssh", "t"}) end) -- attach to the last used tmux session or create one from home directory if there is none. hs.hotkey.bind({"cmd", "ctrl"}, "l", function() launchAlacritty("local", {"zsh", "--login", "-i", "-c", "ta"}) end)
25.037975
96
0.651668
7f2cb3962526353a74c4993fc38b070e727cc695
1,886
kt
Kotlin
samples/demoapp/src/main/java/com/joaquimverges/demoapp/view/MyDetailViewDelegate.kt
nairobi222/Helium
ae2a57bc70deea677a97f8d134d77e0dd8de75d4
[ "Apache-2.0" ]
1
2019-04-06T12:02:59.000Z
2019-04-06T12:02:59.000Z
samples/demoapp/src/main/java/com/joaquimverges/demoapp/view/MyDetailViewDelegate.kt
nairobi222/Helium
ae2a57bc70deea677a97f8d134d77e0dd8de75d4
[ "Apache-2.0" ]
null
null
null
samples/demoapp/src/main/java/com/joaquimverges/demoapp/view/MyDetailViewDelegate.kt
nairobi222/Helium
ae2a57bc70deea677a97f8d134d77e0dd8de75d4
[ "Apache-2.0" ]
null
null
null
package com.joaquimverges.demoapp.view import androidx.core.content.ContextCompat import android.transition.TransitionManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import android.widget.TextView import com.joaquimverges.demoapp.R import com.joaquimverges.demoapp.data.Colors import com.joaquimverges.demoapp.data.MyItem import com.joaquimverges.helium.core.event.ClickEvent import com.joaquimverges.helium.ui.state.ListViewState import com.joaquimverges.helium.core.viewdelegate.BaseViewDelegate /** * @author joaquim */ class MyDetailViewDelegate(inflater: LayoutInflater, container: ViewGroup?) : BaseViewDelegate<ListViewState<MyItem>, ClickEvent<MyItem>>( R.layout.detail_layout, inflater, container) { private val detailColorView: View = view.findViewById(R.id.detail_color_view) private val colorNameView: TextView = view.findViewById(R.id.color_name) private val loader: ProgressBar = view.findViewById(R.id.loader) override fun render(viewState: ListViewState<MyItem>) { TransitionManager.beginDelayedTransition(detailColorView as ViewGroup) when (viewState) { is ListViewState.Loading -> { loader.visibility = View.VISIBLE detailColorView.visibility = View.GONE } is ListViewState.DataReady -> { val item = viewState.data val color = ContextCompat.getColor(context, item.color) loader.visibility = View.GONE colorNameView.text = Colors.toHexString(color) detailColorView.visibility = View.VISIBLE detailColorView.setBackgroundColor(color) detailColorView.setOnClickListener { v -> pushEvent(ClickEvent(v, item)) } } } } }
39.291667
90
0.711559
da9b62a16cfe728237e00e04a4547039e1238c98
3,988
lua
Lua
libexec/httpd/lua/optparse.lua
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
libexec/httpd/lua/optparse.lua
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
libexec/httpd/lua/optparse.lua
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
-- Lua command line option parser. -- Interface based on Pythons optparse. -- http://docs.python.org/lib/module-optparse.html -- (c) 2008 David Manura, Licensed under the same terms as Lua (MIT license) -- -- To be used like this: -- t={usage="<some usage message>", version="<version string>"} -- op=OptionParser(t) -- op=add_option{"<opt>", action=<action>, dest=<dest>, help="<help message for this option>"} -- -- with : -- <opt> the option string to be used (can be anything, if one letter opt, then should be -x val, more letters: -xy=val ) -- <action> one of -- - store: store in options as key, val -- - store_true: stores key, true -- - store_false: stores key, false -- <dest> is the key under which the option is saved -- -- options,args = op.parse_args() -- -- now options is the table of options (key, val) and args is the table with non-option arguments. -- You can use op.fail(message) for failing and op.print_help() for printing the usage as you like. function OptionParser(t) local usage = t.usage local version = t.version local o = {} local option_descriptions = {} local option_of = {} function o.fail(s) -- extension io.stderr:write(s .. '\n') os.exit(1) end function o.add_option(optdesc) option_descriptions[#option_descriptions+1] = optdesc for _,v in ipairs(optdesc) do option_of[v] = optdesc end end function o.parse_args() -- expand options (e.g. "--input=file" -> "--input", "file") local arg = {unpack(arg)} for i=#arg,1,-1 do local v = arg[i] local flag, val = v:match('^(%-%-%w+)=(.*)') if flag then arg[i] = flag table.insert(arg, i+1, val) end end local options = {} local args = {} local i = 1 while i <= #arg do local v = arg[i] local optdesc = option_of[v] if optdesc then local action = optdesc.action local val if action == 'store' or action == nil then i = i + 1 val = arg[i] if not val then o.fail('option requires an argument ' .. v) end elseif action == 'store_true' then val = true elseif action == 'store_false' then val = false end options[optdesc.dest] = val else if v:match('^%-') then o.fail('invalid option ' .. v) end args[#args+1] = v end i = i + 1 end if options.help then o.print_help() os.exit() end if options.version then io.stdout:write(t.version .. "\n") os.exit() end return options, args end local function flags_str(optdesc) local sflags = {} local action = optdesc.action for _,flag in ipairs(optdesc) do local sflagend if action == nil or action == 'store' then local metavar = optdesc.metavar or optdesc.dest:upper() sflagend = #flag == 2 and ' ' .. metavar or '=' .. metavar else sflagend = '' end sflags[#sflags+1] = flag .. sflagend end return table.concat(sflags, ', ') end function o.print_help() io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n") io.stdout:write("\n") io.stdout:write("Options:\n") for _,optdesc in ipairs(option_descriptions) do io.stdout:write(" " .. flags_str(optdesc) .. " " .. optdesc.help .. "\n") end end o.add_option{"--help", action="store_true", dest="help", help="show this help message and exit"} if t.version then o.add_option{"--version", action="store_true", dest="version", help="output version info."} end return o end
32.16129
123
0.541625
71c93e5ee87bdd8e27bd7dda9fc164d76fb9f88c
4,113
ts
TypeScript
src/lib/telegram/extra/menu.ts
gmalamuddeb/AnilistBot
48507b7db246431d28dc8987760398a75940e1c8
[ "MIT" ]
33
2018-09-16T20:18:21.000Z
2022-03-27T18:59:19.000Z
src/lib/telegram/extra/menu.ts
gmalamuddeb/AnilistBot
48507b7db246431d28dc8987760398a75940e1c8
[ "MIT" ]
17
2018-10-11T22:18:24.000Z
2022-02-13T07:38:54.000Z
src/lib/telegram/extra/menu.ts
gmalamuddeb/AnilistBot
48507b7db246431d28dc8987760398a75940e1c8
[ "MIT" ]
27
2018-10-11T22:32:09.000Z
2022-03-13T15:35:06.000Z
// tslint:disable: no-submodule-imports import { aboutKeyboard, countdownKeyboard, counterBackKeyboard, guideKeyboard, languageBackKeyboard, languageKeyboard, menuKeyboard, notifyBackKeyboard, notifyKeyboard, recommendationKeyboard, startKeyboard, timeBackKeyboard, timeHourKeyboard, timeKeyboard, timePeriodKeyboard, userKeyboard } from 'keyboard'; import { Extra } from 'telegraf'; import { LanguageRequest, NotifyRequests, Period, TimeRequest, UserRequest } from 'telegraf-bot-typings'; import { I18n } from 'telegraf-i18n'; import { ExtraEditMessage } from 'telegraf/typings/telegram-types'; import { IHandleLanguageExtra, IHandleMediaExtra, IHandleNotifyExtra, IHandleTimeExtra, IHandleUserExtra } from '.'; import { animeExtra, mangaExtra } from './media'; const timeBackExtra = (): ExtraEditMessage => Extra.markdown().markup(timeBackKeyboard()); const notifyBackExtra = (): ExtraEditMessage => Extra.markdown().markup(notifyBackKeyboard()); const languageBackExtra = (): ExtraEditMessage => Extra.markdown().markup(languageBackKeyboard()); const timeHourExtra = (period: Period): ExtraEditMessage => Extra.markdown().markup(timeHourKeyboard(period)); const timeExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(timeKeyboard(translation)); const notifyExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(notifyKeyboard(translation)); const languageExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(languageKeyboard(translation)); const timePeriodExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(timePeriodKeyboard(translation)); const handleLanguageExtra = ({ value, translation }: IHandleLanguageExtra): ExtraEditMessage => { return (null === value) ? languageExtra(translation) : languageBackExtra(); }; const handleNotifyExtra = ({ value, translation }: IHandleNotifyExtra): ExtraEditMessage => { return (null === value) ? notifyExtra(translation) : notifyBackExtra(); }; const handleTimeExtra = ({ value, request, translation }: IHandleTimeExtra): ExtraEditMessage => { if ('TIME' === <UserRequest> request) { return timeExtra(translation); } if ('PERIOD' === <TimeRequest> request) { return timePeriodExtra(translation); } if ('AM' === <TimeRequest> request || 'PM' === <TimeRequest> request) { return timeHourExtra(<Period> request); } return timeBackExtra(); }; export const aboutExtra = (): ExtraEditMessage => Extra.markdown().markup(aboutKeyboard()); export const counterExtra = (): ExtraEditMessage => Extra.markdown().markup(counterBackKeyboard()); export const countdownExtra = (): ExtraEditMessage => Extra.markdown().markup(countdownKeyboard()); export const recommendationExtra = (): ExtraEditMessage => Extra.markdown().markup(recommendationKeyboard()); export const menuExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(menuKeyboard(translation)); export const userExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(userKeyboard(translation)); export const startExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(startKeyboard(translation)); export const guideExtra = (translation: I18n): ExtraEditMessage => Extra.markdown().markup(guideKeyboard(translation)); export const handleMediaExtra = async ({ user, list, filter, translation }: IHandleMediaExtra): Promise<ExtraEditMessage> => { return ('WATCH' === list) ? mangaExtra({ user, filter, translation }) : animeExtra({ user, filter, translation }); }; export const handleUserExtra = ({ value, request, translation }: IHandleUserExtra): ExtraEditMessage => { if ('ALL' === <UserRequest> request) { return userExtra(translation); } if ('NOTIFY' === <UserRequest> request) { return handleNotifyExtra({ value: <NotifyRequests> value, translation }); } if ('LANGUAGE' === <UserRequest> request) { return handleLanguageExtra({ value: <LanguageRequest> value, translation }); } return handleTimeExtra({ value: <TimeRequest> value, request, translation }); };
52.063291
132
0.742281
161a26670648f222d07a3cc7d9d0d73373cc4f96
9,445
ts
TypeScript
src/blockchain/transactions.ts
OasisDEX/xDex
e75d9fe69a9f9ceda4097546c9f6a8308b599a8d
[ "Apache-2.0" ]
null
null
null
src/blockchain/transactions.ts
OasisDEX/xDex
e75d9fe69a9f9ceda4097546c9f6a8308b599a8d
[ "Apache-2.0" ]
1
2022-02-21T14:14:10.000Z
2022-02-22T06:16:16.000Z
src/blockchain/transactions.ts
OasisDEX/xDex
e75d9fe69a9f9ceda4097546c9f6a8308b599a8d
[ "Apache-2.0" ]
1
2021-08-01T16:29:45.000Z
2021-08-01T16:29:45.000Z
/* * Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC. */ import * as _ from 'lodash'; import { fromPairs } from 'ramda'; import { bindNodeCallback, combineLatest, fromEvent, merge, Observable, of, Subject, timer } from 'rxjs'; import { takeWhileInclusive } from 'rxjs-take-while-inclusive'; import { ajax } from 'rxjs/ajax'; import { catchError, filter, first, map, mergeMap, scan, shareReplay, startWith, switchMap } from 'rxjs/operators'; import { UnreachableCaseError } from '../utils/UnreachableCaseError'; import { account$, context$, onEveryBlock$ } from './network'; import { web3 } from './web3'; export enum TxStatus { WaitingForApproval = 'WaitingForApproval', CancelledByTheUser = 'CancelledByTheUser', Propagating = 'Propagating', WaitingForConfirmation = 'WaitingForConfirmation', Success = 'Success', Error = 'Error', Failure = 'Failure', } export function isDone(state: TxState) { return [TxStatus.CancelledByTheUser, TxStatus.Error, TxStatus.Failure, TxStatus.Success].indexOf(state.status) >= 0; } export function isDoneButNotSuccessful(state: TxState) { return [TxStatus.CancelledByTheUser, TxStatus.Error, TxStatus.Failure].indexOf(state.status) >= 0; } export function isSuccess(state: TxState) { return TxStatus.Success === state.status; } export function getTxHash(state: TxState): string | undefined { if ( state.status === TxStatus.Success || state.status === TxStatus.Failure || state.status === TxStatus.Error || state.status === TxStatus.WaitingForConfirmation ) { return state.txHash; } return undefined; } export enum TxRebroadcastStatus { speedup = 'speedup', cancel = 'cancel', } export type TxState = { account: string; txNo: number; networkId: string; meta: any; start: Date; end?: Date; lastChange: Date; dismissed: boolean; } & ( | { status: TxStatus.WaitingForApproval; } | { status: TxStatus.CancelledByTheUser; error: any; } | { status: TxStatus.WaitingForConfirmation | TxStatus.Propagating; txHash: string; broadcastedAt: Date; } | { status: TxStatus.Success; txHash: string; blockNumber: number; receipt: any; confirmations: number; safeConfirmations: number; rebroadcast?: TxRebroadcastStatus; } | { status: TxStatus.Failure; txHash: string; blockNumber: number; receipt: any; } | { status: TxStatus.Error; txHash: string; error: any; } ); let txCounter: number = 1; type NodeCallback<I, R> = (i: I, callback: (err: any, r: R) => any) => any; interface TransactionReceiptLike { transactionHash: string; status: boolean; blockNumber: number; } type GetTransactionReceipt = NodeCallback<string, TransactionReceiptLike>; interface TransactionLike { hash: string; nonce: number; input: string; blockHash: string; } type GetTransaction = NodeCallback<string, TransactionLike | null>; function txRebroadcastStatus({ hash, nonce, input }: TransactionLike) { return combineLatest(externalNonce2tx$, onEveryBlock$).pipe( map(([externalNonce2tx]) => { if (externalNonce2tx[nonce] && externalNonce2tx[nonce].hash !== hash) { return [ externalNonce2tx[nonce].hash, input === externalNonce2tx[nonce].callData ? TxRebroadcastStatus.speedup : TxRebroadcastStatus.cancel, ]; } return [hash, undefined]; }), ) as Observable<[string, undefined | TxRebroadcastStatus]>; } export function send( account: string, networkId: string, meta: any, method: (...args: any[]) => any, // Any contract method ): Observable<TxState> { const common = { account, networkId, meta, txNo: txCounter += 1, start: new Date(), lastChange: new Date(), }; function successOrFailure( txHash: string, receipt: TransactionReceiptLike, rebroadcast: TxRebroadcastStatus | undefined, ): Observable<TxState> { const end = new Date(); if (!receipt.status) { // TODO: failure should be confirmed! return of({ ...common, txHash, receipt, end, lastChange: end, blockNumber: receipt.blockNumber, status: TxStatus.Failure, } as TxState); } // TODO: error handling! return combineLatest(context$, onEveryBlock$).pipe( mergeMap(([context, blockNumber]) => of({ ...common, txHash, receipt, end, rebroadcast, lastChange: new Date(), blockNumber: receipt.blockNumber, status: TxStatus.Success, confirmations: Math.max(0, blockNumber - receipt.blockNumber), safeConfirmations: context.safeConfirmations, } as TxState), ), takeWhileInclusive((state) => state.status === TxStatus.Success && state.confirmations < state.safeConfirmations), ); } const promiEvent = method(); const result: Observable<TxState> = merge(fromEvent(promiEvent, 'transactionHash'), promiEvent).pipe( map((txHash: string) => [txHash, new Date()]), first(), mergeMap(([txHash, broadcastedAt]: [string, Date]) => timer(0, 1000).pipe( switchMap(() => bindNodeCallback(web3.eth.getTransaction as GetTransaction)(txHash)), filter((transaction) => !!transaction), first(), mergeMap( (transaction: TransactionLike) => (txRebroadcastStatus(transaction).pipe( switchMap(([hash, rebroadcast]) => bindNodeCallback(web3.eth.getTransactionReceipt as GetTransactionReceipt)(hash).pipe( filter((receipt) => receipt && !!receipt.blockNumber), mergeMap((receipt) => successOrFailure(hash, receipt, rebroadcast)), ), ), first(), startWith({ ...common, broadcastedAt, txHash, status: TxStatus.WaitingForConfirmation, } as TxState), catchError((error) => { return of({ ...common, error, txHash: transaction.hash, end: new Date(), lastChange: new Date(), status: TxStatus.Error, } as TxState); }), ) as any) as Observable<TxState>, ), startWith({ ...common, broadcastedAt, txHash, status: TxStatus.Propagating, } as TxState), ), ), startWith({ ...common, status: TxStatus.WaitingForApproval, }), shareReplay(1), catchError((error) => { if ((error.message as string).indexOf('User denied transaction signature') === -1) { console.error(error); } return of({ ...common, error, end: new Date(), lastChange: new Date(), status: TxStatus.CancelledByTheUser, }); }), ); result.subscribe((state) => transactionObserver.next({ state, kind: 'newTx' })); return result; } interface NewTransactionChange { kind: 'newTx'; state: TxState; } interface DismissedChange { kind: 'dismissed'; txNo: number; } export const transactionObserver: Subject<TransactionsChange> = new Subject(); type TransactionsChange = NewTransactionChange | DismissedChange; export const transactions$: Observable<TxState[]> = combineLatest( transactionObserver.pipe( scan((transactions: TxState[], change: TransactionsChange) => { switch (change.kind) { case 'newTx': { const newState = change.state; const result = [...transactions]; const i = result.findIndex((t) => t.txNo === newState.txNo); if (i >= 0) { result[i] = newState; } else { result.push(newState); } return result; } case 'dismissed': { const result = [...transactions]; const i = result.findIndex((t) => t.txNo === change.txNo); result[i].dismissed = true; return result; } default: throw new UnreachableCaseError(change); } }, []), ), account$, context$, ).pipe( map(([transactions, account, context]) => transactions.filter((t: TxState) => t.account === account && t.networkId === context.id), ), startWith([]), shareReplay(1), ); interface ExternalNonce2tx { [nonce: number]: { hash: string; callData: string }; } const externalNonce2tx$: Observable<ExternalNonce2tx> = combineLatest( context$, account$, onEveryBlock$.pipe(first()), onEveryBlock$, ).pipe( switchMap(([context, account, firstBlock]) => ajax({ url: `${context.etherscan.apiUrl}?module=account` + `&action=txlist` + `&address=${account}` + `&startblock=${firstBlock}` + `&sort=desc` + `&apikey=${context.etherscan.apiKey}`, }), ), map(({ response }) => response.result), map((transactions: Array<{ hash: string; nonce: string; input: string }>) => fromPairs( _.map( transactions, (tx) => [tx.nonce, { hash: tx.hash, callData: tx.input }] as [string, { hash: string; callData: string }], ), ), ), catchError((error) => { console.error(error); return of({}); }), shareReplay(1), );
27.456395
120
0.602859
dd7983017a466571396f064b001a766a345a9a97
694
php
PHP
database/seeds/ReportValueTypeSeeder.php
j2cey/adminitL7
526e96e46872caae28958e0bb074d4b08e5d7e13
[ "MIT" ]
null
null
null
database/seeds/ReportValueTypeSeeder.php
j2cey/adminitL7
526e96e46872caae28958e0bb074d4b08e5d7e13
[ "MIT" ]
4
2021-02-02T20:34:23.000Z
2022-02-27T08:18:21.000Z
database/seeds/ReportValueTypeSeeder.php
j2cey/adminitL7
526e96e46872caae28958e0bb074d4b08e5d7e13
[ "MIT" ]
null
null
null
<?php use App\ReportValueType; use Illuminate\Database\Seeder; class ReportValueTypeSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $report_value_types = [ [ 'valuetype' => "STRING" ], [ 'valuetype' => "INTEGER" ], [ 'valuetype' => "BLOB" ], [ 'valuetype' => "BOOLEAN" ], [ 'valuetype' => "DATETIME" ], [ 'valuetype' => "IP address" ], [ 'valuetype' => "JSON" ] ]; foreach ($report_value_types as $report_value_type) { ReportValueType::create($report_value_type); } } }
23.931034
61
0.495677
949ccc28c98abe3831de81a62d9e928c64ebe7c1
9,037
rs
Rust
piet-gpu/src/main.rs
msiglreith/piet-gpu
144f46c5fa89a28d3d0acb290dedf38ca78d6c43
[ "Apache-2.0", "MIT" ]
null
null
null
piet-gpu/src/main.rs
msiglreith/piet-gpu
144f46c5fa89a28d3d0acb290dedf38ca78d6c43
[ "Apache-2.0", "MIT" ]
null
null
null
piet-gpu/src/main.rs
msiglreith/piet-gpu
144f46c5fa89a28d3d0acb290dedf38ca78d6c43
[ "Apache-2.0", "MIT" ]
null
null
null
use std::fs::File; use std::io::BufWriter; use std::path::Path; use rand::{Rng, RngCore}; use piet::kurbo::{BezPath, Circle, Line, Point, Vec2}; use piet::{Color, RenderContext}; use piet_gpu_hal::vulkan::VkInstance; use piet_gpu_hal::{CmdBuf, Device, MemFlags}; mod render_ctx; use render_ctx::PietGpuRenderContext; const WIDTH: usize = 2048; const HEIGHT: usize = 1536; const TILE_W: usize = 16; const TILE_H: usize = 16; const WIDTH_IN_TILEGROUPS: usize = 4; const HEIGHT_IN_TILEGROUPS: usize = 96; const TILEGROUP_STRIDE: usize = 2048; const WIDTH_IN_TILES: usize = 128; const HEIGHT_IN_TILES: usize = 96; const PTCL_INITIAL_ALLOC: usize = 1024; const K2_PER_TILE_SIZE: usize = 8; const N_CIRCLES: usize = 1; fn render_scene(rc: &mut impl RenderContext) { let mut rng = rand::thread_rng(); for _ in 0..N_CIRCLES { let color = Color::from_rgba32_u32(rng.next_u32()); let center = Point::new( rng.gen_range(0.0, WIDTH as f64), rng.gen_range(0.0, HEIGHT as f64), ); let radius = rng.gen_range(0.0, 50.0); let circle = Circle::new(center, radius); rc.fill(circle, &color); } rc.stroke( Line::new((100.0, 100.0), (200.0, 150.0)), &Color::WHITE, 5.0, ); render_cardioid(rc); } fn render_cardioid(rc: &mut impl RenderContext) { let n = 100; let dth = std::f64::consts::PI * 2.0 / (n as f64); let center = Point::new(1024.0, 768.0); let r = 750.0; let mut path = BezPath::new(); for i in 1..n { let p0 = center + Vec2::from_angle(i as f64 * dth) * r; let p1 = center + Vec2::from_angle(((i * 2) % n) as f64 * dth) * r; rc.fill(&Circle::new(p0, 8.0), &Color::WHITE); path.move_to(p0); path.line_to(p1); //rc.stroke(Line::new(p0, p1), &Color::BLACK, 2.0); } rc.stroke(&path, &Color::BLACK, 2.0); } #[allow(unused)] fn dump_scene(buf: &[u8]) { for i in 0..(buf.len() / 4) { let mut buf_u32 = [0u8; 4]; buf_u32.copy_from_slice(&buf[i * 4..i * 4 + 4]); println!("{:4x}: {:8x}", i * 4, u32::from_le_bytes(buf_u32)); } } #[allow(unused)] fn dump_k1_data(k1_buf: &[u32]) { for i in 0..k1_buf.len() { if k1_buf[i] != 0 { println!("{:4x}: {:8x}", i, k1_buf[i]); } } } fn main() { let instance = VkInstance::new().unwrap(); unsafe { let device = instance.device().unwrap(); let host = MemFlags::host_coherent(); let dev = MemFlags::device_local(); let mut ctx = PietGpuRenderContext::new(); render_scene(&mut ctx); let scene = ctx.get_scene_buf(); //dump_scene(&scene); let scene_buf = device .create_buffer(std::mem::size_of_val(&scene[..]) as u64, host) .unwrap(); let scene_dev = device .create_buffer(std::mem::size_of_val(&scene[..]) as u64, dev) .unwrap(); device.write_buffer(&scene_buf, &scene).unwrap(); let tilegroup_buf = device.create_buffer(4 * 1024 * 1024, dev).unwrap(); let ptcl_buf = device.create_buffer(48 * 1024 * 1024, dev).unwrap(); let segment_buf = device.create_buffer(64 * 1024 * 1024, dev).unwrap(); let image_buf = device .create_buffer((WIDTH * HEIGHT * 4) as u64, host) .unwrap(); let image_dev = device .create_buffer((WIDTH * HEIGHT * 4) as u64, dev) .unwrap(); let k1_alloc_buf_host = device.create_buffer(4, host).unwrap(); let k1_alloc_buf_dev = device.create_buffer(4, dev).unwrap(); let k1_alloc_start = WIDTH_IN_TILEGROUPS * HEIGHT_IN_TILEGROUPS * TILEGROUP_STRIDE; device .write_buffer(&k1_alloc_buf_host, &[k1_alloc_start as u32]) .unwrap(); let k1_code = include_bytes!("../shader/kernel1.spv"); let k1_pipeline = device.create_simple_compute_pipeline(k1_code, 3).unwrap(); let k1_ds = device .create_descriptor_set( &k1_pipeline, &[&scene_dev, &tilegroup_buf, &k1_alloc_buf_dev], ) .unwrap(); let k2s_alloc_buf_host = device.create_buffer(4, host).unwrap(); let k2s_alloc_buf_dev = device.create_buffer(4, dev).unwrap(); let k2s_alloc_start = WIDTH_IN_TILES * HEIGHT_IN_TILES * K2_PER_TILE_SIZE; device .write_buffer(&k2s_alloc_buf_host, &[k2s_alloc_start as u32]) .unwrap(); let k2s_code = include_bytes!("../shader/kernel2s.spv"); let k2s_pipeline = device.create_simple_compute_pipeline(k2s_code, 4).unwrap(); let k2s_ds = device .create_descriptor_set( &k2s_pipeline, &[&scene_dev, &tilegroup_buf, &segment_buf, &k2s_alloc_buf_dev], ) .unwrap(); let k3_alloc_buf_host = device.create_buffer(4, host).unwrap(); let k3_alloc_buf_dev = device.create_buffer(4, dev).unwrap(); let k3_alloc_start = WIDTH_IN_TILES * HEIGHT_IN_TILES * PTCL_INITIAL_ALLOC; device .write_buffer(&k3_alloc_buf_host, &[k3_alloc_start as u32]) .unwrap(); let k3_code = include_bytes!("../shader/kernel3.spv"); let k3_pipeline = device.create_simple_compute_pipeline(k3_code, 5).unwrap(); let k3_ds = device .create_descriptor_set( &k3_pipeline, &[ &scene_dev, &tilegroup_buf, &segment_buf, &ptcl_buf, &k3_alloc_buf_dev, ], ) .unwrap(); let k4_code = include_bytes!("../shader/kernel4.spv"); let k4_pipeline = device.create_simple_compute_pipeline(k4_code, 3).unwrap(); let k4_ds = device .create_descriptor_set(&k4_pipeline, &[&ptcl_buf, &segment_buf, &image_dev]) .unwrap(); let query_pool = device.create_query_pool(5).unwrap(); let mut cmd_buf = device.create_cmd_buf().unwrap(); cmd_buf.begin(); cmd_buf.copy_buffer(&scene_buf, &scene_dev); cmd_buf.copy_buffer(&k1_alloc_buf_host, &k1_alloc_buf_dev); cmd_buf.copy_buffer(&k2s_alloc_buf_host, &k2s_alloc_buf_dev); cmd_buf.copy_buffer(&k3_alloc_buf_host, &k3_alloc_buf_dev); cmd_buf.clear_buffer(&tilegroup_buf); cmd_buf.clear_buffer(&ptcl_buf); cmd_buf.memory_barrier(); cmd_buf.write_timestamp(&query_pool, 0); cmd_buf.dispatch( &k1_pipeline, &k1_ds, ((WIDTH / 512) as u32, (HEIGHT / 512) as u32, 1), ); cmd_buf.write_timestamp(&query_pool, 1); cmd_buf.memory_barrier(); cmd_buf.dispatch( &k2s_pipeline, &k2s_ds, ((WIDTH / 512) as u32, (HEIGHT / 16) as u32, 1), ); cmd_buf.write_timestamp(&query_pool, 2); cmd_buf.memory_barrier(); cmd_buf.dispatch( &k3_pipeline, &k3_ds, ((WIDTH / 512) as u32, (HEIGHT / 16) as u32, 1), ); cmd_buf.write_timestamp(&query_pool, 3); cmd_buf.memory_barrier(); cmd_buf.dispatch( &k4_pipeline, &k4_ds, ((WIDTH / TILE_W) as u32, (HEIGHT / TILE_H) as u32, 1), ); cmd_buf.write_timestamp(&query_pool, 4); cmd_buf.memory_barrier(); cmd_buf.copy_buffer(&image_dev, &image_buf); cmd_buf.finish(); device.run_cmd_buf(&cmd_buf).unwrap(); let timestamps = device.reap_query_pool(query_pool).unwrap(); println!("Kernel 1 time: {:.3}ms", timestamps[0] * 1e3); println!( "Kernel 2 time: {:.3}ms", (timestamps[1] - timestamps[0]) * 1e3 ); println!( "Kernel 3 time: {:.3}ms", (timestamps[2] - timestamps[1]) * 1e3 ); println!( "Render time: {:.3}ms", (timestamps[3] - timestamps[2]) * 1e3 ); /* let mut k1_data: Vec<u32> = Default::default(); device.read_buffer(&segment_buf, &mut k1_data).unwrap(); dump_k1_data(&k1_data); */ let mut img_data: Vec<u8> = Default::default(); // Note: because png can use a `&[u8]` slice, we could avoid an extra copy // (probably passing a slice into a closure). But for now: keep it simple. device.read_buffer(&image_buf, &mut img_data).unwrap(); // Write image as PNG file. let path = Path::new("image.png"); let file = File::create(path).unwrap(); let ref mut w = BufWriter::new(file); let mut encoder = png::Encoder::new(w, WIDTH as u32, HEIGHT as u32); encoder.set_color(png::ColorType::RGBA); encoder.set_depth(png::BitDepth::Eight); let mut writer = encoder.write_header().unwrap(); writer.write_image_data(&img_data).unwrap(); } }
35.439216
91
0.577072
d2c9a759cf9e605bec8e246e2efff5549e6d6323
903
php
PHP
src/Model/Env/EnvEntry.php
jakubtobiasz/Yacht
efb5a626ef1f452bed34e3a6e52bf0f5ce3ef83b
[ "MIT" ]
null
null
null
src/Model/Env/EnvEntry.php
jakubtobiasz/Yacht
efb5a626ef1f452bed34e3a6e52bf0f5ce3ef83b
[ "MIT" ]
null
null
null
src/Model/Env/EnvEntry.php
jakubtobiasz/Yacht
efb5a626ef1f452bed34e3a6e52bf0f5ce3ef83b
[ "MIT" ]
null
null
null
<?php /* * This file is part of the Yacht project. * * (c) Jakub Tobiasz <jakub@wolen.software> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Wolen\Yacht\Model\Env; final class EnvEntry implements EnvEntryInterface { private string $key; private string $value; public function __construct(string $key, string $value) { $this->key = $key; $this->value = $value; } public function getKey(): string { return $this->key; } public function getValue(): string { return $this->value; } public function setValue(string $value): void { $this->value = $value; } public function __toString() { return sprintf('%s=%s', $this->getKey(), $this->getValue()); } }
18.8125
75
0.613511
16735c586d5093674db4ba9ef9cbe38c9e1c85be
4,614
ts
TypeScript
src/app/registro/registro.component.ts
jmirandaa/Prestamigos-Angular2
ab3beebbd671f58e24ec858c14c05ddc4e80d26d
[ "MIT" ]
1
2017-10-31T07:46:49.000Z
2017-10-31T07:46:49.000Z
src/app/registro/registro.component.ts
jmirandaa/Prestamigos-Angular2
ab3beebbd671f58e24ec858c14c05ddc4e80d26d
[ "MIT" ]
null
null
null
src/app/registro/registro.component.ts
jmirandaa/Prestamigos-Angular2
ab3beebbd671f58e24ec858c14c05ddc4e80d26d
[ "MIT" ]
null
null
null
declare var componentHandler: any; import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import {ValidatorService} from '../servicios/validator.service'; import {UIService} from '../servicios/ui.service'; import {UsuarioService} from '../servicios/usuario.service'; import {Usuario} from '../modelo/Usuario'; @Component({ moduleId: module.id, templateUrl: 'registro.component.html' }) export class RegistroComponent implements OnInit { model: any = {}; loading = false; returnUrl: string; constructor(private route: ActivatedRoute, private router: Router, private validator : ValidatorService, private ui : UIService, private usuarioService : UsuarioService) { } ngOnInit() { // get return url from route parameters or default to '/' this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; } ngAfterViewInit() { componentHandler.upgradeDom(); } atras() { this.router.navigate(["/"]); } //Comprobar datos procederRegistro() { var resultado = true; if (!this.validator.textoValidoCorto(this.model.nombre)) { this.ui.mostrarSnack("Nombre demasiado corto (min 3)"); resultado = false; } else if (!this.validator.textoValidoCorto(this.model.apellidos)) { this.ui.mostrarSnack("Apellidos demasiado cortos (min 3)"); resultado = false; } else if (!this.validator.emailValido(this.model.email)) { this.ui.mostrarSnack("Correo electrónico inválido"); resultado = false; } else if (!this.validator.textoValido(this.model.password)) { this.ui.mostrarSnack("Contraseña demasiado corta (min 5)"); resultado = false; } else if (this.model.email != this.model.emailRep) { this.ui.mostrarSnack("El correo electrónico no coincide"); resultado = false; } else if (this.model.password != this.model.passwordRep) { this.ui.mostrarSnack("La contraseña no coincide"); resultado = false; } if (resultado) { this.registrarUsuario(); } } //Servicio de nuevo usuario registrarUsuario() { var usuario : Usuario = new Usuario(0); usuario.setNombre(this.model.nombre); usuario.setApellidos(this.model.apellidos); usuario.setEmail(this.model.email); usuario.setPassword(this.model.password); this.usuarioService.nuevoUsuario(usuario).subscribe( data => { console.log(data); if (data.codError == 0) { //Login this.usuarioService.login(this.model.email, this.model.password).subscribe( data => { console.log(data); if (data.codError == 0) { //Guardar datos window.localStorage.setItem('idUsuario', data.contenido.id); window.localStorage.setItem('email', data.contenido.email); window.localStorage.setItem('nombre', data.contenido.nombre); window.localStorage.setItem('apellidos', data.contenido.apellidos); //Ir a pantalla de deudas this.router.navigate(['/deudas',{tipoDeuda: 1}]); } else { //Mensaje error this.ui.mostrarSnack("Nombre de usuario o contraseña incorrecta"); } }, err => { this.ui.mostrarSnack("Error de conexión") }, () => console.log("OK") ); } else { this.ui.mostrarSnack("Error al crear usuario"); } }, err => { this.ui.mostrarSnack("Error de conexión"); }, () => console.log("OK") ); } }
36.046875
127
0.490247
ddd664b86501564b8335ac2f7be893151c97d048
4,699
c
C
pkg/imphttab/test_getphttab.c
rendinam/hstcal
e08676b02e4c7cd06e3d5630b62f7b59951ac8c3
[ "BSD-3-Clause" ]
8
2016-07-28T15:14:27.000Z
2020-04-02T16:37:23.000Z
pkg/imphttab/test_getphttab.c
rendinam/hstcal
e08676b02e4c7cd06e3d5630b62f7b59951ac8c3
[ "BSD-3-Clause" ]
484
2016-03-14T20:44:42.000Z
2022-03-31T15:54:38.000Z
pkg/imphttab/test_getphttab.c
rendinam/hstcal
e08676b02e4c7cd06e3d5630b62f7b59951ac8c3
[ "BSD-3-Clause" ]
21
2016-03-14T14:22:35.000Z
2022-02-07T18:41:49.000Z
#include <stdio.h> #include <string.h> #include "hstio.h" #include "hstcal.h" #include "c_iraf.h" #include "imphttab.h" /* Function to implement a self-test of this library */ int main(int argc, char **argv){ void c_irafinit (int, char **); void compute_values(char [], char [], double, float, float, FILE *); char *outfile; FILE *fp; outfile = "testphot_out.txt"; fp = fopen(outfile, "w"); fprintf(fp, "==== Starting self-test for getphttab.c ====\n"); /* Initialize IRAF environment */ c_irafinit(argc, argv); fprintf(fp, "==> Initialized IRAF environment for getphttab.\n"); compute_values( "acs,wfc1,fr853n#8344.75,mjd#54718", "Half-way points for both pars.", 1.2695867062843802e-18, 8344.119572140797, 56.793040505098716, fp); compute_values( "acs,wfc1,mjd#54718.0,fr853n#8344.75", "Like above but in different order (results should be same).", 1.2695867062843802e-18, 8344.119572140797, 56.793040505098716, fp); compute_values( "acs,wfc1,fr853n#8158,mjd#52334", "Both pars at lower boundary.", 1.1984913607659768e-18, 8158.271171088088, 59.462191932802028, fp); compute_values( "acs,wfc1,fr853n#8158,mjd#54718", "Only FR at lower boundary.", 1.2230171665655153e-18, 8158.273423487024, 59.320487871226852, fp); compute_values( "acs,wfc1,fr853n#8344.75,mjd#59214", "Only MJD at upper boundary.", 1.2544879212041671e-18, 8344.116261683303, 56.820520968140734, fp); compute_values( "acs,wfc1,fr853n#8905,mjd#59214", "Both pars at upper boundary.", 1.522786245291286e-18, 8900.34723883603, 77.771312111848076, fp); compute_values( "acs,wfc1,f625w,fr462n#4462,mjd#55000", "Random 2 pars with another filter.", 1.0157653348302224e-13, 5873.489318646888, 926.61307046259992, fp); compute_values( "acs,wfc1,f814w,mjd#55021.0122", "Random 1 par with a filter.", 7.0073064555265768e-20, 8059.349015606429, 652.38059499466738, fp); compute_values( "acs,wfc1,f814w", "No par with a filter.", 7.0767633114602767e-20, 8058.784799323781, 652.34210160962766, fp); /* Extrapolation is not direct equivalent with pysynphot. Here, extrapolate from last 2 data points with straight line. */ compute_values( "acs,wfc1,fr853n#6500,mjd#54718", "FR extrapolation (should not be allowed).", -9999, -9999, -9999, fp); compute_values( "acs,wfc1,fr853n#8344.75,mjd#48000", "MJD extrapolation into the past.", 1.2339682890817842e-18, 8344.08667342431, 57.038104938309452, fp); compute_values( "acs,wfc1,fr853n#8344.75,mjd#68000", "MJD extrapolation into the future.", 1.2544879212041671e-18, 8344.116261683303, 56.820520968140734, fp); if ((status = fcloseWithStatus(&fp))) return status; printf("Wrote test results to %s\n", outfile); return 0; } void compute_values(char photmode[CHAR_LINE_LENGTH], char test_title[CHAR_LINE_LENGTH], double ans_photflam, float ans_photplam, float ans_photbw, FILE *fp) { PhotPar obs; int status; char refname[CHAR_LINE_LENGTH], refpedigree[SZ_FITS_REC]; double diff_photflam, diff_photplam, diff_photbw; /*strcpy(refname,"/grp/hst/cdbs/jref/w3m17171j_imp.fits");*/ /* -9999 */ strcpy(refname, "w3m17171j_extrap_imp.fits"); /* Extrapolate */ strcpy(refpedigree, "Inflight calibrations"); fprintf(fp, "\n==> PHOTMODE: %s\n==> %s\n", photmode, test_title); InitPhotPar(&obs, refname, refpedigree); fprintf(fp, "==> Finished InitPhotPar()\n"); status = GetPhotTab(&obs, photmode); fprintf(fp, "==> Finished computing photometry keyword values.\n"); FreePhotPar(&obs); fprintf(fp, "==> Cleaned up memory with FreePhotPar()\n"); if (status == 0){ diff_photflam = (obs.photflam - ans_photflam) * 100.0 / ans_photflam; diff_photplam = (obs.photplam - ans_photplam) * 100.0 / ans_photplam; diff_photbw = (obs.photbw - ans_photbw) * 100.0 / ans_photbw; fprintf(fp, "Test Results:\n"); fprintf(fp, " PHOTFLAM: %0.8g (%0.8g, pct_diff=%g)\n", obs.photflam, ans_photflam, diff_photflam); fprintf(fp, " PHOTPLAM: %g (%g, pct_diff=%g)\n", obs.photplam, ans_photplam, diff_photplam); fprintf(fp, " PHOTBW: %g (%g, pct_diff=%g)\n", obs.photbw, ans_photbw, diff_photbw); } else { fprintf(fp, "Did not successfully determine PHOT values.\n"); } }
35.330827
87
0.638647
b61bda5453864afa81954b3f65003c7271264e82
566
rb
Ruby
lib/problem_027.rb
hsteinhilber/project_euler
1270e1d7e09e8efc6cbfcc889af82d0bf4bc2388
[ "MIT" ]
null
null
null
lib/problem_027.rb
hsteinhilber/project_euler
1270e1d7e09e8efc6cbfcc889af82d0bf4bc2388
[ "MIT" ]
null
null
null
lib/problem_027.rb
hsteinhilber/project_euler
1270e1d7e09e8efc6cbfcc889af82d0bf4bc2388
[ "MIT" ]
null
null
null
require 'integer' require 'prime_generator' class Problem027 def count_consec_primes(a, b) n = 0 n += 1 while (n**2 + a*n + b).prime? return n end def pairs(max) Enumerator.new do |yielder| PrimeGenerator.new.take_while { |p| p < max }.each do |p| (-max+1...max).each do |n| yielder << [n, p] end end end end def run a,b = pairs(1000).max_by { |a,b| count_consec_primes(a, b) } a * b end end if $0 == __FILE__ puts "Result: #{Problem027.new.run}" end
18.258065
65
0.538869
24c6dec269d7c632d90e9801d7fd371e425dba33
14,669
go
Go
make-plural.go
gotnospirit/makeplural
a5f48d94d976801ab2251014c9a626d1c86d7e22
[ "BSD-2-Clause" ]
1
2020-04-02T01:08:35.000Z
2020-04-02T01:08:35.000Z
make-plural.go
gotnospirit/makeplural
a5f48d94d976801ab2251014c9a626d1c86d7e22
[ "BSD-2-Clause" ]
null
null
null
make-plural.go
gotnospirit/makeplural
a5f48d94d976801ab2251014c9a626d1c86d7e22
[ "BSD-2-Clause" ]
2
2019-04-12T07:23:21.000Z
2020-04-01T08:17:57.000Z
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "net/http" "os" "sort" "strconv" "strings" "text/template" "time" ) type ( Source interface { Culture() string CultureId() string Code() string } Test interface { toString() string } FuncSource struct { culture, vars, impl string } UnitTestSource struct { culture string tests []Test } UnitTest struct { ordinal bool expected, value string } Op struct { previous_logic, left, operator, right, next_logic string } ) func (x FuncSource) Culture() string { return x.culture } func (x FuncSource) CultureId() string { return sanitize(x.culture) } func (x FuncSource) Code() string { result := "" if "" != x.vars { result += x.vars + "\n" } result += x.impl return result } func (x UnitTestSource) Culture() string { return x.culture } func (x UnitTestSource) CultureId() string { return sanitize(x.culture) } func (x UnitTestSource) Code() string { var result []string for _, child := range x.tests { result = append(result, "\t\t"+child.toString()) } return strings.Join(result, "\n") } func (x UnitTest) toString() string { return fmt.Sprintf( "testNamedKey(t, fn, %s, `%s`, `%s`, %v)", x.value, x.expected, fmt.Sprintf("fn("+x.value+", %v)", x.ordinal), x.ordinal, ) } func sanitize(input string) string { var result string for _, char := range input { switch { case char >= 'a' && char <= 'z', char >= 'A' && char <= 'Z': result += string(char) } } return result } func (x Op) conditions() []string { var result []string conditions := strings.Split(x.right, ",") for _, condition := range conditions { pos := strings.Index(condition, "..") if -1 != pos { lower_bound, upper_bound := condition[:pos], condition[pos+2:] lb, _ := strconv.Atoi(lower_bound) ub, _ := strconv.Atoi(upper_bound) r := rangeCondition(x.left, lb, ub, x.operator) result = append(result, r...) } else { result = append(result, fmt.Sprintf("%s %s %s", x.left, x.operator, condition)) } } return result } func get(url, key string, headers *string) (map[string]map[string]string, error) { fmt.Print("GET ", url) response, err := http.Get(url) if err != nil { return nil, err } defer response.Body.Close() if 200 != response.StatusCode { return nil, fmt.Errorf(response.Status) } contents, err := ioutil.ReadAll(response.Body) var document map[string]map[string]json.RawMessage err = json.Unmarshal([]byte(contents), &document) if nil != err { return nil, err } if _, ok := document["supplemental"]; !ok { return nil, fmt.Errorf("Data does not appear to be CLDR data") } *headers += fmt.Sprintf("//\n// URL: %s\n", url) { var version map[string]string err = json.Unmarshal(document["supplemental"]["version"], &version) if nil != err { return nil, err } *headers += fmt.Sprintf("// %s\n", version["_number"]) } { var generation map[string]string err = json.Unmarshal(document["supplemental"]["generation"], &generation) if nil != err { return nil, err } *headers += fmt.Sprintf("// %s\n", generation["_date"]) } var data map[string]map[string]string err = json.Unmarshal(document["supplemental"]["plurals-type-"+key], &data) if nil != err { return nil, err } return data, nil } func rangeCondition(varname string, lower, upper int, operator string) []string { var result []string for i := lower; i <= upper; i++ { result = append(result, fmt.Sprintf("%s %s %d", varname, operator, i)) } return result } func pattern2code(input string, ptr_vars *[]string) []string { left, short, operator, logic := "", "", "", "" var ops []Op buf := "" loop: for _, char := range input { switch char { default: buf += string(char) case '@': break loop case ' ': case '=': if "" != buf { left, operator, buf = buf, "==", "" short = toVar(left, ptr_vars) } case '!': left, operator, buf = buf, "!=", "" short = toVar(left, ptr_vars) } if "" != buf { pos := strings.Index(buf, "and") if -1 != pos { ops = append(ops, Op{logic, short, operator, buf[:pos], "AND"}) buf, left, operator, logic = "", "", "", "AND" } else { pos = strings.Index(buf, "or") if -1 != pos { ops = append(ops, Op{logic, short, operator, buf[:pos], "OR"}) buf, left, operator, logic = "", "", "", "OR" } } } } if "" != buf { ops = append(ops, Op{logic, short, operator, buf, ""}) } if 1 == len(ops) { conditions := ops[0].conditions() if "==" == ops[0].operator { return conditions } else { return []string{strings.Join(conditions, " && ")} } } var result []string var buffer []string buffer_length := 0 for _, o := range ops { conditions := o.conditions() logic = o.previous_logic nextLogic := o.next_logic operator := o.operator if "OR" == logic && buffer_length > 0 { result = append(result, strings.Join(buffer, ", ")) buffer = []string{} buffer_length = 0 } if ("" == logic && "OR" == nextLogic) || ("OR" == logic && "OR" == nextLogic) || ("OR" == logic && "" == nextLogic) { if "==" == operator { buffer = append(buffer, conditions...) } else { buffer = append(buffer, strings.Join(conditions, " && ")) } buffer_length = len(buffer) } else if "AND" == logic && ("AND" == nextLogic || "" == nextLogic) { if "==" == operator { buffer[buffer_length-1] += " && " + joinOr(conditions) } else { buffer[buffer_length-1] += " && " + strings.Join(conditions, " && ") } } else if "" == logic && "AND" == nextLogic { if "==" == operator { buffer = append(buffer, joinOr(conditions)) } else { buffer = append(buffer, strings.Join(conditions, " && ")) } buffer_length = len(buffer) } else if "OR" == logic && "AND" == nextLogic { if "==" == operator { if len(conditions) > 1 { buffer = append(buffer, joinOr(conditions)) } else { buffer = append(buffer, conditions...) } } else { buffer = append(buffer, strings.Join(conditions, " && ")) } buffer_length = len(buffer) } else if "AND" == logic && "OR" == nextLogic { if "==" == operator { buffer[buffer_length-1] += " && " + joinOr(conditions) } else { buffer[buffer_length-1] += " && " + strings.Join(conditions, " && ") } } } if len(buffer) > 0 { if "OR" == logic { result = append(result, buffer...) } else { result = append(result, strings.Join(buffer, " && ")) } } return result } func joinOr(data []string) string { if len(data) > 1 { return "(" + strings.Join(data, " || ") + ")" } return data[0] } func rule2code(key string, data map[string]string, ptr_vars *[]string, padding string) string { if input, ok := data["pluralRule-count-"+key]; ok { result := "" if "other" == key { if 1 == len(data) { return padding + "return \"other\"\n" } result += padding + "default:\n" } else { cases := pattern2code(input, ptr_vars) result += "\n" + padding + "case " + strings.Join(cases, ", ") + ":\n" } result += padding + "\treturn \"" + key + "\"\n" return result } return "" } func map2code(data map[string]string, ptr_vars *[]string, padding string) string { if 1 == len(data) { return rule2code("other", data, ptr_vars, padding) } result := padding + "switch {\n" result += rule2code("other", data, ptr_vars, padding) result += rule2code("zero", data, ptr_vars, padding) result += rule2code("one", data, ptr_vars, padding) result += rule2code("two", data, ptr_vars, padding) result += rule2code("few", data, ptr_vars, padding) result += rule2code("many", data, ptr_vars, padding) result += padding + "}\n" return result } func splitValues(input string) []string { var result []string pos := -1 for idx, char := range input { switch { case (char >= '0' && char <= '9') || '.' == char: if -1 == pos { pos = idx } // Inutile de générer un interval lorsque l'on rencontre '~' :) case ' ' == char || ',' == char || '~' == char: if -1 != pos { result = append(result, input[pos:idx]) pos = -1 } } } if -1 != pos { result = append(result, input[pos:]) } return result } func pattern2test(expected, input string, ordinal bool) []Test { var result []Test patterns := strings.Split(input, "@") for _, pattern := range patterns { if strings.HasPrefix(pattern, "integer") { for _, value := range splitValues(pattern[8:]) { result = append(result, UnitTest{ordinal, expected, value}) } } else if strings.HasPrefix(pattern, "decimal") { for _, value := range splitValues(pattern[8:]) { result = append(result, UnitTest{ordinal, expected, "\"" + value + "\""}) } } } return result } func map2test(ordinals, plurals map[string]string) []Test { var result []Test for _, rule := range []string{"one", "two", "few", "many", "zero", "other"} { if input, ok := ordinals["pluralRule-count-"+rule]; ok { result = append(result, pattern2test(rule, input, true)...) } if input, ok := plurals["pluralRule-count-"+rule]; ok { result = append(result, pattern2test(rule, input, false)...) } } return result } func culture2code(ordinals, plurals map[string]string, padding string) (string, string, []Test) { var code string var vars []string if nil == ordinals { code = map2code(plurals, &vars, padding) } else { code = padding + "if ordinal {\n" code += map2code(ordinals, &vars, padding+"\t") code += padding + "}\n\n" code += map2code(plurals, &vars, padding) } tests := map2test(ordinals, plurals) str_vars := "" max := len(vars) if max > 0 { // http://unicode.org/reports/tr35/tr35-numbers.html#Operands // // Symbol Value // n absolute value of the source number (integer and decimals). // i integer digits of n. // v number of visible fraction digits in n, with trailing zeros. // w number of visible fraction digits in n, without trailing zeros. // f visible fractional digits in n, with trailing zeros. // t visible fractional digits in n, without trailing zeros. var_f := varname('f', vars) var_i := varname('i', vars) var_n := varname('n', vars) var_v := varname('v', vars) var_t := varname('t', vars) var_w := varname('w', vars) if "_" != var_f || "_" != var_v || "_" != var_t || "_" != var_w { str_vars += padding + fmt.Sprintf("%s, %s, %s, %s, %s, %s := finvtw(value)\n", var_f, var_i, var_n, var_v, var_t, var_w) } else { if "_" != var_n { if "_" != var_i { str_vars += padding + "flt := float(value)\n" str_vars += padding + "n := math.Abs(flt)\n" str_vars += padding + "i := int64(flt)\n" } else { str_vars += padding + "n := math.Abs(float(value))\n" } } else if "_" != var_i { str_vars += padding + "i := int64(float(value))\n" } } for i := 0; i < max; i += 2 { k := vars[i] v := vars[i+1] if k != v { str_vars += padding + k + " := " + v + "\n" } } } return str_vars, code, tests } func addVar(varname, expr string, ptr_vars *[]string) string { exists := false for i := 0; i < len(*ptr_vars); i += 2 { if (*ptr_vars)[i] == varname { exists = true break } } if !exists { *ptr_vars = append(*ptr_vars, varname, expr) } return varname } func toVar(expr string, ptr_vars *[]string) string { var varname string if pos := strings.Index(expr, "%"); -1 != pos { k, v := expr[:pos], expr[pos+1:] varname = k + v if "n" == k { expr = "mod(n, " + v + ")" } else { expr = k + " % " + v } } else { varname = expr } return addVar(varname, expr, ptr_vars) } func varname(char uint8, vars []string) string { for i := 0; i < len(vars); i += 2 { if char == vars[i][0] { return string(char) } } return "_" } func createGoFiles(headers string, ptr_plurals, ptr_ordinals *map[string]map[string]string) error { var cultures []string if "*" == *user_culture { // On sait que len(ordinals) <= len(plurals) for culture, _ := range *ptr_plurals { cultures = append(cultures, culture) } } else { for _, culture := range strings.Split(*user_culture, ",") { culture = strings.TrimSpace(culture) if _, ok := (*ptr_plurals)[culture]; !ok { return fmt.Errorf("Aborted, `%s` not found...", culture) } cultures = append(cultures, culture) } } sort.Strings(cultures) if 0 == len(cultures) { return fmt.Errorf("Not enough data to create source...") } var items []Source var tests []Source for _, culture := range cultures { fmt.Print(culture) plurals := (*ptr_plurals)[culture] if nil == plurals { fmt.Println(" \u2717 - Plural not defined") } else if _, ok := plurals["pluralRule-count-other"]; !ok { fmt.Println(" \u2717 - Plural missing mandatory `other` choice...") } else { ordinals := (*ptr_ordinals)[culture] if nil != ordinals { if _, ok := ordinals["pluralRule-count-other"]; !ok { fmt.Println(" \u2717 - Ordinal missing the mandatory `other` choice...") continue } } vars, code, unit_tests := culture2code(ordinals, plurals, "\t\t") items = append(items, FuncSource{culture, vars, code}) fmt.Println(" \u2713") if len(unit_tests) > 0 { tests = append(tests, UnitTestSource{culture, unit_tests}) } } } if len(tests) > 0 { err := createSource("plural_test.tmpl", "plural/func_test.go", headers, tests) if nil != err { return err } } return createSource("plural.tmpl", "plural/func.go", headers, items) } func createSource(tmpl_filepath, dest_filepath, headers string, items []Source) error { source, err := template.ParseFiles(tmpl_filepath) if nil != err { return err } file, err := os.Create(dest_filepath) if nil != err { return err } defer file.Close() return source.Execute(file, struct { Headers string Timestamp string Items []Source }{ headers, time.Now().Format(time.RFC1123Z), items, }) } var user_culture = flag.String("culture", "*", "Culture subset") func main() { flag.Parse() var headers string ordinals, err := get("https://github.com/unicode-cldr/cldr-core/raw/master/supplemental/ordinals.json", "ordinal", &headers) if nil != err { fmt.Println(" \u2717") fmt.Println(err) } else { fmt.Println(" \u2713") plurals, err := get("https://github.com/unicode-cldr/cldr-core/raw/master/supplemental/plurals.json", "cardinal", &headers) if nil != err { fmt.Println(" \u2717") fmt.Println(err) } else { fmt.Println(" \u2713") err = createGoFiles(headers, &plurals, &ordinals) if nil != err { fmt.Println(err, "(╯°□°)╯︵ ┻━┻") } else { fmt.Println("Succeed (ッ)") } } } }
23.4704
125
0.602631
e52cdc546334d8bb5764116e1f2580314fbe0a67
67
ts
TypeScript
es/PhotoFilter.d.ts
eugeneilyin/mdi-norm
e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4
[ "MIT" ]
3
2018-11-11T01:48:20.000Z
2019-12-02T06:13:14.000Z
es/PhotoFilter.d.ts
eugeneilyin/mdi-norm
e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4
[ "MIT" ]
1
2019-02-21T05:59:35.000Z
2019-02-21T21:57:57.000Z
src/PhotoFilter.d.ts
eugeneilyin/mdi-norm
e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4
[ "MIT" ]
null
null
null
export { default as PhotoFilter } from './utils/createThemedIcon';
33.5
66
0.761194
9c1ee7f7dfb62d8c58708a4207fc522043b1f694
822
tsx
TypeScript
material-icons/src/icons/StretchToPageIcon.tsx
otissv/redesign
d2838f8463d4222af1cd55bf93749ea445a0dcf3
[ "MIT" ]
1
2021-04-13T06:23:57.000Z
2021-04-13T06:23:57.000Z
material-icons/src/icons/StretchToPageIcon.tsx
otissv/redesign
d2838f8463d4222af1cd55bf93749ea445a0dcf3
[ "MIT" ]
null
null
null
material-icons/src/icons/StretchToPageIcon.tsx
otissv/redesign
d2838f8463d4222af1cd55bf93749ea445a0dcf3
[ "MIT" ]
null
null
null
import React, { FC } from 'react'; import { Icon, IconInterface } from "@redesign-system/ui-core"; export const StretchToPageIcon: FC<IconInterface> = function StretchToPageIcon({ className, ...propsRest }) { const classNames = `StretchToPageIcon ${className}`; return ( <Icon alt="StretchToPage" className={classNames} {...propsRest}> <path d="M20,2H4C2.89,2 2,2.89 2,4V20C2,21.11 2.89,22 4,22H20C21.11,22 22,21.11 22,20V4C22,2.89 21.11,2 20,2M9,19H5V15L6.29,16.29L7.83,14.75L9.25,16.17L7.71,17.71M7.83,9.25L6.29,7.71L5,9V5H9L7.71,6.29L9.25,7.83M19,19H15L16.29,17.71L14.75,16.17L16.17,14.75L17.71,16.29L19,15M19,9L17.71,7.71L16.17,9.25L14.75,7.83L16.29,6.29L15,5H19" /> </Icon> ); }; StretchToPageIcon.displayName = 'StretchToPageIcon';
51.375
344
0.659367
064e45a665221d8f83f71d07fb3cc963c10c2196
369
kt
Kotlin
ltviewsx/src/main/java/com/lt/ltviewsx/lt_scrollimageview/LtPosition.kt
1764780379/ltviews
edd0033768e7d9b9e9597f3a53f3b0e110248f88
[ "BSD-2-Clause" ]
9
2018-06-12T03:19:51.000Z
2021-12-19T14:48:03.000Z
ltviewsx/src/main/java/com/lt/ltviewsx/lt_scrollimageview/LtPosition.kt
1764780379/ltviews
edd0033768e7d9b9e9597f3a53f3b0e110248f88
[ "BSD-2-Clause" ]
null
null
null
ltviewsx/src/main/java/com/lt/ltviewsx/lt_scrollimageview/LtPosition.kt
1764780379/ltviews
edd0033768e7d9b9e9597f3a53f3b0e110248f88
[ "BSD-2-Clause" ]
2
2020-09-02T09:25:22.000Z
2021-12-19T14:49:05.000Z
package com.lt.ltviewsx.lt_scrollimageview /** * 创 建: lt 2018/1/5--9:08 * 作 用: 小圆点的方向的枚举 * 注意事项: x轴位置_y轴位置 */ enum class LtPosition { LEFT_TOP, CENTER_TOP, RIGHT_TOP, LEFT_CENTER, CENTER_CENTER, RIGHT_CENTER, LEFT_BOTTOM, CENTER_BOTTOM, RIGHT_BOTTOM, LEFT_BOTTOM_OUT, CENTER_BOTTOM_OUT, RIGHT_BOTTOM_OUT }
17.571429
42
0.653117
149e40eb324765f72b30ac300899143823cc1062
1,109
kt
Kotlin
app/src/main/java/com/mapswithme/maps/search/BookingFilterParams.kt
dnemov/omim.kt
8b75114193e141aee14fcbc207a208c4a39de1db
[ "Apache-2.0" ]
1
2020-03-06T13:56:02.000Z
2020-03-06T13:56:02.000Z
app/src/main/java/com/mapswithme/maps/search/BookingFilterParams.kt
dnemov/omim.kt
8b75114193e141aee14fcbc207a208c4a39de1db
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/mapswithme/maps/search/BookingFilterParams.kt
dnemov/omim.kt
8b75114193e141aee14fcbc207a208c4a39de1db
[ "Apache-2.0" ]
null
null
null
package com.mapswithme.maps.search import android.os.Parcel import android.os.Parcelable import com.mapswithme.util.ConnectionState import kotlinx.android.parcel.Parcelize @Parcelize class BookingFilterParams (val mCheckinMillisec: Long, val mCheckoutMillisec: Long, vararg val mRooms: Room) : Parcelable { @Parcelize class Room(val mAdultsCount: Int, val mAgeOfChild: Int) : Parcelable { constructor(adultsCount: Int) : this(adultsCount, NO_CHILDREN) companion object { // This value is corresponds to AvailabilityParams::Room::kNoChildren in core. const val NO_CHILDREN = -1 @JvmField val DEFAULT = Room(2) } } class Factory { fun createParams( checkIn: Long, checkOut: Long, vararg rooms: Room ): BookingFilterParams? { return if (ConnectionState.isConnected) BookingFilterParams( checkIn, checkOut, *rooms ) else null } } }
29.972973
90
0.593327
2a2420f29f6adadd9dd8c5d5870a17ab58203aac
1,766
java
Java
src/main/java/com/zzm/controller/CourseController.java
jadeghost84/ChildProgrammingEducation
a3d6b8b1e3c898d4a616819deb97b113b1f81830
[ "MIT" ]
null
null
null
src/main/java/com/zzm/controller/CourseController.java
jadeghost84/ChildProgrammingEducation
a3d6b8b1e3c898d4a616819deb97b113b1f81830
[ "MIT" ]
null
null
null
src/main/java/com/zzm/controller/CourseController.java
jadeghost84/ChildProgrammingEducation
a3d6b8b1e3c898d4a616819deb97b113b1f81830
[ "MIT" ]
null
null
null
package com.zzm.controller; import com.zzm.domain.Course; import com.zzm.domain.CourseSection; import com.zzm.domain.CourseType; import com.zzm.service.CourseService; import com.zzm.service.UserService; import com.zzm.util.QiNiuYunUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class CourseController { @Autowired CourseService courseService; @Autowired UserService userService; @GetMapping("/course/{c_id}") @ResponseBody public Course getCourse(@PathVariable String c_id){ Course course = courseService.findCourseAllInfoById(c_id); return course; } //上传课程前先在数据库创建课程,返回课程id,解决七牛云key唯一性问题 @PostMapping("/courses") @ResponseBody public Integer createCourse(@RequestBody Course course, HttpServletRequest request){ //判断是否已登陆,登录返回u_id if("yes".equals(request.getSession().getAttribute("isLogin"))){ Integer u_id = (Integer) request.getSession().getAttribute("u_id"); course.setUpid(u_id); Integer c_id = courseService.saveCourse(course); return c_id; } return 0; } //上传课程的章节 @ResponseBody @PostMapping("/course/{c_id}") public void addCourseSection(@RequestBody CourseSection courseSection,@PathVariable String c_id){ courseSection.setC_id(Integer.parseInt(c_id)); //给url添加域名 courseSection.setUrl(QiNiuYunUtil.getAreaName()+courseSection.getUrl()); courseService.saveCourseSection(courseSection); } // }
31.535714
101
0.720272
0a09c11029c1df0858027057735da987139faff6
54
ts
TypeScript
src/interfaces/ClickCounter.ts
marathe-atharva/react-typescript-template
78fbf7face1c70345c29e3a996004a146b6ee49c
[ "MIT" ]
null
null
null
src/interfaces/ClickCounter.ts
marathe-atharva/react-typescript-template
78fbf7face1c70345c29e3a996004a146b6ee49c
[ "MIT" ]
117
2021-05-08T05:56:10.000Z
2022-03-29T18:57:01.000Z
src/interfaces/ClickCounter.ts
marathe-atharva/react-typescript-template
78fbf7face1c70345c29e3a996004a146b6ee49c
[ "MIT" ]
null
null
null
export interface ClickCounterProps { limit: number }
13.5
36
0.796296
750cbafe43f0db14963e557e6c46eb43e9cdf5b7
1,691
sql
SQL
data/ca/sqlite/subdivisions_PL.sqlite.sql
timshadel/subdivision-list
869415cee0886e34a1cb44e8a545a2e5a82aeb8c
[ "MIT" ]
26
2017-04-14T16:15:13.000Z
2021-11-20T17:41:39.000Z
data/ca/sqlite/subdivisions_PL.sqlite.sql
timshadel/subdivision-list
869415cee0886e34a1cb44e8a545a2e5a82aeb8c
[ "MIT" ]
null
null
null
data/ca/sqlite/subdivisions_PL.sqlite.sql
timshadel/subdivision-list
869415cee0886e34a1cb44e8a545a2e5a82aeb8c
[ "MIT" ]
15
2018-05-23T14:36:47.000Z
2021-11-04T08:26:20.000Z
CREATE TABLE subdivision_PL (id VARCHAR(6) NOT NULL, name VARCHAR(255), level VARCHAR(64) NOT NULL, PRIMARY KEY(id)); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-WP', 'Voivodat de Gran Polònia', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-KP', 'Voivodat de Cuiàvia i Pomerània', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-MA', 'Voivodat de Petita Polònia', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-DS', 'Voivodat de Baixa Silèsia', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-LU', 'Voivodat de Lublin', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-LB', 'Voivodat de Lubusz', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-MZ', 'Voivodat de Masòvia', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-PK', 'Voivodat de Subcarpàcia', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-PD', 'Voivodat de Podlàquia', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-PM', 'Voivodat de Pomerània', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-SL', 'Voivodat de Silèsia', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-WN', 'Voivodat de Warmia i Mazury', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-ZP', 'Voivodat de Pomerània Occidental', 'voivodship'); INSERT INTO "subdivision_PL" ("id", "name", "level") VALUES ('PL-SK', 'Voivodat de Santa Creu', 'voivodship');
99.470588
120
0.678888
cc84e3c5a96b4ed8cdd822cd7eff4bd5d384cde1
1,064
swift
Swift
Architecture/Sources/Architecture/UIViewController+Router.swift
AndreaRR18/ACME-App
2e7cf804ba89026aa6a7dfe94dc015e5c1181621
[ "MIT" ]
null
null
null
Architecture/Sources/Architecture/UIViewController+Router.swift
AndreaRR18/ACME-App
2e7cf804ba89026aa6a7dfe94dc015e5c1181621
[ "MIT" ]
null
null
null
Architecture/Sources/Architecture/UIViewController+Router.swift
AndreaRR18/ACME-App
2e7cf804ba89026aa6a7dfe94dc015e5c1181621
[ "MIT" ]
null
null
null
import UIKit extension UIViewController: Router { public func presentPage(_ module: Presentable, animated: Bool, _ completion: (() -> Void)?) { let destination = module.presented() destination.modalPresentationStyle = .fullScreen present(destination, animated: animated, completion: completion) } public func dismissPage(animated: Bool, completion: (() -> Void)?) { self.dismiss(animated: true, completion: nil) } public func pushPage(_ module: Presentable, animated: Bool) { navigationController?.pushViewController(module.presented(), animated: animated) } public func popPage(animated: Bool) { navigationController?.popViewController(animated: animated) } public func setAsRoot(_ module: Presentable, animated: Bool) { navigationController?.setViewControllers([module.presented()], animated: animated) } public func popToRootPage(animated: Bool) { navigationController?.popToRootViewController(animated: animated) } }
34.322581
97
0.684211
85cfdd5a9b267c3341b0863873d6b5b9ba05f9b0
223
js
JavaScript
app/routes/cityRoute.js
tranducminh/TravelVietnam
637b59343ddaf6dabd67cb697c23254d6414b167
[ "MIT" ]
null
null
null
app/routes/cityRoute.js
tranducminh/TravelVietnam
637b59343ddaf6dabd67cb697c23254d6414b167
[ "MIT" ]
3
2020-07-17T02:04:14.000Z
2020-09-25T03:43:52.000Z
app/routes/cityRoute.js
tranducminh/DiscoverVietnam
637b59343ddaf6dabd67cb697c23254d6414b167
[ "MIT" ]
null
null
null
let router = require('express').Router(); let cityCtrl = require('../controllers').City; router.route('/:cityNameID') .get(cityCtrl.renderCityPage) router.param('cityNameID', cityCtrl.findOne) module.exports = router;
27.875
46
0.730942
d28fa5b5b4c88774ceb8368539a12240aca60301
1,493
php
PHP
src/Esgi/UserBundle/Entity/User.php
Axel29/SymfonyBlog
b697988d40763811b38d2e3467eb0517191fc45d
[ "MIT" ]
null
null
null
src/Esgi/UserBundle/Entity/User.php
Axel29/SymfonyBlog
b697988d40763811b38d2e3467eb0517191fc45d
[ "MIT" ]
null
null
null
src/Esgi/UserBundle/Entity/User.php
Axel29/SymfonyBlog
b697988d40763811b38d2e3467eb0517191fc45d
[ "MIT" ]
null
null
null
<?php namespace Esgi\UserBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="User") */ class User extends BaseUser { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\ManyToMany(targetEntity="Esgi\BlogBundle\Entity\Comments", inversedBy="user", cascade={"persist", "merge"}) * @ORM\JoinTable(name="user_comments") */ private $comments; /** * Get id * * @return integer */ public function getId() { return $this->id; } public function __construct() { parent::__construct(); // your own logic } /** * Add comments * * @param \Esgi\BlogBundle\Entity\Comments $comment * @return User */ public function addComments(\Esgi\BlogBundle\Entity\Comments $comments) { $this->comments[] = $comments; return $this; } /** * Remove comment * * @param \Esgi\BlogBundle\Entity\Comments $comment */ public function removeComment(\Esgi\BlogBundle\Entity\Comments $comment) { $this->comments->removeElement($comment); } /** * Get comments * * @return \Doctrine\Common\Collections\Collection */ public function getComments() { return $this->comments; } }
18.898734
119
0.569324
85c2ade2fccccc56a9f84144f7913d8b15ee6c60
343
js
JavaScript
strongloop/node_modules/strong-pm/lib/receive.js
vnyrjkmr/myapp
abfc83107436e19ccae80389a713985386f37e62
[ "MIT" ]
null
null
null
strongloop/node_modules/strong-pm/lib/receive.js
vnyrjkmr/myapp
abfc83107436e19ccae80389a713985386f37e62
[ "MIT" ]
null
null
null
strongloop/node_modules/strong-pm/lib/receive.js
vnyrjkmr/myapp
abfc83107436e19ccae80389a713985386f37e62
[ "MIT" ]
null
null
null
var http = require('http'); var cicada = require('cicada'); var path = require('path'); exports.listen = function listen(port, base) { var git = cicada(path.resolve(base)); var server = http.createServer(git.handle); server.listen(port); server.git = git; git.on('commit', server.emit.bind(server, 'commit')); return server; };
22.866667
55
0.673469
dd7735867f8a3fe27dec370490173792ee8fa98b
201
php
PHP
src/Network/Http/FormData/Part.php
mozmorris/cakephp
c58f152a32eddc3652782e489dba1d5c2f4aeb11
[ "MIT" ]
133
2015-01-12T07:11:36.000Z
2022-02-16T13:25:18.000Z
vendor/cakephp/cakephp/src/Network/Http/FormData/Part.php
jagoree/task-manager
5d97ccf4c1736ba1676ca793ee059351b16303cf
[ "MIT" ]
534
2015-01-05T21:49:45.000Z
2022-03-31T16:27:03.000Z
vendor/cakephp/cakephp/src/Network/Http/FormData/Part.php
jagoree/task-manager
5d97ccf4c1736ba1676ca793ee059351b16303cf
[ "MIT" ]
448
2015-01-09T15:40:09.000Z
2022-03-11T15:13:25.000Z
<?php // @deprecated 3.4.0 Load new class and alias. class_exists('Cake\Http\Client\FormDataPart'); deprecationWarning('Use Cake\Http\Client\FormDataPart instead of Cake\Network\Http\FormData\Part.');
40.2
100
0.781095
bf90b7e283fcee7cd3ce3b9899620ab3a16b7ac4
9,476
rs
Rust
src/files.rs
opengirok/ogk
6a5deab22f6e5edbd592398cc5b5c52865ceb5ad
[ "MIT" ]
6
2022-03-06T13:07:53.000Z
2022-03-10T06:49:56.000Z
src/files.rs
opengirok/ogk
6a5deab22f6e5edbd592398cc5b5c52865ceb5ad
[ "MIT" ]
null
null
null
src/files.rs
opengirok/ogk
6a5deab22f6e5edbd592398cc5b5c52865ceb5ad
[ "MIT" ]
null
null
null
use crate::client::{BillWithFiles, Client, DntcFile, DtlVo}; use crate::utils::{config, date}; use async_trait::async_trait; use bytes::Bytes; use chrono::prelude::Utc; use console::Emoji; use dirs::home_dir; use git2::{ self, Commit, Cred, IndexAddOption, ObjectType, Oid, RemoteCallbacks, Repository, Signature, }; use regex::Regex; use std::error::Error; use std::fs::{create_dir, remove_dir_all, File}; use std::io; use std::path::Path; static DOCUMENT: Emoji<'_, '_> = Emoji("📑 ", ""); pub struct FileManager<'a> { _remote_url: String, _local_path: String, _local_repo: Option<Repository>, _git_signature: Signature<'a>, } impl<'a> FileManager<'a> { pub async fn new() -> Result<FileManager<'a>, Box<dyn Error>> { let _config = config::Config::load_or_new(); match _config { Ok(config) => match config.remote_file_repository { Some(remote_file_repository) => { let _remote_url = format!("git@github.com:{}", remote_file_repository); let global_config = git2::Config::open_default().unwrap(); let mut fm = FileManager { _local_path: config.local_file_repository.unwrap(), _remote_url: _remote_url, _local_repo: None, _git_signature: Signature::now( &global_config.get_string("user.name").unwrap(), &global_config.get_string("user.email").unwrap(), ) .unwrap(), }; if !Path::new(&fm._local_path).exists() { fm.clone_remote_repo(); } return Ok(fm); } None => { eprintln!("원격 저장소를 설정해주세요."); panic!(); } }, Err(_) => { eprintln!("ogk 기본 설정을 먼저 진행해주세요."); panic!(); } } } pub fn clone_remote_repo(&mut self) -> &Option<Repository> { let _ = remove_dir_all(&self._local_path); let mut callbacks = RemoteCallbacks::new(); callbacks.credentials(|_url, username_from_url, _allowed_types| { Cred::ssh_key( username_from_url.unwrap(), None, // TODO: ssh key 관리 고려 std::path::Path::new(&format!( "{}/.ssh/id_ed25519", home_dir().unwrap().to_str().unwrap() )), None, ) }); let mut fo = git2::FetchOptions::new(); fo.remote_callbacks(callbacks); let mut builder = git2::build::RepoBuilder::new(); builder.fetch_options(fo); match builder.clone(&self._remote_url, Path::new(&self._local_path)) { Ok(repo) => { self._local_repo = Some(repo); } Err(error) => { println!("{}", &self._remote_url); println!("{}", &self._local_path); panic!("{}", error); } } &self._local_repo } pub async fn download( &self, client: &Client, bill: &BillWithFiles, bill_from_list: &DtlVo, ) -> Result<Option<Vec<DntcFile>>, Box<dyn std::error::Error>> { let config = config::Config::load_or_new()?; match config.remote_file_repository { Some(_) => { let mut downloaded_files: Vec<DntcFile> = vec![]; let fm = FileManager::new().await.unwrap(); if let Some(ref file_list) = bill.atchFileList { for file in &*file_list { if fm.has_downloaded(bill, bill_from_list, &file.uploadFileOrginlNm) == false { let downloaded = client.download_file(file).await?; let _ = fm.save( &downloaded, bill, bill_from_list, &file.uploadFileOrginlNm, ); downloaded_files.push(file.clone()); } } Ok(Some(downloaded_files)) } else { Ok(Some(downloaded_files)) } } None => { eprintln!("청구파일을 다운로드 하려면 원격저장소 주소를 먼저 설정해주세요."); Ok(None) } } } // {접수일자}_{청구_제묵} pub fn make_dirname(request_date: &str, request_subject: &str) -> String { let re_illegal_symbols = Regex::new("[.\"\n \t()\'~]").unwrap(); let re_retouch = Regex::new("_+").unwrap(); format!( "{}_{}", request_date.replace(".", "-"), re_retouch .replace_all( &re_illegal_symbols.replace_all(request_subject.trim(), "_"), "_", ) .to_string() ) } // {접수번호}_{처리기관이름}_{업로드_파일명} pub fn make_filename( registration_number: &str, rqest_full_instt_name: &str, file_name: &str, ) -> String { let re_illegal_symbols = Regex::new("[\"\n \t()\'~]").unwrap(); let re_retouch = Regex::new("_+").unwrap(); format!( "{}_{}_{}", registration_number, rqest_full_instt_name.replace(" ", "_"), re_retouch .replace_all(&re_illegal_symbols.replace_all(file_name.trim(), "_"), "_",) .to_string() ) } pub fn save( &self, downloaded_file: &Bytes, downloadable_bill: &BillWithFiles, bill_from_list: &DtlVo, orig_file_name: &str, ) -> Result<File, Box<dyn std::error::Error>> { let dir_path = format!("{}/{}", &self._local_path, downloadable_bill.get_dirname(),); let file_path = format!( "{}/{}", &dir_path, downloadable_bill.get_filename(&bill_from_list.prcsFullInsttNm, orig_file_name) ); create_dir(Path::new(&dir_path)).unwrap_or_default(); let mut local_file = File::create(&file_path)?; io::copy(&mut downloaded_file.as_ref(), &mut local_file)?; Ok(local_file) } fn has_downloaded<T: Downloadable>( &self, downloadable_bill: &T, bill_from_list: &DtlVo, orig_file_name: &str, ) -> bool { let dir_path = format!("{}/{}", &self._local_path, downloadable_bill.get_dirname(),); let file_path = format!( "{}/{}", &dir_path, downloadable_bill.get_filename(&bill_from_list.prcsFullInsttNm, orig_file_name) ); return Path::new(&file_path).exists(); } fn remote_callbaks(&self) -> RemoteCallbacks<'a> { let mut callbacks = RemoteCallbacks::new(); callbacks.credentials(|_url, username_from_url, _allowed_types| { Cred::ssh_key( username_from_url.unwrap(), None, std::path::Path::new(&format!( "{}/.ssh/id_ed25519", home_dir().unwrap().to_str().unwrap() )), None, ) }); return callbacks; } pub async fn upload(&self) -> Result<Oid, git2::Error> { let callbacks = self.remote_callbaks(); fn find_last_commit(repo: &Repository) -> Result<Commit, git2::Error> { let obj = repo.head()?.resolve()?.peel(ObjectType::Commit)?; obj.into_commit() .map_err(|_| git2::Error::from_str("Couldn't find commit")) } let repo = match Repository::open(&self._local_path) { Ok(repo) => repo, Err(e) => panic!("failed to open: {}", e), }; let mut index = repo.index().unwrap(); let _ = index.add_all(["*"].iter(), IndexAddOption::DEFAULT, None); let _ = index.write(); let oid = index.write_tree().unwrap(); let parent_commit = find_last_commit(&repo).unwrap(); let tree = repo.find_tree(oid).unwrap(); repo.commit( Some("HEAD"), &self._git_signature, &self._git_signature, &format!( "{} - {}", DOCUMENT, date::KstDateTime::from(Utc::now()).format(Some("%F %T")) ), &tree, &[&parent_commit], ) .unwrap(); let mut remote = match repo.find_remote("origin") { Ok(r) => r, Err(_) => repo.remote("origin", &self._remote_url)?, }; let mut po = git2::PushOptions::new(); let mut po = po.remote_callbacks(callbacks); match remote.push( &["refs/heads/main", "refs/remotes/origin/main"], Some(&mut po), ) { Ok(_) => Ok(oid), Err(e) => { eprintln!("{}", e); Ok(oid) } } } } #[async_trait] pub trait Downloadable { fn get_filename(&self, prcs_full_instt_nm: &str, orig_file_name: &str) -> String; fn get_dirname(&self) -> String; }
32.675862
96
0.485965
894df5287d3d8f04f5b7464e18854f531d833648
1,917
swift
Swift
InventoryManagement/Other/ImagePicker.swift
tkreind/InventoryManagementApp
591d04e557a9d3a3916d0bc3aba7222ee9ee89e8
[ "MIT" ]
1
2021-05-06T03:58:50.000Z
2021-05-06T03:58:50.000Z
InventoryManagement/Other/ImagePicker.swift
tkreind/InventoryManagementApp
591d04e557a9d3a3916d0bc3aba7222ee9ee89e8
[ "MIT" ]
null
null
null
InventoryManagement/Other/ImagePicker.swift
tkreind/InventoryManagementApp
591d04e557a9d3a3916d0bc3aba7222ee9ee89e8
[ "MIT" ]
null
null
null
// // ImagePicker.swift // InventoryManagement // // Created by Tristan Kreindler on 7/28/20. // Copyright © 2020 Tristan Kreindler. All rights reserved. // import SwiftUI import ImgurAnonymousAPI struct ImagePickerAndUploader: UIViewControllerRepresentable { @Environment(\.presentationMode) var presentationMode @Binding var imageURL: String var sourceType: UIImagePickerController.SourceType static private let imgur = ImgurUploader(clientID: DebugLoginInfo.imgurClientId) func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePickerAndUploader>) -> UIImagePickerController { let picker = UIImagePickerController() picker.sourceType = self.sourceType picker.mediaTypes = ["public.image"] picker.delegate = context.coordinator return picker } func makeCoordinator() -> Coordinator { Coordinator(self) } func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePickerAndUploader>) { } class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { let parent: ImagePickerAndUploader func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { imgur.upload(info) { result in switch result { case .success(let response): self.parent.imageURL = response.link.absoluteString case .failure(let error): print("Upload failed: \(error)") } } parent.presentationMode.wrappedValue.dismiss() } init(_ parent: ImagePickerAndUploader) { self.parent = parent } } }
33.631579
149
0.668232
b11ac9bac63d77d27214db46409c77416b1f4c67
378
css
CSS
src/components/chat/ChatBox.css
mitstark13/marchmadnessdraft
f505561c749a2c0d8f20ab0d19d6ed1a1c8f1131
[ "MIT" ]
null
null
null
src/components/chat/ChatBox.css
mitstark13/marchmadnessdraft
f505561c749a2c0d8f20ab0d19d6ed1a1c8f1131
[ "MIT" ]
9
2020-03-11T15:32:21.000Z
2022-03-08T22:43:59.000Z
src/components/chat/ChatBox.css
mitstark13/marchmadnessdraft
f505561c749a2c0d8f20ab0d19d6ed1a1c8f1131
[ "MIT" ]
null
null
null
.chatInput { display: flex; align-items: center; height: 42px; } .chatInput input { flex: 1; height: 100%; border: 0; padding: 0 15px; } .chatInput button { flex: 0; height: 100%; padding: 0 20px; border: none; background: green; color: white; font-size: 18px; text-align: center; transition: .5s; } .chatInput button:hover { cursor: pointer; opacity: .8; }
13.034483
25
0.65873
9c0698ed7b26cc72d5927f91acd756e350cca55f
1,259
js
JavaScript
apps/driver.js
islam-Attar/caps
d5fe693f3611dfed7f35b39327cecaafa82e29b2
[ "MIT" ]
null
null
null
apps/driver.js
islam-Attar/caps
d5fe693f3611dfed7f35b39327cecaafa82e29b2
[ "MIT" ]
null
null
null
apps/driver.js
islam-Attar/caps
d5fe693f3611dfed7f35b39327cecaafa82e29b2
[ "MIT" ]
null
null
null
'use strict'; const eventEmitter = require('../lib/events'); const {createOrder} = require('./vendor'); eventEmitter.on('pick up', pickUpHandler) eventEmitter.on('in-transit', inTransitHandler) eventEmitter.on('delivered', deliveredHandler) function inTransitHandler(payload){ console.log('EVENT',payload); } function fakeOrderHandler(){ console.log('New order is ready to be picked up!'); eventEmitter.emit('pick up', { event: "pick up", time: new Date().toString(), payload: createOrder() }) } function deliveredHandler(payload){ console.log(`EVENT`, payload); } function pickUpHandler(payload){ console.log('EVENT', payload); console.log(`DRIVER: picked up ${payload.payload.orderID} `); setTimeout(() => { payload.time = new Date().toString() payload.event = 'in-transit' eventEmitter.emit('in-transit', payload) }, 1000); setTimeout(() => { payload.time = new Date().toString().split('(') payload.event = 'delivered' console.log(`DRIVER: delivered up ${payload.payload.orderID}`); console.log(`VENDOR: Thank you for delivering ${payload.payload.orderID}`); eventEmitter.emit('delivered', payload) }, 3000); } module.exports = {fakeOrderHandler}
22.482143
79
0.667196
f50b4f0031deda9dd0708296cfeaa7f4287bb729
7,070
rs
Rust
src/tex_the_program/section_0540_to_0543.rs
crlf0710/tex-rs
9e3950423ec57175484794904151c92ee4adaa68
[ "Apache-2.0", "MIT" ]
18
2020-10-08T04:25:49.000Z
2022-02-12T04:34:00.000Z
src/tex_the_program/section_0540_to_0543.rs
crlf0710/tex-rs
9e3950423ec57175484794904151c92ee4adaa68
[ "Apache-2.0", "MIT" ]
2
2021-01-03T07:10:54.000Z
2022-02-03T05:07:07.000Z
src/tex_the_program/section_0540_to_0543.rs
crlf0710/tex-rs
9e3950423ec57175484794904151c92ee4adaa68
[ "Apache-2.0", "MIT" ]
3
2020-12-11T09:12:56.000Z
2021-11-11T13:51:48.000Z
//! @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit //! integers that give the lengths of the various subsequent portions //! of the file. These twelve integers are, in order: //! $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr //! |lf|&length of the entire file, in words;\cr //! |lh|&length of the header data, in words;\cr //! |bc|&smallest character code in the font;\cr //! |ec|&largest character code in the font;\cr //! |nw|&number of words in the width table;\cr //! |nh|&number of words in the height table;\cr //! |nd|&number of words in the depth table;\cr //! |ni|&number of words in the italic correction table;\cr //! |nl|&number of words in the lig/kern table;\cr //! |nk|&number of words in the kern table;\cr //! |ne|&number of words in the extensible character table;\cr //! |np|&number of font parameter words.\cr}}$$ //! They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|, //! and //! $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$ //! Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|), //! and as few as 0 characters (if |bc=ec+1|). //! //! Incidentally, when two or more 8-bit bytes are combined to form an integer of //! 16 or more bits, the most significant bytes appear first in the file. //! This is called BigEndian order. //! @!@^BigEndian order@> //! //! @ The rest of the \.{TFM} file may be regarded as a sequence of ten data //! arrays having the informal specification //! $$\def\arr$[#1]#2${\&{array} $[#1]$ \&{of} #2} //! \vbox{\halign{\hfil\\{#}&$\,:\,$\arr#\hfil\cr //! header&|[0..lh-1]@t\\{stuff}@>|\cr //! char\_info&|[bc..ec]char_info_word|\cr //! width&|[0..nw-1]fix_word|\cr //! height&|[0..nh-1]fix_word|\cr //! depth&|[0..nd-1]fix_word|\cr //! italic&|[0..ni-1]fix_word|\cr //! lig\_kern&|[0..nl-1]lig_kern_command|\cr //! kern&|[0..nk-1]fix_word|\cr //! exten&|[0..ne-1]extensible_recipe|\cr //! param&|[1..np]fix_word|\cr}}$$ //! The most important data type used here is a |@!fix_word|, which is //! a 32-bit representation of a binary fraction. A |fix_word| is a signed //! quantity, with the two's complement of the entire word used to represent //! negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the //! binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and //! the smallest is $-2048$. We will see below, however, that all but two of //! the |fix_word| values must lie between $-16$ and $+16$. //! //! @ The first data array is a block of header information, which contains //! general facts about the font. The header must contain at least two words, //! |header[0]| and |header[1]|, whose meaning is explained below. //! Additional header information of use to other software routines might //! also be included, but \TeX82 does not need to know about such details. //! For example, 16 more words of header information are in use at the Xerox //! Palo Alto Research Center; the first ten specify the character coding //! scheme used (e.g., `\.{XEROX text}' or `\.{TeX math symbols}'), the next five //! give the font identifier (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the //! last gives the ``face byte.'' The program that converts \.{DVI} files //! to Xerox printing format gets this information by looking at the \.{TFM} //! file, which it needs to read anyway because of other information that //! is not explicitly repeated in \.{DVI}~format. //! //! \yskip\hang|header[0]| is a 32-bit check sum that \TeX\ will copy into //! the \.{DVI} output file. Later on when the \.{DVI} file is printed, //! possibly on another computer, the actual font that gets used is supposed //! to have a check sum that agrees with the one in the \.{TFM} file used by //! \TeX. In this way, users will be warned about potential incompatibilities. //! (However, if the check sum is zero in either the font file or the \.{TFM} //! file, no check is made.) The actual relation between this check sum and //! the rest of the \.{TFM} file is not important; the check sum is simply an //! identification number with the property that incompatible fonts almost //! always have distinct check sums. //! @^check sum@> //! //! \yskip\hang|header[1]| is a |fix_word| containing the design size of //! the font, in units of \TeX\ points. This number must be at least 1.0; it is //! fairly arbitrary, but usually the design size is 10.0 for a ``10 point'' //! font, i.e., a font that was designed to look best at a 10-point size, //! whatever that really means. When a \TeX\ user asks for a font //! `\.{at} $\delta$ \.{pt}', the effect is to override the design size //! and replace it by $\delta$, and to multiply the $x$ and~$y$ coordinates //! of the points in the font image by a factor of $\delta$ divided by the //! design size. {\sl All other dimensions in the\/ \.{TFM} file are //! |fix_word|\kern-1pt\ numbers in design-size units}, with the exception of //! |param[1]| (which denotes the slant ratio). Thus, for example, the value //! of |param[6]|, which defines the \.{em} unit, is often the |fix_word| value //! $2^{20}=1.0$, since many fonts have a design size equal to one em. //! The other dimensions must be less than 16 design-size units in absolute //! value; thus, |header[1]| and |param[1]| are the only |fix_word| //! entries in the whole \.{TFM} file whose first byte might be something //! besides 0 or 255. //! //! @ Next comes the |char_info| array, which contains one |@!char_info_word| //! per character. Each word in this part of the file contains six fields //! packed into four bytes as follows. //! //! \yskip\hang first byte: |@!width_index| (8 bits)\par //! \hang second byte: |@!height_index| (4 bits) times 16, plus |@!depth_index| //! (4~bits)\par //! \hang third byte: |@!italic_index| (6 bits) times 4, plus |@!tag| //! (2~bits)\par //! \hang fourth byte: |@!remainder| (8 bits)\par //! \yskip\noindent //! The actual width of a character is \\{width}|[width_index]|, in design-size //! units; this is a device for compressing information, since many characters //! have the same width. Since it is quite common for many characters //! to have the same height, depth, or italic correction, the \.{TFM} format //! imposes a limit of 16 different heights, 16 different depths, and //! 64 different italic corrections. //! //! @!@^italic correction@> //! The italic correction of a character has two different uses. //! (a)~In ordinary text, the italic correction is added to the width only if //! the \TeX\ user specifies `\.{\\/}' after the character. //! (b)~In math formulas, the italic correction is always added to the width, //! except with respect to the positioning of subscripts. //! //! Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]= //! \\{italic}[0]=0$ should always hold, so that an index of zero implies a //! value of zero. The |width_index| should never be zero unless the //! character does not exist in the font, since a character is valid if and //! only if it lies between |bc| and |ec| and has a nonzero |width_index|. //!
56.56
84
0.680198
df9d407c21446434d202dd10b6de457f68db6a7b
1,759
kt
Kotlin
bluetoothmc/src/main/java/com/ahmedabdelmeged/bluetoothmc/ui/adapter/BluetoothDevicesAdapter.kt
Ahmed-Abdelmeged/Android-BluetoothMCLibrary
594f00b659b49a5d7a1bc7dd049b019d99cf6bde
[ "MIT" ]
26
2017-05-25T23:17:40.000Z
2022-03-09T13:56:57.000Z
bluetoothmc/src/main/java/com/ahmedabdelmeged/bluetoothmc/ui/adapter/BluetoothDevicesAdapter.kt
Ahmed-Abdelmeged/Android-BluetoothMCLibrary
594f00b659b49a5d7a1bc7dd049b019d99cf6bde
[ "MIT" ]
5
2019-04-09T12:45:59.000Z
2021-02-21T14:58:52.000Z
bluetoothmc/src/main/java/com/ahmedabdelmeged/bluetoothmc/ui/adapter/BluetoothDevicesAdapter.kt
Ahmed-Abdelmeged/Android-BluetoothMCLibrary
594f00b659b49a5d7a1bc7dd049b019d99cf6bde
[ "MIT" ]
2
2019-04-07T09:04:29.000Z
2021-02-22T07:07:29.000Z
package com.ahmedabdelmeged.bluetoothmc.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.ahmedabdelmeged.bluetoothmc.R import kotlinx.android.synthetic.main.item_device.view.* /** * custom array adapter to view the list of bluetooth devices * * @author Ahmed Abd-Elmeged */ class BluetoothDevicesAdapter(private val devices: MutableList<String>, private val deviceClickCallbacks: DeviceClickCallbacks) : RecyclerView.Adapter<BluetoothDevicesAdapter.BluetoothDeviceViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BluetoothDeviceViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_device, parent, false) return BluetoothDeviceViewHolder(view) } override fun getItemCount(): Int { return devices.size } override fun onBindViewHolder(holder: BluetoothDeviceViewHolder, position: Int) { //set the device name val currentDevice = devices[position] holder.deviceName.text = currentDevice } inner class BluetoothDeviceViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { val deviceName: TextView = itemView.device_name_textView init { itemView.setOnClickListener(this) } override fun onClick(view: View) { deviceClickCallbacks.onDeviceClick(devices[adapterPosition]) } } fun clear() { this.devices.clear() notifyDataSetChanged() } fun addDevice(device: String) { this.devices.add(device) notifyDataSetChanged() } }
31.410714
127
0.725412
4a3efe6689775db25b79792d20e8cd85d57b877c
341
js
JavaScript
projects/05-travel-app/src/client/index.js
Gonzaloalcina/front-end-nanodegree-udacity
4f834ac6a5c50484772a0ab273428bb96c33e57c
[ "MIT" ]
2
2020-08-26T03:10:53.000Z
2020-09-30T23:09:53.000Z
projects/05-travel-app/src/client/index.js
Gonzaloalcina/front-end-nanodegree-udacity
4f834ac6a5c50484772a0ab273428bb96c33e57c
[ "MIT" ]
null
null
null
projects/05-travel-app/src/client/index.js
Gonzaloalcina/front-end-nanodegree-udacity
4f834ac6a5c50484772a0ab273428bb96c33e57c
[ "MIT" ]
3
2020-12-02T19:23:08.000Z
2021-04-14T18:13:11.000Z
// import main functions import {theUserTrip} from './js/app'; import {theTripChecker} from './js/tripChecker'; // import {welcome} from './js/functions'; // import {delete} from './js/functions'; // import styles import './styles/main.scss'; // final exporting export { theUserTrip, theTripChecker, //welcome, //delete }
18.944444
48
0.665689
130f44ba0957ad1b5c49aa4da36d823ca30051dc
1,093
h
C
src/Waves/Transaction.h
taha-husain/pp-wallet-core
68862468398854cef2d194cad8498801afcc3344
[ "MIT" ]
1
2020-10-27T17:27:04.000Z
2020-10-27T17:27:04.000Z
src/Waves/Transaction.h
vaulto-wallet/wallet-core
6f58ee2f18cc479eba2724b652e7c1fb4d783a33
[ "MIT" ]
null
null
null
src/Waves/Transaction.h
vaulto-wallet/wallet-core
6f58ee2f18cc479eba2724b652e7c1fb4d783a33
[ "MIT" ]
2
2020-01-08T14:28:22.000Z
2020-01-21T15:46:52.000Z
// Copyright © 2017-2020 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #pragma once #include "Address.h" #include "../Data.h" #include "../proto/Waves.pb.h" #include <nlohmann/json.hpp> namespace TW::Waves { enum class TransactionType { transfer = 4, lease = 8, cancelLease = 9 }; enum class TransactionVersion { V1 = 1, V2 = 2 }; class Transaction { /// We only support Transfer V2 transaction. /// See /// https://docs.wavesplatform.com/en/blockchain/waves-protocol/data-structures.html#section-8555a9aaf83a8d01f18a2c38d19484fe public: static const std::string WAVES; const Proto::SigningInput& input; const Data pub_key; Transaction(const Proto::SigningInput& input, const Data pub_key) : input(input), pub_key(std::move(pub_key)) {}; public: Data serializeToSign() const; nlohmann::json buildJson(Data signature) const; }; } // namespace TW::Waves
30.361111
129
0.714547
7f7fae4f349875d3ab55b5f8faef572c7f91d8bc
14,451
go
Go
server/plugin/command.go
kaakaa/mattermost-plugin-reacji
40f5715081c483dd4e00c6e4aba0384ae5ad73ac
[ "Apache-2.0" ]
null
null
null
server/plugin/command.go
kaakaa/mattermost-plugin-reacji
40f5715081c483dd4e00c6e4aba0384ae5ad73ac
[ "Apache-2.0" ]
13
2021-03-24T06:44:39.000Z
2021-04-29T02:40:51.000Z
server/plugin/command.go
kaakaa/mattermost-plugin-reacji
40f5715081c483dd4e00c6e4aba0384ae5ad73ac
[ "Apache-2.0" ]
1
2021-09-16T10:18:57.000Z
2021-09-16T10:18:57.000Z
package plugin import ( "errors" "fmt" "regexp" "strings" "github.com/kaakaa/mattermost-plugin-reacji/server/reacji" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" ) func (p *Plugin) registerCommand() error { return p.API.RegisterCommand(&model.Command{ Trigger: "reacji", DisplayName: "Reacji Channeler", Description: "Move post to other channel by attaching reactions", AutoComplete: true, AutoCompleteDesc: "Available commands: add, list, remove, remove-all, help", AutoCompleteHint: "[command]", AutocompleteData: createAutoCompleteData(), }) } func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { userID := args.UserId FromChannelID := args.ChannelId cmdElements := strings.Split(strings.TrimSpace(args.Command), " ") if len(cmdElements) == 0 || cmdElements[0] != "/"+CommandNameReacji { p.API.LogError("invalid command", "command", cmdElements[0]) return &model.CommandResponse{Text: "invalid command"}, nil } if len(cmdElements) == 1 { return p.help() } p.API.LogDebug("execute reacji command", "subcommand", cmdElements[1]) switch cmdElements[1] { case "add": emojiNames := p.findEmojis(cmdElements[2:]) return p.addReacji(emojiNames, userID, args.TeamId, FromAllChannelKeyword, args.ChannelMentions) case "add-from-here": emojiNames := p.findEmojis(cmdElements[2:]) return p.addReacji(emojiNames, userID, args.TeamId, FromChannelID, args.ChannelMentions) case "remove": if len(cmdElements) == 2 { return &model.CommandResponse{Text: "No delete key"}, nil } return p.remove(userID, cmdElements[2:]) case "remove-all": if len(cmdElements) == 3 && cmdElements[2] == "--force" { return p.forceRemoveAll(userID) } return p.removeAll(userID) case "list": if len(cmdElements) == 3 && cmdElements[2] == "--all" { return p.listAll(userID) } return p.list(userID, FromChannelID) case "refresh-caches": return p.refreshCaches(userID) case "help": return p.help() default: return &model.CommandResponse{Text: fmt.Sprintf("invalid subcommand: %s", cmdElements[1])}, nil } } func (p *Plugin) addReacji(emojiNames []string, userID, teamID, fromChannelID string, channelMentions model.ChannelMentionMap) (*model.CommandResponse, *model.AppError) { if len(p.reacjiList.Reacjis) >= p.getConfiguration().MaxReacjis { return &model.CommandResponse{Text: "Failed to add reacjis because the number of reacjis reaches maximum. Remove unnecessary reacjis or change the value of MaxReacjis from plugin setting in system console, and try again."}, nil } var toChannelIds []string for _, id := range channelMentions { toChannelIds = append(toChannelIds, id) } if len(emojiNames) == 0 || len(toChannelIds) == 0 { return &model.CommandResponse{Text: "Must specify at least one emoji and at least one channel"}, nil } if err := p.storeReacjis(userID, teamID, fromChannelID, emojiNames, toChannelIds); err != nil { return &model.CommandResponse{ Text: fmt.Sprintf("failed to store reacjis. error=%s", err.Error()), }, nil } return &model.CommandResponse{Text: "add reacjis successfully"}, nil } func (p *Plugin) findEmojis(args []string) []string { var ret []string re := regexp.MustCompile(`^:[^:]+:$`) for _, e := range args { text := strings.TrimSpace(e) if re.MatchString(text) { emojiName := strings.Trim(text, ":") if p.isAvailableEmoji(emojiName) { ret = append(ret, emojiName) } } } return ret } func (p *Plugin) isAvailableEmoji(name string) bool { // System emoji if _, ok := model.SystemEmojis[name]; ok { return true } // Custom emoji _, appErr := p.API.GetEmojiByName(name) return appErr == nil } func (p *Plugin) storeReacjis(userID, teamID, fromChannelID string, emojiNames, toChannelIds []string) error { new := p.reacjiList.Clone() count := 0 for _, emoji := range emojiNames { for _, to := range toChannelIds { if !exists(p.reacjiList, emoji, teamID, to) { new.Reacjis = append(new.Reacjis, &reacji.Reacji{ DeleteKey: model.NewId(), Creator: userID, TeamID: teamID, FromChannelID: fromChannelID, ToChannelID: to, EmojiName: emoji, }) count++ } } } if count == 0 { return errors.New("reacji is already registered") } if err := p.Store.Reacji().Update(p.reacjiList, new); err != nil { return err } p.reacjiList = new p.API.LogDebug("reacjis is updated", "reacjis", fmt.Sprintf("%v", new.Reacjis)) return nil } func exists(list *reacji.List, emoji, teamID, to string) bool { for _, reacji := range list.Reacjis { if reacji.EmojiName == emoji && reacji.TeamID == teamID && reacji.ToChannelID == to { return true } } return false } func (p *Plugin) remove(userID string, keys []string) (*model.CommandResponse, *model.AppError) { new := &reacji.List{} var failed []*reacji.Reacji for _, r := range p.reacjiList.Reacjis { if include(keys, r.DeleteKey) { if b, _ := p.HasAdminPermission(r, userID); b { continue } else { failed = append(failed, r) new.Reacjis = append(new.Reacjis, r) } } else { new.Reacjis = append(new.Reacjis, r) } } if err := p.Store.Reacji().Update(p.reacjiList, new); err != nil { return &model.CommandResponse{Text: "failed to remove reacjis"}, nil } p.reacjiList = new if len(failed) == 0 { return &model.CommandResponse{Text: "Reacjis are removed"}, nil } var emojis []string for _, f := range failed { emojis = append(emojis, f.DeleteKey) } return &model.CommandResponse{Text: fmt.Sprintf("Complete to remove reacjis. However, at least one reacjis encountered error: [%s]\nReacji can be removed by creator or SystemAdministrator.", strings.Join(emojis, ", "))}, nil } func include(list []string, key string) bool { for _, v := range list { if v == key { return true } } return false } func (p *Plugin) removeAll(userID string) (*model.CommandResponse, *model.AppError) { // TODO: confirm button if b, appErr := p.HasAdminPermission(nil, userID); !b { appendix := "" if appErr != nil { appendix = fmt.Sprintf("(%s)", appErr.Error()) } return &model.CommandResponse{ Text: "Failed to remove emojis due to invalid permission " + appendix, }, nil } new := &reacji.List{} if err := p.Store.Reacji().Update(p.reacjiList, new); err != nil { return &model.CommandResponse{ Text: err.Error(), }, nil } p.reacjiList = new return &model.CommandResponse{ Text: "All reacjis are removed.", }, nil } func (p *Plugin) forceRemoveAll(userID string) (*model.CommandResponse, *model.AppError) { // TODO: confirm button if b, appErr := p.HasAdminPermission(nil, userID); !b { appendix := "" if appErr != nil { appendix = fmt.Sprintf("(%s)", appErr.Error()) } return &model.CommandResponse{ Text: "Failed to remove emojis due to invalid permission " + appendix, }, nil } new := &reacji.List{} if err := p.Store.Reacji().ForceUpdate(new); err != nil { return &model.CommandResponse{ Text: err.Error(), }, nil } p.reacjiList = new return &model.CommandResponse{ Text: "All reacjis are removed.", }, nil } func (p *Plugin) listAll(userID string) (*model.CommandResponse, *model.AppError) { channelCaches := map[string]*model.Channel{} var contents []string for _, r := range p.reacjiList.Reacjis { from := fmt.Sprintf("Notfound(ID: %s)", r.FromChannelID) if r.FromChannelID == FromAllChannelKeyword { from = FromAllChannelKeyword } else if ch, ok := channelCaches[r.FromChannelID]; ok { from = fmt.Sprintf("~%s", ch.Name) } else { fromChannel, appErr := p.API.GetChannel(r.FromChannelID) if appErr == nil { from = fmt.Sprintf("~%s", fromChannel.Name) channelCaches[r.FromChannelID] = fromChannel } } if r.FromChannelID != FromAllChannelKeyword && !p.HasPermissionToChannel(channelCaches[r.FromChannelID], userID) { continue } to := fmt.Sprintf("Notfound(ID: %s)", r.ToChannelID) if ch, ok := channelCaches[r.ToChannelID]; ok { to = fmt.Sprintf("~%s", ch.Name) } else { toChannel, appErr := p.API.GetChannel(r.ToChannelID) if appErr == nil { to = fmt.Sprintf("~%s", toChannel.Name) channelCaches[r.ToChannelID] = toChannel } } if !p.HasPermissionToChannel(channelCaches[r.ToChannelID], userID) { continue } teamName := "Unknown" team, appErr := p.API.GetTeam(r.TeamID) if appErr == nil { teamName = team.Name } else { p.API.LogWarn("failed to get team", "team_id", r.TeamID) } creator, appErr := p.ConvertUserIDToDisplayName(r.Creator) if appErr != nil { creator = "Unknown" } contents = append(contents, fmt.Sprintf("| :%s: | %s | %s | %s | %s | %s |", r.EmojiName, teamName, from, to, creator, r.DeleteKey)) } if len(contents) == 0 { return &model.CommandResponse{Text: "There is no Reacji. Add Reacji by `/reacji add` command."}, nil } table := []string{ "### All reacjis", "", "| Emoji | Team | From | To | Creator | DeleteKey | ", } table = append(table, "|:-----:|:-----|:-----|:---|:--------|:----------|") table = append(table, contents...) return &model.CommandResponse{ Text: strings.Join(table, "\n"), }, nil } func (p *Plugin) list(userID, channelID string) (*model.CommandResponse, *model.AppError) { channelCaches := map[string]*model.Channel{} fromChannel, appErr := p.API.GetChannel(channelID) if appErr != nil { return &model.CommandResponse{ Text: fmt.Sprintf("Failed to get channel by ID: %s", channelID), }, nil } channelCaches[channelID] = fromChannel from := fmt.Sprintf("~%s", fromChannel.Name) var contents []string for _, r := range p.reacjiList.Reacjis { // Skip if reacji from channel is differ from channel where command is executed if r.FromChannelID != FromAllChannelKeyword && r.FromChannelID != channelID { continue } var fromName string if r.FromChannelID == FromAllChannelKeyword { fromName = FromAllChannelKeyword } else { fromName = from } to := fmt.Sprintf("Notfound(ID: %s)", r.ToChannelID) if ch, ok := channelCaches[r.ToChannelID]; ok { to = fmt.Sprintf("~%s", ch.Name) } else { toChannel, appErr := p.API.GetChannel(r.ToChannelID) if appErr == nil { to = fmt.Sprintf("~%s", toChannel.Name) channelCaches[r.ToChannelID] = toChannel } } if !p.HasPermissionToChannel(channelCaches[r.ToChannelID], userID) { continue } teamName := "Unknown" team, appErr := p.API.GetTeam(r.TeamID) if appErr == nil { teamName = team.Name } else { p.API.LogWarn("failed to get team", "team_id", r.TeamID) } creator, appErr := p.ConvertUserIDToDisplayName(r.Creator) if appErr != nil { creator = "Unknown" } contents = append(contents, fmt.Sprintf("| :%s: | %s | %s | %s | %s | %s |", r.EmojiName, teamName, fromName, to, creator, r.DeleteKey)) } if len(contents) == 0 { return &model.CommandResponse{Text: "There is no Reacji in this channel. Add Reacji by `/reacji add` command or or list reacjis in all channels by `/reacji list --all` command."}, nil } table := []string{ "### Reacjis in this channel", "", "| Emoji | Team | From | To | Creator | DeleteKey | ", } table = append(table, "|:-----:|:-----|:-----|:---|:--------|:----------|") table = append(table, contents...) return &model.CommandResponse{ Text: strings.Join(table, "\n"), }, nil } func (p *Plugin) refreshCaches(userID string) (*model.CommandResponse, *model.AppError) { // TODO: confirm button if b, appErr := p.HasAdminPermission(nil, userID); !b { appendix := "" if appErr != nil { appendix = fmt.Sprintf("(%s)", appErr.Error()) } return &model.CommandResponse{ Text: "failed to refresh caches due to invalid permission " + appendix, }, appErr } count, err := p.Store.Shared().DeleteAll() if err != nil { return &model.CommandResponse{ Text: "failed to refresh caches due to database error " + err.Error(), }, nil } return &model.CommandResponse{ Text: fmt.Sprintf("successfully removing %d caches", count), }, nil } const commandHelpMessage = `Manage Reacjis commands * **/reacji add :EMOJI: ~CHANNEL**: Register new reacji. If you attach EMOJI to the post in any channels except for DM/GM, the post will share to CHANNEL. * **/reacji add-from-here :EMOJI: ~CHANNEL**: Register new reacji. If you attach EMOJI to the post in the channel where this command is executed, the post will share to CHANNEL. * **/reacji list [-all]**: List reacjis that is registered in channel. With **--all** list all registered reacjis in this server. * **/reacji remove [Deletekey...]**: [CREATOR or SYSTEM_ADMIN only] Remove reacjis by DeleteKey. * **/reacji remove-all**: [SYSTEM_ADMIN onlye] Remove all existing reacjis. * **/reacji refresh-caches**: [SYSTEM_ADMIN only] Delete all caches. * **/reacji help**: Show help ` func (p *Plugin) help() (*model.CommandResponse, *model.AppError) { return &model.CommandResponse{ Text: commandHelpMessage, }, nil } func createAutoCompleteData() *model.AutocompleteData { suggestions := model.NewAutocompleteData("reacji", "[command]", "Available commands: add, list, remove, remove-all, help") suggestions.AddCommand(model.NewAutocompleteData("add", ":EMOJI: ~CHANNEL", "Register new reacji. If you attach EMOJI to the post in any channels except for DM/GM, the post will share to CHANNEL.")) suggestions.AddCommand(model.NewAutocompleteData("add-from-here", ":EMOJI: ~CHANNEL", "Register new reacji. If you attach EMOJI to the post in the channel where this command is executed, the post will share to CHANNEL.")) suggestions.AddCommand(model.NewAutocompleteData("list", "[--all]", "List reacjis in this channel. With `--all` list all registered reacjis in this server.")) suggestions.AddCommand(model.NewAutocompleteData("remove", "[DeleteKey...]", "[CREATOR or SYSTEM_ADMIN only] Remove reacji by DeleteKey. You can see `DeleteKey` by `/reacji list`")) suggestions.AddCommand(model.NewAutocompleteData("remove-all", "", "[SYSTEM_ADMIN only] Remove all reacjis in this server.")) suggestions.AddCommand(model.NewAutocompleteData("refresh-caches", "", "[SYSTEM_ADMIN only] Delete all caches. Reacji plugin caches data about shared post for a certain period in order to prevent duplicate sharing.")) suggestions.AddCommand(model.NewAutocompleteData("help", "", "Show help")) return suggestions }
33.764019
229
0.680507
cb493c42819d31b414ebda897c1b87d112dc3574
1,718
swift
Swift
XLsn0wQuora/Classes/APIManager/APIManager.swift
XLsn0w/XLsn0wQuora
93d803a321b1696d0507df8294581c85058a2a3e
[ "MIT" ]
10
2017-10-25T08:49:59.000Z
2018-06-16T01:21:24.000Z
XLsn0wQuora/Classes/APIManager/APIManager.swift
XLsn0w/XLsn0wQuora
93d803a321b1696d0507df8294581c85058a2a3e
[ "MIT" ]
null
null
null
XLsn0wQuora/Classes/APIManager/APIManager.swift
XLsn0w/XLsn0wQuora
93d803a321b1696d0507df8294581c85058a2a3e
[ "MIT" ]
1
2018-03-05T07:21:09.000Z
2018-03-05T07:21:09.000Z
import Foundation import Moya //: URL基地址 let BASE_URL = "http://english.6ag.cn/" enum APIManager { case getLaunchImg case getNewsList case getMoreNews(String) case getThemeList case getThemeDesc(Int) case getNewsDesc(Int) } extension APIManager: TargetType { /// The target's base `URL`. var baseURL: URL { return URL.init(string: "http://news-at.zhihu.com/api/")! } /// The path to be appended to `baseURL` to form the full `URL`. var path: String { switch self { case .getLaunchImg: return "7/prefetch-launch-images/750*1142" case .getNewsList: return "4/news/latest" case .getMoreNews(let date): return "4/news/before/" + date case .getThemeList: return "4/themes" case .getThemeDesc(let id): return "4/theme/\(id)" case .getNewsDesc(let id): return "4/news/\(id)" } } /// The HTTP method used in the request. var method: Moya.Method { return .get } /// The parameters to be incoded in the request. var parameters: [String: Any]? { return nil } /// The method used for parameter encoding. var parameterEncoding: ParameterEncoding { return URLEncoding.default } /// Provides stub data for use in testing. var sampleData: Data { return "".data(using: String.Encoding.utf8)! } /// The type of HTTP task to be performed. var task: Task { return .request } /// Whether or not to perform Alamofire validation. Defaults to `false`. var validate: Bool { return false } }
23.861111
76
0.582072
596af664e04559c63c8135e68c3773175f1f0c03
14,003
h
C
drivers/storage/port/scsi/miniport/advansys/asc/asclib.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/storage/port/scsi/miniport/advansys/asc/asclib.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/storage/port/scsi/miniport/advansys/asc/asclib.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/* ** Copyright (c) 1994-1998 Advanced System Products, Inc. ** All Rights Reserved. ** ** Filename: asclib.h ** */ #ifndef __ASCLIB_H_ #define __ASCLIB_H_ /* ******************************************************************* ** asc_eep.c ** ***************************************************************** */ int AscWriteEEPCmdReg( PortAddr iop_base, uchar cmd_reg ) ; int AscWriteEEPDataReg( PortAddr iop_base, ushort data_reg ) ; void AscWaitEEPRead( void ) ; void AscWaitEEPWrite( void ) ; ushort AscReadEEPWord( PortAddr, uchar ) ; ushort AscWriteEEPWord( PortAddr, uchar, ushort ) ; ushort AscGetEEPConfig( PortAddr, ASCEEP_CONFIG dosfar *, ushort ) ; int AscSetEEPConfigOnce( PortAddr, ASCEEP_CONFIG dosfar *, ushort ) ; int AscSetEEPConfig( PortAddr, ASCEEP_CONFIG dosfar *, ushort ) ; ushort AscEEPSum( PortAddr, uchar, uchar ) ; /* ******************************************************************* ** asc_chip.c ** ***************************************************************** */ int AscStartChip( PortAddr ) ; int AscStopChip( PortAddr ) ; void AscSetChipIH( PortAddr, ushort ) ; int AscIsChipHalted( PortAddr ) ; void AscResetScsiBus( ASC_DVC_VAR asc_ptr_type * ) ; int AscResetChip( PortAddr ) ; void AscSetChipCfgDword( PortAddr, ulong ) ; ulong AscGetChipCfgDword( PortAddr ) ; void AscAckInterrupt( PortAddr ) ; void AscDisableInterrupt( PortAddr ) ; void AscEnableInterrupt( PortAddr ) ; void AscSetBank( PortAddr, uchar ) ; uchar AscGetBank( PortAddr ) ; int AscResetChipAndScsiBus( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscGetIsaDmaChannel( PortAddr ) ; ushort AscSetIsaDmaChannel( PortAddr, ushort ) ; uchar AscSetIsaDmaSpeed( PortAddr, uchar ) ; uchar AscGetIsaDmaSpeed( PortAddr ) ; /* ****************************************************************** ** asc_lram.c ** **************************************************************** */ uchar AscReadLramByte( PortAddr, ushort) ; ushort AscReadLramWord( PortAddr, ushort ) ; ulong AscReadLramDWord( PortAddr, ushort ) ; void AscWriteLramWord( PortAddr, ushort, ushort ) ; void AscWriteLramDWord( PortAddr, ushort, ulong ); void AscWriteLramByte( PortAddr, ushort, uchar ) ; ulong AscMemSumLramWord( PortAddr, ushort, int ) ; void AscMemWordSetLram( PortAddr, ushort, ushort, int ) ; void AscMemWordCopyToLram( PortAddr, ushort, ushort dosfar *, int ) ; void AscMemDWordCopyToLram( PortAddr, ushort, ulong dosfar *, int ) ; void AscMemWordCopyFromLram( PortAddr, ushort, ushort dosfar *, int ) ; int AscMemWordCmpToLram( PortAddr, ushort, ushort dosfar *, int ) ; /* ******************************************************************* ** asc_dvc.c ** ***************************************************************** */ ushort AscInitAscDvcVar( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscInitFromEEP( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscInitWithoutEEP( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscInitFromAscDvcVar( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscInitMicroCodeVar( ASC_DVC_VAR asc_ptr_type *asc_dvc ) ; /* ushort AscGetSetConfig( ASC_DVC_VAR asc_ptr_type * ) ; */ /* ushort AscInitCfgRegister( ASC_DVC_VAR asc_ptr_type * ) ; */ /* ushort AscInitGetConfig( ASC_DVC_VAR asc_ptr_type * ) ; */ /* ushort AscInitAsc1000Driver( ASC_DVC_VAR asc_ptr_type * ) ; */ void dosfar AscInitPollIsrCallBack( ASC_DVC_VAR asc_ptr_type *, ASC_QDONE_INFO dosfar * ) ; int AscTestExternalLram( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscTestLramEndian( PortAddr ) ; /* ******************************************************************* ** a_qop.c ** int AscHostReqRiscHalt( PortAddr ) ; 6-16-95 ** ***************************************************************** */ uchar AscMsgOutSDTR( ASC_DVC_VAR asc_ptr_type *, uchar, uchar ) ; uchar AscCalSDTRData( ASC_DVC_VAR asc_ptr_type *, uchar, uchar ) ; void AscSetChipSDTR( PortAddr, uchar, uchar ) ; int AscInitChipAllSynReg( ASC_DVC_VAR asc_ptr_type *, uchar ) ; uchar AscGetSynPeriodIndex( ASC_DVC_VAR asc_ptr_type *, ruchar ) ; uchar AscAllocFreeQueue( PortAddr, uchar ) ; uchar AscAllocMultipleFreeQueue( PortAddr, uchar, uchar ) ; int AscRiscHaltedAbortSRB( ASC_DVC_VAR asc_ptr_type *, ulong ) ; int AscRiscHaltedAbortTIX( ASC_DVC_VAR asc_ptr_type *, uchar ) ; int AscRiscHaltedAbortALL( ASC_DVC_VAR asc_ptr_type * ) ; int AscHostReqRiscHalt( PortAddr ) ; int AscStopQueueExe( PortAddr ) ; int AscStartQueueExe( PortAddr ) ; int AscCleanUpDiscQueue( PortAddr ) ; int AscCleanUpBusyQueue( PortAddr ) ; int _AscAbortTidBusyQueue( ASC_DVC_VAR asc_ptr_type *, ASC_QDONE_INFO dosfar *, uchar ) ; int _AscAbortSrbBusyQueue( ASC_DVC_VAR asc_ptr_type *, ASC_QDONE_INFO dosfar *, ulong ) ; int AscWaitTixISRDone( ASC_DVC_VAR asc_ptr_type *, uchar ) ; int AscWaitISRDone( ASC_DVC_VAR asc_ptr_type * ) ; ulong AscGetOnePhyAddr( ASC_DVC_VAR asc_ptr_type *, uchar dosfar *, ulong ) ; /* ******************************************************************* ** a_q.c ** ***************************************************************** */ int AscSendScsiQueue( ASC_DVC_VAR asc_ptr_type *asc_dvc, ASC_SCSI_Q dosfar *scsiq, uchar n_q_required ) ; int AscPutReadyQueue( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_Q dosfar *, uchar ) ; int AscPutReadySgListQueue( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_Q dosfar *, uchar ) ; int AscAbortScsiIO( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_Q dosfar * ) ; void AscExeScsiIO( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_Q dosfar * ) ; int AscSetChipSynRegAtID( PortAddr, uchar, uchar ) ; int AscSetRunChipSynRegAtID( PortAddr, uchar, uchar ) ; ushort AscInitLram( ASC_DVC_VAR asc_ptr_type * ) ; int AscReInitLram( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscInitQLinkVar( ASC_DVC_VAR asc_ptr_type * ) ; int AscSetLibErrorCode( ASC_DVC_VAR asc_ptr_type *, ushort ) ; int _AscWaitQDone( PortAddr, ASC_SCSI_Q dosfar * ) ; /* ******************************************************************* ** a_osdep.c ** ***************************************************************** */ int AscEnterCritical( void ) ; void AscLeaveCritical( int ) ; /* ******************************************************************* ** a_isr.c ** ***************************************************************** */ int AscIsrChipHalted( ASC_DVC_VAR asc_ptr_type * ) ; uchar _AscCopyLramScsiDoneQ( PortAddr, ushort, ASC_QDONE_INFO dosfar *, ulong ) ; int AscIsrQDone( ASC_DVC_VAR asc_ptr_type * ) ; ushort AscIsrExeBusyQueue( ASC_DVC_VAR asc_ptr_type *, uchar ) ; int AscScsiSetupCmdQ( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, uchar dosfar *, ulong ) ; /* ****************************************************************** ** asc_scsi.c ** **************************************************************** */ int AscScsiInquiry( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, uchar dosfar *, int ) ; int AscScsiTestUnitReady( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar * ) ; int AscScsiStartStopUnit( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, uchar ) ; int AscScsiReadCapacity( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, uchar dosfar * ) ; /* ******************************************************************* ** asc_inq.c ** ***************************************************************** */ ulong dosfar *swapfarbuf4( uchar dosfar * ) ; int PollQueueDone( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, int ) ; int PollScsiReadCapacity( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, ASC_CAP_INFO dosfar * ) ; int PollScsiInquiry( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, uchar dosfar *, int ) ; int PollScsiTestUnitReady( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar * ) ; int PollScsiStartUnit( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar * ) ; int InitTestUnitReady( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar * ) ; void AscDispInquiry( uchar, uchar, ASC_SCSI_INQUIRY dosfar * ) ; int AscPollQDone( ASC_DVC_VAR asc_ptr_type *, ASC_SCSI_REQ_Q dosfar *, int ) ; int AscCompareString( uchar *, uchar *, int ) ; /* ------------------------------------------------------------------ ** asc_bios.c ** ---------------------------------------------------------------- */ int AscSetBIOSBank( PortAddr, int, ushort ) ; int AscSetVlBIOSBank( PortAddr, int ) ; int AscSetEisaBIOSBank( PortAddr, int ) ; int AscSetIsaBIOSBank( PortAddr, int ) ; /* ******************************************************************* ** a_eisa.c ** ***************************************************************** */ ushort AscGetEisaChipCfg( PortAddr ) ; ushort AscGetEisaChipGpReg( PortAddr ) ; ushort AscSetEisaChipCfg( PortAddr, ushort ) ; ushort AscSetEisaChipGpReg( PortAddr, ushort ) ; /* ******************************************************************* ** ae_init1.c ** ***************************************************************** */ ulong AscGetEisaProductID( PortAddr ) ; PortAddr AscSearchIOPortAddrEISA( PortAddr ) ; /* ******************************************************************* ** a_init1.c ** **************************************************************** */ void AscClrResetScsiBus( PortAddr ) ; uchar AscGetChipScsiCtrl( PortAddr ) ; uchar AscSetChipScsiID( PortAddr, uchar ) ; uchar AscGetChipVersion( PortAddr, ushort ) ; ushort AscGetChipBusType( PortAddr ) ; ulong AscLoadMicroCode( PortAddr, ushort, ushort dosfar *, ushort ); int AscFindSignature( PortAddr ) ; /* ****************************************************************** ** a_init2.c ** ******************************************************************/ PortAddr AscSearchIOPortAddr11( PortAddr ) ; PortAddr AscSearchIOPortAddr100( PortAddr ) ; void AscToggleIRQAct( PortAddr ) ; void AscClrResetChip( PortAddr ) ; short itos( ushort, uchar dosfar *, short, short ) ; int insnchar( uchar dosfar *, short , short, ruchar, short ) ; void itoh( ushort, ruchar dosfar * ) ; void btoh( uchar, ruchar dosfar * ) ; void ltoh( ulong, ruchar dosfar * ) ; uchar dosfar *todstr( ushort, uchar dosfar * ) ; uchar dosfar *tohstr( ushort, uchar dosfar * ) ; uchar dosfar *tobhstr( uchar, uchar dosfar * ) ; uchar dosfar *tolhstr( ulong, uchar dosfar * ) ; /* ****************************************************************** ** a_init3.c ** ******************************************************************/ void AscSetISAPNPWaitForKey( void ) ; uchar AscGetChipIRQ( PortAddr, ushort ) ; uchar AscSetChipIRQ( PortAddr, uchar, ushort ) ; /* ****************************************************************** ** a_bios.c ** ******************************************************************/ int AscIsBiosEnabled( PortAddr, ushort ) ; int AscEnableBios( PortAddr, ushort ) ; ushort AscGetChipBiosAddress( PortAddr, ushort ) ; ushort AscSetChipBiosAddress( PortAddr, ushort, ushort ) ; /* ulong AscGetMaxDmaCount( ushort ) ; */ /* the function prototype in a_ddlib.h */ /* ******************************************************************* ** asc_diag.c ** ***************************************************************** */ void AscSingleStepChip( PortAddr ) ; /* ******************************************************************* ** asc_res.c ** ***************************************************************** */ int AscPollQTailSync( PortAddr ) ; int AscPollQHeadSync( PortAddr ) ; int AscWaitQTailSync( PortAddr ) ; /* ******************************************************************* ** a_novell.c ** ***************************************************************** */ int _AscRestoreMicroCode( PortAddr, ASC_MC_SAVED dosfar * ) ; /* ******************************************************************* ** a_scam.c ******************************************************************* */ int AscSCAM( ASC_DVC_VAR asc_ptr_type * ) ; /* ******************************************************************* ** a_mmio.c ** added # S47 ** ******************************************************************* */ ushort SwapByteOfWord( ushort word_val ) ; ulong SwapWordOfDWord( ulong dword_val ) ; ulong AdjEndianDword( ulong dword_val ) ; /* ******************************************************************* ** a_endian c ** added # S47 ** ******************************************************************* */ int AscAdjEndianScsiQ( ASC_SCSI_Q dosfar * ) ; int AscAdjEndianQDoneInfo( ASC_QDONE_INFO dosfar * ) ; /* ******************************************************************* ** a_sg c ** added # S62 ** ******************************************************************* */ int AscCoalesceSgList( ASC_SCSI_Q dosfar * ); /* ******************************************************************* ** a_debug.c ** added since # S89 ** ******************************************************************* */ int AscVerWriteLramDWord( PortAddr, ushort, ulong ) ; int AscVerWriteLramWord( PortAddr, ushort, ushort ) ; int AscVerWriteLramByte( PortAddr, ushort, uchar ) ; #endif /* __ASCLIB_H_ */
44.173502
85
0.501678
b15baae860d799a277acd24f4e8eb47e96270323
2,243
h
C
DataMgr/ForeignStorage/ForeignDataWrapperFactory.h
yma11/omniscidb
2f975266f5c9f4daeadffd154735dca30c7b633b
[ "Apache-2.0" ]
null
null
null
DataMgr/ForeignStorage/ForeignDataWrapperFactory.h
yma11/omniscidb
2f975266f5c9f4daeadffd154735dca30c7b633b
[ "Apache-2.0" ]
null
null
null
DataMgr/ForeignStorage/ForeignDataWrapperFactory.h
yma11/omniscidb
2f975266f5c9f4daeadffd154735dca30c7b633b
[ "Apache-2.0" ]
1
2021-10-07T11:30:01.000Z
2021-10-07T11:30:01.000Z
/* * Copyright 2021 OmniSci, 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. */ #pragma once #include "ForeignDataWrapper.h" namespace foreign_storage { /** * @type DataWrapperType * @brief Encapsulates an enumeration of foreign data wrapper type strings */ struct DataWrapperType { static constexpr char const* CSV = "OMNISCI_CSV"; static constexpr char const* PARQUET = "OMNISCI_PARQUET"; static constexpr std::array<std::string_view, 2> supported_data_wrapper_types{PARQUET, CSV}; }; class ForeignDataWrapperFactory { public: /** * Creates an instance of a ForeignDataWrapper for the given data wrapper type using * provided database and foreign table details. */ static std::unique_ptr<ForeignDataWrapper> create(const std::string& data_wrapper_type, const int db_id, const ForeignTable* foreign_table); /** * Creates an instance (or gets an existing instance) of an immutable ForeignDataWrapper * to be used for validation purposes. Returned instance should not be used for any * stateful operations, such as fetching foreign table data/metadata. */ static const ForeignDataWrapper& createForValidation( const std::string& data_wrapper_type, const ForeignTable* foreign_table = nullptr); /** * Checks that the given data wrapper type is valid. */ static void validateDataWrapperType(const std::string& data_wrapper_type); private: static std::map<std::string, std::unique_ptr<ForeignDataWrapper>> validation_data_wrappers_; }; } // namespace foreign_storage
35.603175
90
0.687472
f72ace0a39ad6486331d470b37dac04fb915b1af
643
swift
Swift
Currency/MVVM/Views/Cells/ExchangeRatesCell.swift
Rahul-Mayani/Currency-Converter
76a778d68dc65998c6d43d965432d44de7a3fa27
[ "MIT" ]
1
2022-02-15T19:14:06.000Z
2022-02-15T19:14:06.000Z
Currency/MVVM/Views/Cells/ExchangeRatesCell.swift
Rahul-Mayani/Currency-Converter
76a778d68dc65998c6d43d965432d44de7a3fa27
[ "MIT" ]
1
2021-06-22T13:30:23.000Z
2021-06-22T13:30:23.000Z
Currency/MVVM/Views/Cells/ExchangeRatesCell.swift
Rahul-Mayani/Currency-Converter
76a778d68dc65998c6d43d965432d44de7a3fa27
[ "MIT" ]
null
null
null
// // ExchangeRatesCell.swift // Currency // // Created by Rahul Mayani on 31/05/21. // import UIKit class ExchangeRatesCell: UICollectionViewCell { // MARK: - IBOutlet - @IBOutlet weak var currencyLabel: UILabel! @IBOutlet weak var amountLabel: UILabel! // MARK: - Variable - var data: CurrencyQuote? = nil { didSet { guard let quote = data else { return } currencyLabel.text = quote.name amountLabel.text = quote.value.currencyAmount() } } // MARK: - Cell Life Cycle - override func awakeFromNib() { super.awakeFromNib() } }
21.433333
59
0.59409
3b589052726a1235e3c99f3e172ad3f91e68e124
1,111
c
C
GodHands/GodHands/Source/System/RamDisk/RamDiskTest.c
collinsmichael/GodHands
d4523ec83e7c9dac9199b67f365cf44b69c1a5b2
[ "MIT" ]
10
2020-02-16T23:51:47.000Z
2021-11-21T16:59:02.000Z
GodHands/GodHands/Source/System/RamDisk/RamDiskTest.c
collinsmichael/GodHands
d4523ec83e7c9dac9199b67f365cf44b69c1a5b2
[ "MIT" ]
3
2020-02-15T08:50:58.000Z
2021-03-28T18:19:13.000Z
GodHands/GodHands/Source/System/RamDisk/RamDiskTest.c
collinsmichael/GodHands
d4523ec83e7c9dac9199b67f365cf44b69c1a5b2
[ "MIT" ]
2
2021-03-31T19:23:41.000Z
2021-11-21T16:59:07.000Z
#ifdef UNITTEST #include "System/System.h" #include "GodHands.h" extern struct RAMDISK RamDisk; UTEST(Test_0001_RamDisk, NonExistentFile) { ASSERT_TRUE(RamDisk.Reset()); ASSERT_FALSE(RamDisk.Open("does not exist")); ASSERT_FALSE(RamDisk.Close()); } UTEST(Test_0002_RamDisk, OpenAndClose) { ASSERT_TRUE(RamDisk.Open("test.img")); ASSERT_TRUE(RamDisk.Close()); } UTEST(Test_0003_RamDisk, OutOfBounds) { ASSERT_TRUE(RamDisk.Open("test.img")); ASSERT_FALSE(RamDisk.Read(-1, 1)); ASSERT_FALSE(RamDisk.Read(16, 1)); ASSERT_FALSE(RamDisk.Write(-1, 1)); ASSERT_FALSE(RamDisk.Write(16, 1)); ASSERT_TRUE(RamDisk.Close()); } UTEST(Test_0004_RamDisk, ReadAndWrite) { char expect[2*KB]; char *actual; stosb(expect, 'x', sizeof(expect)); ASSERT_TRUE(RamDisk.Open("test.img")); ASSERT_TRUE(RamDisk.Read(15, 1)); ASSERT_NE(0, actual = RamDisk.AddressOf(15)); ASSERT_EQ(0, cmpsb(actual, expect, sizeof(expect))); ASSERT_TRUE(RamDisk.Write(15, 1)); ASSERT_TRUE(RamDisk.Close()); } #endif // UNITTEST
26.452381
57
0.665167
61128f36a00c6ea5052d03f44024c900b79e1257
247
css
CSS
assets/css/ui.css
neilstuff/jewel-thief
60d6c9126b954c29d1271425506497924c17a1da
[ "CC0-1.0" ]
null
null
null
assets/css/ui.css
neilstuff/jewel-thief
60d6c9126b954c29d1271425506497924c17a1da
[ "CC0-1.0" ]
null
null
null
assets/css/ui.css
neilstuff/jewel-thief
60d6c9126b954c29d1271425506497924c17a1da
[ "CC0-1.0" ]
null
null
null
@font-face { font-family: bitOperatorPlus; src: url(../fonts/8bitOperatorPlusSC-Regular.ttf); } body, p { font-family: bitOperatorPlus; } .controls { font-family: bitOperatorPlus; font-size: 12px; } .preload { display: none; }
13
52
0.668016
2a33ebc50cadfc2c30cc891fd59867e0c3d85b75
4,527
java
Java
adapters/mso-tenant-adapter/src/test/java/org/openecomp/mso/adapters/tenant/test/TenantTest.java
kweveen/so
f5618da7e8d8398d5f85fe950fd5c88e84481f83
[ "Apache-2.0" ]
null
null
null
adapters/mso-tenant-adapter/src/test/java/org/openecomp/mso/adapters/tenant/test/TenantTest.java
kweveen/so
f5618da7e8d8398d5f85fe950fd5c88e84481f83
[ "Apache-2.0" ]
null
null
null
adapters/mso-tenant-adapter/src/test/java/org/openecomp/mso/adapters/tenant/test/TenantTest.java
kweveen/so
f5618da7e8d8398d5f85fe950fd5c88e84481f83
[ "Apache-2.0" ]
null
null
null
/*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.openecomp.mso.adapters.tenant.test; import java.util.Map; import javax.xml.ws.Holder; import org.openecomp.mso.adapters.tenant.MsoTenantAdapter; import org.openecomp.mso.adapters.tenant.MsoTenantAdapterImpl; import org.openecomp.mso.adapters.tenant.exceptions.TenantException; import org.openecomp.mso.adapters.tenantrest.TenantRollback; public class TenantTest { public static final void main (String args[]) { String cloudId = "MT"; cloudId = "AIC_GAMMALAB"; MsoTenantAdapter tenantAdapter = new MsoTenantAdapterImpl(); Holder<String> tenantId = new Holder<>(); Holder<String> tenantName = new Holder<>(); Holder<Map<String,String>> tenantMetadata = new Holder<>(); Holder<Boolean> tenantDeleted = new Holder<>(); Holder<TenantRollback> rollback = new Holder<>(); try { tenantAdapter.queryTenant (cloudId, "934a4ac9c4bd4b8d9d8ab3ef900281b0", null, tenantId, tenantName, tenantMetadata); System.out.println ("Got Tenant ID=" + tenantId.value + ", name=" + tenantName.value + ", metadata = " + tenantMetadata.value); } catch (TenantException e) { System.out.println ("Got Tenant Exception: " + e); System.exit(1); } /* Map<String,String> metadata = new HashMap<String,String>(); metadata.put("sdn-global-id", "abc"); metadata.put("service-type", "gamma"); // Create a new tenant try { tenantAdapter.createTenant(cloudId, "TEST_META6", metadata, true, tenantId, rollback); System.out.println ("Created Tenant ID " + tenantId.value); } catch (TenantAlreadyExists e) { System.out.println ("Create: Tenant already exists: " + "TEST_META6"); } catch (TenantException e) { System.out.println ("Got Tenant Exception on Create: " + e); System.exit(1); } // Query the new tenant try { tenantAdapter.queryTenant (cloudId, "TEST_META6", tenantId, tenantName, tenantMetadata); System.out.println ("Queried Tenant ID=" + tenantId.value + ", name=" + tenantName.value + ", metadata = " + tenantMetadata.value); } catch (TenantException e) { System.out.println ("Got Tenant Exception on Query: " + e); System.exit(1); } try { Thread.sleep(10000); } catch (InterruptedException e1) {} // Delete the new tenant try { tenantAdapter.deleteTenant (cloudId, tenantId.value, tenantDeleted); if (tenantDeleted.value) System.out.println ("Deleted Tenant " + tenantId.value); else System.out.println ("Delete: Tenant " + tenantId.value + " does not exist"); } catch (TenantException e) { System.out.println ("Got Tenant Exception on Delete: " + e); } /* // Create another new tenant try { tenantAdapter.createTenant(cloudId, "TEST_MSO2", null, false, tenantId, rollback); System.out.println ("Created Tenant ID " + tenantId.value); } catch (TenantException e) { System.out.println ("Got Tenant Exception on Create: " + e); } // Query the new tenant try { tenantAdapter.queryTenant (cloudId, "TEST_MSO2", tenantId, tenantName); System.out.println ("Queried Tenant ID=" + tenantId.value + ", name=" + tenantName.value); } catch (TenantException e) { System.out.println ("Got Tenant Exception on Query: " + e); } try { Thread.sleep(10000); } catch (InterruptedException e1) {} // Rollback the new tenant try { tenantAdapter.rollbackTenant(rollback.value); System.out.println ("Rolled Back Tenant ID " + tenantId.value); } catch (TenantException e) { System.out.println ("Got Tenant Exception on Rollback: " + e); } */ } }
34.037594
134
0.649879
71bdef5d1f857c078626bd15d870416d283814f7
541
tsx
TypeScript
packages/icons/src/GemSolid.tsx
Armedin/kuka-ui
dc5bc09402eeb6585a91e9af1919055112b42311
[ "MIT" ]
null
null
null
packages/icons/src/GemSolid.tsx
Armedin/kuka-ui
dc5bc09402eeb6585a91e9af1919055112b42311
[ "MIT" ]
null
null
null
packages/icons/src/GemSolid.tsx
Armedin/kuka-ui
dc5bc09402eeb6585a91e9af1919055112b42311
[ "MIT" ]
null
null
null
import React from 'react'; import { SvgIcon, SvgIconProps } from '@kukui/ui'; const SvgComponent = props => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" {...props}> <path d="M378.7 32H133.3L256 182.7 378.7 32zM512 192 404.6 50.7 289.6 192H512zM107.4 50.67 0 192h222.4l-115-141.33zM244.3 474.9c3 3.3 7.3 5.1 11.7 5.1s8.653-1.828 11.67-5.062L510.6 224H1.365L244.3 474.9z" /> </svg> ); const SvgGemSolid = (props: SvgIconProps) => ( <SvgIcon component={SvgComponent} {...props} /> ); export default SvgGemSolid;
36.066667
211
0.676525
30cba74fdb69745c873ad1425930f97409611dc5
1,745
swift
Swift
JKJSON/Array+Optional.swift
jankase/JKJSON
c1c31a0fee63f1a685eb7d5c384b0af8265449a3
[ "MIT" ]
null
null
null
JKJSON/Array+Optional.swift
jankase/JKJSON
c1c31a0fee63f1a685eb7d5c384b0af8265449a3
[ "MIT" ]
null
null
null
JKJSON/Array+Optional.swift
jankase/JKJSON
c1c31a0fee63f1a685eb7d5c384b0af8265449a3
[ "MIT" ]
null
null
null
// // Created by Jan Kase on 04/01/16. // Copyright (c) 2016 Jan Kase. All rights reserved. // import Foundation extension Array { mutating func setOptionalObject(theObject: Element?, index theIndex: Index) throws { if let aObject = theObject { if theIndex < self.endIndex { self[theIndex] = aObject } else if theIndex == self.endIndex { self.append(aObject) } else { throw JSONErrors.ArrayOutOfBounds } } } mutating func appendOptional(theObject: Element?) { if let aObject = theObject { self.append(aObject) } } } extension Optional where Wrapped: protocol<RangeReplaceableCollectionType, MutableCollectionType> { mutating func setOptionalObject(theObject: Wrapped.Generator.Element?, index theIndex: Int) throws { if let aObject = theObject { if self == nil && theIndex == 0 { self = Wrapped() } else { throw JSONErrors.ArrayOutOfBounds } if var anArray = self as? Array<Wrapped.Generator.Element> { if anArray.endIndex > theIndex { anArray[theIndex] = aObject } else if anArray.endIndex == theIndex { anArray.appendOptional(aObject) } else { throw JSONErrors.ArrayOutOfBounds } if let aWrapped = anArray as? Wrapped { self = aWrapped } } } } mutating func append(theObject: Wrapped.Generator.Element?) { if let aObject = theObject { if self == nil { self = Wrapped() } if var anArray = self as? Array<Wrapped.Generator.Element> { anArray.append(aObject) if let aWrapped = anArray as? Wrapped { self = aWrapped } } } } }
22.088608
102
0.608023
70747adc211c0f44a7f5d7cb2d2d7a6cdbc37b66
3,952
c
C
product/synquacer/src/device_nor_mt25.c
wakuakihiro/SCP-firmware
de7e464ecd77130147103cf48328099c2d0e6289
[ "BSD-3-Clause" ]
1
2022-01-25T10:10:32.000Z
2022-01-25T10:10:32.000Z
product/synquacer/src/device_nor_mt25.c
wakuakihiro/SCP-firmware
de7e464ecd77130147103cf48328099c2d0e6289
[ "BSD-3-Clause" ]
null
null
null
product/synquacer/src/device_nor_mt25.c
wakuakihiro/SCP-firmware
de7e464ecd77130147103cf48328099c2d0e6289
[ "BSD-3-Clause" ]
null
null
null
/* * Arm SCP/MCP Software * Copyright (c) 2022, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "nor/device_nor_mt25.h" #include "qspi_api.h" #include <fwk_id.h> #include <fwk_module.h> #include <fwk_status.h> #include <stdbool.h> #include <stdint.h> /* * local functions */ static int set_read_command( fwk_id_t id, const struct qspi_api *qspi_api, struct qspi_command command) { if (IS_QSPI_COMMAND_EMPTY(command)) { return FWK_E_SUPPORT; } return qspi_api->set_read_command(id, &command); } static int set_write_command( fwk_id_t id, const struct qspi_api *qspi_api, struct qspi_command command) { if (IS_QSPI_COMMAND_EMPTY(command)) { return FWK_E_SUPPORT; } return qspi_api->set_write_command(id, &command); } static bool mt25_is_write_enable(fwk_id_t id, const struct qspi_api *qspi_api) { int status; uint8_t buf; status = set_read_command(id, qspi_api, COMMAND_READ_STATUS_REG); if (status != FWK_SUCCESS) { return false; } status = qspi_api->read(id, 0, &buf, sizeof(buf)); if (status != FWK_SUCCESS) { return false; } return MT25_IS_WEL_ENABLE(buf); } static int mt25_read_nv_config_reg( fwk_id_t id, const struct qspi_api *qspi_api, uint8_t *buf) { int status; status = set_read_command(id, qspi_api, MT25_COMMAND_READ_NV_CONFIG_REG); if (status != FWK_SUCCESS) { return status; } return qspi_api->read(id, 0, buf, sizeof(buf[0])); } static int mt25_write_nv_config_reg( fwk_id_t id, const struct qspi_api *qspi_api, uint8_t buf) { int status; status = set_write_command(id, qspi_api, MT25_COMMAND_WRITE_NV_CONFIG_REG); if (status != FWK_SUCCESS) { return status; } return qspi_api->write(id, 0, &buf, sizeof(buf)); } static int mt25_read_flag_status_reg( fwk_id_t id, const struct qspi_api *qspi_api, uint8_t *buf) { int status; status = set_read_command(id, qspi_api, MT25_COMMAND_READ_FLAG_STATUS_REG); if (status != FWK_SUCCESS) { return status; } return qspi_api->read(id, 0, buf, sizeof(buf[0])); } /* * User APIs */ int mt25_nor_set_io_protocol( fwk_id_t id, const struct qspi_api *qspi_api, void *arg) { uint8_t io_num = *(uint8_t *)arg; uint8_t buf; bool req_quad; int status; if (io_num != 1 && io_num != 2 && io_num != 4) { return FWK_E_PARAM; } req_quad = (io_num == 4); status = mt25_read_nv_config_reg(id, qspi_api, &buf); if (status != FWK_SUCCESS) { return status; } if (!req_quad || MT25_IS_QUAD_ENABLE(buf)) { return FWK_SUCCESS; } if (!mt25_is_write_enable(id, qspi_api)) { return FWK_E_ACCESS; } /* At here, quad transfer is requested but not yet enabled. */ MT25_QUAD_ENABLE(buf); status = mt25_write_nv_config_reg(id, qspi_api, buf); if (status != FWK_SUCCESS) { return status; } return FWK_SUCCESS; } int mt25_nor_get_program_result( fwk_id_t id, const struct qspi_api *qspi_api, void *arg) { uint8_t buf; bool *is_fail = (bool *)arg; int status; status = mt25_read_flag_status_reg(id, qspi_api, &buf); if (status != FWK_SUCCESS) { return status; } if (MT25_IS_PROGRAM_FAIL(buf)) { *is_fail = true; } else { *is_fail = false; } return FWK_SUCCESS; } int mt25_nor_get_erase_result( fwk_id_t id, const struct qspi_api *qspi_api, void *arg) { uint8_t buf; bool *is_fail = (bool *)arg; int status; status = mt25_read_flag_status_reg(id, qspi_api, &buf); if (status != FWK_SUCCESS) { return status; } if (MT25_IS_ERASE_FAIL(buf)) { *is_fail = true; } else { *is_fail = false; } return FWK_SUCCESS; }
20.163265
79
0.639676
16632363fdcc77be0a899f80e5c2a23ebd228586
719
ts
TypeScript
dist/src/repositories/profile.repository.d.ts
david1asher/linkedin-private-api
e5f025f2f9ab46826caec627e818298ee494c2c8
[ "MIT" ]
null
null
null
dist/src/repositories/profile.repository.d.ts
david1asher/linkedin-private-api
e5f025f2f9ab46826caec627e818298ee494c2c8
[ "MIT" ]
null
null
null
dist/src/repositories/profile.repository.d.ts
david1asher/linkedin-private-api
e5f025f2f9ab46826caec627e818298ee494c2c8
[ "MIT" ]
null
null
null
import { Client } from '../core/client'; import { LinkedInMiniProfile } from '../entities/linkedin-mini-profile.entity'; import { MiniProfile, ProfileId } from '../entities/mini-profile.entity'; import { Profile } from '../entities/profile.entity'; export declare const getProfilesFromResponse: < T extends { data: any; included: ( | LinkedInMiniProfile | { $type: string; } )[]; } >( response: T, ) => Record<ProfileId, MiniProfile>; export declare class ProfileRepository { private client; constructor({ client }: { client: Client }); getProfile({ publicIdentifier }: { publicIdentifier: string }): Promise<Profile>; getOwnProfile(): Promise<Profile | null>; }
29.958333
83
0.666203
0ee3a8b86c3e4d4e4766bc6ae488b44faf1de69a
754
ts
TypeScript
src/composables/Home/Announcement/useList.ts
hnit-acm/hnit-acm-web-v2
6724c85840a9095c2aaff95776cc988b54252674
[ "MIT" ]
1
2021-04-07T15:24:56.000Z
2021-04-07T15:24:56.000Z
src/composables/Home/Announcement/useList.ts
hnit-acm/hnit-acm-web-v2
6724c85840a9095c2aaff95776cc988b54252674
[ "MIT" ]
9
2021-01-07T01:37:11.000Z
2021-06-20T10:59:46.000Z
src/composables/Home/Announcement/useList.ts
hnit-acm/hnit-acm-web-v2
6724c85840a9095c2aaff95776cc988b54252674
[ "MIT" ]
null
null
null
import {computed, ref, Ref, provide, inject, reactive} from "vue"; import {useRoute} from "vue-router"; type ListContext = { visible: Ref<boolean>; setVisible: (value: boolean) => void; }; const ListSymbol = Symbol(); export function useListProvide(): ListContext { const visible = ref(true) const setVisible = (value: boolean) => { visible.value = value } provide(ListSymbol, { visible, setVisible, }) return { visible, setVisible, } } export function useListInject(): ListContext { const context = inject<ListContext>(ListSymbol); if (!context) { throw new Error(`useBookListInject must be used after useBookListProvide`); } return context; }
19.842105
83
0.629973
d2b33b1363816e6f828f855c681c965815288219
323
php
PHP
Modules/Blog/Http/Repositories/BloggerRepositoryInterface.php
Nacimbob/Laravel-Blog-Api
ff6a0055f1ace57cc0aff1e2aca5e20df66ff5fd
[ "MIT" ]
null
null
null
Modules/Blog/Http/Repositories/BloggerRepositoryInterface.php
Nacimbob/Laravel-Blog-Api
ff6a0055f1ace57cc0aff1e2aca5e20df66ff5fd
[ "MIT" ]
null
null
null
Modules/Blog/Http/Repositories/BloggerRepositoryInterface.php
Nacimbob/Laravel-Blog-Api
ff6a0055f1ace57cc0aff1e2aca5e20df66ff5fd
[ "MIT" ]
null
null
null
<?php namespace Modules\Blog\Http\Repositories; use Modules\Blog\Entities\Blogger; interface BloggerRepositoryInterface { public function create(array $attributes); public function update(Blogger $blogger,array $parameters); public function delete(Blogger $blogger); public function findById($id); }
19
63
0.758514